Texture set size: width and height, so a set can be non-square, set by command and followed by the viewport, filters and export

textureSet.resolution takes an optional height (default: square). Old projects open
square as before; sets whose UV tiles have their own sizes stay square.
This commit is contained in:
Rebornim committed 2026-11-27 06:14:29 +00:00
1 parent 82e3e72201
commit 138b4da099
26 files changed
+395 -129

No files matched your search

+6 -3
View File
@@ -168,6 +168,7 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) {
material: ts.material,
composite: c.composite.clone(),
height_strength: ts.atlas_height_strength(),
height_y_factor: ts.atlas_height_y_factor(),
height_in_normal: ts.height_in_normal(),
height_to_normal: ts.height_to_normal,
})
@@ -205,10 +206,12 @@ pub fn shade(s: &Session) -> Shade {
ViewMode::UvChecker => (3, 0),
ViewMode::NormalHeightMesh => (4, 0),
};
let active_set = s.doc.project.texture_sets.get(s.ts());
Shade {
height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0),
height_in_normal: s.doc.project.texture_sets.get(s.ts()).is_none_or(|t| t.height_in_normal()),
height_to_normal: s.doc.project.texture_sets.get(s.ts()).map_or_else(Default::default, |t| t.height_to_normal),
height_strength: active_set.map_or(1.0, |t| t.atlas_height_strength()),
height_y_factor: active_set.map_or(1.0, |t| t.atlas_height_y_factor()),
height_in_normal: active_set.is_none_or(|t| t.height_in_normal()),
height_to_normal: active_set.map_or_else(Default::default, |t| t.height_to_normal),
view_mode,
channel,
// Only the 2D view uses this default
+50 -34
View File
@@ -171,6 +171,12 @@ impl Inputs<'_> {
self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1))
}
/// Texels across and down an atlas block.
fn block_size(&self) -> [u32; 2] {
let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1)));
[self.gbuf.width / cols, self.gbuf.height / rows]
}
/// The current UV tile can occupy only part of its atlas block
fn tile_res_at(&self, x: u32, y: u32) -> u32 {
((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1)
@@ -439,9 +445,9 @@ enum Op {
/// The shapes moved by `offset` (whole texels), box blurred and laid under them
Shadow { offset: [i32; 2] },
/// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks)
Mirror { mirror: Mirror, block: u32 },
Mirror { mirror: Mirror },
/// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it
Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 },
Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]) },
/// A band along the edge of the shapes past a threshold, from the box blur of the shapes
Outline(MaskOutline),
/// Drawn from the distance to the shapes' edge (see [`distance_filter`])
@@ -529,10 +535,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option<Channel>)
}
// A mirror reads anywhere in its UV tile
EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })),
EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror })),
// A transform reads anywhere in its UV tile; one that changes nothing is skipped
EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => {
Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res }))
Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine() }))
}
// Three box passes reach the band's width
@@ -771,10 +777,10 @@ fn gather(
keep_coverage(&mut acc, comps, center.get(3));
}
}
Op::Mirror { mirror, block } => {
mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample)
Op::Mirror { mirror } => {
mirror_texel(&mirror, (x, y), (block_size, tile_size), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample)
}
Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample),
Op::Transform { transform, affine } => transform_texel(&transform, affine, (x, y), (block_size, tile_size), &mut acc, &sample),
Op::SourceWarp(warp) => warp_texel((&warp, &warp_directions), (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)),
Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)),
Op::HeightToNormal(filter) => {
@@ -1164,21 +1170,14 @@ fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32;
fn mirror_texel(
mirror: &Mirror,
(x, y): (f32, f32),
(block, res): (u32, u32),
(block, tile): ([u32; 2], [u32; 2]),
comps: usize,
alpha: Option<&f32>,
acc: &mut [f32; 5],
sample: &dyn Fn(f32, f32, &mut [f32; 5]),
) {
let (block, size) = (block.max(1) as f32, res.max(1) as f32);
let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block);
let (local_x, local_y) = (x - origin_x, y - origin_y);
if local_x >= size || local_y >= size {
return;
}
let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size];
let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size;
let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return };
let line = (Mirror::DEBUG_HALF_WIDTH * size[0] / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size[0];
if mirror.debug && mirror.on_axis(uv, line) {
// Content stays premultiplied by its own coverage; masks are one value
let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 };
@@ -1192,8 +1191,21 @@ fn mirror_texel(
let [u, v] = mirror.source(uv);
// Whole texels, so an even mirror copies texels exactly
let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0);
sample(at(origin_x, u), at(origin_y, v), acc);
let at = |origin: f32, along: f32, size: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0);
sample(at(origin_x, u, size[0]), at(origin_y, v, size[1]), acc);
}
/// The top left of the UV tile holding texel `(x, y)` (tiles of `tile` texels at the top left of
/// `block`-texel atlas blocks), the texel centre's UV in it and the tile's size, both per axis;
/// None past the tile.
fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option<([f32; 2], [f32; 2], [f32; 2])> {
let (block, size) = (block.map(|b| b.max(1) as f32), tile.map(|t| t.max(1) as f32));
let origin = [(x / block[0]).floor() * block[0], (y / block[1]).floor() * block[1]];
let local = [x - origin[0], y - origin[1]];
if local[0] >= size[0] || local[1] >= size[1] {
return None;
}
Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size))
}
/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty
@@ -1201,21 +1213,14 @@ fn transform_texel(
transform: &TileTransform,
(columns, shift): ([[f32; 2]; 2], [f32; 2]),
(x, y): (f32, f32),
(block, res): (u32, u32),
(block, tile): ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
sample: &dyn Fn(f32, f32, &mut [f32; 5]),
) {
let (block, size) = (block.max(1) as f32, res.max(1) as f32);
let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block);
let (local_x, local_y) = (x - origin_x, y - origin_y);
if local_x >= size || local_y >= size {
return;
}
let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size];
let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return };
// Texel space of the tile, centres at whole numbers
let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5);
let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size[axis] - 0.5);
if !at.iter().all(|a| a.is_finite()) {
return;
}
@@ -1230,7 +1235,7 @@ fn transform_texel(
}
let (cx, cy) = (base_x + dx, base_y + dy);
let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy);
let inside = (0.0..size[0]).contains(&cx) && (0.0..size[1]).contains(&cy);
if !repeat && !inside {
// Empty: no value, full weight
total[4] += k;
@@ -1239,7 +1244,7 @@ fn transform_texel(
// One whole texel: the sample's own weights, so this matches its bilinear read
let mut one = [0.0f32; 5];
sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one);
sample(origin_x + cx.rem_euclid(size[0]), origin_y + cy.rem_euclid(size[1]), &mut one);
for (slot, value) in total.iter_mut().zip(one) {
*slot += value * k;
}
@@ -1615,7 +1620,7 @@ fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) {
_ => None,
};
let source_reach = if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) {
inputs.tile_grid().map_or(longest_side, |_| inputs.tile_res())
inputs.tile_grid().map_or(longest_side, |_| inputs.block_size().into_iter().max().unwrap_or(0))
} else {
0
};
@@ -1825,7 +1830,7 @@ fn filter_region(
// A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels
let (block_size, tiled) = match inputs.tile_grid() {
Some(_) => ([inputs.tile_res(); 2], true),
Some(_) => (inputs.block_size(), true),
None => ([inputs.gbuf.width, inputs.gbuf.height], false),
};
let filtered = |scale: f32| -> Vec<f32> {
@@ -1838,7 +1843,7 @@ fn filter_region(
let scaled = neighbourhood_filters(effects, tile_resolution, channel).find(|filter| filter.0 == index);
let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32);
if !is_box_blur(op) {
let tile_size = if tiled { [tile_resolution; 2] } else { block_size };
let tile_size = if tiled { block_size.map(|side| ((side as f32 * scale).round() as u32).max(1)) } else { block_size };
return gather(
op,
(&stack_values, &cover, &grays),
@@ -5525,6 +5530,17 @@ mod tests {
run_with_images(f, preview, &ImageStore::default())
}
#[test]
fn a_mirror_on_a_wide_set_reflects_across_its_own_height() {
let mirror = Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY };
let (size, near_bottom) = ([256, 128], 120.0);
let read = std::cell::Cell::new(None);
mirror_texel(&mirror, (10.0, near_bottom), (size, size), 4, None, &mut [0.0; 5], &|x, y, _| read.set(Some((x, y))));
let (x, y) = read.get().unwrap();
assert_eq!(x, 10.0);
assert!(y < size[1] as f32 / 2.0, "the bottom half copies the top half: read row {y}");
}
#[test]
fn a_mirrored_fill_culls_against_the_mesh_in_each_copy_view() {
let mut fixture = fixture();
+1
View File
@@ -57,6 +57,7 @@ pub(crate) fn field_identity(inputs: &Inputs) -> u64 {
mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash));
set.uv_tiles.hash(&mut hash);
set.resolution.hash(&mut hash);
set.resolution_height.hash(&mut hash);
set.tile_resolutions.hash(&mut hash);
}
+83 -5
View File
@@ -55,8 +55,12 @@ pub struct TextureSet {
pub description: String,
/// Material index in the mesh this set paints.
pub material: usize,
/// Power of two, 128..=8192.
/// Texels across: a power of two, 128..=8192 (the side of a square set).
pub resolution: u32,
/// Texels down when they differ from `resolution` (a non-square set); a power of two,
/// 128..=8192. Sets with per-tile resolutions stay square.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution_height: Option<u32>,
pub channels: Vec<(Channel, ChannelFormat)>,
/// Top-level layers, bottom → top.
pub stack: Vec<LayerId>,
@@ -173,6 +177,7 @@ impl TextureSet {
description: String::new(),
material,
resolution,
resolution_height: None,
channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(),
stack: Vec::new(),
normal_mixing: NormalMixing::Combine,
@@ -204,16 +209,42 @@ impl TextureSet {
self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32)
}
/// Columns over rows of the atlas grid (1 for a classic set): how much more slopes down the texture tilt than across it, as in export per block
pub fn atlas_height_y_factor(&self) -> f32 {
self.tile_grid().map_or(1.0, |g| g.cols as f32 / g.rows.max(1) as f32)
}
/// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out)
pub fn height_in_normal(&self) -> bool {
self.normal_mixing == NormalMixing::Combine
}
/// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid.
/// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid.
pub fn size(&self) -> (u32, u32) {
let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
let (width, height) = self.block_size();
(width.saturating_mul(cols), height.saturating_mul(rows))
}
/// Texels down of the set's size (`resolution` for a square set).
pub fn height(&self) -> u32 {
self.resolution_height.unwrap_or(self.resolution)
}
/// Set the size to `width × height` (None when square).
pub fn set_size(&mut self, width: u32, height: u32) {
self.resolution = width;
self.resolution_height = (height != width).then_some(height);
}
/// Texels across and down of an atlas block: the set's size, or the largest tile
/// resolution square when tiles have their own.
pub fn block_size(&self) -> (u32, u32) {
if self.tile_resolutions.is_empty() {
return (self.resolution, self.height());
}
let block = self.block_resolution();
(block.saturating_mul(cols), block.saturating_mul(rows))
(block, block)
}
/// Texels per side of UV tile `udim` (its override, else `resolution`).
@@ -221,8 +252,8 @@ impl TextureSet {
self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution)
}
/// Texels per side of an atlas block: the largest tile resolution (`resolution` for a
/// classic set or one without overrides).
/// Texels across an atlas block: the largest tile resolution (`resolution` for a
/// classic set or one without overrides); see [`TextureSet::block_size`] for both sides.
pub fn block_resolution(&self) -> u32 {
if self.tile_resolutions.is_empty() {
return self.resolution;
@@ -733,6 +764,12 @@ impl Project {
if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) {
return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions)));
}
let bad_height = |t: &TextureSet| {
t.resolution_height.is_some_and(|h| !h.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&h) || !t.tile_resolutions.is_empty())
};
if let Some(t) = self.texture_sets.iter().find(|t| bad_height(t)) {
return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", t.name, t.resolution_height)));
}
let mut seen = BTreeSet::new();
for ts in 0..self.texture_sets.len() {
for (id, depth) in self.walk(ts) {
@@ -1065,6 +1102,47 @@ mod tests {
}
}
#[test]
fn atlas_slopes_along_each_side_match_a_block_in_wide_tall_and_square_grids() {
let mut t = TextureSet::new("a", 0, 256);
t.height_strength = 3.0;
for tiles in [vec![1001, 1002], vec![1001, 1011], vec![1001, 1002, 1011, 1012], vec![1001, 1002, 1003]] {
t.uv_tiles = tiles;
let ((width, height), (block_width, block_height)) = (t.size(), t.block_size());
let across = t.atlas_height_strength() * width as f32;
let down = t.atlas_height_strength() * t.atlas_height_y_factor() * height as f32;
assert_eq!(across, t.height_strength * block_width as f32, "{:?}", t.uv_tiles);
assert_eq!(down, t.height_strength * block_height as f32, "{:?}", t.uv_tiles);
}
}
#[test]
fn non_square_sets_are_wider_than_tall_per_block_and_stay_square_with_tile_sizes() {
let mut p = project();
let t = &mut p.texture_sets[0];
t.set_size(1024, 256);
let (w, h) = t.size();
assert!(w > h, "{:?}", t.size());
t.uv_tiles = vec![1001, 1011];
// Tiles stack down, each block keeping the set's shape
assert_eq!(t.size(), (w, h * 2));
p.validate().unwrap();
// A height must be a valid size, and per-tile sizes need a square set
for bad in [Some(100), Some(16384)] {
let mut q = p.clone();
q.texture_sets[0].resolution_height = bad;
assert!(q.validate().is_err(), "{bad:?}");
}
let mut q = p.clone();
q.texture_sets[0].tile_resolutions.insert(1011, 128);
assert!(q.validate().is_err());
// The same size both ways is stored as square
p.texture_sets[0].set_size(512, 512);
assert_eq!(p.texture_sets[0].resolution_height, None);
}
#[test]
fn validate_rejects_newer_formats_and_dangling_ids() {
let mut p = project();
+7 -1
View File
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List export outputs",
[],
None,
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
always,
plan
),
@@ -491,6 +491,10 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
let size = scale_export_side(source_size, block_size, options.size);
// Non-square sets have no tile sizes of their own
let source_height = if set.resolution_height.is_some() { set.height() } else { source_size };
let height = scale_export_side(source_height, block_size, options.size);
files.push(json!({
"ts": set_index,
"map": output.map,
@@ -499,7 +503,9 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
"bitDepth": output.bit_depth,
"dithering": output.dither,
"size": size,
"height": height,
"sourceSize": source_size,
"sourceHeight": source_height,
"warnings": output.warnings,
}));
}
+1
View File
@@ -265,6 +265,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
"index": index,
"name": texture_set.name,
"resolution": texture_set.resolution,
"height": texture_set.height(),
"size": texture_set.size(),
"blockResolution": texture_set.block_resolution(),
"uvTiles": texture_set.uv_tiles,
+9 -7
View File
@@ -42,20 +42,22 @@ impl Session {
let (width, height, values) = atlas;
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
let block = set.block_resolution();
let (block_width, block_height) = set.block_size();
set.uv_tiles
.iter()
.map(|&tile| {
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
for row in 0..side {
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
let scale = set.tile_scale(tile);
let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width);
let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height);
let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize);
for row in 0..tile_height {
let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize;
tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[]));
}
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values })
})
.collect()
}
+1
View File
@@ -66,6 +66,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.resolution_height = src_set.resolution_height;
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
+1 -2
View File
@@ -97,8 +97,7 @@ pub(crate) fn padding_seams(mesh: &Mesh, ts: &TextureSet) -> Vec<UvSeam> {
/// 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))
PaddingMaps::new(ts.uv_padding, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), ts.block_size(), &padding_seams(mesh, ts))
}
/// Active tool.
+31 -12
View File
@@ -20,11 +20,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect texture set",
[],
None,
"{ts?} → {index, name, resolution, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}",
"{ts?} → {index, name, resolution, height, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}",
always,
|s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?))
),
cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution),
cmd!(
"textureSet.resolution",
"Texture set size",
[],
None,
"{ts?, resolution: 128..8192 (power of two, texels across), height?: 128..8192 (texels down; default = resolution, a square set)}",
always,
resolution
),
cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)),
cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)),
cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible),
@@ -112,7 +120,8 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.resolution")?;
let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let task = s.resize_task(ts, u32::try_from(r).unwrap_or(0))?;
let height = u64p(p, "height").unwrap_or(r);
let task = s.resize_task_to(ts, u32::try_from(r).unwrap_or(0), u32::try_from(height).unwrap_or(0))?;
let out = task.run(&texturecraft_bake::Progress::new())?;
s.apply_resize(out)
}
@@ -123,6 +132,7 @@ fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
pub struct ResizeTask {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
mesh: Arc<Mesh>,
/// The session's revision and mesh when the task was made: the result applies only to them.
@@ -133,6 +143,7 @@ pub struct ResizeTask {
pub struct ResizeOutput {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
/// The set's new caches (None when its UV tile layout moved: the session rebuilds them).
cache: Option<SetCache>,
@@ -144,10 +155,13 @@ impl ResizeTask {
/// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its
/// caches. Progress goes from 0 to 1.
pub fn run(self, progress: &texturecraft_bake::Progress) -> Result<ResizeOutput> {
let ResizeTask { ts, resolution, mut doc, mesh, from } = self;
let ResizeTask { ts, resolution, height, mut doc, mesh, from } = self;
let set = doc.project.texture_set_mut(ts)?;
let old = set.clone();
set.resolution = resolution;
set.set_size(resolution, height);
if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() {
return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square"));
}
crate::session::check_size(set)?;
let size = set.size();
let mut log = crate::log::SessionLog::new();
@@ -162,7 +176,7 @@ impl ResizeTask {
let set = doc.project.texture_set(ts)?;
let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set));
progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed);
Ok(ResizeOutput { ts, resolution, doc, cache, log, from })
Ok(ResizeOutput { ts, resolution, height, doc, cache, log, from })
}
}
@@ -174,23 +188,28 @@ impl ResizeOutput {
}
impl Session {
/// Prepare resizing texture set `ts` to `resolution` (a power of two, 128..8192).
/// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192).
pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result<ResizeTask> {
let resolution = check_resolution(resolution)?;
self.resize_task_to(ts, resolution, resolution)
}
/// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192).
pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result<ResizeTask> {
let (resolution, height) = (check_resolution(width)?, check_resolution(height)?);
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask { ts, resolution, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) })
Ok(ResizeTask { ts, resolution, height, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) })
}
/// Apply a finished resize as one undo step. When the document changed while it ran, the
/// resize runs again here on the current document.
pub fn apply_resize(&mut self, out: ResizeOutput) -> Result<Value> {
if out.from != (self.revision, self.mesh_id) || self.stroke_active() {
let task = self.resize_task(out.ts, out.resolution)?;
let task = self.resize_task_to(out.ts, out.resolution, out.height)?;
return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?);
}
let ResizeOutput { ts, resolution, doc, cache, log, .. } = out;
let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out;
let before = std::mem::replace(&mut self.doc, doc);
// Install the new caches before adding history to avoid rebuilding them
@@ -205,7 +224,7 @@ impl Session {
}
self.log.append(log);
self.push_history("Texture set size", before);
Ok(json!({ "ts": ts, "resolution": resolution }))
Ok(json!({ "ts": ts, "resolution": resolution, "height": height }))
}
}
+36 -2
View File
@@ -50,6 +50,10 @@ fn tile_resolution(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles)));
}
if texture_set.resolution_height.is_some() && resolution != texture_set.resolution {
return Err(bad(COMMAND, format!("UV tiles of a non-square texture set (\"{}\") can't have their own size", texture_set.name)));
}
let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile);
if texture_set.tile_resolution(tile) == resolution && !removes_override {
return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() }));
@@ -299,6 +303,11 @@ mod tests {
}
}
/// Width and height of a PNG file, read from its header
fn png_size(bytes: &[u8]) -> (u32, u32) {
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().unwrap()
}
/// Mean painted alpha over the covered texels of the set's current layout.
fn painted_fraction(s: &Session) -> f64 {
let id = s.doc.project.texture_sets[0].stack[0];
@@ -374,8 +383,6 @@ mod tests {
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
let files = s.export_files(&[0], &opts).unwrap();
// PNG: width and height are the big-endian words after the IHDR tag.
let png_size = |b: &[u8]| (u32::from_be_bytes(b[16..20].try_into().unwrap()), u32::from_be_bytes(b[20..24].try_into().unwrap()));
assert!(files.len() >= 4);
for f in &files {
let want = if f.name.contains("1002") { 128 } else { 256 };
@@ -383,6 +390,33 @@ mod tests {
}
}
#[test]
fn non_square_sets_keep_their_paint_export_wide_tiles_and_refuse_tile_sizes() {
let mut s = udim_session();
paint_all(&mut s, 50000);
execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).unwrap();
s.update();
let (w, h) = s.doc.project.texture_sets[0].size();
assert!(w > 2 * h, "two tiles side by side, each wider than tall: {:?}", (w, h));
assert_eq!((s.caches[0].gbuf.width, s.caches[0].gbuf.height), (w, h));
assert!(painted_fraction(&s) > 0.97);
let inspect = execute(&mut s, "textureSet.inspect", &json!({})).unwrap();
assert!(inspect["height"].as_u64() < inspect["resolution"].as_u64());
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
for f in &s.export_files(&[0], &opts).unwrap() {
let (fw, fh) = png_size(&f.bytes);
assert!(fw > fh, "{} is {fw}x{fh}", f.name);
}
assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).is_err());
s.undo().unwrap();
assert_eq!(s.doc.project.texture_sets[0].size(), (512, 256));
// A set whose tiles have their own sizes stays square
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
assert!(execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).is_err());
}
/// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's
/// position across its own UV tile (0..1), so every tile shows the same pattern in UV space.
fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec<u16>) {
+29 -30
View File
@@ -612,7 +612,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
let mut out = Vec::new();
let tiles: Vec<Option<u32>> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() };
let grid = set.tile_grid();
let block_resolution = set.block_resolution();
let (block_resolution, block_size) = (set.block_resolution(), set.block_size());
let scale = |side| scale_export_side(side, block_resolution, opts.size);
for (i, map) in opts.preset.maps.iter().enumerate() {
if !map.channels.iter().any(|(_, s)| source_present(set, s)) {
continue;
@@ -641,19 +642,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
for &tile in &tiles {
if let Some(channels) = psd_channels {
let size = match (tile, grid) {
(Some(tile), Some(_)) => {
(Some(tile), Some(_)) if !set.tile_resolutions.is_empty() => {
let side = tile_side(set, tile, block_resolution);
let side = scale_export_side(side, block_resolution, opts.size);
(side, side)
}
(_, Some(grid)) => {
let side = opts.size.unwrap_or(block_resolution);
(side.saturating_mul(grid.cols), side.saturating_mul(grid.rows))
}
(_, None) => {
let side = opts.size.unwrap_or(block_resolution);
(side, side)
}
(Some(_), Some(_)) | (_, None) => (scale(block_size.0), scale(block_size.1)),
(_, Some(grid)) => (scale(block_size.0).saturating_mul(grid.cols), scale(block_size.1).saturating_mul(grid.rows)),
};
check_psd_size(size, channels, bit_depth)?;
}
@@ -774,9 +769,9 @@ struct Sampler<'a> {
coverage: &'a [bool],
/// Composite width.
res: u32,
/// Texels per atlas block (`res` for a classic set): the height slope and the slope window
/// follow the block.
tile_res: u32,
/// Texels across and down an atlas block (the composite for a classic set): the height
/// slope and the slope window follow the block.
block: (u32, u32),
/// The share of its block each tile fills: a smaller tile's height slope shrinks with it.
scales: BlockScales,
/// Normal convention overriding every normal output.
@@ -820,16 +815,18 @@ impl Sampler<'_> {
fn height_normal(&self, x: u32, y: u32) -> Vec3 {
let center = self.channel(Channel::Height, At::Texel(x, y))[0];
// Clamped to the texel's UV tile.
let t = self.tile_res.max(1);
let (x0, y0, last) = ((x / t * t) as i64, (y / t * t) as i64, t as i64 - 1);
let (tw, th) = (self.block.0.max(1), self.block.1.max(1));
let (x0, y0) = ((x / tw * tw) as i64, (y / th * th) as i64);
let h = |dx: i32, dy: i32| {
let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + last) as u32, (y as i64 + dy as i64).clamp(y0, y0 + last) as u32);
let (sx, sy) = ((x as i64 + dx as i64).clamp(x0, x0 + tw as i64 - 1) as u32, (y as i64 + dy as i64).clamp(y0, y0 + th as i64 - 1) as u32);
if self.covered(sx, sy) { self.channel(Channel::Height, At::Texel(sx, sy))[0] } else { center }
};
let [gx, gy] = self.set.height_to_normal.slope(h);
let s = self.set.height_strength * self.tile_res as f32 * self.scales.at(x, y) / HEIGHT_SPAN;
// Slopes per texel become slopes across the tile along each side
let s = self.set.height_strength * self.scales.at(x, y) / HEIGHT_SPAN;
let (sx, sy) = (s * tw as f32, s * th as f32);
// Image y points down; OpenGL normals have +Y up the image.
Vec3::new(-gx * s, gy * s, 1.0).try_normalize().unwrap_or(Vec3::Z)
Vec3::new(-gx * sx, gy * sy, 1.0).try_normalize().unwrap_or(Vec3::Z)
}
/// The final tangent-space normal (OpenGL): baked normal ⊕ (height ⊕ normal channel).
@@ -911,8 +908,9 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
let set = input.project.texture_set(input.ts)?;
let (width, height) = (input.composite.resolution, input.composite.height);
let grid = set.tile_grid();
let tile_res = width / grid.map_or(1, |g| g.cols.max(1));
if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) {
let (cols, rows) = grid.map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1)));
let (tile_res, tile_height) = (width / cols, height / rows);
if tile_res == 0 || tile_height == 0 || tile_res.max(tile_height) > MAX_IMAGE_SIZE || (width, height) != (tile_res * cols, tile_height * rows) {
return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name)));
}
@@ -925,7 +923,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
}
// Padding stays inside each UV tile
let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_res), input.seams);
let padding_maps = |max_dist| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), max_dist, (tile_res, tile_height), input.seams);
let padding = match options.padding {
Padding::None => None,
Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => Some(padding_maps(Some(d))),
@@ -939,7 +937,7 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
baked: input.baked,
coverage: input.coverage,
res: width,
tile_res,
block: (tile_res, tile_height),
scales: set.block_scales(),
normal_override: options.normal_format,
project_normal: input.project.normal_format,
@@ -961,7 +959,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
// A tile smaller than its block fills the block's top-left corner
let side = tile_side(set, t, tile_res);
(bx * tile_res, by * tile_res, side, side)
let tile_size = if set.tile_resolutions.is_empty() { (tile_res, tile_height) } else { (side, side) };
(bx * tile_res, by * tile_height, tile_size.0, tile_size.1)
}
_ => (0, 0, width, height),
};
@@ -1010,8 +1009,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned
.collect();
// Keep diffusion within each UV tile when rendering an atlas
let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) };
diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize);
let block = if planned_file.tile.is_none() && grid.is_some() { (tile_res, tile_height) } else { (w, h) };
diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, (block.0 as usize, block.1 as usize));
}
let mut data = resize(data, (w, h), component_count, size);
@@ -1060,16 +1059,16 @@ pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: O
u32::try_from(scaled).unwrap_or(u32::MAX).max(u32::from(source_side > 0))
}
fn diffuse_blocks(data: &mut Vec<f32>, (width, height): (usize, usize), channels: usize, known: &[bool], block: usize) {
fn diffuse_blocks(data: &mut Vec<f32>, (width, height): (usize, usize), channels: usize, known: &[bool], (block_w, block_h): (usize, usize)) {
// A whole image or a separately exported tile already occupies a contiguous buffer
if block >= width.max(height) {
if block_w >= width && block_h >= height {
diffuse_fill(data, (width, height), channels, known);
return;
}
for block_y in (0..height).step_by(block.max(1)) {
for block_x in (0..width).step_by(block.max(1)) {
let (block_width, block_height) = (block.min(width - block_x), block.min(height - block_y));
for block_y in (0..height).step_by(block_h.max(1)) {
for block_x in (0..width).step_by(block_w.max(1)) {
let (block_width, block_height) = (block_w.min(width - block_x), block_h.min(height - block_y));
let rows = || (block_y..block_y + block_height).map(|y| (y * width + block_x)..(y * width + block_x + block_width));
let mut block_data: Vec<f32> =
rows().flat_map(|row| data.get(row.start * channels..row.end * channels).unwrap_or_default().iter().copied()).collect();
+1
View File
@@ -145,6 +145,7 @@ mod tests {
material: 0,
composite,
height_strength: strength,
height_y_factor: 1.0,
height_in_normal: true,
height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth,
}
+12 -2
View File
@@ -34,8 +34,8 @@ const _: () = assert!(KINDS == 8);
/// The placeholder mask word's bit for a set with Smooth (Sobel) height to normal (trace.wgsl reads it)
const SMOOTH_HEIGHT_BIT: f32 = (1 << KINDS) as f32;
/// Bytes of the trace uniform: [`Head`] then 256 texture-set entries (`MAX_SETS` in trace.wgsl).
const PARAMS_SIZE: u64 = (size_of::<Head>() + 256 * 16) as u64;
/// Bytes of the trace uniform: [`Head`], 256 texture-set entries (`MAX_SETS` in trace.wgsl), then their height slope factors down the texture, four per entry
const PARAMS_SIZE: u64 = (size_of::<Head>() + 256 * 16 + 256 * 4) as u64;
/// Post uniform slots: resolve and denoise init, then the five à-trous steps.
const STEPS: [u32; 6] = [0, 1, 2, 4, 8, 16];
const WORKGROUP: u32 = 8;
@@ -103,6 +103,8 @@ struct SceneConst {
rotation: f32,
env_camera: bool,
heights: Vec<f32>,
/// Per set: how much more the height slope tilts down the texture than across it
height_y_factors: Vec<f32>,
/// Per set: Smooth (Sobel) height to normal
smooth: Vec<bool>,
ior: f32,
@@ -426,6 +428,7 @@ impl GpuTracer {
rotation: scene.env_rotation,
env_camera: scene.env_camera,
heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(),
height_y_factors: scene.sets.iter().map(|s| s.height_y_factor).collect(),
smooth: scene.sets.iter().map(|s| s.height_to_normal == HeightToNormalMethod::Smooth).collect(),
ior: scene.ior,
lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]),
@@ -627,8 +630,13 @@ impl GpuTracer {
let smooth = if sc.smooth.get(i).copied().unwrap_or(false) { SMOOTH_HEIGHT_BIT } else { 0.0 };
*slot = [m[0], m[1], m[2] + smooth, sc.heights.get(i).copied().unwrap_or(0.0)];
}
let mut height_y_factors = [1.0f32; 256];
for (slot, factor) in height_y_factors.iter_mut().zip(&sc.height_y_factors) {
*slot = *factor;
}
let mut bytes = bytemuck::bytes_of(&head).to_vec();
bytes.extend_from_slice(bytemuck::cast_slice(&sets));
bytes.extend_from_slice(bytemuck::cast_slice(&height_y_factors));
queue.write_buffer(&self.params, 0, &bytes);
let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_trace"), timestamp_writes: None });
cpass.set_pipeline(&self.trace_pipe);
@@ -853,6 +861,7 @@ mod tests {
material: 0,
composite,
height_strength: 0.0,
height_y_factor: 1.0,
height_in_normal: true,
height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth,
}],
@@ -1053,6 +1062,7 @@ mod tests {
material: 0,
composite,
height_strength: 0.0,
height_y_factor: 1.0,
height_in_normal: true,
height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth,
}],
+5
View File
@@ -110,6 +110,7 @@ struct GlobalsRaw {
bake_neutral: [f32; 4],
bake_bent_normal: [f32; 4],
uv_rotation: [f32; 4],
height_slope: [f32; 4],
}
/// The post pass uniform (see `Post` in post.wgsl).
@@ -157,6 +158,8 @@ pub struct Shade {
pub env_opacity: f32,
pub ao_intensity: f32,
pub height_strength: f32,
/// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`])
pub height_y_factor: f32,
/// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out)
pub height_in_normal: bool,
/// How the height becomes normal slopes
@@ -299,6 +302,7 @@ impl Default for Shade {
env_opacity: 0.0,
ao_intensity: 0.75,
height_strength: 1.0,
height_y_factor: 1.0,
height_in_normal: true,
height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth,
normal_y: 1.0,
@@ -2142,6 +2146,7 @@ impl Renderer {
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }],
fwd: [fwd.x, fwd.y, fwd.z, 0.0],
disp: [disp[0], disp[1], disp[2], if s.height_in_normal { 1.0 } else { 0.0 }],
height_slope: [1.0, s.height_y_factor, 0.0, 0.0],
refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0],
highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data),
highlight_shift: highlight_shift(frame.size),
+6 -6
View File
@@ -36,6 +36,7 @@ struct Globals {
bake_neutral: vec4<f32>, // x roughness, y metallic, z AO intensity of the neutral material, w on (1)
bake_bent_normal: vec4<f32>, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw -
uv_rotation: vec4<f32>, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height); w Smooth (Sobel) height to normal (1) or Sharp (0)
height_slope: vec4<f32>, // xy height slope factors across and down the texture (y: columns over rows of a UV tile grid), zw -
};
@group(0) @binding(0) var<uniform> g: Globals;
@@ -492,11 +493,10 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
let hgt = textureSample(t_height, samp, uv);
let hc = hgt.r;
// Match export: a unit height over 1/16 of the width tilts 45°
// Combine the height gradient with the tangent-space normal
let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(uv);
// Match export (a unit height over 1/16 of a block's width or height tilts 45°), then combine with the tangent-space normal
let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(uv);
let slope = height_slope(uv, ts);
let n_height = normalize(vec3<f32>(-slope.x * k, slope.y * k, 1.0));
let n_height = normalize(vec3<f32>(-slope.x * k.x, slope.y * k.y, 1.0));
// The Normal texture holds the signed normal in half floats (flat is exactly +z)
var n_detail = clamp(nrm_s, vec3<f32>(-1.0), vec3<f32>(1.0));
@@ -736,9 +736,9 @@ fn fs_uv(i: VOut) -> @location(0) vec4<f32> {
// The tangent-space normal the shading uses: the height slope turned by the normal channel
let dims = vec2<f32>(textureDimensions(t_height));
let ts = 1.0 / dims;
let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(i.uv);
let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(i.uv);
let slope = height_slope(i.uv, ts);
let n_height = normalize(vec3<f32>(-slope.x * k, slope.y * k, 1.0));
let n_height = normalize(vec3<f32>(-slope.x * k.x, slope.y * k.y, 1.0));
var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3<f32>(-1.0), vec3<f32>(1.0));
n_detail.y *= g.mode.w;
return raw_out(rnm(n_height, normalize(n_detail)) * 0.5 + 0.5);
+9 -5
View File
@@ -8,6 +8,8 @@ const TAU: f32 = 6.28318530717959;
const BIG: f32 = 3.0e38;
const WALK_STEPS: u32 = 48u;
const MAX_SETS: u32 = 256u;
// MAX_SETS / 4: the height slope factors pack four sets to an entry
const HEIGHT_Y_FACTOR_ENTRIES: u32 = 64u;
struct Params {
inv_vp: mat4x4<f32>,
@@ -18,8 +20,10 @@ struct Params {
sigma: vec4<f32>, // subsurface extinction per color channel
eye: vec4<f32>, // camera position
lens: vec4<f32>, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR
// Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength.
// Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength
sets: array<vec4<f32>, MAX_SETS>,
// Per texture set, four to an entry: how much more the height slope tilts down the texture than across it
height_y_factors: array<vec4<f32>, HEIGHT_Y_FACTOR_ENTRIES>,
};
@group(0) @binding(0) var<uniform> P: Params;
@@ -209,7 +213,6 @@ fn occluded(o: vec3<f32>, d: vec3<f32>) -> bool {
// ---- Materials ----
// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy).
// The change of height per texel to the right and down: Sobel when smooth, else the neighbours across (as HeightToNormalMethod::slope)
fn height_slope(layer: u32, uv: vec2<f32>, sobel: bool) -> vec2<f32> {
let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r;
@@ -226,6 +229,7 @@ fn height_slope(layer: u32, uv: vec2<f32>, sobel: bool) -> vec2<f32> {
return vec2<f32>(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0;
}
// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy).
fn texel(layer: u32, k: u32, uv: vec2<f32>, dx: i32, dy: i32) -> vec2<i32> {
let info = P.sets[layer];
let small = ((u32(info.z) >> k) & 1u) == 1u;
@@ -315,11 +319,11 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
let info = P.sets[layer];
// Extra alpha stores 32 × log2(1 / UV tile scale)
let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0);
let k = info.w * info.xy * vec2<f32>(1.0, P.height_y_factors[layer / 4u][layer % 4u]) / 16.0 * exp2(-extra.a * 255.0 / 32.0);
var n_height = vec3<f32>(0.0, 0.0, 1.0);
if (k != 0.0) {
if (info.w != 0.0) {
let slope = height_slope(layer, uv, ((u32(info.z) >> 8u) & 1u) == 1u);
n_height = normalize_or(vec3<f32>(-slope.x * k, slope.y * k, 1.0), vec3<f32>(0.0, 0.0, 1.0));
n_height = normalize_or(vec3<f32>(-slope.x * k.x, slope.y * k.y, 1.0), vec3<f32>(0.0, 0.0, 1.0));
}
// The signed normal in half floats, as in mesh.wgsl (flat is exactly +z)
+64 -5
View File
@@ -29,6 +29,9 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera};
use crate::ibl::EnvImage;
/// A unit height over this share of a side tilts the normal 45°, as in export
const HEIGHT_SPAN: f32 = 16.0;
/// One texture set's composited channels.
#[derive(Clone)]
pub struct TraceSet {
@@ -37,6 +40,8 @@ pub struct TraceSet {
pub composite: Composite,
/// Height displacement and, with `height_in_normal`, height-to-normal strength
pub height_strength: f32,
/// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`])
pub height_y_factor: f32,
pub height_in_normal: bool,
pub height_to_normal: HeightToNormalMethod,
}
@@ -582,14 +587,15 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3
s.composite.value(c, x, y)
};
let base = Vec3::from(ch(Channel::BaseColor, 0, 0));
// A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink.
let k = set.map_or(0.0, |s| {
// Slopes per texel become slopes across the set along each side (less in a UV tile smaller than its block)
let slope_scale = set.map_or(Vec2::ZERO, |s| {
let (x, y) = texel(s, 0, 0);
s.normal_height_strength() * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y)
let strength = s.normal_height_strength() / HEIGHT_SPAN * s.composite.block_scales.at(x, y);
Vec2::new(s.composite.resolution as f32, s.composite.height as f32 * s.height_y_factor) * strength
});
let n_height = if k != 0.0 {
let n_height = if slope_scale != Vec2::ZERO {
let [gx, gy] = set.map_or(HeightToNormalMethod::Smooth, |s| s.height_to_normal).slope(|dx, dy| ch(Channel::Height, dx, dy)[0]);
Vec3::new(-gx * k, gy * k, 1.0).normalize_or(Vec3::Z)
Vec3::new(-gx * slope_scale.x, gy * slope_scale.y, 1.0).normalize_or(Vec3::Z)
} else {
Vec3::Z
};
@@ -1250,6 +1256,7 @@ mod tests {
material: 0,
composite,
height_strength: 0.0,
height_y_factor: 1.0,
height_in_normal: true,
height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth,
}],
@@ -1258,6 +1265,58 @@ mod tests {
)
}
/// How far the shaded normal of a plane leans from straight up under a height ramp along x or along y over `texture_set`'s atlas
fn ramp_tilt(texture_set: &texturecraft_core::TextureSet, along_x: bool) -> f32 {
let mesh = Arc::new(primitives::plane(2.0, 1));
let bvh = Arc::new(Bvh::new(&mesh));
let ((width, height), (block_width, block_height)) = (texture_set.size(), texture_set.block_size());
let mut composite = Composite::with_size(&[Channel::Height], width, height);
let img = composite.channels.get_mut(&Channel::Height).unwrap();
for y in 0..height {
for x in 0..width {
// The same rise per block side along either side
let rise = if along_x { x as f32 / block_width as f32 } else { y as f32 / block_height as f32 };
img.set(x, y, &[texturecraft_texel::to_u16(rise * 0.5)]);
}
}
let set = TraceSet {
material: 0,
composite,
height_strength: texture_set.atlas_height_strength(),
height_y_factor: texture_set.atlas_height_y_factor(),
height_in_normal: true,
height_to_normal: HeightToNormalMethod::Sharp,
};
let env = Arc::new(EnvImage { width: 8, height: 4, data: vec![[1.0; 3]; 32] });
let s = TraceScene::new(mesh, bvh, vec![set], env, 0.0);
let (o, d) = (Vec3::new(0.1, 1.0, 0.1), Vec3::NEG_Y);
let hit = s.bvh.closest(o, d, f32::MAX).unwrap();
let surf = surface(&s, hit.tri, hit.u, hit.v, o, d, hit.t).unwrap();
surf.n.angle_between(Vec3::Y)
}
#[test]
fn a_wide_set_tilts_the_normal_alike_for_the_same_rise_along_either_side() {
let mut wide = texturecraft_core::TextureSet::new("wide", 0, 128);
wide.set_size(128, 64);
let (across, down) = (ramp_tilt(&wide, true), ramp_tilt(&wide, false));
assert!(across > 0.05, "the ramp tilts the normal: {across}");
assert!((across - down).abs() < 0.1 * across, "across {across} down {down}");
}
#[test]
fn a_uv_tile_row_tilts_the_normal_alike_for_the_same_rise_along_either_side_of_a_tile() {
let mut row = texturecraft_core::TextureSet::new("row", 0, 64);
row.uv_tiles = vec![1001, 1002];
let (across, down) = (ramp_tilt(&row, true), ramp_tilt(&row, false));
assert!(across > 0.05, "the ramp tilts the normal: {across}");
assert!((across - down).abs() < 0.1 * across, "across {across} down {down}");
}
/// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included)
/// in a uniform white environment.
fn furnace(values: &[(Channel, [f32; 3])]) -> Vec3 {
+15
View File
@@ -260,6 +260,21 @@ fn the_combined_normal_view_shows_the_shading_normal_unlit() {
assert_eq!(a.px, b.px, "a data view ignores exposure");
}
#[test]
fn the_height_y_factor_steepens_slopes_down_the_texture_only() {
let Some((mut h, frame)) = setup() else { return };
let normal_view = shaded(&frame, |s| s.view_mode = 4);
let doubled = shaded(&normal_view, |s| s.height_y_factor = 2.0);
upload_height(&mut h, |x, _| [x as f32 / 256.0, 0.0, 0.0, 0.0]);
let (across, across_doubled) = (render(&mut h, &normal_view, "height_across"), render(&mut h, &doubled, "height_across_y_doubled"));
upload_height(&mut h, |_, y| [y as f32 / 256.0, 0.0, 0.0, 0.0]);
let (down, down_doubled) = (render(&mut h, &normal_view, "height_down"), render(&mut h, &doubled, "height_down_y_doubled"));
assert_same(&across, &across_doubled, "a slope across the texture keeps its tilt");
assert_ne!(down.px, down_doubled.px, "a slope down the texture tilts more");
}
#[test]
fn post_effects() {
let Some((mut h, frame)) = setup() else { return };
+2 -2
View File
@@ -51,7 +51,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue };
let name = texture_set.name.clone();
let resolution = texture_set.resolution;
let (resolution, height) = (texture_set.resolution, texture_set.height());
let mut is_enabled = texture_set.bake.common.is_enabled;
let visible = texture_set.visible;
let tiles: Vec<_> = texture_set
@@ -71,7 +71,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
}
// The name takes the room the resolution leaves, so it only shortens when the row is too narrow
let resolution_text = format!("{resolution}x{resolution}");
let resolution_text = format!("{resolution}x{height}");
let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0);
let name_size = egui::vec2(name_width, ui.spacing().interact_size.y);
let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| {
+3 -3
View File
@@ -49,10 +49,10 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) {
.texture_sets
.iter()
.map(|t| {
let res = t.resolution;
let (width, height) = (t.resolution, t.height());
let size = match t.uv_tiles.len() {
0 => format!("{res}x{res}"),
n => format!("{res}x{res}, {n} UDIM"),
0 => format!("{width}x{height}"),
n => format!("{width}x{height}, {n} UDIM"),
};
(t.name.clone(), size, t.visible)
})
+1 -1
View File
@@ -86,7 +86,7 @@ fn attributes(app: &TextureCraftApp, sheet: &mut PropertySheet<'_>, def: Option<
sheet.attribute(tr("Tags"), &about.tags.iter().map(|tag| tr(tag)).collect::<Vec<_>>().join(", "));
}
if let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) {
sheet.attribute(tr("Size"), &format!("{0} × {0}", texture_set.resolution));
sheet.attribute(tr("Size"), &format!("{} × {}", texture_set.resolution, texture_set.height()));
}
}
+7 -3
View File
@@ -938,14 +938,18 @@ impl TextureCraftApp {
self.session.bake_preview_end();
}
/// Resize texture set `ts` to `resolution` on a worker thread (the document changes when
/// it is done, as one undo step).
/// Resize texture set `ts` to `resolution` texels across on a worker thread, keeping its
/// shape (the document changes when it is done, as one undo step).
pub fn start_resize(&mut self, ts: usize, resolution: u32) {
if self.resize.is_some() {
return;
}
match self.session.resize_task(ts, resolution) {
let height = self.session.doc.project.texture_set(ts).map_or(resolution, |set| {
let scaled = u64::from(set.height()) * u64::from(resolution) / u64::from(set.resolution.max(1));
u32::try_from(scaled).unwrap_or(u32::MAX).clamp(texturecraft_engine::core::MIN_RESOLUTION, texturecraft_engine::core::MAX_RESOLUTION)
});
match self.session.resize_task_to(ts, resolution, height) {
Ok(task) => {
let progress = Arc::new(Progress::new());
let p = progress.clone();
+5 -4
View File
@@ -18,7 +18,8 @@ pub(super) struct LinkImport {
mesh: u64,
canceled: Arc<AtomicBool>,
set: usize,
resolution: u32,
/// The set's size when the import started: a resize cancels it
size: (u32, u32),
place: Place,
result: Receiver<texturecraft_engine::Result<ImportedMaterial>>,
}
@@ -53,7 +54,7 @@ impl TextureCraftApp {
),
explicit => explicit,
};
let resolution = texture_set.resolution;
let (resolution, size) = (texture_set.resolution, texture_set.size());
let baked = self.session.baked(set).cloned();
let path = PathBuf::from(path);
let canceled = Arc::new(AtomicBool::new(false));
@@ -65,7 +66,7 @@ impl TextureCraftApp {
// A pending installation only needs its source package and cooked outputs
Ok((source.package, source.source_ext, cooked))
});
self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, resolution, place, result: rx });
self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, size, place, result: rx });
self.toast("Cooking MaterialCraft material", false);
Some(json!({"pending":true}))
}
@@ -83,7 +84,7 @@ impl TextureCraftApp {
for mut job in std::mem::take(&mut self.link_imports) {
if job.project != self.session.project_id
|| job.mesh != self.session.mesh_id
|| !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.resolution == job.resolution)
|| !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.size() == job.size)
{
self.toast("Material import canceled because the target texture set changed", true);
continue;
+8 -2
View File
@@ -272,6 +272,7 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene {
material: set.material,
composite: cache.composite.clone(),
height_strength: set.atlas_height_strength(),
height_y_factor: set.atlas_height_y_factor(),
height_in_normal: set.height_in_normal(),
height_to_normal: set.height_to_normal,
})
@@ -333,8 +334,13 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work {
/// revisions bump with every composited chunk, so while textures load this changes every frame).
fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String {
let revisions: Vec<u64> = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() };
let sets: Vec<_> =
session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal(), set.height_to_normal)).collect();
let sets: Vec<_> = session
.doc
.project
.texture_sets
.iter()
.map(|set| (set.material, set.atlas_height_strength(), set.atlas_height_y_factor(), set.height_in_normal(), set.height_to_normal))
.collect();
let display = &session.doc.project.display;
let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr);
+2
View File
@@ -383,6 +383,7 @@ fn shade(app: &TextureCraftApp) -> Shade {
let set_index = app.session.ts();
let active_set = app.session.doc.project.texture_sets.get(set_index);
let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0);
let height_y_factor = active_set.map_or(1.0, |texture_set| texture_set.atlas_height_y_factor());
let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal());
let height_to_normal = active_set.map_or_else(Default::default, |texture_set| texture_set.height_to_normal);
@@ -390,6 +391,7 @@ fn shade(app: &TextureCraftApp) -> Shade {
let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill;
Shade {
height_strength,
height_y_factor,
height_in_normal,
height_to_normal,
view_mode,