Keep only the texels past a seam beside the island-edge padding, so padding across seams holds one full-size map instead of two

This commit is contained in:
Rebornim committed 2026-11-27 07:33:26 +00:00
1 parent fcd3644744
commit 8dfe916224
5 files changed
+90 -67

No files matched your search

+21 -19
View File
@@ -4886,33 +4886,35 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc:
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 (padding.all.width, padding.all.height) != (w, h) {
if padding.size() != (w, h) {
return written;
}
let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64);
let mut set = std::collections::BTreeSet::new();
// The tiles and their neighbours, which padding reaches into
let (tiles_across, tiles_down) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64);
let mut near_tiles = std::collections::BTreeSet::new();
for &(tx, ty) in tiles {
for dy in -1..=1i64 {
for dx in -1..=1i64 {
let (x, y) = (tx as i64 + dx, ty as i64 + dy);
if x >= 0 && y >= 0 && x < nx && y < ny {
set.insert((x as u32, y as u32));
if x >= 0 && y >= 0 && x < tiles_across && y < tiles_down {
near_tiles.insert((x as u32, y as u32));
}
}
}
}
let set: Vec<(u32, u32)> = set.into_iter().collect();
let near_tiles: Vec<(u32, u32)> = near_tiles.into_iter().collect();
for (channel, img) in out.channels.iter_mut() {
let comps = img.comps();
let src: &TileImage = img;
let dilation = padding.for_channel(*channel);
let across_seams = crate::PaddingMaps::crosses_seams(*channel);
// Each tile pads from the original image, so parallel writes stay independent
let padded: Vec<((u32, u32), Vec<u16>)> = set
let padded: Vec<((u32, u32), Vec<u16>)> = near_tiles
.par_iter()
.filter_map(|&(tx, ty)| {
let mut data: Option<Vec<u16>> = None;
let mut padded_tile: Option<Vec<u16>> = None;
for ly in 0..TILE {
for lx in 0..TILE {
let (x, y) = (tx * TILE + lx, ty * TILE + ly);
@@ -4920,24 +4922,24 @@ pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u3
continue;
}
let Some((sx, sy)) = dilation.source(x, y) else { continue };
let Some((sx, sy)) = padding.source(across_seams, x, y) else { continue };
if (sx, sy) == (x, y) {
continue;
}
let v = src.get(sx, sy);
let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec));
let o = (ly * TILE + lx) as usize * comps;
if let Some(px) = d.get_mut(o..o + comps) {
px.copy_from_slice(&v[..comps]);
let source_texel = src.get(sx, sy);
let tile_data = padded_tile.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec));
let offset = (ly * TILE + lx) as usize * comps;
if let Some(texel) = tile_data.get_mut(offset..offset + comps) {
texel.copy_from_slice(&source_texel[..comps]);
}
}
}
Some(((tx, ty), data?))
Some(((tx, ty), padded_tile?))
})
.collect();
for ((tx, ty), d) in padded {
img.set_tile(tx, ty, Some(std::sync::Arc::new(d)));
for ((tx, ty), tile_data) in padded {
img.set_tile(tx, ty, Some(std::sync::Arc::new(tile_data)));
written.insert((tx, ty));
}
}
@@ -6436,7 +6438,7 @@ 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 padding = crate::PaddingMaps { all: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), flat: None };
let padding = crate::PaddingMaps { flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), crossed: Vec::new() };
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));
+45 -29
View File
@@ -1,4 +1,4 @@
//! A texture set's UV padding maps, one per kind of channel
//! A texture set's UV padding: from island edges, and across seams for the texels past one
use texturecraft_core::{Channel, ChannelKind, UvPaddingMode};
use texturecraft_geom::UvSeam;
@@ -6,36 +6,48 @@ use texturecraft_texel::dilate::DilationMap;
use crate::seam_padding::{SEAM_REACH, cross_seams};
/// A texture set's padding maps: `all` for its channels, `flat` for tangent-space normals
/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed`
#[derive(Clone, Debug, PartialEq)]
pub struct PaddingMaps {
pub all: DilationMap,
/// Padding from island edges (2D) always: a tangent-space normal turns with its island, so it can't continue across a seam
pub flat: Option<DilationMap>,
/// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam
pub flat: DilationMap,
/// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel
pub crossed: Vec<(u32, u32)>,
}
impl PaddingMaps {
/// The maps for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block`
/// The padding 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<u32>, 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) }
}
let crossed = match mode {
UvPaddingMode::Space2d => Vec::new(),
UvPaddingMode::Space3d => cross_seams(&flat, covered, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams),
};
PaddingMaps { flat, crossed }
}
/// Texels across and down
pub fn size(&self) -> (u32, u32) {
(self.flat.width, self.flat.height)
}
/// Whether `channel` pads across seams; tangent-space normals pad from island edges
pub fn crosses_seams(channel: Channel) -> bool {
channel.kind() != ChannelKind::NormalMap
}
/// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides
pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> {
let source = self.flat.source(x, y)?;
if !across_seams || source == (x, y) || self.crossed.is_empty() {
return Some(source);
}
}
/// 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 }
let (texel, width) = (y * self.flat.width + x, self.flat.width);
match self.crossed.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) {
Ok(found) => self.crossed.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)),
Err(_) => Some(source),
}
}
}
@@ -61,15 +73,19 @@ mod tests {
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" });
let island = |padding: &PaddingMaps, across_seams: bool, x: u32| {
padding.source(across_seams, 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);
assert_eq!((island(&space_3d, true, 13), island(&space_3d, true, 18)), (Some("right"), Some("left")));
assert_eq!((island(&space_2d, true, 13), island(&space_2d, true, 18)), (Some("left"), Some("right")));
assert_eq!((island(&space_3d, false, 13), island(&space_3d, false, 18)), (Some("left"), Some("right")));
assert!(PaddingMaps::crosses_seams(Channel::BaseColor) && !PaddingMaps::crosses_seams(Channel::Normal));
// Away from the seam, both modes pad from the near island
assert_eq!(island(&space_3d.all, 2), Some("left"));
// Away from the seam, both modes pad from the near island, and only texels between the islands are kept apart
assert_eq!(island(&space_3d, true, 2), Some("left"));
assert!(!space_3d.crossed.is_empty() && space_2d.crossed.is_empty());
assert!(space_3d.crossed.iter().all(|(texel, _)| (12..20).contains(&(texel % 32))));
}
}
+19 -13
View File
@@ -1,5 +1,7 @@
//! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side
use std::collections::HashMap;
use texturecraft_geom::{UvSeam, glam::Vec2};
use texturecraft_texel::dilate::{DilationMap, NONE};
@@ -8,13 +10,15 @@ use crate::texel_edge::TexelEdge;
/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel
pub const SEAM_REACH: u32 = 32;
/// Point every padding texel just outside a seam at the texel as far inside the seam's other side
pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) {
let (width, height) = (map.width, map.height);
/// The padding texels of `flat` just outside a seam, each with the texel as far inside the seam's other side: (texel, source) indices sorted by texel
pub(crate) fn cross_seams(flat: &DilationMap, covered: &[bool], reach: u32, block: (u32, u32), seams: &[UvSeam]) -> Vec<(u32, u32)> {
let (width, height) = (flat.width, flat.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()];
// Each crossed texel's source and how far outside its seam it is; a nearer seam replaces it
let mut crossed: HashMap<u32, (u32, f32)> = HashMap::new();
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 {
@@ -28,15 +32,16 @@ pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, b
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 {
let index = y * width + x;
let Some(&flat_source) = flat.src.get(index as usize) else { continue };
if flat_source == NONE || flat_source == index {
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) {
let (source, crossed_at) = crossed.get(&index).copied().unwrap_or((flat_source, f32::INFINITY));
if outside > reach || outside >= crossed_at {
continue;
}
@@ -59,14 +64,15 @@ pub(crate) fn cross_seams(map: &mut DilationMap, covered: &[bool], reach: u32, b
}
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;
if is_covered(target_x, target_y) {
crossed.insert(index, (target_y * width + target_x, outside));
}
}
}
}
}
let mut sources: Vec<(u32, u32)> = crossed.into_iter().map(|(texel, (source, _))| (texel, source)).collect();
sources.sort_unstable();
sources
}
+1 -1
View File
@@ -590,7 +590,7 @@ mod tests {
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();
let crosses_seams = |s: &Session| !s.caches[0].padding.crossed.is_empty();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true));
s.update();
+4 -5
View File
@@ -977,20 +977,19 @@ 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 = |flat: bool| {
let at = |across_seams: 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)) {
match padding.as_ref().and_then(|padding| padding.source(across_seams, x, y)) {
Some((sx, sy)) => Some(At::Texel(sx, sy)),
None => beyond_default.then_some(At::Default),
}
};
// Only normals use the sample cache, and they all sample the 2D padding
let (at_all, at_flat) = (at(false), at(true));
let (at_all, at_flat) = (at(true), at(false));
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 };
@@ -1006,7 +1005,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
if diffuse {
let known: Vec<bool> = (y0..y0 + h)
.flat_map(|y| (x0..x0 + w).map(move |x| (x, y)))
.map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.all.source(x, y).is_some()))
.map(|(x, y)| sampler.covered(x, y) || padding.as_ref().is_some_and(|padding| padding.flat.source(x, y).is_some()))
.collect();
// Keep diffusion within each UV tile when rendering an atlas