From 82e3e72201fbc269d64f82bf3674fcd298299b83 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:57 +0000 Subject: [PATCH] Texture set UV padding: across seams (3D) or from island edges (2D), set by command and followed by the viewport and export textureSet.settings takes uvPadding (3d or 2d) as one undo step and textureSet.inspect reports it. Padding from island edges (2D) is the padding we always had: each texel outside the UV islands repeats the nearest covered texel. Padding across seams (3D) continues the surface across UV seams: a texel just outside a seam takes the texel as far inside the seam's other island (UvSeam finds the edges two triangles share in 3D but not in UV space), up to 32 texels out, and falls back to the nearest covered texel elsewhere. Tangent-space normals always pad in 2D, since they turn with their island. New texture sets pad across seams; projects without the field keep 2D, so they open and export as before. --- crates/compose/src/eval.rs | 17 +-- crates/compose/src/lib.rs | 2 + crates/compose/src/seam_padding.rs | 160 +++++++++++++++++++++++++++++ crates/core/src/lib.rs | 2 + crates/core/src/project.rs | 5 + crates/core/src/uv_padding_mode.rs | 29 ++++++ crates/engine/src/file_cmds.rs | 2 + crates/engine/src/inspect.rs | 4 + crates/engine/src/session.rs | 40 ++++++-- crates/engine/src/set_cmds.rs | 30 +++++- crates/engine/src/solo.rs | 2 +- crates/formats/src/export/mod.rs | 46 ++++++--- crates/formats/src/export/tests.rs | 35 ++++++- crates/geom/src/lib.rs | 4 + crates/geom/src/uv_seam.rs | 79 ++++++++++++++ crates/geom/src/uv_seam_side.rs | 11 ++ 16 files changed, 429 insertions(+), 39 deletions(-) create mode 100644 crates/compose/src/seam_padding.rs create mode 100644 crates/core/src/uv_padding_mode.rs create mode 100644 crates/geom/src/uv_seam.rs create mode 100644 crates/geom/src/uv_seam_side.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52184129..db448b28 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -21,7 +21,7 @@ use texturecraft_core::{ }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; -use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; @@ -4874,12 +4874,12 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: } } -/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from their -/// nearest covered texel. Returns the tiles it wrote. -pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { +/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from the +/// covered texel `padding` gives each channel. Returns the tiles it wrote. +pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); - if (dmap.width, dmap.height) != (w, h) { + if (padding.all.width, padding.all.height) != (w, h) { return written; } @@ -4896,9 +4896,10 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) } } let set: Vec<(u32, u32)> = set.into_iter().collect(); - for img in out.channels.values_mut() { + for (channel, img) in out.channels.iter_mut() { let comps = img.comps(); let src: &TileImage = img; + let dmap = padding.for_channel(*channel); // Each tile pads from the original image, so parallel writes stay independent let padded: Vec<((u32, u32), Vec)> = set @@ -6417,8 +6418,8 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let dmap = DilationMap::new(&covered, 64, 64, Some(4)); - pad_tiles(&mut out, &dmap, &[(0, 0)]); + let padding = crate::PaddingMaps { all: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), flat: None }; + pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 32b480e0..75615ba0 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -44,6 +44,7 @@ pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; mod sampled_map; +pub mod seam_padding; mod sections; mod shape_distance; mod slope_texel; @@ -79,6 +80,7 @@ pub use eval::{ pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; pub use projector_depth_cache::ProjectorDepthCache; +pub use seam_padding::PaddingMaps; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs new file mode 100644 index 00000000..d0f49b26 --- /dev/null +++ b/crates/compose/src/seam_padding.rs @@ -0,0 +1,160 @@ +//! 3D Space Neighbor UV padding: texels past a UV seam continue the surface from the seam's other side + +use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; +use texturecraft_geom::{UvSeam, UvSeamSide, glam::Vec2}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel +pub const SEAM_REACH: u32 = 32; + +/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals +#[derive(Clone, Debug, PartialEq)] +pub struct PaddingMaps { + pub all: DilationMap, + /// 2D Space Neighbor always: a tangent-space normal turns with its island, so it can't continue across a seam + pub flat: Option, +} + +impl PaddingMaps { + /// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` + pub fn new(mode: UvPaddingMode, covered: &[bool], (width, height): (u32, u32), max_dist: Option, block: (u32, u32), seams: &[UvSeam]) -> PaddingMaps { + let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); + match mode { + UvPaddingMode::Space2d => PaddingMaps { all: flat, flat: None }, + UvPaddingMode::Space3d => { + let mut all = flat.clone(); + cross_seams(&mut all, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams); + PaddingMaps { all, flat: Some(flat) } + } + } + } + + /// The map padding tangent-space normals + pub fn flat(&self) -> &DilationMap { + self.flat.as_ref().unwrap_or(&self.all) + } + + /// The map padding `channel` + pub fn for_channel(&self, channel: Channel) -> &DilationMap { + if channel.kind() == ChannelKind::NormalMap { self.flat() } else { &self.all } + } +} + +/// Point every padding texel just outside a seam at the texel as far inside the seam's other side +fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) { + let (width, height) = (map.width, map.height); + let size = Vec2::new(width as f32, height as f32); + let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0)); + let is_covered = |x: u32, y: u32| covered.get((y * width + x) as usize).copied().unwrap_or(false); + let mut crossed_at = vec![f32::INFINITY; map.src.len()]; + for seam in seams { + for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] { + let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else { + continue; + }; + + let reach = reach as f32; + let low = near_edge.start.min(near_edge.end) - Vec2::splat(reach); + let high = near_edge.start.max(near_edge.end) + Vec2::splat(reach); + let (x0, y0) = (low.x.floor().max(0.0) as u32, low.y.floor().max(0.0) as u32); + let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); + for y in y0..y1 { + for x in x0..x1 { + let index = (y * width + x) as usize; + let Some(&source) = map.src.get(index) else { continue }; + if source == NONE || source == index as u32 { + continue; + } + + let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let Some((along, outside)) = near_edge.outside(point) else { continue }; + if outside > reach || outside >= crossed_at.get(index).copied().unwrap_or(0.0) { + continue; + } + + // Another island's edge nearer than the seam keeps its texel + let (source_x, source_y) = (source % width, source / width); + if (source_x.abs_diff(x).max(source_y.abs_diff(y)) as f32) + 1.0 < outside { + continue; + } + + // Padding stays inside its UV tile, like the 2D padding + let inside = near_edge.start.lerp(near_edge.end, along) + near_edge.inward * 0.5; + if block_of(inside.x.max(0.0) as u32, inside.y.max(0.0) as u32) != block_of(x, y) { + continue; + } + + // As far inside the other side as the texel is outside this one, at least to that side's first texel centres + let target = far_edge.start.lerp(far_edge.end, along) + far_edge.inward * outside.max(0.5); + if target.x < 0.0 || target.y < 0.0 || target.x >= size.x || target.y >= size.y { + continue; + } + + let (target_x, target_y) = (target.x as u32, target.y as u32); + if is_covered(target_x, target_y) + && let (Some(destination), Some(at)) = (map.src.get_mut(index), crossed_at.get_mut(index)) + { + *destination = target_y * width + target_x; + *at = outside; + } + } + } + } + } +} + +/// A seam side in texel space, with its unit normal into the island +struct TexelEdge { + start: Vec2, + end: Vec2, + inward: Vec2, +} + +impl TexelEdge { + fn new(side: UvSeamSide, size: Vec2) -> Option { + let (start, end, interior) = (side.start * size, side.end * size, side.interior * size); + let normal = (end - start).perp().try_normalize()?; + let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal }; + Some(TexelEdge { start, end, inward }) + } + + /// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside + fn outside(&self, point: Vec2) -> Option<(f32, f32)> { + let direction = self.end - self.start; + let along = (point - self.start).dot(direction) / direction.length_squared(); + let outside = -(point - self.start).dot(self.inward); + ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Two islands of one 3D edge: the left one's right side is the right one's left side + fn two_islands() -> (Vec, Vec) { + let (width, height) = (32u32, 8u32); + let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let left = UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) }; + let right = UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) }; + (covered, vec![UvSeam { sides: [left, right] }]) + } + + #[test] + fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() { + let (covered, seams) = two_islands(); + let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), &seams); + let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), &seams); + let island = |map: &DilationMap, x: u32| map.source(x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }); + + // Just right of the left island, then just left of the right island + assert_eq!((island(&space_3d.all, 13), island(&space_3d.all, 18)), (Some("right"), Some("left"))); + assert_eq!((island(&space_2d.all, 13), island(&space_2d.all, 18)), (Some("left"), Some("right"))); + assert_eq!(space_3d.for_channel(Channel::Normal), &space_2d.all); + assert_eq!(space_3d.for_channel(Channel::BaseColor), &space_3d.all); + + // Away from the seam, both modes pad from the near island + assert_eq!(island(&space_3d.all, 2), Some("left")); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 6c7776c7..c450cff6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -69,6 +69,7 @@ pub mod target_color_mode; pub mod threshold_mode; pub mod tile_transform; pub mod unit_value; +mod uv_padding_mode; pub mod validation_mode; pub mod warp_blending; pub mod warp_mode; @@ -151,6 +152,7 @@ pub use target_color_mode::TargetColorMode; pub use threshold_mode::ThresholdMode; pub use tile_transform::{FlipMode, RepeatMode, TileTransform}; pub use unit_value::{at_or_above_threshold, finite_unit}; +pub use uv_padding_mode::UvPaddingMode; pub use validation_mode::ValidationMode; pub use warp_blending::WarpBlending; pub use warp_mode::WarpMode; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 03939e3d..fd939909 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{ BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId, LayerKind, Result, + UvPaddingMode, }; pub use crate::env_alignment::EnvAlignment; @@ -66,6 +67,9 @@ pub struct TextureSet { /// Height to normal method; projects without it keep Smooth, the filter their exports already used #[serde(default)] pub height_to_normal: HeightToNormalMethod, + /// UV padding; projects without it keep 2D Space Neighbor, the padding they were made with + #[serde(default)] + pub uv_padding: UvPaddingMode, /// Height-to-normal strength. #[serde(default = "one")] pub height_strength: f32, @@ -174,6 +178,7 @@ impl TextureSet { normal_mixing: NormalMixing::Combine, ao_mixing: AoMixing::Multiply, height_to_normal: HeightToNormalMethod::Smooth, + uv_padding: UvPaddingMode::Space3d, height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), diff --git a/crates/core/src/uv_padding_mode.rs b/crates/core/src/uv_padding_mode.rs new file mode 100644 index 00000000..ab5150ec --- /dev/null +++ b/crates/core/src/uv_padding_mode.rs @@ -0,0 +1,29 @@ +//! Where a texture set's UV padding takes its texels from + +use serde::{Deserialize, Serialize}; + +/// UV padding mode: what fills the texels just outside a texture set's UV islands +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum UvPaddingMode { + /// Across seams (3D): past a UV seam, the texels continue the surface from the seam's other side + Space3d, + /// From island edges (2D): every texel repeats the nearest covered texel in the texture + #[default] + Space2d, +} + +impl UvPaddingMode { + pub const ALL: [UvPaddingMode; 2] = [UvPaddingMode::Space3d, UvPaddingMode::Space2d]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + UvPaddingMode::Space3d => "3d", + UvPaddingMode::Space2d => "2d", + } + } + + pub fn parse(id: &str) -> Option { + UvPaddingMode::ALL.into_iter().find(|value| value.id() == id) + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5c813d46..cafee7a6 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -343,12 +343,14 @@ impl Session { let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; let coverage = cache.gbuf.coverage_mask(); + let seams = self.doc.project.texture_set(set_index).map_or_else(|_| Vec::new(), |set| crate::session::padding_seams(&self.mesh, set)); let input = ExportInput { project: &self.doc.project, ts: set_index, composite: &composite, baked: self.doc.baked.get(&set_index).unwrap_or(&empty), coverage: &coverage, + seams: &seams, mesh_name: &mesh_name, }; out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index ada4d0fe..292bdbf3 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -286,6 +286,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { texturecraft_core::HeightToNormalMethod::Sharp => "sharp", texturecraft_core::HeightToNormalMethod::Smooth => "smooth", }, + "uvPadding": match texture_set.uv_padding { + texturecraft_core::UvPaddingMode::Space3d => "3d", + texturecraft_core::UvPaddingMode::Space2d => "2d", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 0864bf7b..1ed8dcbd 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -5,13 +5,12 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use texturecraft_compose::{ - BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, + BakedMaps, BelowCache, Composite, PaddingMaps, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, }; -use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode}; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; +use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer, UvSeam}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; -use texturecraft_texel::DilationMap; use crate::fill_mode::FillMode; pub use crate::stencil_look::StencilLook; @@ -40,7 +39,9 @@ pub struct SetCache { /// Texels across and down (`TextureSet::size`). pub size: (u32, u32), pub gbuf: Arc, - pub dilation: Arc, + /// The set's UV padding mode and the display padding it gives + pub uv_padding: UvPaddingMode, + pub padding: Arc, pub covered_tiles: Arc>, pub composite: Composite, /// Tiles to recomposite. @@ -62,15 +63,14 @@ impl SetCache { pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = UvGBuffer::new(mesh, ts.material, w, h); - - // Padding stays inside each UV tile - let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution()); + let padding = display_padding(mesh, ts, &gbuf); let covered = covered_tiles(&gbuf); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); SetCache { size: (w, h), gbuf: Arc::new(gbuf), - dilation: Arc::new(dilation), + uv_padding: ts.uv_padding, + padding: Arc::new(padding), covered_tiles: Arc::new(covered), composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), @@ -87,6 +87,20 @@ impl SetCache { } } +/// The seams `ts`'s UV padding crosses: none for 2D Space Neighbor +pub(crate) fn padding_seams(mesh: &Mesh, ts: &TextureSet) -> Vec { + match ts.uv_padding { + UvPaddingMode::Space3d => UvSeam::of_material(mesh, ts.material), + UvPaddingMode::Space2d => Vec::new(), + } +} + +/// The viewport's padding of `ts`, which stays inside each UV tile +fn display_padding(mesh: &Mesh, ts: &TextureSet, gbuf: &UvGBuffer) -> PaddingMaps { + let block = ts.block_resolution(); + PaddingMaps::new(ts.uv_padding, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), (block, block), &padding_seams(mesh, ts)) +} + /// Active tool. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Tool { @@ -911,6 +925,12 @@ impl Session { for (i, ts) in sets.iter().enumerate() { match self.caches.get_mut(i) { Some(c) if c.size == ts.size() => { + if c.uv_padding != ts.uv_padding { + c.uv_padding = ts.uv_padding; + c.padding = Arc::new(display_padding(&self.mesh, ts, &c.gbuf)); + c.invalidate_all(); + } + let (want, scales) = (ts.channel_list(), ts.block_scales()); if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) }; @@ -1130,7 +1150,7 @@ impl Session { ); // The composited tiles and the neighbours their padding reached change - let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); + let padded = pad_tiles(&mut cache.composite, &cache.padding, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); cache.revision = cache.revision.wrapping_add(1); changed = true; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 4060ba8d..f9302e3c 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing}; +use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing, UvPaddingMode}; use std::sync::Arc; @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Texture set settings", [], None, - "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, normalFormat?: openGl|directX}", + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, uvPadding?: 3d|2d, normalFormat?: openGl|directX}", always, settings ), @@ -308,6 +308,12 @@ fn settings(s: &mut Session, p: &Value) -> Result { Some("smooth") => Some(HeightToNormalMethod::Smooth), Some(other) => return Err(bad("textureSet.settings", format!("unknown height to normal method {other:?} (sharp or smooth)"))), }; + let uv_padding = match strp(p, "uvPadding") { + None => None, + Some("3d") => Some(UvPaddingMode::Space3d), + Some("2d") => Some(UvPaddingMode::Space2d), + Some(other) => return Err(bad("textureSet.settings", format!("unknown UV padding {other:?} (3d or 2d)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -328,6 +334,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(method) = height_to_normal { set.height_to_normal = method; } + if let Some(mode) = uv_padding { + set.uv_padding = mode; + } Ok(()) })?; @@ -387,6 +396,23 @@ mod tests { assert_eq!(method(&s, 0), json!("smooth")); } + #[test] + fn uv_padding_rebuilds_the_viewport_padding_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mode = |s: &Session| crate::inspect::texture_set(s, 0)["uvPadding"].clone(); + let crosses_seams = |s: &Session| s.caches[0].padding.flat.is_some(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + s.update(); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "uvPadding": "2d"})).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false)); + assert!(!s.caches[0].dirty.is_empty(), "the set recomposites with its new padding"); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + } + #[test] fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/engine/src/solo.rs b/crates/engine/src/solo.rs index 454a8817..bf8c1b74 100644 --- a/crates/engine/src/solo.rs +++ b/crates/engine/src/solo.rs @@ -81,7 +81,7 @@ impl Session { let set = inputs.project.texture_sets.get(ts)?; let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; composite_tiles(inputs, &mut output, tiles); - pad_tiles(&mut output, &cache.dilation, tiles); + pad_tiles(&mut output, &cache.padding, tiles); Some(Cow::Owned(output)) }) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 404980df..e369aa95 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -18,10 +18,10 @@ use std::io::Cursor; use craft_image_codecs::{ChannelLayout, EncodeOptions, Format as CodecFormat, Image as CodecImage, SampleType}; use rayon::prelude::*; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, Composite}; +use texturecraft_compose::{BakedMaps, Composite, PaddingMaps}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, Project, TextureSet}; -use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_geom::{UvSeam, glam::Vec3}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; @@ -290,6 +290,16 @@ impl SourceRef { self.raw_component().min(2) } + /// Whether the source is a tangent-space normal, which pads in 2D whatever the set's UV padding + fn pads_flat(&self) -> bool { + match self { + SourceRef::Channel { channel, .. } => channel.kind() == ChannelKind::NormalMap, + SourceRef::Virtual { map, .. } => matches!(map, VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX | VirtualMap::HeightNormal), + SourceRef::Baked { map, .. } => *map == BakedMap::Normal, + SourceRef::Constant(_) => false, + } + } + /// Components the source has (1 or 3; constants are 1). pub fn components(&self) -> usize { match self { @@ -480,6 +490,8 @@ pub struct ExportInput<'a> { pub composite: &'a Composite, pub baked: &'a BakedMaps, pub coverage: &'a [bool], + /// The set's UV seams, which 3D Space Neighbor padding crosses + pub seams: &'a [UvSeam], pub mesh_name: &'a str, } @@ -913,12 +925,11 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned } // Padding stays inside each UV tile - let dilation_map = match options.padding { + let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_res), input.seams); + let padding = match options.padding { Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) - } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => Some(padding_maps(Some(d))), + Padding::Infinite => Some(padding_maps(None)), }; let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); @@ -941,6 +952,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned let channel_layout = layout(set, map); let component_count = channel_layout.len(); let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let pads_flat: Vec = channel_layout.iter().map(|(_, source)| source.pads_flat()).collect(); // The texels written: one tile, or the whole set let (x0, y0, w, h) = match (planned_file.tile, grid) { @@ -965,17 +977,23 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { let y = y0 + row_y as u32; for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.as_ref().and_then(|d| d.source(x, y)) { + let at = |flat: bool| { + if sampler.covered(x, y) { + return Some(At::Texel(x, y)); + } + + let dilation_map = padding.as_ref().map(|padding| if flat { padding.flat() } else { &padding.all }); + match dilation_map.and_then(|d| d.source(x, y)) { Some((sx, sy)) => Some(At::Texel(sx, sy)), None => beyond_default.then_some(At::Default), } }; - let Some(at) = at else { continue }; + + // Only normals use the sample cache, and they all sample the 2D padding + let (at_all, at_flat) = (at(false), at(true)); let mut cache = None; for (component, (_, source)) in channel_layout.iter().enumerate() { + let Some(at) = (if pads_flat.get(component).copied().unwrap_or(false) { at_flat } else { at_all }) else { continue }; if let Some(value) = row.get_mut(column * component_count + component) { let sample = sampler.sample(source, at, &mut cache); *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; @@ -988,7 +1006,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned if diffuse { let known: Vec = (y0..y0 + h) .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) + .map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.all.source(x, y).is_some())) .collect(); // Keep diffusion within each UV tile when rendering an atlas diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 71435ae0..24b24b95 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1,7 +1,7 @@ use std::io::Cursor; use image::{DynamicImage, GenericImageView, ImageFormat}; -use texturecraft_core::{ChannelFormat, Project, TextureSet}; +use texturecraft_core::{ChannelFormat, Project, TextureSet, UvPaddingMode}; use texturecraft_texel::{to_u16, to_u16_signed}; use super::*; @@ -50,7 +50,7 @@ impl Fx { } fn input(&self) -> ExportInput<'_> { - ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, mesh_name: "sphere" } + ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, seams: &[], mesh_name: "sphere" } } fn render(&self, opts: &ExportOptions) -> Vec { @@ -654,7 +654,8 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() { } } } - let input = ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "udim_plane" }; + let input = + ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, seams: &[], mesh_name: "udim_plane" }; let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { @@ -705,7 +706,7 @@ fn small_export_size_keeps_each_nonempty_udim_tile_one_pixel_or_larger() { project.texture_sets.push(set); let composite = Composite::with_size(&[Channel::Roughness], 1024, 512); let coverage = vec![true; 1024 * 512]; - let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "m" }; + let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, seams: &[], mesh_name: "m" }; for format in [FileFormat::Png, FileFormat::Psd] { let opts = ExportOptions { size: Some(2), padding: Padding::None, ..one_map(format, 8, roughness()) }; @@ -1319,6 +1320,32 @@ fn dithering_is_ordered_and_keeps_the_average() { assert!(list_outputs(&fx.project, 0, "sphere", &wide).unwrap().iter().all(|p| !p.dither)); } +#[test] +fn padding_past_a_seam_takes_the_far_island_except_for_normals() { + // Two islands of one 3D edge: the left one's right side (x = 12) is the right one's left side (x = 20) + let mut fx = Fx::new(&default_channels()); + fx.coverage = (0..RES * RES).map(|i| matches!(i % RES, 4..=11 | 20..=27)).collect(); + fx.set_all(Channel::Roughness, |x, _| [if x < 16 { 0.2 } else { 0.8 }; 3]); + fx.set_all(Channel::Normal, |x, _| if x < 16 { [0.3, 0.5, 0.9] } else { [0.7, 0.5, 0.9] }); + let at = |x: f32, y: f32| texturecraft_geom::glam::Vec2::new(x, y) / RES as f32; + let left = texturecraft_geom::UvSeamSide { start: at(12.0, 0.0), end: at(12.0, 64.0), interior: at(4.0, 0.0) }; + let right = texturecraft_geom::UvSeamSide { start: at(20.0, 0.0), end: at(20.0, 64.0), interior: at(28.0, 0.0) }; + let seams = [UvSeam { sides: [left, right] }]; + let normal_x = SourceRef::Channel { channel: Channel::Normal, component: 0 }; + let mut options = one_map(FileFormat::Png, 16, vec![(Dest::R, roughness()[0].1.clone()), (Dest::G, normal_x), (Dest::B, SourceRef::Constant(0.0))]); + options.padding = Padding::Dilation(4); + let render = |fx: &Fx| decode(&render_maps(&ExportInput { seams: &seams, ..fx.input() }, &options).unwrap()[0]).to_rgb16(); + + // Just right of the left island: roughness continues from the right island, the normal stays the left island's + let space_3d = render(&fx); + let (outside, near, far) = (space_3d.get_pixel(13, 30), space_3d.get_pixel(8, 30), space_3d.get_pixel(24, 30)); + assert_eq!((outside[0], outside[1]), (far[0], near[1])); + + fx.project.texture_sets[0].uv_padding = UvPaddingMode::Space2d; + let space_2d = render(&fx); + assert_eq!(space_2d.get_pixel(13, 30), space_2d.get_pixel(8, 30)); +} + #[test] fn diffusion_padding_fills_beyond_the_dilation_smoothly() { let mut fx = Fx::new(&default_channels()); diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index eb71f854..e9720ba7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -13,6 +13,8 @@ pub mod mesh; pub mod primitives; pub mod triangle_partition; pub mod unwrap; +mod uv_seam; +mod uv_seam_side; pub use bvh::{Bvh, Hit}; pub use camera::{OrbitCamera, Ray}; @@ -20,6 +22,8 @@ pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; pub use triangle_partition::TrianglePartition; +pub use uv_seam::UvSeam; +pub use uv_seam_side::UvSeamSide; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum GeomError { diff --git a/crates/geom/src/uv_seam.rs b/crates/geom/src/uv_seam.rs new file mode 100644 index 00000000..f22bc39e --- /dev/null +++ b/crates/geom/src/uv_seam.rs @@ -0,0 +1,79 @@ +//! UV seams: mesh edges two triangles share in 3D but not in UV space + +use std::collections::HashMap; + +use crate::{Mesh, UvSeamSide}; + +/// Edge ends closer than this share a UV position +const SAME_UV: f32 = 1e-5; + +/// A UV seam: the same 3D edge on two UV islands; both sides' starts are the same 3D point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeam { + pub sides: [UvSeamSide; 2], +} + +impl UvSeam { + /// The seams between triangles of `material` + pub fn of_material(mesh: &Mesh, material: usize) -> Vec { + // Corners within a millionth of the mesh size are the same 3D point + let (minimum, maximum) = mesh.bounds(); + let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6; + let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64)); + let mut first_sides = HashMap::new(); + let mut seams = Vec::new(); + for triangle in mesh.triangles_of(material) { + let Some(corners) = mesh.tri(triangle) else { + continue; + }; + + for edge in 0..3 { + let (first, second, third) = (corners[edge], corners[(edge + 1) % 3], corners[(edge + 2) % 3]); + let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else { + continue; + }; + + // A pole's collapsed edges have no length to cross + if first_key == second_key { + continue; + } + + let (Some(&first_uv), Some(&second_uv), Some(&interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { + continue; + }; + + // Each side starts at the corner with the smaller key, so both sides run the same way + let (key, side) = if first_key <= second_key { + ((first_key, second_key), UvSeamSide { start: first_uv, end: second_uv, interior }) + } else { + ((second_key, first_key), UvSeamSide { start: second_uv, end: first_uv, interior }) + }; + let Some(other) = first_sides.insert(key, side) else { + continue; + }; + + if side.start.distance(other.start) > SAME_UV || side.end.distance(other.end) > SAME_UV { + seams.push(UvSeam { sides: [other, side] }); + } + } + } + + seams + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_closed_mesh_has_seams_and_a_single_island_has_none() { + let sphere = crate::primitives::sphere(1.0, 16, 8); + let plane = crate::primitives::plane(1.0, 4); + let seams = UvSeam::of_material(&sphere, 0); + + assert!(!seams.is_empty()); + assert!(seams.iter().all(|seam| seam.sides[0].start != seam.sides[1].start || seam.sides[0].end != seam.sides[1].end)); + assert!(UvSeam::of_material(&plane, 0).is_empty()); + } +} diff --git a/crates/geom/src/uv_seam_side.rs b/crates/geom/src/uv_seam_side.rs new file mode 100644 index 00000000..b8b810d4 --- /dev/null +++ b/crates/geom/src/uv_seam_side.rs @@ -0,0 +1,11 @@ +//! One side of a UV seam + +use glam::Vec2; + +/// One side of a [`UvSeam`](crate::UvSeam): an island edge in UV space and the third corner of its triangle (which side the island is on) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeamSide { + pub start: Vec2, + pub end: Vec2, + pub interior: Vec2, +}