From 715baf47609f689eb5ab0676825869639820a3e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:36:12 +0100 Subject: [PATCH 01/76] 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 02/76] 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 d4ea67703de986eb907138148751d9561ed84f7b Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 03/76] 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 04/76] 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 05/76] 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 19f75c3a00b9eb7635d4763f6ac4ccd657f66b03 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 07:00:56 +0000 Subject: [PATCH 06/76] Smart material previews on the preview orb Smart material shelf tiles and hover previews render the real material, applied with materials::apply to the baked preview orb and composited by the compositor, lit in a dark studio of soft boxes. MaskPreview becomes OrbPreview (masks and materials share one bake and one worker). Tiles show a loading icon until their preview arrives; the web takes one worker request per frame. preview::material keeps plain materials only. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 5 +- crates/engine/src/mask_preview.rs | 161 ---------- crates/engine/src/mask_preview_pixel.rs | 2 +- crates/engine/src/material_preview_pixel.rs | 16 + .../{mask_preview_camera.rs => orb_camera.rs} | 30 +- crates/engine/src/orb_preview.rs | 297 ++++++++++++++++++ crates/engine/src/preview.rs | 115 +++---- crates/geom/src/primitives.rs | 2 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/mask_preview_image.rs | 2 +- crates/ui-egui/src/mask_shape.rs | 33 -- crates/ui-egui/src/material_preview_image.rs | 100 ++++++ crates/ui-egui/src/orb_shape.rs | 33 ++ crates/ui-egui/src/preview_image.rs | 73 +++-- crates/ui-egui/src/preview_request.rs | 10 +- crates/ui-egui/src/preview_worker.rs | 19 +- crates/ui-egui/src/shelf.rs | 49 +-- crates/ui-egui/src/shelf_preview.rs | 35 ++- crates/ui-egui/src/soft_box.rs | 48 +++ crates/ui-egui/src/thumbs.rs | 50 ++- crates/ui-egui/src/worker_preview.rs | 2 +- crates/ui-egui/tests/shelf_hover_preview.rs | 2 +- 22 files changed, 727 insertions(+), 361 deletions(-) delete mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/material_preview_pixel.rs rename crates/engine/src/{mask_preview_camera.rs => orb_camera.rs} (69%) create mode 100644 crates/engine/src/orb_preview.rs delete mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/material_preview_image.rs create mode 100644 crates/ui-egui/src/orb_shape.rs create mode 100644 crates/ui-egui/src/soft_box.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..cedf6cdb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,13 +22,14 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; -pub mod mask_preview; -mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; +mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod orb_camera; +pub mod orb_preview; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs deleted file mode 100644 index a44757fc..00000000 --- a/crates/engine/src/mask_preview.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Smart mask previews share one baked [`primitives::preview_orb`] -//! Presets use `mask.smart.apply` and the compositor, matching document masks - -use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::primitives; - -use crate::mask_preview_camera::MaskPreviewCamera; -pub use crate::mask_preview_pixel::MaskPreviewPixel; -use crate::{EngineError, Result, Session}; - -/// Bake resolution in texels; 256 loses the thin edge lines -const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline) -const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews -pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel; thumbnail detail needs fewer than the default -const OCCLUSION_RAYS: u32 = 12; -/// Curvature rays per texel; thumbnail detail needs fewer than the default -const CURVATURE_RAYS: u32 = 12; -/// Radius relative to the bounding box; isolates panel edges from the round body -const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read -const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Keep camera views for the thumbnail and hover preview sizes -const CAMERAS_KEPT: usize = 2; - -/// The baked preview shape and, per preview size, what its camera sees -pub struct MaskPreview { - session: Session, - layer: LayerId, - /// Cached camera views, least recently used first - cameras: Vec, -} - -impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it) - pub fn new() -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); - } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; - session.bake_now(0, false)?; - - Ok(MaskPreview { session, layer, cameras: Vec::new() }) - } - - /// Row-major `size²` pixels, with None outside the shape - /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] - pub fn render(&mut self, id: &str, size: usize) -> Option>> { - if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { - return None; - } - - crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Previews need no undo history; retaining snapshots grows memory across presets - self.session.undo.clear(); - - let camera = camera_for(&mut self.cameras, &self.session, size)?; - let values = self.session.mask_at(self.layer, &camera.texels)?; - - let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..size * size) - .map(|i| { - let (x, y) = (i % size, i / size); - let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); - for sy in 0..SUPERSAMPLE { - for sx in 0..SUPERSAMPLE { - let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; - let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; - - mask += values.get(texel).copied().unwrap_or(0.0); - normal += n; - hits += 1.0; - } - } - (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) - }) - .collect(); - Some(pixels) - } -} - -/// Cache one camera per preview size, evicting the least recently used view -fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { - let rays_per_side = size * SUPERSAMPLE; - let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { - Some(i) => cameras.remove(i), - None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), - }; - if cameras.len() >= CAMERAS_KEPT { - cameras.remove(0); - } - - cameras.push(camera); - cameras.last() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Mean absolute difference of the masks of two previews over the pixels both see - fn difference(a: &[Option], b: &[Option]) -> f32 { - let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); - pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 - } - - #[test] - fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { - let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - let layer = session.doc.project.texture_set(0).unwrap().stack[0]; - let mut preview = MaskPreview { session, layer, cameras: Vec::new() }; - for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { - assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); - assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); - assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); - } - } - - #[test] - fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { - let size = 24; - let mut preview = MaskPreview::new().unwrap(); - for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); - assert_eq!(px.len(), size * size, "{}", sm.id); - assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); - let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); - assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); - for p in seen { - assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); - assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); - } - } - - let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); - let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); - assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); - assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope", size).is_none()); - - let big = preview.render("edges_sharp", size * 3).unwrap(); - let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; - assert_eq!(big.len(), size * size * 9); - assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); - preview.render("edges_sharp", size * 2).unwrap(); - assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); - } -} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs index bcde5629..14ad5842 100644 --- a/crates/engine/src/mask_preview_pixel.rs +++ b/crates/engine/src/mask_preview_pixel.rs @@ -1,4 +1,4 @@ -//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). +//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`]) use texturecraft_geom::glam::Vec3; diff --git a/crates/engine/src/material_preview_pixel.rs b/crates/engine/src/material_preview_pixel.rs new file mode 100644 index 00000000..7b83422e --- /dev/null +++ b/crates/engine/src/material_preview_pixel.rs @@ -0,0 +1,16 @@ +//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`]) + +use texturecraft_geom::glam::Vec3; + +use crate::preview::Sample; + +/// The material values seen at a preview pixel, with what a display needs to light the shape +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialPreviewPixel { + /// Linear material values, averaged over the pixel + pub sample: Sample, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer) + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline) + pub coverage: f32, +} diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/orb_camera.rs similarity index 69% rename from crates/engine/src/mask_preview_camera.rs rename to crates/engine/src/orb_camera.rs index ea3d6d1f..d0015361 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/orb_camera.rs @@ -1,4 +1,4 @@ -//! Cached camera rays for one smart mask preview size +//! Cached camera rays for one preview orb size use std::collections::HashMap; @@ -11,11 +11,11 @@ use crate::Session; const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss +/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees -pub(crate) struct MaskPreviewCamera { +/// What each ray of a square orthographic view of the orb sees +pub(crate) struct OrbCamera { /// Rays along each side of the view pub rays_per_side: usize, /// The texels (x, y) the camera sees, each once @@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera { pub samples: Vec, } -impl MaskPreviewCamera { +impl OrbCamera { /// Trace a square orthographic view onto a `texture_px²` texture - pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera { + let (min, max) = session.mesh.bounds(); + let center = (min + max) * 0.5; + let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max); let pitch = CAMERA_PITCH_DEG.to_radians(); let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); @@ -40,9 +40,9 @@ impl MaskPreviewCamera { let mut texels = Vec::new(); let mut index_of = HashMap::new(); let samples = (0..rays_per_side * rays_per_side) - .map(|i| { + .map(|ray| { let side = rays_per_side as f32; - let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0); // Start well outside the shape so every ray enters it from the front let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; let hit = session.bvh.closest(origin, forward, radius * 8.0)?; @@ -52,10 +52,12 @@ impl MaskPreviewCamera { texels.push(texel); texels.len() - 1 }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + + let normal = surface.nrm; + Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward)))) }) .collect(); - MaskPreviewCamera { rays_per_side, texels, samples } + + OrbCamera { rays_per_side, texels, samples } } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs new file mode 100644 index 00000000..f29a247d --- /dev/null +++ b/crates/engine/src/orb_preview.rs @@ -0,0 +1,297 @@ +//! Smart mask and smart material previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use texturecraft_texel::TILE; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +pub use crate::material_preview_pixel::MaterialPreviewPixel; +use crate::orb_camera::OrbCamera; +use crate::preview::Sample; +use crate::session::Document; +use crate::{EngineError, Result, Session, materials}; + +/// Bake resolution in texels; 256 loses the thin edge lines +const TEXTURE_PX: u32 = 512; +/// Camera rays per preview pixel along each axis (anti-aliased outline) +const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for shelf previews +pub const MAX_PREVIEW_SIZE_PX: usize = 512; +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default +const OCCLUSION_RAYS: u32 = 12; +/// Curvature rays per texel; thumbnail detail needs fewer than the default +const CURVATURE_RAYS: u32 = 12; +/// Radius relative to the bounding box; isolates panel edges from the round body +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read; smart materials build on the same presets +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Keep camera views for the thumbnail and hover preview sizes +const CAMERAS_KEPT: usize = 2; +/// The channels a material preview shows, in [`Sample`] order +const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; +/// The orb's only texture set +const SET: usize = 0; + +/// The baked orb and, per preview size, what its camera sees +pub struct OrbPreview { + session: Session, + /// The layer smart masks are applied to + layer: LayerId, + /// The baked document and selection, restored before each material + bare: (Document, BTreeMap), + /// Cached camera views, least recently used first + cameras: Vec, +} + +impl OrbPreview { + /// Bake the orb once (previews of any size reuse it) + pub fn new() -> Result { + let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(SET)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(SET, false)?; + + let bare = (session.doc.clone(), session.selected.clone()); + Ok(OrbPreview { session, layer, bare, cameras: Vec::new() }) + } + + /// Row-major `size²` pixels of smart mask `id`, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn mask(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Previews need no undo history; retaining snapshots grows memory across presets + self.session.undo.clear(); + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + mask_sum += values.get(texel).copied().unwrap_or(0.0); + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } + + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn material(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each material goes on the bare shape, not over the previous one + (self.session.doc, self.session.selected) = self.bare.clone(); + let applied = materials::apply(&mut self.session, id); + // Previews need no undo history; retaining snapshots grows memory across materials + self.session.undo.clear(); + applied.ok()?; + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = material_at(&self.session, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 }; + let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + let Some(value) = values.get(texel) else { continue }; + + sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]); + sum.metallic += value.metallic; + sum.roughness += value.roughness; + sum.height += value.height; + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| { + let mean = Sample { + base: sum.base.map(|component| component / hits), + metallic: sum.metallic / hits, + roughness: sum.roughness / hits, + height: sum.height / hits, + }; + MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels } + }) + }) + .collect(); + Some(pixels) + } +} + +/// Preview sizes the camera may allocate +fn valid_size(size: usize) -> bool { + (1..=MAX_PREVIEW_SIZE_PX).contains(&size) +} + +/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal) +fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator + '_ { + let (x, y) = (pixel % size, pixel / size); + (0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| { + let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE); + let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x; + camera.samples.get(ray).copied().flatten() + }) +} + +/// The material values at `texels`, compositing only the tiles that hold them +fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> { + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + + session.with_inputs(SET, |inputs| { + let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); + texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); + + let samples = texels + .iter() + .map(|&(x, y)| { + let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y)); + Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] } + }) + .collect(); + Some(samples) + }) +} + +/// Cache one camera per preview size, evicting the least recently used view +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a OrbCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) { + Some(index) => cameras.remove(index), + None => OrbCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } + + cameras.push(camera); + cameras.last() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + /// Mean mask value over the pixels a preview sees + fn mean_mask(pixels: &[Option]) -> f32 { + pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 + } + + #[test] + fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); + for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { + assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); + assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); + assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); + } + } + + #[test] + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for smart_mask in crate::smart_masks::SMART_MASKS { + let id = smart_mask.id; + let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame"); + for pixel in seen { + assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite(), "{id}: {pixel:?}"); + } + } + + let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap()); + let shows = |pixels: &[Option]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.mask("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.mask("edges_sharp", size * 3).unwrap(); + assert_eq!(big.len(), size * size * 9); + assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges)); + + preview.mask("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); + } + + #[test] + fn smart_materials_render_on_the_orb_and_show_their_wear() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for material in materials::MATERIALS.iter().filter(|material| material.smart) { + let id = material.id; + let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + for pixel in pixels.iter().flatten() { + let sample = pixel.sample; + let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]); + assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); + } + } + assert!(preview.material("nope", size).is_none()); + + // Paint chipped at the edges shows the steel under it: the smart material is not its base + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); + let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); + assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); + + let base_colors = |pixels: &[Option]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::>(); + assert_ne!(base_colors(&worn), base_colors(&steel)); + + // Each material starts from the bare orb: rendering another one in between changes nothing + preview.material("iron_rusted", size).unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 5b72cea4..ce45b9ff 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,14 +1,8 @@ -//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or -//! baked maps (generators that need mesh maps are approximated with world-space noise), and -//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked -//! preview ([`crate::mask_preview`]). +//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) use rayon::prelude::*; -use texturecraft_compose::pattern::{Coords, procedural, world_noise}; -use texturecraft_core::{ - Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, - Projection, Source, TextureSet, blend1, -}; +use texturecraft_compose::pattern::{Coords, procedural}; +use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { } } -/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities). -fn generator(g: &Generator, c: &Coords) -> f32 { - let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y); - let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2; - let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1; - let s = match g.kind { - GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5, - GeneratorKind::EdgeWear => wear, - GeneratorKind::Curvature => 0.5 + wear * 0.5, - GeneratorKind::AmbientOcclusion => 1.0 - cavity, - _ => cavity, - }; - // Same thresholding as the compositor. - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } -} - -fn mask(m: &Mask, c: &Coords) -> f32 { - if !m.enabled { - return 1.0; - } - let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 }; - for e in m.effects.iter().filter(|e| e.visible) { - let val = match &e.kind { - EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]), - EffectKind::Generator(g) => Some(generator(g, c)), - EffectKind::Levels(l) => Some(l.apply(v)), - EffectKind::Filter(Filter::Invert) => Some(1.0 - v), - _ => None, - }; - if let Some(val) = val { - let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) }; - v += (blended - v) * e.opacity.clamp(0.0, 1.0); - } - } - v.clamp(0.0, 1.0) -} - const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; -/// Preview of built-in material `id` (None for an unknown id). +/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps) pub fn material(id: &str, size: usize) -> Option>> { + let plain = crate::materials::find(id).filter(|found| !found.smart)?; let mut project = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?; // Pixels evaluate independently and big previews take long on one core let normals: Vec<_> = sphere_normals(size).collect(); @@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option>> { .map(|normal| { let at = coords(normal?); let mut values = CHANNELS.map(Channel::default_value); - for layer in layers.iter().filter(|l| l.visible) { + for layer in layers.iter().filter(|layer| layer.visible) { + // Plain materials are unmasked fills let LayerKind::Fill(fill) = &layer.kind else { continue }; - let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); for (value, channel) in values.iter_mut().zip(CHANNELS) { - let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at)); if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { - let weight = coverage * blend.opacity.clamp(0.0, 1.0); - *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); + let weight = blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight); } } } - let [base, metal, rough, height] = values; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + let [base, metallic, roughness, height] = values; + Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }) }) .collect(); + Some(samples) } @@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option>> { mod tests { use super::*; + /// Whether every value of `sample` is finite + fn finite(sample: &Sample) -> bool { + sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite) + } + #[test] fn previews_cover_the_sphere_with_finite_values() { - for m in crate::materials::MATERIALS { - let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id)); - let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id)); - assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); - assert!(px[0].is_none(), "corners are outside the sphere"); + let size = 16; + for built_in in crate::materials::MATERIALS { + let id = built_in.id; + if built_in.smart { + assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb"); + continue; + } + + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap(); + assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks"); + + let pixels = material(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); + assert!(pixels[0].is_none(), "corners are outside the sphere"); } - assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); - for f in crate::filter_lib::FILTERS { - let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); - let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); - assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id); + assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + + let size = 24; + for library_filter in crate::filter_lib::FILTERS { + let id = library_filter.id; + let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); } - let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap()); + let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } } diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 29bad947..69fab43b 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8; /// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. const ORB_PANEL_VALLEY: f32 = 0.88; -/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base /// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly /// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys /// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..f383c197 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,8 +17,9 @@ pub mod gpu; pub mod i18n; pub mod keymap; mod mask_preview_image; -mod mask_shape; +mod material_preview_image; pub mod menus; +mod orb_shape; pub mod parity; mod preview_image; mod preview_request; @@ -27,6 +28,7 @@ pub mod profile; pub mod render_mode; pub mod shelf; pub mod shelf_preview; +mod soft_box; pub mod state; pub mod theme; pub mod thumbs; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 4418d099..de7368df 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -2,7 +2,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::orb_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; /// View-space lighting uses an upper-left key and a weaker right fill diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs deleted file mode 100644 index c99a9b1c..00000000 --- a/crates/ui-egui/src/mask_shape.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The smart mask preview shape, baked on first use - -use texturecraft_engine::mask_preview::MaskPreview; - -/// Whether the smart mask preview shape is baked -#[derive(Default)] -pub enum MaskShape { - #[default] - NotBaked, - /// Box the large session to keep the unbaked worker small - Baked(Box), - /// The bake failed; smart mask previews stay empty - Failed, -} - -impl MaskShape { - /// Bake on first use; retain failure to avoid retrying every frame - pub fn get(&mut self) -> Option<&mut MaskPreview> { - if matches!(self, MaskShape::NotBaked) { - *self = match MaskPreview::new() { - Ok(preview) => MaskShape::Baked(Box::new(preview)), - Err(e) => { - log::warn!("smart mask previews: {e}"); - MaskShape::Failed - } - }; - } - match self { - MaskShape::Baked(preview) => Some(preview), - MaskShape::NotBaked | MaskShape::Failed => None, - } - } -} diff --git a/crates/ui-egui/src/material_preview_image.rs b/crates/ui-egui/src/material_preview_image.rs new file mode 100644 index 00000000..bc232b75 --- /dev/null +++ b/crates/ui-egui/src/material_preview_image.rs @@ -0,0 +1,100 @@ +//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaterialPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius}; +use crate::soft_box::{SoftBox, smoothstep}; + +/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind +const SOFT_BOXES: [SoftBox; 3] = [ + SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 }, + SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 }, + SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 }, +]; +/// The studio's backdrop brightness straight down and straight up (linear) +const FLOOR: f32 = 0.03; +const CEILING: f32 = 0.16; +/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges) +const MIN_ROUGHNESS: f32 = 0.02; +/// Reflectance of dielectrics at normal incidence +const DIELECTRIC_F0: f32 = 0.04; +/// Exposure before tone mapping +const EXPOSURE: f32 = 1.4; + +/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals +pub fn material_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let radius = preview_radius(size); + let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() { + let Some(pixel) = pixel else { continue }; + + let sample = pixel.sample; + let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius); + let roughness = sample.roughness.max(MIN_ROUGHNESS); + let normal_dot_view = normal.z.max(0.0); + // Mirror the direction towards the viewer (+Z) about the normal + let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero(); + let specular_light = reflected_light(reflected, roughness); + let diffuse_light = diffuse_light(normal); + // Schlick's Fresnel term, damped on rough surfaces below + let fresnel = (1.0 - normal_dot_view).powi(5); + + let color = [0, 1, 2].map(|component| { + let base = sample.base[component]; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic; + let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel; + let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light; + (linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8 + }); + let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha); + } + image +} + +/// How far unit direction component `y` points up: 0 straight down, 1 straight up +fn upward(y: f32) -> f32 { + y * 0.5 + 0.5 +} + +/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1) +fn backdrop(upward: f32) -> f32 { + FLOOR + (CEILING - FLOOR) * upward +} + +/// The studio seen along unit direction `view` by a surface of `roughness` +fn reflected_light(view: Vec3, roughness: f32) -> f32 { + // A soft horizon: reflections sweep from floor to ceiling smoothly + backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::() +} + +/// The light reaching a diffuse surface with unit normal `normal` +fn diffuse_light(normal: Vec3) -> f32 { + backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::preview::Sample; + + use super::*; + + #[test] + fn the_studio_lights_the_shape_from_the_upper_right() { + let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 }; + let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 }); + // Halfway between the viewer and the key light, a mirror reflects the key + let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z; + let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None]; + + let image = material_preview_image(2, &pixels); + let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]); + assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}"); + assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside"); + } +} diff --git a/crates/ui-egui/src/orb_shape.rs b/crates/ui-egui/src/orb_shape.rs new file mode 100644 index 00000000..3d220a5c --- /dev/null +++ b/crates/ui-egui/src/orb_shape.rs @@ -0,0 +1,33 @@ +//! The preview orb of the smart mask and smart material previews, baked on first use + +use texturecraft_engine::orb_preview::OrbPreview; + +/// Whether the preview orb is baked +#[derive(Default)] +pub enum OrbShape { + #[default] + NotBaked, + /// Box the large session to keep the unbaked worker small + Baked(Box), + /// The bake failed; previews on the orb stay empty + Failed, +} + +impl OrbShape { + /// Bake on first use; retain failure to avoid retrying every frame + pub fn get(&mut self) -> Option<&mut OrbPreview> { + if matches!(self, OrbShape::NotBaked) { + *self = match OrbPreview::new() { + Ok(preview) => OrbShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("preview orb: {e}"); + OrbShape::Failed + } + }; + } + match self { + OrbShape::Baked(preview) => Some(preview), + OrbShape::NotBaked | OrbShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index f689c85d..9b753b74 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -3,6 +3,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; @@ -12,6 +13,14 @@ use texturecraft_engine::texel::linear_to_srgb; const PROCEDURAL_SCALE: f32 = 3.0; /// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; +/// Normal tilt per height step, relative to the shape's radius in pixels +const BUMP_PER_RADIUS: f32 = 0.75; +/// Exposure of the shaded previews before tone mapping +const EXPOSURE: f32 = 1.4; +/// Gap between a preview's shape and the image edge in pixels +const SHAPE_MARGIN_PX: f32 = 1.0; +/// Guards the normal division against a zero vector +const MIN_NORMAL_LENGTH: f32 = 1e-6; /// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -52,28 +61,52 @@ pub fn aces(x: f32) -> f32 { /// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let radius = preview_radius(size); + let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height); - let (x, y) = (i % size, i / size); - let c = s.height; - // Image Y points down; the shading normal uses Y up - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + for (index, normal) in preview::sphere_normals(size).enumerate() { + let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue }; + + // Anti-aliased outline: opaque from one pixel inside the rim + let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0); + image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage); } - img + image +} + +/// Radius in pixels of the shape filling a `size²` preview +pub(crate) fn preview_radius(size: usize) -> f32 { + (size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5) +} + +/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center` +pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option) -> [f32; 2] { + let (x, y) = (pixel % size, pixel / size); + let at = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + height(y.checked_mul(size)?.checked_add(x)?) + }; + + // Image Y points down; the shading normal uses Y up + let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center); + let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center); + [right, up] +} + +/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels +pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 { + let bump = radius * BUMP_PER_RADIUS; + let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z]; + let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH); + Vec3::from(bumped.map(|component| component / length)) +} + +/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque +fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 { + let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness); + let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8) } /// Grayscale `size²` swatch of procedural `kind` diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c7870b..7797a7e3 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -3,7 +3,8 @@ use egui::ColorImage; use crate::mask_preview_image::mask_preview_image; -use crate::mask_shape::MaskShape; +use crate::material_preview_image::material_preview_image; +use crate::orb_shape::OrbShape; use crate::shelf_preview::ShelfPreview; /// Render `preview` at `size_px²`; the answer comes back under `key` @@ -18,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the mask shape on first use + /// Render the asset, baking the orb on first use for smart masks and smart materials /// Unknown assets and failed bakes return None - pub fn render(&self, shape: &mut MaskShape) -> Option { + pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { - ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index a3d2cc8f..1fe89353 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -2,7 +2,7 @@ //! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] -use crate::mask_shape::MaskShape; +use crate::orb_shape::OrbShape; use crate::preview_request::PreviewRequest; /// Request key and rendered image; None on failure @@ -18,7 +18,7 @@ pub enum PreviewWorker { Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] - Inline { shape: MaskShape, results: Vec }, + Inline { shape: OrbShape, results: Vec }, /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -89,7 +89,7 @@ impl PreviewWorker { use std::collections::VecDeque; use std::sync::mpsc::channel; - use crate::mask_shape::MaskShape; + use crate::orb_shape::OrbShape; let (requests, request_rx) = channel::(); let (result_tx, results) = channel(); @@ -101,7 +101,7 @@ impl PreviewWorker { if let Err(e) = &pool { log::warn!("shelf previews share the global thread pool: {e}"); } - let mut shape = MaskShape::default(); + let mut shape = OrbShape::default(); let mut queue = VecDeque::new(); loop { if queue.is_empty() { @@ -136,7 +136,7 @@ impl PreviewWorker { /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { - PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() } } } @@ -170,23 +170,26 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), + ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; + let requests_sent = requests.len(); for (key, preview) in requests { assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); } let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask"] { + for key in ["material", "mask", "smart material"] { let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); assert_eq!(image.size, [size_px, size_px], "{key}"); } - for key in ["unknown material", "unknown mask"] { + for key in ["unknown material", "unknown mask", "unknown smart material"] { assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); } assert!(!worker.is_stopped()); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..5d876249 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,8 +12,8 @@ use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::materials::MATERIALS; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -34,8 +34,9 @@ const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width -const PLACEHOLDER_RADIUS: f32 = 0.45; +/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color +const LOADING_ICON_SCALE: f32 = 0.9; +const LOADING_ICON_OPACITY: f32 = 0.5; /// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; @@ -300,20 +301,22 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// Built-in materials (or smart materials), grouped by category. +/// Built-in materials or smart materials, grouped by category fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect(); + let shown: Vec<_> = + MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); if shown.is_empty() { return; } + title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); + for category in categories(&shown, |material| material.category) { + header(ui, category); tiles(ui, |ui| { - for m in shown.iter().filter(|m| m.category == cat) { - let tex = app.thumbs.material(ctx, m.id); - let asset = Asset::Material(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { + for material in shown.iter().filter(|material| material.category == category) { + let texture = app.thumbs.material(ctx, material.id); + let asset = Asset::Material(material.id); + if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -623,8 +626,9 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let preview = preview(); let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; - // High display scales must respect the mask camera's allocation limit - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + // High display scales must respect the orb camera's allocation limit + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); @@ -636,14 +640,21 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders -fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { - match tex { - Some(t) => { - painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); +/// `texture` drawn into `rect`, or a dim loading icon while it renders +fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); + let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROWS_CLOCKWISE, + font, + tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY), + ); } } } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a23ffb32..b512f250 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; @@ -14,9 +15,11 @@ use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_ /// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere + /// A built-in plain material on a sphere Material(&'static str), - /// Smart mask rendering requires the worker's baked shape + /// Smart material rendering requires the worker's baked orb + SmartMaterial(&'static str), + /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), /// A library filter on a sample material on a sphere Filter(&'static str), @@ -31,10 +34,19 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Smart materials preview on the orb, plain materials on a sphere + pub fn material(id: &'static str) -> ShelfPreview { + match materials::find(id) { + Some(found) if found.smart => ShelfPreview::SmartMaterial(id), + Some(_) | None => ShelfPreview::Material(id), + } + } + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), @@ -45,11 +57,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks return None here because their bake belongs to the worker + /// Smart masks and smart materials return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), @@ -86,14 +98,23 @@ mod tests { let key = preview.key(); let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); - assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows"); } let finite = |samples: Vec>| { - samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) }; assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); - assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); + assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); + } + + #[test] + fn smart_materials_and_only_they_preview_on_the_orb() { + for material in MATERIALS { + let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_)); + assert_eq!(on_the_orb, material.smart, "{}", material.id); + } } } diff --git a/crates/ui-egui/src/soft_box.rs b/crates/ui-egui/src/soft_box.rs new file mode 100644 index 00000000..9c2c8391 --- /dev/null +++ b/crates/ui-egui/src/soft_box.rs @@ -0,0 +1,48 @@ +//! A soft box of the smart material preview studio (see [`crate::material_preview_image`]) + +use texturecraft_engine::geom::glam::Vec3; + +/// How much roughness widens a soft box's reflection, in radians per unit of roughness +const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1; +/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians +const EDGE_SOFTNESS: f32 = 0.25; +const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02; +/// The share of a soft box's light that reaches a diffuse surface facing it +const DIFFUSE_SHARE: f32 = 0.9; + +/// A round area light far away, seen as a disc in reflections +pub struct SoftBox { + /// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized + pub direction: [f32; 3], + /// Angular radius of the disc in radians + pub radius_rad: f32, + /// Brightness of the disc (linear) + pub intensity: f32, +} + +impl SoftBox { + /// The unit direction towards the light + pub fn unit_direction(&self) -> Vec3 { + Vec3::from(self.direction).normalize_or_zero() + } + + /// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out) + pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 { + let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS); + let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos(); + let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD; + let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad); + self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside + } + + /// The light reaching a diffuse surface with unit normal `normal` + pub fn diffuse(&self, normal: Vec3) -> f32 { + self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0) + } +} + +/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends +pub fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9ed4f73b..d0067411 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,6 @@ //! Shelf and brush preview caches //! Small synchronous renders are limited per frame -//! Smart masks and hover previews use [`PreviewWorker`] +//! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -16,7 +16,7 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) +/// UI-thread renders per frame at most; a web worker request uses the whole budget const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; @@ -37,7 +37,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews + /// Renders the orb thumbnails and the big previews worker: PreviewWorker, /// Worker-rendered previews by [`worker_key`] rendered: HashMap, @@ -82,25 +82,34 @@ impl Thumbs { /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); } + if !self.spend_budget(ctx, 1) { + return None; + } + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint + fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool { let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); } - if self.budget.1 >= PER_FRAME { + if self.budget.1 + renders > PER_FRAME { ctx.request_repaint(); - return None; + return false; } - self.budget.1 += 1; - // An unknown asset shows as an empty thumbnail - let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); - let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + self.budget.1 += renders; + true } /// Request once per asset and size; return None while pending or after failure @@ -109,13 +118,19 @@ impl Thumbs { self.receive(ctx); let key = worker_key(&preview, size_px); - if !self.rendered.contains_key(&key) { + if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); } + self.ready(&key) } + /// Native workers take every request; the web renders inline, so it takes one per frame + fn may_request(&mut self, ctx: &egui::Context) -> bool { + !cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME) + } + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { @@ -169,9 +184,12 @@ impl Thumbs { self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id` + /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { - self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + match ShelfPreview::material(id) { + preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false), + preview => self.shelf(ctx, preview, SPHERE_PX), + } } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 53767276..27c3525b 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -7,6 +7,6 @@ pub enum WorkerPreview { /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) + /// The asset is unknown or the worker could not render it (the tile keeps its loading icon) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 460ed7c8..2ad76a68 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -145,7 +145,7 @@ fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { - use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; + use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::smart_masks::SMART_MASKS; let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0); From 0f0047ae7b4f3427b7278a7cb28fac560aa0601b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:27:43 +0000 Subject: [PATCH 07/76] Panel layouts survive a restart The UI state was saved as RON through eframe's storage, and a dock read through a JSON value lost RON's enum variant names, so every saved layout loaded as the default. The UI state is now saved as JSON in a store of its own: ui.json beside eframe's settings on the desktop, a storage key on the web. A saved state this build cannot fully read is kept beside it before the next save, and the state earlier builds saved still loads. --- apps/texturecraft/src/main.rs | 60 +++-- crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/state.rs | 24 +- crates/ui-egui/src/ui_state_store.rs | 314 ++++++++++++++++++++++++++ crates/ui-egui/tests/split_divider.rs | 14 +- 5 files changed, 373 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/ui_state_store.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..694e8826 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,6 +11,7 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). @@ -115,13 +116,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// 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 { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + 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) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -170,20 +174,24 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged 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 so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // 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()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + 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 mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -195,7 +203,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -296,19 +304,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + 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; - // Written as eframe writes it: a pretty RON map of RON strings. + // 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(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + 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); + + ui.prefs.system_title_bar = !on; + 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"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + 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))); + 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))); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..2a586519 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -32,6 +32,7 @@ pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; pub mod viewport; pub mod web_files; pub mod widgets; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { /// A smooth move to a saved camera in progress. camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -132,12 +135,13 @@ pub struct TextureCraftApp { impl TextureCraftApp { pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui @@ -147,6 +151,7 @@ impl TextureCraftApp { camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -179,14 +184,14 @@ impl TextureCraftApp { export_templates::load_library(&mut app, cc.storage); #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } app } @@ -477,7 +482,7 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); export_templates::save_library(self, storage); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..2aaab049 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -429,35 +429,13 @@ mod tests { } } - /// The app's own settings store: eframe keeps `UiState` as RON text under a key - #[derive(Default)] - struct MemoryStorage(std::collections::HashMap); - - impl eframe::Storage for MemoryStorage { - fn get_string(&self, key: &str) -> Option { - self.0.get(key).cloned() - } - - fn set_string(&mut self, key: &str, value: String) { - self.0.insert(key.to_string(), value); - } - - fn remove_string(&mut self, key: &str) { - self.0.remove(key); - } - - fn flush(&mut self) {} - } - #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { let mut ui = UiState { mode, ..UiState::default() }; ui.sync_mode_dock(); - let mut storage = MemoryStorage::default(); - eframe::set_value(&mut storage, "ui", &ui); - let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + let mut restarted = crate::ui_state_store::tests::restart(&ui); restarted.sync_mode_dock(); let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..467dad78 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,314 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// eframe storage key under which earlier builds kept the UI state, as RON +const RON_STORAGE_KEY: &str = "ui"; + +/// eframe storage key of a saved state this build could not fully read, where there is no file +const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; + +/// Largest UI state file read; a saved state is a few kilobytes +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Copies of unreadable saved states kept beside the file before saving stops +const MAX_UNREADABLE_COPIES: u32 = 10; + +/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + unreadable: Option>, + /// The unreadable state could not be kept, so the saved one is left as it is + frozen: bool, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, unreadable: None, frozen: false } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) if too_large(file) => { + self.frozen = true; + return None; + } + Some(file) => std::fs::read(file).ok(), + None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), + }; + let Some(bytes) = saved else { + return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); + }; + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some(bytes); + } + ui + } + + /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds + pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { + if let Some(bytes) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, storage); + } + if self.frozen { + return; + } + + let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => { + storage.set_string(STORAGE_KEY, json); + true + } + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + } + } + + /// Keep a saved state this build could not fully read, beside the file or under its own storage key + fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + match &self.file { + Some(file) => keep_file_copy(file, bytes), + None => { + storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + true + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + if too_large(file) { + return None; + } + + serde_json::from_slice(&std::fs::read(file).ok()?).ok() +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// Whether `file` is too large to be a saved UI state, so it is neither read nor saved over +fn too_large(file: &Path) -> bool { + std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` +fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { + use std::io::Write as _; + + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; + match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// eframe's storage held in memory + #[derive(Default)] + pub(crate) struct MemoryStorage(pub(crate) std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.0)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.0.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + store.save(&loaded.unwrap_or_default(), &mut storage); + let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); + assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + let folder = test_folder("frozen"); + let file = folder.join("ui.json"); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; + std::fs::write(folder.join(name), "").unwrap(); + } + std::fs::write(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); + let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); + storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } +} diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs index d5af8c8f..e0a487fc 100644 --- a/crates/ui-egui/tests/split_divider.rs +++ b/crates/ui-egui/tests/split_divider.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` const MIN_VIEW_WIDTH: f32 = 16.0; @@ -144,16 +145,15 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { let mut storage = MemoryStorage::default(); let mut ui_state = UiState::default(); ui_state.split_ratio = 0.3; - eframe::set_value(&mut storage, "ui", &ui_state); - let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); assert_eq!(restored.split_ratio, 0.3); // A state saved before the divider existed has no ratio - let saved = storage.0.get("ui").cloned().unwrap(); - let without_ratio = saved.replace("split_ratio:0.3,", ""); - assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); - storage.0.insert("ui".to_owned(), without_ratio); - let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); assert_eq!(restored.split_ratio, 0.5); } From a626af86bb7f9e3009968b3c77be0444c6d883e0 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:10:23 +0000 Subject: [PATCH 08/76] Keep every saved state that cannot be read, and save only states that read back --- crates/ui-egui/src/ui_state_store.rs | 146 +++++++++++++++++++++------ 1 file changed, 114 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 467dad78..4535817d 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -8,16 +8,16 @@ use crate::UiState; /// eframe storage key of the UI state as JSON, where there is no file const STORAGE_KEY: &str = "ui.json"; +/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there +const STORAGE_STEM: &str = "ui"; + /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; -/// eframe storage key of a saved state this build could not fully read, where there is no file -const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; - /// Largest UI state file read; a saved state is a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; -/// Copies of unreadable saved states kept beside the file before saving stops +/// Copies of unreadable saved states kept before saving stops const MAX_UNREADABLE_COPIES: u32 = 10; /// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage @@ -27,8 +27,9 @@ pub static FILE: OnceLock = OnceLock::new(); #[derive(Default)] pub struct UiStateStore { file: Option, - unreadable: Option>, - /// The unreadable state could not be kept, so the saved one is left as it is + /// A saved state this build could not fully read and its file extension, kept by the next save + unreadable: Option<(Vec, &'static str)>, + /// A saved state could not be read or kept, so it is left as it is frozen: bool, } @@ -45,30 +46,51 @@ impl UiStateStore { self.frozen = true; return None; } - Some(file) => std::fs::read(file).ok(), + Some(file) => match std::fs::read(file) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => { + self.frozen = true; + return None; + } + }, None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), }; - let Some(bytes) = saved else { - return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); - }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; let ui = serde_json::from_slice::(&bytes).ok(); if !ui.as_ref().is_some_and(fully_read) { - self.unreadable = Some(bytes); + self.unreadable = Some((bytes, "json")); + } + ui + } + + /// The RON state an earlier build saved; its docks never read back, so only text that does not parse is kept + fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if ui.is_none() { + self.unreadable = Some((text.into_bytes(), "ron")); } ui } /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { - if let Some(bytes) = self.unreadable.take() { - self.frozen = !self.keep_unreadable(&bytes, storage); + if let Some((bytes, extension)) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, extension, storage); } if self.frozen { return; } let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + // JSON writes a non-finite number as null, which would not read back + if serde_json::from_str::(&json).is_err() { + log::warn!("the UI state was not saved: it would not read back"); + return; + } + let saved = match &self.file { Some(file) => write_file(file, json.as_bytes()), None => { @@ -81,12 +103,15 @@ impl UiStateStore { } } - /// Keep a saved state this build could not fully read, beside the file or under its own storage key - fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + /// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage + fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool { match &self.file { - Some(file) => keep_file_copy(file, bytes), + Some(file) => keep_file_copy(file, bytes, extension), None => { - storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none()); + let Some(key) = free else { return false }; + + storage.set_string(&key, String::from_utf8_lossy(bytes).into_owned()); true } } @@ -112,6 +137,11 @@ fn too_large(file: &Path) -> bool { std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) } +/// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` +fn unreadable_name(stem: &str, n: u32, extension: &str) -> String { + if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") } +} + #[cfg(not(target_arch = "wasm32"))] fn write_file(file: &Path, bytes: &[u8]) -> bool { if let Some(folder) = file.parent() { @@ -126,14 +156,14 @@ fn write_file(_file: &Path, _bytes: &[u8]) -> bool { false } -/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` -fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { +/// Copy `bytes` beside `file` under the first free copy name +fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool { use std::io::Write as _; let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; - match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + let copy_file = file.with_file_name(unreadable_name(&stem, n, extension)); + match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) { Ok(mut copy) => return copy.write_all(bytes).is_ok(), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} Err(_) => return false, @@ -257,7 +287,7 @@ pub(crate) mod tests { } store.save(&loaded.unwrap_or_default(), &mut storage); - let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + let copy = unreadable_name("ui", n as u32 + 1, "json"); assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); } @@ -269,8 +299,7 @@ pub(crate) mod tests { let folder = test_folder("frozen"); let file = folder.join("ui.json"); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; - std::fs::write(folder.join(name), "").unwrap(); + std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap(); } std::fs::write(&file, "not json").unwrap(); @@ -298,17 +327,70 @@ pub(crate) mod tests { } #[test] - fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() { let mut storage = MemoryStorage::default(); UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); - let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); - storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + let saved = storage.0[STORAGE_KEY].clone(); + for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] { + let unreadable = saved.replacen("\"Assets\"", panel, 1); + storage.0.insert(STORAGE_KEY.to_owned(), unreadable.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, n, "json")], unreadable); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays"); + } + + #[test] + fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() { + let folder = test_folder("ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + storage.0.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned()); + + let mut store = UiStateStore::new(file.clone()); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + let copy = match &file { + Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(), + None => storage.0[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(), + }; + assert_eq!(copy, "(not ron", "{file:?}"); + assert!(!storage.0.contains_key(RON_STORAGE_KEY), "{file:?}"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() { + let folder = test_folder("read-error"); + let file = folder.join("ui.json"); + // A folder in the file's place fails to read with an error other than not found + std::fs::create_dir_all(&file).unwrap(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + + let mut store = UiStateStore::new(Some(file.clone())); + assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place"); + store.save(&UiState::default(), &mut storage); + assert!(file.is_dir()); + assert!(storage.0.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_state_that_would_not_read_back_is_not_saved() { + let mut storage = MemoryStorage::default(); let mut store = UiStateStore::default(); - let loaded = store.load(Some(&storage)).unwrap(); - assert_eq!(loaded.dock, Dock::default()); - store.save(&loaded, &mut storage); - assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); - assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + let saved = storage.0[STORAGE_KEY].clone(); + + store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage); + assert_eq!(storage.0[STORAGE_KEY], saved); } } From 3b302b88dc9d44235bbccb4cdd6721212a0760ba Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 05:03:21 +0000 Subject: [PATCH 09/76] Polygon fill: box selection, polygon mode, hit-test, visible polygons only and the 2D view A drag in the 3D or 2D view draws a rectangle and fills what it selects live; releasing it records one undo step. A click still fills one target, now also in the 2D view. Fill modes gain Polygon (the source quad or n-gon, from the importer's diagonals), and Mesh fills connected geometry. The hit-test picks polygons the rectangle touches or whose center it holds; visible polygons only uses a nearest-triangle buffer next to the eye-depth raster, leaving hidden texture sets out. Polygon fill's properties show its own settings and, by selection, the material, the mask gray, or why it can't fill. Wireframes show while the tool is active without changing the saved toggles. Commands: tool.fillMode takes polygon, tool.fillSelection sets hitTest and visibleOnly, and tool.click takes a screen box, a UV point or a UV box. --- crates/engine/src/fill_hit_test.rs | 80 ++++ crates/engine/src/lib.rs | 5 + crates/engine/src/painting.rs | 130 ++----- crates/engine/src/polygon_fill.rs | 470 ++++++++++++++++++++++++ crates/engine/src/polygon_fill_drag.rs | 28 ++ crates/engine/src/session.rs | 19 +- crates/engine/src/tool_cmds.rs | 71 +++- crates/engine/src/triangle_partition.rs | 77 ++++ crates/engine/tests/session.rs | 23 ++ crates/paint/src/visibility.rs | 135 ++++--- crates/ui-egui/src/dock.rs | 183 +++++++-- crates/ui-egui/src/i18n/ar.rs | 20 + crates/ui-egui/src/i18n/de.rs | 23 ++ 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 | 23 ++ crates/ui-egui/src/i18n/pt_br.rs | 26 ++ crates/ui-egui/src/i18n/zh_hans.rs | 17 + crates/ui-egui/src/toolbar.rs | 31 +- crates/ui-egui/src/viewport.rs | 74 +++- crates/ui-egui/tests/polygon_fill.rs | 85 +++++ 23 files changed, 1414 insertions(+), 210 deletions(-) create mode 100644 crates/engine/src/fill_hit_test.rs create mode 100644 crates/engine/src/polygon_fill.rs create mode 100644 crates/engine/src/polygon_fill_drag.rs create mode 100644 crates/engine/src/triangle_partition.rs create mode 100644 crates/ui-egui/tests/polygon_fill.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs new file mode 100644 index 00000000..8a2b9359 --- /dev/null +++ b/crates/engine/src/fill_hit_test.rs @@ -0,0 +1,80 @@ +//! Which polygons a polygon fill box selects. + +use serde::{Deserialize, Serialize}; +use texturecraft_geom::glam::Vec2; + +/// How a polygon fill box decides whether it selects a polygon +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillHitTest { + /// Any part of the polygon inside the box or crossing it + #[default] + Intersection, + /// The polygon's center point inside the box + ContainedCenter, +} + +impl FillHitTest { + /// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners) + pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool { + match self { + FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)), + FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()), + } + } +} + +/// Area-weighted center of the triangles (their corners' mean when they have no area) +fn center(triangles: &[[Vec2; 3]]) -> Option { + let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; + let total: f32 = triangles.iter().map(area).sum(); + let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); + let centroids: Vec2 = triangles.iter().map(centroid).sum(); + + match triangles.len() { + 0 => None, + count if total <= f32::EPSILON => Some(centroids / count as f32), + _ => Some(weighted / total), + } +} + +/// Separating axis test of a triangle against an axis-aligned box +fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool { + let triangle_low = corners[0].min(corners[1]).min(corners[2]); + let triangle_high = corners[0].max(corners[1]).max(corners[2]); + if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() { + return false; + } + + let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)]; + (0..3).all(|edge| { + let axis = (corners[(edge + 1) % 3] - corners[edge]).perp(); + let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point)))); + let (triangle_min, triangle_max) = span(&corners); + let (box_min, box_max) = span(&box_corners); + triangle_max >= box_min && box_max >= triangle_min + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; + + #[test] + fn intersection_needs_any_overlap_and_contained_center_the_center() { + let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); + } + + #[test] + fn a_polygon_center_weighs_its_triangles_by_area() { + let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]]; + assert_eq!(center(&square), Some(Vec2::ONE)); + assert_eq!(center(&[]), None); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..824ccf48 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_hit_test; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -31,6 +32,8 @@ pub mod materialx_cmds; pub mod meshmap_cmds; pub mod painting; pub mod path_tool; +mod polygon_fill; +mod polygon_fill_drag; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] mod preserve; @@ -45,11 +48,13 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod triangle_partition; pub mod uv_tile_cmds; pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; +pub use fill_hit_test::FillHitTest; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..86761f79 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -7,11 +7,11 @@ use texturecraft_compose::PaintTarget; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ - CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, - fill_triangles, pick, rasterize, + CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, + rasterize, }; -use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; use crate::{EngineError, Result}; impl Session { @@ -301,12 +301,15 @@ impl Session { Ok(self.continue_stroke(screen, pressure)) } - /// Start a stroke in the 2D view at texture coordinate `uv`. + /// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there). pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { 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())); + match self.tool.tool { + Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()), + Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())), + _ => {} } + self.start_stroke(self.viewport, true, Some(uv))?; self.continue_stroke_uv(uv, pressure); Ok(()) @@ -482,21 +485,6 @@ impl Session { Ok(tiles) } - /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. - pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { - 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; - if hit.material != material { - return Err(EngineError::Other("that surface belongs to another texture set".into())); - } - let tris = self.fill_set(hit.tri, material); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - fill_triangles(&mut canvas, &gbuf, &tris); - self.commit_fill("Polygon fill", ts, &canvas)?; - Ok(tris.len()) - } - /// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the /// quick mask unless the fill edits it. pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc, StrokeCanvas)> { @@ -510,61 +498,30 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { - let size = (canvas.alpha.width(), canvas.alpha.height()); - let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; if self.quick_mask.editing { - self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); - return Ok(()); + return self.paint_fill(ts, canvas); } - self.edit(label, |s| { - let target = s.paint_target()?; - let values = s.stroke_values(target); - match target { - PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()), - PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()), - } - Ok(()) - }) + + self.edit(label, |session| session.paint_fill(ts, canvas)) } - /// Triangles filled by the current fill mode starting from `tri`. - fn fill_set(&self, tri: u32, material: usize) -> BTreeSet { - let m = &self.mesh; - match self.tool.fill_mode { - FillMode::Triangle => [tri].into_iter().collect(), - FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), - FillMode::UvIsland => { - // Triangles sharing an edge in UV space form a UV island: imported meshes often - // split vertices along hard edges (or per face) where the UVs run on, so shared - // vertex indices alone break an island into its polygons. - let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); - let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { - Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), - _ => Vec::new(), - }; - let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); - for t in m.triangles_of(material) { - for e in edges(t) { - by_edge.entry(e).or_default().push(t as u32); - } - } - let mut seen = BTreeSet::new(); - let mut stack = vec![tri]; - while let Some(t) = stack.pop() { - if !seen.insert(t) { - continue; - } - for e in edges(t as usize) { - for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } - } - } - } - seen - } + /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) + pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> { + let size = (canvas.alpha.width(), canvas.alpha.height()); + let opacity = self.tool.brush.opacity; + let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.quick_mask.editing { + self.commit_quick_mask(ts, size, source); + return Ok(()); } + + let target = self.paint_target()?; + let values = self.stroke_values(target); + match target { + PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()), + PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()), + } + Ok(()) } /// Color picker: copy the material under the cursor into the tool's paint values. @@ -627,34 +584,3 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } - -#[cfg(test)] -mod tests { - use texturecraft_geom::glam::{Vec2, Vec3}; - use texturecraft_geom::mesh::Mesh; - use texturecraft_geom::primitives; - - use crate::session::{FillMode, Session}; - - #[test] - fn uv_island_fill_follows_uvs_across_split_vertices() { - // Two copies of a plane, each triangle with its own three vertices (as hard edges or - // per-face imports leave a mesh), the second copy apart in UV space. - let plane = primitives::plane(2.0, 4); - let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); - for shift in [0.0, 0.5] { - for i in plane.indices.iter().map(|i| *i as usize) { - positions.push(plane.positions[i] + Vec3::Y * shift); - uvs.push(plane.uvs[i] * 0.5 + shift); - } - } - let indices = (0..positions.len() as u32).collect(); - let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); - let n = plane.triangle_count(); - assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); - let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); - s.tool.fill_mode = FillMode::UvIsland; - assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); - assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); - } -} diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs new file mode 100644 index 00000000..2d577835 --- /dev/null +++ b/crates/engine/src/polygon_fill.rs @@ -0,0 +1,470 @@ +//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view. + +use std::borrow::Cow; +use std::collections::{BTreeSet, HashSet}; + +use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_paint::{EyeDepth, fill_triangles}; + +use crate::polygon_fill_drag::PolygonFillDrag; +use crate::session::{FillMode, Session}; +use crate::triangle_partition::TrianglePartition; +use crate::{EngineError, Result}; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +const CORNER_GRID_STEPS: f32 = 1e5; + +/// Clip-space w below which a vertex counts as behind the camera +const MIN_CLIP_W: f32 = 1e-5; + +impl Session { + /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` + pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + if hit.material != self.fill_material()? { + return Err(EngineError::Other("that surface belongs to another texture set".into())); + } + + self.fill_group_of(hit.tri) + } + + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { + let material = self.fill_material()?; + let mesh = &self.mesh; + let triangle = mesh + .triangles_of(material) + .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + + self.fill_group_of(triangle as u32) + } + + /// 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.drag_polygon_fill_box(corner, opposite, viewport)?; + Ok(self.end_polygon_fill_box()) + } + + /// 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.drag_polygon_fill_box_uv(corner, opposite)?; + Ok(self.end_polygon_fill_box()) + } + + /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` + pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + let viewport = viewport.max(Vec2::ONE); + self.start_polygon_fill_drag(Some(viewport))?; + + let view_proj = self.camera.view_proj(viewport.x / viewport.y); + let mesh = self.mesh.clone(); + let to_screen = |vertex: usize| { + let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); + let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; + Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) + }; + let screen_corners = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) + }; + let selected = self.box_selection(&screen_corners, low, high); + self.show_box_fill(selected) + } + + /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) + pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + self.start_polygon_fill_drag(None)?; + + let mesh = self.mesh.clone(); + let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); + self.show_box_fill(selected) + } + + /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count + pub fn end_polygon_fill_box(&mut self) -> usize { + let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; + + // Quick mask edits keep no history, as with its strokes + let filled = drag.filled.len(); + if filled > 0 && drag.quick_mask_before.is_none() { + self.push_history("Polygon fill", drag.before); + } + filled + } + + /// The mesh material of the texture set being painted + fn fill_material(&self) -> Result { + Ok(self.doc.project.texture_set(self.ts())?.material) + } + + /// The triangles the current fill mode fills together, for `material` + fn fill_partition(&self, material: usize) -> TrianglePartition { + match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges), + FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges), + FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), + } + } + + /// Fill the fill-mode group holding `triangle` (one undo step) + fn fill_group_of(&mut self, triangle: u32) -> Result { + let ts = self.ts(); + let groups = self.fill_partition(self.fill_material()?); + let triangles: BTreeSet = groups.group(triangle).unwrap_or_default().iter().copied().collect(); + + let (gbuf, mut canvas) = self.fill_canvas(ts)?; + fill_triangles(&mut canvas, &gbuf, &triangles); + self.commit_fill("Polygon fill", ts, &canvas)?; + Ok(triangles.len()) + } + + /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + if self.polygon_fill_drag.is_some() { + return Ok(()); + } + + let material = self.fill_material()?; + let polygons = match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + _ => TrianglePartition::new(&self.mesh, material, polygon_edges), + }; + let depth = viewport + .filter(|_| self.tool.fill_visible_only) + .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); + self.polygon_fill_drag = Some(PolygonFillDrag { + before: self.doc.clone(), + quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), + filled: BTreeSet::new(), + depth, + polygons, + fill_groups: self.fill_partition(material), + failed: false, + }); + Ok(()) + } + + /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden + fn shown_mesh(&self) -> Cow<'_, Mesh> { + let sets = &self.doc.project.texture_sets; + if sets.iter().all(|set| set.visible) { + return Cow::Borrowed(&self.mesh); + } + + let mut mesh = (*self.mesh).clone(); + for set in sets.iter().filter(|set| !set.visible) { + for triangle in self.mesh.triangles_of(set.material) { + if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) { + let first = corners[0]; + corners.fill(first); + } + } + } + Cow::Owned(mesh) + } + + /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space + fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; + + let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let hit_test = self.tool.fill_hit_test; + let mut groups = BTreeSet::new(); + for polygon in &drag.polygons.groups { + let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); + let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); + if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); + } + } + + groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect() + } + + /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed + fn show_box_fill(&mut self, selected: BTreeSet) -> Result { + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + if drag.failed || drag.filled == selected { + return Ok(drag.filled.len()); + } + + drag.filled = selected.clone(); + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + } + + let ts = self.ts(); + let painted = if selected.is_empty() { + Ok(()) + } else { + self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| { + fill_triangles(&mut canvas, &gbuf, &selected); + self.paint_fill(ts, &canvas) + }) + }; + self.invalidate_changed(&previous); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + + // A failed fill is reported once; the rest of the drag fills nothing + if painted.is_err() + && let Some(mut drag) = self.polygon_fill_drag.take() + { + self.restore_before_box(&drag); + drag.failed = true; + drag.filled.clear(); + self.polygon_fill_drag = Some(drag); + } + painted.map(|_| selected.len()) + } + + /// Put back the document and quick mask from before the box `drag` + fn restore_before_box(&mut self, drag: &PolygonFillDrag) { + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + } + self.invalidate_changed(&previous); + } +} + +/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { + let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); + let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); + let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + + rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) + .copied() + .filter(|triangle| *triangle != NO_TRI) + .collect() +} + +/// The two corners spanning a box, lowest first +fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + Ok((corner.min(opposite), corner.max(opposite))) +} + +/// Texture coordinates of `triangle`'s corners +fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) +} + +/// Whether `point` lies in the triangle with `corners` (either winding) +fn contains(corners: [Vec2; 3], point: Vec2) -> bool { + let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); + let sides = [side(0), side(1), side(2)]; + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) +} + +/// The polygon diagonals of `triangle`: edges the importer added to split a polygon +fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { + let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); + let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() }; + + (0..3) + .filter(|edge| hidden >> edge & 1 == 1) + .map(|edge| { + let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]); + (from.min(to), from.max(to)) + }) + .collect() +} + +/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart +fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { + let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected +fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> { + let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64)); + let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() }; + let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +#[cfg(test)] +mod tests { + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::fill_hit_test::FillHitTest; + use crate::session::{FillMode, Session, Tool}; + + /// The roughness the test fills paint, to tell filled texels apart + const FILL_ROUGHNESS: f32 = 0.9; + + /// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`] + fn fill_session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.tool.tool = Tool::PolygonFill; + session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]); + session.update(); + session + } + + /// Whether the texel at texture coordinate `uv` shows the fill's roughness + fn filled_at(session: &Session, uv: Vec2) -> bool { + let (width, height) = session.caches[0].size; + let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32); + (roughness[0] - FILL_ROUGHNESS).abs() < 0.01 + } + + /// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh) + fn split_planes() -> (Mesh, usize) { + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for vertex in plane.indices.iter().map(|index| *index as usize) { + positions.push(plane.positions[vertex] + Vec3::Y * shift); + uvs.push(plane.uvs[vertex] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared"); + (mesh, plane.triangle_count()) + } + + #[test] + fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() { + let (mesh, per_plane) = split_planes(); + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + + for fill_mode in [FillMode::UvIsland, FillMode::Mesh] { + session.tool.fill_mode = fill_mode; + let groups = session.fill_partition(0); + assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane"); + assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane"); + } + } + + #[test] + fn polygon_mode_groups_the_two_triangles_of_each_quad() { + let mut session = fill_session(primitives::plane(2.0, 2)); + + session.tool.fill_mode = FillMode::Triangle; + assert_eq!(session.fill_partition(0).group(0), Some(&[0][..])); + + session.tool.fill_mode = FillMode::Polygon; + let mut quad = session.fill_partition(0).group(0).unwrap().to_vec(); + quad.sort_unstable(); + assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad"); + } + + #[test] + fn a_uv_box_over_half_a_plane_fills_that_half() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap(); + session.update(); + + assert_eq!(filled, 16, "the left two columns of quads"); + assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9))); + assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1))); + } + + #[test] + fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() { + let mut session = fill_session(primitives::plane(2.0, 2)); + session.tool.fill_mode = FillMode::Polygon; + let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2)); + + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside"); + assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step"); + + session.tool.fill_hit_test = FillHitTest::Intersection; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts"); + } + + #[test] + fn visible_only_skips_the_back_of_a_cube() { + let mut session = fill_session(primitives::cube(1.0)); + session.camera.yaw = 0.6; + session.camera.pitch = 0.4; + let (low, high) = (Vec2::ZERO, session.viewport); + let every_triangle = session.mesh.triangle_count(); + + session.tool.fill_visible_only = true; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees"); + + session.tool.fill_visible_only = false; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle); + } + + #[test] + fn visible_only_sees_through_a_hidden_texture_set() { + let mut session = fill_session(primitives::material_ball()); + let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap(); + session.active_set = base; + let (low, high) = (Vec2::ZERO, session.viewport); + + let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap(); + session.doc.project.texture_sets[0].visible = false; + let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap(); + + assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}"); + } + + #[test] + fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills"); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging"); + assert_eq!(session.history_labels().len(), history, "no undo step yet"); + + assert_eq!(session.end_polygon_fill_box(), 16); + assert_eq!(session.history_labels().len(), history + 1); + session.undo().unwrap(); + session.update(); + assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); + } + + #[test] + fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { + let mut session = fill_session(primitives::udim_plane()); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let every_triangle = session.mesh.triangle_count(); + assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); + } + + #[test] + fn a_2d_click_fills_the_triangle_under_it() { + let mut session = fill_session(primitives::plane(2.0, 1)); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + + assert!(filled_at(&session, Vec2::new(0.2, 0.7))); + assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays"); + assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs"); + } +} diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs new file mode 100644 index 00000000..4a7bc104 --- /dev/null +++ b/crates/engine/src/polygon_fill_drag.rs @@ -0,0 +1,28 @@ +//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move. + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_geom::glam::Vec2; +use texturecraft_paint::EyeDepth; +use texturecraft_texel::TileImage; + +use crate::session::Document; +use crate::triangle_partition::TrianglePartition; + +/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends +pub(crate) struct PolygonFillDrag { + /// The document before the drag, refilled each time the selection changes + pub before: Document, + /// The quick mask's coverage before the drag, when the drag paints the quick mask + pub quick_mask_before: Option>, + /// The triangles filled so far + pub filled: BTreeSet, + /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) + pub depth: Option<(EyeDepth, Vec2)>, + /// The polygons the box tests + pub polygons: TrianglePartition, + /// What the fill mode fills together + pub fill_groups: TrianglePartition, + /// The fill failed (reported once): the rest of the drag fills nothing + pub failed: bool, +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..c5b55649 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -165,6 +165,8 @@ impl ViewMode { pub enum FillMode { #[default] Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, UvIsland, Mesh, } @@ -210,6 +212,12 @@ pub struct ToolState { /// Gray painted into masks. pub mask_value: f32, pub fill_mode: FillMode, + /// How a polygon fill box decides which polygons it selects + #[serde(default)] + pub fill_hit_test: crate::fill_hit_test::FillHitTest, + /// Polygon fill boxes in the 3D view select only the polygons the camera sees + #[serde(default = "default_fill_visible_only")] + pub fill_visible_only: bool, /// Stencil used by the Projection tool. #[serde(default)] pub stencil: Option, @@ -231,6 +239,10 @@ fn default_smudge_strength() -> f32 { 0.5 } +fn default_fill_visible_only() -> bool { + true +} + /// What the Clone tool copies (the clone source modes). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum CloneFrom { @@ -260,6 +272,8 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), mask_value: 1.0, fill_mode: FillMode::Triangle, + fill_hit_test: Default::default(), + fill_visible_only: default_fill_visible_only(), stencil: None, smudge_strength: default_smudge_strength(), clone_source: None, @@ -356,6 +370,8 @@ pub struct Session { /// The last stroke's camera visibility buffer: reused while the camera, view size and mesh /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, + /// The polygon fill box being dragged + pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). pub export_presets: crate::preset_cmds::UserPresets, /// The user's project templates (kept when another project opens). @@ -405,6 +421,7 @@ impl Session { revision: 1, log: Vec::new(), depth_cache: None, + polygon_fill_drag: None, export_presets: Default::default(), templates: Default::default(), }) @@ -530,7 +547,7 @@ impl Session { /// 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::>(); diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..ba7f0f9b 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,6 +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::fill_hit_test::FillHitTest; use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; use crate::{Result, Session, cmd}; @@ -69,7 +70,16 @@ pub fn specs() -> Vec { always, clone_source ), - cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode), + cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode), + cmd!( + "tool.fillSelection", + "Polygon fill selection", + [], + None, + "{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}", + always, + fill_selection + ), cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke), cmd!( "tool.strokeUv", @@ -80,7 +90,15 @@ pub fn specs() -> Vec { always, stroke_uv ), - cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click), + cmd!( + "tool.click", + "Tool click", + [], + None, + "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + always, + click + ), cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))), ] } @@ -322,6 +340,7 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { fn fill_mode(s: &mut Session, p: &Value) -> Result { s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, + "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), @@ -329,6 +348,20 @@ fn fill_mode(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +fn fill_selection(s: &mut Session, p: &Value) -> Result { + match strp(p, "hitTest") { + None => {} + Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), + } + if let Some(visible_only) = boolp(p, "visibleOnly") { + s.tool.fill_visible_only = visible_only; + } + + Ok(Value::Null) +} + pub(crate) fn viewport_of(s: &Session, p: &Value) -> Vec2 { match p.get("viewport").and_then(Value::as_array) { Some(a) if a.len() == 2 => { @@ -370,21 +403,43 @@ fn stroke(s: &mut Session, p: &Value) -> Result { } fn click(s: &mut Session, p: &Value) -> Result { + if s.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(s, p)? + { + s.update(); + return Ok(json!({ "triangles": triangles })); + } + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; - let vp = viewport_of(s, p); + + let point = Vec2::new(x, y); + let viewport = viewport_of(s, p); let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }), + Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let v = s.color_pick(Vec2::new(x, y), vp)?; - json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>()) + let picked = s.color_pick(point, viewport)?; + json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?, - _ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, + _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), }; s.update(); Ok(out) } +/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point +fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { + let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); + let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, + (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, + _ => return Ok(None), + }; + + Ok(Some(filled)) +} + fn stroke_uv(s: &mut Session, p: &Value) -> Result { let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?; let tiles = s.stroke_uv_points(&points)?; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs new file mode 100644 index 00000000..1364fe69 --- /dev/null +++ b/crates/engine/src/triangle_partition.rs @@ -0,0 +1,77 @@ +//! Triangles of one material grouped into the pieces polygon fill selects and fills. + +use std::collections::{BTreeMap, HashMap}; + +use texturecraft_geom::Mesh; + +/// A material's triangles split into groups joined across shared edges +pub struct TrianglePartition { + /// The triangles of each group + pub groups: Vec>, + /// The index of each triangle's group + group_of: HashMap, +} + +impl TrianglePartition { + /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); + let mut by_edge: BTreeMap> = BTreeMap::new(); + for &triangle in &triangles { + for edge in edges(mesh, triangle as usize) { + by_edge.entry(edge).or_default().push(triangle); + } + } + + let mut groups = Vec::new(); + let mut group_of = HashMap::with_capacity(triangles.len()); + for &start in &triangles { + if group_of.contains_key(&start) { + continue; + } + let mut members = Vec::new(); + let mut stack = vec![start]; + group_of.insert(start, groups.len()); + while let Some(triangle) = stack.pop() { + members.push(triangle); + for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + if !group_of.contains_key(neighbour) { + group_of.insert(*neighbour, groups.len()); + stack.push(*neighbour); + } + } + } + groups.push(members); + } + TrianglePartition { groups, group_of } + } + + /// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material) + pub fn index_of(&self, triangle: u32) -> Option { + self.group_of.get(&triangle).copied() + } + + /// The group holding `triangle` (None for a triangle of another material) + pub fn group(&self, triangle: u32) -> Option<&[u32]> { + self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::primitives; + + use super::*; + + #[test] + fn triangles_sharing_a_key_join_one_group() { + let mesh = primitives::plane(2.0, 2); + let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]); + + assert_eq!(singles.groups.len(), mesh.triangle_count()); + assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2); + assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2)); + assert_eq!(pairs.group(99), None); + } +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..7973d52e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -105,6 +105,29 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn polygon_fill_boxes_survive_hostile_params() { + let hostile = [ + json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}), + json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}), + json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}), + json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}), + json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}), + ]; + for visible_only in [true, false] { + for hit_test in ["intersection", "containedCenter"] { + let mut session = session(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap(); + for params in &hostile { + let _ = execute(&mut session, "tool.click", params); + let _ = execute(&mut session, "tool.fillSelection", params); + session.update(); + } + } + } +} + /// Every command must return Ok or Err — never panic — for hostile params. #[test] fn panic_hunt() { diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index 01ce84f8..e914d297 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -3,10 +3,25 @@ use rayon::prelude::*; use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; -use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; +/// Largest buffer side in pixels. +const MAX_SIZE: u32 = 4096; + +/// Clip-space w below which a vertex counts as behind the camera. +const MIN_CLIP_W: f32 = 1e-5; + +/// Screen area (pixels squared) below which a triangle is skipped as degenerate. +const MIN_SCREEN_AREA: f32 = 1e-9; + +/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours. +const EDGE_TOLERANCE: f32 = 1e-4; + +/// [`EyeDepth::bias`] as a fraction of the scene radius. +const BIAS_PER_RADIUS: f32 = 0.004; + /// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty). #[derive(Clone, Debug)] pub struct EyeDepth { @@ -15,73 +30,99 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { - let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096)); - let aspect = w as f32 / h as f32; - let vp = camera.view_proj(aspect); + let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); + let view_proj = camera.view_proj(width as f32 / height as f32); let eye = camera.eye(); - // Project every vertex once. - let clip: Vec = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect(); - let screen: Vec> = - clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect(); - let dist_v: Vec = mesh.positions.iter().map(|p| p.distance(eye)).collect(); - let bands = (h as usize).div_ceil(BAND); - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in 0..mesh.triangle_count() { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0); - let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32); - if y1 <= y0 || !y0.is_finite() || !y1.is_finite() { + + // Project every vertex once + let screen: Vec> = mesh + .positions + .iter() + .map(|position| { + let clip: Vec4 = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) + }) + .collect(); + let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); + + // Bin each triangle into the bands of rows it covers + let mut bands: Vec> = vec![Vec::new(); (height as usize).div_ceil(BAND)]; + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; + + let top = first.1.min(second.1).min(third.1).floor().max(0.0); + let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } - let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let mut dist = vec![f32::MAX; (w * h) as usize]; - dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| { - let row0 = bi * BAND; - let nrows = rows.len() / w as usize; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]); - let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0); - if area.abs() < 1e-9 { + + let mut dist = vec![f32::MAX; (width * height) as usize]; + let mut triangle = vec![NO_TRI; (width * height) as usize]; + let band_len = BAND * width as usize; + dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let first_row = band * BAND; + let row_count = band_dist.len() / width as usize; + for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { + let Some(corners) = mesh.tri(candidate as usize) else { continue }; + let [first, second, third] = corners; + let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third)) + else { + continue; + }; + let corner_distance = corners.map(|vertex| vertex_distance[vertex]); + let area = + (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + if area.abs() < MIN_SCREEN_AREA { continue; } - let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize; - let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize; - let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize; - let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize; - for y in y0.max(row0)..y1 { - for x in x0..x1.min(w as usize) { - let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); - let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area; - let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 { + + let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; + let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; + let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; + let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + for row in top.max(first_row)..bottom { + for column in left..right.min(width as usize) { + let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); + let first_weight = + ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; + let second_weight = + ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + let third_weight = 1.0 - first_weight - second_weight; + if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; } - let d = w0 * da + w1 * db + w2 * dc; - if let Some(slot) = rows.get_mut((y - row0) * w as usize + x) - && d < *slot + + let distance = first_weight * corner_distance[0] + second_weight * corner_distance[1] + third_weight * corner_distance[2]; + let at = (row - first_row) * width as usize + column; + if let Some(slot) = band_dist.get_mut(at) + && distance < *slot { - *slot = d; + *slot = distance; + if let Some(nearest) = band_triangles.get_mut(at) { + *nearest = candidate; + } } } } } }); - EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 } + + EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS } } /// Whether world point `p` is visible (not hidden behind other geometry, inside the view). diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 87e9d84b..c42ee799 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -912,12 +912,14 @@ fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits. pub(crate) fn properties_title(app: &TextureCraftApp) -> String { - let p = &app.session.doc.project; - let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) { - (Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), - (Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(), - (Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(), + let project = &app.session.doc.project; + let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { + // Polygon fill keeps its own properties whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), + (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), _ => tr(app.session.tool.tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) @@ -927,12 +929,14 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } -/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); match (&selected, app.session.target) { + // Polygon fill shows its own settings and says what it fills into, whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => { @@ -1144,6 +1148,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Width of the label column in polygon fill's properties +const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; + +/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill) +fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::FillHitTest; + + let button_size = ui.spacing().interact_size.y; + ui.label(caption(&tr("Polygon fill").to_uppercase())); + property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| { + icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size); + }); + property_row( + ui, + tr("Fill mode"), + tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"), + |ui| crate::toolbar::fill_mode_buttons(app, ui), + ); + property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| { + for (hit_test, icon, tooltip) in [ + (FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")), + (FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() { + app.session.tool.fill_hit_test = hit_test; + } + } + }); + ui.horizontal(|ui| { + ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)"))); + }); + section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| { + let mut opacity = app.session.tool.brush.opacity * 100.0; + if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() { + app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0); + } + }); + ui.separator(); + + match polygon_fill_paints_mask(app) { + Ok(false) => { + ui.label(caption(&tr("Material").to_uppercase())); + material_controls(app, ui); + } + Ok(true) => { + ui.label(caption(&tr("Grayscale").to_uppercase())); + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; + } + } + Err(note) => { + ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim)); + } + } +} + +/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge +fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let label_width = ui.label(label).rect.width(); + ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0)); + controls(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info)); + }); +} + +/// A dim info icon explaining a setting on hover +fn info_icon(ui: &mut Ui, text: &str) { + ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); +} + +/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill +fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { + if app.session.quick_mask.editing { + return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string()); + } + + let project = &app.session.doc.project; + let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else { + return Err(tr("Select a paint layer or a layer's mask to fill").to_string()); + }; + + match app.session.target { + StackTarget::Mask => Ok(true), + StackTarget::Effect(_) => Ok(!targets_content(app)), + StackTarget::Content => { + let content = project.content_layer(layer.id).unwrap_or(layer); + if matches!(content.kind, LayerKind::Paint) { + Ok(false) + } else { + Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)])) + } + } + } +} + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); @@ -1365,59 +1467,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; +/// The tool's material under a "Material" heading fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + material_controls(app, ui); +} + +/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) +fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::core::ChannelKind; + + let tokens = Tokens::get(ui.ctx()); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); + for channel in &channels { + let on = app.session.tool.enabled.contains(channel); + if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo})); } } }); ui.add_space(4.0); - let mask_mode = !targets_content(app); - if mask_mode { - let mut v = app.session.tool.mask_value; - if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() { - app.session.tool.mask_value = v; + + if !targets_content(app) { + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; } return; } - for c in chans { - if !app.session.tool.enabled.contains(&c) { + + for channel in channels { + if !app.session.tool.enabled.contains(&channel) { continue; } - let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value()); - match c.kind() { - texturecraft_engine::core::ChannelKind::Color => { + let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()); + match channel.kind() { + ChannelKind::Color => { ui.horizontal(|ui| { - ui.label(tr(c.label())); - if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.session.tool.values.insert(c, v); + ui.label(tr(channel.label())); + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + app.session.tool.values.insert(channel, value); } }); } - texturecraft_engine::core::ChannelKind::NormalMap => { - ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim)); + ChannelKind::NormalMap => { + ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim)); } - texturecraft_engine::core::ChannelKind::Signed => { - if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Signed => { + if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } - texturecraft_engine::core::ChannelKind::Scalar => { - if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Scalar => { + if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } } } if app.session.tool.tool == Tool::Eraser { - ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim)); + ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0f2e023f..4c50e9ac 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه", + ), + ("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."), + ("Fill mode", "وضع التعبئة"), + ("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"), + ("Hit-test", "اختبار الإصابة"), + ("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"), + ("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"), + ("Rectangle fill", "تعبئة مستطيلة"), + ("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"), + ("Selection mode", "وضع التحديد"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV", + ), + ("Visible polygons only", "المضلعات المرئية فقط"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 77cf296b..63ec501e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,27 @@ 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}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Fill mode", "Füllmodus"), + ("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"), + ("Hit-test", "Treffertest"), + ("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"), + ("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"), + ("Rectangle fill", "Rechteckfüllung"), + ("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"), + ("Selection mode", "Auswahlmodus"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln", + ), + ("Visible polygons only", "Nur sichtbare Polygone"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4153783e..99fd2177 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,30 @@ 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}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Fill mode", "Modo de relleno"), + ("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"), + ("Hit-test", "Prueba de selección"), + ("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"), + ("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"), + ("Rectangle fill", "Relleno rectangular"), + ("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"), + ("Selection mode", "Modo de selección"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV", + ), + ("Visible polygons only", "Solo polígonos visibles"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0c07e5a4..4ef684a1 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,30 @@ 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}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Fill mode", "Mode de remplissage"), + ("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"), + ("Hit-test", "Test de sélection"), + ("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"), + ("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"), + ("Rectangle fill", "Remplissage rectangulaire"), + ("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"), + ("Selection mode", "Mode de sélection"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV", + ), + ("Visible polygons only", "Polygones visibles uniquement"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index b4bd33b3..44171f06 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,30 @@ 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}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Fill mode", "Modalità di riempimento"), + ("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"), + ("Hit-test", "Test di selezione"), + ("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"), + ("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"), + ("Rectangle fill", "Riempimento rettangolare"), + ("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"), + ("Selection mode", "Modalità di selezione"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV", + ), + ("Visible polygons only", "Solo poligoni visibili"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f764e268..9b4b7fe9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします", + ), + ("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Fill mode", "塗りつぶしモード"), + ("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"), + ("Hit-test", "ヒットテスト"), + ("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"), + ("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"), + ("Rectangle fill", "矩形塗りつぶし"), + ("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"), + ("Selection mode", "選択モード"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします", + ), + ("Visible polygons only", "表示されているポリゴンのみ"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a1c8d363..e11e5ccb 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,27 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다", + ), + ("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Fill mode", "채우기 모드"), + ("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"), + ("Hit-test", "히트 테스트"), + ("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"), + ("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"), + ("Rectangle fill", "사각형 채우기"), + ("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"), + ("Selection mode", "선택 모드"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다", + ), + ("Visible polygons only", "보이는 폴리곤만"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 880b62ff..307a93e6 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,30 @@ 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}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Fill mode", "Modo de preenchimento"), + ("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"), + ("Hit-test", "Teste de seleção"), + ("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"), + ("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"), + ("Rectangle fill", "Preenchimento retangular"), + ("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"), + ("Selection mode", "Modo de seleção"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV", + ), + ("Visible polygons only", "Apenas polígonos visíveis"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f894f1ad..d3d35296 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,21 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"), + ("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"), + ("Fill mode", "填充模式"), + ("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"), + ("Hit-test", "命中测试"), + ("How a rectangle selects polygons", "矩形选择多边形的方式"), + ("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"), + ("Rectangle fill", "矩形填充"), + ("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"), + ("Selection mode", "选择模式"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛", + ), + ("Visible polygons only", "仅可见多边形"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ]; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..889d2de7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -281,19 +281,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) path_controls(app, ui); } } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - - for (fill_mode, icon, tooltip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } + Tool::PolygonFill => fill_mode_buttons(app, ui), Tool::ColorPicker => { ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); } @@ -317,6 +305,23 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Polygon fill's fill modes (top bar and properties) +pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + use texturecraft_engine::FillMode; + + let button_size = ui.spacing().interact_size.y; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")), + (FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + (FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } +} + /// 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; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..91f816e9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -9,7 +9,7 @@ use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; -use texturecraft_engine::{Tool, ViewMode}; +use texturecraft_engine::{Session, Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; @@ -213,12 +213,14 @@ fn shade(app: &TextureCraftApp) -> Shade { }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + // Polygon fill shows the polygons it fills without changing the saved wireframe toggles + let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe, - wireframe_3d: app.ui.wireframe_3d, + wireframe: app.ui.uv_wireframe || polygon_fill, + wireframe_3d: app.ui.wireframe_3d || polygon_fill, ..Shade::from_project(&app.session.doc.project) } } @@ -575,8 +577,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill(local(point), viewport), + |session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -621,6 +632,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1003,6 +1015,52 @@ fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); } +/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image +fn polygon_fill_input( + app: &mut TextureCraftApp, + ui: &Ui, + response: &egui::Response, + fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result, + drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result, +) -> Option { + let origin_id = response.id.with("polygon_fill_box"); + let dragging = response.dragged_by(PointerButton::Primary); + let released = response.drag_stopped_by(PointerButton::Primary); + let held = ui.input(|input| input.pointer.primary_down()); + if !held && !released { + // A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step + if ui.data_mut(|data| data.remove_temp::(origin_id)).is_some() { + app.session.end_polygon_fill_box(); + } + } else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) { + ui.data_mut(|data| data.insert_temp(origin_id, press)); + } + + let origin = ui.data(|data| data.get_temp::(origin_id)); + let pointer = ui.input(|input| input.pointer.latest_pos()); + let (filled, dragged_box) = match (origin, pointer) { + _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), + (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), + _ => (None, None), + }; + if let Some(Err(error)) = filled { + app.toast(error.to_string(), true); + } + dragged_box +} + +/// How strongly the polygon fill box tints what it covers (0..1) +const FILL_BOX_TINT: f32 = 0.15; + +/// The polygon fill box being dragged, over view `rect` +fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { + let Some(fill_box) = fill_box else { return }; + + let accent = Tokens::get(ui.ctx()).viewport_accent; + ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); +} + /// V held with the Clone tool in painting mode: clicks set the clone source. fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { app.ui.mode == crate::state::Mode::Painting @@ -1213,8 +1271,17 @@ 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; + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill_uv(to_uv(point)), + |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -1254,6 +1321,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); // The UV tile outlines (numbered for UDIM sets) and the path being edited diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs new file mode 100644 index 00000000..dc007035 --- /dev/null +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -0,0 +1,85 @@ +//! Polygon fill in the views: a click fills one target and a box drag fills what the box selects, each as one undo step + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool +fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + harness +} + +/// Drag 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(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); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Press and release the primary button at `at` +fn click(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.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The undo steps recorded so far +fn history(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.history_labels() +} + +#[test] +fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { + let mut clicked = polygon_fill_app(); + let center = clicked.state().viewport_rect.center(); + let before = history(&clicked).len(); + click(&mut clicked, center); + assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle"); + + let mut boxed = polygon_fill_app(); + drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0)); + assert_eq!(history(&boxed).len(), before + 1); + assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill")); + assert!( + painted_tiles(&boxed) > painted_tiles(&clicked), + "the box fills every triangle in it: {} tiles vs {}", + painted_tiles(&boxed), + painted_tiles(&clicked) + ); +} + +#[test] +fn a_box_drag_in_the_2d_view_is_one_fill() { + let mut harness = polygon_fill_app(); + let view_3d = harness.state().viewport_rect; + let center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let before = history(&harness).len(); + + drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + assert_eq!(history(&harness).len(), before + 1); + assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); +} From 49bd4a1273fdf58bb8e4954addeaa0bf7c7c8b6a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:52:40 +0000 Subject: [PATCH 10/76] Polygon fill: review fixes - A box drag always finishes: on release (even after a failed move), before any edit, undo, redo or tool change, and when a scripted box fails or starts while another drag is open. A camera move mid-drag (wheel zoom) keeps the drag and selects again from the new camera. - A drag projects the mesh once, skips repaints whose box hasn't moved, and builds each grouping once; triangle edges are computed once. - 2D clicks read the triangle from the set's UV G-buffer at the clicked texel, so collapsed UV faces can't take the click. - Brush strokes no longer record the nearest-triangle buffer; only polygon fill asks for it (EyeDepth::render_with_triangles). Screen projection is shared through paint::screen_point. - A box touching the view's edge or zero-size on whole pixels selects exactly the pixels it covers. - Click fills never merge into a box drag's undo step; FillMode moves to its own file; partial box parameters get their own error. --- crates/engine/src/fill_hit_test.rs | 33 ++- crates/engine/src/fill_mode.rs | 17 ++ crates/engine/src/lib.rs | 4 +- crates/engine/src/painting.rs | 3 +- crates/engine/src/polygon_fill.rs | 367 ++++++++++++++++-------- crates/engine/src/polygon_fill_drag.rs | 23 +- crates/engine/src/session.rs | 56 ++-- crates/engine/src/tool_cmds.rs | 72 ++--- crates/engine/src/triangle_partition.rs | 20 +- crates/paint/src/lib.rs | 2 +- crates/paint/src/visibility.rs | 72 +++-- crates/ui-egui/src/viewport.rs | 13 +- crates/ui-egui/tests/polygon_fill.rs | 3 +- 13 files changed, 439 insertions(+), 246 deletions(-) create mode 100644 crates/engine/src/fill_mode.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs index 8a2b9359..b30b2452 100644 --- a/crates/engine/src/fill_hit_test.rs +++ b/crates/engine/src/fill_hit_test.rs @@ -25,17 +25,17 @@ impl FillHitTest { /// Area-weighted center of the triangles (their corners' mean when they have no area) fn center(triangles: &[[Vec2; 3]]) -> Option { - let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); - let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; - let total: f32 = triangles.iter().map(area).sum(); - let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); - let centroids: Vec2 = triangles.iter().map(centroid).sum(); - - match triangles.len() { - 0 => None, - count if total <= f32::EPSILON => Some(centroids / count as f32), - _ => Some(weighted / total), + if triangles.is_empty() { + return None; } + + // One pass: total area, area-weighted centroids and plain centroids + let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| { + let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = (corners[0] + corners[1] + corners[2]) / 3.0; + (total_area + area, weighted + centroid * area, centroids + centroid) + }); + Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 }) } /// Separating axis test of a triangle against an axis-aligned box @@ -63,11 +63,14 @@ mod tests { const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; #[test] - fn intersection_needs_any_overlap_and_contained_center_the_center() { - let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); - assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); - assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); - assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + fn intersection_selects_any_overlap() { + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge"); + } + + #[test] + fn contained_center_selects_only_by_the_center() { + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside"); assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); } diff --git a/crates/engine/src/fill_mode.rs b/crates/engine/src/fill_mode.rs new file mode 100644 index 00000000..f314562e --- /dev/null +++ b/crates/engine/src/fill_mode.rs @@ -0,0 +1,17 @@ +//! What one polygon fill target grows to. + +use serde::{Deserialize, Serialize}; + +/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillMode { + /// The triangle itself + #[default] + Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, + /// The UV island: triangles sharing edges in UV space + UvIsland, + /// The connected geometry: triangles sharing edges by position + Mesh, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 824ccf48..6c6c9964 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; pub mod fill_hit_test; +pub mod fill_mode; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -55,9 +56,10 @@ pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; +pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; -pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; +pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; pub use texturecraft_compose as compose; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 86761f79..afc67a28 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -502,7 +502,8 @@ impl Session { return self.paint_fill(ts, canvas); } - self.edit(label, |session| session.paint_fill(ts, canvas)) + // Each fill is its own step, never merged into a box drag's step of the same label + self.edit_merging(label, false, |session| session.paint_fill(ts, canvas)) } /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 2d577835..a235e483 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -3,21 +3,19 @@ use std::borrow::Cow; use std::collections::{BTreeSet, HashSet}; -use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Mesh, NO_TRI}; -use texturecraft_paint::{EyeDepth, fill_triangles}; +use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; +use crate::fill_mode::FillMode; use crate::polygon_fill_drag::PolygonFillDrag; -use crate::session::{FillMode, Session}; +use crate::session::Session; use crate::triangle_partition::TrianglePartition; use crate::{EngineError, Result}; /// Corners closer than one step of this grid (per unit of position or UV) count as the same corner const CORNER_GRID_STEPS: f32 = 1e5; -/// Clip-space w below which a vertex counts as behind the camera -const MIN_CLIP_W: f32 = 1e-5; - impl Session { /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { @@ -29,73 +27,131 @@ impl Session { self.fill_group_of(hit.tri) } - /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { - let material = self.fill_material()?; - let mesh = &self.mesh; - let triangle = mesh - .triangles_of(material) - .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let size = Vec2::new(gbuf.width as f32, gbuf.height as f32); + let texel = (uv * size).floor(); + let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all()) + .then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied()) + .flatten() + .filter(|triangle| *triangle != NO_TRI) .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - self.fill_group_of(triangle as u32) + self.fill_group_of(triangle) } /// 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.drag_polygon_fill_box(corner, opposite, viewport)?; - Ok(self.end_polygon_fill_box()) + // 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); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// 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.drag_polygon_fill_box_uv(corner, opposite)?; - Ok(self.end_polygon_fill_box()) + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box_uv(corner, opposite); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - let viewport = viewport.max(Vec2::ONE); - self.start_polygon_fill_drag(Some(viewport))?; - - let view_proj = self.camera.view_proj(viewport.x / viewport.y); - let mesh = self.mesh.clone(); - let to_screen = |vertex: usize| { - let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); - let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; - Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) - }; - let screen_corners = |triangle: usize| { - let [first, second, third] = mesh.tri(triangle)?; - Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) - }; - let selected = self.box_selection(&screen_corners, low, high); - self.show_box_fill(selected) + // Whole pixels, as the visibility buffer is rendered at + self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE))) } /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - self.start_polygon_fill_drag(None)?; - - let mesh = self.mesh.clone(); - let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); - self.show_box_fill(selected) + self.drag_polygon_fill(corner, opposite, None) } /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count pub fn end_polygon_fill_box(&mut self) -> usize { let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; - // Quick mask edits keep no history, as with its strokes let filled = drag.filled.len(); + // Quick mask edits keep no history, as with its strokes if filled > 0 && drag.quick_mask_before.is_none() { self.push_history("Polygon fill", drag.before); } filled } + /// 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 { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + let (low, high) = (corner.min(opposite), corner.max(opposite)); + self.start_polygon_fill_drag(viewport)?; + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + + if drag.failed || drag.last_box == Some((low, high)) { + return Ok(drag.filled.len()); + } + + drag.last_box = Some((low, high)); + let selected = self.box_selection(low, high); + self.show_box_fill(selected) + } + + /// Begin a box drag unless one is under way in the same view, texture set and quick mask state; a drag from another one ends first + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + let ts = self.ts(); + let quick_mask = self.quick_mask.editing; + // A different view size, set or quick mask state starts a new drag; the old one keeps its fill as one step + if let Some(drag) = &self.polygon_fill_drag { + if drag.ts == ts && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask { + // A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera + if drag.camera != self.camera { + let (points, depth) = self.box_space(viewport); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + (drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None); + } + } + return Ok(()); + } + self.end_polygon_fill_box(); + } + + let material = self.fill_material()?; + let (points, depth) = self.box_space(viewport); + let polygons = match self.tool.fill_mode { + FillMode::Triangle | FillMode::Polygon => None, + FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)), + }; + self.polygon_fill_drag = Some(PolygonFillDrag { + ts, + viewport, + camera: self.camera, + before: self.doc.clone(), + quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()), + points, + depth, + fill_groups: self.fill_partition(material), + polygons, + filled: BTreeSet::new(), + last_box: None, + failed: false, + }); + Ok(()) + } + + /// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees + fn box_space(&self, viewport: Option) -> (Vec>, Option) { + let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) }; + + let view_proj = self.camera.view_proj(size.x / size.y); + let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); + let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32)); + (points, depth) + } + /// The mesh material of the texture set being painted fn fill_material(&self) -> Result { Ok(self.doc.project.texture_set(self.ts())?.material) @@ -123,32 +179,6 @@ impl Session { Ok(triangles.len()) } - /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) - fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { - if self.polygon_fill_drag.is_some() { - return Ok(()); - } - - let material = self.fill_material()?; - let polygons = match self.tool.fill_mode { - FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), - _ => TrianglePartition::new(&self.mesh, material, polygon_edges), - }; - let depth = viewport - .filter(|_| self.tool.fill_visible_only) - .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); - self.polygon_fill_drag = Some(PolygonFillDrag { - before: self.doc.clone(), - quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), - filled: BTreeSet::new(), - depth, - polygons, - fill_groups: self.fill_partition(material), - failed: false, - }); - Ok(()) - } - /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden fn shown_mesh(&self) -> Cow<'_, Mesh> { let sets = &self.doc.project.texture_sets; @@ -168,17 +198,28 @@ impl Session { Cow::Owned(mesh) } - /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space - fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + /// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode + fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet { let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; - let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high)); + let point = |vertex: usize| drag.points.get(vertex).copied().flatten(); + let corners = |triangle: u32| { + let [first, second, third] = self.mesh.tri(triangle as usize)?; + Some([point(first)?, point(second)?, point(third)?]) + }; let hit_test = self.tool.fill_hit_test; + let mut polygon_corners = Vec::new(); let mut groups = BTreeSet::new(); - for polygon in &drag.polygons.groups { + for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups { let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); - let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); - if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + if !seen { + continue; + } + + polygon_corners.clear(); + polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle))); + if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) { groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); } } @@ -189,17 +230,17 @@ impl Session { /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed fn show_box_fill(&mut self, selected: BTreeSet) -> Result { let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; - if drag.failed || drag.filled == selected { - return Ok(drag.filled.len()); + if drag.filled == selected { + return Ok(selected.len()); } - drag.filled = selected.clone(); + let ts = drag.ts; let previous = std::mem::replace(&mut self.doc, drag.before.clone()); if let Some(masks) = &drag.quick_mask_before { self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); } - let ts = self.ts(); let painted = if selected.is_empty() { Ok(()) } else { @@ -209,37 +250,23 @@ impl Session { }) }; self.invalidate_changed(&previous); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - // A failed fill is reported once; the rest of the drag fills nothing - if painted.is_err() - && let Some(mut drag) = self.polygon_fill_drag.take() - { - self.restore_before_box(&drag); - drag.failed = true; - drag.filled.clear(); - self.polygon_fill_drag = Some(drag); + // A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing + let selected_count = selected.len(); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + drag.failed = painted.is_err(); + drag.filled = if drag.failed { BTreeSet::new() } else { selected }; } - painted.map(|_| selected.len()) - } - - /// Put back the document and quick mask from before the box `drag` - fn restore_before_box(&mut self, drag: &PolygonFillDrag) { - let previous = std::mem::replace(&mut self.doc, drag.before.clone()); - if let Some(masks) = &drag.quick_mask_before { - self.quick_mask.masks = masks.clone(); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - } - self.invalidate_changed(&previous); + painted.map(|_| selected_count) } } -/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { - let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; - let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); - let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); - let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel); + let columns = pixel_span(low.x, high.x, depth.width); + let rows = pixel_span(low.y, high.y, depth.height); rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) .copied() @@ -247,13 +274,11 @@ fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> .collect() } -/// The two corners spanning a box, lowest first -fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { - if !corner.is_finite() || !opposite.is_finite() { - return Err(EngineError::Other("the box corners must be finite".into())); - } - - Ok((corner.min(opposite), corner.max(opposite))) +/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside) +fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { + let first = low.floor().clamp(0.0, count as f32) as usize; + let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize; + first..end.max(first) } /// Texture coordinates of `triangle`'s corners @@ -262,13 +287,6 @@ fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) } -/// Whether `point` lies in the triangle with `corners` (either winding) -fn contains(corners: [Vec2; 3], point: Vec2) -> bool { - let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); - let sides = [side(0), side(1), side(2)]; - sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) -} - /// The polygon diagonals of `triangle`: edges the importer added to split a polygon fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); @@ -308,7 +326,8 @@ mod tests { use texturecraft_geom::primitives; use crate::fill_hit_test::FillHitTest; - use crate::session::{FillMode, Session, Tool}; + use crate::fill_mode::FillMode; + use crate::session::{Session, Tool}; /// The roughness the test fills paint, to tell filled texels apart const FILL_ROUGHNESS: f32 = 0.9; @@ -446,6 +465,44 @@ mod tests { assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); } + #[test] + fn a_failed_box_fill_leaves_no_drag_behind() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let layer = session.selected.remove(&0).unwrap(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on"); + + session.selected.insert(0, layer); + assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again"); + } + + #[test] + fn undo_and_tool_changes_finish_a_box_drag_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished"); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step"); + } + + #[test] + fn an_unmoved_box_keeps_its_fill() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let narrow_box = Vec2::new(0.3, 1.0); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches"); + + // Contained center would select one column, so a second selection would show 8 + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again"); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again"); + } + #[test] fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { let mut session = fill_session(primitives::udim_plane()); @@ -456,6 +513,82 @@ mod tests { assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); } + #[test] + fn a_2d_click_skips_a_triangle_with_collapsed_uvs() { + // A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them + let plane = primitives::plane(2.0, 1); + let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z]; + let mut uvs = vec![Vec2::ZERO; 3]; + positions.extend(&plane.positions); + uvs.extend(&plane.uvs); + let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect(); + let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one"); + } + + #[test] + fn a_failing_drag_reports_once_and_records_nothing() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + session.selected.clear(); + + assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err()); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing"); + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(session.history_labels().len(), history); + } + + #[test] + fn an_edit_during_a_drag_records_the_fill_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + + let layers = session.doc.project.layers.len(); + crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + let labels = session.history_labels(); + assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}"); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(); + assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer"); + } + + #[test] + fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() { + let mut session = fill_session(primitives::cube(1.0)); + let center = (session.viewport * 0.5).floor(); + + assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0); + } + + #[test] + fn a_camera_move_mid_drag_keeps_one_drag() { + let mut session = fill_session(primitives::cube(1.0)); + let viewport = session.viewport; + let history = session.history_labels().len(); + + let (corner, opposite) = (viewport * 0.4, viewport * 0.6); + + let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.camera.zoom(0.5); + let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.end_polygon_fill_box(); + + assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera"); + assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it"); + } + + #[test] + fn pixel_spans_include_both_edges_and_nothing_outside() { + assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel"); + assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel"); + assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel"); + assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100); + } + #[test] fn a_2d_click_fills_the_triangle_under_it() { let mut session = fill_session(primitives::plane(2.0, 1)); diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs index 4a7bc104..f4457e55 100644 --- a/crates/engine/src/polygon_fill_drag.rs +++ b/crates/engine/src/polygon_fill_drag.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::Vec2; use texturecraft_paint::EyeDepth; use texturecraft_texel::TileImage; @@ -11,18 +12,28 @@ use crate::triangle_partition::TrianglePartition; /// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends pub(crate) struct PolygonFillDrag { + /// The texture set it fills + pub ts: usize, + /// The 3D view's size in pixels, or None for a drag in the 2D view + pub viewport: Option, + /// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with + pub camera: OrbitCamera, /// The document before the drag, refilled each time the selection changes pub before: Document, /// The quick mask's coverage before the drag, when the drag paints the quick mask pub quick_mask_before: Option>, - /// The triangles filled so far - pub filled: BTreeSet, - /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) - pub depth: Option<(EyeDepth, Vec2)>, - /// The polygons the box tests - pub polygons: TrianglePartition, + /// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view + pub points: Vec>, + /// What the camera sees (3D view, visible polygons only) + pub depth: Option, /// What the fill mode fills together pub fill_groups: TrianglePartition, + /// The polygons the box tests, when they differ from the fill groups + pub polygons: Option, + /// The triangles filled so far + pub filled: BTreeSet, + /// The box last shown, lowest corner first: an unmoved box isn't selected again + pub last_box: Option<(Vec2, Vec2)>, /// The fill failed (reported once): the rest of the drag fills nothing pub failed: bool, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index c5b55649..c6b7c469 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; use texturecraft_texel::DilationMap; +use crate::fill_mode::FillMode; use crate::{EngineError, Result}; /// Padding (texels) applied to composites for display. @@ -160,17 +161,6 @@ impl ViewMode { } } -/// Polygon fill granularity. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum FillMode { - #[default] - Triangle, - /// The source polygon (quad or n-gon) the importer split into triangles - Polygon, - UvIsland, - Mesh, -} - /// A screen-pinned image for the Projection tool (a stencil). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { @@ -506,22 +496,24 @@ impl Session { self.edit_merging(label, self.merge_edits, f) } - /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the - /// same label (a drag in the viewport is one step however many updates it makes). - pub fn edit_merging(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result) -> Result { + /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes). + pub fn edit_merging(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result) -> Result { + // A box fill under way becomes its own step first, so this edit isn't written over or folded into it + self.end_polygon_fill_box(); + let before = self.doc.clone(); - let result = f(self).and_then(|v| match self.doc.project.instance_cycle() { + let result = change(self).and_then(|value| match self.doc.project.instance_cycle() { Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), - None => Ok(v), + None => Ok(value), }); match result { - Ok(v) => { + Ok(value) => { self.record(label, before, merge); - Ok(v) + Ok(value) } - Err(e) => { + Err(error) => { self.doc = before; - Err(e) + Err(error) } } } @@ -642,25 +634,29 @@ impl Session { } 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(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); 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); - self.after_history(&now); - self.redo.push((label.clone(), now)); + + let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) } 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(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); 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); - self.after_history(&now); - self.undo.push((label.clone(), now)); + + let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index ba7f0f9b..a3f92bba 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -8,7 +8,8 @@ use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; use crate::fill_hit_test::FillHitTest; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::fill_mode::FillMode; +use crate::session::{CloneFrom, CloneSource, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -103,11 +104,13 @@ pub fn specs() -> Vec { ] } -pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result { - s.cancel_stroke(); - s.tool.tool = t; - s.revision = s.revision.wrapping_add(1); - Ok(json!({ "tool": t.id() })) +pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result { + session.cancel_stroke(); + // A box fill under way keeps what it filled as one undo step + session.end_polygon_fill_box(); + session.tool.tool = tool; + session.revision = session.revision.wrapping_add(1); + Ok(json!({ "tool": tool.id() })) } fn select(s: &mut Session, p: &Value) -> Result { @@ -337,26 +340,27 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null)) } -fn fill_mode(s: &mut Session, p: &Value) -> Result { - s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { +fn fill_mode(session: &mut Session, params: &Value) -> Result { + session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), }; + Ok(Value::Null) } -fn fill_selection(s: &mut Session, p: &Value) -> Result { - match strp(p, "hitTest") { +fn fill_selection(session: &mut Session, params: &Value) -> Result { + match strp(params, "hitTest") { None => {} - Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, - Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter, Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), } - if let Some(visible_only) = boolp(p, "visibleOnly") { - s.tool.fill_visible_only = visible_only; + if let Some(visible_only) = boolp(params, "visibleOnly") { + session.tool.fill_visible_only = visible_only; } Ok(Value::Null) @@ -402,38 +406,42 @@ fn stroke(s: &mut Session, p: &Value) -> Result { Ok(json!({ "stamps": stamps })) } -fn click(s: &mut Session, p: &Value) -> Result { - if s.tool.tool == Tool::PolygonFill - && let Some(triangles) = polygon_fill_click(s, p)? +fn click(session: &mut Session, params: &Value) -> Result { + if session.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(session, params)? { - s.update(); + session.update(); return Ok(json!({ "triangles": triangles })); } - let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; let point = Vec2::new(x, y); - let viewport = viewport_of(s, p); - let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), + let viewport = viewport_of(session, params); + let out = match session.tool.tool { + Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let picked = s.color_pick(point, viewport)?; + let picked = session.color_pick(point, viewport)?; json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, - _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?, + _ => json!({ "stamps": session.stroke_points(&[point], viewport)? }), }; - s.update(); + session.update(); Ok(out) } /// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point -fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { - let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); - let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { - (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, - (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, - (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, +fn polygon_fill_click(session: &mut Session, params: &Value) -> Result> { + let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1")); + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?, + _ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")), + (_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?, + _ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")), + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?, + _ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")), _ => return Ok(None), }; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs index 1364fe69..bd137e35 100644 --- a/crates/engine/src/triangle_partition.rs +++ b/crates/engine/src/triangle_partition.rs @@ -1,6 +1,7 @@ //! Triangles of one material grouped into the pieces polygon fill selects and fills. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; +use std::hash::Hash; use texturecraft_geom::Mesh; @@ -14,12 +15,15 @@ pub struct TrianglePartition { impl TrianglePartition { /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both - pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + // Each triangle's edges once, in mesh order so the groups come out the same every time let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); - let mut by_edge: BTreeMap> = BTreeMap::new(); - for &triangle in &triangles { - for edge in edges(mesh, triangle as usize) { - by_edge.entry(edge).or_default().push(triangle); + let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); + let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); + let mut by_edge: HashMap> = HashMap::new(); + for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { + for edge in triangle_edges { + by_edge.entry(edge.clone()).or_default().push(*triangle); } } @@ -29,12 +33,14 @@ impl TrianglePartition { if group_of.contains_key(&start) { continue; } + let mut members = Vec::new(); let mut stack = vec![start]; group_of.insert(start, groups.len()); while let Some(triangle) = stack.pop() { members.push(triangle); - for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { if !group_of.contains_key(neighbour) { group_of.insert(*neighbour, groups.len()); stack.push(*neighbour); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..307ccd7f 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -29,4 +29,4 @@ 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 stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; -pub use visibility::EyeDepth; +pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index e914d297..c2921979 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -2,7 +2,7 @@ //! rendered once at the start of a stroke. use rayon::prelude::*; -use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; +use texturecraft_geom::glam::{Mat4, Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; @@ -11,7 +11,7 @@ const BAND: usize = 16; const MAX_SIZE: u32 = 4096; /// Clip-space w below which a vertex counts as behind the camera. -const MIN_CLIP_W: f32 = 1e-5; +pub const MIN_CLIP_W: f32 = 1e-5; /// Screen area (pixels squared) below which a triangle is skipped as degenerate. const MIN_SCREEN_AREA: f32 = 1e-9; @@ -30,28 +30,38 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, - /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`]. pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } +/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera. +pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option { + let clip = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size) +} + impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`]. pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, false) + } + + /// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`]. + pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, true) + } + + /// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set. + fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth { let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); - let view_proj = camera.view_proj(width as f32 / height as f32); + let size = Vec2::new(width as f32, height as f32); + let view_proj = camera.view_proj(size.x / size.y); let eye = camera.eye(); // Project every vertex once - let screen: Vec> = mesh - .positions - .iter() - .map(|position| { - let clip: Vec4 = view_proj * position.extend(1.0); - (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) - }) - .collect(); + let screen: Vec> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); // Bin each triangle into the bands of rows it covers @@ -60,8 +70,8 @@ impl EyeDepth { let Some([first, second, third]) = mesh.tri(triangle) else { continue }; let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; - let top = first.1.min(second.1).min(third.1).floor().max(0.0); - let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + let top = first.y.min(second.y).min(third.y).floor().max(0.0); + let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y); if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } @@ -72,9 +82,11 @@ impl EyeDepth { } let mut dist = vec![f32::MAX; (width * height) as usize]; - let mut triangle = vec![NO_TRI; (width * height) as usize]; + let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() }; let band_len = BAND * width as usize; - dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let mut triangle_bands: Vec> = triangle.chunks_mut(band_len).map(Some).collect(); + triangle_bands.resize_with(dist.len().div_ceil(band_len), || None); + dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| { let first_row = band * BAND; let row_count = band_dist.len() / width as usize; for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { @@ -84,24 +96,22 @@ impl EyeDepth { else { continue; }; - let corner_distance = corners.map(|vertex| vertex_distance[vertex]); - let area = - (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + + let corner_distance = corners.map(|vertex| vertex_distance.get(vertex).copied().unwrap_or(f32::MAX)); + let area = (*second_point - *first_point).perp_dot(*third_point - *first_point); if area.abs() < MIN_SCREEN_AREA { continue; } - let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; - let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; - let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; - let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + let low = first_point.min(*second_point).min(*third_point).floor(); + let high = first_point.max(*second_point).max(*third_point).ceil(); + let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize)); + let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize); for row in top.max(first_row)..bottom { - for column in left..right.min(width as usize) { - let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); - let first_weight = - ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; - let second_weight = - ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + for column in left..right { + let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5); + let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area; + let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area; let third_weight = 1.0 - first_weight - second_weight; if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; @@ -113,7 +123,7 @@ impl EyeDepth { && distance < *slot { *slot = distance; - if let Some(nearest) = band_triangles.get_mut(at) { + if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) { *nearest = candidate; } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 91f816e9..491aed10 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -214,13 +214,13 @@ fn shade(app: &TextureCraftApp) -> Shade { let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles - let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; + let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe || polygon_fill, - wireframe_3d: app.ui.wireframe_3d || polygon_fill, + wireframe: app.ui.uv_wireframe || polygon_fill_tool, + wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool, ..Shade::from_project(&app.session.doc.project) } } @@ -1040,7 +1040,12 @@ fn polygon_fill_input( let pointer = ui.input(|input| input.pointer.latest_pos()); let (filled, dragged_box) = match (origin, pointer) { _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), - (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) if released => { + // The drag ends on release even when its last move failed + let shown = drag_box(&mut app.session, origin, pointer); + let filled = app.session.end_polygon_fill_box(); + (Some(shown.map(|_| filled)), None) + } (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), _ => (None, None), }; diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs index dc007035..313ad184 100644 --- a/crates/ui-egui/tests/polygon_fill.rs +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -27,8 +27,9 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { harness.run_steps(1); } + // Only the release frame runs, so the release itself must finish the drag harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(3); + harness.run_steps(1); } /// Press and release the primary button at `at` From 695a3eed910226ef6e815df4a47c8de5e6de2667 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:27 +0000 Subject: [PATCH 11/76] Shift+click paints straight lines in the 2D view The 2D view keeps the end of the last finished stroke in texture coordinates, with its texture set, so a line drawn after zooming or panning joins the same texels, and previews the line while Shift is held, as the 3D view does. A cancelled stroke (Escape) leaves the line start where it was. Session::continue_stroke_uv stamps a long segment in batches of 4096 up to 1 << 17 stamps instead of stopping at 4096, keeps its carry within one step, and seeds stamps from the stroke's running count (UvStrokeState) so noise alphas don't repeat every pointer sample. The line preview is clipped to the view, keeping its dash phase. Refs #306 --- crates/engine/src/lib.rs | 1 + crates/engine/src/painting.rs | 83 +++++++----- crates/engine/src/session.rs | 4 +- crates/engine/src/uv_stroke_state.rs | 14 ++ crates/engine/tests/uv_strokes.rs | 77 +++++++++++ crates/ui-egui/src/lib.rs | 25 +++- crates/ui-egui/src/viewport.rs | 171 ++++++++++++++++++----- crates/ui-egui/tests/shift_lines_2d.rs | 180 +++++++++++++++++++++++++ 8 files changed, 482 insertions(+), 73 deletions(-) create mode 100644 crates/engine/src/uv_stroke_state.rs create mode 100644 crates/engine/tests/uv_strokes.rs create mode 100644 crates/ui-egui/tests/shift_lines_2d.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..a6c444e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..c9c19085 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -12,8 +12,18 @@ use texturecraft_paint::{ }; use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::uv_stroke_state::UvStrokeState; use crate::{EngineError, Result}; +/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. +const MIN_UV_STAMP_STEP: f32 = 1e-5; + +/// 2D view stamps rasterized together, bounding the memory of one batch. +const UV_STAMP_BATCH: usize = 4096; + +/// Most stamps one 2D view sample adds: a line across the texture at the finest brush (about 71k) fits, a hostile coordinate stays bounded. +const MAX_UV_STAMPS_PER_SAMPLE: usize = 1 << 17; + impl Session { /// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change). fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc { @@ -234,7 +244,7 @@ impl Session { stroke, canvas, depth, - uv: uv_mode.then_some((None, 0.0)), + uv: uv_mode.then(UvStrokeState::default), camera: self.camera, viewport, values, @@ -314,40 +324,45 @@ impl Session { /// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square. pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) { - let Some(st) = self.stroke.as_mut() else { return }; - let Some((last, carry)) = st.uv.as_mut() else { return }; - let Some(cache) = self.caches.get_mut(st.ts) else { return }; - let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; - let step = (b.spacing * 2.0 * radius).max(1e-5); - let mut points = Vec::new(); - match *last { - None => points.push(uv), - Some(prev) => { - let seg = uv - prev; - let len = seg.length(); - let mut t = step - *carry; - while t <= len && points.len() < 4096 { - points.push(prev + seg * (t / len.max(1e-9))); - t += step; - } - *carry = len - (t - step); - } - } - // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down). - let angle = match *last { - Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0, - _ => b.angle, + let Some(active) = self.stroke.as_mut() else { return }; + let Some(progress) = active.uv.as_mut() else { return }; + let Some(cache) = self.caches.get_mut(active.ts) else { return }; + let settings = &active.stroke.settings; + let pressure = pressure.clamp(0.0, 1.0); + let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; + let radius = settings.size * 2.0 * size_scale; + let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); + + // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) + let angle = match progress.last { + Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0, + _ => settings.angle, }; - *last = Some(uv); - let n0 = st.stroke.stamps.len() as u32; - let stamps: Vec = points - .iter() - .enumerate() - .map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 }) - .collect(); - texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps); + + // The first sample is one stamp; a later one stamps every `step` along the segment from the previous + let (start, segment, mut distance) = match progress.last.replace(uv) { + None => (uv, Vec2::ZERO, 0.0), + Some(previous) => (previous, uv - previous, step - progress.carry), + }; + let length = segment.length(); + let shape = Self::shape(&self.images, settings); + let mut stamped = 0; + while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { + let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped); + let mut batch = Vec::new(); + while distance <= length && batch.len() < batch_size { + let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); + let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + distance += step; + } + stamped += batch.len(); + texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); + } + + // At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards + progress.carry = (length - (distance - step)).min(step); + progress.stamps = progress.stamps.wrapping_add(stamped as u32); self.stroke_painted(); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..137affdc 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -291,8 +291,8 @@ pub(crate) struct ActiveStroke { pub canvas: StrokeCanvas, /// Camera visibility for 3D strokes (None for strokes in the 2D view). pub depth: Option>, - /// 2D view strokes: last UV point and the distance carried to the next stamp. - pub uv: Option<(Option, f32)>, + /// 2D view strokes: where the stroke is between samples. + pub uv: Option, pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, diff --git a/crates/engine/src/uv_stroke_state.rs b/crates/engine/src/uv_stroke_state.rs new file mode 100644 index 00000000..5ce5ae2f --- /dev/null +++ b/crates/engine/src/uv_stroke_state.rs @@ -0,0 +1,14 @@ +//! Where a stroke in the 2D view is between pointer samples. + +use texturecraft_geom::glam::Vec2; + +/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct UvStrokeState { + /// The last sample's texture coordinates (None before the first sample). + pub last: Option, + /// Distance from the last stamp to the last sample, at most one stamp step. + pub carry: f32, + /// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample. + pub stamps: u32, +} diff --git a/crates/engine/tests/uv_strokes.rs b/crates/engine/tests/uv_strokes.rs new file mode 100644 index 00000000..b17fb0bf --- /dev/null +++ b/crates/engine/tests/uv_strokes.rs @@ -0,0 +1,77 @@ +//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// Texture size: 1e-4 UV is 0.0256 texels +const RESOLUTION: u32 = 256; + +/// A sphere project painting red with `brush` settings (the UI's 0–100 scales) +fn red_brush_session(brush: serde_json::Value) -> Session { + let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &brush).unwrap(); + session +} + +/// The composite base color at texel (`x`, `y`) +fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] { + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Whether the composite base color at (`u`, `v`) is the painted red +fn red_at(session: &Session, u: f32, v: f32) -> bool { + let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +#[test] +fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() { + // 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap(); + + for u in [0.1, 0.5, 0.9] { + assert!(red_at(&session, u, 0.5), "painted at u = {u}"); + } +} + +#[test] +fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() { + // 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off the texture, near u = -6.9 + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap(); + + assert!(red_at(&session, 0.55, 0.5), "the last segment is painted"); + assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start"); +} + +#[test] +fn each_sample_of_a_stroke_stamps_new_noise() { + // A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5 + let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap(); + + let patch = |centre_x: u32| -> Vec<[f32; 3]> { + (centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect() + }; + let first_stamp = patch(64); + assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted"); + assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise"); +} + +#[test] +fn a_hostile_segment_stays_bounded() { + // The finest brush the settings allow: 2e-5 UV between stamps + let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0})); + + let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]})); + + assert!(result.is_ok(), "{result:?}"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..15d22ac5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -110,6 +110,8 @@ pub struct TextureCraftApp { pub profiler: profile::Profiler, /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. pub last_paint_point: Option, + /// Where the last finished 2D view stroke ended: its texture set and texture coordinates (so zoom and pan keep it), for Shift+click straight lines. + pub last_paint_uv: Option<(usize, texturecraft_engine::geom::glam::Vec2)>, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, /// The Properties popup a right click in a view opens. @@ -133,19 +135,23 @@ pub struct TextureCraftApp { } impl TextureCraftApp { + /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + + // The first run speaks the OS (or browser) language + let ui = cc.storage.and_then(|storage| eframe::get_value::(storage, "ui")).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = TextureCraftApp { camera_glide: None, session, @@ -166,6 +172,7 @@ impl TextureCraftApp { brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, + last_paint_uv: None, placing_decal: None, properties_popup: None, render_state: cc.wgpu_render_state.clone(), @@ -181,17 +188,21 @@ impl TextureCraftApp { app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); export_templates::load_library(&mut app, cc.storage); + #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } + let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } + app } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..cb1c9bc1 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -165,6 +165,18 @@ const UV_VIEW_MAX_ZOOM: f32 = 40.0; /// UV zoom change per point of mouse wheel, as a fraction of the zoom const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; +/// Dash length of the straight-line preview, in points +const RUBBER_BAND_DASH: f32 = 6.0; + +/// Gap between the straight-line preview's dashes, in points +const RUBBER_BAND_GAP: f32 = 4.0; + +/// Opacity of the UV tile outlines in the 2D view +const UV_TILE_OUTLINE_ALPHA: u8 = 40; + +/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible +const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -996,11 +1008,43 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons } } -/// Dashed preview of a straight segment. +/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. 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)); + let Some(visible) = visible_dashes(rect, from, to) else { return }; + let painter = ui.painter_at(rect); + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + } +} + +/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place. +fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> { + let direction = to - from; + let length = direction.length(); + if length == 0.0 { + return rect.contains(from).then_some([from, to]); + } + + // Clip the segment's parameter range against each axis's slab + let (mut enter, mut exit) = (0.0_f32, 1.0_f32); + for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta); + enter = enter.max(at_low.min(at_high)); + exit = exit.min(at_low.max(at_high)); + } + if enter > exit { + return None; + } + + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let start = (enter * length / period).floor() * period / length; + Some([from + direction * start, from + direction * exit]) } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -1148,11 +1192,12 @@ fn pen_pressure(ui: &Ui) -> f32 { } } +/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|input| input.modifiers.alt); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); let adjusting = brush_drag(app, ui, &response); // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor @@ -1216,29 +1261,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if painting && path_tool { path_input(app, ui, &response, 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) { - if let Some(pointer) = response.interact_pointer_pos() - && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) - { - app.toast(error.to_string(), true); - } - if response.clicked_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } - } else if response.dragged_by(PointerButton::Primary) - && app.session.stroke_active() - && let Some(pointer) = response.interact_pointer_pos() - { - app.session.continue_stroke_uv(to_uv(pointer), pressure); - } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + paint_2d_input(app, ui, &response, shift, &to_uv); } if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; @@ -1259,7 +1282,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1285,10 +1308,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &response, true, show); } + // Shift: preview the straight line Shift+click paints from the last stroke + if painting + && shift + && !path_tool + && brush_tool(app.session.tool.tool) + && let Some((last_set, from)) = app.last_paint_uv + && last_set == ts + && let Some(hover) = response.hover_pos() + { + rubber_band(ui, rect, to_screen(from.x, from.y), hover); + } + if app.ui.mode == crate::state::Mode::Baking { bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { - let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } @@ -1300,6 +1335,51 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. +fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let pressure = pen_pressure(ui); + let set = app.session.ts(); + // Where the stroke under way is; it becomes the line start only when the stroke finishes + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + + if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { + // A line starts only from a point on the same texture set + let line_start = match app.last_paint_uv { + Some((last_set, last_uv)) if shift && last_set == set => Some(last_uv), + _ => None, + }; + if let Some(pointer) = resp.interact_pointer_pos() { + let uv = to_uv(pointer); + match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { + Ok(()) => { + if line_start.is_some() { + app.session.continue_stroke_uv(uv, pressure); + } + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + Err(error) => app.toast(error.to_string(), true), + } + } + } else if resp.dragged_by(PointerButton::Primary) + && app.session.stroke_active() + && let Some(pointer) = resp.interact_pointer_pos() + { + let uv = to_uv(pointer); + app.session.continue_stroke_uv(uv, pressure); + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + + // Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here + if resp.clicked_by(PointerButton::Primary) || resp.drag_stopped_by(PointerButton::Primary) { + let finishing = app.session.stroke_active(); + match app.session.end_stroke() { + Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) => {} + Err(error) => app.toast(error.to_string(), true), + } + } +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); @@ -1351,3 +1431,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t }; painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + +#[cfg(test)] +mod tests { + use super::*; + + 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; + + #[test] + fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() { + let far_start = pos2(-10_003.0, 50.0); + + let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap(); + + assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}"); + let periods = (start.x - far_start.x) / DASH_PERIOD; + assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}"); + assert_eq!(end, pos2(50.0, 50.0)); + } + + #[test] + fn a_segment_inside_the_view_is_kept_whole() { + assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)])); + } + + #[test] + fn a_segment_outside_the_view_draws_nothing() { + assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None); + assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/tests/shift_lines_2d.rs b/crates/ui-egui/tests/shift_lines_2d.rs new file mode 100644 index 00000000..5b87f409 --- /dev/null +++ b/crates/ui-egui/tests/shift_lines_2d.rs @@ -0,0 +1,180 @@ +//! Shift+click in the 2D view paints a straight line from where the last stroke ended, as in the 3D view + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// The first click, on the sample's texture in the 2D view +const FIRST_CLICK: Pos2 = pos2(700.0, 420.0); + +/// The Shift+click, on the texture of both of the sample's texture sets +const SECOND_CLICK: Pos2 = pos2(900.0, 520.0); + +/// Start of a drag cancelled with Escape, well away from the line between the two clicks +const CANCELLED_DRAG_FROM: Pos2 = pos2(760.0, 700.0); + +/// End of the cancelled drag +const CANCELLED_DRAG_TO: Pos2 = pos2(820.0, 700.0); + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// How far beside the line the unpainted check looks, in brush radii +const BESIDE_LINE_IN_RADII: f32 = 3.0; + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// Press at `from`, drag to `to`, press Escape and release: the stroke is cancelled +fn cancelled_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(1); + harness.hover_at(to); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!harness.state().session.stroke_active(), "Escape cancelled the stroke"); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// Alpha added between two snapshots +fn added(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// Whether `paint` holds visible alpha at `texel` +fn painted_at(paint: &[f32], width: u32, texel: Vec2) -> bool { + let index = texel.y.round() as usize * width as usize + texel.x.round() as usize; + paint[index] > PAINTED_ALPHA +} + +/// The brush radius in texels: a 2D view stamp's radius is twice the brush size in UV units +fn brush_radius_in_texels(harness: &Harness<'_, TextureCraftApp>, width: u32) -> f32 { + harness.state().session.tool.brush.size * 2.0 * width as f32 +} + +/// Click, run `between` (zoom or pan), Shift+click; assert one straight stroke joins both dabs +fn assert_shift_click_draws_a_line(between: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) { + let mut harness = uv_view_app(); + let (blank, width) = alpha(&harness); + click(&mut harness, FIRST_CLICK, false); + let (first_dab, _) = alpha(&harness); + let start = centre(&added(&blank, &first_dab), width); + + between(&mut harness); + harness.run_steps(2); + let steps_before = harness.state().session.history_labels().len(); + click(&mut harness, SECOND_CLICK, true); + assert_eq!(harness.state().session.history_labels().len(), steps_before + 1, "the line is one undo step"); + let (with_line, _) = alpha(&harness); + let line = added(&first_dab, &with_line); + + // A plain click at the same point finds where the line should end + harness.state_mut().session.undo().unwrap(); + click(&mut harness, SECOND_CLICK, false); + let (with_dab, _) = alpha(&harness); + let end = centre(&added(&first_dab, &with_dab), width); + + let middle = (start + end) * 0.5; + let across = (end - start).perp().normalize() * brush_radius_in_texels(&harness, width) * BESIDE_LINE_IN_RADII; + assert!(painted_at(&line, width, middle), "the line passes halfway between {start} and {end}"); + assert!(!painted_at(&line, width, middle + across), "nothing is painted beside the line"); +} + +#[test] +fn shift_click_paints_a_straight_line_from_the_last_stroke() { + assert_shift_click_draws_a_line(|_| {}); +} + +#[test] +fn the_line_joins_the_same_texture_points_after_zoom_and_pan() { + assert_shift_click_draws_a_line(|harness| { + let ui_state = &mut harness.state_mut().ui; + ui_state.uv_zoom *= 1.5; + ui_state.uv_pan = [0.2, -0.1]; + }); +} + +/// Shift+click at the second point; assert it painted the same dot a plain click there paints +fn assert_shift_click_paints_only_a_dot(harness: &mut Harness<'_, TextureCraftApp>) { + let (before, _) = alpha(harness); + click(harness, SECOND_CLICK, true); + let (after_shift_click, _) = alpha(harness); + let shift_click_alpha: f32 = added(&before, &after_shift_click).iter().sum(); + + harness.state_mut().session.undo().unwrap(); + click(harness, SECOND_CLICK, false); + let (after_click, _) = alpha(harness); + let click_alpha: f32 = added(&before, &after_click).iter().sum(); + + assert!(click_alpha > 1.0, "the plain click painted: {click_alpha}"); + assert!((shift_click_alpha - click_alpha).abs() < click_alpha * 0.01, "Shift+click paints only a dot: {shift_click_alpha} vs {click_alpha}"); +} + +#[test] +fn shift_click_without_a_previous_stroke_paints_a_dot() { + assert_shift_click_paints_only_a_dot(&mut uv_view_app()); +} + +#[test] +fn a_line_does_not_start_from_a_point_on_another_texture_set() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { + assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); +} From cfe837b86cb83b60c4224aa04f1fb8cf1d22b4cf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:20 +0000 Subject: [PATCH 12/76] Import baked maps when creating a project New project > Advanced settings gets the project's normal map format and Import baked maps: Add lists image files, and Create imports them with the new textureSet.meshMap.import command, which sets each file as the mesh map of the texture set and slot its name names (Body_ambient_occlusion.png, Body_normal.1001.png) in one undo step and reports the files it left out. --- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 43 ++--- crates/engine/src/meshmap_file_name.rs | 153 +++++++++++++++++ crates/engine/src/meshmap_import_cmds.rs | 79 +++++++++ crates/engine/src/resource_cmds.rs | 35 ++-- crates/engine/tests/meshmap_import.rs | 136 +++++++++++++++ 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 | 1 + crates/ui-egui/src/new_project_advanced.rs | 155 ++++++++++++++++++ crates/ui-egui/src/state.rs | 10 +- crates/ui-egui/src/windows.rs | 7 +- .../ui-egui/tests/new_project_baked_maps.rs | 80 +++++++++ docs/control-protocol.md | 2 +- 22 files changed, 725 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/meshmap_file_name.rs create mode 100644 crates/engine/src/meshmap_import_cmds.rs create mode 100644 crates/engine/tests/meshmap_import.rs create mode 100644 crates/ui-egui/src/new_project_advanced.rs create mode 100644 crates/ui-egui/tests/new_project_baked_maps.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..922c380b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -65,6 +65,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..da0ab3ae 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,8 @@ pub mod material_lib; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 0fbe1f5b..932ba137 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,11 +38,17 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) +} + +/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width +pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { + let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). + let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), @@ -52,37 +58,34 @@ fn set(s: &mut Session, p: &Value) -> Result { } }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); + return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; let data = match &tiles { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. + // An atlas texel reads the image of the tile its mesh UV falls in Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(res) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; tiles .iter() .map(|&t| { let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) }) .collect() } diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..cfc4f125 --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,153 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The file name without its folder and extension +fn stem(path: &str) -> &str { + Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +} + +/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) +fn words(path: &str) -> Vec { + stem(path) + .split(is_separator) + .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) + .map(str::to_lowercase) + .collect() +} + +/// The mesh map a file holds, from the words of its name; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str) -> Option { + let words = words(path); + let has = |word: &str| words.iter().any(|w| w == word); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = stem(path).to_lowercase(); + set_names + .iter() + .enumerate() + .filter(|(_, name)| !name.is_empty()) + .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) + .max_by_key(|(_, name)| name.chars().count()) + .map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png"), None); + assert_eq!(baked_map_from_file_name("ambient.png"), None); + assert_eq!(baked_map_from_file_name(""), None); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..9770cf63 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,79 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::use_image; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes +const MAX_FILES: usize = 1024; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); + let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let map = match strp(file, "map") { + Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + None => baked_map_from_file_name(path), + }; + match (texture_set_from_file_name(path, &set_names), map) { + (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + _ => unmatched.push(path), + } + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + for ((ts, map), paths) in &slots { + // A UV-tiled set reads every tile's file; any other set takes the first file for a slot + let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; + let (taken, extra) = paths.split_at(files_used); + let mut image_name = None; + for path in taken { + let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; + image_name.get_or_insert(name); + } + if let Some(name) = image_name { + use_image(s, CMD, *ts, *map, &name)?; + } + + assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); + unmatched.extend(extra); + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..74682be8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,9 +38,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) + } + + /// [`Session::import_resource_bytes`] without its own undo step, for imports inside a larger edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } + let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,27 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// The bytes of the image file at `path`, refused above [`MAX_BYTES`] +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str) -> Result> { + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if meta.len() > MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is too large"))); + } + + std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs new file mode 100644 index 00000000..62a983d6 --- /dev/null +++ b/crates/engine/tests/meshmap_import.rs @@ -0,0 +1,136 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = 20 + 20 * index as u8; + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) + .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|f| (f, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_failed_file_imports_nothing() { + let dir = bake_folder("failed", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile() { + let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + + let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..e1746a31 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..1b86b2e7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,10 @@ 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}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..a0445eed 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,10 @@ 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}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..235bf5a9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,10 @@ 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}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..12a180ed 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,10 @@ 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}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..8b930774 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..30d5eef5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..330c09a3 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,10 @@ 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}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..f0731a7c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..23f67ca9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod keymap; mod mask_preview_image; mod mask_shape; pub mod menus; +pub mod new_project_advanced; pub mod parity; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..50dd64c6 --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,155 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::template_cmds::builtin_templates; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| baked_maps(&mut app.ui.new_project, ui)); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let user_templates = app.session.templates.list.iter().cloned(); + let template_format = + builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add_baked_map_files(new_project, pick_baked_map_files()); + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn pick_baked_map_files() -> Vec { + let files = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); + files.unwrap_or_default().into_iter().map(|path| path.display().to_string()).collect() +} + +#[cfg(target_arch = "wasm32")] +fn pick_baked_map_files() -> Vec { + Vec::new() +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..f22d1d69 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -151,6 +151,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -167,6 +173,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..8ac07749 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -392,7 +392,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { @@ -429,6 +429,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.selectable_label(t.name == np.template, &t.name).clicked() { np.template = t.name.clone(); np.resolution = t.resolution; + np.normal_format = None; } } }); @@ -469,6 +470,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -490,6 +493,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if r.is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + app.ui.new_project.baked_maps.clear(); + crate::new_project_advanced::apply_after_create(app, &np); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs new file mode 100644 index 00000000..a2c95e98 --- /dev/null +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -0,0 +1,80 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78707aa1..734036ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From ffe8587e541792eb356226b6cc476e1c3bc4a56e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:25:04 +0000 Subject: [PATCH 13/76] Take &Path in the import test helper --- crates/engine/tests/meshmap_import.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index 62a983d6..da3cb780 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -1,6 +1,6 @@ //! Importing baked map files at once: each lands in the texture set and mesh map its name names -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde_json::{Value, json}; use texturecraft_engine::core::BakedMap; @@ -23,7 +23,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { dir } -fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { +fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value { let files: Vec = files .iter() .map(|(file, map)| { From 6eed52435db0ff1dfc05ff16e38ae51a8ae647f6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 09:14:35 +0000 Subject: [PATCH 14/76] Match UV tiles per file, skip empty imports, review cleanups - Each tiled file is keyed by its own tile number and its image passed to use_images, so tiles named differently or renamed on import still match - Files of a tiled set without one of its tiles, and maps missing a tile, go to unmatched instead of failing the import - Nothing to import leaves no undo step - The map is read from the file name after the set name - Toast counts maps; a failed import keeps the file list - Cap the bytes one import reads; whole-method cleanup of set, use_images, tile_images and new_project --- crates/engine/src/meshmap_cmds.rs | 79 +++++++++++------- crates/engine/src/meshmap_file_name.rs | 72 ++++++++-------- crates/engine/src/meshmap_import_cmds.rs | 83 +++++++++++++------ crates/engine/src/resource_cmds.rs | 2 +- crates/engine/tests/meshmap_import.rs | 68 +++++++++++---- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- crates/ui-egui/src/new_project_advanced.rs | 20 +++-- crates/ui-egui/src/windows.rs | 56 +++++++------ .../ui-egui/tests/new_project_baked_maps.rs | 10 ++- 17 files changed, 258 insertions(+), 150 deletions(-) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 932ba137..ac9003b7 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,58 +38,81 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let texture_set = s.doc.project.texture_set(ts)?; + let images = match texture_set.tile_grid() { + Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?, + None => BTreeMap::from([(FIRST_TILE, image)]), + }; + + let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; Ok(json!({ "map": map.id(), "resolution": resolution })) } -/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width -pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { - let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; - let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; +/// The tile number a set without UV tiles keys its one image by +pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); - // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) - let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); - let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { - Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => { - let (width, height) = set.bake.common.output_size(); - (width.saturating_mul(cols), height.saturating_mul(rows)) - } - }; - if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width +pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { + return Err(bad(cmd, format!("no image for UV tile {tile}"))); } - let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; - let data = match &tiles { - None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) + let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) { + Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))), + None => { + let (width, height) = texture_set.bake.common.output_size(); + (width.saturating_mul(columns), height.saturating_mul(rows)) + } + }; + let empty = width == 0 || height == 0; + let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS; + let too_wide = grid.is_none() && width > MAX_RESOLUTION; + if empty || too_many_texels || too_wide { + return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty"))); + } + + let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = match (grid, images.values().next()) { + (_, None) => return Err(bad(cmd, "no image to use")), + (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in - Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { + (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { let uv = grid.from_atlas([u, v]); - udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; + entry.resolution = width; entry.maps.insert(map, Arc::new(data)); s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(res) + Ok(width) } /// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { - let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let tile_at = + udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default()); tiles .iter() - .map(|&t| { - let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) + .map(|&tile| { + let tile_name = format!("{before_tile}{tile}{after_tile}"); + images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}"))) }) .collect() } +/// The UV tile number in a file name (`Body_ao.1002.png` → 1002) +pub(crate) fn tile_number(file_name: &str) -> Option { + udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok()) +} + /// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts. fn udim_in(name: &str) -> Option { let b = name.as_bytes(); diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs index cfc4f125..fde32d5e 100644 --- a/crates/engine/src/meshmap_file_name.rs +++ b/crates/engine/src/meshmap_file_name.rs @@ -5,13 +5,14 @@ use std::path::Path; use texturecraft_core::{BakedMap, UDIM_RANGE}; /// Mesh maps named by two words anywhere in the file name; they win over the one-word names -const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ +const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[ ("world", &["normal", "normals"], BakedMap::WorldNormal), ("bent", &["normal", "normals"], BakedMap::BentNormal), ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), ]; -const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ +/// Mesh maps named by one word, including the two-word names written as one +const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[ ("worldnormal", BakedMap::WorldNormal), ("worldnormals", BakedMap::WorldNormal), ("bentnormal", BakedMap::BentNormal), @@ -38,29 +39,33 @@ fn is_separator(c: char) -> bool { matches!(c, '_' | '-' | '.' | ' ') } -/// The file name without its folder and extension -fn stem(path: &str) -> &str { - Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +/// The lowercase file name without its folder and extension +fn lowercase_stem(path: &str) -> String { + Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase() } -/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) -fn words(path: &str) -> Vec { - stem(path) - .split(is_separator) - .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) - .map(str::to_lowercase) - .collect() +/// What follows `set_name` at the start of a lowercase stem, when a separator follows it +fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> { + if set_name.is_empty() { + return None; + } + + stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator)) } -/// The mesh map a file holds, from the words of its name; the last recognised word wins -pub(crate) fn baked_map_from_file_name(path: &str) -> Option { - let words = words(path); - let has = |word: &str| words.iter().any(|w| w == word); +/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option { + let stem = lowercase_stem(path); + let rest = after_set_name(&stem, set_name).unwrap_or(&stem); + let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number)); + let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect(); + + let has = |name: &str| words.contains(&name); TWO_WORD_NAMES .iter() - .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second))) .map(|(_, _, map)| *map) - .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) + .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map))) } /// The set a file is for: the longest set name its name starts with before a separator (any name with one set) @@ -69,14 +74,8 @@ pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Opti return Some(0); } - let stem = stem(path).to_lowercase(); - set_names - .iter() - .enumerate() - .filter(|(_, name)| !name.is_empty()) - .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) - .max_by_key(|(_, name)| name.chars().count()) - .map(|(ts, _)| ts) + let stem = lowercase_stem(path); + set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts) } #[cfg(test)] @@ -109,23 +108,30 @@ mod tests { ("Body_alpha.png", BakedMap::Opacity), ]; for (file, map) in cases { - assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}"); } } #[test] fn tile_numbers_and_folders_are_ignored() { - assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); - assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal)); assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); } #[test] fn unknown_words_match_no_map() { - assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); - assert_eq!(baked_map_from_file_name("Body_1001.png"), None); - assert_eq!(baked_map_from_file_name("ambient.png"), None); - assert_eq!(baked_map_from_file_name(""), None); + assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None); + assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None); + assert_eq!(baked_map_from_file_name("", "Body"), None); + } + + #[test] + fn the_set_name_is_not_read_as_a_map() { + assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None); + assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion)); } #[test] diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 9770cf63..f8ea8244 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -1,20 +1,24 @@ //! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names use std::collections::BTreeMap; +use std::path::Path; use serde_json::{Value, json}; use texturecraft_core::BakedMap; use crate::commands::{CommandSpec, always, bad, strp}; -use crate::meshmap_cmds::use_image; +use crate::meshmap_cmds::{FIRST_TILE, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; -/// Most files one import takes -const MAX_FILES: usize = 1024; +/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles +const MAX_FILES: usize = 512; + +/// Most bytes one import reads, since every file stays decoded in memory until the import ends +const MAX_TOTAL_BYTES: u64 = 2 << 30; pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +26,7 @@ pub fn specs() -> Vec { "Import baked maps", [], None, - "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); desktop only", always, import )] @@ -34,39 +38,52 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); } - let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); - let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); - let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new(); let mut unmatched = Vec::new(); for file in files { let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; - let map = match strp(file, "map") { - Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), - None => baked_map_from_file_name(path), - }; - match (texture_set_from_file_name(path, &set_names), map) { - (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + let given_map = strp(file, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))).transpose()?; + match slot_of(s, &set_names, path, given_map) { + Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => { + slots.entry(slot).or_default().insert(tile, path); + } _ => unmatched.push(path), } } + // A UV-tiled map needs a file for every tile of its set + slots.retain(|(ts, _), tiles| { + let complete = + s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile))); + if !complete { + unmatched.extend(tiles.values()); + } + complete + }); + if slots.is_empty() { + return Ok(json!({ "assigned": [], "unmatched": unmatched })); + } + let result = s.edit("Import baked maps", |s| { let mut assigned = Vec::new(); - for ((ts, map), paths) in &slots { - // A UV-tiled set reads every tile's file; any other set takes the first file for a slot - let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; - let (taken, extra) = paths.split_at(files_used); - let mut image_name = None; - for path in taken { - let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; - image_name.get_or_insert(name); - } - if let Some(name) = image_name { - use_image(s, CMD, *ts, *map, &name)?; - } + let mut total_bytes = 0; + for ((ts, map), tiles) in &slots { + let mut images = BTreeMap::new(); + for (tile, path) in tiles { + let bytes = read_image_file(CMD, path)?; + total_bytes += bytes.len() as u64; + if total_bytes > MAX_TOTAL_BYTES { + return Err(bad(CMD, format!("the files are larger than {} GB together", MAX_TOTAL_BYTES >> 30))); + } - assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); - unmatched.extend(extra); + let name = s.add_image_resource(path, bytes)?; + if let Some(image) = s.images.get(&name) { + images.insert(*tile, image.clone()); + } + assigned.push(json!({"path": path, "ts": ts, "map": map.id()})); + } + use_images(s, CMD, *ts, *map, &images)?; } Ok(assigned) }); @@ -77,3 +94,15 @@ fn import(s: &mut Session, p: &Value) -> Result { Ok(json!({ "assigned": result?, "unmatched": unmatched })) } + +/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles) +fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> { + let ts = texture_set_from_file_name(path, set_names)?; + let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?; + let texture_set = s.doc.project.texture_sets.get(ts)?; + let tile = match texture_set.tile_grid() { + Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?, + None => FIRST_TILE, + }; + Some(((ts, map), tile)) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 74682be8..3dc415a4 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -36,7 +36,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { } impl Session { - /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. + /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) } diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index da3cb780..d9ed53f1 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -17,7 +17,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for (index, file) in files.iter().enumerate() { - let gray = 20 + 20 * index as u8; + let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX); image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); } dir @@ -41,13 +41,13 @@ fn file_names(list: &Value) -> Vec { list.as_array() .unwrap() .iter() - .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) - .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap())) + .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string()) .collect() } fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { - s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) + s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) } #[test] @@ -57,21 +57,21 @@ fn files_go_to_the_set_and_map_their_names_name() { let mut s = session(); let label_before = s.undo_label().map(str::to_string); - let result = import(&mut s, &dir, &files.map(|f| (f, None))); + let result = import(&mut s, &dir, &files.map(|file| (file, None))); let assigned = &result["assigned"]; assert_eq!(file_names(assigned).len(), 5, "{result}"); for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); - assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}"); } assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); assert_eq!(s.undo_label(), Some("Import baked maps")); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); - assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported image resources"); std::fs::remove_dir_all(dir).ok(); } @@ -103,8 +103,8 @@ fn a_second_file_for_one_slot_is_left_out() { } #[test] -fn a_failed_file_imports_nothing() { - let dir = bake_folder("failed", &["Ball_ao.png"]); +fn an_undecodable_file_imports_nothing() { + let dir = bake_folder("undecodable", &["Ball_ao.png"]); std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); let mut s = session(); let label_before = s.undo_label().map(str::to_string); @@ -113,18 +113,24 @@ fn a_failed_file_imports_nothing() { let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); assert!(error.contains("Base_ao.png"), "{error}"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty())); assert!(s.doc.resources.is_empty() && s.images.is_empty()); assert_eq!(s.undo_label().map(str::to_string), label_before); std::fs::remove_dir_all(dir).ok(); } -#[test] -fn a_uv_tiled_set_takes_one_file_per_tile() { - let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); - let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); +/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002 +fn tiled_session() -> Session { + Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap() +} - let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() { + let files = ["Plane_ao.1001.png", "plane-AO-1002.png"]; + let dir = bake_folder("tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); let baked = &s.doc.baked[&0]; @@ -134,3 +140,33 @@ fn a_uv_tiled_set_takes_one_file_per_tile() { assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); std::fs::remove_dir_all(dir).ok(); } + +#[test] +fn tiled_files_without_their_tiles_are_left_out_alone() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"]; + let dir = bake_folder("partial-tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]); + assert!(has_map(&s, 0, BakedMap::AmbientOcclusion)); + assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn nothing_matched_makes_no_undo_step() { + let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]); + + assert_eq!(file_names(&result["assigned"]), Vec::::new()); + assert_eq!(file_names(&result["unmatched"]).len(), 2); + assert_eq!(s.undo_label().map(str::to_string), label_before); + assert!(!s.modified); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e1746a31..6ed381eb 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1039,6 +1039,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "استيراد خرائط مخبوزة"), ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), ("Add...", "إضافة..."), - ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 1b86b2e7..4d59f67f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1082,6 +1082,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Gebackene Maps importieren"), ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), ("Add...", "Hinzufügen..."), - ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index a0445eed..f8b84617 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1067,6 +1067,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas horneados"), ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), ("Add...", "Añadir..."), - ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 235bf5a9..b282f90b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1091,6 +1091,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importer des cartes précalculées"), ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), ("Add...", "Ajouter..."), - ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 12a180ed..5d937383 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1076,6 +1076,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importa mappe bake"), ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), ("Add...", "Aggiungi..."), - ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 8b930774..634660bd 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1061,6 +1061,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "ベイク済みマップを読み込む"), ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), ("Add...", "追加..."), - ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 30d5eef5..cafc4b90 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1049,6 +1049,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "베이크된 맵 가져오기"), ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), ("Add...", "추가..."), - ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 330c09a3..f7779924 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1064,6 +1064,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas com bake"), ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), ("Add...", "Adicionar..."), - ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f0731a7c..83044fc3 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1007,6 +1007,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "导入已烘焙贴图"), ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), ("Add...", "添加..."), - ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 50dd64c6..ae1993d1 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -1,5 +1,7 @@ //! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation +use std::collections::BTreeSet; + use egui::{RichText, Sense, Ui, vec2}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; @@ -19,7 +21,7 @@ const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolut const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; /// Width of the dialog's dropdowns -const COMBO_WIDTH: f32 = 200.0; +pub(crate) const COMBO_WIDTH: f32 = 200.0; /// Width of the Add... and Clear buttons const FILE_BUTTON_WIDTH: f32 = 96.0; @@ -64,8 +66,12 @@ pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let new_project = &mut app.ui.new_project; let user_templates = app.session.templates.list.iter().cloned(); - let template_format = - builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let template_format = builtin_templates() + .into_iter() + .chain(user_templates) + .find(|template| template.name == new_project.template) + .map(|template| template.normal_format) + .unwrap_or_default(); let current = new_project.normal_format.unwrap_or(template_format); let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { @@ -114,7 +120,7 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { } } -/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { @@ -129,14 +135,16 @@ pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewPro return; }; - let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let assigned = result["assigned"].as_array().into_iter().flatten(); + let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect(); let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); - let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]); if !not_imported.is_empty() { text.push('\n'); text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); } app.toast(text, !not_imported.is_empty()); + app.ui.new_project.baked_maps.clear(); } fn file_name(path: &str) -> String { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ac07749..4bd8197f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -11,6 +11,7 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; +use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; @@ -388,6 +389,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; } + let mut open = true; let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { @@ -399,13 +401,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { BUILTINS .iter() .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) .unwrap_or_default() }); - egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| { - for (id, l) in BUILTINS { + egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { + for (id, builtin_label) in BUILTINS { if ui - .selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .selectable_label( + app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), + trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), + ) .clicked() { app.ui.new_project.mesh = id.to_string(); @@ -415,21 +420,21 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); if file_dialogs_available() && ui.button(tr("Select...")).clicked() - && let Some(p) = pick_mesh_file() + && let Some(path) = pick_mesh_file() { - app.ui.new_project.file = Some(p); + app.ui.new_project.file = Some(path); } }); ui.end_row(); ui.label(tr("Project template")); - let np = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| { - let user = app.session.templates.list.iter(); - for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) { - if ui.selectable_label(t.name == np.template, &t.name).clicked() { - np.template = t.name.clone(); - np.resolution = t.resolution; - np.normal_format = None; + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; } } }); @@ -448,20 +453,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); ui.label(tr("Document resolution")); egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for r in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}")); + for size in [512u32, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); } }); ui.end_row(); ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |m: Option| match m { + let tiles_label = |tiles: Option| match tiles { None => tr("Automatic (from the mesh UVs)"), Some(true) => tr("On"), Some(false) => tr("Off"), }; egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for m in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m)); + for tiles in [None, Some(true), Some(false)] { + ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); } }); ui.end_row(); @@ -484,17 +489,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); if create { - let np = app.ui.new_project.clone(); - let (cmd, mesh) = match &np.file { + let new_project = app.ui.new_project.clone(); + let (command, mesh) = match &new_project.file { Some(path) => ("file.new", path.clone()), - None => ("project.new", np.mesh.clone()), + None => ("project.new", new_project.mesh.clone()), }; - let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ()); - if r.is_some() { + let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); + if app.run(command, params).is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; - app.ui.new_project.baked_maps.clear(); - crate::new_project_advanced::apply_after_create(app, &np); + crate::new_project_advanced::apply_after_create(app, &new_project); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs index a2c95e98..5b1d7615 100644 --- a/crates/ui-egui/tests/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -21,7 +21,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h } -/// 4×4 PNGs named `files` in a fresh folder, as their full paths +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read fn bake_files(test: &str, files: &[&str]) -> Vec { let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -29,7 +29,7 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { .iter() .map(|file| { let path: PathBuf = dir.join(file); - image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap(); path.display().to_string() }) .collect() @@ -70,11 +70,13 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { assert!(!state.ui.windows.new_project, "the dialog closes"); let project = &state.session.doc.project; assert_eq!(project.normal_format, NormalFormat::DirectX); - let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1]; + assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}"); assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); let toast = &state.toasts.last().unwrap().text; - assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(toast.contains("Baked maps imported: 2") && toast.contains("Ball_notes.png"), "{toast}"); assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); assert_eq!(state.session.undo_label(), Some("Import baked maps")); } From 4543c858122565b13529299e8715b31fc7c990db Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 10:32:33 +0000 Subject: [PATCH 15/76] 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 16/76] 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 17/76] 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 bac53688c139d5779291c77d7ab7034613d729b2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 12:13:03 +0000 Subject: [PATCH 18/76] Bake mode: draw the high poly, the cage and where the bake's rays miss The 3D view in bake mode gets a Baking Visualization panel (high poly, cage, UV seams, low poly, selected texture set only). The cage is built from the bake's own ray starts (a RayFrame now shared by the bake and the view), so it grows and shrinks with the distance sliders exactly as the rays do, and high-poly vertices the transfer rays cannot reach are drawn red. Refs #330 --- crates/bake/src/cage.rs | 15 + crates/bake/src/cage/cage_shell.rs | 65 +++ crates/bake/src/cage/high_poly_reach.rs | 103 +++++ crates/bake/src/cage/ray_frame.rs | 63 +++ crates/bake/src/cage/ray_start.rs | 20 + crates/bake/src/cage/vertex_reach.rs | 28 ++ crates/bake/src/lib.rs | 4 + crates/bake/src/map.rs | 3 + crates/bake/src/map/bake_context.rs | 86 +--- crates/bake/src/map/sampling.rs | 47 +- crates/bake/src/map/source.rs | 13 + crates/bake/src/map/transfer_keys.rs | 8 + crates/bake/src/mesh_extent.rs | 35 ++ crates/bake/src/test/cage_shell.rs | 103 +++++ crates/bake/src/test/high_poly_reach.rs | 198 ++++++++ crates/bake/src/tests.rs | 6 + crates/engine/src/bake/bake_cage_inputs.rs | 45 ++ crates/engine/src/bake/bake_meshes.rs | 5 + crates/engine/src/bake/mesh_map_command.rs | 90 +++- crates/engine/src/bake/mod.rs | 2 + crates/geom/src/mesh.rs | 54 +++ crates/render/src/bake_visualization.rs | 12 + crates/render/src/cage_gpu.rs | 9 + crates/render/src/high_poly_gpu.rs | 11 + crates/render/src/lib.rs | 5 + crates/render/src/renderer.rs | 423 ++++++++++++++---- crates/render/src/shaders/bake_view.wgsl | 88 ++++ crates/render/src/uv_seam_gpu.rs | 8 + crates/render/tests/headless.rs | 75 +++- .../src/bake_mode/bake_visualization_panel.rs | 61 +++ .../bake_mode/bake_visualization_toggles.rs | 34 ++ crates/ui-egui/src/bake_mode/mod.rs | 4 + crates/ui-egui/src/bake_scene.rs | 11 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 213 +++++++++ crates/ui-egui/src/bake_scene/cage_link.rs | 16 + .../ui-egui/src/bake_scene/cage_shell_key.rs | 47 ++ crates/ui-egui/src/bake_scene/cage_upload.rs | 10 + crates/ui-egui/src/bake_scene/reach_link.rs | 100 +++++ .../ui-egui/src/bake_scene/shared_handle.rs | 32 ++ crates/ui-egui/src/gpu.rs | 206 ++++++--- 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 | 5 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/viewport.rs | 56 ++- 52 files changed, 2179 insertions(+), 285 deletions(-) create mode 100644 crates/bake/src/cage.rs create mode 100644 crates/bake/src/cage/cage_shell.rs create mode 100644 crates/bake/src/cage/high_poly_reach.rs create mode 100644 crates/bake/src/cage/ray_frame.rs create mode 100644 crates/bake/src/cage/ray_start.rs create mode 100644 crates/bake/src/cage/vertex_reach.rs create mode 100644 crates/bake/src/map/transfer_keys.rs create mode 100644 crates/bake/src/mesh_extent.rs create mode 100644 crates/bake/src/test/cage_shell.rs create mode 100644 crates/bake/src/test/high_poly_reach.rs create mode 100644 crates/engine/src/bake/bake_cage_inputs.rs create mode 100644 crates/render/src/bake_visualization.rs create mode 100644 crates/render/src/cage_gpu.rs create mode 100644 crates/render/src/high_poly_gpu.rs create mode 100644 crates/render/src/shaders/bake_view.wgsl create mode 100644 crates/render/src/uv_seam_gpu.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_panel.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs create mode 100644 crates/ui-egui/src/bake_scene.rs create mode 100644 crates/ui-egui/src/bake_scene/bake_scene_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_shell_key.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_upload.rs create mode 100644 crates/ui-egui/src/bake_scene/reach_link.rs create mode 100644 crates/ui-egui/src/bake_scene/shared_handle.rs diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs new file mode 100644 index 00000000..d2c7d7f3 --- /dev/null +++ b/crates/bake/src/cage.rs @@ -0,0 +1,15 @@ +//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws + +mod cage_shell; +mod high_poly_reach; +mod ray_frame; +mod ray_start; +mod vertex_reach; + +#[cfg(test)] +pub(crate) use cage_shell::CORNERS; +pub use cage_shell::CageShell; +pub use high_poly_reach::HighPolyReach; +pub(crate) use ray_frame::RayFrame; +pub use ray_start::RayStart; +pub use vertex_reach::VertexReach; diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs new file mode 100644 index 00000000..e1664219 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,65 @@ +use super::{RayFrame, RayStart}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::surface_at; + +/// Barycentric coordinates of a triangle's three corners +pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + +/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles +#[derive(Clone, Debug, Default)] +pub struct CageShell { + /// Low-poly position of each triangle corner, three per triangle + pub positions: Vec, + pub starts: Vec, + /// Corner pairs along the low poly's polygon edges, for the wireframe + pub edges: Vec<[u32; 2]>, + /// World units per unit of the max frontal distance setting + pub cage_units: f32, +} + +impl CageShell { + /// The cage of `request`'s texture set, from the same ray starts the bake uses + pub fn new(request: &BakeRequest) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let (frame, mesh) = (&ray_frame, request.mesh); + let triangles: Vec = mesh.triangles_of(request.material).collect(); + let (positions, starts): (Vec, Vec) = triangles + .par_iter() + .flat_map_iter(|&triangle| { + CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) { + Some(surface) => (surface.pos, frame.start(&surface, barycentric)), + None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }), + }) + }) + .unzip(); + + let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let mut edge_corners = HashMap::new(); + for (triangle_index, &triangle) in triangles.iter().enumerate() { + let Some(vertices) = mesh.tri(triangle) else { continue }; + + for corner in 0..3 { + let next = (corner + 1) % 3; + let (from, to) = (vertices[corner] as u32, vertices[next] as u32); + let key = (from.min(to), from.max(to)); + if wire_edges.contains(&key) { + let first_corner = (triangle_index * 3) as u32; + edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + } + } + } + let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); + edges.sort_unstable(); + + Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + } + + /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling + pub fn corners(&self, max_frontal: f32) -> Vec { + let frontal = max_frontal * self.cage_units; + self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect() + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs new file mode 100644 index 00000000..f957ce49 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,103 @@ +use super::{RayFrame, VertexReach}; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, surface_at}; + +/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses +#[derive(Clone, Debug, Default)] +pub struct HighPolyReach { + /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly + pub vertices: Vec>, + /// World units per unit of the cage distance settings + pub cage_units: f32, + pub ignore_backface: bool, +} + +impl HighPolyReach { + /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there + pub fn new(request: &BakeRequest) -> Result { + let Some(high) = request.high else { return Ok(HighPolyReach::default()) }; + + let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let mut in_set = vec![false; request.mesh.triangle_count()]; + for triangle in request.mesh.triangles_of(request.material) { + if let Some(flag) = in_set.get_mut(triangle) { + *flag = true; + } + } + + let winding_normals = winding_normals(high.mesh); + let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode { + MeshMatchMode::Always => (Vec::new(), Vec::new()), + MeshMatchMode::ByMeshName => { + let (low_keys, high_keys) = transfer_keys(request); + (low_keys, vertex_keys(high.mesh, &high_keys)) + } + }; + let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY); + let frame = &frame; + let vertices = high + .mesh + .positions + .par_iter() + .zip(&winding_normals) + .enumerate() + .map(|(vertex, (&high_position, &high_facing))| { + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?; + if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) { + return None; + } + + let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?; + let ray_key = key(&low_keys, nearest.tri as usize); + Some(VertexReach { + low_position: surface.pos, + start: frame.start(&surface, [nearest.u, nearest.v]), + high_position, + high_facing, + name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key, + }) + }) + .collect(); + + Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface }) + } + + /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's + pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option { + let reach = self.vertices.get(vertex).copied().flatten()?; + Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface)) + } +} + +/// 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 &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) { + 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 { + if let Some(normal) = normals.get_mut(corner as usize) { + *normal += winding_normal; + } + } + } + normals +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs new file mode 100644 index 00000000..e8692cf2 --- /dev/null +++ b/crates/bake/src/cage/ray_frame.rs @@ -0,0 +1,63 @@ +use super::RayStart; +use crate::MeshExtent; +use crate::map::{interpolate, welded}; +use crate::skew::PreparedSkew; +use crate::{BakeError, BakePaintMap, BakeRequest}; +use texturecraft_core::CageType; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +pub(crate) struct RayFrame<'a> { + mesh: &'a Mesh, + ray_normals: Vec, + cage: Option<&'a Mesh>, + skew: Option>, + cage_paint: Option<&'a BakePaintMap>, + /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead + ray_epsilon: f32, + /// World units per unit of the cage distance settings + pub(crate) cage_units: f32, +} + +impl<'a> RayFrame<'a> { + pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { + let settings = request.settings; + let ray_normals = match settings.cage.average_normals && request.high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + Ok(RayFrame { + mesh: request.mesh, + ray_normals, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, + cage_paint: request.cage_paint, + ray_epsilon: extent.ray_epsilon(), + cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 }, + }) + } + + /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts + pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart { + let cage_offset = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.ray_epsilon); + if let Some(offset) = cage_offset { + return RayStart::CageMesh(offset); + } + + let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let up = match &self.skew { + Some(skew) => skew.correct(self.mesh, surface, averaged_normal), + None => averaged_normal, + }; + RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) } + } +} diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs new file mode 100644 index 00000000..c0c3923a --- /dev/null +++ b/crates/bake/src/cage/ray_start.rs @@ -0,0 +1,20 @@ +use texturecraft_geom::glam::Vec3; + +/// Where the bake's transfer ray for one low-poly point starts +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RayStart { + /// On the cage mesh: the offset from the cage to the low-poly point + CageMesh(Vec3), + /// Out along `up` by the frontal distance times `scale` (the painted cage amount) + Distance { up: Vec3, scale: f32 }, +} + +impl RayStart { + /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance + pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 { + match *self { + RayStart::CageMesh(offset) => position - offset, + RayStart::Distance { up, scale } => position + up * frontal * scale, + } + } +} diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs new file mode 100644 index 00000000..34adea92 --- /dev/null +++ b/crates/bake/src/cage/vertex_reach.rs @@ -0,0 +1,28 @@ +use super::RayStart; +use texturecraft_geom::glam::Vec3; + +/// One high-poly vertex seen from the transfer ray through its nearest low-poly point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VertexReach { + pub low_position: Vec3, + pub start: RayStart, + pub high_position: Vec3, + /// The side the high poly's triangles face at the vertex, by their winding (not normalized) + pub high_facing: Vec3, + /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name) + pub name_matches: bool, +} + +impl VertexReach { + /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray + pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { + let origin = self.start.origin(self.low_position, frontal); + let (direction, front) = match self.start { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), + RayStart::Distance { up, scale } => (-up, frontal * scale), + }; + let along_ray = (self.high_position - origin).dot(direction); + + !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index a8b087bc..eb8a61de 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -6,13 +6,17 @@ mod bake_error; mod bake_output; mod bake_request; +mod cage; mod high_poly; +mod mesh_extent; mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; pub use bake_request::BakeRequest; +pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; +pub(crate) use mesh_extent::MeshExtent; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 384d9d02..c9c30fd6 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -15,10 +15,13 @@ mod source; mod texel_grid; mod traced; mod transfer; +mod transfer_keys; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use sampling::{interpolate, welded}; pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; +pub(crate) use transfer_keys::transfer_keys; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index 21fed094..f3e35df6 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,28 +1,22 @@ use super::curvature::Curvature; -use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::skew::PreparedSkew; +use crate::cage::{RayFrame, RayStart}; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::{BakeError, BakeRequest}; +use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; -use std::collections::HashMap; use texturecraft_core::{ - AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; +use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - cage_paint: Option<&'a crate::BakePaintMap>, - ray_normals: Vec, + ray_frame: RayFrame<'a>, settings: &'a BakeSettings, - eps: f32, frontal: f32, rear: f32, position: PositionProjection, @@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> { impl<'a> BakeContext<'a> { pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { let settings = request.settings; - let (bounds_min, bounds_max) = request.mesh.bounds(); - let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); - if !mesh_diagonal.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - - let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); - let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); - let high = request.high.map(|high_mesh| { - Source::new( - high_mesh.mesh, - high_mesh.bvh, - high_mesh.base_color, - high_mesh.file_ids, - &settings.high_poly.high_suffix, - &settings.high_poly, - &mut name_keys, - ) - }); - let ray_normals = match settings.cage.average_normals && high.is_some() { - true => { - let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; - let ray_epsilon = 1e-6 * mesh_diagonal; + let extent = MeshExtent::of(request.mesh)?; + let (low, high) = Source::of_request(request); + let ray_frame = RayFrame::new(request, extent)?; + let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; @@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> { pass.ignore_backface = parameters.ignore_backface; pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; pass.attenuation = parameters.attenuation; - pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset); } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); if let Some(pass) = &mut bent { pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); if let Some(pass) = &mut thickness { pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; } - let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + + let cage_units = ray_frame.cage_units; Ok(BakeContext { low, high, - cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, - skew, - cage_paint: request.cage_paint, - ray_normals, + ray_frame, settings, - eps: ray_epsilon, frontal: settings.cage.max_frontal * cage_units, rear: settings.cage.max_rear * cage_units, position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), @@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> { } pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { - let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); - let cage = self - .cage - .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) - .map(|cage_position| surface.pos - cage_position) - .filter(|offset| offset.length() > self.eps); - let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); - let (origin, direction, front) = match cage { - Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), - None => { - let up = match &self.skew { - Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), - None => averaged_normal, - }; - (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) - } + let start = self.ray_frame.start(surface, barycentric); + let origin = start.origin(surface.pos, self.frontal); + let (direction, front) = match start { + RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), + RayStart::Distance { up, scale } => (-up, self.frontal * scale), }; let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index d19e4afa..5f2d2677 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -3,34 +3,43 @@ use std::ops::{Add, Mul}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +/// `values` (one per vertex) at `barycentric` in triangle `triangle` +pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option { + let [first, second, third] = mesh.tri(triangle as usize)?; + let [second_weight, third_weight] = barycentric; + + Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight) } -pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh +/// Vertices closer than this fraction of the mesh diagonal count as one when welding +const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5; + +/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals +pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) { + let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL; + let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new()); + + let welded_indices: Vec = mesh .positions .iter() .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 + .map(|(position, normal)| { + let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64); + let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| { + positions.push(*position); + normal_sums.push(Vec3::ZERO); + (positions.len() - 1) as u32 }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; + if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; } - id + welded_index }) .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) + + let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (welded_indices, positions, normals) } pub(super) fn splitmix64(x: u64) -> u64 { diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..ad057b11 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,4 +1,5 @@ use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; @@ -21,6 +22,18 @@ pub(super) struct Source<'a> { } impl<'a> Source<'a> { + /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part + pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) { + let settings = &request.settings.high_poly; + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys) + }); + + (low, high) + } + pub(super) fn new( mesh: &'a Mesh, bvh: &'a Bvh, diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs new file mode 100644 index 00000000..69e9b12a --- /dev/null +++ b/crates/bake/src/map/transfer_keys.rs @@ -0,0 +1,8 @@ +use super::source::Source; +use crate::BakeRequest; + +/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key +pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) { + let (low, high) = Source::of_request(request); + (low.key, high.map(|high| high.key).unwrap_or_default()) +} diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs new file mode 100644 index 00000000..3c6fa48d --- /dev/null +++ b/crates/bake/src/mesh_extent.rs @@ -0,0 +1,35 @@ +use crate::BakeError; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances +const MIN_MESH_SIZE: f32 = 1e-6; + +/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal +const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6; + +/// The low-poly mesh's size, which scales the bake's relative distances +#[derive(Clone, Copy, Debug)] +pub(crate) struct MeshExtent { + pub(crate) bounds_min: Vec3, + pub(crate) diagonal: f32, + /// The bounding box's largest side + pub(crate) scale: f32, +} + +impl MeshExtent { + pub(crate) fn of(mesh: &Mesh) -> Result { + let (bounds_min, bounds_max) = mesh.bounds(); + let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE); + if !diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) }) + } + + /// How far a ray starts past the surface it leaves, in world units + pub(crate) fn ray_epsilon(&self) -> f32 { + RAY_EPSILON_PER_DIAGONAL * self.diagonal + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..2d114b06 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,103 @@ +use super::settings; +use crate::cage::CORNERS; +use crate::map::BakeContext; +use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly}; +use texturecraft_core::{BakedMap, CageType}; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// A painted map whose values vary over the UV square +fn painted_map() -> BakePaintMap { + let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap(); + map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap(); + map +} + +/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit +fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { + let shell = CageShell::new(request).unwrap(); + let corners = shell.corners(request.settings.cage.max_frontal); + let context = BakeContext::new(request).unwrap(); + let triangles: Vec = request.mesh.triangles_of(request.material).collect(); + assert_eq!(corners.len(), triangles.len() * 3); + + for (corner_index, corner) in corners.iter().enumerate() { + let barycentric = CORNERS[corner_index % 3]; + let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap(); + let (ray, _) = context.transfer_ray(&surface, barycentric); + assert_eq!(*corner, ray.origin, "corner {corner_index}"); + } +} + +#[test] +fn the_cage_corners_are_the_bake_ray_origins() { + let low = primitives::cube(1.0); + let high_mesh = primitives::sphere(0.8, 16, 8); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let (skew, cage_paint) = (painted_map(), painted_map()); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.max_frontal = 0.03; + bake_settings.skew.edge_protection = true; + let request = |settings| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings, + high: Some(high), + cage: None, + skew: Some(&skew), + cage_paint: Some(&cage_paint), + tiles: (1, 1), + }; + + assert_cage_matches_the_ray_origins(&request(&bake_settings)); + let face_normals = { + let mut face_normals = bake_settings.clone(); + face_normals.cage.average_normals = false; + face_normals.cage.relative_to_bounding_box = false; + face_normals + }; + assert_cage_matches_the_ray_origins(&request(&face_normals)); +} + +#[test] +fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { + let low = primitives::cube(1.0); + let low_bvh = Bvh::new(&low); + let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] }; + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max); + + assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly"); + // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis + assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance"); + assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge"); + + let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() }; + let custom_settings = { + let mut custom_settings = bake_settings.clone(); + custom_settings.cage.kind = CageType::CustomFile; + custom_settings + }; + let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request }; + assert_cage_matches_the_ray_origins(&custom); + let corners = CageShell::new(&custom).unwrap().corners(0.0); + assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); + assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs new file mode 100644 index 00000000..bb8753f8 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,198 @@ +use super::settings; +use crate::map::{BakeContext, transfer_keys}; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart}; +use texturecraft_core::{BakedMap, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them +const BOUNDARY: f32 = 1e-4; + +/// How close the ray's hit must be to the vertex to count as reaching it +const HIT_TOLERANCE: f32 = 1e-4; + +/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way +fn bumpy_high_poly() -> (Mesh, Vec) { + const FLIPPED_FROM_X: f32 = 0.2; + + let mut mesh = primitives::plane(1.0, 40); + for position in &mut mesh.positions { + position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005; + } + + 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) { + 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); + } + for &corner in corners.iter() { + 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) +} + +#[test] +fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { + let low = primitives::plane(1.0, 8); + let (high_mesh, mixed) = bumpy_high_poly(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let back_facing = |triangle: u32, direction: Vec3| { + let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]); + (b - a).cross(c - a).dot(direction) > 0.0 + }; + let mut checked = [0usize; 2]; + + for ignore_backface in [false, true] { + for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] { + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.high_poly.ignore_backface = ignore_backface; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); + let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") }; + let height = vertex_reach.high_position.y - vertex_reach.low_position.y; + let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY); + if near_the_range_end || mixed[vertex] { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let hit = high_bvh + .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction))); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!( + missed, !reaches_the_vertex, + "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}" + ); + checked[usize::from(missed)] += 1; + } + } + } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); +} + +#[test] +fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() { + let mut low = primitives::plane(1.0, 4); + let mut right = primitives::plane(1.0, 4); + for position in &mut right.positions { + position.x += 2.0; + } + low.append(&right); + assert_eq!(low.materials.len(), 2, "each plane is its own texture set"); + let mut high_mesh = primitives::plane(3.0, 30); + for position in &mut high_mesh.positions { + position.x += 1.0; + position.y = 0.3; + } + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = |material| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap()); + + for (vertex, position) in high_mesh.positions.iter().enumerate() { + let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some()); + assert!(owners != (true, true), "vertex {vertex} belongs to one set at most"); + if position.x < 0.9 { + assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set"); + } else if position.x > 1.1 { + assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set"); + } + } +} + +#[test] +fn matching_by_mesh_name_misses_the_parts_with_another_name() { + const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01; + + let mut low = primitives::plane(1.0, 8); + low.submeshes[0].name = "part_low".into(); + let mut high_mesh = primitives::plane(0.5, 10); + let mut other_part = primitives::plane(0.5, 10); + for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] { + for position in &mut mesh.positions { + position.x += center_x; + position.y = HEIGHT_INSIDE_THE_CAGE; + } + } + high_mesh.append(&other_part); + high_mesh.submeshes[0].name = "part_high".into(); + high_mesh.submeshes[1].name = "other_high".into(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.cage.max_frontal = 0.02; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + let (_, high_keys) = transfer_keys(&request); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles + if vertex_reach.high_position.x.abs() < BOUNDARY { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key); + let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position); + assert_eq!( + missed, + vertex >= high_mesh.positions.len() - other_part.positions.len(), + "only the part named like the low poly is reached: vertex {vertex}" + ); + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 26c8665c..c834da7a 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,6 +14,12 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/cage_shell.rs"] +mod cage_shell; + +#[path = "test/high_poly_reach.rs"] +mod high_poly_reach; + #[path = "test/setting.rs"] mod setting; diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs new file mode 100644 index 00000000..ab559beb --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,45 @@ +use super::MergedHigh; +use std::sync::Arc; +use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it +#[derive(Clone, Debug)] +pub struct BakeCageInputs { + pub(super) mesh: Arc, + pub(super) bvh: Arc, + pub(super) material: usize, + pub(super) settings: BakeSettings, + pub(super) high: MergedHigh, + pub(super) cage: Option>, + pub(super) skew: Option>, + pub(super) cage_paint: Option>, +} + +impl BakeCageInputs { + /// The cage the 3D view draws: the bake's ray origins at each triangle corner + pub fn cage_shell(&self) -> Result { + CageShell::new(&self.request()) + } + + /// Where each high-poly vertex sits relative to the bake's transfer rays + pub fn high_poly_reach(&self) -> Result { + HighPolyReach::new(&self.request()) + } + + fn request(&self) -> BakeRequest<'_> { + BakeRequest { + low_base_color: &[], + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }), + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: (1, 1), + } + } +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index 260002db..da0e4a97 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -14,6 +14,11 @@ pub struct BakeMeshes { } impl BakeMeshes { + /// Every high poly appended into one mesh, as bakes see it + pub fn merged_high(&self) -> Option<&MergedHigh> { + self.merged.as_ref() + } + pub(crate) fn rebuild(&mut self) { self.merged = (!self.high.is_empty()).then(|| { let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e5982f18..b65d6ac8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; +use super::{BakeCageInputs, MergedHigh}; use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; @@ -15,6 +16,7 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; +use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; @@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; + pub fn bake_task(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } @@ -112,31 +114,22 @@ impl Session { } else { Arc::new(Vec::new()) }; - let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { - Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) - } else { - None - }; - let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); - let skew = painted(BakePaintTarget::Skew)?; - let cage_paint = painted(BakePaintTarget::Cage)?; + + let high = self.bake_high(texture_set)?; + let cage = self.bake_cage(texture_set, high.is_some())?; + let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?; + let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?; + let grid = set.tile_grid(); let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); - let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; + let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, - ts, - mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { - Some(grid) => { - let mut mesh = (*self.source).clone(); - mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); - Arc::new(mesh) - } - None => self.mesh.clone(), - }, + ts: texture_set, + mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -151,6 +144,61 @@ impl Session { }) } + /// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file + pub fn bake_cage_inputs(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + let Some(high) = self.bake_high(texture_set)? else { return Ok(None) }; + let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) }; + + Ok(Some(BakeCageInputs { + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?, + cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?, + })) + } + + /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly + fn bake_high(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + } + + /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage + fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile { + return Ok(None); + } + + let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + Ok(Some(cage.mesh.clone())) + } + + /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly + fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() + } + + /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas + fn bake_mesh(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }) + } + /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 213e1ff6..16ff68a7 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod bake_cage_inputs; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -11,6 +12,7 @@ mod paint_command; mod preserve_tiles; mod tile_command; +pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..a145ccb2 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -107,6 +110,37 @@ impl Mesh { .collect() } + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + let bits = |position: Vec3| position.to_array().map(f32::to_bits); + (0..self.materials.len().max(1)) + .map(|material| { + // Each 3D edge (by position) with the vertex pairs of the triangles that use it, the lower position first + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue }; + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let side = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(side.0).or_default().push(side.1); + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + let mut seams: Vec<(u32, u32)> = sides + .into_values() + .filter(|pairs| pairs.iter().any(|&(from, to)| (uv(from), uv(to)) != (uv(pairs[0].0), uv(pairs[0].1)))) + .flat_map(|pairs| pairs.into_iter().map(|(from, to)| (from.min(to), from.max(to)))) + .collect(); + seams.sort_unstable(); + seams.dedup(); + seams + }) + .collect() + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -433,6 +467,26 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..8dbc4927 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,12 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly + +/// Which parts of the bake setup the 3D view draws +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, + /// Draw the cage, seams and low poly of only this texture set + pub only_set: Option, +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..3ed4f13f --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,9 @@ +/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs +pub(crate) struct CageGpu { + /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners` + pub(crate) topology: u64, + pub(crate) corners: wgpu::Buffer, + pub(crate) corner_count: u32, + pub(crate) edges: wgpu::Buffer, + pub(crate) edge_index_count: u32, +} diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs new file mode 100644 index 00000000..97da6861 --- /dev/null +++ b/crates/render/src/high_poly_gpu.rs @@ -0,0 +1,11 @@ +/// The high poly bake mode draws over the low poly +pub(crate) struct HighPolyGpu { + /// Which mesh the buffers hold + pub(crate) id: u64, + pub(crate) vertices: wgpu::Buffer, + pub(crate) vertex_count: usize, + pub(crate) indices: wgpu::Buffer, + pub(crate) index_count: u32, + /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it + pub(crate) missed: wgpu::Buffer, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c5ca2221..bb0967c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,12 +13,15 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_visualization; +mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; pub mod gpu_trace; #[cfg(not(target_arch = "wasm32"))] pub mod headless; +mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; pub mod readback; @@ -26,7 +29,9 @@ pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; +mod uv_seam_gpu; +pub use bake_visualization::BakeVisualization; 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/renderer.rs b/crates/render/src/renderer.rs index 4ce9dac3..a2da0223 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; +use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -173,6 +177,8 @@ pub struct Shade { /// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in /// the vertex shader at the height-to-normal strength. pub displacement: bool, + /// Bake mode's high poly, cage and UV seams over the 3D view + pub bake: Option, } /// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the @@ -259,6 +265,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -530,6 +537,11 @@ pub struct Renderer { wire3d_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, + /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams + bake_high_pipeline: wgpu::RenderPipeline, + cage_pipeline: wgpu::RenderPipeline, + cage_wire_pipeline: wgpu::RenderPipeline, + uv_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -563,6 +575,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + uv_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 { const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); +/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves +const SHADOW_SLOPE_BIAS: f32 = 1.5; + +/// Anisotropic filtering of the texture sets' sampler +const MAX_ANISOTROPY: u16 = 8; + +/// Size of the environment texture before the first environment loads +const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; + impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { let shader = |label: &str, source: &str| { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) }; - let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"))); + let module = + shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl"))); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl"))); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + + let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) }; - let globals_bgl = bgl( + let globals_bind_group_layout = bind_group_layout( "tc_globals", &[ uniform_entry(0), @@ -838,44 +865,47 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); - // The display textures, the aux texture, the sampler. + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; - // Displacement reads the height (and the sampler) in the vertex shader. - let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32; + // Displacement reads the height (and the sampler) in the vertex shader + let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) .map(tex_entry) .chain(std::iter::once(sampler_entry(textures))) - .map(|mut e| { - if e.binding == height || e.binding == textures { - e.visibility |= wgpu::ShaderStages::VERTEX; + .map(|mut entry| { + if entry.binding == height || entry.binding == textures { + entry.visibility |= wgpu::ShaderStages::VERTEX; } - e + entry }) .collect(); - let set_bgl = bgl("tc_set", &set_entries); - let refr_bgl = bgl("tc_refr", &[tex_entry(0)]); - let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); - let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]); - let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); - let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]); - let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { + let set_bind_group_layout = bind_group_layout("tc_set", &set_entries); + let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]); + let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); + let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]); + let effect_bind_group_layout = + bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); + let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]); + + let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 }) }; - let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]); - let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]); - let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]); - let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]); - let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]); - let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]); - let vb = [Some(wgpu::VertexBufferLayout { + let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]); + let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]); + let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]); + let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]); + let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]); + let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]); + + let vertex_layout = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode - // (e.g. RGBM) if WebGL2 without float color buffers turns out to matter. + + // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; - let hdr = |fs, blend| Some((fs, hdr_format, blend)); + let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); let mesh_pipeline = pipeline( device, @@ -883,8 +913,8 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_mesh", None), + &vertex_layout, + hdr_target("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); @@ -894,31 +924,103 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_opaque", None), + &vertex_layout, + hdr_target("fs_opaque", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); - let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); + let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); - let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); + let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("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 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()); + let wire3d_pipeline = + pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = pipeline( + device, + "tc_highlight", + &layout, + &module, + "vs_wire_highlight", + &vertex_layout, + hdr_target("fs_wire_highlight", blend), + MSAA, + wire3d_depth.clone(), + ); + + let [mesh_vertex_layout] = vertex_layout.clone(); + let high_layout = [ + mesh_vertex_layout, + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![4 => Float32], + }), + ]; + let bake_high_pipeline = pipeline( + device, + "tc_bake_high", + &background_layout, + &module, + "vs_bake_high", + &high_layout, + hdr_target("fs_bake_high", None), + MSAA, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let corner_layout = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let cage_pipeline = pipeline( + device, + "tc_cage", + &background_layout, + &module, + "vs_bake_cage", + &corner_layout, + hdr_target("fs_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let cage_wire_pipeline = pipeline( + device, + "tc_cage_wire", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_seam_pipeline = + pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); - let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); - let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] - .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = - pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); - let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); - let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); + let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); + let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { + pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None) + }); + let gbuffer_pipeline = pipeline( + device, + "tc_gbuf", + &mesh_layout, + &module, + "vs_mesh", + &vertex_layout, + hdr_target("fs_gbuf", None), + 1, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| { + pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None) + }); + let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("tc_dof_gather"), - layout: Some(&fx_layout), + layout: Some(&effect_layout), vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, @@ -932,20 +1034,23 @@ impl Renderer { multiview_mask: None, cache: None, }); + let shadow_depth = wgpu::DepthStencilState { - bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 }, + bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 }, ..depth_state(true, wgpu::CompareFunction::Less) }; - let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); - // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. + let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth)); + + // accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add, }; - let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); + let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); - let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None); + let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("tc_tex"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -953,7 +1058,7 @@ impl Renderer { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, - anisotropy_clamp: 8, + anisotropy_clamp: MAX_ANISOTROPY, ..Default::default() }); let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -972,7 +1077,8 @@ impl Renderer { compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); - let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor { + + let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_shadow"), size: std::mem::size_of::<[[f32; 4]; 5]>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -986,39 +1092,45 @@ impl Renderer { vp: Mat4::IDENTITY, bg: device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_shadow"), - layout: &shadow_bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }], + layout: &shadow_bind_group_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }], }), - buf: shadow_buf, + buf: shadow_buffer, }; + let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view; - let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor { + let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_refr_black"), - layout: &refr_bgl, + layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); - let mut r = Renderer { + let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + + let mut renderer = Renderer { target_format, hdr_format, - globals_bgl, - set_bgl, - blit_bgl, - mip_bgl, - fx_bgl, - refr_bgl, - refr_black, + globals_bgl: globals_bind_group_layout, + set_bgl: set_bind_group_layout, + blit_bgl: blit_bind_group_layout, + mip_bgl: mip_bind_group_layout, + fx_bgl: effect_bind_group_layout, + refr_bgl: refraction_bind_group_layout, + refr_black: refraction_black, mesh_pipeline, opaque_pipeline, uv_pipeline, wire_pipeline, wire3d_pipeline, highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + uv_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, bloom_pipelines, - gbuf_pipeline, + gbuf_pipeline: gbuffer_pipeline, sss_pipelines, dof_gather_pipeline, dof_pipeline, @@ -1038,13 +1150,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + uv_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), views: HashMap::new(), }; - r.set_environment(device, queue, "Studio Soft", None); - r + renderer.set_environment(device, queue, "Studio Soft", None); + renderer } pub fn environment_name(&self) -> &str { @@ -1124,6 +1239,79 @@ impl Renderer { self.content_rev += 1; } + /// Upload the high poly bake mode draws when `id` changed; `None` removes it + pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) { + if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) { + return; + } + + self.bake_high = mesh.map(|mesh| HighPolyGpu { + id, + vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX), + vertex_count: mesh.positions.len(), + indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX), + index_count: mesh.indices.len() as u32, + missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX), + }); + self.content_rev += 1; + } + + /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count + pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) { + let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return }; + + queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed)); + self.content_rev += 1; + } + + /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + if self.cages.len() <= texture_set { + self.cages.resize_with(texture_set + 1, || None); + } + let Some(slot) = self.cages.get_mut(texture_set) else { return }; + + match (cage, slot.as_mut()) { + (None, _) => *slot = None, + (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + } + (Some((corners, edges)), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), + corner_count: corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), + edge_index_count: (edges.len() * 2) as u32, + }); + } + } + self.content_rev += 1; + } + + /// Forget the cages of texture sets from `count` on (sets that were removed) + pub fn truncate_bake_cages(&mut self, count: usize) { + if self.cages.len() > count { + self.cages.truncate(count); + self.content_rev += 1; + } + } + + /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` + pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + let mut line_indices: Vec = Vec::new(); + let mut line_draws = Vec::new(); + for (material, edges) in seams.iter().enumerate() { + let start = line_indices.len() as u32; + line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to])); + line_draws.push((start, line_indices.len() as u32 - start, material)); + } + + let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + self.content_rev += 1; + } + /// Build the mesh's dense copy for displacement (once per mesh). fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let Some(m) = self.mesh.as_mut() else { return }; @@ -1889,30 +2077,30 @@ impl Renderer { self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` + /// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, encoder: &mut wgpu::CommandEncoder, - v: &ViewTargets, + targets: &ViewTargets, resolve: &wgpu::TextureView, - globals_bg: &wgpu::BindGroup, + globals_bind_group: &wgpu::BindGroup, frame: &Frame, - pipe: &wgpu::RenderPipeline, + mesh_pipeline: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, highlight: Option<(&wgpu::RenderPipeline, usize)>, - refr: &wgpu::BindGroup, + refraction_source: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("tc_view"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &v.msaa, + view: &targets.msaa, resolve_target: Some(resolve), depth_slice: None, ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &v.depth, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), stencil_ops: None, }), @@ -1920,33 +2108,86 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, globals_bg, &[]); + pass.set_bind_group(0, globals_bind_group, &[]); pass.set_pipeline(&self.bg_pipeline); pass.draw(0..3, 0..1); - let Some(m) = &self.mesh else { return }; - let uv_ts = match frame.kind { + let Some(mesh) = &self.mesh else { return }; + + let uv_set = match frame.kind { ViewKind::Scene => None, ViewKind::Uv { ts, .. } => Some(ts), }; - pass.set_bind_group(2, refr, &[]); - let geo = self.geometry(m, frame); - // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + pass.set_bind_group(2, refraction_source, &[]); + let geometry = self.geometry(mesh, frame); let (highlight, highlight_set) = highlight.unzip(); + let bake = frame.shade.bake.filter(|_| uv_set.is_none()); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); + let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), - (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), - (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (Some(mesh_pipeline).filter(|_| low_poly_shown), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), + (wire, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; - for (pipe, vb, ib, ranges, only, instances) in passes { - let Some(pipe) = pipe else { continue }; - pass.set_pipeline(pipe); - pass.set_vertex_buffer(0, vb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only) { + for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + let Some(pipeline) = pipeline else { continue }; + + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(ranges, &frame.visible, only_set) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..instances); } } + + if let Some(bake) = bake { + self.draw_bake(&mut pass, mesh, frame, bake); + } + } + + /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { + if bake.high_poly + && let Some(high) = &self.bake_high + { + pass.set_pipeline(&self.bake_high_pipeline); + pass.set_vertex_buffer(0, high.vertices.slice(..)); + pass.set_vertex_buffer(1, high.missed.slice(..)); + pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..high.index_count, 0, 0..1); + } + + if bake.uv_seams + && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } + + if !bake.cage { + return; + } + + let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); + let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..1985f980 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,88 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams + +struct BakeViewOut { + @builtin(position) clip: vec4, + @location(0) world_position: vec3, + @location(1) normal: vec3, + // 1 where the bake's rays miss the high poly, 0 where they reach it + @location(2) missed: f32, +}; + +const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); +const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); +const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); +const CAGE_OPACITY: f32 = 0.16; +const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); +const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); + +// Brightness of surfaces seen edge-on; facing the camera adds the rest +const HEADLIGHT_AMBIENT: f32 = 0.3; + +// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order +const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001; +const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002; + +// Lit from the camera: surfaces facing it are brightest +fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 { + let facing = abs(dot(normal, normalize(g.eye.xyz - world_position))); + return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing); +} + +fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 { + return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0); +} + +// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it +@vertex +fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = normal; + out.missed = missed; + return out; +} + +@fragment +fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { + let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); +} + +@vertex +fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = g.view_proj * vec4(position, 1.0); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +// The cage's own faces: their normal comes from the screen-space change of the position +@fragment +fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); + return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); +} + +// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces +@vertex +fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +@fragment +fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + return CAGE_WIRE_COLOR; +} + +@fragment +fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { + return UV_SEAM_COLOR; +} diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs new file mode 100644 index 00000000..0ac80dc9 --- /dev/null +++ b/crates/render/src/uv_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's UV seams as a line list over its vertex buffer +pub(crate) struct UvSeamGpu { + /// The low-poly mesh the lines belong to + pub(crate) mesh_id: u64, + pub(crate) lines: wgpu::Buffer, + /// (first index, count, material) per material + pub(crate) line_draws: Vec<(u32, u32, usize)>, +} diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..d148a268 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,8 +1,9 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,6 +43,9 @@ impl Img { } } +/// The id `setup` uploads the material ball under +const MESH_ID: u64 = 1; + /// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). fn setup() -> Option<(Headless, Frame)> { let Ok(mut h) = Headless::new() else { @@ -49,7 +53,7 @@ fn setup() -> Option<(Headless, Frame)> { return None; }; let mesh = primitives::material_ball(); - h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1); + h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); @@ -220,6 +224,73 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +#[test] +fn bake_visualization_draws_the_high_poly_and_the_cage() { + // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color + const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3; + const CAGE_SCALE: f32 = 2.5; + const HIGH_POLY_ID: u64 = 7; + const CAGE_TOPOLOGY: u64 = 1; + const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]]; + const COLOR_LEAD: i32 = 30; + + let Some((mut h, frame)) = setup() else { return }; + let ball = primitives::material_ball(); + let (low_min, low_max) = ball.bounds(); + let ball_center = (low_min + low_max) * 0.5; + let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16); + for position in &mut high.positions { + *position += ball_center; + } + h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID); + let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + let center = (frame.size[0] / 2, frame.size[1] / 2); + + let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); + let low_only = only(&mut h, bake, "bake_low_only"); + let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); + let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); + let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); + assert_same(&hidden, &background, "without the low poly only the background is left"); + let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]); + let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1)); + assert!( + caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue, + "the cage tints the ball tan: {:?} → {:?}", + [low_red, low_green, low_blue], + [caged_red, caged_green, caged_blue] + ); + + // Vertices the bake's rays miss turn red + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); + let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); + assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + + // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out + let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); + assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); + assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); + assert_ne!(first_set.px, second_set.px); + + // UV seams draw over the low poly + h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); + let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + + // A new distance with the same topology only moves the corners + let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + assert_ne!(caged.px, bigger.px, "the cage grew"); +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs new file mode 100644 index 00000000..42da4393 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,61 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::{icon_button_without_tooltip, section_chevron}; + +/// The panel's width and its gap from the 3D view's top-left corner +const PANEL_WIDTH: f32 = 280.0; +const PANEL_MARGIN: f32 = 12.0; + +/// Size of the panel's eye buttons +const EYE_BUTTON_SIZE: f32 = 22.0; + +/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` +pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let toggles = &mut app.ui.bake_visualization; + egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( + ui.ctx(), + |ui| { + ui.set_width(PANEL_WIDTH); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); + let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| { + ui.add_enabled_ui(toggles.on, |ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); + eye_row(ui, &mut toggles.cage, tr("Cage"), None); + eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); + eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); + }); + }); + }, + ); +} + +/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response +fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = match open { + Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), + None => egui::RichText::new(label), + }; + let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { + *shown = !*shown; + } + }); + response + }) + .inner +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs new file mode 100644 index 00000000..0603c523 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::BakeVisualization; + +/// The Baking Visualization panel's switches in bake mode's 3D view +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: the whole visualization on or off + pub on: bool, + pub selected_set_only: bool, + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these switches while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> Option { + self.on.then_some(BakeVisualization { + high_poly: self.high_poly, + cage: self.cage, + uv_seams: self.uv_seams, + low_poly: self.low_poly, + only_set: self.selected_set_only.then_some(selected_set), + }) + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3a308a4a..70dd4225 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,9 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; +pub(crate) use bake_visualization_panel::bake_visualization_panel; +pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; mod mesh_map_bakers; diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs new file mode 100644 index 00000000..1a30780e --- /dev/null +++ b/crates/ui-egui/src/bake_scene.rs @@ -0,0 +1,11 @@ +//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session + +mod bake_scene_link; +mod cage_link; +mod cage_shell_key; +mod cage_upload; +mod reach_link; +mod shared_handle; + +pub use bake_scene_link::BakeSceneLink; +pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs new file mode 100644 index 00000000..7f4459c6 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,213 @@ +use std::sync::Arc; + +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; +use texturecraft_render::BakeVisualization; + +use super::CageUpload; +use super::cage_link::CageLink; +use super::cage_shell_key::CageShellKey; +use super::reach_link::ReachLink; +use super::shared_handle::SharedHandle; +use crate::gpu::SceneSync; + +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +#[derive(Default)] +pub struct BakeSceneLink { + /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) + high: SharedHandle, + high_id: u64, + /// Whether the GPU has the high poly (a lost frame sends it again under the same id) + high_sent: bool, + cages: Vec>, + /// How many texture sets' cages the GPU was last told to keep + sent_cage_count: Option, + /// The low-poly mesh whose seams are uploaded + seams_mesh_id: Option, + next_topology: u64, + reach: ReachLink, +} + +impl BakeSceneLink { + /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay + pub fn resend(&mut self) { + self.high_sent = false; + self.sent_cage_count = None; + self.seams_mesh_id = None; + for link in self.cages.iter_mut().flatten() { + link.max_frontal = f32::NAN; + } + self.reach.resend(); + } + + /// Whether something is still being worked out off the UI thread + pub fn busy(&self) -> bool { + self.reach.busy() + } + + /// Add to `out` what the GPU needs to draw `visualization` this frame + pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + let Some(visualization) = visualization else { return }; + + if visualization.high_poly { + let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let handle = SharedHandle::of(high.as_ref()); + if handle != self.high { + self.high = handle; + self.high_id += 1; + self.high_sent = false; + } + if !self.high_sent { + out.bake_high = Some((high, self.high_id)); + self.high_sent = true; + } + self.reach.sync(session, self.high_id, visualization.only_set, out); + } + + if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + } + + if visualization.cage { + self.sync_cages(session, out); + } + } + + /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed + fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + if self.sent_cage_count != Some(set_count) { + out.bake_cage_count = Some(set_count); + self.sent_cage_count = Some(set_count); + } + self.cages.truncate(set_count); + self.cages.resize_with(set_count, || None); + + for (texture_set, link) in self.cages.iter_mut().enumerate() { + let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; + + let max_frontal = set.bake.cage.max_frontal; + match link { + Some(link) if link.key == key => { + if link.max_frontal == max_frontal { + continue; + } + link.max_frontal = max_frontal; + } + _ => { + self.next_topology += 1; + let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); + } + } + + let Some(link) = link.as_ref() else { continue }; + + let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() }); + out.bake_cages.push((texture_set, upload, link.topology)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + + /// The sample project with a high poly a little outside its low poly + fn session() -> Session { + const HIGH_POLY_OFFSET: f32 = 0.02; + + let mut session = texturecraft_engine::sample_session(128, 128).unwrap(); + let low = session.mesh.clone(); + let mut obj = String::new(); + for (position, normal) in low.positions.iter().zip(&low.normals) { + let raised = *position + *normal * HIGH_POLY_OFFSET; + obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z); + } + for corners in low.indices.chunks(3) { + obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1); + } + session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap(); + session + } + + fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync { + let mut out = SceneSync::default(); + link.sync(session, Some(visualization), &mut out); + out + } + + /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red + fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { + for _ in 0..2000 { + if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { + return missed.iter().sum::() / missed.len().max(1) as f32; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the reach never arrived"); + } + + fn set_distances(session: &mut Session, max_frontal: f32) { + texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap(); + } + + #[test] + fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + let first = sync(&mut link, &session, EVERYTHING); + assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + + let unchanged = sync(&mut link, &session, EVERYTHING); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + + set_distances(&mut session, 0.03); + let moved = sync(&mut link, &session, EVERYTHING); + let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + assert_eq!(moved_topology, topology, "a distance only moves the corners"); + assert_ne!(moved_cage.corners, cage.corners); + + texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); + let rebuilt = sync(&mut link, &session, EVERYTHING); + assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + + link.resend(); + let resent = sync(&mut link, &session, EVERYTHING); + assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); + assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); + assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); + assert!(!link.busy(), "a lost frame doesn't work out the reach again"); + } + + #[test] + fn the_red_follows_the_distances_and_the_selected_set() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + set_distances(&mut session, 0.0); + let at_zero = red_share(&mut link, &session, EVERYTHING); + assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); + + set_distances(&mut session, 0.05); + let covered = red_share(&mut link, &session, EVERYTHING); + assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); + + set_distances(&mut session, 0.0); + let by_name = |session: &mut Session, low_suffix: &str| { + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName; + set.bake.high_poly.low_suffix = low_suffix.into(); + } + }; + by_name(&mut session, "_no_such_suffix"); + let by_name_red = red_share(&mut link, &session, EVERYTHING); + assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); + + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; + assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs new file mode 100644 index 00000000..855d9619 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_link.rs @@ -0,0 +1,16 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; + +use super::cage_shell_key::CageShellKey; + +/// A texture set's cage as the GPU has it +pub(super) struct CageLink { + pub(super) key: CageShellKey, + /// `None`: the set bakes without a high poly or its cage can't be built + pub(super) shell: Option>, + /// The renderer's name for the shell's corner order and edges + pub(super) topology: u64, + /// The max frontal distance the GPU's corners are at + pub(super) max_frontal: f32, +} diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs new file mode 100644 index 00000000..44e17eca --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeMap; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::geom::Mesh; + +use super::shared_handle::SharedHandle; + +/// Everything a texture set's cage shell is built from except the distances, which only move its corners +#[derive(Clone, Debug, PartialEq)] +pub(super) struct CageShellKey { + mesh_id: u64, + high: SharedHandle, + cage_file: SharedHandle, + material: usize, + uv_tiles: Vec, + tile_resolutions: BTreeMap, + cage_kind: CageType, + relative_to_bounding_box: bool, + average_normals: bool, + use_low_as_high: bool, + skew: SkewSettings, + /// The painted skew and cage maps + paint: [SharedHandle; 2], +} + +impl CageShellKey { + pub(super) fn of(session: &Session, texture_set: usize) -> Option { + let set = session.doc.project.texture_sets.get(texture_set)?; + let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); + Some(CageShellKey { + mesh_id: session.mesh_id, + high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + material: set.material, + uv_tiles: set.uv_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + cage_kind: set.bake.cage.kind, + relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, + average_normals: set.bake.cage.average_normals, + use_low_as_high: set.bake.high_poly.use_low_as_high, + skew: set.bake.skew, + paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], + }) + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs new file mode 100644 index 00000000..81951645 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_upload.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; +use texturecraft_engine::geom::glam::Vec3; + +/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from +pub struct CageUpload { + pub corners: Vec, + pub shell: Arc, +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs new file mode 100644 index 00000000..45527522 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,100 @@ +use std::sync::mpsc::{Receiver, TryRecvError}; + +use rayon::prelude::*; +use texturecraft_engine::Session; +use texturecraft_engine::bake::HighPolyReach; +use texturecraft_engine::core::HighPolySettings; + +use super::cage_shell_key::CageShellKey; +use crate::gpu::SceneSync; + +/// Each set's (max frontal, max rear) and the selected-set filter +type ShownDistances = (Vec<(f32, f32)>, Option); + +/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show +#[derive(Default)] +pub(super) struct ReachLink { + /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for + keys: Vec>, + high_id: u64, + job: Option>>>, + reach: Vec>, + /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for + shown: Option, +} + +impl ReachLink { + /// Whether a reach is being worked out (the view must keep drawing to pick it up) + pub(super) fn busy(&self) -> bool { + self.job.is_some() + } + + /// Send the colors again (the GPU lost what it was sent); the reach itself stays + pub(super) fn resend(&mut self) { + self.shown = None; + } + + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed + pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + let keys: Vec> = session + .doc + .project + .texture_sets + .iter() + .enumerate() + .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) + .collect(); + if keys != self.keys || high_id != self.high_id { + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); + self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { + inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() + })); + (self.keys, self.high_id) = (keys, high_id); + } + + if let Some(job) = &self.job { + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + + // Colors wait for the reach being worked out: the old ones stay until it arrives + if self.job.is_some() { + return; + } + + let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect(); + let shown = (distances, only_set); + if self.shown.as_ref() == Some(&shown) { + return; + } + + let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + + // Each vertex is its nearest set's: other sets, and a set left out by the selected-set filter, never color it + let sets: Vec<(&HighPolyReach, f32, f32)> = self + .reach + .iter() + .zip(&shown.0) + .enumerate() + .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) + .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) + .collect(); + let missed: Vec = (0..vertex_count) + .into_par_iter() + .map(|vertex| { + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); + f32::from(u8::from(missed.unwrap_or(false))) + }) + .collect(); + out.bake_high_missed = Some((self.high_id, missed)); + self.shown = Some(shown); + } +} diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs new file mode 100644 index 00000000..15ceb1d8 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Weak}; + +/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it +#[derive(Debug)] +pub(super) struct SharedHandle(Option>); + +impl SharedHandle { + pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + SharedHandle(value.map(Arc::downgrade)) + } +} + +impl Clone for SharedHandle { + fn clone(&self) -> Self { + SharedHandle(self.0.clone()) + } +} + +impl Default for SharedHandle { + fn default() -> Self { + SharedHandle(None) + } +} + +impl PartialEq for SharedHandle { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(this), Some(other)) => Weak::ptr_eq(this, other), + (this, other) => this.is_none() && other.is_none(), + } + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index c6695b34..6bce1312 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,9 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; + +use crate::bake_scene::{BakeSceneLink, CageUpload}; /// Content shown through the aux texture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -25,6 +27,9 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); +/// The low poly's UV seam edges (vertex pairs) per material +pub type UvSeamEdges = Vec>; + /// What the renderer must catch up with before drawing. #[derive(Default)] pub struct SceneSync { @@ -36,6 +41,16 @@ pub struct SceneSync { pub env: Option<(String, Option>)>, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, pub aux: Vec<(usize, u32, Vec)>, + /// Bake mode's high poly (`None` removes it) and the id it is sent under + pub bake_high: Option<(Option>, u64)>, + /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) + pub bake_high_missed: Option<(u64, Vec)>, + /// Changed cages: texture set, the cage or `None` to remove it, its topology + pub bake_cages: Vec<(usize, Option, u64)>, + /// Texture sets left after some were removed: their cages go too + pub bake_cage_count: Option, + /// The low poly's UV seams per material, for mesh id + pub uv_seams: Option<(u64, UvSeamEdges)>, } /// Lives in egui's callback resources. @@ -78,6 +93,7 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + bake_scene: BakeSceneLink, } /// Compositing time per frame: a full recomposite of a large texture set spreads over frames. @@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + bake_scene: BakeSceneLink::default(), } } @@ -133,132 +150,158 @@ impl GpuLink { std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) } - /// Collect everything the GPU needs this frame (runs the compositor first). + /// Whether bake mode's visualization is still being worked out off the UI thread + pub fn bake_busy(&self) -> bool { + self.bake_scene.busy() + } + /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { let pending = s.pending_tiles(); (pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32) } - /// `spent_ms`: time this frame already took before the sync. - pub fn sync(&mut self, s: &mut Session, aux_map: Option, shift: u32, spent_ms: f64) -> SceneSync { - let start = crate::now_ms(); + /// 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 { + let start_ms = crate::now_ms(); let mut queued = 0usize; - let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE; - let pending = s.pending_tiles(); + 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) }; - s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).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) { self.mesh_id = 0; self.sets.clear(); self.env = Default::default(); + self.bake_scene.resend(); self.reset.store(true, Ordering::Release); } - if self.mesh_id != s.mesh_id { - out.mesh = Some((s.mesh.clone(), s.mesh_id)); - self.mesh_id = s.mesh_id; + + if self.mesh_id != session.mesh_id { + out.mesh = Some((session.mesh.clone(), session.mesh_id)); + self.mesh_id = session.mesh_id; self.aux.clear(); } - let sets: Vec = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect(); + + let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); if sets != self.sets || shift != self.shift || out.mesh.is_some() { - out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift)); + out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); self.sets = sets; self.shift = shift; } - let d = &s.doc.project.display; - let image = d.environment_resource().and_then(|n| s.images.get(n)); - let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize); - if self.env.0 != d.environment || self.env.1 != ptr { - self.env = (d.environment.clone(), ptr); - out.env = Some((d.environment.clone(), image.cloned())); + + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)); + let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize); + if self.env.0 != display.environment || self.env.1 != image_identity { + self.env = (display.environment.clone(), image_identity); + out.env = Some((display.environment.clone(), image.cloned())); } + if self.reset.swap(false, Ordering::AcqRel) { - for c in &mut s.caches { - c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1)); + for cache in &mut session.caches { + cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1)); } self.aux.clear(); } - for ts in 0..s.caches.len() { - let tiles = s.take_uploads(ts); + + for texture_set in 0..session.caches.len() { + let tiles = session.take_uploads(texture_set); if tiles.is_empty() { continue; } + let mut done = 0; - if let Some(cache) = s.caches.get(ts) { + if let Some(cache) = session.caches.get(texture_set) { let empty = Default::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&empty); - let comp = &cache.composite; - // In chunks while the frame has time (at least one chunk); the rest waits. + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let composite = &cache.composite; + // In chunks while the frame has time (at least one chunk); the rest waits for chunk in tiles.chunks(UPLOAD_CHUNK) { let bytes: Vec<_> = chunk .par_iter() - .flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty))) - .map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty))) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); done += chunk.len(); - if left(queued) < MIN_SLICE_MS { + if time_left_ms(queued) < MIN_SLICE_MS { break; } } } - if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) { + if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) { cache.upload.extend(rest.iter().copied()); } } + 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); - if self.aux.get(&ts) == Some(&key) { + Some(AuxView::MeshMap(map)) => { + for texture_set in 0..session.caches.len() { + let revision = session.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)).map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}"), revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let Some(cache) = s.caches.get(ts) else { continue }; + let Some(cache) = session.caches.get(texture_set) else { continue }; - let res = texturecraft_render::aux_size(cache.size); + let resolution = texturecraft_render::aux_size(cache.size); out.aux.push(( - ts, - res, - texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + texture_set, + resolution, + texturecraft_render::mesh_maps::mesh_map_rgba( + session.doc.baked.get(&texture_set), + map, + resolution, + cache.size, + &cache.composite.block_scales, + ), )); - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } Some(AuxView::Mask(id)) => { - if let Some((ts, _, _)) = s.doc.project.locate(id) { - let key = (format!("mask{}", id.0), s.revision); - if self.aux.get(&ts) != Some(&key) && !s.stroke_active() { - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - if let Some(rgba) = s.mask_view_rgba(id, res) { - out.aux.push((ts, res, rgba)); + if let Some((texture_set, _, _)) = session.doc.project.locate(id) { + let key = (format!("mask{}", id.0), session.revision); + if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { + let resolution = + session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); + if let Some(rgba) = session.mask_view_rgba(id, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } } Some(AuxView::QuickMask) => { - for ts in 0..s.caches.len() { - let Some(cache) = s.caches.get(ts) else { continue }; - let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision); - if self.aux.get(&ts) == Some(&key) { + for texture_set in 0..session.caches.len() { + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = s.quick_mask_rgba(ts, res) { - out.aux.push((ts, res, rgba)); + let resolution = texturecraft_render::aux_size(cache.size); + if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } None => {} } + + self.bake_scene.sync(session, bake, &mut out); out } } +/// Mask view resolution for a texture set without a composite cache +const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024; + /// Paint callback for one view. pub struct ViewCallback { pub frame: Frame, @@ -295,39 +338,58 @@ impl CallbackTrait for ViewCallback { if let Some((mesh, id)) = &sync.mesh { gpu.renderer.set_mesh(device, queue, mesh, *id); } - if let Some((sets, mats, shift)) = &sync.sets { + if let Some((sets, material_count, shift)) = &sync.sets { gpu.renderer.set_display_shift(*shift); - let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats); + let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count); if !reset.is_empty() { gpu.reset.store(true, Ordering::Release); } } - for (ts, k, tx, ty, bytes) in &sync.tiles { - gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); + for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles { + gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes); } - for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + for (texture_set, size, bytes) in &sync.aux { + gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes); + } + if let Some((high, id)) = &sync.bake_high { + gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id); + } + if let Some((id, missed)) = &sync.bake_high_missed { + gpu.renderer.set_bake_high_missed(queue, *id, missed); + } + if let Some(count) = sync.bake_cage_count { + gpu.renderer.truncate_bake_cages(count); + } + for (texture_set, cage, topology) in &sync.bake_cages { + let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.uv_seams { + gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); } } - // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + + // Also installs (or rejects) full-size textures WebGPU answered for since last frame gpu.renderer.prepare(device, queue, encoder, &self.frame); let failed = gpu.renderer.take_memory_failures(); if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for texture_set in failed { + if !reports.memory.contains(&texture_set) { + reports.memory.push(texture_set); } } - // This frame's report drain already ran: the next frame shows the toast. + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } if gpu.renderer.awaiting_gpu() { gpu.ctx.request_repaint(); } - let ppp = screen.pixels_per_point; - let r = self.rect; - gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); + + let pixels_per_point = screen.pixels_per_point; + let rect = self.rect; + let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point]; + gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels); Vec::new() } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..5487c415 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..ac1c709d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,9 @@ 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}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..07b0be27 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,9 @@ 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}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..0f5288c9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,9 @@ 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}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..e3956a8c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,9 @@ 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}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..089e77e4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..726e1c35 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..607c0c49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,9 @@ 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}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..5b47bd31 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..bd7591fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,6 +8,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod bake_scene; pub mod control; pub mod dock; pub mod docking; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..94958f61 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, + /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) + #[serde(default)] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { @@ -365,6 +368,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..82bd0258 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -296,30 +296,43 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { } fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); + let bake = bake_visualization(app); let scene = match (sync.0.take(), app.gpu.as_mut()) { - (Some(aux), Some(g)) => { - let t0 = crate::now_ms(); - let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); - let reports = g.take_reports(); - app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + (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)); + let reports = gpu_link.take_reports(); + app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); - // Display tiles left for later frames (the frame budget ran out). - if app.session.caches.iter().any(|c| !c.upload.is_empty()) { + + // Display tiles left for later frames (the frame budget ran out), or the bake visualization still being worked out + if app.session.caches.iter().any(|cache| !cache.upload.is_empty()) || app.gpu.as_ref().is_some_and(crate::gpu::GpuLink::bake_busy) { ui.ctx().request_repaint(); } Some(scene) } _ => None, }; + let Some(gpu) = &app.gpu else { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, tr("No GPU renderer available"), egui::FontId::proportional(14.0), tk.viewport_text); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("No GPU renderer available"), + egui::FontId::proportional(NO_GPU_TEXT_SIZE), + tokens.viewport_text, + ); return; }; - let cb = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; - ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); + + let callback = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; + ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, callback)); } +/// Text size of the notice a view shows without a GPU renderer +const NO_GPU_TEXT_SIZE: f32 = 14.0; + /// Width of the camera and view pickers centred at the top of a view const VIEW_HEADER_WIDTH: f32 = 300.0; @@ -617,7 +630,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + shade: Shade { highlight: drop_highlight(app, ui, &response), bake: bake_visualization(app), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); @@ -658,17 +671,30 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( - rect.left_top() + vec2(12.0, 40.0), + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, egui::Align2::LEFT_TOP, tr("Editing quick mask: paint where painting is allowed (U to finish)"), - egui::FontId::proportional(12.0), - Color32::from_rgb(0xe8, 0x6a, 0x6a), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, ); } + if app.ui.mode == crate::state::Mode::Baking { + crate::bake_mode::bake_visualization_panel(app, ui, rect); + } view_header(app, ui, rect, "v3d"); axis_gizmo(ui, rect, app, false); } +/// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red +const QUICK_MASK_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 40.0); +const QUICK_MASK_NOTICE_TEXT_SIZE: f32 = 12.0; +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() +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { From ca19e714a0cf76fd809f9abc47ef8cdc8d3d86e6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:51:56 +0000 Subject: [PATCH 19/76] Filter picker: swap a filter's type from its Properties slot effect.set takes filter: to swap a filter effect's type in place, keeping its place, blending, opacity and visibility (one undo step). A reusable resource_picker shows grouped, searchable shelf tiles at a slot; the filter slot uses it, and Add filter adds a neutral filter. --- crates/engine/src/filter_lib.rs | 7 ++ crates/engine/src/mask_cmds.rs | 96 +++++++++++----- crates/engine/tests/filter_swap.rs | 94 +++++++++++++++ crates/ui-egui/src/dock.rs | 126 ++++++++++----------- crates/ui-egui/src/filter_slot.rs | 83 ++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus.rs | 8 +- crates/ui-egui/src/resource_picker.rs | 126 +++++++++++++++++++++ crates/ui-egui/src/resource_picker_item.rs | 9 ++ crates/ui-egui/src/shelf.rs | 10 +- crates/ui-egui/tests/filter_picker.rs | 81 +++++++++++++ 20 files changed, 562 insertions(+), 99 deletions(-) create mode 100644 crates/engine/tests/filter_swap.rs create mode 100644 crates/ui-egui/src/filter_slot.rs create mode 100644 crates/ui-egui/src/resource_picker.rs create mode 100644 crates/ui-egui/src/resource_picker_item.rs create mode 100644 crates/ui-egui/tests/filter_picker.rs diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index f3168c9d..0f0fd952 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -19,6 +19,13 @@ pub struct FilterDef { pub mask: bool, } +impl FilterDef { + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) + pub fn is_filter_effect(&self) -> bool { + matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) + } +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..bd545fbc 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -413,55 +413,76 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } +/// Edits effect `effect`: visibility, blending, name, its kind's parameters, or a filter's type fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { + const CMD: &str = "effect.set"; + let effect = effect_id(s, p, CMD)?; + let blend = blend_param(CMD, p, "blend")?; + + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one + let anchor = match s.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; + let channel_param = channel_param(CMD, p, "anchorChannel")?; match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + Some(anchor) => Some(anchor_source(s, CMD, owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; + + let swapped = match strp(p, "filter") { + Some(filter) => Some(swapped_filter(s, effect, filter, p)?), + None => None, + }; + let swaps_filter = swapped.is_some(); + s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + let edited = s.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some((kind, label)) = swapped { + if let EffectKind::Filter(old) = &edited.kind + && edited.name == old.label() + { + edited.name = label.to_string(); + } + edited.kind = kind; } - if let Some(b) = blend { - e.blend = b; + + if let Some(visible) = boolp(p, "visible") { + edited.visible = visible; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(blend) = blend { + edited.blend = blend; } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(opacity) = f32p(p, "opacity") { + edited.opacity = opacity.clamp(0.0, 1.0); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + if let Some(name) = name_param(p) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => generator_from(p, generator), + EffectKind::Levels(levels) => levels_from(p, levels), + // The swapped filter was built with the parameters already + EffectKind::Filter(_) if swaps_filter => {} + EffectKind::Filter(filter) => crate::filter_lib::apply(p, filter, CMD)?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(p, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(p, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} @@ -471,6 +492,27 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Filter `id` built with `p` and its label, to replace filter effect `effect` +fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { + const CMD: &str = "effect.set"; + let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if !matches!(current.kind, EffectKind::Filter(_)) { + return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase()))); + } + + let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; + if !def.is_filter_effect() { + return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); + } + + let mask = s.doc.project.layer(owner)?.mask.as_ref(); + let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); + if on_mask && !def.mask { + return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); + } + Ok((crate::filter_lib::build(def.id, p)?, def.label)) +} + /// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { project.layers.values_mut().find_map(|l| { diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs new file mode 100644 index 00000000..87341c60 --- /dev/null +++ b/crates/engine/tests/filter_swap.rs @@ -0,0 +1,94 @@ +//! Swapping a filter effect's type in place through `effect.set {filter}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// A sphere project with its default layer selected +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() +} + +/// Runs effect-adding `command` and returns the new effect, which it selects +fn add(s: &mut Session, command: &str, params: Value) -> LayerId { + execute(s, command, ¶ms).unwrap(); + let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) }; + + added +} + +/// A copy of effect `id` +fn effect(s: &Session, id: LayerId) -> Effect { + s.doc.project.effect(id).unwrap().1.clone() +} + +/// Ids of the selected layer's content effects, bottom first +fn content_order(s: &Session) -> Vec { + let layer = s.selected_layer().unwrap(); + s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect() +} + +#[test] +fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert_eq!(blur.name, "Blur", "a default name follows the new filter"); + assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); + assert_eq!(content_order(&s), vec![below, swapped, above]); +} + +#[test] +fn swapping_a_filter_keeps_a_name_the_user_chose() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + + assert_eq!(effect(&s, id).name, "Flip"); +} + +#[test] +fn one_undo_restores_the_old_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + let restored = effect(&s, id); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert_eq!(restored.name, "Threshold"); +} + +#[test] +fn a_mask_refuses_a_content_only_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + + assert!(err.to_string().contains("not on masks"), "{err}"); + assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn only_filter_effects_swap_and_only_to_filters() { + let mut s = session(); + let levels = add(&mut s, "effect.add.levels", json!({"target": "content"})); + let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); + assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..13604e91 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,7 +8,7 @@ use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; +use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -19,6 +19,13 @@ 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}; +/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +const NEW_FILTER: &str = "hsl"; +const FILTER_SWATCH_WIDTH: f32 = 36.0; +const FILTER_HINT_SIZE: f32 = 10.5; +/// The most colors `effect.set {colors}` takes for a gradient map +const MAX_GRADIENT_STOPS: usize = 16; + const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -208,48 +215,34 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go -/// to the content when it is the selected target; generators and compare always go to the -/// mask, anchor points to the content. +/// "Add effect" items for `layer`: content when it is the selected target, else the mask fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let t = if content { "content" } else { "mask" }; + let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); + + // Generators and compare masks always go to the mask, anchor points to the content let items = [ (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": t})), - (tr("Add fill"), "effect.add.fill", json!({"target": t})), - (tr("Add levels"), "effect.add.levels", json!({"target": t})), + (tr("Add paint"), "effect.add.paint", json!({"target": target})), + (tr("Add fill"), "effect.add.fill", json!({"target": target})), + (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), + (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), (tr("Add anchor point"), "effect.add.anchor", json!({})), ]; - let run = |app: &mut TextureCraftApp, id: &str, p: &Value| { + for (label, command, params) in items { + let enabled = command != "effect.add.anchor" || !layer.is_group(); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(id, with(p, json!({"layer": layer.id.0}))); - }; - for (label, id, p) in items { - let enabled = id != "effect.add.anchor" || !layer.is_group(); - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - run(app, id, &p); - ui.close(); - } + app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + ui.close(); } - // The filter library (material finishes only fill content). - ui.menu_button(tr("Add filter"), |ui| { - let mut group = ""; - for f in FILTERS.iter().filter(|f| content || f.mask) { - if f.group != group { - ui.label(caption(tr(f.group))); - group = f.group; - } - if ui.button(tr(f.label)).clicked() { - run(app, "effect.add.filter", &json!({"target": t, "filter": f.id})); - ui.close(); - } - } - }); } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { @@ -2058,82 +2051,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye } } -/// The parameters of filter effect `id`. -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { +/// The filter slot and the parameters of filter effect `id` +fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| { - let mut p = json!({ "effect": id, "merge": merge }); - p[key] = v; - app.run("effect.set", p); + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); }; - ui.label(caption(tr(f.label()))); - if let Filter::Hsl { hue, .. } = f { - let mut h = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { - set(app, "hue", json!(h / 360.0), merge); + crate::filter_slot::show(app, ui, id, filter); + + if let Filter::Hsl { hue, .. } = filter { + let mut degrees = hue * 360.0; + if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { + set(app, "hue", json!(degrees / 360.0), merge); } } - for (key, label, mut v, lo, hi) in scalar_params(f) { + + for (key, label, mut value, min, max) in scalar_params(filter) { let decimals = if matches!(key, "seed" | "levels") { 0 - } else if hi - lo > 10.0 { + } else if max - min > 10.0 { 1 } else { 2 }; - if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { - set(app, key, json!(v), merge); + if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { + set(app, key, json!(value), merge); } } - match f { + + match filter { Filter::ColorBalance { shadows, midtones, highlights } => { for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] { ui.label(RichText::new(label).strong()); - let mut v = *rgb; + let mut balance = *rgb; let mut edit = None; - for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2)); + for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { + edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); } if let Some(merge) = edit { - set(app, key, json!(v), merge); + set(app, key, json!(balance), merge); } } } Filter::ReplaceColor { from, to, .. } => { for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut v = *rgb; + let mut color = *rgb; ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { - set(app, key, json!(v), false); + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { + set(app, key, json!(color), false); } ui.label(label); }); } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::GradientMap { colors } => { - let mut c = colors.clone(); + let mut stops = colors.clone(); let mut changed = false; ui.horizontal_wrapped(|ui| { - for (i, col) in c.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0); + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); } }); ui.horizontal(|ui| { - if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - c.push(c.last().copied().unwrap_or([1.0; 3])); + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); changed = true; } - if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - c.pop(); + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); changed = true; } }); if changed { - set(app, "colors", json!(c), false); + set(app, "colors", json!(stops), false); } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::Warp { .. } | Filter::DirectionalBlur { .. } @@ -2144,7 +2140,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter | Filter::Bevel { .. } | Filter::Mosaic { .. } | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } _ => {} } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs new file mode 100644 index 00000000..7a143612 --- /dev/null +++ b/crates/ui-egui/src/filter_slot.rs @@ -0,0 +1,83 @@ +//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it + +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Filter, LayerId}; +use texturecraft_engine::filter_lib::{FILTERS, find}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; + +/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { + let ctx = ui.ctx().clone(); + let on_mask = is_on_mask(app, effect); + let current = find(filter.label()).map(|def| def.id); + let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); + let name = tr(filter.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); + + let popup = ui.make_persistent_id(("filter_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let items = |thumbs: &mut Thumbs| { + FILTERS + .iter() + .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) + .collect() + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("effect.set", json!({"effect": effect, "filter": id})); + } +} + +/// Whether filter effect `effect` sits in a mask rather than the layer content +fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { + let project = &app.session.doc.project; + let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); + owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) +} + +/// The slot's box: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + + if let Some(texture) = thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + let center = rect.center(); + painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); + painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + + let caret_color = if hovered { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..c61f4ce3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -304,6 +304,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "تعبئة"), ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), @@ -677,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..18a2c94b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -328,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Füllung"), ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), @@ -716,6 +717,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..e0c7842b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Relleno"), ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), @@ -704,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..20209ab5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -331,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Remplissage"), ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), @@ -722,6 +723,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..8388adcc 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -325,6 +325,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Riempimento"), ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), @@ -713,6 +714,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b20c9d55 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -316,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "塗りつぶし"), ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), @@ -695,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..9837b49f 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -313,6 +313,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "채우기"), ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), ("Filters", "필터"), ("Fine noise", "미세 노이즈"), @@ -686,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7badff49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Preenchimento"), ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), @@ -701,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..4afec91d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -286,6 +286,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "填充"), ("Fill the closed path (lasso)", "填充闭合路径(套索)"), ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), ("Filters", "滤镜"), ("Fine noise", "细噪波"), @@ -647,6 +648,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..4db0acd7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; @@ -26,6 +27,8 @@ mod preview_worker; pub mod profile; pub mod properties_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; pub mod shelf; pub mod shelf_preview; pub mod state; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..3f645eeb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -305,6 +305,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } +/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture 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; @@ -319,6 +320,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } + // Escape closes an open popup first, before the Properties popup or the stroke + let popup_open = egui::Popup::is_any_open(ctx); + let active_shortcuts = crate::keymap::active(&app.ui.keymap); let mut commands_to_invoke: Vec<&str> = Vec::new(); ctx.input_mut(|input| { @@ -337,9 +341,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } 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(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs new file mode 100644 index 00000000..5b119c2f --- /dev/null +++ b/crates/ui-egui/src/resource_picker.rs @@ -0,0 +1,126 @@ +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name + +use egui::{Id, Response, Stroke, Ui}; + +use crate::i18n::tr; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +/// Four shelf tiles and the scrollbar +const PICKER_WIDTH: f32 = 320.0; +/// The grid's height, fixed so the popup keeps its place while searching +const PICKER_HEIGHT: f32 = 340.0; +const CURRENT_OUTLINE_WIDTH: f32 = 1.5; +const TILE_ROUNDING: f32 = 3.0; + +/// Opens the picker `popup_id` with an empty, focused search field, or closes it +pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { + if egui::Popup::is_id_open(ctx, popup_id) { + egui::Popup::close_id(ctx, popup_id); + return; + } + + egui::Popup::open_id(ctx, popup_id); + ctx.data_mut(|data| { + data.insert_temp(search_id(popup_id), String::new()); + data.insert_temp(focus_id(popup_id), true); + }); +} + +/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) +pub(crate) fn show( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + current: Option<&str>, + items: impl FnOnce(&mut Thumbs) -> Vec, + preview: impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let items = items(thumbs); + let mut picked = None; + egui::Popup::from_response(slot) + .id(popup_id) + .open_memory(None) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(PICKER_WIDTH) + .show(|ui| { + ui.set_width(PICKER_WIDTH); + let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let query = search_field(ui, popup_id, just_opened); + egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(PICKER_HEIGHT); + picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + }); + }); + + if picked.is_some() { + egui::Popup::close_id(&ctx, popup_id); + } + picked +} + +/// The search field, focused the frame the picker opens; returns the lowercase query +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); + let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY)); + if just_opened { + field.request_focus(); + } + + let query = search.trim().to_lowercase(); + ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + query +} + +/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked +fn grid( + ui: &mut Ui, + thumbs: &mut Thumbs, + items: &[ResourcePickerItem], + query: &str, + current: Option<&str>, + reveal_current: bool, + preview: &impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let tk = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); + let mut picked = None; + for group in shelf::categories(&shown, |item| item.group) { + shelf::header(ui, group); + shelf::tiles(ui, |ui| { + for item in shown.iter().filter(|item| item.group == group) { + let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); + if current == Some(item.id) { + if reveal_current { + response.scroll_to_me(Some(egui::Align::Center)); + } + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(item.id); + } + } + }); + } + picked +} + +/// Where the picker keeps its search text +fn search_id(popup_id: Id) -> Id { + popup_id.with("search") +} + +/// Set while the picker waits for its first frame open +fn focus_id(popup_id: Id) -> Id { + popup_id.with("focus") +} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs new file mode 100644 index 00000000..5b9e8071 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -0,0 +1,9 @@ +//! One choice offered by a resource picker + +/// A resource the picker offers: its id, translated label and group, and its thumbnail +pub(crate) struct ResourcePickerItem { + pub id: &'static str, + pub label: &'static str, + pub group: &'static str, + pub thumbnail: Option, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..55ef400f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -266,7 +266,7 @@ fn drag_preview(ctx: &egui::Context) { p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); } -fn matches(filter: &str, texts: &[&str]) -> bool { +pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -275,13 +275,13 @@ fn title(ui: &mut Ui, text: &str) { ui.label(RichText::new(text).strong().color(tk.text_strong)); } -fn header(ui: &mut Ui, text: &str) { +pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); ui.label(RichText::new(text).size(11.0).color(tk.text_dim)); } -fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { +pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); body(ui); @@ -290,7 +290,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { } /// The distinct categories of `items`, in order of first appearance. -fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { +pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); for c in items.iter().map(category) { if !out.contains(&c) { @@ -586,7 +586,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// Asset tile with optional dragging and a larger hover preview -fn tile( +pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, tex: Option<&egui::TextureHandle>, diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs new file mode 100644 index 00000000..31daef69 --- /dev/null +++ b/crates/ui-egui/tests/filter_picker.rs @@ -0,0 +1,81 @@ +//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot +fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { + harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() +} + +/// Clicks the Invert slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_filter() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // The picker's search field has the focus as it opens + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); + + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn escape_closes_the_picker_without_changes() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // Without the search field's focus, the painting shortcuts see Escape first + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn add_filter_adds_a_filter_and_selects_it() { + let (mut harness, _) = app_with_invert(); + harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.run_steps(3); + + harness.get_by_label("Add filter").click(); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); +} From c827d1b910c0a8eb625d396289989e148244c30d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:48:32 +0000 Subject: [PATCH 20/76] 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 a1d010ccb2f131c867f4551f1d12f1fa47911052 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:20:33 +0000 Subject: [PATCH 21/76] Curvature generators: mode and detail sizes Curvature and edge wear generators read the baked curvature map one texel at a time, so they only marked the sharpest edges. They now take a mode (edges, cavities, both, raw) and seven detail size weights: the map itself and the map blurred at 1 to 32 texels at 2K, padded past the UV islands and built once per map and layout. Each size's edges and cavities combine like a screen blend. New curvature and edge wear generators use detail sizes. Generators saved without them, and smart masks, read the map exactly as before. --- crates/compose/src/curvature_size_level.rs | 42 ++++ crates/compose/src/curvature_sizes.rs | 133 +++++++++++++ crates/compose/src/eval.rs | 215 +++++++++++++++------ crates/compose/src/lib.rs | 2 + crates/core/src/layer.rs | 31 ++- crates/core/src/layer/curvature_detail.rs | 22 +++ crates/core/src/layer/curvature_mode.rs | 34 ++++ crates/core/src/lib.rs | 5 +- crates/engine/src/inspect.rs | 59 +++--- crates/engine/src/mask_cmds.rs | 140 ++++++++------ crates/engine/src/smart_masks.rs | 6 +- crates/engine/tests/session.rs | 20 ++ crates/ui-egui/src/dock.rs | 185 +++++++++++------- crates/ui-egui/src/i18n/ar.rs | 9 + crates/ui-egui/src/i18n/de.rs | 9 + crates/ui-egui/src/i18n/es.rs | 9 + crates/ui-egui/src/i18n/fr.rs | 9 + crates/ui-egui/src/i18n/it.rs | 9 + 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 | 6 + 22 files changed, 753 insertions(+), 219 deletions(-) create mode 100644 crates/compose/src/curvature_size_level.rs create mode 100644 crates/compose/src/curvature_sizes.rs create mode 100644 crates/core/src/layer/curvature_detail.rs create mode 100644 crates/core/src/layer/curvature_mode.rs diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs new file mode 100644 index 00000000..aa09d747 --- /dev/null +++ b/crates/compose/src/curvature_size_level.rs @@ -0,0 +1,42 @@ +/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers. +pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0; + +/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map. +pub struct CurvatureSizeLevel { + pub step: u32, + pub width: u32, + pub height: u32, + pub deviation: Vec, +} + +impl CurvatureSizeLevel { + /// The deviation at map texel `(x, y)`, bilinear between the stored texels. + pub fn sample(&self, x: u32, y: u32) -> f32 { + if self.width == 0 || self.height == 0 { + return 0.0; + } + + let to_level = |texel: u32| (texel as f32 + 0.5) / self.step as f32 - 0.5; + let (level_x, level_y) = (to_level(x).max(0.0), to_level(y).max(0.0)); + let (x0, y0) = ((level_x.floor() as u32).min(self.width - 1), (level_y.floor() as u32).min(self.height - 1)); + let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1)); + let (blend_x, blend_y) = (level_x - x0 as f32, level_y - y0 as f32); + let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE); + let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x; + let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x; + top + (bottom - top) * blend_y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_blend_the_stored_texels() { + let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] }; + assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1"); + assert!((level.sample(3, 0) - 0.25).abs() < 1e-3); + assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends"); + } +} diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs new file mode 100644 index 00000000..c2dfe755 --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,133 @@ +//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. + +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; +use crate::eval::{Inputs, blur}; + +/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +pub struct CurvatureSizes { + pub levels: Vec, +} + +/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. +type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl CurvatureSizes { + /// The sizes of the texture set `inp` composites (None without a baked curvature map). + pub fn of(inp: &Inputs) -> Option> { + let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); + let working_size = (inp.gbuf.width, inp.gbuf.height); + + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); + let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { + same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales + }); + if let Some((.., sizes)) = cached { + return Some(sizes.clone()); + } + + // Covered working texels mark where they land in the bake atlas + let mut covered = vec![false; (width * height) as usize]; + for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + *slot = true; + } + } + } + + let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); + cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); + Some(sizes) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. + fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); + let deviation: Vec = + padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); + let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); + + let levels = CurvatureDetail::SIZES + .iter() + .skip(1) + .map(|size| { + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser + let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; + let step = (radius / 2).max(1).next_power_of_two(); + + let mut blurred = deviation.clone(); + for block_y in (0..height).step_by(block_height as usize) { + for block_x in (0..width).step_by(block_width as usize) { + let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y)); + blur_block(&mut blurred, width, region, radius); + } + } + coarsen(&blurred, (width, height), step) + }) + .collect(); + CurvatureSizes { levels } + } +} + +/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { + let mut block: Vec = + (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, w as usize, h as usize, radius as usize); + + for (row, values) in block.chunks(w as usize).enumerate() { + let start = ((y0 + row as u32) * width + x0) as usize; + if let Some(target) = data.get_mut(start..start + values.len()) { + target.copy_from_slice(values); + } + } +} + +/// `data` averaged over `step × step` squares (the last ones clipped to the map). +fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { + let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); + let deviation = (0..coarse_width * coarse_height) + .into_par_iter() + .map(|cell| { + let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width); + let columns = cell_x * step..((cell_x + 1) * step).min(width); + let rows = cell_y * step..((cell_y + 1) * step).min(height); + let count = (columns.len() * rows.len()).max(1) as f32; + let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize)); + let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::() / count; + (mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16 + }) + .collect(); + CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, deviation } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn padding_keeps_an_island_border_from_reading_flat() { + let left_half = |texel: u32| texel % 64 < 32; + let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..64 * 64).map(left_half).collect(); + let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); + for level in &sizes.levels { + assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..412cfe58 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,17 +4,20 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, + blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level}; +use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -204,6 +207,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, + /// The curvature detail sizes a generator with detail reads. + curvature_sizes: Option>, } struct MaskPlan<'a> { @@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] { [cs, -sn] } +/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white). +const MAP_GAIN: f32 = 2.0; + +/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength. +const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; + /// Samples along a directional or slope blur at most (beyond, samples spread out). const LINE_SAMPLES: i32 = 24; @@ -423,7 +434,7 @@ const FIX: f64 = (1u64 << 24) as f64; /// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. /// Rows (and columns, transposed) blur in parallel. -fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { +pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; let mut v: Vec = data.par_iter().map(fix).collect(); blur_rows(&mut v, w, r); @@ -808,12 +819,14 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), }; + let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { kind: &e.kind, blend: e.blend, opacity: e.opacity, data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, preview: previews(inp, target), + curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } }) .collect() @@ -1166,94 +1179,130 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, g: &Generator) -> f32 { - let c = self.coords(); - let s = match g.kind { - GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5), - GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), - GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let coords = self.coords(); + let signal = match (generator.kind, &generator.detail) { + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), + (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + let signal = if generator.noise_amount > 0.0 { + signal + (world_noise(coords.pos, generator.noise_scale, generator.seed) - 0.5) * generator.noise_amount + } else { + signal + }; + + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(1e-3); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + let value = ramp * ramp * (3.0 - 2.0 * ramp); + if generator.invert { 1.0 - value } else { value } } - fn mask(&mut self, m: &MaskPlan) -> f32 { - let mut v = m.background; - let mut skip = 0; - if let Some((k, field)) = m.start - && let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied()) - { - v = f; - skip = k + 1; + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); + let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let (mut edges, mut cavities) = (0.0f32, 0.0f32); + for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { + let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; + + let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size }; + let weight = weight.clamp(0.0, 1.0); + edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0)); + cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } + } + + fn mask(&mut self, plan: &MaskPlan) -> f32 { + let mut value = plan.background; + let mut skip = 0; + if let Some((filtered_index, field)) = plan.start + && let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied()) + { + value = filtered; + skip = filtered_index + 1; + } + + for effect in plan.effects.iter().skip(skip) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut pv, mut cov) = match e.data.as_deref() { - Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), + let (mut painted, mut cov) = match effect.data.as_deref() { + Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; - if e.preview - && let Some(p) = self.inp.preview + if effect.preview + && let Some(preview) = self.inp.preview { - let a = (self.stroke * p.opacity).clamp(0.0, 1.0); - if p.erase { - pv *= 1.0 - a; - cov *= 1.0 - a; + let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + if preview.erase { + painted *= 1.0 - stroke; + cov *= 1.0 - stroke; } else { - pv = p.mask_value * a + pv * (1.0 - a); - cov = a + cov * (1.0 - a); + painted = preview.mask_value * stroke + painted * (1.0 - stroke); + cov = stroke + cov * (1.0 - stroke); } } if cov > 0.0 { - let val = pv / cov.max(1e-5); - v += (blend1(e.blend, v, val) - v) * cov * o; + let layer_value = painted / cov.max(1e-5); + value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; } } EffectKind::Fill { source, projection } => { - let val = self.source(source, projection, ChannelKind::Scalar)[0]; - v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection); + let fill = self.source(source, projection, ChannelKind::Scalar)[0]; + value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); } - EffectKind::Generator(g) => { - let val = self.generator(g); - v += (blend1(e.blend, v, val) - v) * o; + EffectKind::Generator(generator) => { + let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + value += (blend1(effect.blend, value, generated) - value) * opacity; } - EffectKind::Levels(l) => v += (l.apply(v) - v) * o, - EffectKind::Filter(f) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come - // precomputed through `MaskPlan::start`. - let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]); - v += (val - v) * o; + EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter) => { + // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` + let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + value += (filtered - value) * opacity; } EffectKind::ColorSelection { colors, tolerance } => { let id = self.baked_color(BakedMap::Id); - let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); - let val = if hit { 1.0 } else { 0.0 }; - v += (blend1(e.blend, v, val) - v) * o; + let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); + let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; + value += (blend1(effect.blend, value, selected) - value) * opacity; } - EffectKind::Compare { op, value, tolerance } => { + EffectKind::Compare { op, value: compared, tolerance } => { let pass = match op { - CompareOp::LesserThan => v < *value, - CompareOp::GreaterThan => v > *value, - CompareOp::WithinTolerance => (v - value).abs() <= *tolerance, + CompareOp::LesserThan => value < *compared, + CompareOp::GreaterThan => value > *compared, + CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, }; - let val = if pass { 1.0 } else { 0.0 }; - v += (val - v) * o; + let result = if pass { 1.0 } else { 0.0 }; + value += (result - value) * opacity; } - // Content-only effects. + // Content-only effects EffectKind::Material(_) | EffectKind::Anchor => {} } } - v.clamp(0.0, 1.0) + value.clamp(0.0, 1.0) } /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` @@ -2455,6 +2504,44 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); + fixture.project.texture_sets[0].resolution = 256; + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + }; + + // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth + let (ridge, five_texels_away) = (8, 3); + let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); + assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 01365a27..fe57e611 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -9,6 +9,8 @@ mod baked_maps; pub mod below; +mod curvature_size_level; +pub mod curvature_sizes; pub mod display; pub mod eval; pub mod pattern; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 551c9803..19c82f61 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize}; use crate::{BlendMode, Channel, ChannelKind, lum}; +mod curvature_detail; +mod curvature_mode; + +pub use curvature_detail::CurvatureDetail; +pub use curvature_mode::CurvatureMode; + /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct LayerId(pub u64); @@ -540,17 +546,27 @@ pub struct Generator { /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, + /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, } impl Generator { pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { - GeneratorKind::EdgeWear => (0.6, 0.12, 0.5), + GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), + GeneratorKind::Curvature => (0.5, 0.5, 0.0), GeneratorKind::Dirt => (0.55, 0.25, 0.35), GeneratorKind::ThinAreas => (0.3, 0.2, 0.0), _ => (0.5, 0.25, 0.0), }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false } + let detail = match kind { + GeneratorKind::Curvature => Some(CurvatureDetail::default()), + // Worn edges are thin lines: mostly the finer sizes + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + _ => None, + }; + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } } } @@ -1050,6 +1066,17 @@ impl Effect { mod tests { use super::*; + #[test] + fn curvature_generators_saved_before_detail_sizes_load_without_them() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes"); + + saved.as_object_mut().unwrap().remove("detail"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.detail, None); + assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs new file mode 100644 index 00000000..f843eac9 --- /dev/null +++ b/crates/core/src/layer/curvature_detail.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +use super::curvature_mode::CurvatureMode; + +/// How a curvature generator reads the curvature map: its mode and how much each detail size adds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurvatureDetail { + pub mode: CurvatureMode, + /// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first. + pub weights: [f32; CurvatureDetail::SIZES.len()], +} + +impl CurvatureDetail { + /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. + pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; +} + +impl Default for CurvatureDetail { + fn default() -> Self { + CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + } +} diff --git a/crates/core/src/layer/curvature_mode.rs b/crates/core/src/layer/curvature_mode.rs new file mode 100644 index 00000000..a4183e7a --- /dev/null +++ b/crates/core/src/layer/curvature_mode.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// Which side of the curvature map a curvature generator shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum CurvatureMode { + /// Convex edges white. + #[default] + Edges, + /// Concave cavities white. + Cavities, + /// Edges and cavities both white. + Both, + /// Signed curvature around mid gray (cavities dark, edges light). + Raw, +} + +impl CurvatureMode { + pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw]; + + pub fn label(self) -> &'static str { + match self { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Edges and cavities", + CurvatureMode::Raw => "Raw curvature", + } + } + + /// The mode named `name` (its variant or label, any case). + pub fn parse(name: &str) -> Option { + let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 72adf044..75ea2405 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,8 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, - LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, + LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, + hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 347b7390..ae73a3a7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; use crate::Session; use crate::session::StackTarget; @@ -34,38 +34,45 @@ fn fill_json(f: &Fill) -> Value { } /// A mask or content (`content`) effect. -fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { - let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity }); - match &e.kind { - EffectKind::Generator(g) => { - ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) - } - EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), +fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { + let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); + let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); + let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); + + match &effect.kind { + EffectKind::Generator(generator) => out["generator"] = generator_json(generator), + EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), EffectKind::Path(paths) => { - ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::>()); - ej["tiles"] = json!(if content { - s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::() - } else { - s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0) - }); + out["paths"] = json!( + paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::>() + ); + out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() }); } - EffectKind::Paint if content => { - ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::()) - } - EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)), - EffectKind::Fill { source, .. } => ej["source"] = source_json(source), - EffectKind::Material(f) => ej["fill"] = fill_json(f), - EffectKind::Filter(f) => { - ej["filter"] = json!(f); - match f { - Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]), - Filter::Blur { radius } => ej["radius"] = json!(radius), + EffectKind::Paint if content => out["tiles"] = json!(content_tiles()), + EffectKind::Paint => out["tiles"] = json!(mask_tiles()), + EffectKind::Fill { source, .. } => out["source"] = source_json(source), + EffectKind::Material(fill) => out["fill"] = fill_json(fill), + EffectKind::Filter(filter) => { + out["filter"] = json!(filter); + match filter { + Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius } => out["radius"] = json!(radius), _ => {} } } _ => {} } - ej + out +} + +/// A generator's settings, with its curvature mode and detail size weights when it has them. +fn generator_json(generator: &Generator) -> Value { + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert }); + if let Some(detail) = &generator.detail { + out["mode"] = json!(format!("{:?}", detail.mode)); + out["sizes"] = json!(detail.weights); + } + out } fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..41cecca8 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Project, Source, + BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -314,39 +314,67 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { push_effect(s, p, EffectKind::Fill { source, projection }, blend) } -fn generator_from(p: &Value, g: &mut Generator) { - if let Some(v) = f32p(p, "level") { - g.level = v.clamp(0.0, 1.0); +/// Apply the generator parameters in `params` to `generator` (`command` names it in errors). +fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if let Some(level) = f32p(params, "level") { + generator.level = level.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "softness") { - g.softness = v.clamp(0.0, 1.0); + if let Some(softness) = f32p(params, "softness") { + generator.softness = softness.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "noise") { - g.noise_amount = v.clamp(0.0, 2.0); + if let Some(noise) = f32p(params, "noise") { + generator.noise_amount = noise.clamp(0.0, 2.0); } - if let Some(v) = f32p(p, "noiseScale") { - g.noise_scale = v.clamp(0.01, 1000.0); + if let Some(noise_scale) = f32p(params, "noiseScale") { + generator.noise_scale = noise_scale.clamp(0.01, 1000.0); } - if let Some(v) = u64p(p, "seed") { - g.seed = v as u32; + if let Some(seed) = u64p(params, "seed") { + generator.seed = seed as u32; } - if let Some(v) = boolp(p, "invert") { - g.invert = v; + if let Some(invert) = boolp(params, "invert") { + generator.invert = invert; } - if let Some(d) = color_param(p, "direction") { - g.direction = d; + if let Some(direction) = color_param(params, "direction") { + generator.direction = direction; } + + // A mode or sizes also give a curvature generator saved before detail sizes its detail + let mode = + strp(params, "mode").map(|name| CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))).transpose()?; + let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?; + if mode.is_none() && weights.is_none() { + return Ok(()); + } + if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes")); + } + + let detail = generator.detail.get_or_insert_with(CurvatureDetail::default); + if let Some(mode) = mode { + detail.mode = mode; + } + if let Some(weights) = weights { + detail.weights = weights; + } + Ok(()) } -fn add_generator(s: &mut Session, p: &Value) -> Result { - let kind = match strp(p, "generator") { - Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?, +/// The detail size weights in `value`: one number (0..1) per size of [`CurvatureDetail::SIZES`], finest first. +fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> { + let weights: Vec = + value.as_array().map(|items| items.iter().filter_map(Value::as_f64).map(|weight| (weight as f32).clamp(0.0, 1.0)).collect()).unwrap_or_default(); + weights.try_into().map_err(|_| bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()))) +} + +fn add_generator(session: &mut Session, params: &Value) -> Result { + let kind = match strp(params, "generator") { + Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, None => GeneratorKind::EdgeWear, }; - let mut g = Generator::new(kind); - generator_from(p, &mut g); - let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal); - push_effect(s, p, EffectKind::Generator(g), blend) + let mut generator = Generator::new(kind); + generator_from("effect.add.generator", params, &mut generator)?; + let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); + push_effect(session, params, EffectKind::Generator(generator), blend) } pub(crate) fn levels_from(p: &Value, l: &mut Levels) { @@ -413,55 +441,57 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } -fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { +fn set(session: &mut Session, params: &Value) -> Result { + let target = effect_id(session, params, "effect.set")?; + let blend = blend_param("effect.set", params, "blend")?; + + // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone re-targets the current one + let anchor = match session.doc.project.effect(target) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; - match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + let channel_param = channel_param("effect.set", params, "anchorChannel")?; + match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { + Some(anchor) => Some(anchor_source(session, "effect.set", owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; - s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + + session.edit("Edit effect", |session| { + let effect = session.doc.project.effect_mut(target).ok_or_else(|| bad("effect.set", format!("no effect {}", target.0)))?; + if let Some(visible) = boolp(params, "visible") { + effect.visible = visible; } - if let Some(b) = blend { - e.blend = b; + if let Some(blend) = blend { + effect.blend = blend; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(opacity) = f32p(params, "opacity") { + effect.opacity = opacity.clamp(0.0, 1.0); } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(name) = name_param(params) { + effect.name = name.to_string(); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + + match &mut effect.kind { + EffectKind::Generator(generator) => generator_from("effect.set", params, generator)?, + EffectKind::Levels(levels) => levels_from(params, levels), + EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, "effect.set")?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 5038abbb..dd0111f3 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup. +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes). pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill. diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..e7e38614 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -380,3 +380,23 @@ fn background_resizes_match_the_command_and_keep_later_edits() { b.update(); assert_eq!(b.caches[0].size, (512, 512)); } + +#[test] +fn curvature_generators_take_a_mode_and_detail_sizes() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); + + let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]})); + assert!(too_few.is_err(), "sizes takes one weight per detail size"); + let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"})); + assert!(unknown.is_err(), "unknown modes are rejected"); + let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"})); + assert!(dirt.is_err(), "only curvature generators have a mode"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..55e9e8f3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,8 +5,8 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Projection, Source, + BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, + LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -1873,63 +1873,42 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { let tk = Tokens::get(ui.ctx()); - let Some((_, e)) = app.session.doc.project.effect(eid).map(|(l, e)| (l, e.clone())) else { return }; + let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; + let id = eid.0; ui.horizontal(|ui| { ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(e.blend.label())).show_ui(ui, |ui| { - for m in BlendMode::all() { - if ui.selectable_label(m == e.blend, tr(m.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{m:?}")})); + egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { + for mode in BlendMode::all() { + if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); } } }); }); - let mut op = e.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": op, "merge": merge})); + let mut opacity = effect.opacity; + if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); } ui.separator(); - match &e.kind { - EffectKind::Generator(g) => { - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(g.kind.label())).show_ui(ui, |ui| { - for k in GeneratorKind::ALL { - if ui.selectable_label(k == g.kind, tr(k.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple. - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{k:?}")})); - } - } - }); - let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); - let mut inv = g.invert; - let r5 = ui.checkbox(&mut inv, tr("Invert")); - if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) { - app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge})); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label( - RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning), - ); - } - } - EffectKind::Levels(l) => { + + match &effect.kind { + EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), + EffectKind::Levels(levels) => { 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]; + levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high)); + let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.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)); + for (index, label) in labels.iter().enumerate() { + let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; + edit = edit.or(slider_edit(ui, label, &mut values[index], 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})); + app.run( + "effect.set", + json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}), + ); } } EffectKind::Fill { source, .. } => { @@ -1945,25 +1924,25 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (a, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*a), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": a.0})); + for (anchor, label) in &anchors { + if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } } }); match source { - Source::Uniform(v) => { - let mut x = v[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "value": x, "merge": merge})); + Source::Uniform(color) => { + let mut value = color[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } Source::Anchor { channel, .. } => { - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == *channel, tr(c.label())).clicked() { - app.run("effect.set", json!({"effect": id, "anchorChannel": c.id()})); + for option in channels { + if ui.selectable_label(option == *channel, tr(option.label())).clicked() { + app.run("effect.set", json!({"effect": id, "anchorChannel": option.id()})); } } }); @@ -1975,10 +1954,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); } } - EffectKind::Material(f) => { + EffectKind::Material(fill) => { ui.label(caption(tr("Fill"))); - let on: Vec = f.sources.keys().copied().collect(); - fill_editor(app, ui, f, &json!({"effect": id}), &on, layer.id); + let enabled: Vec = fill.sources.keys().copied().collect(); + fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -1988,7 +1967,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|x| x.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == eid) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") @@ -2002,30 +1981,102 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: .color(tk.text_dim), ); let editing = app.session.tool.path.editing; - for i in 0..paths.len() { + for index in 0..paths.len() { ui.horizontal(|ui| { - let on = editing == Some((eid, i)); - if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() { - if on { + let selected = editing == Some((eid, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { app.run("tool.path", json!({"clear": true})); } else { - app.run("path.edit", json!({"effect": id, "index": i})); + app.run("path.edit", json!({"effect": id, "index": index})); } } if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { - app.run("path.remove", json!({"effect": id, "index": i})); + app.run("path.remove", json!({"effect": id, "index": index})); } }); } tool_properties(app, ui); } - EffectKind::Filter(f) => filter_properties(app, ui, id, f), + EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } } } +/// The settings of generator effect `id`. +fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let tk = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Replace the generator kind: remove and add keeps ordering simple + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + let (mut level, mut softness, mut noise, mut noise_scale, mut invert) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}), + ); + } + + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); + } +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tk = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + /// 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. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..a76cabf0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Edges", "الحواف"), + ("Cavities", "التجاويف"), + ("Edges and cavities", "الحواف والتجاويف"), + ("Raw curvature", "الانحناء الخام"), + ("Detail sizes", "أحجام التفاصيل"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..7135f142 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,13 @@ 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}"), + ("Edges", "Kanten"), + ("Cavities", "Vertiefungen"), + ("Edges and cavities", "Kanten und Vertiefungen"), + ("Raw curvature", "Rohe Krümmung"), + ("Detail sizes", "Detailgrößen"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..3c5e03ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,13 @@ 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}"), + ("Edges", "Bordes"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordes y cavidades"), + ("Raw curvature", "Curvatura sin procesar"), + ("Detail sizes", "Tamaños de detalle"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..1c55b5ee 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,13 @@ 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}"), + ("Edges", "Arêtes"), + ("Cavities", "Cavités"), + ("Edges and cavities", "Arêtes et cavités"), + ("Raw curvature", "Courbure brute"), + ("Detail sizes", "Tailles de détail"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a84b16d1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,13 @@ 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}"), + ("Edges", "Bordi"), + ("Cavities", "Cavità"), + ("Edges and cavities", "Bordi e cavità"), + ("Raw curvature", "Curvatura grezza"), + ("Detail sizes", "Dimensioni del dettaglio"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..3f2fa7e6 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Edges", "エッジ"), + ("Cavities", "くぼみ"), + ("Edges and cavities", "エッジとくぼみ"), + ("Raw curvature", "生の曲率"), + ("Detail sizes", "ディテールサイズ"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..e0513259 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Edges", "가장자리"), + ("Cavities", "오목한 부분"), + ("Edges and cavities", "가장자리와 오목한 부분"), + ("Raw curvature", "원시 곡률"), + ("Detail sizes", "디테일 크기"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..65e55fa2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,13 @@ 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}"), + ("Edges", "Bordas"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordas e cavidades"), + ("Raw curvature", "Curvatura bruta"), + ("Detail sizes", "Tamanhos de detalhe"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..e41e91d4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Edges", "边缘"), + ("Cavities", "凹陷"), + ("Edges and cavities", "边缘和凹陷"), + ("Raw curvature", "原始曲率"), + ("Detail sizes", "细节尺寸"), + ("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"), ]; From 906dcf324e2ed8de2f72cd630ec992fa0324aceb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 01:17:47 +0000 Subject: [PATCH 22/76] Curvature detail: name the tuned weights, clean up the effect plans and blur --- crates/compose/src/eval.rs | 38 +++++++++++------------ crates/core/src/layer.rs | 3 +- crates/core/src/layer/curvature_detail.rs | 8 ++++- 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 412cfe58..1eb29882 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -432,15 +432,15 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; -/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. -/// Rows (and columns, transposed) blur in parallel. -pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { - let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut v: Vec = data.par_iter().map(fix).collect(); - blur_rows(&mut v, w, r); - let mut t = transpose(&v, w, h); - blur_rows(&mut t, h, r); - data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32); +/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. +pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } /// Three box blurs of radius `r` along every row (`w` long) of `data`. @@ -813,18 +813,18 @@ struct Node<'a> { fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { effects .iter() - .filter(|e| e.visible) - .map(|e| { - let (img, target) = match channel { - Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), - None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), + .filter(|effect| effect.visible) + .map(|effect| { + let (image, target) = match channel { + Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), + None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { - kind: &e.kind, - blend: e.blend, - opacity: e.opacity, - data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, + kind: &effect.kind, + blend: effect.blend, + opacity: effect.opacity, + data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, preview: previews(inp, target), curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 19c82f61..37ce47e8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -562,8 +562,7 @@ impl Generator { }; let detail = match kind { GeneratorKind::Curvature => Some(CurvatureDetail::default()), - // Worn edges are thin lines: mostly the finer sizes - GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index f843eac9..826b9823 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -13,10 +13,16 @@ pub struct CurvatureDetail { impl CurvatureDetail { /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + + /// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly. + pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15]; + + /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. + pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; } impl Default for CurvatureDetail { fn default() -> Self { - CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS } } } From 1a0fc5fec8d28085d2b0b17630d63e3cb2fe3481 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 11:51:43 +0000 Subject: [PATCH 23/76] Curvature detail: build only the sizes in use, map coverage on all cores --- crates/compose/src/curvature_sizes.rs | 160 ++++++++++++++++------ crates/compose/src/eval.rs | 51 +++++-- crates/core/src/layer/curvature_detail.rs | 8 ++ 3 files changed, 167 insertions(+), 52 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index c2dfe755..7b6014e0 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -1,5 +1,6 @@ //! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; @@ -11,52 +12,55 @@ use crate::eval::{Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { - pub levels: Vec, + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, } -/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. -type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); static CACHE: Mutex> = Mutex::new(Vec::new()); impl CurvatureSizes { - /// The sizes of the texture set `inp` composites (None without a baked curvature map). - pub fn of(inp: &Inputs) -> Option> { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); - let working_size = (inp.gbuf.width, inp.gbuf.height); - - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(source, ..)| source.strong_count() > 0); - let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); - let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { - same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales - }); - if let Some((.., sizes)) = cached { + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { return Some(sizes.clone()); } - // Covered working texels mark where they land in the bake atlas - let mut covered = vec![false; (width * height) as usize]; - for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { - let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; - if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { - let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); - if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { - *slot = true; - } - } - } - - let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); - cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); - Some(sizes) + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) } - /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. - fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at the sizes `needed` marks; sizes already in `built` are kept as they are. + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); let deviation: Vec = padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); @@ -65,7 +69,15 @@ impl CurvatureSizes { let levels = CurvatureDetail::SIZES .iter() .skip(1) - .map(|size| { + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let step = (radius / 2).max(1).next_power_of_two(); @@ -77,13 +89,55 @@ impl CurvatureSizes { blur_block(&mut blurred, width, region, radius); } } - coarsen(&blurred, (width, height), step) + Some(Arc::new(coarsen(&blurred, (width, height), step))) }) .collect(); CurvatureSizes { levels } } } +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any. +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)).map(|(.., sizes)| sizes.clone()) +} + +/// Cache `sizes`, keeping the sizes another thread cached meanwhile, and return what the cache holds now. +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + return sizes; + }; + + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + *cached_sizes = Arc::new(CurvatureSizes { levels }); + cached_sizes.clone() +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) that the covered working texels of `inp` land on. +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + /// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { let mut block: Vec = @@ -122,12 +176,40 @@ mod tests { #[test] fn padding_keeps_an_island_border_from_reading_flat() { - let left_half = |texel: u32| texel % 64 < 32; - let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); - let covered: Vec = (0..64 * 64).map(left_half).collect(); - let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); - for level in &sizes.levels { - assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1eb29882..e8fd391b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -771,28 +771,48 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// 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 mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -810,7 +830,7 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -819,14 +839,17 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, + }; EffectPlan { kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, - data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, + curvature_sizes, } }) .collect() @@ -1215,7 +1238,9 @@ impl<'a, 'b> Texel<'a, 'b> { let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); - let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; let (mut edges, mut cavities) = (0.0f32, 0.0f32); for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index 826b9823..75c9d36a 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -19,6 +19,14 @@ impl CurvatureDetail { /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; + + /// How many sizes are blurred copies of the map (all but the first). + pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1; + + /// Which blurred sizes this detail reads: those with a weight above 0. + pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] { + std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0)) + } } impl Default for CurvatureDetail { From 508c4bb2aaba8c3a7a5e7af481516fdbff69eeb8 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 02:49:47 +0000 Subject: [PATCH 24/76] 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 25/76] 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 26/76] 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 27/76] 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 346a0b24f53339015d6c173d038d7059e6fa94ea Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 00:26:26 +0000 Subject: [PATCH 28/76] Bake visualization: test every branch of VertexReach::missed A table over distance starts (painted amount 1 and 2) and a cage-mesh start covers both inclusive ends of the ray range, a name mismatch and Ignore Backface both ways. Also test a request with no high poly. --- crates/bake/src/test/high_poly_reach.rs | 24 ++++++++++++ crates/bake/src/test/vertex_reach.rs | 51 +++++++++++++++++++++++++ crates/bake/src/tests.rs | 3 ++ 3 files changed, 78 insertions(+) create mode 100644 crates/bake/src/test/vertex_reach.rs diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index bb8753f8..e6d66d07 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -196,3 +196,27 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { ); } } + +#[test] +fn without_a_high_poly_no_vertex_has_a_reach() { + let low = primitives::plane(1.0, 4); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + + let reach = HighPolyReach::new(&request).unwrap(); + assert!(reach.vertices.is_empty()); + // Any cage distances: there is no vertex to miss + assert_eq!(reach.missed(0, 0.02, 0.01), None); +} diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs new file mode 100644 index 00000000..7675e8dc --- /dev/null +++ b/crates/bake/src/test/vertex_reach.rs @@ -0,0 +1,51 @@ +use crate::{RayStart, VertexReach}; +use texturecraft_geom::glam::Vec3; + +/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25 +const FRONTAL: f32 = 0.5; +const REAR: f32 = 0.25; + +/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage +const IGNORED_FRONTAL: f32 = 9.0; + +/// How far past an end of the ray's range a vertex counts as outside it +const PAST_THE_END: f32 = 1e-3; + +/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing` +fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach { + VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches } +} + +#[test] +fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() { + // A painted cage amount of 2 doubles the frontal distance + let starts = [ + (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL), + (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0), + (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL), + ]; + let (top, bottom) = (FRONTAL, -REAR); + // Height, facing, name matches, ignore backface: missed + let cases = [ + (top, Vec3::Y, true, false, false), + (bottom, Vec3::Y, true, false, false), + (0.0, Vec3::Y, true, false, false), + (top + PAST_THE_END, Vec3::Y, true, false, true), + (bottom - PAST_THE_END, Vec3::Y, true, false, true), + (0.0, Vec3::Y, false, false, true), + (0.0, Vec3::NEG_Y, true, false, false), + (0.0, Vec3::NEG_Y, true, true, true), + (0.0, Vec3::Y, true, true, false), + ]; + + for (start, frontal) in starts { + for (height, facing, name_matches, ignore_backface, missed) in cases { + let reach = vertex(start, height, facing, name_matches); + assert_eq!( + reach.missed(frontal, REAR, ignore_backface), + missed, + "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}" + ); + } + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index c834da7a..abfccaac 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -29,6 +29,9 @@ mod normal_map_curvature; #[path = "test/tile_selection.rs"] mod tile_selection; +#[path = "test/vertex_reach.rs"] +mod vertex_reach; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { From e2a69c4d121de6260443b871819e3cf077e2625d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:15:26 +0000 Subject: [PATCH 29/76] Filter picker: Add filter opens the picker, same-id set edits in place Add filter still adds a neutral HSL filter, and its slot now opens the picker straight away; Esc keeps the HSL and one undo removes it. effect.set naming the filter the effect already is edits its parameters instead of rebuilding it from defaults. The picker's filter list is worked out once. The slot cuts long names short between the thumbnail and the caret, stays highlighted while its picker is open and shows an outline while it has keyboard focus. More engine tests: a swap on a mask, an explicit name, refused swaps leave no change and no undo step. --- crates/engine/src/filter_lib.rs | 7 +++ crates/engine/src/mask_cmds.rs | 12 ++++- crates/engine/tests/filter_swap.rs | 61 ++++++++++++++++++++++++- crates/ui-egui/src/dock.rs | 12 ++++- crates/ui-egui/src/filter_slot.rs | 65 +++++++++++++++++++++------ crates/ui-egui/tests/filter_picker.rs | 54 ++++++++++++++++++++-- 6 files changed, 190 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 0f0fd952..7856f565 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -26,6 +26,13 @@ impl FilterDef { } } +/// The library entries that build filter effects, in shelf order, worked out once +pub fn filter_effects() -> &'static [&'static FilterDef] { + static FILTER_EFFECTS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect()); + &FILTER_EFFECTS +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index bd545fbc..97003298 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -435,7 +435,9 @@ fn set(s: &mut Session, p: &Value) -> Result { _ => None, }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(p, "filter") { + Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(s, effect) == Some(def.id)) => None, Some(filter) => Some(swapped_filter(s, effect, filter, p)?), None => None, }; @@ -492,6 +494,14 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The library id of the filter effect `effect` is, if it is one +fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { + match &s.doc.project.effect(effect)?.1.kind { + EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id), + _ => None, + } +} + /// Filter `id` built with `p` and its label, to replace filter effect `effect` fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { const CMD: &str = "effect.set"; diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index 87341c60..ed39fa6e 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -78,7 +78,65 @@ fn a_mask_refuses_a_content_only_filter() { assert!(err.to_string().contains("not on masks"), "{err}"); assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn a_mask_filter_swaps_in_place_on_the_mask() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); + assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4)); + let layer = s.selected_layer().unwrap(); + let mask_order: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask_order, vec![below, swapped, above]); +} + +#[test] +fn naming_the_current_filter_edits_it_in_place() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, id); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); +} + +#[test] +fn a_name_given_with_the_swap_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap(); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Edges"); +} + +#[test] +fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); + let before = effect(&s, id); + + for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); + } + + assert_eq!(effect(&s, id), before); + // The last step is still the blend, opacity and name edit + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect(&s, id).name, "Invert"); } #[test] @@ -88,6 +146,7 @@ fn only_filter_effects_swap_and_only_to_filters() { let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 13604e91..4931d071 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -19,7 +19,7 @@ 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}; -/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it const NEW_FILTER: &str = "hsl"; const FILTER_SWATCH_WIDTH: f32 = 36.0; const FILTER_HINT_SIZE: f32 = 10.5; @@ -240,7 +240,15 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + + let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + // The neutral filter is a placeholder: its slot opens the picker to choose the real one + if command == "effect.add.filter" + && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) + { + crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); + } + ui.close(); } } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 7a143612..bf169e22 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -4,7 +4,7 @@ use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::{Filter, LayerId}; -use texturecraft_engine::filter_lib::{FILTERS, find}; +use texturecraft_engine::filter_lib::{filter_effects, find}; use crate::TextureCraftApp; use crate::i18n::tr; @@ -13,9 +13,11 @@ use crate::resource_picker_item::ResourcePickerItem; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; +use crate::widgets::elided; const SLOT_HEIGHT: f32 = 52.0; const SLOT_ROUNDING: f32 = 3.0; +const BORDER_WIDTH: f32 = 1.0; const THUMBNAIL_SIZE: f32 = 40.0; const THUMBNAIL_INSET: f32 = 6.0; const CAPTION_FONT_SIZE: f32 = 11.0; @@ -24,6 +26,8 @@ const NAME_FONT_SIZE: f32 = 13.0; const LINE_GAP: f32 = 15.0; const CARET_INSET: f32 = 14.0; const CARET_FONT_SIZE: f32 = 14.0; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; /// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { @@ -35,17 +39,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); - paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); let popup = ui.make_persistent_id(("filter_picker", effect)); - if response.clicked() { + let open_requested = take_open_request(&ctx, effect); + + if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { resource_picker::toggle(&ctx, popup); } + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + let items = |thumbs: &mut Thumbs| { - FILTERS + filter_effects() .iter() - .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .filter(|def| def.mask || !on_mask) .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) .collect() }; @@ -55,6 +63,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: } } +/// Has the slot of filter effect `effect` open its picker if it shows this frame or the next, as Add filter does for the filter it adds +pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame))); +} + +/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses +fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { + let frame = ctx.cumulative_frame_nr(); + let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id())); + + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1) +} + +/// Where the effect whose slot should open its picker waits +fn open_request_id() -> egui::Id { + egui::Id::new("filter_slot_open_request") +} + /// Whether filter effect `effect` sits in a mask rather than the layer content fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { let project = &app.session.doc.project; @@ -62,22 +90,31 @@ fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// The slot's box: thumbnail, "Filter" over the name, caret -fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { +/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { let tk = Tokens::get(ui.ctx()); let painter = ui.painter(); - let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; - painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); + if focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(texture) = thumbnail { let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); } - let center = rect.center(); - painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); - painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + // Long names are cut short rather than run under the thumbnail or the caret + let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; + let text_right = rect.right() - CARET_INSET * 2.0; + let text_center_x = (text_left + text_right) * 0.5; + let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + for (text, size, color, offset) in lines { + let galley = elided(painter, text, size, color, text_right - text_left); + painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + } - let caret_color = if hovered { tk.text } else { tk.text_dim }; - painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); + let caret_color = if highlighted { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); } diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs index 31daef69..819dcc25 100644 --- a/crates/ui-egui/tests/filter_picker.rs +++ b/crates/ui-egui/tests/filter_picker.rs @@ -66,16 +66,64 @@ fn escape_closes_the_picker_without_changes() { assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); } -#[test] -fn add_filter_adds_a_filter_and_selects_it() { - let (mut harness, _) = app_with_invert(); +/// Opens the wand's Add effect menu and clicks Add filter +fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); harness.run_steps(3); harness.get_by_label("Add filter").click(); harness.run_steps(3); +} + +#[test] +fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); + assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter"); + + // The search field has the focus, and a search brings Sharpen into view + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added)); +} + +#[test] +fn escape_after_add_filter_keeps_the_neutral_filter() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); + assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") }; + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + + harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter"); +} + +#[test] +fn add_filter_on_a_mask_adds_it_to_the_mask() { + let (mut harness, _) = app_with_invert(); + let layer = harness.state().session.selected_layer().unwrap(); + // A new mask becomes the selected target, so the wand adds to it + harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); + harness.run_steps(3); + + add_filter_from_the_wand(&mut harness); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); + assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters"); } From c39d95b4c8a53da5791d513c76c8ae00e761de89 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:21:42 +0000 Subject: [PATCH 30/76] Filter swap: test that invalid parameters for the new filter are refused --- crates/engine/tests/filter_swap.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index ed39fa6e..27103ab4 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -129,7 +129,12 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); let before = effect(&s, id); - for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + for refused in [ + json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "nope"}), + json!({"effect": id.0, "filter": "levels"}), + json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), + ] { assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); } From 45ab0f42d9b26600f710dbf87e6a74aed7b35bfc Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:23:12 +0000 Subject: [PATCH 31/76] 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 284cb7d125aa98791d00e529b40b4111cb8eaa90 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:25:04 +0000 Subject: [PATCH 32/76] Refuse host paths in files entries for automation textureSet.meshMap.import takes its paths in files[].path, which authorize_command did not look at, so a control client could import an image from outside --read-root. Treat a path or dir in any files entry like a top-level one, and document that automation imports baked maps through resource_import plus textureSet.meshMap.set. --- crates/automation/src/workspace.rs | 35 ++++++++++++++++++++++-------- docs/control-protocol.md | 6 ++--- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2015c090..1061db2d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { AutomationError::Io(format!("{op} `{path}` failed: {e}")) } -/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`, -/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped -/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command -/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is -/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the -/// embedded mesh). +/// Host keys a command reads or writes a file through, at the top level or in each `files` entry +const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; + +/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); - let ok = match id { + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); + + // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path + let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, _ => !id.starts_with("file.") && !has_path, }; - if ok { + if allowed { Ok(()) } else { Err(bad(format!( @@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError } } +/// Whether `params` names a host path or folder at its own top level +fn names_host_path(params: &Value) -> bool { + HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())) +} + #[cfg(test)] mod tests { use super::*; @@ -243,6 +248,18 @@ mod tests { assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } + #[test] + fn nested_file_paths_are_denied() { + let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]}); + assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err()); + + let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]}); + assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err()); + + let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]}); + assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok()); + } + /// Every registry command documenting a host path must be classified (fails when a new /// path-taking command is added without an automation policy). #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 734036ca..079788be 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -153,8 +153,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From 6d3f7c216ddf478c8c3cb9227f759604653bf4f1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:26:54 +0000 Subject: [PATCH 33/76] 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 dd7bb51bd531205ace004614e3238a8196d5082e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:27:58 +0000 Subject: [PATCH 34/76] Bake visualization: pick up the reach even when nothing is drawn The reach job was only polled while the high poly was drawn, so leaving bake mode or hiding the high poly mid-reach kept busy() true and the view repainting every frame. Poll it at the start of every sync. The resend test now waits for the rebuilt cage's reach before checking that a resend starts none, so it no longer depends on thread timing. --- .../ui-egui/src/bake_scene/bake_scene_link.rs | 30 +++++++++++++++++-- crates/ui-egui/src/bake_scene/reach_link.rs | 27 +++++++++-------- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index 7f4459c6..b9cecaa9 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -47,6 +47,8 @@ impl BakeSceneLink { /// Add to `out` what the GPU needs to draw `visualization` this frame pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + self.reach.poll(); + let Some(visualization) = visualization else { return }; if visualization.high_poly { @@ -117,6 +119,10 @@ mod tests { const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + /// How long a test waits for the reach worker: frames, and the pause between them + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5); + /// The sample project with a high poly a little outside its low poly fn session() -> Session { const HIGH_POLY_OFFSET: f32 = 0.02; @@ -143,11 +149,11 @@ mod tests { /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { - for _ in 0..2000 { + for _ in 0..WAIT_FRAMES { if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { return missed.iter().sum::() / missed.len().max(1) as f32; } - std::thread::sleep(std::time::Duration::from_millis(5)); + std::thread::sleep(WAIT_FRAME_PAUSE); } panic!("the reach never arrived"); } @@ -175,6 +181,8 @@ mod tests { texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); let rebuilt = sync(&mut link, &session, EVERYTHING); assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts + red_share(&mut link, &session, EVERYTHING); link.resend(); let resent = sync(&mut link, &session, EVERYTHING); @@ -185,6 +193,24 @@ mod tests { assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + for hidden in [None, Some(no_high_poly)] { + let mut link = BakeSceneLink::default(); + sync(&mut link, &session, EVERYTHING); + assert!(link.busy(), "the first frame starts working out the reach"); + + let finished = (0..WAIT_FRAMES).any(|_| { + std::thread::sleep(WAIT_FRAME_PAUSE); + link.sync(&session, hidden, &mut SceneSync::default()); + !link.busy() + }); + assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}"); + } + } + #[test] fn the_red_follows_the_distances_and_the_selected_set() { let (mut session, mut link) = (session(), BakeSceneLink::default()); diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index 45527522..cdf0ca58 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -34,6 +34,21 @@ impl ReachLink { self.shown = None; } + /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears + pub(super) fn poll(&mut self) { + let Some(job) = &self.job else { return }; + + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { let set_count = session.doc.project.texture_sets.len(); @@ -53,18 +68,6 @@ impl ReachLink { (self.keys, self.high_id) = (keys, high_id); } - if let Some(job) = &self.job { - match job.try_recv() { - Ok(reach) => { - self.reach = reach; - self.shown = None; - self.job = None; - } - Err(TryRecvError::Disconnected) => self.job = None, - Err(TryRecvError::Empty) => {} - } - } - // Colors wait for the reach being worked out: the old ones stay until it arrives if self.job.is_some() { return; From 8cdd5dc296eead1c9d6bc884c867bbe9a342294e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:28:25 +0000 Subject: [PATCH 35/76] Filter slot: use Id::unique for the open request (Id::new is deprecated) --- crates/ui-egui/src/filter_slot.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index bf169e22..172017d9 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -80,7 +80,7 @@ fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { /// Where the effect whose slot should open its picker waits fn open_request_id() -> egui::Id { - egui::Id::new("filter_slot_open_request") + egui::Id::unique("filter_slot_open_request") } /// Whether filter effect `effect` sits in a mask rather than the layer content From aecf9cd7ab4a7cf5c80e1a6703b45d6f8cc4d1b7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:29:28 +0100 Subject: [PATCH 36/76] 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 cbe3c86acb76e6ddf98b4b77dd4a5eda836ee5a1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:32:06 +0000 Subject: [PATCH 37/76] Curvature detail: full-strength block borders, neutral raw curvature, stricter sizes Divide each blurred detail size by the share of the blur window inside its UV tile block, so texels near a block or map edge keep their strength instead of fading toward zero. Raw mode reads mid gray when there is no curvature to sample. The size cache keeps one layout per curvature map. Mask previews of hidden layers build their sizes once before the tiles run in parallel. effect.set rejects a sizes array with a non-numeric entry. --- crates/compose/src/curvature_sizes.rs | 77 ++++++++++++++++++++++++--- crates/compose/src/eval.rs | 53 ++++++++++++++---- crates/engine/src/mask_cmds.rs | 8 +-- crates/engine/tests/session.rs | 2 + 4 files changed, 120 insertions(+), 20 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 7b6014e0..0d9c3bc9 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -8,7 +8,7 @@ use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; -use crate::eval::{Inputs, blur}; +use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { @@ -107,6 +107,8 @@ fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Opt fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + // One layout per curvature map: sizes built for an earlier tile layout or working size are dropped with it + cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); let sizes = Arc::new(sizes); cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); return sizes; @@ -138,20 +140,47 @@ fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { covered.into_iter().map(AtomicBool::into_inner).collect() } -/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. -fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { +/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) { + let rows = top..top + region_height; let mut block: Vec = - (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); - blur(&mut block, w as usize, h as usize, radius as usize); + rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, region_width as usize, region_height as usize, radius as usize); - for (row, values) in block.chunks(w as usize).enumerate() { - let start = ((y0 + row as u32) * width + x0) as usize; + // The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength + let column_weights = window_inside(region_width as usize, radius as usize); + let row_weights = window_inside(region_height as usize, radius as usize); + for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) { + for (value, column_weight) in values.iter_mut().zip(&column_weights) { + *value /= row_weight * column_weight; + } + } + + for (row, values) in block.chunks(region_width as usize).enumerate() { + let start = ((top + row as u32) * width + left) as usize; if let Some(target) = data.get_mut(start..start + values.len()) { target.copy_from_slice(values); } } } +/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in. +fn window_inside(length: usize, radius: usize) -> Vec { + let window = (2 * radius + 1) as f64; + let mut weights = vec![1.0f64; length]; + for _ in 0..BLUR_BOX_PASSES { + let running_totals: Vec = std::iter::once(0.0) + .chain(weights.iter().scan(0.0, |total, weight| { + *total += weight; + Some(*total) + })) + .collect(); + let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0); + weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect(); + } + weights.into_iter().map(|weight| weight as f32).collect() +} + /// `data` averaged over `step × step` squares (the last ones clipped to the map). fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); @@ -190,6 +219,40 @@ mod tests { } } + #[test] + fn uniform_curvature_keeps_its_strength_at_block_borders() { + let (map_width, map_height): (u32, u32) = (256, 256); + // Curvature 0.8 reads 0.3 above the neutral 0.5 at every size + const CURVATURE: f32 = 0.8; + let expected = CURVATURE - 0.5; + let curvature = vec![CURVATURE; (map_width * map_height) as usize]; + let covered = vec![true; curvature.len()]; + let block = (map_width / 2, map_height); + let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The map's corner, then the last texel of the left block and the first of the right one, halfway down + let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)]; + for level in sizes.levels.iter().flatten() { + for (x, y) in border_texels { + assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y)); + } + } + } + + #[test] + fn a_new_layout_replaces_the_sizes_of_the_old_one() { + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let entries_for_curvature = || { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() + }; + + store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); + store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); + assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + } + #[test] fn sizes_built_on_demand_match_a_full_build() { let map_size: u32 = 64; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e8fd391b..3a30c7d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -443,6 +443,9 @@ pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } +/// The box blurs `blur` runs along each axis +pub(crate) const BLUR_BOX_PASSES: usize = 3; + /// Three box blurs of radius `r` along every row (`w` long) of `data`. fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { @@ -450,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { } data.par_chunks_mut(w).for_each(|row| { let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); row.copy_from_slice(&tmp); } @@ -800,9 +803,14 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 /// 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 mut needed = [false; CurvatureDetail::BLURRED_SIZES]; let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + prepare_mask_curvature_sizes(inp, masks); +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { @@ -1230,11 +1238,19 @@ impl<'a, 'b> Texel<'a, 'b> { /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + }; + + // Without curvature to read the texel is flat: no edges or cavities + let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); @@ -1251,12 +1267,7 @@ impl<'a, 'b> Texel<'a, 'b> { cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), - } + combine(edges, cavities) } fn mask(&mut self, plan: &MaskPlan) -> f32 { @@ -1972,6 +1983,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() @@ -2025,6 +2040,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option