Auto: Integrate main 6e4e081 with saved brush repairs

Merge the latest main project configuration and compositor changes into the reviewed PR tree while preserving the saved shelf repair and removal of the unstable disabled-mask anchor test.
This commit is contained in:
chasse20 committed 2026-11-17 08:49:57 +00:00
commit ed606dfb27
29 files changed
+1976 -146

No files matched your search

+102 -11
View File
@@ -178,6 +178,52 @@ impl StackKey {
}
}
impl StackKey {
/// The tiles whose pixels differ between `self` and `other` when nothing but painted pixels
/// changed (same set, roots, layers, baked maps and images; the same images by id, channel
/// and size). None when anything else differs: the caller recomposites everything.
pub fn changed_tiles(&self, other: &StackKey) -> Option<BTreeSet<(u32, u32)>> {
if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images {
return None;
}
if self.pixels.len() != other.pixels.len() {
return None;
}
let size = self.set.size();
let mut changed = BTreeSet::new();
for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) {
let (left_image, right_image) = (&left_image.0, &right_image.0);
let same_shape = left_id == right_id
&& left_channel == right_channel
&& left_image.width() == right_image.width()
&& left_image.height() == right_image.height()
&& left_image.comps() == right_image.comps();
// Image tiles are composite tiles only when the grids coincide
if !same_shape || (left_image.width(), left_image.height()) != size {
return None;
}
if left_image.same_tiles(right_image) {
continue;
}
for tile_y in 0..left_image.tiles_y() {
for tile_x in 0..left_image.tiles_x() {
let equal = match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) {
(None, None) => true,
(Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile),
_ => false,
};
if !equal {
changed.insert((tile_x, tile_y));
}
}
}
}
Some(changed)
}
}
/// An image compared by tile identity: holding the clone keeps its tiles alive, and a tile
/// rewritten since is a different allocation (copy-on-write), so pointer equality means the
/// same pixels without reading them.
@@ -186,17 +232,18 @@ struct Shared(TileImage);
impl PartialEq for Shared {
fn eq(&self, other: &Self) -> bool {
let (a, b) = (&self.0, &other.0);
a.width() == b.width()
&& a.height() == b.height()
&& a.comps() == b.comps()
&& (0..a.tiles_y()).all(|ty| {
(0..a.tiles_x()).all(|tx| match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) {
(None, None) => true,
(Some(x), Some(y)) => Arc::ptr_eq(x, y),
_ => false,
})
})
let (left_image, right_image) = (&self.0, &other.0);
left_image.width() == right_image.width()
&& left_image.height() == right_image.height()
&& left_image.comps() == right_image.comps()
&& (left_image.same_tiles(right_image)
|| (0..left_image.tiles_y()).all(|tile_y| {
(0..left_image.tiles_x()).all(|tile_x| match (left_image.tile_handle(tile_x, tile_y), right_image.tile_handle(tile_x, tile_y)) {
(None, None) => true,
(Some(left_tile), Some(right_tile)) => Arc::ptr_eq(left_tile, right_tile),
_ => false,
})
}))
}
}
@@ -416,4 +463,48 @@ mod tests {
c.set_hot(Some(LayerId(3)));
assert!(c.is_empty() && c.bytes() == 0);
}
/// A project with one paint layer in a 128 px set, its pixels and a key builder.
fn painted() -> (Project, PixelStore, LayerId) {
let mut project = Project::new("t", "builtin:plane");
project.texture_sets.push(TextureSet::new("Plane", 0, 128));
let id = project.alloc_id();
let layer = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]);
project.insert_layer(0, layer, None, false).unwrap();
(project, PixelStore::default(), id)
}
fn key(project: &Project, pixels: &PixelStore) -> StackKey {
let stack = project.texture_sets[0].stack.clone();
StackKey::new(project, pixels, &BakedMaps::default(), &ImageStore::default(), 0, &stack).unwrap()
}
#[test]
fn changed_tiles_lists_only_rewritten_tiles() {
let (project, mut pixels, id) = painted();
pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(70, 5, &[9, 9, 9, 9]);
let before = key(&project, &pixels);
pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(70, 6, &[1, 1, 1, 1]);
let after = key(&project, &pixels);
assert_eq!(before.changed_tiles(&after), Some(BTreeSet::from([(1, 0)])));
}
#[test]
fn changed_tiles_is_none_when_a_layer_changes() {
let (mut project, pixels, id) = painted();
let before = key(&project, &pixels);
project
.layer_mut(id)
.unwrap()
.channels
.insert(Channel::BaseColor, texturecraft_core::ChannelBlend { mode: texturecraft_core::BlendMode::Multiply, opacity: 0.5 });
assert_eq!(before.changed_tiles(&key(&project, &pixels)), None);
}
#[test]
fn changed_tiles_is_empty_for_identical_documents() {
let (project, mut pixels, id) = painted();
pixels.layer_mut(id, Channel::BaseColor, (128, 128)).set(3, 3, &[5, 5, 5, 5]);
assert_eq!(key(&project, &pixels).changed_tiles(&key(&project, &pixels)), Some(BTreeSet::new()));
}
}
+89 -33
View File
@@ -6,13 +6,16 @@
//! |-----------|----------|-------------------|----------------|-------------------|-------------------|
//! | BaseColor | sRGB8 | base color | | | opacity |
//! | Orm | RGBA8 | AO (× baked) | roughness | metallic | specular level |
//! | Normal | RGBA8 | normal x | normal y | normal z | sheen roughness |
//! | Normal | RGBA16F | normal x | normal y | normal z | sheen roughness |
//! | Height | RGBA16F | height | Specular (F0) r| g | b |
//! | Emissive | sRGB8 | emissive | | | scattering weight |
//! | Lobes | RGBA8 | coat weight | coat roughness | anisotropy level | anisotropy angle |
//! | Sheen | sRGB8 | sheen color | | | sheen weight |
//! | Extra | RGBA8 | coat normal x | coat normal y | transmission | tile scale |
//!
//! Normal holds the tangent-space normal signed (flat is `(0, 0, 1)`) in half floats: baked
//! normals are high-precision data, and 8 bits per axis bands smooth surfaces in the shading.
//!
//! Extra packs the coat normal's x and y as `128 + 127 × n` (the default normal is exactly 0;
//! z is rebuilt in the shader). Its alpha is the [`Composite::block_scales`] of the texel's UV
//! tile as `32 × log2(1 / scale)` (0 for a tile filling its block): the shader turns height
@@ -36,7 +39,7 @@ pub enum DisplayKind {
/// RGBA8 linear: ambient occlusion (channel × baked), roughness (1 − glossiness when the set
/// has a Glossiness channel), metallic, specular level.
Orm,
/// RGBA8: painted tangent-space normal.
/// RGBA16F: the shown tangent-space normal, signed (flat is `(0, 0, 1)`), alpha = sheen roughness.
Normal,
/// RGBA16F: height in r, the linear Specular (F0) color in gba.
Height,
@@ -64,7 +67,7 @@ impl DisplayKind {
/// Bytes per texel of the upload format.
pub fn bytes_per_texel(self) -> usize {
if self == DisplayKind::Height { 8 } else { 4 }
if matches!(self, DisplayKind::Height | DisplayKind::Normal) { 8 } else { 4 }
}
/// Display textures affected by a channel.
@@ -117,6 +120,7 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t
};
let (src, alpha) = (get(c), scalar8(alpha));
let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8);
for i in 0..TILE_AREA {
let pixel = &mut out[i * 4..i * 4 + 4];
match src {
@@ -132,6 +136,7 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t
}
DisplayKind::Lobes => {
let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8);
for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
for (d, lane) in pixel.iter_mut().zip(&lanes) {
*d = lane(i);
@@ -161,12 +166,14 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t
let gloss = composite.channels.contains_key(&Channel::Glossiness);
let (r, r_default) =
if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
for i in 0..TILE_AREA {
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let baked_ao = baked
.sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales)
.map_or(1.0, |value| value[0]);
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
let pixel = &mut out[i * 4..i * 4 + 4];
pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default);
@@ -176,34 +183,36 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t
}
}
DisplayKind::Normal => {
let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness));
for i in 0..TILE_AREA {
let pixel = &mut out[i * 4..i * 4 + 4];
let (normal_tile, sheen_roughness_tile) = (get(Channel::Normal), get(Channel::SheenRoughness));
let sheen_default = Channel::SheenRoughness.default_value()[0];
let has_baked_normal = baked.maps.contains_key(&BakedMap::Normal);
// The baked normal is the base the painted normal details sit on (as in export)
for (i, pixel) in out.as_chunks_mut::<8>().0.iter_mut().enumerate() {
// Baked normals form the base for painted detail, matching export
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales);
match (n, base) {
(Some(t), None) => {
for (k, d) in pixel.iter_mut().take(3).enumerate() {
*d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0));
}
}
(detail, Some(base)) => {
let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0)));
let v = texturecraft_core::blend::rnm(base, detail);
for (d, v) in pixel.iter_mut().zip(v) {
*d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
}
(None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]),
let baked_sample =
if has_baked_normal { baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales) } else { None };
// Invalid baked samples must not enter half-float shading
let base = baked_sample.filter(|normal| normal.iter().all(|component| (0.0..=1.0).contains(component)));
let painted = normal_tile.map(|tile| [0, 1, 2].map(|k| tile.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0)));
let packed = match (painted, base) {
(Some(painted), None) => painted,
(painted, Some(base)) => texturecraft_core::blend::rnm(base, painted.unwrap_or([0.5, 0.5, 1.0])),
(None, None) => [0.5, 0.5, 1.0],
};
let sheen = sheen_roughness_tile.and_then(|tile| tile.get(i)).map_or(sheen_default, |v| *v as f32 / 65535.0);
let [x, y, z] = packed.map(|v| (v * 2.0 - 1.0).clamp(-1.0, 1.0));
for (k, c) in [x, y, z, sheen].into_iter().enumerate() {
pixel[k * 2..k * 2 + 2].copy_from_slice(&half::f16::from_f32(c).to_le_bytes());
}
pixel[3] = sheen_roughness(i);
}
}
DisplayKind::Height => {
let (h, spec) = (get(Channel::Height), get(Channel::Specular));
let spec_default = Channel::Specular.default_value();
for i in 0..TILE_AREA {
let v = h.and_then(|t| t.get(i)).map(|v| texturecraft_texel::from_u16_signed(*v)).unwrap_or(0.0);
let f0 = |k: usize| spec.and_then(|t| t.get(i * 3 + k)).map(|v| *v as f32 / 65535.0).unwrap_or(spec_default[k]);
@@ -227,7 +236,9 @@ mod tests {
let mut comp = Composite::new(&[Channel::BaseColor, Channel::Opacity], 64);
comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]);
let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0);
assert_eq!(b[0], 255);
assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]);
assert_eq!(b[2], 0);
@@ -241,7 +252,8 @@ mod tests {
set.tile_resolutions.insert(1002, 64);
let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) };
let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3];
// Tile 1001 fills its block; 1002 (from texel 256) a quarter of it: 32 × log2(4).
// Tile 1001 fills its block; 1002 fills a quarter, encoded as 32 × log2(4)
assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64));
}
@@ -249,16 +261,18 @@ mod tests {
fn missing_channels_fall_back_to_defaults() {
let comp = Composite::new(&[], 64);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
assert_eq!(&orm[..4], &[255, 128, 0, 128]);
let n = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Normal, 0, 0);
assert_eq!(&n[..4], &[128, 128, 255, 128], "sheen roughness 0.5 rides in alpha");
assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1");
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission");
for k in DisplayKind::ALL {
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]);
}
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
assert_eq!(h.len(), TILE_AREA * 8);
assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0");
@@ -266,30 +280,70 @@ mod tests {
#[test]
fn the_baked_normal_is_the_base_of_the_shown_normal() {
// A baked normal tilted to +X (packed), 64² like the set.
// A baked normal tilted to +X at the set resolution
let tilted = [0.8f32, 0.5, 0.9];
let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(tilted.repeat(64 * 64)))].into_iter().collect() };
let shown = |comp: &Composite| tile_bytes(comp, &baked, DisplayKind::Normal, 0, 0)[..3].to_vec();
let pack = |v: [f32; 3]| v.map(|x| (x * 255.0 + 0.5) as u8).to_vec();
// No normal channel: the baked normal as it is.
let shown = |comp: &Composite| normal_texel(comp, &baked, 0)[..3].to_vec();
let pack = |v: [f32; 3]| v.map(|x| half::f16::from_f32(x * 2.0 - 1.0).to_f32()).to_vec();
// Without a painted normal, show the bake directly
assert_eq!(shown(&Composite::new(&[], 64)), pack(tilted));
// A flat painted normal leaves it; a painted detail is re-oriented onto it.
// Flat paint preserves the bake; tilted paint reorients onto it
let mut comp = Composite::new(&[Channel::Normal], 64);
comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.5), to_u16(1.0)]);
assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (*a as i32 - b as i32).abs() <= 1), "{:?}", shown(&comp));
assert!(shown(&comp).iter().zip(pack(tilted)).all(|(a, b)| (a - b).abs() < 1e-3), "{:?}", shown(&comp));
comp.channels.get_mut(&Channel::Normal).unwrap().set(0, 0, &[to_u16(0.5), to_u16(0.8), to_u16(0.9)]);
assert_eq!(shown(&comp), pack(texturecraft_core::blend::rnm(tilted, [0.5, 0.8, 0.9])));
}
/// Decode texel `i` of the Normal display tile (0, 0).
fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] {
let bytes = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0);
[0, 1, 2, 3].map(|k| half::f16::from_le_bytes([bytes[i * 8 + k * 2], bytes[i * 8 + k * 2 + 1]]).to_f32())
}
#[test]
fn baked_normals_keep_more_than_8_bits_in_the_viewport() {
// Steps of 1/1024 distinguish texels that an 8-bit texture merges
let ramp: Vec<f32> = (0..64 * 64).flat_map(|i| [0.5 + (i % 64) as f32 / 1024.0, 0.5, 0.9]).collect();
let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(ramp))].into_iter().collect() };
let comp = Composite::new(&[], 64);
let xs: Vec<f32> = (0..8).map(|i| normal_texel(&comp, &baked, i)[0]).collect();
assert!(xs.windows(2).all(|w| w[1] > w[0]), "every texel of the gradient is distinct: {xs:?}");
assert!(xs.windows(2).all(|w| w[1] - w[0] < 1.0 / 255.0), "steps finer than one 8-bit level: {xs:?}");
}
#[test]
fn nonfinite_baked_normal_does_not_reach_the_display_texture() {
let mut pixels = vec![0.5; 64 * 64 * 3];
pixels[..3].copy_from_slice(&[f32::NAN, 0.5, 1.0]);
pixels[3..6].copy_from_slice(&[0.5, f32::INFINITY, 1.0]);
let baked = BakedMaps { resolution: 64, maps: [(BakedMap::Normal, std::sync::Arc::new(pixels))].into_iter().collect() };
let composite = Composite::new(&[], 64);
assert_eq!(normal_texel(&composite, &baked, 0), [0.0, 0.0, 1.0, 0.5]);
assert_eq!(normal_texel(&composite, &baked, 1), [0.0, 0.0, 1.0, 0.5]);
}
#[test]
fn glossiness_shows_as_roughness_and_specular_rides_in_height() {
let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64);
comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]);
comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]);
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32();
assert_eq!(at(0), 0.0);
assert!((at(1) - 1.0).abs() < 1e-3 && (at(2) - 0.5).abs() < 1e-3 && at(3) == 0.0);
assert_eq!(DisplayKind::of_channel(Channel::Specular), DisplayKind::Height);
@@ -310,11 +364,13 @@ mod tests {
set(Channel::ScatterWeight, &[to_u16(0.4)]);
set(Channel::Transmission, &[to_u16(0.6)]);
set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]);
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec();
let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1);
assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes));
assert!(near(&px(DisplayKind::Sheen), &[255, 0, 188, 204]), "{:?}", px(DisplayKind::Sheen));
assert!(near(&px(DisplayKind::Normal)[3..], &[77]) && near(&px(DisplayKind::Emissive)[3..], &[102]));
assert!((normal_texel(&comp, &BakedMaps::default(), 1)[3] - 0.3).abs() < 1e-3 && near(&px(DisplayKind::Emissive)[3..], &[102]));
assert!(near(&px(DisplayKind::Extra), &[255, 128, 153, 0]), "{:?}", px(DisplayKind::Extra));
for c in Channel::LOBES {
assert_ne!(DisplayKind::of_channel(c), DisplayKind::Orm, "{c:?}");
+32
View File
@@ -327,6 +327,22 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (
})
}
/// Whether any mask or content effect in a texture set reads neighbouring texels. Includes
/// filters, blurred generators and reduced-resolution generators. Hidden layers and disabled
/// masks count too, so partial invalidation remains conservative.
pub fn stack_reads_neighbours(project: &Project, texture_set_index: usize) -> bool {
const NEIGHBOUR_PROBE_RESOLUTION: u32 = 2048;
let Some(set) = project.texture_sets.get(texture_set_index) else {
return false;
};
project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
neighbourhood(&layer.content_effects, NEIGHBOUR_PROBE_RESOLUTION).is_some()
|| layer.mask.as_ref().is_some_and(|mask| neighbourhood(&mask.effects, NEIGHBOUR_PROBE_RESOLUTION).is_some())
})
}
/// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn
/// counterclockwise on screen.
fn direction(angle: f32) -> [f32; 2] {
@@ -3194,6 +3210,22 @@ mod tests {
assert!(values.iter().all(|value| (value - 0.5).abs() < 0.01), "flat curvature is mid gray in raw mode, not black: {values:?}");
}
#[test]
fn stack_reads_neighbours_sees_blurs_in_masks_and_content() {
let mut f = fixture();
let id = fill_layer(&mut f.project, [1.0; 3], 1.0);
assert!(!stack_reads_neighbours(&f.project, 0));
let mut mask = Mask::new(MaskBackground::White);
let eid = f.project.alloc_id();
mask.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Blur { radius: 8.0 })));
f.project.layer_mut(id).unwrap().mask = Some(mask);
assert!(stack_reads_neighbours(&f.project, 0));
f.project.layer_mut(id).unwrap().mask = None;
assert!(!stack_reads_neighbours(&f.project, 0));
content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 8.0 }));
assert!(stack_reads_neighbours(&f.project, 0));
}
#[test]
fn blur_filter_softens_mask_edges() {
let mut f = fixture();
+1 -1
View File
@@ -23,7 +23,7 @@ pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, tile_bytes};
pub use eval::{
BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram,
flatten_layer, mask_at, mask_image, pad_tiles,
flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours,
};
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+36 -7
View File
@@ -4,7 +4,9 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles};
use texturecraft_compose::{
BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours,
};
use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
@@ -607,7 +609,6 @@ impl Session {
})
})
};
let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default());
let stack_key = |document: &Document, texture_set_index: usize| {
let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default();
@@ -621,12 +622,40 @@ impl Session {
)
};
for texture_set_index in 0..self.caches.len() {
if (removed_or_replaced_resource
|| stack_key(previous_document, texture_set_index) != stack_key(&self.doc, texture_set_index)
|| uses_added_resource(texture_set_index))
&& let Some(cache) = self.caches.get_mut(texture_set_index)
{
let before = stack_key(previous_document, texture_set_index);
let after = stack_key(&self.doc, texture_set_index);
let resource_changed = removed_or_replaced_resource || uses_added_resource(texture_set_index);
let Some(cache) = self.caches.get_mut(texture_set_index) else {
continue;
};
if resource_changed {
cache.invalidate_all();
continue;
}
if before == after {
continue;
}
// Neighbourhood readers require a full recomposite after painted pixels change
let changed_tiles = match (&before, &after) {
(Some(before), Some(after))
if !stack_reads_neighbours(&self.doc.project, texture_set_index)
&& !stack_reads_neighbours(&previous_document.project, texture_set_index) =>
{
before.changed_tiles(after)
}
_ => None,
};
match changed_tiles {
Some(changed_tiles) => {
// covered_tiles is emitted in row order
cache
.dirty
.extend(changed_tiles.into_iter().filter(|tile| cache.covered_tiles.binary_search_by_key(&(tile.1, tile.0), |&(x, y)| (y, x)).is_ok()));
}
None => cache.invalidate_all(),
}
}
}
+85
View File
@@ -319,6 +319,91 @@ fn bench_8k_stroke_end() {
}
}
/// What undo history costs: cloning a many-layer document, and a run of small strokes that each
/// make one undo step.
#[test]
#[ignore]
fn bench_history() {
let res = 4096;
let t = Instant::now();
let mut s = stack(res);
for _ in 0..20 {
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[200, 300], [260, 320]]})).unwrap();
}
println!("[{res}²] history setup {:.2?}", t.elapsed());
let t = Instant::now();
for _ in 0..100 {
drop(std::hint::black_box(s.doc.clone()));
}
println!("[{res}²] document clone {:.2?} average over 100", t.elapsed() / 100);
let steps = s.history_labels().len();
let t = Instant::now();
for i in 0..100 {
// Rows 300..490 of the 800-pixel viewport, across the framed sphere.
let y = 300 + (i % 20) * 10;
execute(&mut s, "tool.stroke", &json!({"points": [[300, y], [360, y + 20]]})).unwrap();
}
let total = t.elapsed();
assert_eq!(s.history_labels().len(), steps + 100, "every stroke paints the mesh and makes an undo step");
println!("[{res}²] 100 strokes {total:.2?} ({:.2?} per stroke)", total / 100);
let m = s.memory();
println!("[{res}²] memory: layer pixels {:.1} MB, composites {:.1} MB, hot-layer cache {:.1} MB", mb(m.pixels), mb(m.composites), mb(m.cache));
}
/// Drain the pending tiles with `Session::update`, returning how long that took.
fn settle(s: &mut Session) -> Duration {
let t = Instant::now();
while s.pending_tiles() > 0 {
s.update();
}
t.elapsed()
}
/// Undo and redo of one small stroke: the tiles left pending and the time to recomposite them.
/// `blur` keeps the stack's blurred mask (a neighbourhood filter forces a full recomposite).
fn bench_undo_at(res: u32, blur: bool) {
use texturecraft_engine::core::{EffectKind, Filter};
let t = Instant::now();
let mut s = stack(res);
if !blur {
let blurs: Vec<_> = s
.doc
.project
.layers
.values()
.filter_map(|l| l.mask.as_ref())
.flat_map(|m| m.effects.iter())
.filter(|e| matches!(e.kind, EffectKind::Filter(Filter::Blur { .. })))
.map(|e| e.id.0)
.collect();
for id in blurs {
execute(&mut s, "effect.remove", &json!({"effect": id})).unwrap();
}
}
s.update();
let label = if blur { "blur mask kept" } else { "no neighbourhood filters" };
println!("[{res}², {label}] setup {:.2?} ({} covered tiles)", t.elapsed(), s.caches[0].covered_tiles.len());
// Seed the layer image before measuring partial undo
execute(&mut s, "tool.stroke", &json!({"points": [[500, 500], [520, 510]]})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[300, 300], [330, 310]]})).unwrap();
s.update();
for (name, cmd) in [("undo", "edit.undo"), ("redo", "edit.redo")] {
execute(&mut s, cmd, &Value::Null).unwrap();
let pending = s.pending_tiles();
println!("[{res}², {label}] {name}: {pending} tiles pending, settled in {:.2?}", settle(&mut s));
}
}
#[test]
#[ignore]
fn bench_undo() {
// The 8192 setup takes many minutes under load
let res = 4096;
bench_undo_at(res, true);
bench_undo_at(res, false);
}
#[test]
#[ignore]
fn bench_8k_resize() {
+91
View File
@@ -561,6 +561,97 @@ fn background_resizes_match_the_command_and_keep_later_edits() {
assert_eq!(b.caches[0].size, (512, 512));
}
/// A 2048 sphere set with a fill layer and an empty paint layer, a small brush, and the
/// oracle: the composite after recompositing every covered tile from scratch.
fn painted_set() -> Session {
use texturecraft_engine::geom::glam::Vec2;
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 12, "hardness": 70, "opacity": 0.8})).unwrap();
// Seed the image so later strokes change existing tiles
execute(&mut s, "tool.stroke", &json!({"points": [[150, 160], [170, 170]]})).unwrap();
s.update();
s
}
fn full(s: &mut Session) -> texturecraft_engine::compose::Composite {
s.caches[0].invalidate_all();
s.update();
s.caches[0].composite.clone()
}
/// Undo and redo of `change` queue the right tiles: `Some(max)` fewer than `max` of them, matching
/// a full recomposite once updated; `None` every covered tile.
fn check_undo_redo(s: &mut Session, change: impl FnOnce(&mut Session), limit: Option<usize>) {
change(s);
s.update();
for cmd in ["edit.undo", "edit.redo"] {
execute(s, cmd, &Value::Null).unwrap();
let (dirty, covered) = (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len());
match limit {
Some(max) => assert!(0 < dirty && dirty < max, "{cmd}: {dirty} of {covered} tiles dirty"),
None => assert_eq!(dirty, covered, "{cmd}"),
}
s.update();
let settled = s.caches[0].composite.clone();
assert_eq!(settled, full(s), "{cmd}: matches a full recomposite");
}
}
#[test]
fn undo_recomposites_only_changed_tiles() {
let mut s = painted_set();
let stroke = |s: &mut Session| drop(execute(s, "tool.stroke", &json!({"points": [[150, 200], [190, 210]]})).unwrap());
// The stroke covers a handful of the set's 1024 tiles
check_undo_redo(&mut s, stroke, Some(64));
}
#[test]
fn undo_with_a_blur_above_recomposites_everything() {
use texturecraft_engine::geom::glam::Vec2;
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap();
execute(&mut s, "mask.add.white", &Value::Null).unwrap();
execute(&mut s, "effect.add.filter", &json!({"filter": "blur", "radius": 8})).unwrap();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 12, "hardness": 70, "opacity": 0.8})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[150, 160], [170, 170]]})).unwrap();
s.update();
let stroke = |s: &mut Session| drop(execute(s, "tool.stroke", &json!({"points": [[150, 200], [190, 210]]})).unwrap());
check_undo_redo(&mut s, stroke, None);
}
#[test]
fn polygon_fill_recomposites_only_changed_tiles() {
let mut s = painted_set();
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.1})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[150, 240], [170, 250]]})).unwrap();
execute(&mut s, "tool.polygonFill", &Value::Null).unwrap();
s.update();
let tris = s.polygon_fill(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap();
assert!(tris > 0);
let (dirty, covered) = (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len());
assert!(0 < dirty && dirty < covered / 4, "{dirty} of {covered} tiles dirty after one triangle");
s.update();
let settled = s.caches[0].composite.clone();
assert_eq!(settled, full(&mut s));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.caches[0].dirty.len() < covered / 4);
s.update();
let settled = s.caches[0].composite.clone();
assert_eq!(settled, full(&mut s));
}
#[test]
fn undo_of_a_layer_change_recomposites_everything() {
let mut s = painted_set();
let change = |s: &mut Session| drop(execute(s, "layer.blend", &json!({"channel": "all", "opacity": 0.5})).unwrap());
check_undo_redo(&mut s, change, None);
}
#[test]
fn curvature_generators_take_a_mode_and_detail_sizes() {
let mut state = session();
+3 -2
View File
@@ -638,8 +638,9 @@ fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
match k {
DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => wgpu::TextureFormat::Rgba8UnormSrgb,
DisplayKind::Orm | DisplayKind::Normal | DisplayKind::Lobes | DisplayKind::Extra => wgpu::TextureFormat::Rgba8Unorm,
DisplayKind::Height => wgpu::TextureFormat::Rgba16Float,
DisplayKind::Orm | DisplayKind::Lobes | DisplayKind::Extra => wgpu::TextureFormat::Rgba8Unorm,
// Baked normals are smooth high-precision data: 8 bits band the shading
DisplayKind::Normal | DisplayKind::Height => wgpu::TextureFormat::Rgba16Float,
}
}
+62 -23
View File
@@ -257,8 +257,7 @@ fn rnm(base: vec3<f32>, detail: vec3<f32>) -> vec3<f32> {
return normalize(t * dot(t, u) - u * t.z);
}
// Signed values packed in 8 bits: byte 128 decodes to exactly 0, so flat normals stay flat
// (the CPU packing and both path tracers use the same rule).
// Byte 128 decodes to zero so the coat normal in Extra stays flat
fn snorm8(v: vec3<f32>) -> vec3<f32> {
return clamp((v * 255.0 - 128.0) / 127.0, vec3<f32>(-1.0), vec3<f32>(1.0));
}
@@ -380,11 +379,36 @@ fn fs_gbuf(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
return vec4<f32>(sss, z);
}
// Roughness floors keep specular lobes finite
const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045;
const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07;
// Lower bounds prevent degenerate lobes and normalization divisions
const GRAZING_COSINE_FLOOR: f32 = 1e-4;
const ANISOTROPIC_ALPHA_FLOOR: f32 = 0.002;
const TANGENT_LENGTH_SQUARED_FLOOR: f32 = 1e-8;
const REFRACTION_LENGTH_SQUARED_FLOOR: f32 = 1e-6;
const PROJECTION_W_FLOOR: f32 = 1e-6;
// Ignore coat tilts below half a signed 8-bit step
const COAT_TILT_THRESHOLD: f32 = 0.004;
// Tune the anisotropic reflection bend and geometric horizon fade
const ANISOTROPY_BEND_GAIN: f32 = 5.0;
const HORIZON_FADE_STRENGTH: f32 = 1.3;
const UV_CHECKER_CELLS: f32 = 32.0;
const UV_CHECKER_FINE_CELLS: f32 = 256.0;
// Offset alpha dithering between accumulated frames
const DITHER_FRAME_STEP: vec2<f32> = vec2<f32>(17.0, 59.0);
fn shade_mesh(i: VOut, front: bool) -> Shaded {
var n_geo = normalize(i.nrm);
if (!front) {
n_geo = -n_geo;
}
let t = normalize(i.tan.xyz - n_geo * dot(n_geo, i.tan.xyz));
let b = cross(n_geo, t) * i.tan.w;
let v = normalize(g.eye.xyz - i.wpos);
@@ -392,6 +416,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
if (g.material.y > 0.5) {
uv = parallax_uv(uv, vec3<f32>(dot(v, t), dot(v, b), dot(v, n_geo)));
}
let base_s = textureSample(t_base, samp, uv);
let orm = textureSample(t_orm, samp, uv);
let nrm_t = textureSample(t_nrm, samp, uv);
@@ -415,7 +440,9 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
// Combine the height gradient with the tangent-space normal
let k = g.mode.z * dims.x / 16.0 * tile_scale(uv);
let n_height = normalize(vec3<f32>(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0));
var n_detail = snorm8(nrm_s);
// 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));
n_detail.y *= g.mode.w;
let n_ts = rnm(n_height, normalize(n_detail));
let n = normalize(t * n_ts.x + b * n_ts.y + n_geo * n_ts.z);
@@ -441,14 +468,15 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
default: { return unlit(raw_out(vec3<f32>(orm.a))); }
}
}
if (mode == 2) {
return unlit(raw_out(aux.rgb));
}
if (mode == 3) {
let c = floor(uv * 32.0);
let c = floor(uv * UV_CHECKER_CELLS);
let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5);
let fine = floor(uv * 256.0);
let fine = floor(uv * UV_CHECKER_FINE_CELLS);
let f2 = (fine.x + fine.y) - 2.0 * floor((fine.x + fine.y) * 0.5);
let col = mix(vec3<f32>(0.85, 0.85, 0.85), vec3<f32>(0.18, 0.2, 0.24), chk) * (0.92 + 0.08 * f2);
let tint = vec3<f32>(fract(uv.x), fract(uv.y), 0.5) * 0.25;
@@ -461,15 +489,15 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
}
// Change the alpha dither each frame so accumulation smooths it
if (base_s.a < hash12(i.clip.xy + g.material.z * vec2<f32>(17.0, 59.0))) {
if (base_s.a < hash12(i.clip.xy + g.material.z * DITHER_FRAME_STEP)) {
discard;
}
let albedo = base_s.rgb;
let ao = mix(1.0, orm.r, g.env.z);
let rough = clamp(orm.g, 0.045, 1.0);
let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0);
let metal = orm.b;
let nov = clamp(abs(dot(n, v)), 1e-4, 1.0);
let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0);
var f0 = mix(vec3<f32>(0.08 * orm.a), albedo, metal);
var diffuse_col = albedo * (1.0 - metal);
if (g.material.x > 0.5) {
@@ -484,32 +512,33 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
// Zero lobe weights preserve the base shading
let coat_w = lobes.r;
let coat_rough = clamp(lobes.g, 0.045, 1.0);
let coat_rough = clamp(lobes.g, SPECULAR_ROUGHNESS_FLOOR, 1.0);
let aniso = lobes.b;
let sheen_col = sheen_t.rgb * sheen_t.a;
let sheen_max = max3(sheen_col);
let sheen_rough = clamp(nrm_t.a, 0.07, 1.0);
let sheen_rough = clamp(nrm_t.a, SHEEN_ROUGHNESS_FLOOR, 1.0);
// Scatter color controls each channel's diffuse wrap
let wrap = emis_t.a * g.scatter.xyz;
// Stretch GGX along the tangent rotated by 0..π
let a = rough * rough;
let at = max(a * (1.0 + aniso), 0.002);
let ab = max(a * (1.0 - aniso), 0.002);
let at = max(a * (1.0 + aniso), ANISOTROPIC_ALPHA_FLOOR);
let ab = max(a * (1.0 - aniso), ANISOTROPIC_ALPHA_FLOOR);
let ang = lobes.a * PI;
let ta0 = t * cos(ang) + b * sin(ang);
let ta1 = ta0 - n * dot(n, ta0);
let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8));
let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), TANGENT_LENGTH_SQUARED_FLOOR));
let ba = cross(n, ta);
// Coat normals perturb the geometric normal independently of base detail
var n_c = n_geo;
let cn = coat_normal_ts(extra);
if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) {
if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > COAT_TILT_THRESHOLD) {
n_c = normalize(t * cn.x + b * cn.y + n_geo * cn.z);
}
let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0);
let nov_c = clamp(abs(dot(n_c, v)), GRAZING_COSINE_FLOOR, 1.0);
let coat_t = 1.0 - coat_w * schlick(0.04, nov_c);
// Coat transmission and sheen albedo limit energy reaching the base
@@ -525,18 +554,20 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
if (aniso > 0.0) {
// Bend the reflection to approximate anisotropic IBL
let bent = cross(cross(ba, v), ba);
r = reflect(-v, normalize(mix(n, bent, aniso * clamp(5.0 * rough, 0.0, 1.0))));
r = reflect(-v, normalize(mix(n, bent, aniso * clamp(ANISOTROPY_BEND_GAIN * rough, 0.0, 1.0))));
}
let pre = textureSampleLevel(env_tex, env_samp, env_uv(r), rough * g.env.y).rgb;
// Fade reflections below the geometric surface
let horizon = clamp(1.0 + 1.3 * dot(r, n_geo), 0.0, 1.0);
let horizon = clamp(1.0 + HORIZON_FADE_STRENGTH * dot(r, n_geo), 0.0, 1.0);
let spec = pre * env_brdf(f0, rough, nov) * ao * horizon * horizon;
var layers = vec3<f32>(0.0);
if (sheen_max > 0.0) {
let pre_s = textureSampleLevel(env_tex, env_samp, env_uv(reflect(-v, n)), sheen_rough * g.env.y).rgb;
layers += pre_s * sheen_col * (sheen_e * ao * coat_t);
}
if (coat_w > 0.0) {
let pre_c = textureSampleLevel(env_tex, env_samp, env_uv(reflect(-v, n_c)), coat_rough * g.env.y).rgb;
layers += pre_c * env_brdf(vec3<f32>(0.04), coat_rough, nov_c) * (coat_w * ao);
@@ -545,14 +576,15 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
if (trans > 0.0) {
// Approximate one refraction interface; the path tracer also handles the exit
var td = refract(-v, n, 1.0 / max(g.material.w, 1.0));
if (dot(td, td) < 1e-6) {
if (dot(td, td) < REFRACTION_LENGTH_SQUARED_FLOOR) {
td = reflect(-v, n);
}
var behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb;
if (g.refr.x > 0.5) {
// Composite the refracted screen sample over the environment fallback
let p = g.view_proj * vec4<f32>(i.wpos + td * g.refr.z, 1.0);
let s = p.xy / max(p.w, 1e-6);
let s = p.xy / max(p.w, PROJECTION_W_FLOOR);
let suv = vec2<f32>(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5);
if (p.w > 0.0 && all(suv >= vec2<f32>(0.0)) && all(suv <= vec2<f32>(1.0))) {
let lod = g.refr.y * rough * clamp(g.material.w * 2.0 - 2.0, 0.0, 1.0);
@@ -578,6 +610,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
} else {
dv = ggx_dv(a, nov, nol, noh);
}
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
// Normalize wrapped Lambert to conserve energy
@@ -588,10 +621,12 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
let sa = sheen_rough * sheen_rough;
direct += sheen_col * (d_charlie(sa, noh) * sheen_vis(nov, nol, sa) * nol * g.light.w * coat_t);
}
if (coat_w > 0.0) {
let nol_c = max(dot(n_c, l), 0.0);
direct += vec3<f32>(ggx_dv(coat_rough * coat_rough, nov_c, nol_c, max(dot(n_c, h), 0.0)) * schlick(0.04, voh) * coat_w * nol_c * g.light.w);
}
if (g.shadow.x > 0.5 && nol > 0.0) {
let sh = shadow_factor(i.wpos, n_geo);
direct *= sh;
@@ -602,7 +637,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
return Shaded(vec4<f32>((diffuse + spec) * base_scale + layers + direct + emis, 1.0), (diffuse * base_scale + direct_diffuse) * emis_t.a);
}
// The 2D UV view: unlit material color (or the selected debug channel) over the UV layout.
// The 2D UV view shows unlit color or a debug channel over the UV layout
@fragment
fn fs_uv(i: VOut) -> @location(0) vec4<f32> {
let base_s = textureSample(t_base, samp, i.uv);
@@ -615,10 +650,11 @@ fn fs_uv(i: VOut) -> @location(0) vec4<f32> {
let sheen = textureSample(t_sheen, samp, i.uv);
return lobe_view(ch, lobes, sheen, textureSample(t_nrm, samp, i.uv).a, textureSample(t_emis, samp, i.uv).a, textureSample(t_extra, samp, i.uv));
}
switch ch {
case 1: { return data_out(vec3<f32>(orm.b)); }
case 2: { return data_out(vec3<f32>(orm.g)); }
case 3: { return raw_out(textureSample(t_nrm, samp, i.uv).rgb); }
case 3: { return raw_out(textureSample(t_nrm, samp, i.uv).rgb * 0.5 + 0.5); }
case 4: { return raw_out(vec3<f32>(textureSample(t_height, samp, i.uv).r * 0.5 + 0.5)); }
case 5: { return data_out(textureSample(t_emis, samp, i.uv).rgb); }
case 6: { return raw_out(vec3<f32>(base_s.a)); }
@@ -629,15 +665,18 @@ fn fs_uv(i: VOut) -> @location(0) vec4<f32> {
default: { return data_out(base_s.rgb); }
}
}
if (mode == 2) {
return raw_out(textureSample(t_aux, samp, i.uv).rgb);
}
if (mode == 3) {
let c = floor(i.uv * 32.0);
let c = floor(i.uv * UV_CHECKER_CELLS);
let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5);
return data_out(mix(vec3<f32>(0.85), vec3<f32>(0.18, 0.2, 0.24), chk));
}
// Lightly shade by the AO so the flat 2D material view still reads as a surface.
// Light AO shading keeps the flat 2D material view readable
return data_out(base_s.rgb * mix(1.0, orm.r, 0.5));
}
+18 -8
View File
@@ -254,6 +254,10 @@ fn rnm(base: vec3<f32>, detail: vec3<f32>) -> vec3<f32> {
return normalize_or(t * dot(t, u) - u * t.z, vec3<f32>(0.0, 0.0, 1.0));
}
// Roughness floors keep specular lobes finite
const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045;
const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07;
fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
let p0 = tri_p(hit.idx, 0u);
let p1 = tri_p(hit.idx, 1u);
@@ -272,9 +276,11 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
if (!front) {
geo = -geo;
}
if (dot(n_geo, geo) < 0.0) {
n_geo = -n_geo;
}
let a0 = verts[ix.x * 2u + 1u];
let a1 = verts[ix.y * 2u + 1u];
let a2 = verts[ix.z * 2u + 1u];
@@ -291,7 +297,8 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0);
let info = P.sets[layer];
// A UV tile smaller than its atlas block: Extra alpha holds 32 × log2(1 / its share), as in mesh.wgsl.
// Extra alpha stores 32 × log2(1 / UV tile scale)
let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0);
var n_height = vec3<f32>(0.0, 0.0, 1.0);
if (k != 0.0) {
@@ -299,9 +306,9 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
let hy = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r;
n_height = normalize_or(vec3<f32>(-hx * 0.5 * k, hy * 0.5 * k, 1.0), vec3<f32>(0.0, 0.0, 1.0));
}
// 8-bit normals centred on 128, so the flat normal (128, 128, 255) is exactly +z (with
// `× 2 − 1` it would lean 0.3°, shifting every reflection).
let detail = normalize_or((nrm_t.rgb * 255.0 - 128.0) / 127.0, vec3<f32>(0.0, 0.0, 1.0));
// The signed normal in half floats, as in mesh.wgsl (flat is exactly +z)
let detail = normalize_or(clamp(nrm_t.rgb, vec3<f32>(-1.0), vec3<f32>(1.0)), vec3<f32>(0.0, 0.0, 1.0));
let n_ts = rnm(n_height, detail);
let tt = normalize_or(tw - n_geo * dot(n_geo, tw), onb_t(n_geo));
let b = cross(n_geo, tt) * tsign;
@@ -309,6 +316,7 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
if (dot(n, -d) <= 0.0) {
n = n_geo;
}
let angle = clamp(lobes.a, 0.0, 1.0) * PI;
let turned = tt * cos(angle) + b * sin(angle);
let tangent = normalize_or(turned - n * dot(n, turned), onb_t(n));
@@ -326,11 +334,13 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
diffuse = base * (1.0 - metallic);
f0 = mix(vec3<f32>(0.08 * level), base, metallic);
}
// The coat normal packs x and y as 128 + 127·n (flat: exactly 0); z is rebuilt.
// The coat normal packs x and y around 128 so flat stays exact
let coat_base = select(geo, n_geo, dot(n_geo, -d) > 0.0);
let cxy = (extra.xy * 255.0 - 128.0) / 127.0;
let c = normalize_or(vec3<f32>(cxy, sqrt(max(1.0 - dot(cxy, cxy), 0.0))), vec3<f32>(0.0, 0.0, 1.0));
let coat_turned = normalize_or(tt * c.x + b * c.y + coat_base * c.z, coat_base);
var s: Surface;
s.pos = o + d * hit.t;
s.geo = geo;
@@ -338,15 +348,15 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
s.tangent = tangent;
s.diffuse = diffuse;
s.f0 = f0;
s.roughness = clamp(orm.g, 0.045, 1.0);
s.roughness = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0);
s.emissive = emi.rgb;
s.opacity = clamp(base_t.a, 0.0, 1.0);
s.anisotropy = clamp(lobes.b, 0.0, 1.0);
s.coat = clamp(lobes.r, 0.0, 1.0);
s.coat_roughness = max(clamp(lobes.g, 0.0, 1.0), 0.045);
s.coat_roughness = max(clamp(lobes.g, 0.0, 1.0), SPECULAR_ROUGHNESS_FLOOR);
s.coat_n = select(coat_base, coat_turned, dot(coat_turned, -d) > 0.0);
s.sheen = clamp(sheen_t.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * clamp(sheen_t.a, 0.0, 1.0);
s.sheen_roughness = max(clamp(nrm_t.a, 0.0, 1.0), 0.07);
s.sheen_roughness = max(clamp(nrm_t.a, 0.0, 1.0), SHEEN_ROUGHNESS_FLOOR);
s.scatter = clamp(emi.a, 0.0, 1.0);
s.transmission = clamp(extra.b, 0.0, 1.0) * (1.0 - metallic);
s.base = clamp(base, vec3<f32>(0.0), vec3<f32>(1.0));
+15
View File
@@ -1026,3 +1026,18 @@ fn painted_placeholders_render_like_full_textures() {
let [r1, g1, _] = red.at(w / 2, hgt / 2);
assert!(r1 > r0 && g1 < g0, "the painted base color shows: {:?} → {:?}", before.at(w / 2, hgt / 2), red.at(w / 2, hgt / 2));
}
#[test]
fn signed_half_float_normal_tiles_change_shading() {
let Some((mut headless, frame)) = setup() else { return };
let flat = render(&mut headless, &frame, "flat_main_normal");
let tilted_normal: Vec<u8> = [0.8, 0.0, 0.6, 0.5].into_iter().flat_map(|value| half::f16::from_f32(value).to_le_bytes()).collect();
fill(&mut headless, &[0, 1], DisplayKind::Normal, &tilted_normal);
let tilted = render(&mut headless, &frame, "tilted_main_normal");
let (flat_pixels, _) = flat.px.as_chunks::<4>();
let (tilted_pixels, _) = tilted.px.as_chunks::<4>();
let changed_pixels = flat_pixels.iter().zip(tilted_pixels).filter(|(before, after)| before != after).count();
assert!(changed_pixels > 100, "the signed normal should change the material highlight: {changed_pixels} pixels");
}
+51 -7
View File
@@ -10,8 +10,9 @@ pub const TILE_AREA: usize = (TILE * TILE) as usize;
/// A tile's texel data: `TILE_AREA × comps` interleaved components.
pub type TileData = Arc<Vec<u16>>;
/// An image split into 64×64 tiles; unallocated tiles read as zero. Cloning shares every tile,
/// so snapshots for undo cost one `Arc` clone per allocated tile.
/// An image split into 64×64 tiles; unallocated tiles read as zero. Cloning shares the tile table
/// and every tile, so a snapshot costs one reference-count bump; the first write after a clone
/// copies the table (one pointer per tile slot) once.
#[derive(Clone, Debug, PartialEq)]
pub struct TileImage {
width: u32,
@@ -19,7 +20,7 @@ pub struct TileImage {
comps: usize,
tiles_x: u32,
tiles_y: u32,
tiles: Vec<Option<TileData>>,
tiles: Arc<Vec<Option<TileData>>>,
}
impl TileImage {
@@ -28,7 +29,7 @@ impl TileImage {
let (width, height) = (width.max(1), height.max(1));
let tiles_x = width.div_ceil(TILE);
let tiles_y = height.div_ceil(TILE);
TileImage { width, height, comps: comps.clamp(1, 4), tiles_x, tiles_y, tiles: vec![None; (tiles_x * tiles_y) as usize] }
TileImage { width, height, comps: comps.clamp(1, 4), tiles_x, tiles_y, tiles: Arc::new(vec![None; (tiles_x * tiles_y) as usize]) }
}
pub fn width(&self) -> u32 {
@@ -65,7 +66,7 @@ impl TileImage {
let len = TILE_AREA * self.comps;
let data = data.filter(|d| d.len() == len);
if let Some(i) = self.tile_index(tx, ty)
&& let Some(slot) = self.tiles.get_mut(i)
&& let Some(slot) = Arc::make_mut(&mut self.tiles).get_mut(i)
{
*slot = data;
}
@@ -76,7 +77,7 @@ impl TileImage {
pub fn tile_mut(&mut self, tx: u32, ty: u32, fill: &[u16]) -> Option<&mut [u16]> {
let comps = self.comps;
let i = self.tile_index(tx, ty)?;
let slot = self.tiles.get_mut(i)?;
let slot = Arc::make_mut(&mut self.tiles).get_mut(i)?;
let tile = slot.get_or_insert_with(|| {
let mut v = vec![0u16; TILE_AREA * comps];
if fill.iter().any(|f| *f != 0) {
@@ -140,9 +141,19 @@ impl TileImage {
self.allocated_count() * TILE_AREA * self.comps * 2
}
/// Whether `self` and `other` share their tile table: no tile of either changed since one
/// was cloned from the other.
pub fn same_tiles(&self, other: &TileImage) -> bool {
Arc::ptr_eq(&self.tiles, &other.tiles)
}
/// Drop tiles whose every texel is zero.
pub fn prune_empty(&mut self) {
for t in &mut self.tiles {
let is_empty = |t: &Option<TileData>| t.as_ref().is_some_and(|d| d.iter().all(|v| *v == 0));
if !self.tiles.iter().any(is_empty) {
return;
}
for t in Arc::make_mut(&mut self.tiles) {
if t.as_ref().is_some_and(|d| d.iter().all(|v| *v == 0)) {
*t = None;
}
@@ -205,6 +216,39 @@ mod tests {
assert_eq!(a.get(1, 0)[0], 6);
}
#[test]
fn clone_shares_the_table_until_written() {
let mut a = TileImage::new(512, 512, 2);
a.set(0, 0, &[1, 2]);
let mut b = a.clone();
assert!(a.same_tiles(&b));
b.set(70, 0, &[3, 4]);
assert!(!a.same_tiles(&b));
assert_eq!(a.get(70, 0)[..2], [0, 0]);
assert_eq!(b.get(70, 0)[..2], [3, 4]);
assert_eq!(a.get(0, 0)[..2], [1, 2]);
assert_eq!(b.get(0, 0)[..2], [1, 2]);
}
#[test]
fn out_of_range_writes_do_not_unshare() {
let mut a = TileImage::new(512, 512, 2);
a.set(0, 0, &[1, 2]);
let mut b = a.clone();
b.set_tile(999, 999, None);
assert!(b.tile_mut(999, 999, &[0, 0]).is_none());
assert!(a.same_tiles(&b));
}
#[test]
fn noop_prune_does_not_unshare() {
let mut a = TileImage::new(512, 512, 2);
a.set(0, 0, &[1, 2]);
let mut b = a.clone();
b.prune_empty();
assert!(a.same_tiles(&b));
}
#[test]
fn tile_mut_fills_new_tiles() {
let mut img = TileImage::new(64, 64, 2);
+1 -1
View File
@@ -1714,7 +1714,7 @@ fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut
}
/// A dim info icon explaining a setting on hover
fn info_icon(ui: &mut Ui, text: &str) {
pub(crate) fn info_icon(ui: &mut Ui, text: &str) {
ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text);
}
+2
View File
@@ -42,6 +42,8 @@ mod preview_image;
mod preview_request;
mod preview_worker;
pub mod profile;
#[cfg(not(target_arch = "wasm32"))]
mod project_config;
pub mod properties_popup;
mod rail_popup;
pub mod render_mode;
+15 -1
View File
@@ -164,6 +164,11 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
"ui.newProject" => app.ui.windows.new_project = true,
"ui.export" => app.ui.windows.export = true,
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
#[cfg(not(target_arch = "wasm32"))]
"ui.projectConfig" => crate::project_config::open(app),
// The browser cannot change the mesh file, so open Display instead
#[cfg(target_arch = "wasm32")]
"ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display),
"ui.settings" => app.ui.windows.settings = true,
"ui.mode.bake" => app.ui.mode = Mode::Baking,
@@ -191,6 +196,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
if crate::windows::file_action(app, ctx, id) {
return;
}
app.run(id, Value::Null);
}
}
@@ -352,6 +358,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Escape closes a dropdown before Properties, the rail popup, color picking or the stroke
let popup_open = egui::Popup::is_any_open(ctx);
#[cfg(not(target_arch = "wasm32"))]
let nothing_focused = ctx.memory(|memory| memory.focused().is_none());
let commands_to_invoke = ctx.input_mut(|input| {
// egui's label selection copies on these events at the end of the frame
let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect();
@@ -371,7 +379,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
}
if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
if app.ui.windows.project_config.is_some() {
// Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched
#[cfg(not(target_arch = "wasm32"))]
crate::project_config::keys_in(app, input, nothing_focused, popup_open);
} else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
app.properties_popup = None;
} else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) {
app.ui.rail_panel = None;
@@ -381,6 +393,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.session.cancel_stroke();
app.session.cancel_path();
}
commands
});
@@ -391,6 +404,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Ctrl+V reaches the app only while the system clipboard holds text or an image
ctx.copy_text(layer.name.clone());
}
invoke(app, ctx, effect_command(app, id));
}
}
+342
View File
@@ -0,0 +1,342 @@
//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the
//! 3D mesh: pick another mesh file for the project, or read the current one again.
use std::sync::atomic::{AtomicU64, Ordering};
use egui::{Key, Modifiers};
use serde_json::{Value, json};
use texturecraft_engine::core::NormalFormat;
use crate::TextureCraftApp;
use crate::dock::info_icon;
use crate::file_dialogs::{Bound, FileDialog};
use crate::i18n::{tr, trf};
use crate::state::ProjectConfig;
use crate::theme::caption;
use crate::widgets::primary_button;
/// Room for the Select... button and its info icon beside the path.
const SELECT_BUTTON_WIDTH_POINTS: f32 = 150.0;
/// Room for an info icon at the end of a row.
const INFO_WIDTH_POINTS: f32 = 28.0;
/// Keep a usable field when the dialog is narrowed.
const MIN_FIELD_WIDTH_POINTS: f32 = 60.0;
/// Initial width of the configuration dialog.
const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0;
/// Leave space around the centered dialog on short viewports.
const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0;
/// Opens the window on the current project, with nothing chosen yet.
pub(crate) fn open(app: &mut TextureCraftApp) {
// Layout resets must not reuse an identity held by a pending file picker
static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1);
app.ui.windows.project_config = Some(ProjectConfig {
mesh: None,
reimport: false,
preserve: true,
normal_format: None,
confirm: false,
project: app.session.project_id,
opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed),
});
}
/// `text` with its beginning replaced by an ellipsis until `fits` accepts it (the end of a path
/// is the part that tells files apart).
fn elide_start(text: &str, fits: impl Fn(&str) -> bool) -> String {
if fits(text) {
return text.to_string();
}
let chars: Vec<char> = text.chars().collect();
let shown = |from: usize| format!("…{}", chars[from..].iter().collect::<String>());
// Bisection finds the longest tail that fits because each shorter tail also fits
let (mut low, mut high) = (1, chars.len());
while low < high {
let mid = low + (high - low) / 2;
if fits(&shown(mid)) {
high = mid;
} else {
low = mid + 1;
}
}
shown(low)
}
/// The keys of the open window, read in `menus::shortcuts` before any panel draws: Escape closes
/// it (and goes no further, so it doesn't cancel a stroke), Enter confirms it unless a text field
/// or button had the keyboard (`nothing_focused`), whose Enter belongs to it. An open dropdown
/// (`popup_open`) takes both keys first: Escape closes only it, Enter doesn't press OK behind it.
pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) {
if popup_open {
return;
}
let escape = input.consume_key(Modifiers::NONE, Key::Escape);
let enter = input.consume_key(Modifiers::NONE, Key::Enter);
if escape {
app.ui.windows.project_config = None;
} else if enter
&& nothing_focused
&& let Some(config) = app.ui.windows.project_config.as_mut()
{
config.confirm = true;
}
}
/// The command OK runs for the mesh: the project moves to `chosen`, or `reimport` (the project's
/// own file, when Reimport mesh is ticked) is read again. `preserve` is the Import settings box.
fn mesh_command(chosen: Option<&str>, reimport: Option<&str>, preserve: bool) -> Option<(&'static str, Value)> {
match (chosen, reimport) {
(Some(path), _) => Some(("file.changeMesh", json!({"path": path, "preserveStrokes": preserve}))),
(None, Some(path)) => Some(("file.reimportMesh", json!({"path": path, "preserveStrokes": preserve}))),
(None, None) => None,
}
}
fn format_name(format: NormalFormat) -> &'static str {
match format {
NormalFormat::OpenGl => "OpenGL",
NormalFormat::DirectX => "DirectX",
}
}
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(mut config) = app.ui.windows.project_config.clone() else { return };
// Choices for another project cannot be applied here
if config.project != app.session.project_id {
app.ui.windows.project_config = None;
return;
}
let project = &app.session.doc.project;
let current_mesh_path = project.mesh_path.clone();
// Show the imported name when there is no file path
let mesh_label = if current_mesh_path.is_empty() { project.mesh_file.clone() } else { current_mesh_path.clone() };
let source_file_available = app.session.remembered_mesh_path().is_some();
let current_normal_format = project.normal_format;
// Keep each texture set's tiles together for the read-only list
let texture_set_tiles: Vec<(String, Option<String>)> = project
.texture_sets
.iter()
.map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::<Vec<_>>().join(", "))))
.collect();
// Re-selecting the current path cancels an earlier choice
let chosen_mesh = config.mesh.as_ref().filter(|chosen| **chosen != current_mesh_path).cloned();
let mut open = true;
let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false);
let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open)
.default_width(DEFAULT_DIALOG_WIDTH_POINTS)
.max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0))
.vscroll(true);
dialog.show(ctx, |ui| {
// Keep the project sections in the order users expect
ui.label(caption(tr("3D MESH")));
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.label(tr("3D mesh"));
info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full."));
let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone());
let font = egui::TextStyle::Body.resolve(ui.style());
let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS);
let measure = |text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points;
if display_path.is_empty() {
ui.weak(tr("Built-in mesh"));
} else {
ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK."));
select = ui.button(tr("Select...")).clicked();
});
});
if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available {
ui.colored_label(ui.visuals().error_fg_color, tr("File not found"));
}
ui.add_space(4.0);
// A selected replacement always reads the mesh again
// A missing source file cannot be reimported
let mut reimport = config.reimport || chosen_mesh.is_some();
let can_reimport_source = chosen_mesh.is_none() && source_file_available;
let reimport_checkbox = ui
.horizontal(|ui| {
let checkbox = ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh")));
info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes"));
checkbox
})
.inner;
if can_reimport_source {
config.reimport = reimport;
} else if chosen_mesh.is_none() {
reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one."));
}
ui.add_space(8.0);
ui.label(caption(tr("Import settings")));
// Import settings matter only when a mesh will be read
let importing = chosen_mesh.is_some() || (config.reimport && source_file_available);
ui.horizontal(|ui| {
ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh")));
info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ"));
});
ui.add_space(12.0);
ui.label(caption(tr("PROJECT SETTINGS")));
ui.add_space(4.0);
let shown_format = config.normal_format.unwrap_or(current_normal_format);
ui.horizontal(|ui| {
ui.label(tr("Normal map format"));
egui::ComboBox::from_id_salt(tr("Normal map format"))
.width((ui.available_width() - INFO_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS))
.wrap_mode(egui::TextWrapMode::Truncate)
.selected_text(format_name(shown_format))
.show_ui(ui, |ui| {
for format in [NormalFormat::OpenGl, NormalFormat::DirectX] {
if ui.selectable_label(format == shown_format, format_name(format)).clicked() {
config.normal_format = (format != current_normal_format).then_some(format);
}
}
})
.response
.on_hover_text(tr(
"For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export",
));
info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."));
});
ui.add_space(4.0);
// Texture Set Settings owns UV tile changes
ui.horizontal(|ui| {
ui.label(tr("UV Tile settings (UDIMs)"));
info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings."));
});
if texture_set_tiles.iter().all(|(_, tile_text)| tile_text.is_none()) {
ui.label(egui::RichText::new(tr("No UV tiles")).weak());
}
for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) {
let tile_list = tile_text.as_deref().unwrap_or_default();
ui.label(
egui::RichText::new(if texture_set_tiles.len() > 1 {
trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)])
} else {
tile_list.to_string()
})
.weak(),
);
}
ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak());
ui.add_space(12.0);
ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak());
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ok |= ui.add(primary_button(ui, tr("OK"))).clicked();
cancel = ui.button(tr("Cancel")).clicked();
});
});
});
if select {
let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS);
let opening_id = config.opening_id;
app.ask_file(dialog, Bound::Project, move |app, paths| {
let Some(path) = paths.first().map(|p| p.display().to_string()) else { return };
let current_mesh_path = app.session.doc.project.mesh_path.clone();
if let Some(config) = app.ui.windows.project_config.as_mut().filter(|config| config.opening_id == opening_id) {
// Re-selecting the source file drops an earlier choice
config.mesh = (path != current_mesh_path).then_some(path);
}
});
}
// Apply the mesh first so a failed mesh change leaves the format untouched
let mut mesh_applied = false;
let done = ok && {
let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten();
mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() {
// Drop a stale reimport tick so the user can retry the remaining settings
app.toast(tr("File not found"), true);
config.reimport = false;
false
} else {
match mesh_command(chosen_mesh.as_deref(), reimport.as_deref(), config.preserve) {
Some((command, params)) => app.run(command, params).is_some(),
None => true,
}
};
// Another panel may have set the same format while this dialog was open
let format = config.normal_format.filter(|format| *format != app.session.doc.project.normal_format);
mesh_applied
&& match format {
Some(format) => {
app.run("textureSet.settings", json!({"normalFormat": if format == NormalFormat::DirectX { "directX" } else { "openGl" }})).is_some()
}
None => true,
}
};
if done || cancel || !open {
app.ui.windows.project_config = None;
} else if let Some(stored) = app.ui.windows.project_config.as_mut() {
// A file answer arrives later through the stored state
(stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false);
// A format retry must not reimport an already changed mesh
if ok && mesh_applied {
(stored.mesh, stored.reimport) = (None, false);
}
}
}
#[cfg(test)]
mod tests {
use super::{elide_start, mesh_command};
#[test]
fn a_path_that_fits_is_unchanged() {
assert_eq!(elide_start("/a/b.obj", |s| s.chars().count() <= 20), "/a/b.obj");
}
#[test]
fn a_long_path_loses_its_beginning() {
let shown = elide_start("/home/me/projects/models/hero.obj", |s| s.chars().count() <= 12);
assert_eq!(shown, "…ls/hero.obj", "the longest tail that fits, not a shorter one");
}
#[test]
fn the_import_setting_goes_to_the_command() {
for preserve in [true, false] {
let (command, params) = mesh_command(Some("/a/b.obj"), None, preserve).unwrap();
assert_eq!((command, params["preserveStrokes"].as_bool()), ("file.changeMesh", Some(preserve)));
let (command, params) = mesh_command(None, Some("/a/c.obj"), preserve).unwrap();
assert_eq!((command, params["preserveStrokes"].as_bool(), params["path"].as_str()), ("file.reimportMesh", Some(preserve), Some("/a/c.obj")));
}
assert!(mesh_command(None, None, true).is_none(), "nothing to read");
}
}
+1
View File
@@ -102,6 +102,7 @@ pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) {
}
/// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail)
#[cfg(target_arch = "wasm32")]
pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) {
if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) {
app.ui.dock.focus(panel);
+6
View File
@@ -9,6 +9,9 @@ use crate::saved_search::SavedSearch;
use crate::shelf_panes::ShelfPanes;
use crate::shelf_view::ShelfView;
mod project_config;
pub use project_config::ProjectConfig;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Mode {
#[default]
@@ -79,6 +82,9 @@ pub struct Windows {
/// The start window: new, open, recent projects (the app opens it at launch).
#[serde(skip)]
pub start: bool,
/// Edit > Project Configuration: what is chosen so far, applied by OK.
#[serde(skip)]
pub project_config: Option<ProjectConfig>,
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
#[serde(skip)]
pub unsaved: Option<Unsaved>,
@@ -0,0 +1,18 @@
/// Edit > Project Configuration: choices waiting for OK
#[derive(Clone, Debug, PartialEq, Default)]
pub struct ProjectConfig {
/// A mesh file picked with Select..., waiting for OK
pub mesh: Option<String>,
/// The user's Reimport mesh selection
pub reimport: bool,
/// Whether painted strokes follow the surface of a newly imported mesh
pub preserve: bool,
/// The selected normal map format when it differs from the project's
pub normal_format: Option<texturecraft_engine::core::NormalFormat>,
/// Whether Enter requested confirmation in the next frame
pub confirm: bool,
/// The project that was open when this window opened
pub project: u64,
/// This opening's identity, used to reject late file picker answers
pub(crate) opening_id: u64,
}
+58 -14
View File
@@ -1709,28 +1709,72 @@ pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position:
/// windowing layer reports it for Windows Ink pens, and in the browser for pens that send touch
/// events (tablets and phones); other pens come through as a mouse.
/// shortcut: the windowing layer reports no pen tilt, so tilt can't drive the brush angle yet.
fn pen_pressure(ui: &Ui) -> f32 {
let id = egui::Id::unique("pen_pressure");
let touch = ui.input(|i| {
i.raw.events.iter().rev().find_map(|e| match e {
egui::Event::Touch { phase, force, .. } => Some((*phase, force.filter(|f| f.is_finite()))),
pub fn pen_pressure(ui: &Ui) -> f32 {
let pressure_id = egui::Id::unique("pen_pressure");
let touch = ui.input(|input| {
let events = &input.raw.events;
events.iter().enumerate().rev().find_map(|(index, event)| match event {
egui::Event::Touch { device_id, id: touch_id, phase, force, .. } => {
let mut contact_force = force.filter(|pressure| pressure.is_finite());
let mut effective_phase = *phase;
if contact_force.is_none() && matches!(*phase, egui::TouchPhase::Move | egui::TouchPhase::End) {
// Recover pressure only from this contact, including an unforced press-frame move
for previous_event in events[..index].iter().rev() {
if let egui::Event::Touch { device_id: previous_device_id, id: previous_touch_id, phase: previous_phase, force: previous_force, .. } =
previous_event
&& previous_device_id == device_id
&& previous_touch_id == touch_id
{
// A completed contact cannot supply pressure to a reused touch ID
if matches!(previous_phase, egui::TouchPhase::End | egui::TouchPhase::Cancel) {
effective_phase = egui::TouchPhase::Cancel;
break;
}
contact_force = previous_force.filter(|pressure| pressure.is_finite());
if contact_force.is_none() && *previous_phase == egui::TouchPhase::Start {
effective_phase = egui::TouchPhase::Start;
break;
}
if contact_force.is_some() {
break;
}
}
}
}
Some((effective_phase, contact_force))
}
_ => None,
})
});
match touch {
Some((_, Some(f))) => {
let f = f.clamp(0.0, 1.0);
ui.data_mut(|d| d.insert_temp(id, f));
f
Some((_, Some(pressure))) => {
let pressure = pressure.clamp(0.0, 1.0);
ui.data_mut(|data| *data.get_temp_mut_or(pressure_id, pressure) = pressure);
pressure
}
// A pen lifts with no pressure, so keep its contact pressure for a tap
Some((egui::TouchPhase::End, None)) => ui.data(|d| d.get_temp(id)).unwrap_or(1.0),
// A finger must not inherit an earlier pen's pressure
Some((egui::TouchPhase::Start, None)) => {
ui.data_mut(|d| d.remove_temp::<f32>(id));
Some((egui::TouchPhase::End, None)) => ui.data(|data| data.get_temp(pressure_id)).unwrap_or(1.0),
// A touch without pressure must not inherit an earlier pen's pressure
Some((egui::TouchPhase::Start | egui::TouchPhase::Cancel, None)) => {
ui.data_mut(|data| data.remove_temp::<f32>(pressure_id));
1.0
}
_ => 1.0,
_ => {
let (primary_pressed, primary_active) =
ui.input(|input| (input.pointer.primary_pressed(), input.pointer.primary_down() || input.pointer.primary_released()));
// A fresh mouse press must not inherit the previous pen's pressure
if primary_active && !primary_pressed {
ui.data(|data| data.get_temp::<f32>(pressure_id)).unwrap_or(1.0)
} else {
ui.data_mut(|data| data.remove_temp::<f32>(pressure_id));
1.0
}
}
}
}
+3 -1
View File
@@ -23,6 +23,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
new_project(app, ctx);
about(app, ctx);
settings(app, ctx);
#[cfg(not(target_arch = "wasm32"))]
crate::project_config::show(app, ctx);
crate::keymap::window(app, ctx);
crate::windows::export(app, ctx);
#[cfg(target_arch = "wasm32")]
@@ -152,7 +154,7 @@ pub(crate) fn window<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Win
}
/// A centered dialog; `id` keeps its place across UI languages.
fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> {
pub(crate) fn dialog<'a>(id: &str, title: &str, open: &'a mut bool) -> egui::Window<'a> {
egui::Window::new(title.to_owned())
.id(egui::Id::unique(id))
.open(open)
+1
View File
@@ -27,6 +27,7 @@ mod path_in_view;
mod path_list;
mod pen_pressure;
mod polygon_fill;
mod project_config;
mod properties_popup;
mod rail;
mod shelf_drop;
+181 -31
View File
@@ -8,67 +8,73 @@ use texturecraft_ui_egui::state::ViewLayout;
/// One frame of input: the windowing layer sends a pen sample as a touch (`pen`: its phase and
/// force) plus the pointer events it drives, in the same frame. A mouse sends no touch.
fn frame(h: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Option<f32>)>, pos: Pos2, button: Option<bool>) {
let events = &mut h.input_mut().events;
fn frame(harness: &mut Harness<'_, TextureCraftApp>, pen: Option<(TouchPhase, Option<f32>)>, position: Pos2, button: Option<bool>) {
let events = &mut harness.input_mut().events;
if let Some((phase, force)) = pen {
events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase, pos, force });
events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase, pos: position, force });
}
events.push(Event::PointerMoved(pos));
events.push(Event::PointerMoved(position));
if let Some(pressed) = button {
events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
events.push(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
}
h.step();
harness.step();
}
/// Paint in the 2D view with `input` and return the summed base color alpha it added.
fn paint_2d(input: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) -> f64 {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.layout = ViewLayout::Only2D;
h.state_mut().session.tool.brush.min_size = 0.0;
h.run_steps(4);
let before = painted(&h);
input(&mut h);
h.run_steps(3);
painted(&h) - before
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.state_mut().session.tool.brush.min_size = 0.0;
harness.run_steps(4);
let before = painted(&harness);
input(&mut harness);
harness.run_steps(3);
painted(&harness) - before
}
const FROM: Pos2 = pos2(600.0, 500.0);
const STROKE_START: Pos2 = pos2(600.0, 500.0);
/// One stroke across the view, with pen `force` on every sample (None: a mouse).
fn stroke(force: Option<f32>) -> f64 {
let pen = |phase| force.map(|f| (phase, Some(f)));
let to = pos2(800.0, 500.0);
paint_2d(|h| {
frame(h, pen(TouchPhase::Start), FROM, Some(true));
for k in 1..=8 {
frame(h, pen(TouchPhase::Move), FROM + (to - FROM) * (k as f32 / 8.0), None);
let pen = |phase| force.map(|pressure| (phase, Some(pressure)));
let stroke_end = pos2(800.0, 500.0);
paint_2d(|harness| {
frame(harness, pen(TouchPhase::Start), STROKE_START, Some(true));
for sample_index in 1..=8 {
frame(harness, pen(TouchPhase::Move), STROKE_START + (stroke_end - STROKE_START) * (sample_index as f32 / 8.0), None);
}
frame(h, pen(TouchPhase::End), to, Some(false));
frame(harness, pen(TouchPhase::End), stroke_end, Some(false));
})
}
/// A tap; a pen lifts reporting no pressure (as Windows Ink does), and the dab paints then.
fn tap(force: Option<f32>) -> f64 {
paint_2d(|h| {
frame(h, force.map(|f| (TouchPhase::Start, Some(f))), FROM, Some(true));
frame(h, force.map(|_| (TouchPhase::End, None)), FROM, Some(false));
paint_2d(|harness| {
frame(harness, force.map(|pressure| (TouchPhase::Start, Some(pressure))), STROKE_START, Some(true));
frame(harness, force.map(|_| (TouchPhase::End, None)), STROKE_START, Some(false));
})
}
/// The selected layer's summed base color alpha.
fn painted(h: &Harness<'_, TextureCraftApp>) -> f64 {
let s = &h.state().session;
let id = s.selected_layer().expect("a selected layer");
let Some(img) = s.doc.pixels.layer(id, Channel::BaseColor) else { return 0.0 };
let (w, hgt) = s.doc.project.texture_sets[s.ts()].size();
(0..hgt).flat_map(|y| (0..w).map(move |x| (x, y))).map(|(x, y)| img.get(x, y)[3] as f64 / 65535.0).sum()
fn painted(harness: &Harness<'_, TextureCraftApp>) -> f64 {
let session = &harness.state().session;
let layer_id = session.selected_layer().expect("a selected layer");
let Some(image) = session.doc.pixels.layer(layer_id, Channel::BaseColor) else { return 0.0 };
let (width, height) = session.doc.project.texture_sets[session.ts()].size();
(0..height).flat_map(|y| (0..width).map(move |x| (x, y))).map(|(x, y)| image.get(x, y)[3] as f64 / 65535.0).sum()
}
#[test]
fn pen_pressure_thins_strokes_in_the_2d_view() {
let mouse = stroke(None);
let light = stroke(Some(0.2));
assert!(mouse > 10.0, "the mouse stroke painted: {mouse}");
assert!(light > 0.0 && light < mouse * 0.5, "a light pen paints a thinner stroke: {light} vs {mouse}");
}
@@ -77,6 +83,150 @@ fn pen_pressure_thins_strokes_in_the_2d_view() {
fn a_light_pen_tap_paints_a_small_dab() {
let mouse = tap(None);
let light = tap(Some(0.2));
assert!(mouse > 1.0, "the mouse click painted: {mouse}");
assert!(light > 0.0 && light < mouse * 0.25, "the tap keeps its contact pressure: {light} vs {mouse}");
}
#[test]
fn frames_omitting_touch_events_during_stroke_do_not_spike_pressure() {
let stroke_end = pos2(800.0, 500.0);
let intermittent = paint_2d(|harness| {
frame(harness, Some((TouchPhase::Start, Some(0.2))), STROKE_START, Some(true));
for sample_index in 1..=8 {
let touch = if sample_index % 2 == 0 { Some((TouchPhase::Move, Some(0.2))) } else { None };
frame(harness, touch, STROKE_START + (stroke_end - STROKE_START) * (sample_index as f32 / 8.0), None);
}
frame(harness, Some((TouchPhase::End, Some(0.2))), stroke_end, Some(false));
});
let mouse = stroke(None);
assert!(intermittent > 0.0 && intermittent < mouse * 0.5, "intermittent frames without touch keep light pressure: {intermittent} vs {mouse}");
}
#[test]
fn mouse_stroke_immediately_after_pen_release_uses_full_pressure() {
let stroke_end = pos2(800.0, 500.0);
let baseline = stroke(None);
let immediate_mouse = paint_2d(|harness| {
let tap_position = pos2(600.0, 680.0);
frame(harness, Some((TouchPhase::Start, Some(0.2))), tap_position, Some(true));
frame(harness, Some((TouchPhase::End, None)), tap_position, Some(false));
frame(harness, None, STROKE_START, Some(true));
for sample_index in 1..=8 {
frame(harness, None, STROKE_START + (stroke_end - STROKE_START) * (sample_index as f32 / 8.0), None);
}
frame(harness, None, stroke_end, Some(false));
});
assert!(immediate_mouse > baseline * 0.9, "mouse stroke after pen release keeps full pressure: {immediate_mouse} vs {baseline}");
}
#[test]
fn secondary_pressed_during_active_primary_pen_stroke_retains_light_pressure() {
let context = egui::Context::default();
let mut start_input = egui::RawInput::default();
start_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: pos2(100.0, 100.0), force: Some(0.2) });
start_input.events.push(Event::PointerButton { pos: pos2(100.0, 100.0), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
context
.run_ui(start_input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 0.2).abs() < 1e-4, "initial touch records 0.2: {pressure}");
})
.drop_without_applying_deltas();
let mut secondary_input = egui::RawInput::default();
secondary_input.events.push(Event::PointerButton { pos: pos2(110.0, 100.0), button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
context
.run_ui(secondary_input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 0.2).abs() < 1e-4, "secondary press preserves contact pressure: {pressure}");
})
.drop_without_applying_deltas();
}
#[test]
fn touch_start_and_unforced_end_in_one_frame_keep_contact_pressure() {
let context = egui::Context::default();
let position = pos2(100.0, 100.0);
let mut input = egui::RawInput::default();
input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: position, force: Some(0.2) });
input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::End, pos: position, force: None });
context
.run_ui(input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 0.2).abs() < 1e-4, "the tap keeps its contact pressure: {pressure}");
})
.drop_without_applying_deltas();
}
#[test]
fn unforced_move_on_press_frame_keeps_same_contact_pressure() {
let context = egui::Context::default();
let position = pos2(100.0, 100.0);
let mut press_input = egui::RawInput::default();
press_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: position, force: Some(0.2) });
press_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: position, force: None });
press_input.events.push(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
context
.run_ui(press_input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 0.2).abs() < 1e-4, "press frame keeps the same contact's pressure: {pressure}");
})
.drop_without_applying_deltas();
context
.run_ui(egui::RawInput::default(), |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 0.2).abs() < 1e-4, "touch-free frame keeps the recovered pressure: {pressure}");
})
.drop_without_applying_deltas();
}
#[test]
fn unforced_move_does_not_recover_a_completed_contact() {
let context = egui::Context::default();
let position = pos2(100.0, 100.0);
let mut input = egui::RawInput::default();
input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::End, pos: position, force: Some(0.2) });
input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: position, force: None });
input.events.push(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
context
.run_ui(input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 1.0).abs() < 1e-4, "a completed contact cannot supply pressure to the later move: {pressure}");
})
.drop_without_applying_deltas();
}
#[test]
fn unforced_touch_start_and_end_in_one_frame_clear_old_pen_pressure() {
let context = egui::Context::default();
let position = pos2(100.0, 100.0);
let mut pen_input = egui::RawInput::default();
pen_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: position, force: Some(0.2) });
pen_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::End, pos: position, force: None });
context
.run_ui(pen_input, |ui| {
assert!((texturecraft_ui_egui::viewport::pen_pressure(ui) - 0.2).abs() < 1e-4);
})
.drop_without_applying_deltas();
let mut finger_input = egui::RawInput::default();
finger_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Start, pos: position, force: None });
finger_input.events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::End, pos: position, force: None });
context
.run_ui(finger_input, |ui| {
let pressure = texturecraft_ui_egui::viewport::pen_pressure(ui);
assert!((pressure - 1.0).abs() < 1e-4, "a pressure-free tap clears the old pen pressure: {pressure}");
})
.drop_without_applying_deltas();
}
+719
View File
@@ -0,0 +1,719 @@
//! Edit > Project Configuration...: the 3D mesh section. File pickers are answered by the
//! override, never shown.
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
mod temp_dir;
use temp_dir::TempDir;
const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n";
const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n";
/// The format combo's tooltip, which is its accessible label.
const FORMAT_HINT: &str = "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export";
const TITLE: &str = "Project configuration";
fn temp_dir(test: &str) -> TempDir {
TempDir::new(test)
}
/// An app whose project is the quad in `dir/quad.obj` with a fill layer on it.
fn app_on_a_quad(dir: &std::path::Path) -> Harness<'static, TextureCraftApp> {
let file = dir.join("quad.obj");
std::fs::write(&file, QUAD).unwrap();
let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap();
texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
session.doc.project.mesh_path = file.display().to_string();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h
}
/// The widget of `role` and `label` inside the window, which sits at the middle of the screen
/// (a panel of the dock may show the same text).
fn in_window<'h>(h: &'h Harness<'_, TextureCraftApp>, role: Role, label: &'h str) -> egui_kittest::Node<'h> {
let middle = egui::pos2(800.0, 480.0);
h.get_all_by_role_and_label(role, label)
.min_by(|a, b| a.rect().center().distance(middle).total_cmp(&b.rect().center().distance(middle)))
.expect("the widget in the window")
}
fn click_in_window(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
in_window(h, role, label).click();
h.run_steps(3);
}
fn open_window(h: &mut Harness<'_, TextureCraftApp>) {
let ctx = h.ctx.clone();
texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig");
h.run_steps(3);
}
fn window_is_open(h: &Harness<'_, TextureCraftApp>) -> bool {
h.query_by_label(TITLE).is_some()
}
fn click(h: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
h.get_by_role_and_label(role, label).click();
h.run_steps(3);
}
/// Select... answered with `file`.
fn select(h: &mut Harness<'_, TextureCraftApp>, file: &std::path::Path) {
let file = file.to_path_buf();
h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![file.clone()]))));
click(h, Role::Button, "Select...");
}
/// The Reimport mesh box as the window shows it.
fn reimport_ticked(h: &Harness<'_, TextureCraftApp>) -> bool {
h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)
}
/// The tick the user made themselves, as stored.
fn own_tick(h: &Harness<'_, TextureCraftApp>) -> bool {
h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.reimport)
}
#[test]
fn the_menu_opens_the_window() {
let dir = temp_dir("menu");
let mut h = app_on_a_quad(&dir);
assert!(!window_is_open(&h));
open_window(&mut h);
assert!(window_is_open(&h));
assert!(h.query_by_label("3D MESH").is_some(), "the 3D mesh section");
assert!(!reimport_ticked(&h), "nothing is ticked at first");
assert!(h.state().ui.rail_panel.is_none(), "the Display panel stays where it was");
}
#[test]
fn many_texture_sets_keep_dialog_actions_reachable_in_a_short_viewport() {
let dir = temp_dir("many-tiles");
let mut h = app_on_a_quad(&dir);
let template = h.state().session.doc.project.texture_sets[0].clone();
h.state_mut().session.doc.project.texture_sets = (0..30)
.map(|index| {
let mut set = template.clone();
set.name = format!("Set {index}");
set.uv_tiles = vec![1001];
set
})
.collect();
h.set_size(egui::vec2(800.0, 480.0));
open_window(&mut h);
h.get_by_role_and_label(Role::Button, "Cancel").scroll_to_me();
h.run_steps(3);
let ok = h.get_by_role_and_label(Role::Button, "OK");
assert!(ok.rect().top() >= 0.0 && ok.rect().bottom() <= 480.0, "OK must be inside the viewport after scrolling: {:?}", ok.rect());
let cancel = h.get_by_role_and_label(Role::Button, "Cancel");
assert!(cancel.rect().top() >= 0.0 && cancel.rect().bottom() <= 480.0, "Cancel must be inside the viewport after scrolling: {:?}", cancel.rect());
cancel.click();
h.run_steps(3);
assert!(!window_is_open(&h));
}
#[test]
fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() {
let dir = temp_dir("info");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect();
let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.";
assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons");
assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles");
assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering");
// The format icon is fifth in the window's rows
let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect();
centers.sort_by(|a, b| a.y.total_cmp(&b.y));
let format_center = centers[4];
h.hover_at(format_center);
h.run_steps(30);
assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it");
}
#[test]
fn another_file_shows_its_path_and_ticks_reimport() {
let dir = temp_dir("select");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
open_window(&mut h);
select(&mut h, &tri);
assert!(h.query_by_label_contains("tri.obj").is_some(), "the chosen file is shown");
assert!(reimport_ticked(&h));
assert!(!own_tick(&h), "shown ticked, not stored as the user's tick");
assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing changes before OK");
}
#[test]
fn a_delayed_selection_does_not_change_a_reopened_window() {
let dir = temp_dir("stale-selection");
let mut harness = app_on_a_quad(&dir);
let triangle = dir.join("tri.obj");
std::fs::write(&triangle, TRIANGLE).unwrap();
open_window(&mut harness);
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![triangle.clone()]))));
harness.get_by_role_and_label(Role::Button, "Select...").click();
harness.run_steps(1);
assert_eq!(harness.state().file_dialogs.pending(), 1, "the answer has not been applied yet");
harness.state_mut().ui.windows.project_config = None;
open_window(&mut harness);
assert!(harness.state().ui.windows.project_config.as_ref().is_some_and(|config| config.mesh.is_none()));
assert_eq!(harness.state().file_dialogs.pending(), 0, "the old answer was released");
let replacement = dir.join("other.obj");
std::fs::write(&replacement, TRIANGLE).unwrap();
select(&mut harness, &replacement);
assert_eq!(harness.state().ui.windows.project_config.as_ref().and_then(|config| config.mesh.as_deref()), replacement.to_str());
}
#[test]
fn a_delayed_selection_does_not_change_a_window_reopened_after_layout_reset() {
let dir = temp_dir("reset-layout-selection");
let mut harness = app_on_a_quad(&dir);
let triangle = dir.join("tri.obj");
std::fs::write(&triangle, TRIANGLE).unwrap();
open_window(&mut harness);
harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![triangle.clone()]))));
harness.get_by_role_and_label(Role::Button, "Select...").click();
harness.run_steps(1);
assert_eq!(harness.state().file_dialogs.pending(), 1);
let context = harness.ctx.clone();
texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.resetUi");
open_window(&mut harness);
assert!(harness.state().ui.windows.project_config.as_ref().is_some_and(|config| config.mesh.is_none()));
assert_eq!(harness.state().file_dialogs.pending(), 0);
}
#[test]
fn ok_moves_the_project_to_the_chosen_mesh_and_keeps_the_layers() {
let dir = temp_dir("ok");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
let layers = h.state().session.doc.project.layers.len();
open_window(&mut h);
select(&mut h, &tri);
click(&mut h, Role::Button, "OK");
let session = &h.state().session;
assert_eq!(session.mesh.triangle_count(), 1, "the new mesh is in use");
assert_eq!(session.doc.project.mesh_file, "tri.obj");
assert!(session.doc.project.mesh_path.ends_with("tri.obj"), "Reimport mesh now follows the new file");
assert_eq!(session.doc.project.layers.len(), layers, "the layers stay");
assert!(!window_is_open(&h));
}
#[test]
fn ticking_reimport_alone_reads_the_same_file_again() {
let dir = temp_dir("reimport");
let mut h = app_on_a_quad(&dir);
let project = h.state().session.project_id;
let layers = h.state().session.doc.project.layers.len();
// The file changed on disk since it was imported
std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap();
open_window(&mut h);
click(&mut h, Role::CheckBox, "Reimport mesh");
assert!(reimport_ticked(&h) && own_tick(&h));
click(&mut h, Role::Button, "OK");
let session = &h.state().session;
assert_eq!(session.mesh.triangle_count(), 1, "the edited file was read again");
assert_eq!(session.project_id, project);
assert_eq!(session.doc.project.layers.len(), layers);
assert!(!window_is_open(&h));
}
#[test]
fn ok_with_nothing_chosen_changes_nothing() {
let dir = temp_dir("nothing");
let mut h = app_on_a_quad(&dir);
std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap();
let mesh = h.state().session.mesh_id;
open_window(&mut h);
click(&mut h, Role::Button, "OK");
assert_eq!(h.state().session.mesh_id, mesh);
assert_eq!(h.state().session.mesh.triangle_count(), 2);
assert!(!window_is_open(&h));
}
#[test]
fn cancel_changes_nothing() {
let dir = temp_dir("cancel");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
let mesh = h.state().session.mesh_id;
open_window(&mut h);
select(&mut h, &tri);
click(&mut h, Role::Button, "Cancel");
assert!(!window_is_open(&h));
assert_eq!(h.state().session.mesh_id, mesh);
assert_eq!(h.state().session.mesh.triangle_count(), 2);
// Opened again, the old choice is gone
open_window(&mut h);
assert!(!reimport_ticked(&h));
assert!(h.state().ui.windows.project_config.as_ref().is_some_and(|c| c.mesh.is_none()));
}
#[test]
fn escape_closes_the_window_and_leaves_a_stroke_alone() {
let dir = temp_dir("escape");
let mut h = app_on_a_quad(&dir);
assert_eq!(h.state().ui.mode, texturecraft_ui_egui::state::Mode::Painting, "Painting is where Escape cancels strokes");
texturecraft_engine::execute(&mut h.state_mut().session, "layer.add.paint", &json!({})).unwrap();
h.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap();
open_window(&mut h);
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!window_is_open(&h));
assert!(h.state().session.stroke_active(), "Escape went to the window, not to the stroke");
}
#[test]
fn escape_with_the_dropdown_open_closes_only_the_dropdown() {
let dir = temp_dir("escape-dropdown");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is open");
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!egui::Popup::is_any_open(&h.ctx), "Escape closed the dropdown");
assert!(window_is_open(&h), "and left the window");
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert!(!window_is_open(&h), "the next Escape closes the window");
}
#[test]
fn enter_with_the_dropdown_open_does_not_press_ok() {
let dir = temp_dir("enter-dropdown");
let mut h = app_on_a_quad(&dir);
std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap();
open_window(&mut h);
h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true;
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
// Nothing focused, as the shortcut handler needs for Enter to mean OK
h.ctx.memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
h.run_steps(1);
assert!(h.ctx.memory(|m| m.focused().is_none()), "nothing has the keyboard");
assert!(egui::Popup::is_any_open(&h.ctx), "the dropdown is still open");
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert!(window_is_open(&h), "Enter did not press OK behind the dropdown");
assert_eq!(h.state().session.mesh.triangle_count(), 2, "nothing was applied");
}
#[test]
fn ok_after_the_ticked_file_went_missing_reports_it_and_stays_open() {
let dir = temp_dir("ticked-then-missing");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
click_in_window(&mut h, Role::CheckBox, "Reimport mesh");
assert!(own_tick(&h));
std::fs::remove_file(dir.join("quad.obj")).unwrap();
h.run_steps(2);
click(&mut h, Role::Button, "OK");
assert!(window_is_open(&h), "the window stays open");
assert!(h.state().toasts.iter().any(|t| t.error && t.text == "File not found"), "the error shows as a toast");
assert!(!own_tick(&h), "the tick that can't be applied is dropped");
assert_eq!(h.state().session.mesh.triangle_count(), 2);
click(&mut h, Role::Button, "OK");
assert!(!window_is_open(&h), "a second OK has nothing left to read");
}
#[test]
fn enter_confirms_but_not_a_text_fields_enter() {
let dir = temp_dir("enter");
let mut h = app_on_a_quad(&dir);
std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap();
open_window(&mut h);
// Ticked without a click, which would leave the box focused
h.state_mut().ui.windows.project_config.as_mut().unwrap().reimport = true;
// Renaming a layer: Enter belongs to the text field
let layer = h.state().session.selected_layer().unwrap().0;
let name = h.state().session.doc.project.layers.values().find(|l| l.id.0 == layer).unwrap().name.clone();
h.state_mut().ui.rename = Some((layer, name));
h.run_steps(3);
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert!(h.state().ui.rename.is_none(), "Enter ended the rename");
assert!(window_is_open(&h), "and did not press OK");
assert_eq!(h.state().session.mesh.triangle_count(), 2);
// With nothing focused, Enter is OK
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert!(!window_is_open(&h));
assert_eq!(h.state().session.mesh.triangle_count(), 1, "the tick was applied");
}
#[test]
fn picking_the_projects_own_file_again_drops_the_choice_and_its_tick() {
let dir = temp_dir("own");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
std::fs::write(dir.join("quad.obj"), TRIANGLE).unwrap();
let mesh = h.state().session.mesh_id;
open_window(&mut h);
select(&mut h, &tri);
let own = h.state().session.doc.project.mesh_path.clone();
select(&mut h, std::path::Path::new(&own));
assert!(!reimport_ticked(&h), "the tick was only ever the file's");
click(&mut h, Role::Button, "OK");
assert_eq!(h.state().session.mesh_id, mesh, "OK does nothing");
assert_eq!(h.state().session.mesh.triangle_count(), 2);
}
#[test]
fn a_missing_file_cannot_be_reimported() {
let dir = temp_dir("missing");
let mut h = app_on_a_quad(&dir);
std::fs::remove_file(dir.join("quad.obj")).unwrap();
open_window(&mut h);
assert!(h.query_by_label("File not found").is_some());
assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled());
click(&mut h, Role::Button, "OK");
assert_eq!(h.state().file_dialogs.pending(), 0, "no second dialog");
assert!(!window_is_open(&h));
assert!(h.state().toasts.is_empty());
}
#[test]
fn a_built_in_mesh_shows_its_name_and_has_nothing_to_reimport() {
let dir = temp_dir("builtin");
let mut h = app_on_a_quad(&dir);
h.state_mut().session.doc.project.mesh_path.clear();
open_window(&mut h);
assert!(h.query_by_label("quad.obj").is_some(), "the name it was imported under");
assert!(h.query_by_label("File not found").is_none());
assert!(h.get_by_role_and_label(Role::CheckBox, "Reimport mesh").accesskit_node().is_disabled());
h.state_mut().session.doc.project.mesh_file.clear();
h.run_steps(2);
assert!(h.query_by_label("Built-in mesh").is_some());
}
#[test]
fn a_failing_change_is_reported_as_a_toast() {
let dir = temp_dir("error");
let mut h = app_on_a_quad(&dir);
let missing = dir.join("missing.obj");
open_window(&mut h);
select(&mut h, &missing);
click(&mut h, Role::Button, "OK");
assert!(h.state().toasts.iter().any(|t| t.error), "the error shows as a toast");
assert!(window_is_open(&h), "the window stays open");
assert_eq!(h.state().ui.windows.project_config.as_ref().and_then(|c| c.mesh.clone()), Some(missing.display().to_string()), "with the choice kept");
assert_eq!(h.state().session.mesh.triangle_count(), 2, "the project keeps its mesh");
}
fn project_normal_format(h: &Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::NormalFormat {
h.state().session.doc.project.normal_format
}
#[test]
fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() {
use texturecraft_engine::core::NormalFormat;
let dir = temp_dir("normal-format");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
click_in_window(&mut h, Role::Button, "DirectX");
assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "nothing changes before OK");
click(&mut h, Role::Button, "OK");
assert_eq!(project_normal_format(&h), NormalFormat::DirectX);
h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings);
h.run_steps(3);
assert!(h.query_all_by_value("DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format");
// One undo step puts it back
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);
h.run_steps(3);
assert_eq!(project_normal_format(&h), NormalFormat::OpenGl);
}
#[test]
fn cancel_discards_a_normal_map_format() {
use texturecraft_engine::core::NormalFormat;
let dir = temp_dir("normal-format-cancel");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
click_in_window(&mut h, Role::Button, "DirectX");
click(&mut h, Role::Button, "Cancel");
assert_eq!(project_normal_format(&h), NormalFormat::OpenGl);
}
#[test]
fn uv_tiles_are_shown_read_only() {
let dir = temp_dir("udim");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some());
assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles");
assert!(h.query_by_label("Change them in Texture Set Settings").is_some());
click(&mut h, Role::Button, "Cancel");
texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.uvTiles", &json!({"ts": 0, "enabled": true})).unwrap();
open_window(&mut h);
assert!(h.query_by_label("No UV tiles").is_none());
assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project");
}
#[test]
fn preserving_strokes_is_an_import_setting_of_a_mesh_that_is_read() {
let dir = temp_dir("preserve");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
let preserve_is_disabled =
|h: &Harness<'_, TextureCraftApp>| h.get_by_role_and_label(Role::CheckBox, "Preserve stroke positions on mesh").accesskit_node().is_disabled();
open_window(&mut h);
assert!(preserve_is_disabled(&h), "greyed while no mesh is going to be read");
assert!(h.state().ui.windows.project_config.as_ref().unwrap().preserve, "on by default");
select(&mut h, &tri);
assert!(!preserve_is_disabled(&h));
click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh");
assert!(!h.state().ui.windows.project_config.as_ref().unwrap().preserve);
click(&mut h, Role::Button, "OK");
assert_eq!(h.state().session.mesh.triangle_count(), 1, "the mesh changed without reprojecting strokes");
}
/// The same quad with its UVs mirrored in u.
const MIRRORED_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1 0\nvt 0 0\nvt 0 1\nvt 1 1\nf 1/1 2/2 3/3 4/4\n";
/// Paints the half of the quad with the larger x on its first layer.
fn paint_the_right_half(h: &mut Harness<'_, TextureCraftApp>) -> texturecraft_engine::core::LayerId {
use texturecraft_engine::core::Channel;
let session = &mut h.state_mut().session;
let id = session.doc.project.texture_sets[0].stack[0];
let (size, cells) = {
let cache = &session.caches[0];
let xs: Vec<(usize, f32)> =
(0..cache.size.0 as usize * cache.size.1 as usize).filter_map(|i| cache.gbuf.surface(&session.mesh, i).map(|p| (i, p.pos.x))).collect();
let (low, high) = xs.iter().fold((f32::MAX, f32::MIN), |(l, h), (_, x)| (l.min(*x), h.max(*x)));
(cache.size, xs.into_iter().filter(|(_, x)| *x > (low + high) / 2.0).map(|(i, _)| i).collect::<Vec<_>>())
};
let image = session.doc.pixels.layer_mut(id, Channel::BaseColor, size);
for i in cells {
image.set(i as u32 % size.0, i as u32 / size.0, &[65535, 0, 0, 65535]);
}
id
}
/// Painted texels on the right and on the left half of the quad's surface, away from the middle.
fn painted_halves(h: &Harness<'_, TextureCraftApp>, id: texturecraft_engine::core::LayerId) -> (usize, usize) {
use texturecraft_engine::core::Channel;
let session = &h.state().session;
let cache = &session.caches[0];
let image = session.doc.pixels.layer(id, Channel::BaseColor).unwrap();
let texels: Vec<(u32, u32, f32)> = (0..cache.size.0 * cache.size.1)
.filter_map(|i| cache.gbuf.surface(&session.mesh, i as usize).map(|p| (i % cache.size.0, i / cache.size.0, p.pos.x)))
.collect();
let (low, high) = texels.iter().fold((f32::MAX, f32::MIN), |(l, h), t| (l.min(t.2), h.max(t.2)));
// Ignore the center seam where rasterization may place texels on either side
let (middle, margin) = ((low + high) / 2.0, (high - low) * 0.05);
let painted = |x: u32, y: u32| image.get(x, y)[3] > 32768;
let right = texels.iter().filter(|t| t.2 > middle + margin && painted(t.0, t.1)).count();
let left = texels.iter().filter(|t| t.2 < middle - margin && painted(t.0, t.1)).count();
(right, left)
}
/// OK on a mirrored-UV mesh with the Preserve box as given; returns the painted (right, left) texels afterwards.
fn painted_after_changing_to_mirrored_uvs(test: &str, preserve: bool) -> ((usize, usize), (usize, usize)) {
let dir = temp_dir(test);
let mut h = app_on_a_quad(&dir);
let mirrored = dir.join("mirrored.obj");
std::fs::write(&mirrored, MIRRORED_QUAD).unwrap();
let id = paint_the_right_half(&mut h);
let before = painted_halves(&h, id);
open_window(&mut h);
select(&mut h, &mirrored);
if !preserve {
click(&mut h, Role::CheckBox, "Preserve stroke positions on mesh");
}
click(&mut h, Role::Button, "OK");
assert!(!window_is_open(&h));
(before, painted_halves(&h, id))
}
#[test]
fn preserve_on_moves_the_strokes_with_the_surface() {
let (before, after) = painted_after_changing_to_mirrored_uvs("preserve-on", true);
assert!(before.0 > 2000 && before.1 == 0, "painted on the right half: {before:?}");
assert!(after.0 > 2000 && after.1 < 200, "still on the right half of the surface: {after:?}");
}
#[test]
fn preserve_off_leaves_the_strokes_in_the_uv_layout() {
let (_, after) = painted_after_changing_to_mirrored_uvs("preserve-off", false);
assert!(after.1 > 2000 && after.0 < 200, "the paint stayed where it was in UV space, now on the left half: {after:?}");
}
#[test]
fn a_mesh_and_a_format_change_in_one_ok() {
use texturecraft_engine::core::NormalFormat;
let dir = temp_dir("both");
let mut h = app_on_a_quad(&dir);
let tri = dir.join("tri.obj");
std::fs::write(&tri, TRIANGLE).unwrap();
open_window(&mut h);
select(&mut h, &tri);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
click_in_window(&mut h, Role::Button, "DirectX");
click(&mut h, Role::Button, "OK");
assert!(!window_is_open(&h));
assert_eq!(h.state().session.mesh.triangle_count(), 1);
assert_eq!(project_normal_format(&h), NormalFormat::DirectX);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);
h.run_steps(3);
assert_eq!(project_normal_format(&h), NormalFormat::OpenGl, "the format is one undo step");
assert_eq!(h.state().session.mesh.triangle_count(), 1, "and the mesh stays");
}
#[test]
fn a_format_the_project_already_has_is_not_set_again() {
use texturecraft_engine::core::NormalFormat;
let dir = temp_dir("same-format");
let mut h = app_on_a_quad(&dir);
open_window(&mut h);
click_in_window(&mut h, Role::ComboBox, FORMAT_HINT);
click_in_window(&mut h, Role::Button, "DirectX");
// The Texture Set Settings panel sets it meanwhile
texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.settings", &json!({"normalFormat": "directX"})).unwrap();
let steps = h.state().session.history_labels().len();
click(&mut h, Role::Button, "OK");
assert_eq!(project_normal_format(&h), NormalFormat::DirectX);
assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step");
}
@@ -0,0 +1,27 @@
use std::path::{Path, PathBuf};
/// A test folder removed when its owner drops
pub(super) struct TempDir(PathBuf);
impl TempDir {
pub(super) fn new(test: &str) -> Self {
let path = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
}
impl std::ops::Deref for TempDir {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for TempDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).ok();
}
}
+2 -3
View File
@@ -226,9 +226,8 @@ fn window_views_open_the_rail_panels_popup() {
assert!(popup_shows(&harness, "Shader Settings"));
assert!(!harness.state().ui.dock.is_open(Panel::Shader));
// Project configuration opens Display Settings, in its popup too
texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig");
harness.run_steps(SETTLE_FRAMES);
// Display Settings still opens from its rail icon
click_rail(&mut harness, "Display Settings");
assert!(popup_shows(&harness, "Display Settings"));
}
+7
View File
@@ -205,6 +205,11 @@ fn window_snapshots() {
save(&mut harness, &output_dir, "window-settings");
harness.state_mut().ui.windows.settings = false;
let context = harness.ctx.clone();
texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.projectConfig");
save(&mut harness, &output_dir, "window-project-configuration");
harness.state_mut().ui.windows.project_config = None;
// A taller window exposes every mesh-map slot
harness.state_mut().ui.dock.focus(Panel::TextureSetSettings);
harness.set_size(egui::vec2(1600.0, 1800.0));
@@ -222,6 +227,7 @@ fn window_snapshots() {
texturecraft_engine::execute(session, id, &params).unwrap();
}
save(&mut harness, &output_dir, "properties-levels");
// Show the Layers panel thumbnails with a hidden content effect, a folder and a mask
let session = &mut harness.state_mut().session;
for (id, params) in [
@@ -256,6 +262,7 @@ fn window_snapshots() {
}
save(&mut harness, &output_dir, "panel-layers");
harness.set_size(egui::vec2(1600.0, 960.0));
// Show the second path selected in Properties
let session = &mut harness.state_mut().session;
for (id, params) in [
+4 -3
View File
@@ -96,9 +96,10 @@ construction and content, mask and stage rendering on a ten-layer 4096 set. Run
## Undo
`Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a
change and restores it if the change fails. Pixel data is copy-on-write (`Arc` tiles), so a
snapshot costs one reference-count bump per allocated tile, and an undo step only keeps the tiles
that actually changed.
change and restores it if the change fails. Pixel images are copy-on-write at two levels: an
image's tile table and each 64×64 tile are `Arc`-shared, so a snapshot costs one
reference-count bump per image, and an undo step keeps only the tables and tiles the change
wrote.
## Rendering
+4
View File
@@ -85,6 +85,10 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
and images and a loose USD layer's textures are read from its folder and kept in the project.
Reimport a changed mesh and your painted strokes stay on the surface. The
`file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers.
**Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the
file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted
strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and
lists its UV tiles (read only; Texture Set Settings changes them).
- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs,
other filters and height-to-normal slopes keep their size in UV space at any tile resolution)
and one texture per tile on export (`$udim`).