Merge pull request #843 from Rebornim/feat/bake-pass-3

Bake pass 3: the Baking Log, out-of-date mesh maps and Auto-rebake
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-27 17:33:15 -05:00
commit 4e8cdd6f97
80 files changed
+4021 -219

No files matched your search

+16 -3
View File
@@ -1,7 +1,7 @@
use crate::cage::RayFrame;
use crate::map::BakeContext;
use crate::tracing::{CpuTracer, Tracer};
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress};
use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake};
use std::sync::atomic::Ordering::Relaxed;
use texturecraft_core::{BakeSettings, BakedMap};
@@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> {
progress: &Progress,
excluded_tiles: &[(u32, u32)],
tracer: Option<&dyn Tracer>,
) -> Result<BakeOutput, BakeError> {
self.bake_map_in(map, progress, excluded_tiles, None, tracer)
}
/// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does
pub fn bake_map_in(
&mut self,
map: BakedMap,
progress: &Progress,
excluded_tiles: &[(u32, u32)],
region: Option<RegionBake>,
tracer: Option<&dyn Tracer>,
) -> Result<BakeOutput, BakeError> {
let mut settings = self.request.settings.clone();
settings.maps.select([map]);
self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS)
self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS)
}
pub(super) fn run(
@@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> {
settings: &BakeSettings,
progress: &Progress,
excluded_tiles: &[(u32, u32)],
region: Option<RegionBake>,
tracer: Option<&dyn Tracer>,
strip_texels: usize,
) -> Result<BakeOutput, BakeError> {
@@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> {
}
};
let context = BakeContext::with_frame(&request, *extent, frame);
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles);
let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region);
match tracer {
Some(tracer) => match bake(tracer) {
Err(BakeError::Tracer(error)) => {
+55 -6
View File
@@ -12,6 +12,8 @@ mod high_poly;
mod mesh_extent;
mod name_pair;
mod progress;
mod region_bake;
mod texel_box;
pub use bake_error::BakeError;
pub use bake_output::BakeOutput;
@@ -22,6 +24,8 @@ pub use high_poly::HighPoly;
pub(crate) use mesh_extent::MeshExtent;
pub use name_pair::NamePair;
pub use progress::Progress;
pub use region_bake::{RegionBake, region_keeps_pixels};
pub use texel_box::TexelBox;
mod map;
mod skew;
@@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24;
const BATCH: usize = 1 << 18;
// Curvature batches stay small so progress and cancellation remain responsive
const CURVATURE_BATCH: usize = 1 << 15;
/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero
const MIN_MESH_EXTENT: f32 = 1e-6;
fn validate(request: &BakeRequest) -> Result<(), BakeError> {
let settings = request.settings;
@@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing
pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result<BakeOutput, BakeError> {
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS)
bake_tiles_in(request, progress, excluded_tiles, None, tracer)
}
/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps
pub fn bake_tiles_in(
request: &BakeRequest,
progress: &Progress,
excluded_tiles: &[(u32, u32)],
region: Option<RegionBake>,
tracer: Option<&dyn Tracer>,
) -> Result<BakeOutput, BakeError> {
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS)
}
type OutRow<'a> = Vec<&'a mut [f32]>;
@@ -173,8 +190,9 @@ fn bake_in_strips(
strip_texels: usize,
tracer: &dyn Tracer,
excluded_tiles: &[(u32, u32)],
region: Option<RegionBake>,
) -> Result<BakeOutput, BakeError> {
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels)
BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels)
}
fn bake_prepared(
@@ -184,6 +202,7 @@ fn bake_prepared(
strip_texels: usize,
tracer: &dyn Tracer,
excluded_tiles: &[(u32, u32)],
region: Option<RegionBake>,
) -> Result<BakeOutput, BakeError> {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
@@ -211,7 +230,7 @@ fn bake_prepared(
let mut padding_map = None;
let total_rows = height.max(1) as u64;
let mut rows_done = 0u64;
let strip_error = || BakeError::Invalid("strip output of range".into());
let strip_error = || BakeError::Invalid("strip output out of range".into());
let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis);
let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height);
@@ -250,6 +269,16 @@ fn bake_prepared(
}
});
// Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled
if let Some(region) = region {
for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() {
let y = (sample_start_y + row_index) / samples_per_axis;
for outside in region.texels.outside_row(y, samples_per_axis, row.len()) {
row.get_mut(outside).unwrap_or_default().fill(NO_TRI);
}
}
}
let mut output_rows: Vec<OutRow> = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect();
for (map, data) in maps.iter().zip(buffers.iter_mut()) {
let component_count = map.components();
@@ -258,6 +287,7 @@ fn bake_prepared(
row.push(chunk);
}
}
let mut bake_strip = || {
for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() {
if progress.cancel.load(Relaxed) {
@@ -276,10 +306,11 @@ fn bake_prepared(
(width, samples_per_axis, sample_start_y * sample_width),
)?;
rows_done += batch.len() as u64;
progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed);
progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed);
}
Ok(())
};
if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) {
bake_strip()?;
} else {
@@ -291,6 +322,22 @@ fn bake_prepared(
}
}
if let Some(region) = region {
for (map, pixels) in maps.iter().zip(buffers.iter_mut()) {
let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len());
let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?;
let components = map.components();
let row_len = (width * components).max(1);
for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() {
for outside in region.texels.outside_row(y, components, row_len) {
if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) {
row.copy_from_slice(kept);
}
}
}
}
}
let mut output: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(buffers).collect();
if from_normal {
let world_normal =
@@ -306,7 +353,8 @@ fn bake_prepared(
}
let (bounds_min, bounds_max) = request.mesh.bounds();
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6));
map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT));
if let Some(padding_map) = padding_map {
for (map, data) in output.iter_mut() {
padding_map.apply(data, map.components());
@@ -315,11 +363,12 @@ fn bake_prepared(
}
}
}
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
progress.done.store(10_000, Relaxed);
progress.done.store(Progress::DONE, Relaxed);
Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() })
}
+4 -1
View File
@@ -8,12 +8,15 @@ pub struct Progress {
}
impl Progress {
/// The basis points of a finished bake
pub const DONE: u32 = 10_000;
pub fn new() -> Self {
Self::default()
}
pub fn fraction(&self) -> f32 {
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32
}
pub fn cancel(&self) {
+17
View File
@@ -0,0 +1,17 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use texturecraft_core::BakedMap;
use crate::TexelBox;
/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size
#[derive(Clone, Copy, Debug)]
pub struct RegionBake<'a> {
pub texels: TexelBox,
pub previous: &'a BTreeMap<BakedMap, Arc<Vec<f32>>>,
}
/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours
pub fn region_keeps_pixels(map: BakedMap) -> bool {
!matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness)
}
+3 -1
View File
@@ -28,11 +28,13 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
cage_paint: None,
tiles: (2, 1),
};
let full = bake(&request, &Progress::new()).unwrap();
for excluded in [[(0, 0)], [(1, 0)]] {
let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap();
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap();
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap();
let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap();
assert_eq!(strips.maps, partial.maps);
assert_eq!(fallback.maps, partial.maps);
assert!(fallback.tracer.contains("Broken unavailable"));
+14 -12
View File
@@ -365,9 +365,9 @@ fn two_runs_are_identical_and_sized() {
#[test]
fn strips_match_a_single_pass() {
let m = primitives::material_ball();
let bvh = Bvh::new(&m);
let s = with_rays(
let mesh = primitives::material_ball();
let bvh = Bvh::new(&mesh);
let bake_settings = with_rays(
{
let mut base = settings(64, &[]);
base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common };
@@ -377,24 +377,26 @@ fn strips_match_a_single_pass() {
4,
0.25,
);
let req = BakeRequest {
let request = BakeRequest {
low_base_color: &[],
mesh: &m,
mesh: &mesh,
bvh: &bvh,
material: 0,
settings: &s,
settings: &bake_settings,
high: None,
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let whole = bake(&req, &Progress::new()).unwrap();
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap();
for (map, a) in &whole.maps {
let b = &strips.maps[map];
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
assert!(off * 200 < a.len(), "{map:?}: {off} of {} differ", a.len());
let whole = bake(&request, &Progress::new()).unwrap();
let strips = bake_in_strips(&request, &Progress::new(), 128 * 2, &CpuTracer, &[], None).unwrap();
for (map, whole_pixels) in &whole.maps {
let strip_pixels = &strips.maps[map];
let differences = whole_pixels.iter().zip(strip_pixels).filter(|(whole, strip)| (*whole - *strip).abs() > 1e-3).count();
assert!(differences * 200 < whole_pixels.len(), "{map:?}: {differences} of {} differ", whole_pixels.len());
}
}
+57
View File
@@ -0,0 +1,57 @@
use std::ops::Range;
/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TexelBox {
pub min: (u32, u32),
pub max: (u32, u32),
}
impl TexelBox {
/// Whether texel (`x`, `y`) lies inside the box
pub fn contains(&self, x: usize, y: usize) -> bool {
(self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y)
}
/// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it
pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range<usize>; 2] {
let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) {
true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)),
false => (len, len),
};
[0..start, end.max(start)..len]
}
/// The box grown by `texels` on every side, kept inside a `width` x `height` image
pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox {
TexelBox {
min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)),
max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_items_outside_a_row_are_the_ones_contains_leaves_out() {
let (width, scale) = (6, 2);
let boxes = [
TexelBox { min: (1, 1), max: (4, 3) },
TexelBox { min: (0, 0), max: (6, 4) },
TexelBox { min: (3, 1), max: (9, 2) },
TexelBox { min: (4, 1), max: (2, 3) },
];
for texels in boxes {
for y in 0..4 {
let outside = texels.outside_row(y, scale, width * scale);
for item in 0..width * scale {
let is_outside = outside.iter().any(|range| range.contains(&item));
assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}");
}
}
}
}
}
+4
View File
@@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation;
mod ambient_occlusion_settings;
mod backface_mode;
mod bake_antialiasing;
mod bake_change;
mod bake_paint_target;
mod bake_resolution;
mod bake_settings;
mod bake_source;
mod bake_sync;
mod bake_sync_group;
mod mesh_match_mode;
@@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation;
pub use ambient_occlusion_settings::AmbientOcclusionSettings;
pub use backface_mode::BackfaceMode;
pub use bake_antialiasing::BakeAntialiasing;
pub use bake_change::BakeChange;
pub use bake_resolution::BakeResolution;
pub use bake_settings::BakeSettings;
pub use bake_source::{BakeSource, fingerprint, fingerprint_words};
pub use bake_sync::BakeSync;
pub use bake_sync_group::BakeSyncGroup;
pub use baked_map::BakedMap;
+25
View File
@@ -0,0 +1,25 @@
use serde::{Deserialize, Serialize};
/// What changed since a mesh map was baked, which makes it out of date
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BakeChange {
LowPoly,
HighPoly,
Cage,
Settings,
MapSettings,
}
impl BakeChange {
/// Identifier in automation replies
pub fn id(self) -> &'static str {
match self {
BakeChange::LowPoly => "lowPoly",
BakeChange::HighPoly => "highPoly",
BakeChange::Cage => "cage",
BakeChange::Settings => "settings",
BakeChange::MapSettings => "mapSettings",
}
}
}
+79
View File
@@ -0,0 +1,79 @@
use super::BakeChange;
use serde::{Deserialize, Serialize};
/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BakeSource {
/// The low poly's geometry
pub low_poly: u64,
/// The embedded mesh file when this map reads its material colors.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub low_material_file: Option<u64>,
/// The high poly files, in list order (0: none, the set bakes from the low poly)
pub high_poly: u64,
/// The cage file (0: none)
pub cage: u64,
/// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles
pub settings: u64,
/// The map's own settings
pub map_settings: u64,
}
impl BakeSource {
/// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date)
pub fn changes(&self, current: &BakeSource) -> Vec<BakeChange> {
// Switching color source is already reported under high poly or map settings
let material_changed = match (self.low_material_file, current.low_material_file) {
(Some(previous), Some(now)) => previous != now,
(None, None) => false,
_ => self.high_poly == current.high_poly && self.map_settings == current.map_settings,
};
[
(self.low_poly != current.low_poly || material_changed, BakeChange::LowPoly),
(self.high_poly != current.high_poly, BakeChange::HighPoly),
(self.cage != current.cage, BakeChange::Cage),
(self.settings != current.settings, BakeChange::Settings),
(self.map_settings != current.map_settings, BakeChange::MapSettings),
]
.into_iter()
.filter_map(|(changed, change)| changed.then_some(change))
.collect()
}
}
/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`)
pub fn fingerprint(bytes: &[u8]) -> u64 {
let words = bytes.chunks(8).map(|chunk| {
let mut word_bytes = [0; 8];
word_bytes[..chunk.len()].copy_from_slice(chunk);
u64::from_le_bytes(word_bytes)
});
fingerprint_words(words.chain([bytes.len() as u64]))
}
/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step
pub fn fingerprint_words(words: impl IntoIterator<Item = u64>) -> u64 {
// FNV-1a 64-bit offset basis and prime
const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fingerprint_changes_with_any_byte_and_with_the_length() {
let bytes: Vec<u8> = (0..=20).collect();
let mut changed = bytes.clone();
changed[17] ^= 1;
assert_ne!(fingerprint(&bytes), fingerprint(&changed));
assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20]));
assert_ne!(fingerprint(&[]), fingerprint(&[0]));
}
}
+21
View File
@@ -37,6 +37,11 @@ impl Default for MeshMapSettings {
}
impl MeshMapSettings {
/// Whether this map reads the source mesh's material colors, independently of its enabled flag.
pub fn reads_material_colors(&self, map: BakedMap) -> bool {
map == BakedMap::Opacity || (map == BakedMap::Id && self.id.parameters.source == super::IdColorSource::MaterialColor)
}
pub fn is_enabled(&self, map: BakedMap) -> bool {
match map {
BakedMap::Normal => self.normal.is_enabled,
@@ -84,6 +89,22 @@ impl MeshMapSettings {
}
}
/// `map`'s typed parameters as JSON
pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value {
let parameters = match map {
// These maps have no parameters of their own
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null,
BakedMap::Id => serde_json::to_value(self.id.parameters),
BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters),
BakedMap::Curvature => serde_json::to_value(self.curvature.parameters),
BakedMap::Position => serde_json::to_value(self.position.parameters),
BakedMap::Thickness => serde_json::to_value(self.thickness.parameters),
BakedMap::Height => serde_json::to_value(self.height.parameters),
BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters),
};
parameters.unwrap_or_default()
}
pub fn enabled(&self) -> impl Iterator<Item = BakedMap> {
BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map))
}
+8
View File
@@ -1268,6 +1268,14 @@ impl Generator {
if reads_geometry { &[] } else { self.kind.inputs() }
}
/// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces
pub fn baked_maps_read(&self) -> &'static [BakedMap] {
match self.kind {
GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion],
_ => self.inputs_in_use(),
}
}
/// The texture the generator blends over its signal: only on the section controls, turned on with some opacity
pub fn texture_in_use(&self) -> Option<&TextureLayer> {
self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some())
+6 -5
View File
@@ -82,11 +82,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0;
pub use anisotropic_kuwahara::AnisotropicKuwahara;
pub use backface::Backface;
pub use bake::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync,
BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings,
HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings,
MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings,
SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings,
BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings,
GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings,
MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale,
PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint,
fingerprint_words,
};
pub use bevel::Bevel;
pub use bevel_blur::BevelBlur;
+22 -1
View File
@@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result};
pub use crate::env_alignment::EnvAlignment;
pub use crate::shadow_mode::ShadowMode;
@@ -69,6 +69,12 @@ pub struct TextureSet {
/// Mesh maps that have been baked (pixels live with the engine / project file).
#[serde(default)]
pub baked: BTreeSet<BakedMap>,
/// What each baked map was baked from; a map without a record (imported, or older project) is never out of date
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub bake_sources: BTreeMap<BakedMap, BakeSource>,
/// The one mesh map the app rebakes by itself when what it is baked from changes
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_rebake: Option<BakedMap>,
#[serde(default = "yes")]
pub visible: bool,
/// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode);
@@ -171,6 +177,8 @@ impl TextureSet {
height_strength: 1.0,
bake: BakeSettings::default(),
baked: BTreeSet::new(),
bake_sources: BTreeMap::new(),
auto_rebake: None,
visible: true,
uv_tiles: Vec::new(),
bake_excluded_tiles: BTreeSet::new(),
@@ -187,6 +195,19 @@ impl TextureSet {
self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile))
}
/// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions)
pub fn bake_settings_fingerprint(&self) -> u64 {
let mut common = self.bake.common;
common.is_enabled = true;
let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles);
crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes())
}
/// Fingerprint of `map`'s own bake settings (not whether it is checked)
pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 {
crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes())
}
/// Height strength for slopes measured over the whole texture width (the viewport shader,
/// the path tracer): a UV tile atlas is one tile per column wide.
pub fn atlas_height_strength(&self) -> f32 {
+73
View File
@@ -0,0 +1,73 @@
//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes
use serde_json::{Value, json};
use texturecraft_core::{BakeSource, BakedMap};
use crate::commands::{CommandSpec, always, bad, strp, u64p};
use crate::{Result, Session, cmd};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"bake.autoRebake",
"Auto-rebake",
[],
None,
"{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes",
always,
set_auto_rebake
)]
}
fn set_auto_rebake(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "bake.autoRebake";
let texture_set = match params.get("ts") {
None => session.ts(),
Some(_) => u64p(params, "ts")
.and_then(|index| usize::try_from(index).ok())
.filter(|index| *index < session.set_count())
.ok_or_else(|| bad(COMMAND, "invalid `ts`"))?,
};
let map = match params.get("map") {
Some(Value::Null) => None,
Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?),
None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")),
};
if session.doc.project.texture_set(texture_set)?.auto_rebake != map {
session.edit("Auto-rebake", |session| {
session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map;
Ok(())
})?;
}
Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) }))
}
impl Session {
/// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now)
pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> {
let sets = self.doc.project.texture_sets.iter().enumerate();
sets.filter_map(|(index, set)| {
let map = set.auto_rebake?;
let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?;
let current = self.bake_source(index, map).ok()?;
(*record != current).then_some((index, map, current))
})
.collect()
}
/// Bake the selected map alone, or include every checked map if the atlas changed size
pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec<BakedMap> {
let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] };
let (tile_width, tile_height) = set.bake.common.output_size();
let (columns, rows) = set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows));
let (width, height) = (tile_width * columns, tile_height * rows);
let stored = self.doc.baked.get(&texture_set);
let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height));
match resized {
true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(),
false => vec![map],
}
}
}
+27
View File
@@ -0,0 +1,27 @@
use serde::Serialize;
/// Where one high poly file of a bake stands, as the Baking Log shows it
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
pub enum BakeHighState {
/// Its texture set has not started baking
Waiting,
Loading,
Loaded,
/// Its texture set's bake failed while getting the high polys ready; the reason is the error
Failed(String),
/// The bake stopped before the file was loaded
Canceled,
}
impl BakeHighState {
/// Whether the file can still change in this bake
pub fn is_pending(&self) -> bool {
matches!(self, Self::Waiting | Self::Loading)
}
/// Whether the file counts as an issue in the log
pub fn is_issue(&self) -> bool {
matches!(self, Self::Failed(_) | Self::Canceled)
}
}
+188
View File
@@ -0,0 +1,188 @@
use std::collections::HashSet;
use texturecraft_bake::NamePair;
use texturecraft_core::{BakedMap, MeshMatchMode, Project};
use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh};
use crate::Session;
/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BakeLog {
pub maps: Vec<BakeLogMap>,
/// Each high poly file of each texture set that bakes from the high polys, in bake order
pub highs: Vec<BakeLogHigh>,
/// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name"
pub matching: Option<BakeLogMatching>,
}
impl BakeLog {
/// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order
pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) {
self.maps = sets
.iter()
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
.flat_map(|(index, set)| {
set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting })
})
.collect();
self.highs = sets
.iter()
.filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set)))
.filter(|(_, set)| !set.bake.high_poly.use_low_as_high)
.flat_map(|(index, set)| {
high_polys.iter().map(move |high| BakeLogHigh {
texture_set: index,
set_name: set.name.clone(),
file: high.name.clone(),
state: BakeHighState::Waiting,
})
})
.collect();
self.matching = None;
}
/// `set` starts baking: its high polys load and its first map is the one in progress
pub fn set_started(&mut self, set: usize) {
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) {
row.state = BakeHighState::Loading;
}
self.start_next(set);
}
/// `set`'s bake has its high polys ready
pub fn high_polys_loaded(&mut self, set: usize) {
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) {
row.state = BakeHighState::Loaded;
}
}
/// `map` of `set` is baked; the set's next map starts
pub fn map_baked(&mut self, set: usize, map: BakedMap) {
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) {
row.state = BakeMapState::Baked;
}
self.start_next(set);
}
/// `set`'s bake was kept: a map it did not hand over is not baked
pub fn set_finished(&mut self, set: usize) {
for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
row.state = BakeMapState::Canceled;
}
}
/// Nothing of `set` was kept: every one of its maps failed for `reason`
pub fn set_failed(&mut self, set: usize, reason: &str) {
for row in self.maps.iter_mut().filter(|row| row.texture_set == set) {
row.state = BakeMapState::Failed(reason.to_owned());
}
// A file that loaded is not what failed
for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) {
row.state = BakeHighState::Failed(reason.to_owned());
}
}
/// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept)
pub fn cancel(&mut self, discarded: Option<usize>) {
for row in &mut self.maps {
if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) {
row.state = BakeMapState::Canceled;
}
}
self.cancel_pending_highs();
}
/// The whole bake was rolled back: every map that did not fail is canceled
pub fn discard(&mut self) {
for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) {
row.state = BakeMapState::Canceled;
}
self.cancel_pending_highs();
}
/// Whether a map is still waiting or baking
pub fn is_running(&self) -> bool {
self.maps.iter().any(|row| row.state.is_pending())
}
/// Whether a high poly file is still waiting or loading
pub fn is_loading_high_polys(&self) -> bool {
self.highs.iter().any(|row| row.state.is_pending())
}
fn cancel_pending_highs(&mut self) {
for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) {
row.state = BakeHighState::Canceled;
}
}
fn start_next(&mut self, set: usize) {
if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) {
return;
}
if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) {
row.state = BakeMapState::Baking;
}
}
}
impl Session {
/// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name
pub fn begin_bake_log(&mut self, sets: &[usize]) {
let matching = self.bake_log_matching(sets);
self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets);
self.bake_log.matching = matching;
}
/// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not
pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) {
self.begin_bake_log(sets);
let project = &self.doc.project;
self.bake_log.maps = sets
.iter()
.filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone())))
.flat_map(|(texture_set, set_name)| {
maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting })
})
.collect();
}
/// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part
fn bake_log_matching(&self, sets: &[usize]) -> Option<BakeLogMatching> {
let mut matching: Option<BakeLogMatching> = None;
let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new());
let mut every_high_used = false;
for &set in sets {
let Ok(texture_set) = self.doc.project.texture_set(set) else { continue };
let settings = &texture_set.bake.high_poly;
every_high_used |= !settings.use_low_as_high && settings.match_mode == MeshMatchMode::Always;
let Ok(Some(pairs)) = self.bake_name_pairs(set) else { continue };
let matching = matching.get_or_insert_with(|| BakeLogMatching {
low_suffix: settings.low_suffix.clone(),
high_suffix: settings.high_suffix.clone(),
pairs: Vec::new(),
});
for pair in pairs {
match (&pair.low, &pair.high) {
(None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()),
(None, _) => {}
(Some(_), high) => {
paired_highs.extend(high.clone());
matching.pairs.push(pair);
}
}
}
}
if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) {
let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high));
matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) }));
}
matching
}
}
+11
View File
@@ -0,0 +1,11 @@
use super::BakeHighState;
/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake
#[derive(Clone, Debug, PartialEq)]
pub struct BakeLogHigh {
pub texture_set: usize,
pub set_name: String,
/// The file's name as the project keeps it (the project carries the file itself, not where it came from)
pub file: String,
pub state: BakeHighState,
}
+12
View File
@@ -0,0 +1,12 @@
use texturecraft_core::BakedMap;
use super::BakeMapState;
/// One row of the Baking Log's process list: a map of a texture set in the latest bake
#[derive(Clone, Debug, PartialEq)]
pub struct BakeLogMap {
pub texture_set: usize,
pub set_name: String,
pub map: BakedMap,
pub state: BakeMapState,
}
@@ -0,0 +1,18 @@
use texturecraft_bake::NamePair;
/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name
#[derive(Clone, Debug, PartialEq)]
pub struct BakeLogMatching {
/// The suffixes the first set matching by name strips, for the column captions
pub low_suffix: String,
pub high_suffix: String,
/// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with
pub pairs: Vec<NamePair>,
}
impl BakeLogMatching {
/// How many parts found no partner
pub fn issue_count(&self) -> usize {
self.pairs.iter().filter(|pair| pair.unpaired()).count()
}
}
+26
View File
@@ -0,0 +1,26 @@
use serde::Serialize;
/// Where one map of a bake stands, as the Baking Log shows it
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase", tag = "state", content = "reason")]
pub enum BakeMapState {
Waiting,
Baking,
Baked,
/// The bake of its texture set failed; the reason is the error
Failed(String),
/// The bake stopped before this map was kept
Canceled,
}
impl BakeMapState {
/// Whether the map can still change in this bake
pub fn is_pending(&self) -> bool {
matches!(self, Self::Waiting | Self::Baking)
}
/// Whether the map counts as an issue in the log
pub fn is_issue(&self) -> bool {
matches!(self, Self::Failed(_) | Self::Canceled)
}
}
+2
View File
@@ -11,4 +11,6 @@ pub struct BakeMesh {
pub bytes: Arc<Vec<u8>>,
pub mesh: Arc<Mesh>,
pub base_color: Vec<Option<Arc<BaseColor>>>,
/// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record
pub fingerprint: u64,
}
+115
View File
@@ -0,0 +1,115 @@
//! What each baked map was baked from, and which maps are out of date since
use std::collections::BTreeMap;
use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, TextureSet, fingerprint, fingerprint_words};
use crate::{Result, Session};
impl Session {
/// What a bake of `map` on texture set `texture_set` would read now
pub fn bake_source(&self, texture_set: usize, map: BakedMap) -> Result<BakeSource> {
let set = self.doc.project.texture_set(texture_set)?;
Ok(self.map_bake_source(set, map, self.set_bake_source(set)))
}
/// The inputs of the maps selected for one task.
pub(super) fn task_bake_sources(&self, set: &TextureSet, maps: impl Iterator<Item = BakedMap>) -> BTreeMap<BakedMap, BakeSource> {
let shared = std::cell::LazyCell::new(|| self.set_bake_source(set));
maps.map(|map| (map, self.map_bake_source(set, map, *shared))).collect()
}
/// The inputs shared by every map in a texture set.
fn set_bake_source(&self, set: &TextureSet) -> BakeSource {
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
let high_poly = match from_high {
true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)),
false => 0,
};
let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile;
let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint);
BakeSource {
low_poly: self.low_poly_fingerprint(),
low_material_file: None,
high_poly,
cage,
settings: set.bake_settings_fingerprint(),
map_settings: 0,
}
}
fn map_bake_source(&self, set: &TextureSet, map: BakedMap, shared: BakeSource) -> BakeSource {
let reads_low_colors = shared.high_poly == 0 && set.bake.maps.reads_material_colors(map);
let low_material_file =
self.mesh_source.as_ref().filter(|_| reads_low_colors).map(|(_, bytes)| *self.low_material_file_fingerprint.get_or_init(|| fingerprint(bytes)));
BakeSource { low_material_file, map_settings: set.map_settings_fingerprint(map), ..shared }
}
/// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record
pub fn bake_changes(&self, texture_set: usize, map: BakedMap) -> Vec<BakeChange> {
let Ok(set) = self.doc.project.texture_set(texture_set) else { return Vec::new() };
let Some(record) = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map)) else { return Vec::new() };
self.bake_source(texture_set, map).map(|current| record.changes(&current)).unwrap_or_default()
}
/// The out-of-date maps of texture set `texture_set`, each with what changed
pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap<BakedMap, Vec<BakeChange>> {
let Ok(set) = self.doc.project.texture_set(texture_set) else { return BTreeMap::new() };
let mut records = set.bake_sources.iter().filter(|(map, _)| set.baked.contains(map)).peekable();
if records.peek().is_none() {
return BTreeMap::new();
}
let shared = self.set_bake_source(set);
let changes = records.map(|(map, record)| (*map, record.changes(&self.map_bake_source(set, *map, shared))));
changes.filter(|(_, changes)| !changes.is_empty()).collect()
}
/// Fingerprint of the low poly's geometry, tangent frame, vertex colors and part assignments (computed once per loaded mesh)
fn low_poly_fingerprint(&self) -> u64 {
*self.low_poly_fingerprint.get_or_init(|| {
let source = &self.source;
let floats = source
.positions
.iter()
.chain(&source.normals)
.flat_map(|vector| vector.to_array())
.chain(source.tangents.iter().flat_map(|tangent| tangent.to_array()))
.chain(source.uvs.iter().flat_map(|uv| uv.to_array()))
.chain(source.colors.iter().flat_map(|color| color.to_array()));
let indices = source.indices.iter().copied().map(u64::from);
let parts =
source.submeshes.iter().flat_map(|part| [fingerprint(part.name.as_bytes()), part.material as u64, part.start.into(), part.count.into()]);
fingerprint_words(floats.map(|float| u64::from(float.to_bits())).chain(indices).chain(parts))
})
}
/// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record
pub(super) fn record_bake_sources(
&mut self,
texture_set: usize,
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
stored: &[BakedMap],
) -> Result<()> {
let set = self.doc.project.texture_set_mut(texture_set)?;
match recorded {
Some((sources, _)) => set.bake_sources.extend(sources),
None => set.bake_sources.retain(|map, _| !stored.contains(map)),
}
let baked = &set.baked;
set.bake_sources.retain(|map, _| baked.contains(map));
if let Some((_, painted_stroke)) = recorded {
self.forget_painted_region(texture_set, stored, painted_stroke);
}
Ok(())
}
}
+33 -16
View File
@@ -1,12 +1,12 @@
use super::{MergedHigh, StreamedBake, StreamedMap};
use crate::{EngineError, Result};
use std::sync::Arc;
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer};
use texturecraft_compose::BakedMaps;
use texturecraft_core::{BakeSettings, BakedMap};
use texturecraft_geom::{Bvh, Mesh};
/// A self-contained bake task that can run on another thread.
/// A self-contained bake task that can run on another thread
pub struct BakeTask {
pub low_base_color: super::MaterialColors,
pub ts: usize,
@@ -14,18 +14,24 @@ pub struct BakeTask {
pub bvh: Arc<Bvh>,
pub material: usize,
pub settings: BakeSettings,
/// The merged high polys, unless the set bakes from the low poly.
/// The merged high polys, unless the set bakes from the low poly
pub high: Option<MergedHigh>,
pub cage: Option<Arc<Mesh>>,
pub skew: Option<Arc<BakePaintMap>>,
pub cage_paint: Option<Arc<BakePaintMap>>,
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles
pub tiles: (u32, u32),
/// Snapshot of tile selection and pixels to retain while the worker runs
pub excluded_tiles: Vec<(u32, u32)>,
pub previous_maps: BakedMaps,
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`)
pub tracer: Option<Arc<dyn Tracer>>,
/// What each map this task makes is baked from, taken when the task was made
pub sources: std::collections::BTreeMap<BakedMap, texturecraft_core::BakeSource>,
/// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake
pub painted_stroke: u64,
/// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel
pub region: Option<TexelBox>,
}
impl BakeTask {
@@ -34,13 +40,7 @@ impl BakeTask {
self.settings.maps.enabled().collect()
}
/// Bake the maps one after another, handing each one to `on_map` as soon as it is padded,
/// and return all of them together. Each map is a bake of its own, so with a high poly
/// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several
/// maps, in exchange for showing them as they land. The pixels are the same as `run`'s.
/// The handed-over buffers are the returned ones too (no copy is made), so a preview that
/// keeps them costs no second set of maps. A cancel or an error leaves the maps already
/// handed over whole.
/// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all
pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result<StreamedBake> {
let maps = self.maps();
let total = maps.len();
@@ -48,7 +48,7 @@ impl BakeTask {
let mut passes = BakePasses::new(self.request());
for (index, map) in maps.iter().copied().enumerate() {
let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
let Some(data) = output.maps.remove(&map) else { continue };
if combined.is_none() {
@@ -66,7 +66,14 @@ impl BakeTask {
// A resized partial bake also returns unchecked maps that must survive application
let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
retained.insert(map, data);
combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer });
combined = Some(StreamedBake {
resolution: output.resolution,
height: output.height,
maps: retained,
tracer: output.tracer,
sources: self.sources.clone(),
painted_stroke: self.painted_stroke,
});
}
}
}
@@ -80,18 +87,25 @@ impl BakeTask {
height: output.height,
maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(),
tracer: output.tracer,
sources: self.sources.clone(),
painted_stroke: self.painted_stroke,
})
}
}
}
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?;
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
Ok(output)
}
/// The texels to sample, with the stored maps to take the rest from; `None` samples every texel
fn region(&self) -> Option<RegionBake<'_>> {
self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps })
}
fn request(&self) -> BakeRequest<'_> {
let high =
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
@@ -111,7 +125,10 @@ impl BakeTask {
}
fn bake_error(error: texturecraft_bake::BakeError) -> EngineError {
EngineError::Other(format!("bake failed: {error}"))
match error {
texturecraft_bake::BakeError::Cancelled => EngineError::BakeCancelled,
error => EngineError::Other(format!("bake failed: {error}")),
}
}
#[cfg(test)]
+41
View File
@@ -0,0 +1,41 @@
//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them
use std::collections::BTreeMap;
use texturecraft_compose::BakedMaps;
use texturecraft_core::{BakeSource, BakedMap};
use crate::{Result, Session};
impl Session {
/// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps
pub fn keep_canceled_bake(
&mut self,
texture_set: usize,
finished: BakedMaps,
sources: &BTreeMap<BakedMap, BakeSource>,
painted_stroke: u64,
) -> Result<Vec<BakedMap>> {
let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) };
let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| {
!stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height))
});
if resized {
return Ok(Vec::new());
}
// A map the bake did not finish keeps the record of what its stored pixels were baked from
let kept_sources: BTreeMap<BakedMap, BakeSource> =
sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect();
let kept: Vec<BakedMap> = finished.maps.keys().copied().collect();
self.edit("Bake mesh maps", |session| {
session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke)))
})?;
// Named like the Texture Set List and the progress footer, which count sets from 1
let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone());
self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len()));
Ok(kept)
}
}
+74 -29
View File
@@ -15,8 +15,8 @@ use serde_json::{Value, json};
use texturecraft_bake::tracing::Tracer;
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
use texturecraft_core::{
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings,
SelfOcclusion,
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution,
RaySettings, SelfOcclusion,
};
use texturecraft_geom::Mesh;
@@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect();
let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty());
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color })
let fingerprint = texturecraft_core::fingerprint(&bytes);
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint })
}
impl Session {
@@ -130,9 +131,14 @@ impl Session {
self.bake_task_of(texture_set, None)
}
/// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are
pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result<BakeTask> {
self.bake_task_of(texture_set, Some(maps))
}
/// The bake of texture set `texture_set`'s map `map` alone, checked or not
pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result<BakeTask> {
self.bake_task_of(texture_set, Some(map))
self.bake_task_of(texture_set, Some(&[map]))
}
/// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles
@@ -142,20 +148,19 @@ impl Session {
Ok(task)
}
fn bake_task_of(&self, texture_set: usize, only: Option<BakedMap>) -> Result<BakeTask> {
fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> Result<BakeTask> {
let set = self.doc.project.texture_set(texture_set)?;
if !set.has_enabled_bake_tiles() {
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
}
let mut settings = set.bake.clone();
if let Some(map) = only {
settings.maps.select([map]);
if let Some(maps) = only {
settings.maps.select(maps.iter().copied());
}
// Read from the maps that bake, so a map baked alone while unchecked still gets the colours
let needs_low_color = settings.maps.opacity.is_enabled
|| (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
let needs_low_color = settings.maps.enabled().any(|map| settings.maps.reads_material_colors(map));
let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) {
self.doc
.bake_meshes
@@ -183,6 +188,8 @@ impl Session {
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() };
let tracer = chosen_tracer(GPU_TRACER.get(), GPU_RAYTRACING.load(Ordering::Relaxed));
let sources = self.task_bake_sources(set, settings.maps.enabled());
Ok(BakeTask {
low_base_color,
ts: texture_set,
@@ -198,6 +205,9 @@ impl Session {
excluded_tiles,
previous_maps,
tracer,
sources,
painted_stroke: self.painted_strokes,
region: None,
})
}
@@ -260,26 +270,36 @@ impl Session {
/// Store a finished bake as one undo step
pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
let tracer = output.tracer.clone();
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?;
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?;
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
Ok(())
}
/// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the
/// preview that showed them holds the same ones)
/// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares
pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> {
let tracer = output.tracer.clone();
self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?;
self.edit("Bake mesh maps", |session| {
session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke)))
})?;
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
Ok(())
}
fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> {
/// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`])
fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>) -> Result<()> {
let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect();
self.store_bake_maps(texture_set, output.resolution, output.height, maps)
self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded)
}
fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap<BakedMap, Arc<Vec<f32>>>) -> Result<()> {
pub(super) fn store_bake_maps(
&mut self,
texture_set: usize,
resolution: u32,
height: u32,
maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
recorded: Option<(&BTreeMap<BakedMap, BakeSource>, u64)>,
) -> Result<()> {
let stored: Vec<BakedMap> = maps.keys().copied().collect();
let entry = self.doc.baked.entry(texture_set).or_default();
let size_changed = entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height);
crate::meshmap_cmds::detach_imported_sources(&mut self.doc.project, texture_set, |map| size_changed || maps.contains_key(&map));
@@ -290,18 +310,20 @@ impl Session {
entry.resolution = resolution;
entry.maps.extend(maps);
self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect();
Ok(())
self.record_bake_sources(texture_set, recorded, &stored)
}
/// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran.
pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result<String> {
let mut task = self.bake_task(ts)?;
/// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran
pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result<String> {
let mut task = self.bake_task(texture_set)?;
if cpu {
task.tracer = None;
}
let out = task.run(&Progress::new())?;
let tracer = out.tracer.clone();
self.apply_bake(ts, out)?;
let output = task.run(&Progress::new())?;
let tracer = output.tracer.clone();
self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?;
self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})"));
Ok(tracer)
}
@@ -845,16 +867,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
for (index, settings) in next {
session.doc.project.texture_set_mut(index)?.bake = settings;
}
session.begin_bake_log(&sets);
let mut tracers = Vec::with_capacity(sets.len());
for &index in &sets {
let mut task = session.bake_task(index)?;
if cpu {
task.tracer = None;
session.bake_log.set_started(index);
let baked = bake_one_set(session, index, cpu);
match baked {
Ok(tracer) => tracers.push(tracer),
Err(error) => {
session.bake_log.set_failed(index, &error.to_string());
// The edit rolls back the sets baked before this one too
session.bake_log.discard();
return Err(error);
}
}
let output = task.run(&Progress::new())?;
tracers.push(output.tracer.clone());
session.store_bake(index, output)?;
}
Ok(tracers)
})?;
@@ -865,6 +892,24 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
Ok(json!({ "baked": sets, "tracer": tracers }))
}
/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log
fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result<String> {
let mut task = session.bake_task(index)?;
session.bake_log.high_polys_loaded(index);
if cpu {
task.tracer = None;
}
let maps = task.maps();
let output = task.run(&Progress::new())?;
let tracer = output.tracer.clone();
session.store_bake(index, output, Some((&task.sources, task.painted_stroke)))?;
for map in maps {
session.bake_log.map_baked(index, map);
}
Ok(tracer)
}
#[cfg(test)]
mod named_tracer;
+18
View File
@@ -1,10 +1,19 @@
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
mod auto_rebake;
mod bake_cage_inputs;
mod bake_checks;
mod bake_high_state;
mod bake_log;
mod bake_log_high;
mod bake_log_map;
mod bake_log_matching;
mod bake_map_state;
mod bake_mesh;
mod bake_meshes;
mod bake_sources;
mod bake_task;
mod canceled_bake;
mod high_poly_load;
mod high_poly_missed;
mod layout;
@@ -12,6 +21,7 @@ mod merged_high;
mod mesh_map_command;
mod model_patch;
mod paint_command;
mod painted_region;
mod preserve_tiles;
mod streamed_bake;
mod streamed_map;
@@ -19,6 +29,12 @@ mod sync_command;
mod tile_command;
pub use bake_cage_inputs::BakeCageInputs;
pub use bake_high_state::BakeHighState;
pub use bake_log::BakeLog;
pub use bake_log_high::BakeLogHigh;
pub use bake_log_map::BakeLogMap;
pub use bake_log_matching::BakeLogMatching;
pub use bake_map_state::BakeMapState;
pub use bake_mesh::BakeMesh;
pub use bake_meshes::BakeMeshes;
pub use bake_task::BakeTask;
@@ -27,6 +43,7 @@ pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed};
pub use merged_high::MergedHigh;
pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params};
pub use model_patch::settings_patch;
pub use painted_region::PaintedRegion;
pub use streamed_bake::StreamedBake;
pub use streamed_map::StreamedMap;
pub use texturecraft_bake::*;
@@ -38,6 +55,7 @@ type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom
pub(crate) fn specs() -> Vec<CommandSpec> {
let mut commands = mesh_map_command::specs();
commands.extend(paint_command::specs());
commands.extend(auto_rebake::specs());
commands.extend(tile_command::specs());
commands.extend(sync_command::specs());
commands
+44 -9
View File
@@ -3,7 +3,7 @@ use crate::{Result, Session, cmd};
use serde_json::Value;
use std::sync::Arc;
use texturecraft_bake::BakePaintMap;
use texturecraft_core::BakePaintTarget;
use texturecraft_core::{BakePaintTarget, BakedMap};
use texturecraft_geom::glam::Vec2;
pub(super) fn specs() -> Vec<CommandSpec> {
@@ -61,10 +61,13 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?),
};
map.validate().map_err(|error| bad("bake.paint", error.to_string()))?;
session.edit("Set Bake Paint Map", |session| {
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
Ok(())
})?;
session.note_bake_paint(texture_set, None);
Ok(super::meshes_json(session))
}
@@ -75,18 +78,31 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
session.doc.bake_paint.remove(&(texture_set, target));
Ok(())
})?;
session.note_bake_paint(texture_set, None);
}
Ok(super::meshes_json(session))
}
/// Most UV points one `bake.paint` call takes
const MAX_STROKE_POINTS: usize = 100_000;
/// Brush radius in UV units: the default, and the smallest that still paints
const DEFAULT_RADIUS: f32 = 0.03;
const MIN_RADIUS: f32 = 0.00001;
/// Brush hardness when a call gives none: halfway between a soft and a hard edge
const DEFAULT_HARDNESS: f32 = 0.5;
/// Side of a new paint map in texels: the default, and the range a call may ask for
const DEFAULT_PAINT_SIZE_TEXELS: u64 = 1024;
const PAINT_SIZE_RANGE_TEXELS: std::ops::RangeInclusive<u64> = 16..=4096;
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
const MAX_POINTS: usize = 100_000;
let texture_set = texture_set(session, parameters)?;
let points = parameters
.get("points")
.and_then(Value::as_array)
.filter(|points| !points.is_empty() && points.len() <= MAX_POINTS)
.ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?;
.filter(|points| !points.is_empty() && points.len() <= MAX_STROKE_POINTS)
.ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_STROKE_POINTS} UV coordinates")))?;
let points = points
.iter()
.map(|point| {
@@ -97,17 +113,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
}
})
.collect::<Result<Vec<_>>>()?;
let value = number(parameters, "value", 1.0, 0.0, 1.0)?;
let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?;
let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?;
let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?;
let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?;
let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?;
let size = match parameters.get("size") {
None => 1024,
None => DEFAULT_PAINT_SIZE_TEXELS,
Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?,
};
if !(16..=4096).contains(&size) {
return Err(bad("bake.paint", "size must be between 16 and 4096"));
if !PAINT_SIZE_RANGE_TEXELS.contains(&size) {
return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZE_RANGE_TEXELS.start(), PAINT_SIZE_RANGE_TEXELS.end())));
}
let default = match target {
BakePaintTarget::Cage => 1.0,
BakePaintTarget::Skew => 0.0,
@@ -116,13 +134,30 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
BakePaintTarget::Cage => "Paint Cage",
BakePaintTarget::Skew => "Paint Skew Correction",
};
session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| {
// Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one
let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target));
let set = session.doc.project.texture_set_mut(texture_set)?;
if first_skew && set.auto_rebake.is_none() {
set.auto_rebake = Some(BakedMap::Normal);
}
let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default)));
if map.values.len() == 1 {
*map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?);
}
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
})?;
// Bilinear sampling extends each dab's reach by one paint texel
let paint_texel = session.doc.bake_paint.get(&(texture_set, target)).map_or(0.0, |map| 1.0 / map.width.min(map.height).max(1) as f32);
let reach = Vec2::splat(radius + paint_texel);
let uv_min = points.iter().fold(Vec2::INFINITY, |min, point| min.min(*point)) - reach;
let uv_max = points.iter().fold(Vec2::NEG_INFINITY, |max, point| max.max(*point)) + reach;
session.note_bake_paint(texture_set, Some((uv_min, uv_max)));
Ok(super::meshes_json(session))
}
+79
View File
@@ -0,0 +1,79 @@
//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked
use texturecraft_bake::{TexelBox, region_keeps_pixels};
use texturecraft_core::{BakeSource, BakedMap};
use texturecraft_geom::glam::Vec2;
use crate::{Result, Session};
/// The UV box painted since the last bake of a texture set's auto-rebake map
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PaintedRegion {
pub uv_min: Vec2,
pub uv_max: Vec2,
/// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes
pub stroke: u64,
}
/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it
const MARGIN_TEXELS: u32 = 1;
impl Session {
/// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`)
pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) {
let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE));
let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) {
Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)),
None => (uv_min, uv_max),
};
self.painted_strokes += 1;
self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes });
}
/// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke`
pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) {
let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake);
let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke);
if !painted_since && auto.is_none_or(|map| stored.contains(&map)) {
self.doc.painted_regions.remove(&texture_set);
}
}
/// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke)
pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> {
let regions = self.doc.painted_regions.iter();
regions
.filter_map(|(index, region)| {
let set = self.doc.project.texture_sets.get(*index)?;
let map = set.auto_rebake.filter(|map| set.baked.contains(map))?;
let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty();
from_high.then_some(())?;
let current = self.bake_source(*index, map).ok()?;
// Only painting changed it: a map without a record is never out of date
let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current);
up_to_date.then_some((*index, map, current, region.stroke))
})
.collect()
}
/// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map
pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result<crate::BakeTask> {
let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?;
let Some(region) = self.doc.painted_regions.get(&texture_set) else { return Ok(task) };
let (width, height) = task.settings.common.output_size();
let stored =
self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map));
let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) };
let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size);
let painted = TexelBox {
min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)),
max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)),
};
task.previous_maps = stored.clone();
task.region = Some(painted.grown(MARGIN_TEXELS, width, height));
Ok(task)
}
}
+5 -1
View File
@@ -1,7 +1,7 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use texturecraft_core::BakedMap;
use texturecraft_core::{BakeSource, BakedMap};
/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them,
/// so the preview and the document hold one buffer per map, never two
@@ -11,4 +11,8 @@ pub struct StreamedBake {
pub height: u32,
pub maps: BTreeMap<BakedMap, Arc<Vec<f32>>>,
pub tracer: String,
/// What the baked maps were baked from (the task's [`crate::BakeTask::sources`])
pub sources: BTreeMap<BakedMap, BakeSource>,
/// The task's [`crate::BakeTask::painted_stroke`]
pub painted_stroke: u64,
}
+43
View File
@@ -0,0 +1,43 @@
//! The `bake.log` query: the Baking Log's rows for automation
use serde_json::{Value, json};
use crate::commands::{CommandSpec, always, bad};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"bake.log",
"Baking log",
[],
None,
"{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake",
always,
log
)]
}
fn log(session: &mut Session, _: &Value) -> Result<Value> {
let log = &session.bake_log;
let maps = log.maps.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "map", json!(row.map.id()))).collect::<Result<Vec<Value>>>()?;
let high_polys = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::<Result<Vec<Value>>>()?;
let matching = log.matching.as_ref().map(|matching| {
let pairs: Vec<Value> = matching.pairs.iter().map(|pair| json!({ "low": pair.low, "high": pair.high })).collect();
json!({ "lowSuffix": matching.low_suffix, "highSuffix": matching.high_suffix, "pairs": pairs })
});
Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": high_polys, "matching": matching }))
}
/// One row: its `state` (and `reason`), its texture set, and an item identified by `key`
fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, value: Value) -> Result<Value> {
let mut entry = serde_json::to_value(state).map_err(|error| bad("bake.log", error.to_string()))?;
if let Some(fields) = entry.as_object_mut() {
fields.insert("textureSet".into(), json!(texture_set));
fields.insert("setName".into(), json!(set_name));
fields.insert(key.into(), value);
}
Ok(entry)
}
+3 -3
View File
@@ -1,9 +1,9 @@
//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon
//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in
//! the document: nothing enters the undo history until a texture set's bake is applied
//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already
//! applied keep their results and undo steps. The preview shows one map at a time, raw on the
//! model; maps and texture sets not baked yet show their neutral value.
//! ([`Session::apply_streamed_bake`]). The UI can apply eligible finished maps on cancellation.
//! Already applied sets keep their results and undo steps. The preview shows one raw map at a time.
//! Maps and texture sets that are still pending show their neutral value.
mod preview_set;
mod preview_show;
+15 -2
View File
@@ -31,7 +31,7 @@ impl CommandSpec {
/// that only return data or do nothing without parameters, and the ones that replace the
/// open project (the menu asks to save first).
pub fn bindable(&self) -> bool {
const NOT_FROM_A_KEY: [&str; 14] = [
const NOT_FROM_A_KEY: &[&str] = &[
"project.inspect",
"project.templates",
"project.new",
@@ -43,6 +43,7 @@ impl CommandSpec {
"textureSet.parts",
"bake.settings",
"bake.preview",
"bake.log",
"camera.set",
"textureSet.settings",
"resource.status",
@@ -140,6 +141,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::project_cmds::specs());
v.extend(crate::bake::specs());
v.extend(crate::bake_preview::specs());
v.extend(crate::bake_log_cmds::specs());
v.extend(crate::materialx_cmds::specs());
v.extend(crate::pbr_cmds::specs());
v.extend(crate::file_cmds::specs());
@@ -373,7 +375,18 @@ mod tests {
] {
assert!(!bindable(id), "{id} needs a parameter");
}
for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] {
for id in [
"layer.move",
"layer.list",
"project.inspect",
"edit.history",
"export.presets",
"tool.state",
"project.new",
"camera.set",
"layer.blend",
"bake.log",
] {
assert!(!bindable(id), "{id} is a query or has several forms");
}
}
+15 -2
View File
@@ -293,6 +293,7 @@ impl Session {
pixels: project_file.pixels,
baked: project_file.baked,
resources,
painted_regions: Default::default(),
},
mesh,
project_file.mesh,
@@ -744,6 +745,10 @@ impl Session {
next.modified = true;
next.project_id = self.project_id;
// Keep the stroke counter aligned with the painted regions in the cloned document
next.painted_strokes = self.painted_strokes;
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
// Keep the stored source in the current session until reimport succeeds
@@ -752,6 +757,7 @@ impl Session {
}
self.switch_to(next);
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
}
}
@@ -1663,11 +1669,18 @@ f 1/1 2/2 3/3
let a = dir.join("a.obj");
std::fs::write(&a, "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").unwrap();
// Same triangle count, other vertices
// Keep the triangle count fixed while changing the geometry
let b = dir.join("b.obj");
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
let cage = crate::bake::BakeMesh {
name: "cage".into(),
folder: None,
bytes: Default::default(),
mesh: s.mesh.clone(),
base_color: Vec::new(),
fingerprint: 0,
};
s.doc.bake_meshes.cage = Some(cage);
let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into()));
+6
View File
@@ -264,6 +264,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
})
})
.collect();
let out_of_date: std::collections::BTreeMap<_, Vec<_>> =
session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect();
json!({
"index": index,
"name": texture_set.name,
@@ -276,6 +280,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
"layers": session.doc.project.walk(index).len(),
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
"outOfDate": out_of_date,
"autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id),
"visible": texture_set.visible,
"active": index == session.ts(),
})
+3
View File
@@ -11,6 +11,7 @@
pub mod add_mask_cmds;
mod anchored_micro_edit;
pub mod bake;
pub mod bake_log_cmds;
pub mod bake_preview;
pub mod brush_preset_cmds;
pub mod camera_cmds;
@@ -139,6 +140,8 @@ pub enum EngineError {
BadParams { cmd: String, msg: String },
#[error(transparent)]
Core(#[from] texturecraft_core::CoreError),
#[error("bake failed: bake cancelled")]
BakeCancelled,
#[error("{0}")]
Other(String),
}
+3
View File
@@ -70,6 +70,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
Document {
bake_meshes: Default::default(),
bake_paint: BTreeMap::new(),
@@ -77,6 +78,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
pixels: PixelStore::default(),
baked: BTreeMap::new(),
resources: BTreeMap::new(),
painted_regions: Default::default(),
}
}
@@ -145,6 +147,7 @@ impl Session {
project: project_file.project,
pixels: project_file.pixels,
baked: BTreeMap::new(),
painted_regions: Default::default(),
resources,
};
+26 -16
View File
@@ -65,14 +65,20 @@ pub(crate) fn detach_imported_sources(project: &mut Project, texture_set: usize,
/// The tile number a set without UV tiles keys its one image by
pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start();
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width
pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(s, cmd, ts, map, images)?.render();
/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `texture_set` in the caller's edit; returns its width
pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap<u32, Arc<ImageRes>>) -> Result<u32> {
let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(session, command, texture_set, map, images)?.render();
let entry = s.doc.baked.entry(ts).or_default();
let entry = session.doc.baked.entry(texture_set).or_default();
entry.resolution = width;
entry.maps.insert(map, Arc::new(data));
s.doc.project.texture_set_mut(ts)?.baked.insert(map);
let set = session.doc.project.texture_set_mut(texture_set)?;
set.baked.insert(map);
// Imported pixels have no bake provenance
set.bake_sources.remove(&map);
Ok(width)
}
@@ -128,22 +134,26 @@ fn udim_in(name: &str) -> Option<usize> {
})
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "textureSet.meshMap.clear";
let ts = ts_param(s, p, CMD)?;
let map = map_param(p, CMD)?;
if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) {
return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id())));
fn clear(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "textureSet.meshMap.clear";
let texture_set = ts_param(session, params, COMMAND)?;
let map = map_param(params, COMMAND)?;
if !session.doc.baked.get(&texture_set).is_some_and(|baked| baked.maps.contains_key(&map)) {
return Err(bad(COMMAND, format!("texture set {texture_set} has no {} map", map.id())));
}
s.edit("Clear mesh map", |s| {
if let Some(b) = s.doc.baked.get_mut(&ts) {
b.maps.remove(&map);
session.edit("Clear mesh map", |session| {
if let Some(baked) = session.doc.baked.get_mut(&texture_set) {
baked.maps.remove(&map);
}
s.doc.project.texture_set_mut(ts)?.baked.remove(&map);
detach_imported_sources(&mut s.doc.project, ts, |previous| previous == map);
let set = session.doc.project.texture_set_mut(texture_set)?;
set.baked.remove(&map);
set.bake_sources.remove(&map);
detach_imported_sources(&mut session.doc.project, texture_set, |previous| previous == map);
Ok(())
})?;
Ok(Value::Null)
}
+16
View File
@@ -33,6 +33,9 @@ pub struct Document {
pub resources: BTreeMap<String, Arc<Vec<u8>>>,
/// High-definition meshes and cage for baking (saved inside the project)
pub bake_meshes: crate::BakeMeshes,
/// Skew and cage paint bounds since each set's last Auto-rebake. Undo restores the bounds
/// with their maps. The project file omits these bounds.
pub(crate) painted_regions: BTreeMap<usize, crate::bake::PaintedRegion>,
}
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
@@ -425,6 +428,12 @@ pub struct Session {
pub project_id: u64,
/// The mesh with its own UVs (`mesh` maps UV-tiled sets into their atlas).
pub(crate) source: Arc<Mesh>,
/// Fingerprint of the bake inputs in `source`, computed on first use
pub(crate) low_poly_fingerprint: std::sync::OnceLock<u64>,
/// Fingerprint of the packed mesh file, computed only for bakes that read its material colors.
pub(crate) low_material_file_fingerprint: std::sync::OnceLock<u64>,
/// Skew and cage strokes so far
pub(crate) painted_strokes: u64,
pub bvh: Arc<Bvh>,
/// Original mesh file (saved inside the project); None for built-in meshes.
pub mesh_source: Option<(String, Arc<Vec<u8>>)>,
@@ -451,6 +460,8 @@ pub struct Session {
pub solo: Option<crate::Solo>,
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
pub bake_preview: Option<crate::bake_preview::BakePreview>,
/// The latest bake, map by map (the Baking Log)
pub bake_log: crate::bake::BakeLog,
/// Viewport size (pixels) used by scripted strokes.
pub viewport: Vec2,
pub(crate) stroke: Option<ActiveStroke>,
@@ -528,6 +539,9 @@ impl Session {
mesh_id: next_mesh_id(),
project_id: next_mesh_id(),
source,
low_poly_fingerprint: Default::default(),
low_material_file_fingerprint: Default::default(),
painted_strokes: 0,
mesh,
bvh: Arc::new(bvh),
mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))),
@@ -546,6 +560,7 @@ impl Session {
view_image: None,
solo: None,
bake_preview: None,
bake_log: Default::default(),
viewport: Vec2::new(1280.0, 800.0),
stroke: None,
clipboard: None,
@@ -649,6 +664,7 @@ impl Session {
pixels: PixelStore::default(),
baked: BTreeMap::new(),
resources: BTreeMap::new(),
painted_regions: Default::default(),
},
mesh,
mesh_source,
+1
View File
@@ -243,6 +243,7 @@ impl Session {
pixels: pf.pixels,
baked: BTreeMap::new(),
resources: BTreeMap::new(),
painted_regions: Default::default(),
};
let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default();
+3 -3
View File
@@ -1,5 +1,5 @@
//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it
//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
//! document share each map's buffer instead of holding two copies.
@@ -208,14 +208,14 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() {
assert!(result.is_err(), "a cancelled bake fails");
// The two maps that landed are whole and equal to a full bake's; the others are still neutral
// Compare the streamed pixels with a full bake to verify each preview is complete
let shown = session.bake_preview_baked(0).unwrap();
assert_eq!(shown.maps.len(), 2);
for (map, data) in &shown.maps {
assert!(**data == full.maps[map], "{map:?}");
}
// What the app does on cancel: end the preview; the document keeps what it had
// The UI applies eligible maps separately through keep_canceled_bake
session.bake_preview_end();
assert_eq!(session.doc.baked.get(&0).cloned(), before);
+231
View File
@@ -0,0 +1,231 @@
//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone
use serde_json::json;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute, sample_session};
/// A plane with its position and ID maps baked
fn baked_plane() -> Session {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap();
session
}
fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> {
session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect()
}
#[test]
fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() {
let mut session = baked_plane();
execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap();
let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first");
assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session));
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
assert_eq!(due_maps(&session), [(0, BakedMap::Position)]);
execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap();
assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session));
assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err());
}
#[test]
fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() {
let mut session = baked_plane();
let before = session.to_project_bytes().unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position));
let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap();
assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position"));
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None);
assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none");
}
#[test]
fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() {
let mut session = baked_plane();
execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap();
let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap();
assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for");
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
session.apply_streamed_bake(0, output).unwrap();
assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position));
let baked = session.baked(0).unwrap();
assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again");
assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::<Vec<_>>(), [BakedMap::Id], "the checks stay");
}
#[test]
fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() {
let mut session = baked_plane();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap();
let maps = session.auto_rebake_maps(0, BakedMap::Position);
let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap();
session.apply_streamed_bake(0, output).unwrap();
let baked = session.baked(0).unwrap();
assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::<Vec<_>>());
assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0));
}
#[test]
fn an_unchanged_uv_atlas_size_rebakes_only_the_auto_rebake_map() {
let mut session = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap();
let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
let maps = session.auto_rebake_maps(0, BakedMap::Position);
let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap();
session.apply_streamed_bake(0, output).unwrap();
let id_after = &session.baked(0).unwrap().maps[&BakedMap::Id];
assert!(std::sync::Arc::ptr_eq(&id_before, id_after), "an unchanged atlas size leaves the other map alone");
}
#[test]
fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() {
let mut session = super::bake::leaning_session(true);
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake");
let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone();
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap();
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
assert_eq!(painted, [(0, BakedMap::Position)]);
assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session));
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
task.tracer = None;
let region = task.region.expect("a stroke rebakes only its box");
let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap();
whole.tracer = None;
let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap();
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
let width = output.resolution as usize;
assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}");
let components = BakedMap::Position.components();
let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components));
let mut changed = 0;
for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() {
assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake");
if region.contains(index % width, index / width) {
changed += usize::from(rebaked != kept);
} else {
assert_eq!(rebaked, kept, "texel {index} outside the box");
}
}
assert!(changed > 0, "the stroke changed the map inside its box");
session.apply_streamed_bake(0, output).unwrap();
assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
}
#[test]
fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() {
let mut session = super::bake::leaning_session(true);
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 });
execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap();
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
task.tracer = None;
execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap();
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
session.apply_streamed_bake(0, output).unwrap();
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet");
}
#[test]
fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() {
let mut session = super::bake::leaning_session(true);
execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap();
let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap();
task.tracer = None;
let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap();
session.apply_streamed_bake(0, output).unwrap();
assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
session.undo().unwrap();
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted");
session.redo().unwrap();
assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back");
}
#[test]
fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() {
let quad = "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\nf 1/1 3/3 4/4\n";
let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap();
session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
session.reimport_mesh(None, false).unwrap();
execute(&mut session, "bake.run", &json!({})).unwrap();
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}");
}
#[test]
fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() {
let mut session = sample_session(256, 64).unwrap();
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap();
execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
let second = &mut session.doc.project.texture_sets[1].bake.maps.ao;
second.is_enabled = true;
second.parameters.rays.rays = 0;
assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast");
let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect();
assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake");
}
#[test]
fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() {
let mut session = super::bake::leaning_session(true);
let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 });
execute(&mut session, "bake.cage.paint", &stroke).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone");
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal));
execute(&mut session, "edit.undo", &json!({})).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke");
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays");
execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap();
execute(&mut session, "bake.skew.paint", &stroke).unwrap();
assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off");
}
+32 -2
View File
@@ -435,6 +435,35 @@ fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec<u8> {
glb
}
#[test]
fn reimporting_a_low_poly_texture_changes_opacity_provenance() {
use texturecraft_engine::core::BakeChange;
use texturecraft_engine::formats::MeshFile;
let mesh = primitives::builtin("plane").unwrap();
let name = "painted.glb";
let mut session = Session::from_mesh_bytes(name, &textured_glb(&mesh, 0.0, &quadrants_png()), 128, "painted").unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "opacity" })).unwrap();
let prior_opacity = session.baked(0).unwrap().maps[&BakedMap::Opacity].clone();
let mut opaque = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([255; 4])).write_to(&mut std::io::Cursor::new(&mut opaque), image::ImageFormat::Png).unwrap();
let replacement = MeshFile { name: name.into(), bytes: textured_glb(&mesh, 0.0, &opaque), warnings: Vec::new() };
session.reimport_mesh(Some(replacement), false).unwrap();
assert_eq!(session.bake_changes(0, BakedMap::Opacity), [BakeChange::LowPoly]);
assert!(session.bake_changes(0, BakedMap::Position).is_empty());
assert_eq!(session.out_of_date_maps(0).len(), 1);
assert_eq!(session.auto_rebake_due().first().map(|entry| entry.1), Some(BakedMap::Opacity));
execute(&mut session, "bake.run", &json!({})).unwrap();
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_ne!(reopened.baked(0).unwrap().maps[&BakedMap::Opacity], prior_opacity);
assert!(reopened.auto_rebake_due().is_empty());
}
#[test]
fn opacity_samples_a_textured_gltf_high_poly() {
let mut session = plane_session();
@@ -526,13 +555,14 @@ fn opacity_samples_textures_next_to_a_high_poly() {
std::fs::remove_dir_all(&dir).unwrap();
}
/// A plane session whose vertex normals lean, with a high poly plane `dy` above it.
fn leaning_session(lean: bool) -> Session {
/// Two parallel planes, with tilted low-poly vertex normals when `lean` is true.
pub(super) fn leaning_session(lean: bool) -> Session {
let mut mesh = primitives::builtin("plane").unwrap();
if lean {
mesh.normals = vec![texturecraft_engine::geom::glam::Vec3::new(0.6, 0.8, 0.0); mesh.positions.len()];
mesh.compute_tangents();
}
let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]);
let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
+198
View File
@@ -0,0 +1,198 @@
//! The Baking Log's record of the latest bake, map by map
use std::collections::BTreeSet;
use serde_json::json;
use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair};
use texturecraft_engine::compose::BakedMaps;
use texturecraft_engine::core::{BakedMap, MeshMatchMode};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute, sample_session};
#[test]
fn bake_run_lists_every_checked_map_of_the_set_as_baked() {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
let set_name = &session.doc.project.texture_sets[0].name;
let rows = &session.bake_log.maps;
let maps: BTreeSet<BakedMap> = rows.iter().map(|row| row.map).collect();
assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity]));
assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}");
assert!(!session.bake_log.is_running());
}
#[test]
fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() {
let mut session = sample_session(256, 64).unwrap();
for set in &mut session.doc.project.texture_sets {
set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]);
}
let log = &mut session.bake_log;
log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]);
log.set_started(0);
log.map_baked(0, BakedMap::Normal);
log.map_baked(0, BakedMap::Curvature);
log.set_finished(0);
log.set_started(1);
log.map_baked(1, BakedMap::Normal);
let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect();
assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress");
log.cancel(Some(1));
let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::<Vec<_>>();
assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps);
assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps);
assert!(!log.is_running());
}
#[test]
fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap();
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
assert_eq!(log["running"], false);
let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect();
assert_eq!(maps, BTreeSet::from(["opacity", "position"]));
assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}");
session.bake_log.set_failed(0, "The high poly file could not be read.");
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}");
}
#[test]
fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() {
let mut session = sample_session(256, 64).unwrap();
session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true;
execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap();
let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect();
assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]);
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}");
}
#[test]
fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() {
let mut session = sample_session(256, 64).unwrap();
session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
let log = &mut session.bake_log;
log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]);
let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone());
log.set_started(0);
assert_eq!(state(log, 0), Some(BakeHighState::Loading));
assert!(log.is_loading_high_polys());
log.set_failed(0, "The cage file could not be read.");
log.set_started(1);
log.cancel(Some(1));
assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into())));
assert_eq!(state(log, 1), Some(BakeHighState::Canceled));
assert!(!log.is_loading_high_polys());
}
#[test]
fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() {
let obj = "o Box_low\nusemtl Body\nv 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\
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
session
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
.unwrap();
session.begin_bake_log(&[0, 1]);
assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs");
for set in &mut session.doc.project.texture_sets {
set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
}
session.begin_bake_log(&[0, 1]);
let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) };
let matching = session.bake_log.matching.clone().unwrap();
assert_eq!(
matching.pairs,
[pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))],
"Box_high is paired by the other set"
);
assert_eq!(matching.issue_count(), 2);
let log = execute(&mut session, "bake.log", &json!({})).unwrap();
assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}");
}
#[test]
fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() {
let obj = "o Box_low\nusemtl Body\nv 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\
o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap();
session
.add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec())
.unwrap();
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
session.begin_bake_log(&[0, 1]);
let matching = session.bake_log.matching.clone().unwrap();
assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs);
assert_eq!(matching.issue_count(), 0);
}
#[test]
fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() {
let mut session = sample_session(256, 64).unwrap();
let before = session.baked(0).cloned().unwrap();
let resolution = before.resolution * 2;
let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]);
let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() };
let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap();
assert!(kept.is_empty(), "{kept:?}");
assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::<Vec<_>>()), Some(before.maps.keys().copied().collect()));
assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution));
}
#[test]
fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() {
let mut session = sample_session(256, 64).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap();
let stored = session.baked(0).cloned().unwrap();
let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() };
let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap();
assert_eq!(kept, [BakedMap::Id]);
assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date");
}
#[test]
fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() {
let mut session = sample_session(256, 64).unwrap();
let stored = session.baked(0).cloned().unwrap();
let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap();
let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() };
session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap();
let name = session.doc.project.texture_sets[0].name.clone();
let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap();
assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}");
}
+189
View File
@@ -0,0 +1,189 @@
//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now
use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::json;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::{BakeChange, BakedMap, CageType, IdColorSource, MeshMatchMode};
use texturecraft_engine::formats::MeshFile;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
/// A plane with its position map baked by `bake.run`
fn baked_plane() -> Session {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap();
session
}
fn changes(session: &Session) -> Vec<BakeChange> {
session.bake_changes(0, BakedMap::Position)
}
#[test]
fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() {
let mut session = baked_plane();
assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session));
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
assert_eq!(changes(&session), [BakeChange::MapSettings]);
execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap();
assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]);
let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap();
assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] }));
execute(&mut session, "bake.run", &json!({})).unwrap();
assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session));
}
#[test]
fn the_record_is_saved_with_the_project() {
let mut session = baked_plane();
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(changes(&reopened), [BakeChange::MapSettings]);
}
#[test]
fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() {
let mut old = baked_plane();
old.doc.project.texture_sets[0].bake_sources.clear();
let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap();
execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
assert!(changes(&old).is_empty(), "{:?}", changes(&old));
let mut imported = baked_plane();
let mut png = Vec::new();
image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
imported.import_resource_bytes("position.png", png).unwrap();
execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap();
execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
assert!(changes(&imported).is_empty(), "{:?}", changes(&imported));
}
#[test]
fn adding_a_high_poly_puts_the_maps_out_of_date() {
let mut session = baked_plane();
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
assert_eq!(changes(&session), [BakeChange::HighPoly]);
}
#[test]
fn replacing_low_poly_vertex_colors_marks_the_id_map_out_of_date() {
let triangle = |color: &str| format!("o Painted\nv 0 0 0 {color}\nv 1 0 0 {color}\nv 0 1 0 {color}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
let name = "painted.obj";
let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("1 0 0").as_bytes(), 128, "painted", None, false).unwrap();
session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::VertexColor;
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["id"], "dilation": 0 })).unwrap();
let previous = session.baked(0).unwrap().maps[&BakedMap::Id].clone();
let replacement = MeshFile { name: name.into(), bytes: triangle("0 1 0").into_bytes(), warnings: Vec::new() };
session.reimport_mesh(Some(replacement), false).unwrap();
assert_eq!(session.bake_changes(0, BakedMap::Id), [BakeChange::LowPoly]);
execute(&mut session, "bake.run", &json!({})).unwrap();
assert_ne!(session.baked(0).unwrap().maps[&BakedMap::Id], previous);
assert!(session.bake_changes(0, BakedMap::Id).is_empty());
}
#[test]
fn reimporting_a_quad_as_triangles_invalidates_its_tangent_frame() {
let corners = "v 0 0 0\nv 1 0 0\nv 1 1 0.6\nv 0 1 0\nvt 0 0.1\nvt 1 0\nvt 0.9 1\nvt 0.3 0.8\nvn 0 0 1\n";
let quad = format!("{corners}f 1/1/1 2/2/1 3/3/1 4/4/1\n");
let triangles = format!("{corners}f 1/1/1 2/2/1 3/3/1\nf 1/1/1 3/3/1 4/4/1\n");
let mut session = Session::from_mesh_bytes("surface.obj", quad.as_bytes(), 128, "surface").unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["normal"], "dilation": 0 })).unwrap();
let previous = session.mesh.clone();
let replacement = MeshFile { name: "surface.obj".into(), bytes: triangles.into_bytes(), warnings: Vec::new() };
session.reimport_mesh(Some(replacement), false).unwrap();
assert_eq!(session.mesh.indices, previous.indices);
assert_ne!(session.mesh.tangents, previous.tangents);
assert_eq!(session.bake_changes(0, BakedMap::Normal), [BakeChange::LowPoly]);
}
#[test]
fn renaming_a_low_poly_part_invalidates_its_by_name_bake() {
let triangle = |part: &str, height: f32| format!("o {part}\nv 0 0 {height}\nv 1 0 {height}\nv 0 1 {height}\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
let name = "parts.obj";
let mut session = Session::from_mesh_bytes_with_uvs(name, triangle("Body_low", 0.0).as_bytes(), 128, "parts", None, false).unwrap();
session.add_high_poly_bytes("detail.obj", triangle("Body_high", 0.05).into_bytes()).unwrap();
session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName;
execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().any(|pair| !pair.unpaired()));
let replacement = MeshFile { name: name.into(), bytes: triangle("Trim_low", 0.0).into_bytes(), warnings: Vec::new() };
session.reimport_mesh(Some(replacement), false).unwrap();
assert!(session.bake_name_pairs(0).unwrap().unwrap().iter().all(|pair| pair.unpaired()));
assert_eq!(changes(&session), [BakeChange::LowPoly]);
}
#[test]
fn a_cage_file_counts_only_for_sets_that_bake_with_it() {
let mut session = baked_plane();
session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
execute(&mut session, "bake.run", &json!({})).unwrap();
let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect();
session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap();
assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session));
session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile;
assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session));
}
#[test]
fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() {
let mut session = baked_plane();
let task = session.bake_task(0).unwrap();
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
let streamed_once = AtomicBool::new(false);
let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap();
session.apply_streamed_bake(0, output).unwrap();
assert!(streamed_once.load(Ordering::Relaxed));
assert_eq!(changes(&session), [BakeChange::MapSettings]);
}
/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly
fn two_parts(lift: f32) -> String {
let mut obj = String::new();
for left in [0.0, 2.0] {
let right = left + 1.0;
obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n");
}
obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n";
obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n";
obj
}
#[test]
fn a_reopened_project_keeps_every_sets_maps_up_to_date() {
let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap();
session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap();
session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap();
for texture_set in &mut session.doc.project.texture_sets {
texture_set.bake.cage.kind = CageType::CustomFile;
}
execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap();
let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::<Vec<_>>();
assert_eq!(session.set_count(), 2);
assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded");
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(records(&reopened), records(&session), "the records are saved as they were");
for texture_set in 0..reopened.set_count() {
assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set));
}
assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake");
}
+3
View File
@@ -2,8 +2,11 @@
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
mod add_mask_items;
mod auto_rebake;
mod bake;
mod bake_checks;
mod bake_log;
mod bake_out_of_date;
mod bake_resolution;
mod bake_settings;
mod bake_tiles;
@@ -368,6 +368,31 @@ fn an_explicit_mesh_map_replacement_breaks_the_import_link_even_when_pixels_matc
assert!(ambient_occlusion(&session) == imported, "replacing a map explicitly takes ownership even when the pixels were equal");
}
#[test]
fn a_file_import_replaces_bake_provenance_and_clear_detaches_the_link() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Ball_position.png");
write_png(&file, 4, RED);
let mut session = ball();
execute(&mut session, "bake.run", &json!({"ts": 0, "resolution": 32, "maps": ["position"], "dilation": 0})).unwrap();
execute(&mut session, "bake.settings", &json!({"ts": 0, "positionMode": "boundingBox"})).unwrap();
assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "the previous bake is stale");
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
write_png(&file, 8, [0, 0, 255, 255]);
let imported = session.baked(0).unwrap().maps[&BakedMap::Position].clone();
execute(&mut session, "resource.update", &Value::Null).unwrap();
assert_ne!(*imported, *session.baked(0).unwrap().maps[&BakedMap::Position], "the replacement follows its file");
assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "the imported map has no bake provenance");
execute(&mut session, "textureSet.meshMap.clear", &json!({"ts": 0, "map": "position"})).unwrap();
assert!(session.doc.project.resource_sources["Ball_position.png"].mesh_map.is_none(), "clearing releases the file link");
write_png(&file, 16, RED);
execute(&mut session, "resource.update", &Value::Null).unwrap();
assert!(!session.baked(0).unwrap().maps.contains_key(&BakedMap::Position), "updating the old source leaves the slot empty");
}
#[test]
fn removing_unused_resources_keeps_the_file_that_feeds_an_imported_mesh_map() {
let dir = tempfile::tempdir().unwrap();
+143
View File
@@ -0,0 +1,143 @@
//! Auto-rebake: a texture set's auto-rebake map is baked again in the background once what it is baked from has stopped changing
use texturecraft_engine::core::{BakeSource, BakedMap};
use crate::{BakeJob, TextureCraftApp, bake_report, state};
/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts
const SETTLE_SECONDS: f64 = 0.5;
/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it
pub type Due = (usize, BakedMap, BakeSource, Option<u64>);
/// What the app has seen of the out-of-date auto-rebake maps
#[derive(Default)]
pub struct AutoRebake {
/// The project these records are of: another project starts with none
project: u64,
/// The due maps and the frame time they were first seen as they are
pending: Option<(Vec<Due>, f64)>,
/// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes
tried: Vec<Due>,
}
/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed
pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) {
if app.auto_rebake.project != app.session.project_id {
app.auto_rebake = AutoRebake { project: app.session.project_id, ..AutoRebake::default() };
}
if app.ui.mode != state::Mode::Baking {
app.auto_rebake.pending = None;
return;
}
let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None));
let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke)));
let due: Vec<Due> = stale.chain(painted).collect();
if let Some(job) = &app.bake {
// Newest wins: a rebake whose map changed again while it ran starts over with the new settings
if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) {
app.cancel_bake();
}
return;
}
app.auto_rebake.tried.retain(|tried| due.contains(tried));
let waiting: Vec<Due> = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect();
if waiting.is_empty() {
app.auto_rebake.pending = None;
return;
}
let now = app.last_time;
ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS));
// A held press (a slider dragged and paused) is still editing: the wait starts once it is let go
if pointer_held(ctx, app.docks.floating_windows()) {
app.auto_rebake.pending = Some((waiting, now));
return;
}
match &app.auto_rebake.pending {
Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {}
Some((seen, _)) if *seen == waiting => return,
_ => {
app.auto_rebake.pending = Some((waiting, now));
return;
}
}
app.auto_rebake.pending = None;
if let Some(rebake) = waiting.first().copied() {
app.auto_rebake.tried.push(rebake);
start(app, rebake);
}
}
/// Whether a mouse button is down in the main window or in one of the floating panels' own `windows`
fn pointer_held(ctx: &egui::Context, windows: &[egui::ViewportId]) -> bool {
ctx.input(|input| input.pointer.any_down()) || windows.iter().any(|window| ctx.input_for(*window, |input| input.pointer.any_down()))
}
/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake
fn start(app: &mut TextureCraftApp, rebake: Due) {
let (set, map, ..) = rebake;
// Restore the previous view before the rebake takes it over
app.live_preview.release(&mut app.session);
crate::id_color_pick::IdColorPick::end(app);
// The progress footer names the maps this rebake makes, not every checked map of the set
let maps = app.session.auto_rebake_maps(set, map);
app.session.bake_preview_begin(vec![(set, maps.clone())]);
app.session.begin_map_bake_log(&[set], &maps);
app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) };
app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) });
}
#[cfg(test)]
mod tests {
use super::*;
/// Whether a press is held, seen from the main window after a button went down in a floating panel's window (`window_listed`)
fn held_after_a_press_in_a_floating_window(window_listed: bool) -> bool {
use std::{cell::RefCell, rc::Rc};
let window = egui::ViewportId::from_hash_of("floating panel");
let context = egui::Context::default();
context.set_embed_viewports(false);
// Runs the window's pass inside its parent's, as eframe does
let arriving = Rc::new(RefCell::new(Vec::new()));
let queued = Rc::clone(&arriving);
egui::Context::set_immediate_viewport_renderer(move |context, viewport| {
let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() };
input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() });
let mut output = context.run_ui(input, viewport.viewport_ui_cb);
output.textures_delta.clear();
});
let at = egui::pos2(20.0, 20.0);
let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
*arriving.borrow_mut() = vec![egui::Event::PointerMoved(at), press];
let windows: &[egui::ViewportId] = if window_listed { &[window] } else { &[] };
let mut held = false;
// The first pass hands the press to the window after the hold was read; the second reads it
for _ in 0..2 {
let mut output = context.run_ui(egui::RawInput::default(), |ui| {
held = pointer_held(ui.ctx(), windows);
ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |_, _| {});
});
output.textures_delta.clear();
}
held
}
#[test]
fn a_press_held_in_a_floating_panels_window_counts_as_held() {
assert!(held_after_a_press_in_a_floating_window(true), "the slider dragged in a floating panel is still editing");
assert!(!held_after_a_press_in_a_floating_window(false), "the main window's own pointer is up");
}
}
+2
View File
@@ -11,4 +11,6 @@ pub struct BakeJob {
pub mesh_id: u64,
/// The one map to bake (a row's quick bake) instead of the checked ones
pub only: Option<BakedMap>,
/// An auto-rebake: the set, the one map it bakes and what that map was baked from when it started; `None` bakes every checked map
pub rebake: Option<crate::auto_rebake::Due>,
}
+121 -27
View File
@@ -1,15 +1,16 @@
use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2};
use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2};
use egui_phosphor::regular as icon;
use serde_json::json;
use serde_json::{Value, json};
use texturecraft_engine::ViewMode;
use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap};
use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap};
use super::glyph_look::GlyphLook;
use super::row_click::RowClick;
use super::set_picker::SetPicker;
use super::set_picker_purpose::SetPickerPurpose;
use crate::TextureCraftApp;
use crate::docking::Panel;
use crate::i18n::{baked_map_label, tr, trf};
use crate::i18n::{bake_change_reason, baked_map_label, tr, trf};
use crate::property_sheet::{CHECK_SIZE, paint_check};
use crate::theme::{Tokens, semibold};
@@ -34,8 +35,13 @@ const ROW_INSET: f32 = 6.0;
/// Side of a row's map thumbnail, and the air on its sides
const THUMBNAIL_SIZE: f32 = 22.0;
const THUMBNAIL_AIR: f32 = 9.0;
/// Side of a row's icon buttons and of the list menu button
/// Side of the header icon slots and of the list menu button
const ROW_BUTTON_SIZE: f32 = 20.0;
/// Side of a row's hover icons, and the air right of each: four icons stay right of the row's middle in the Bakers column, so a click there selects the row
const ROW_ICON_SIZE: f32 = 18.0;
const ROW_ICON_GAP: f32 = 1.0;
/// Radius of the out-of-date clock on a thumbnail's corner
const CLOCK_BADGE_RADIUS: f32 = 6.0;
/// Size of a row's glyphs
const ROW_GLYPH_SIZE: f32 = 14.0;
/// Size of the map names
@@ -46,8 +52,10 @@ const ROW_RADIUS: u8 = 4;
const HOVER_FACE_OPACITY: f32 = 0.5;
/// Air above and below the hairline under Check All
const RULE_AIR: f32 = 4.0;
/// Size of a row icon's tooltip title and reasons
const TOOLTIP_TEXT_SIZE: f32 = 12.0;
/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects)
/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects, a hover icon toggles Auto-rebake)
pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) {
let several_sets = app.session.doc.project.texture_sets.len() > 1;
ui.add_space(HEADER_AIR);
@@ -85,10 +93,21 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
let drag_from_id = ui.scope_id().with("check_drag_from");
let mut check_drag: Option<bool> = ui.data(|data| data.get_temp(check_drag_id));
let drag_from: Option<Pos2> = ui.data(|data| data.get_temp(drag_from_id));
let texture_set = app.session.ts();
let out_of_date = app.session.out_of_date_maps(texture_set);
for map in BakedMap::ALL {
if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner {
app.ui.selected_baked_map = Some(map);
app.ui.dock.focus(Panel::MeshMapSettings);
let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice);
match ui.push_id(map, |ui| row(app, ui, (map, changes), settings, map == selected, &mut check_drag, drag_from)).inner {
Some(RowClick::Row) => {
app.ui.selected_baked_map = Some(map);
app.ui.dock.focus(Panel::MeshMapSettings);
}
Some(RowClick::AutoRebake) => {
let selection = if auto_rebake_map(app, texture_set) == Some(map) { Value::Null } else { json!(map.id()) };
app.run("bake.autoRebake", json!({ "ts": texture_set, "map": selection }));
}
None => {}
}
}
@@ -99,7 +118,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
if let (Some(value), true) = (check_drag, is_held) {
data.insert_temp(check_drag_id, value);
// A pointer back from outside the window starts a new line, so rows it never crossed stay as they were
// Break the drag line when the pointer leaves the window
if let Some(pointer) = pointer {
data.insert_temp(drag_from_id, pointer);
} else {
@@ -239,21 +258,21 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w
}
}
/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked
/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock naming its `changes` (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check
fn row(
app: &mut TextureCraftApp,
ui: &mut Ui,
map: BakedMap,
(map, changes): (BakedMap, &[BakeChange]),
settings: &mut BakeSettings,
is_selected: bool,
check_drag: &mut Option<bool>,
drag_from: Option<Pos2>,
) -> bool {
) -> Option<RowClick> {
let several_sets = app.session.doc.project.texture_sets.len() > 1;
let tokens = Tokens::get(ui.ctx());
let name = tr(baked_map_label(map));
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click());
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name));
response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_selected, name));
let hovered = ui.rect_contains_pointer(rect);
if is_selected {
@@ -262,7 +281,7 @@ fn row(
ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover.gamma_multiply(HOVER_FACE_OPACITY));
}
// Added after the row's own response, so the check and icons take the clicks over it
// Register the checkbox after the row so it gets first chance at clicks
let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE));
let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake"));
checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name));
@@ -272,35 +291,46 @@ fn row(
} else if checkbox.clicked() && check_drag.is_none() {
settings.maps.set_enabled(map, !settings.maps.is_enabled(map));
}
paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered());
paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered());
crate::property_sheet::paint_keyboard_focus(ui, &checkbox, &tokens);
let texture = app.bake_map_thumbnails.texture(ui.ctx(), &app.session, app.session.ts(), map);
let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
thumbnail(ui, thumbnail_rect, texture.as_ref());
let mut icons_left = rect.right();
let texture_set = app.session.ts();
if !changes.is_empty() {
out_of_date_mark(ui, thumbnail_rect, name, changes);
}
let focus_in_row = || {
ui.memory(|memory| memory.focused())
.and_then(|id| ui.ctx().read_response(id))
.is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center()))
};
if is_selected || hovered || focus_in_row() {
let mut next_icon = || {
let slot =
Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE));
icons_left = slot.left() - ROW_INSET / 2.0;
slot
};
if several_sets {
let is_active = is_selected || hovered || focus_in_row();
let is_auto_rebake = auto_rebake_map(app, texture_set) == Some(map);
// Reserve Auto-rebake's slot before placing the hover-only icons
let mut icons_left = rect.right();
let mut next_icon = || icon_slot(&mut icons_left, rect.center().y);
let sync_slot = several_sets.then(&mut next_icon);
let toggle = next_icon();
let mut toggled = false;
if is_active {
if let Some(slot) = sync_slot {
let shares = settings.sync.shares(BakeSyncGroup::Map(map));
let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain };
let glyph = if shares { icon::LINK } else { icon::LINK_BREAK };
let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look);
let sync = glyph_button(ui, slot, glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look);
if sync.clicked() {
SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map)));
}
}
toggled = auto_rebake_toggle(ui, toggle, name, is_auto_rebake).clicked();
let baking = app.bake_progress().is_some();
let bolt = next_icon();
let bolt_label = trf("Bake {map} Only", &[("map", &name)]);
@@ -308,12 +338,17 @@ fn row(
let active = app.session.ts();
app.start_bake_of(vec![active], Some(map));
}
let shown = app.session.view == ViewMode::MeshMap(map);
let look = if shown { GlyphLook::Pressed } else { GlyphLook::Plain };
if glyph_button(ui, next_icon(), icon::EYE, &trf("Show {map} in the Viewport", &[("map", &name)]), look).clicked() {
let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) };
app.run("viewport.view", json!({ "mode": mode }));
}
} else if is_auto_rebake {
toggled = auto_rebake_toggle(ui, toggle, name, true).clicked();
} else {
icons_left = rect.right();
}
let name_left = thumbnail_rect.right() + THUMBNAIL_AIR;
@@ -356,7 +391,35 @@ fn row(
response.request_focus();
}
response.clicked()
if toggled {
Some(RowClick::AutoRebake)
} else if response.clicked() {
Some(RowClick::Row)
} else {
None
}
}
/// The map texture set `texture_set` rebakes on its own, if any
fn auto_rebake_map(app: &TextureCraftApp, texture_set: usize) -> Option<BakedMap> {
app.session.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake)
}
/// The Auto-rebake toggle in `rect`: bright while on or pointed at, dim while off
fn auto_rebake_toggle(ui: &mut Ui, rect: Rect, name: &str, is_on: bool) -> egui::Response {
let tokens = Tokens::get(ui.ctx());
let response = ui.interact(rect, ui.scope_id().with("auto_rebake"), Sense::click());
let title = tr("Auto-rebake");
let label = trf("Auto-rebake {map}", &[("map", &name)]);
response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_on, &label));
let is_pointed = response.hovered() || response.has_focus();
let color = if is_on || is_pointed { tokens.text_strong } else { tokens.text_dim };
ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::ARROWS_CLOCKWISE, FontId::proportional(ROW_GLYPH_SIZE), color);
crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens);
response.on_hover_ui(|ui| {
ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text));
})
}
/// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from`
@@ -420,8 +483,10 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response {
let icon = ui.painter().layout_no_wrap(glyph.to_owned(), FontId::proportional(ROW_GLYPH_SIZE), tokens.text);
let words = ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), tokens.text);
let width = 2.0 * HEADER_BUTTON_PADDING + icon.size().x + HEADER_GLYPH_GAP + words.size().x;
let (rect, response) = ui.allocate_exact_size(vec2(width, HEADER_BUTTON_HEIGHT), Sense::click());
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text));
let fill = if response.hovered() { tokens.row_hover } else { tokens.button };
ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), fill, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside);
let x = rect.left() + HEADER_BUTTON_PADDING;
@@ -430,3 +495,32 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response {
crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens);
response
}
/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail, or its node's description, tells what changed
fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) {
let tokens = Tokens::get(ui.ctx());
let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover());
let title = tr("Out of date");
let label = trf("Out of date: {map}", &[("map", &name)]);
response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label));
let reasons: Vec<&str> = changes.iter().map(|change| tr(bake_change_reason(*change))).collect();
ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reasons.join(" ")));
let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5;
ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel);
ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning);
response.on_hover_ui(|ui| {
ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text));
for reason in reasons {
ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim));
}
});
}
/// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it
fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect {
let slot = Rect::from_center_size(pos2(*icons_left - ROW_ICON_SIZE / 2.0 - ROW_ICON_GAP, center_y), vec2(ROW_ICON_SIZE, ROW_ICON_SIZE));
*icons_left = slot.left();
slot
}
+6 -4
View File
@@ -23,6 +23,7 @@ mod map_settings;
mod map_thumbnails;
mod mesh_map_bakers;
pub use map_thumbnails::MapThumbnails;
mod row_click;
mod set_picker;
mod set_picker_purpose;
mod set_picker_row;
@@ -230,15 +231,16 @@ fn edit_settings(
let mut settings = before.clone();
let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner;
if settings == before && reset.is_none() {
return false;
}
// One drag is one undo step: a press's later changes continue its first one
let Some(merge) = crate::widgets::press_edit(ui, ui.make_persistent_id((scroll_id, "press")), settings != before || reset.is_some()) else { return false };
let mut patch = settings_patch(&before, &settings);
if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) {
fields.extend(reset);
}
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch }));
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch, "merge": merge }));
true
}
@@ -0,0 +1,5 @@
/// What a click on a Mesh Map Bakers row hit
pub(super) enum RowClick {
Row,
AutoRebake,
}
+10 -6
View File
@@ -10,16 +10,19 @@ pub struct BakeReport {
pub map_count: usize,
/// Number of texture sets whose bake failed
pub failed_set_count: usize,
/// A rebake the app started by itself (Auto-rebake): only a failure makes a toast
pub auto_rebake: bool,
}
impl BakeReport {
pub fn started(now: f64) -> Self {
BakeReport { started_at_seconds: now, ..Default::default() }
pub fn started(now_seconds: f64) -> Self {
BakeReport { started_at_seconds: now_seconds, ..Default::default() }
}
/// The toast text, the Log line and whether the toast is an error (some set failed)
pub fn summary(&self, now: f64) -> (String, String, bool) {
let time = duration_text((now - self.started_at_seconds).max(0.0));
pub fn summary(&self, now_seconds: f64) -> (String, String, bool) {
let time = duration_text((now_seconds - self.started_at_seconds).max(0.0));
let line = if self.failed_set_count == 0 {
format!("Bake finished: {} maps in {time}", self.map_count)
} else {
@@ -35,6 +38,7 @@ impl BakeReport {
tr("Failures are listed in the Log.")
)
};
(text, line, self.failed_set_count > 0)
}
}
@@ -57,7 +61,7 @@ mod tests {
#[test]
fn success_names_maps_and_time() {
let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0 };
let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0, auto_rebake: false };
let (text, line, failed) = report.summary(22.34);
@@ -68,7 +72,7 @@ mod tests {
#[test]
fn failures_are_counted_and_point_to_the_log() {
let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2 };
let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2, auto_rebake: false };
let (text, _, failed) = report.summary(125.0);
+378
View File
@@ -0,0 +1,378 @@
//! The Baking Log panel: the latest bake under three tabs, read from the session's bake record
use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2};
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeLogMatching, BakeMapState};
use texturecraft_engine::core::BakedMap;
use crate::TextureCraftApp;
use crate::docking::Panel;
use crate::i18n::{baked_map_label, tr, trf};
use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box};
use crate::theme::{Tokens, semibold};
mod baking_log_tab;
mod high_poly_list;
mod matching_list;
pub use baking_log_tab::BakingLogTab;
/// Height of the tab strip, as the Properties section tabs
const STRIP_HEIGHT: f32 = 30.0;
/// How far the first tab reaches left of the rows' side padding, as the Properties section tabs
const FIRST_TAB_OUTDENT: f32 = 4.0;
/// Height of one row of a list
const ROW_HEIGHT: f32 = 24.0;
/// Air above the first row
const LIST_TOP: f32 = 4.0;
/// How far a hovered row's fill stays inside the panel's sides
const HOVER_INSET: f32 = 3.0;
/// From the panel's left edge to a row's glyph centre, and to its name
const GLYPH_CENTER: f32 = SIDE_PADDING_POINTS + 6.0;
const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0;
/// Size of a row's glyph and of its name
const GLYPH_SIZE: f32 = 13.0;
const NAME_SIZE: f32 = 12.0;
/// Size of the open-settings arrow at an issue row's right end, and of the square it answers clicks in
const OPEN_ICON_SIZE: f32 = 14.0;
const OPEN_BUTTON_SIZE: f32 = 20.0;
/// Height of the issues filter toggle, and its width without a count
const FILTER_HEIGHT: f32 = 22.0;
const FILTER_BUTTON_WIDTH: f32 = 30.0;
/// How far the issues filter sits below the strip's centre, and how far it reaches past the side padding
const FILTER_DROP: f32 = 1.0;
const FILTER_OUTDENT: f32 = 4.0;
/// Corner rounding of the issues filter's pressed and hovered fill
const FILTER_ROUNDING: f32 = 5.0;
/// From the issues filter's left edge to its glyph's centre and to its count, and the glyph's size
const FILTER_GLYPH_CENTER: f32 = 15.0;
const FILTER_COUNT_LEFT: f32 = 26.0;
const FILTER_GLYPH_SIZE: f32 = 14.0;
/// Air between the issue count and the toggle's right end
const FILTER_COUNT_GAP: f32 = 4.0;
/// Height of the two lines the issues filter leaves when nothing is wrong, to centre them
const EMPTY_TEXT_HEIGHT: f32 = 40.0;
pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover());
ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome);
// The tabs keep clear of the issues filter at its widest, so picking a tab never moves the edge they scroll under
let filter_room = BakingLogTab::ALL.into_iter().map(|tab| filter_width(ui, issue_count(&app.session.bake_log, tab))).fold(0.0, f32::max);
let tabs_right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT - filter_room - TAB_GAP;
if let Some(tab) = tabs(ui, strip.with_max_x(tabs_right.max(strip.left())), app.ui.baking_log_tab, &app.session.bake_log) {
app.ui.baking_log_tab = tab;
}
let tab = app.ui.baking_log_tab;
let issue_count = issue_count(&app.session.bake_log, tab);
if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) {
app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only;
}
let issues_only = app.ui.baking_log_issues_only;
let log = &app.session.bake_log;
let baked = !log.maps.is_empty();
if tab == BakingLogTab::MatchingByName && baked && log.matching.is_none() {
matching_not_enabled(ui);
return;
}
if issues_only && issue_count == 0 {
no_issues(ui, tab);
return;
}
let opened = egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
// Rows sit edge to edge at ROW_HEIGHT, as the matching list's rules need
ui.spacing_mut().item_spacing.y = 0.0;
ui.add_space(LIST_TOP);
match tab {
BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only),
BakingLogTab::HighPolyParameters => {
high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only);
None
}
BakingLogTab::MatchingByName => {
if let Some(matching) = &app.session.bake_log.matching {
matching_list::matching_list(ui, matching, issues_only);
}
None
}
}
})
.inner;
if let Some((texture_set, map)) = opened {
open_map_settings(app, texture_set, map);
}
}
/// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does
fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) {
// A guard against a row naming a set the session no longer has
if texture_set >= app.session.set_count() {
return;
}
if texture_set != app.session.ts() {
app.run("textureSet.select", json!({ "ts": texture_set }));
}
app.ui.selected_baked_map = Some(map);
app.ui.dock.focus(Panel::MeshMapSettings);
}
/// How many rows of `tab` have an issue, for the issues filter's count
fn issue_count(log: &BakeLog, tab: BakingLogTab) -> usize {
match tab {
BakingLogTab::BakingProcess => log.maps.iter().filter(|row| row.state.is_issue()).count(),
BakingLogTab::HighPolyParameters => log.highs.iter().filter(|row| row.state.is_issue()).count(),
BakingLogTab::MatchingByName => log.matching.as_ref().map_or(0, BakeLogMatching::issue_count),
}
}
/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; they scroll sideways when wider than it
fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option<BakingLogTab> {
let tokens = Tokens::get(ui.ctx());
let names = BakingLogTab::ALL.map(|tab| tr(tab.name()));
let widths = names.map(|name| ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING);
let first_left = SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT;
let content_width = first_left + widths.iter().sum::<f32>() + TAB_GAP * (widths.len() - 1) as f32;
let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip).id_salt("baking_log_tabs"));
egui::ScrollArea::horizontal()
.id_salt("baking_log_tabs")
.auto_shrink([false, false])
.show(&mut strip_ui, |ui| {
let (content, _) = ui.allocate_exact_size(vec2(content_width, strip.height()), Sense::hover());
let mut picked = None;
let mut left = content.left() + first_left;
for ((tab, name), width) in BakingLogTab::ALL.into_iter().zip(names).zip(widths) {
if tab_button(ui, content, left, width, (tab, name), tab == shown, log) {
picked = Some(tab);
}
left += width + TAB_GAP;
}
picked
})
.inner
}
/// One tab `width` wide from `left` on the `strip`, scrolled into view when the focus reaches it; dots for its icon while its work runs
fn tab_button(ui: &mut Ui, strip: Rect, left: f32, width: f32, (tab, name): (BakingLogTab, &str), on: bool, log: &BakeLog) -> bool {
let tokens = Tokens::get(ui.ctx());
let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom()));
let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click());
response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name));
if response.gained_focus() {
response.scroll_to_me(None);
}
let painter = ui.painter();
if on {
shown_tab_box(painter, &tokens, rect);
}
let color = if on || response.hovered() { tokens.text } else { tokens.text_dim };
let in_progress = match tab {
BakingLogTab::BakingProcess => log.is_running(),
BakingLogTab::HighPolyParameters => log.is_loading_high_polys(),
BakingLogTab::MatchingByName => false,
};
let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) };
let center_y = strip.center().y + TAB_TOP / 2.0;
painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color);
let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) };
painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color);
if response.has_focus() {
crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong);
}
response.clicked()
}
/// The issues filter's width when it counts `issue_count` rows
fn filter_width(ui: &Ui, issue_count: usize) -> f32 {
let count_width = if issue_count == 0 {
0.0
} else {
let tokens = Tokens::get(ui.ctx());
ui.painter().layout_no_wrap(issue_count.to_string(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP
};
FILTER_BUTTON_WIDTH + count_width
}
/// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are
fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool {
let tokens = Tokens::get(ui.ctx());
let count = (issue_count > 0).then(|| issue_count.to_string());
let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT;
let center_y = strip.center().y + FILTER_DROP;
let rect = Rect::from_min_max(pos2(right - filter_width(ui, issue_count), center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0));
let name = match &count {
Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]),
None => tr("Show only rows with an issue").to_owned(),
};
let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click());
response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name));
let painter = ui.painter();
if on {
painter.rect(rect, FILTER_ROUNDING, tokens.tool_active, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside);
} else if response.hovered() {
painter.rect_filled(rect, FILTER_ROUNDING, tokens.row_hover);
}
let glyph_color = if count.is_some() { tokens.warning } else { tokens.text_dim };
painter.text(pos2(rect.left() + FILTER_GLYPH_CENTER, center_y), Align2::CENTER_CENTER, ic::WARNING, FontId::proportional(FILTER_GLYPH_SIZE), glyph_color);
if let Some(count) = count {
painter.text(pos2(rect.left() + FILTER_COUNT_LEFT, center_y), Align2::LEFT_CENTER, count, semibold(NAME_SIZE), tokens.text);
}
if response.has_focus() {
crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong);
}
response.on_hover_text(tr("Show only rows with an issue")).clicked()
}
/// What the issues filter leaves when `tab` has no issue: one line for that tab, and how to see every row
fn no_issues(ui: &mut Ui, tab: BakingLogTab) {
let tokens = Tokens::get(ui.ctx());
let message = match tab {
BakingLogTab::BakingProcess => tr("Every map so far baked without a problem."),
BakingLogTab::HighPolyParameters => tr("Every high poly file so far loaded."),
BakingLogTab::MatchingByName => tr("Every part so far has its partner."),
};
let area = ui.available_rect_before_wrap();
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center)));
child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0);
child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text));
child.label(egui::RichText::new(tr("Turn off the issues filter to see every row.")).size(NAME_SIZE).color(tokens.text_dim));
ui.allocate_rect(area, Sense::hover());
}
/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting and its value in SemiBold
fn matching_not_enabled(ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let mut text = egui::text::LayoutJob::default();
let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() };
// One sentence to translate, its setting and value kept apart to set them in SemiBold
let sentence = tr("Set {setting} to {value} to pair parts by name.");
let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence));
let (between, after) = rest.split_once("{value}").unwrap_or((rest, ""));
text.append(before, 0.0, format(FontId::proportional(NAME_SIZE)));
text.append(tr("Match"), 0.0, format(semibold(NAME_SIZE)));
text.append(between, 0.0, format(FontId::proportional(NAME_SIZE)));
text.append(tr("By Mesh Name"), 0.0, format(semibold(NAME_SIZE)));
text.append(after, 0.0, format(FontId::proportional(NAME_SIZE)));
let area = ui.available_rect_before_wrap();
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center)));
child.add_space((area.height() - EMPTY_TEXT_HEIGHT / 2.0).max(0.0) / 2.0);
child.label(text);
ui.allocate_rect(area, Sense::hover());
}
/// One row per texture set and map (with an issue, if `issues_only`) in bake order, following the map being baked; returns the map to open
fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option<(usize, BakedMap)> {
let followed = maps.iter().position(|row| row.state == BakeMapState::Baking);
let follow_id = Id::unique("baking_log_followed_map");
let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::<Option<usize>>(follow_id)) != Some(followed);
ui.data_mut(|data| data.insert_temp(follow_id, followed));
let mut opened = None;
for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) {
let (rect, open_clicked) = map_row(ui, row);
// Bring the next map into view too, so the list shows what comes after the map being baked
if newly_followed && followed == Some(index) {
ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None);
}
if open_clicked {
opened = Some((row.texture_set, row.map));
}
}
opened
}
/// A map's row: glyph, then "<texture set> <map>"; a map not baked tells why on hover and has an arrow to its settings; returns the row and whether the arrow was clicked
fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) {
let tokens = Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover());
let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map)));
let (glyph, glyph_color, state) = match &row.state {
BakeMapState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")),
BakeMapState::Baking => (ic::DOTS_THREE, tokens.accent, tr("Baking")),
BakeMapState::Baked => (ic::CHECK, tokens.text, tr("Baked")),
BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")),
BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")),
};
let reason = match &row.state {
BakeMapState::Failed(reason) => Some(reason.as_str()),
BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")),
_ => None,
};
response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}")));
describe(ui, &response, reason);
let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name));
let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered());
let painter = ui.painter();
if row_hovered {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover);
}
let center_y = rect.center().y;
painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color);
let (font, color) = match row.state {
BakeMapState::Baking => (semibold(NAME_SIZE), tokens.text),
BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim),
_ => (FontId::proportional(NAME_SIZE), tokens.text),
};
painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, &name, font, color);
if let Some(open) = &open
&& (row_hovered || open.has_focus())
{
let color = if open.hovered() || open.has_focus() { tokens.text } else { tokens.text_dim };
painter.text(open.rect.center(), Align2::CENTER_CENTER, ic::ARROW_SQUARE_OUT, FontId::proportional(OPEN_ICON_SIZE), color);
if open.has_focus() {
crate::property_sheet::paint_focus_outline(painter, open.rect, tokens.text_strong);
}
}
if let Some(reason) = reason {
response.on_hover_ui(|ui| {
ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text));
ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim));
});
}
let open_clicked = open.is_some_and(|open| open.clicked());
(rect, open_clicked)
}
/// Give a row's node the `reason` its tooltip shows, so a screen reader reads it without hovering
pub(super) fn describe(ui: &Ui, response: &egui::Response, reason: Option<&str>) {
if let Some(reason) = reason {
ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reason));
}
}
/// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus
fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response {
let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y);
let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE));
let label = trf("Open the {name} settings", &[("name", &name)]);
let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", set_map)), Sense::click());
response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label));
response.on_hover_text(label)
}
@@ -0,0 +1,36 @@
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::i18n::n_;
/// The Baking Log panel's tabs
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BakingLogTab {
/// Every map of the latest bake and how it went
#[default]
BakingProcess,
/// The high poly files each texture set bakes from
HighPolyParameters,
/// Which low poly part bakes from which high poly part
MatchingByName,
}
impl BakingLogTab {
pub const ALL: [BakingLogTab; 3] = [BakingLogTab::BakingProcess, BakingLogTab::HighPolyParameters, BakingLogTab::MatchingByName];
pub fn name(self) -> &'static str {
match self {
BakingLogTab::BakingProcess => n_("Baking Process"),
BakingLogTab::HighPolyParameters => n_("High Poly Parameters"),
BakingLogTab::MatchingByName => n_("Matching by Name"),
}
}
pub(crate) fn icon(self) -> &'static str {
match self {
BakingLogTab::BakingProcess => ic::LIST_CHECKS,
BakingLogTab::HighPolyParameters => ic::CUBE,
BakingLogTab::MatchingByName => ic::ARROWS_LEFT_RIGHT,
}
}
}
@@ -0,0 +1,108 @@
//! The Baking Log's High Poly Parameters tab: each texture set of the latest bake and the high poly files it loads
use egui::{Align2, CornerRadius, FontId, Id, Role, Sense, Ui, WidgetInfo, pos2, vec2};
use egui_phosphor::regular as ic;
use texturecraft_engine::bake::{BakeHighState, BakeLogHigh};
use super::{GLYPH_CENTER, GLYPH_SIZE, HOVER_INSET, NAME_LEFT, NAME_SIZE, ROW_HEIGHT};
use crate::i18n::{tr, trf};
use crate::theme::{Tokens, semibold};
/// How far a file's row sits right of its texture set's row
const FILE_INDENT: f32 = 22.0;
/// A row per texture set that loads high polys, folding open onto a row per file (with an issue, if `issues_only`)
pub(super) fn high_poly_list(ui: &mut Ui, highs: &[BakeLogHigh], issues_only: bool) {
let mut start = 0;
while start < highs.len() {
let set = highs[start].texture_set;
let end = highs[start..].iter().position(|row| row.texture_set != set).map_or(highs.len(), |length| start + length);
let files: Vec<&BakeLogHigh> = highs[start..end].iter().filter(|row| !issues_only || row.state.is_issue()).collect();
start = end;
if files.is_empty() {
continue;
}
if set_row(ui, set, &files[0].set_name) {
for row in files {
file_row(ui, row);
}
}
}
}
/// A texture set's row: a caret and its name in SemiBold, named for what it holds; a click folds it. Returns whether it is open
fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool {
let tokens = Tokens::get(ui.ctx());
let id = Id::unique(("baking_log_high_poly_set", set));
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover());
let response = ui.interact(rect, id, Sense::click());
response.widget_info(|| WidgetInfo::labeled(Role::Button, true, trf("{set}, High poly files", &[("set", &name)])));
let mut open = ui.data(|data| data.get_temp::<bool>(id)).unwrap_or(true);
if response.clicked() {
open = !open;
ui.data_mut(|data| data.insert_temp(id, open));
}
ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open));
let painter = ui.painter();
if response.hovered() {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover);
}
let center_y = rect.center().y;
let caret = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT };
painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, caret, FontId::proportional(GLYPH_SIZE), tokens.text_dim);
painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, semibold(NAME_SIZE), tokens.text);
if response.has_focus() {
crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong);
}
open
}
/// A high poly file's row under its texture set: glyph and file name; a file not loaded tells why on hover
fn file_row(ui: &mut Ui, row: &BakeLogHigh) {
let tokens = Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover());
let (glyph, glyph_color, state) = match &row.state {
BakeHighState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")),
BakeHighState::Loading => (ic::DOTS_THREE, tokens.accent, tr("Loading")),
BakeHighState::Loaded => (ic::CHECK, tokens.text, tr("Loaded")),
BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")),
BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")),
};
let reason = match &row.state {
BakeHighState::Failed(reason) => Some(reason.as_str()),
BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")),
_ => None,
};
response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file)));
super::describe(ui, &response, reason);
let painter = ui.painter();
if response.hovered() {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover);
}
let center_y = rect.center().y;
painter.text(pos2(rect.left() + GLYPH_CENTER + FILE_INDENT, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color);
let (font, color) = match row.state {
BakeHighState::Loading => (semibold(NAME_SIZE), tokens.text),
BakeHighState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim),
_ => (FontId::proportional(NAME_SIZE), tokens.text),
};
painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color);
if let Some(reason) = reason {
response.on_hover_ui(|ui| {
ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text));
ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim));
});
}
}
@@ -0,0 +1,138 @@
//! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part
use egui::{Align2, Color32, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2};
use egui_phosphor::regular as ic;
use texturecraft_engine::bake::{BakeLogMatching, NamePair};
use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT};
use crate::i18n::{tr, trf};
use crate::property_sheet::SIDE_PADDING_POINTS;
use crate::theme::{Tokens, semibold};
use crate::widgets::elided;
/// Size of the column captions
const CAPTION_SIZE: f32 = 11.0;
/// Air between the end of a low poly name and the high poly column
const COLUMN_GAP: f32 = 8.0;
/// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below
pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) {
let tokens = Tokens::get(ui.ctx());
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover());
let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)];
for (column, caption) in columns(rect).into_iter().zip(captions) {
column_text(ui, column, caption, CAPTION_SIZE, tokens.text_dim);
}
rule(ui, rect);
for pair in matching.pairs.iter().filter(|pair| !issues_only || pair.unpaired()) {
pair_row(ui, pair);
}
}
/// A column caption in capitals, with the set's `suffix` kept as typed
fn caption(template: &str, suffix: &str) -> String {
template.split("{suffix}").map(str::to_uppercase).collect::<Vec<_>>().join(suffix)
}
/// The low and high poly columns of `row`, each ending a gap short of the next column or the side padding
fn columns(row: Rect) -> [Rect; 2] {
let low = row.with_min_x(row.left() + SIDE_PADDING_POINTS).with_max_x(row.center().x - COLUMN_GAP);
let high = row.with_min_x(row.center().x).with_max_x(row.right() - SIDE_PADDING_POINTS);
[low, high]
}
/// Paint `text` in `color` at the left end of `column`, centred on its height and cut short to its width; whether it was cut
fn column_text(ui: &Ui, column: Rect, text: String, size: f32, color: Color32) -> bool {
let galley = elided(ui.painter(), text, size, color, column.width());
let cut_short = galley.elided;
ui.painter().galley(pos2(column.left(), column.center().y - galley.size().y / 2.0), galley, color);
cut_short
}
/// The hairline under `row`, inside the side padding
fn rule(ui: &Ui, row: Rect) {
let tokens = Tokens::get(ui.ctx());
let x = row.left() + SIDE_PADDING_POINTS..=row.right() - SIDE_PADDING_POINTS;
ui.painter().hline(x, row.bottom() - 0.5, Stroke::new(1.0, tokens.separator));
}
/// A pair's row: the low poly part, then the high poly part; a side with no partner is a warning glyph that tells why on hover
fn pair_row(ui: &mut Ui, pair: &NamePair) {
let tokens = Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover());
let no_match = tr("No match");
let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match));
let reason = match (&pair.low, &pair.high) {
(Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])),
(None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])),
_ => None,
};
response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name));
super::describe(ui, &response, reason.as_deref());
let painter = ui.painter();
if response.hovered() {
painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover);
}
let mut cut_short = false;
for (column, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) {
match part {
Some(part) => cut_short |= column_text(ui, column, part.clone(), NAME_SIZE, tokens.text),
None => {
painter.text(pos2(column.left(), column.center().y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning);
}
}
}
rule(ui, rect);
// A name cut short shows in full on hover; the row's label carries it in full already
if reason.is_some() || cut_short {
response.on_hover_ui(|ui| {
if cut_short {
ui.label(egui::RichText::new(&name).size(NAME_SIZE).color(tokens.text));
}
if let Some(reason) = reason {
ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text));
ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim));
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Names longer than their column, in a list as narrow as a small docked log
#[test]
fn long_names_stay_in_their_own_column() {
let long = |side: &str| format!("Left_shoulder_strap_buckle_with_its_rivets_and_stitching_{side}");
let matching = BakeLogMatching {
low_suffix: "_low".into(),
high_suffix: "_high".into(),
pairs: vec![NamePair { low: Some(long("low")), high: Some(long("high")) }],
};
let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 200.0));
let context = egui::Context::default();
let mut output = context.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| matching_list(ui, &matching, false));
output.textures_delta.clear();
let texts: Vec<Rect> = output
.shapes
.iter()
.filter_map(|clipped| match &clipped.shape {
egui::Shape::Text(text) => Some(text.visual_bounding_rect()),
_ => None,
})
.collect();
assert_eq!(texts.len(), 4, "two captions and two names");
for (index, text) in texts.iter().enumerate() {
assert!(screen.contains_rect(*text), "text {index} {text:?} stays inside the list");
for other in &texts[index + 1..] {
assert!(!text.intersects(*other), "text {index} {text:?} runs into {other:?}");
}
}
}
}
+29 -21
View File
@@ -308,7 +308,7 @@ impl Dock {
self.replaced_unreadable
}
/// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport
/// Texture sets over the bakers, the two settings tabs, the Baking Log under both, then the viewport
pub(crate) fn for_baking() -> Self {
let painting = default_workspace();
let mut hidden = painting.hidden().to_vec();
@@ -318,17 +318,18 @@ impl Dock {
}
}
let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log];
let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::BakingLog];
hidden.retain(|(panel, _)| !bake_panels.contains(panel));
let gutter_width = f32::from(crate::theme::GUTTER);
let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers]));
let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]);
let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column);
let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log]));
let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::BakingLog]));
let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH;
let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport]));
let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec());
Dock { workspace, raise: None, replaced_unreadable: false }
}
@@ -391,27 +392,34 @@ impl Dock {
}
}
/// What the dock area keeps between passes: the workspace it shows and the panels' specs.
/// What the dock area keeps between passes: the workspace it shows and the panels' specs
#[derive(Default)]
pub(crate) struct LiveDock {
shown: Option<Arc<Workspace>>,
specs: Tracked<DockSpecs>,
/// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window.
/// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window
continue_move: Option<(Panel, egui::Vec2)>,
/// The OS windows of the floating panels, as the last pass's dock drew them
floating_windows: Vec<ViewportId>,
}
impl LiveDock {
/// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`.
/// The OS windows the last pass's dock drew floating panels in
pub(crate) fn floating_windows(&self) -> &[ViewportId] {
&self.floating_windows
}
/// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`
pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) {
self.continue_move = Some((panel, grab));
}
/// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same,
/// so an idle pass keeps the workspace's revision and the dock reads no spec.
/// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, so an idle pass reads no spec
fn shown(&mut self, workspace: &Workspace) -> Arc<Workspace> {
if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) {
return Arc::clone(shown);
}
let shown = Arc::new(workspace.clone());
self.shown = Some(Arc::clone(&shown));
shown
@@ -470,7 +478,7 @@ pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> b
modal
}
/// Draw the dock (viewport and panels) into `ui`.
/// Draw the dock (viewport and panels) into `ui`
pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
// Rendering keeps disabled panels visible because it shares the painting dock
let dock_mode = if app.ui.mode == crate::state::Mode::Rendering { crate::state::Mode::Painting } else { app.ui.mode };
@@ -484,12 +492,13 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let context = ui.ctx().clone();
refresh_specs(app);
let shown = app.docks.shown(&app.ui.dock.workspace);
// The specs leave the app while its panels borrow it, and come back with their revision.
// Move the specs out so the dock can borrow the app to draw panels
let specs = std::mem::take(&mut app.docks.specs);
let hand_over = app.docks.continue_move.take();
let raise = app.ui.dock.raise.take();
// Panels arrange in a split tree around the viewport; floating title bars only move windows.
// Each closable tab has its close button, as each group header had one for its shown panel.
// Keep drag targets on the dock so a floating title bar only moves its window
let config = DockConfig::default().new_dock_zones(false).title_bar_docks(false).tab_close_buttons(true);
let (output, focused_windows) = {
let tokens = Tokens::get(&context);
@@ -504,7 +513,10 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let output = area.show(ui);
(output, panels.focused_windows)
};
app.docks.specs = specs;
app.docks.floating_windows.clear();
app.docks.floating_windows.extend(output.windows.iter().map(|(_, viewport)| *viewport));
// The popup needs the viewport the dock recorded this frame
crate::rail_popup::show(app, &context);
@@ -517,6 +529,7 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
}
#[cfg(target_arch = "wasm32")]
let _ = focused_windows;
if let Some(error) = &output.error {
log::warn!("docking: {:?}", error.error);
}
@@ -612,13 +625,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) {
Panel::Shader => crate::shader_settings::body(app, ui),
Panel::History => crate::windows::history(app, ui),
Panel::Log => crate::log_panel::body(app, ui),
Panel::BakingLog => {
egui::ScrollArea::vertical().show(ui, |ui| {
for entry in app.session.log.entries().iter().filter(|entry| entry.source == "Baker") {
ui.label(entry.line());
}
});
}
Panel::BakingLog => crate::baking_log::body(app, ui),
Panel::Export => crate::export_panel::body(app, ui),
Panel::Renderer => crate::render_mode::settings_body(app, ui),
Panel::Viewport => {}
@@ -759,16 +766,17 @@ mod tests {
}
#[test]
fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() {
fn the_bake_dock_round_trips_with_the_baking_log_under_both_settings_columns() {
let dock = Dock::for_baking();
assert!(validate(dock.workspace()).is_ok());
assert_eq!(
panels_of(dock.workspace()),
[Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport]
[Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::BakingLog, Panel::Viewport]
);
assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings));
let back: Dock = serde_json::from_str(&serde_json::to_string(&dock).unwrap()).unwrap();
assert_eq!(back, dock);
}
+3 -3
View File
@@ -18,6 +18,8 @@ use crate::property_sheet::PropertySheet;
use crate::shelf_preview::ShelfPreview;
use crate::theme::Tokens;
mod bake_note;
/// The outline on the preview while it can open enlarged under the pointer, or is open, in points
const ENLARGE_OUTLINE_WIDTH: f32 = 1.0;
@@ -35,6 +37,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui,
PropertySheet::show(ui, ("generator_sheet", id), |sheet| {
sheet.section(tr("Generator"), false);
slot_card(app, sheet, id, generator);
bake_note::bake_notes(app, sheet, generator);
let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None);
if band.reset {
@@ -68,9 +71,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui,
if sheet.band(tr("Attributes"), false, None, None).open {
attributes(sheet, generator.kind);
}
if !app.session.doc.baked.contains_key(&app.session.ts()) {
sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators."));
}
});
}
@@ -0,0 +1,104 @@
//! One quiet line under a generator's kind when a mesh map it reads is not baked or out of date, with a Bake button
use egui::{Align, Layout, RichText, Stroke, Ui, UiBuilder, vec2};
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::bake::settings_patch;
use texturecraft_engine::core::{BakeChange, BakedMap, Generator};
use crate::TextureCraftApp;
use crate::i18n::{bake_change_reason, baked_map_label, tr, trf};
use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS};
use crate::theme::{Tokens, semibold};
/// Height of the note's line, in points (the mock's 28 px row)
const NOTE_HEIGHT: f32 = 28.0;
/// Height of the Bake button, in points (the panels' 24 px controls)
const BUTTON_HEIGHT: f32 = 24.0;
/// Size of the tooltip's title and reasons, in points
const TOOLTIP_TEXT_SIZE: f32 = 12.0;
/// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date
pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) {
let texture_set = app.session.ts();
for map in generator.baked_maps_read() {
if generator.inputs.contains_key(map) {
continue;
}
let baked = app.session.baked(texture_set).is_some_and(|baked| baked.maps.contains_key(map));
let changes = if baked { app.session.bake_changes(texture_set, *map) } else { Vec::new() };
if baked && changes.is_empty() {
continue;
}
// A full-width line inside the sheet's side padding
let (line, _) = sheet.ui.allocate_exact_size(vec2(sheet.ui.available_width(), NOTE_HEIGHT), egui::Sense::hover());
let builder = UiBuilder::new().id_salt(map).max_rect(line.shrink2(vec2(SIDE_PADDING_POINTS, 0.0))).layout(Layout::left_to_right(Align::Center));
sheet.ui.scope_builder(builder, |ui| note(app, ui, (texture_set, *map), &changes));
}
}
/// The line for `map` of `texture_set`: not baked when `changes` is empty, else out of date because of them
fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, BakedMap), changes: &[BakeChange]) {
let tokens = Tokens::get(ui.ctx());
let name = tr(baked_map_label(map));
let (glyph, text, title) = match changes.is_empty() {
true => (ic::WARNING, trf("{map} map not baked", &[("map", &name)]), tr("Not baked")),
false => (ic::CLOCK, trf("{map} map out of date", &[("map", &name)]), tr("Out of date")),
};
let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map));
ui.label(RichText::new(glyph).color(tokens.warning));
let reasons = reasons(changes, checked);
let line = ui.add(egui::Label::new(&text).truncate());
ui.ctx().accesskit_node_builder(line.id, |node| node.set_description(reasons.join(" ")));
line.on_hover_ui(|ui| {
ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text));
for reason in reasons {
ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim));
}
});
let bake = ui
.with_layout(Layout::right_to_left(Align::Center), |ui| {
let button = egui::Button::new(tr("Bake")).stroke(Stroke::new(1.0, tokens.button_border)).min_size(vec2(0.0, BUTTON_HEIGHT));
ui.add_enabled(app.bake.is_none(), button)
.on_hover_text(tr("Bake this texture set's mesh maps in the background"))
.on_disabled_hover_text(tr("A bake is already running"))
})
.inner;
if bake.clicked() {
bake_map(app, texture_set, map);
}
}
/// Why the line shows: what changed since the bake, or what a missing map does to the generator
fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> {
if changes.is_empty() {
let mut reasons = vec![tr("The generator reads a flat value until this map is baked.")];
if !checked {
reasons.push(tr("Bake turns this map on in the bake settings first."));
}
return reasons;
}
changes.iter().map(|change| tr(bake_change_reason(*change))).collect()
}
/// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off
fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) {
let Some(before) = app.session.doc.project.texture_sets.get(texture_set).map(|set| set.bake.clone()) else { return };
if !before.maps.is_enabled(map) {
let mut after = before.clone();
after.maps.set_enabled(map, true);
app.run("bake.settings", json!({ "ts": texture_set, "patch": settings_patch(&before, &after) }));
}
app.start_bake(vec![texture_set]);
}
+13
View File
@@ -97,6 +97,19 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta
}
}
/// Why a baked map is out of date: one sentence for what changed after its bake
pub(crate) fn bake_change_reason(change: texturecraft_engine::core::BakeChange) -> &'static str {
use texturecraft_engine::core::BakeChange;
match change {
BakeChange::LowPoly => n_("The mesh changed after this bake."),
BakeChange::HighPoly => n_("The high poly files changed after this bake."),
BakeChange::Cage => n_("The cage changed after this bake."),
BakeChange::Settings => n_("The common bake settings changed after this bake."),
BakeChange::MapSettings => n_("This map's bake settings changed after this bake."),
}
}
/// The saved language that follows the operating system's (Settings > Language > Default (System Language)).
pub const SYSTEM_LANGUAGE: &str = "";
+94 -18
View File
@@ -10,6 +10,7 @@
mod anchor_properties;
mod angle_dial;
mod ask;
mod auto_rebake;
#[cfg(not(target_arch = "wasm32"))]
mod autosave_name;
mod bake_job;
@@ -18,6 +19,7 @@ mod bake_preset;
pub mod bake_presets;
mod bake_report;
mod bake_scene;
pub mod baking_log;
mod color_management;
mod color_picker;
mod color_selection_editor;
@@ -121,6 +123,7 @@ mod placed_fill_slot;
mod placement;
mod pointer_lock;
mod popup_drag;
mod press_edit;
mod preview_dots;
mod preview_image;
mod preview_request;
@@ -294,6 +297,8 @@ pub struct TextureCraftApp {
pub bake: Option<BakeJob>,
/// What the bake running now has done so far, for the summary when it ends
pub bake_report: bake_report::BakeReport,
/// When the out-of-date auto-rebake maps are rebaked
auto_rebake: auto_rebake::AutoRebake,
/// The Import PBR textures dialog while it is open.
pub pbr_import: Option<pbr_import::PbrDialog>,
pub resize: Option<ResizeJob>,
@@ -476,6 +481,7 @@ impl TextureCraftApp {
gpu_memory: (Vec::new(), None),
bake: None,
bake_report: Default::default(),
auto_rebake: Default::default(),
pbr_import: None,
resize: None,
#[cfg(not(target_arch = "wasm32"))]
@@ -732,8 +738,12 @@ impl TextureCraftApp {
self.session.bake_preview_begin(orders);
let total = sets.len();
match only {
Some(map) => self.session.begin_map_bake_log(&sets, &[map]),
None => self.session.begin_bake_log(&sets),
}
self.bake_report = bake_report::BakeReport::started(self.last_time);
self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only });
self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only, rebake: None });
}
/// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer
@@ -850,17 +860,21 @@ impl TextureCraftApp {
if let Some(running) = &job.current {
running.progress.cancel.store(true, Ordering::Relaxed);
}
self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index));
self.bake = None;
return;
}
ctx.request_repaint_after(BAKE_POLL_INTERVAL);
if let Some(running) = &job.current {
if let Some(running) = &mut job.current {
let set_index = running.set_index;
// Wait for the sender to close so the last map also gets a preview frame
match running.maps.try_recv() {
Ok(map) => {
running.finished.resolution = map.resolution;
running.finished.maps.insert(map.map, map.data.clone());
self.session.bake_log.map_baked(set_index, map.map);
self.session.bake_preview_map(set_index, map);
return;
}
@@ -874,22 +888,21 @@ impl TextureCraftApp {
job.current = None;
match self.session.apply_streamed_bake(set_index, output) {
Ok(()) => self.bake_report.map_count += maps_baked,
Ok(()) => {
self.session.bake_log.set_finished(set_index);
self.bake_report.map_count += maps_baked;
}
Err(error) => self.bake_failed(set_index, &error.to_string()),
}
}
Ok(Err(error)) => {
// The worker's error ends the whole bake; the maps of the sets before it stay
self.bake_failed(set_index, &error.to_string());
self.cancel_bake();
self.finish_bake_report();
self.end_failed_bake(set_index, &error.to_string());
return;
}
Err(std::sync::mpsc::TryRecvError::Empty) => return,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
self.bake_failed(set_index, i18n::tr("The bake worker stopped"));
self.cancel_bake();
self.finish_bake_report();
self.end_failed_bake(set_index, i18n::tr("The bake worker stopped"));
return;
}
}
@@ -906,17 +919,23 @@ impl TextureCraftApp {
let set_index = job.queue.remove(0);
let only = job.only;
let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some()));
self.session.bake_preview_set_current(set_index);
let task = match only {
Some(map) => self.session.bake_task_only(set_index, map),
None => self.session.bake_task(set_index),
self.session.bake_log.set_started(set_index);
let task = match (rebake, only) {
(Some((map, true)), _) => self.session.bake_painted_task(set_index, map),
(Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)),
(None, Some(map)) => self.session.bake_task_only(set_index, map),
(None, None) => self.session.bake_task(set_index),
};
match task {
Ok(task) => {
self.session.bake_log.high_polys_loaded(set_index);
let progress = Arc::new(Progress::new());
let worker_progress = progress.clone();
let maps_total = task.maps().len();
let (sources, painted_stroke) = (task.sources.clone(), task.painted_stroke);
let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let worker_done = maps_done.clone();
let (sender, maps) = std::sync::mpsc::channel();
@@ -930,16 +949,29 @@ impl TextureCraftApp {
});
if let Some(job) = self.bake.as_mut() {
job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total });
job.current =
Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total, finished: Default::default(), sources, painted_stroke });
}
}
Err(error) => self.bake_failed(set_index, &error.to_string()),
}
}
/// End the bake at texture set `set_index`, whose worker failed: none of its maps are kept, the queued sets are canceled
fn end_failed_bake(&mut self, set_index: usize, error: &str) {
if let Some(job) = &mut self.bake {
job.current = None;
}
self.bake_failed(set_index, error);
self.cancel_bake();
self.finish_bake_report();
}
/// Note a texture set whose bake failed: one Log line, counted in the summary
fn bake_failed(&mut self, set_index: usize, error: &str) {
self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}"));
self.session.bake_log.set_failed(set_index, error);
self.bake_report.failed_set_count += 1;
}
@@ -952,23 +984,66 @@ impl TextureCraftApp {
self.session.log.info("Baker", line);
}
if self.bake_report.auto_rebake && !failed {
return;
}
self.toast(text, failed);
if let Some(toast) = self.toasts.last_mut() {
toast.show_log = failed;
}
}
/// Cancel the active worker, discard queued sets and restore the view. The current set's
/// preview maps are discarded; previously applied sets keep their results and undo steps.
/// Cancel the bake and restore the view. Keep applied sets and any eligible maps from the running set.
pub fn cancel_bake(&mut self) {
let Some(job) = self.bake.take() else { return };
if let Some(running) = job.current {
running.progress.cancel.store(true, Ordering::Relaxed);
let mut discarded = None;
let mut worker_failed = false;
if let Some(mut running) = job.current {
running.progress.cancel();
let set_index = running.set_index;
if job.mesh_id != self.session.mesh_id {
discarded = Some(set_index);
} else {
// Collect every map the worker sent, including those the preview never took
while let Ok(map) = running.maps.try_recv() {
running.finished.resolution = map.resolution;
running.finished.maps.insert(map.map, map.data);
self.session.bake_log.map_baked(set_index, map.map);
}
let failure = match running.receiver.try_recv() {
Ok(Ok(_) | Err(texturecraft_engine::EngineError::BakeCancelled)) | Err(std::sync::mpsc::TryRecvError::Empty) => None,
Ok(Err(error)) => Some(error.to_string()),
Err(std::sync::mpsc::TryRecvError::Disconnected) => Some(i18n::tr("The bake worker stopped").to_owned()),
};
if let Some(error) = failure {
self.bake_failed(set_index, &error);
worker_failed = true;
} else {
let kept = self.session.keep_canceled_bake(set_index, running.finished, &running.sources, running.painted_stroke);
match kept {
Ok(maps) if !maps.is_empty() => {}
Ok(_) => discarded = Some(set_index),
Err(error) => {
self.toast(error.to_string(), true);
discarded = Some(set_index);
}
}
}
}
}
// Only the current set is uncommitted; completed sets remain applied
self.session.bake_log.cancel(discarded);
self.session.bake_preview_end();
if worker_failed {
self.finish_bake_report();
}
}
/// Resize texture set `ts` to `resolution` on a worker thread (the document changes when
@@ -1238,6 +1313,7 @@ impl eframe::App for TextureCraftApp {
self.poll_bake(ctx);
self.bake_map_thumbnails.retain_mesh(self.session.mesh_id);
bake_mode::poll_live_preview(self, ctx);
auto_rebake::poll(self, ctx);
self.poll_resize(ctx);
#[cfg(not(target_arch = "wasm32"))]
self.poll_high_poly_job(ctx);
+8
View File
@@ -0,0 +1,8 @@
//! What [`crate::widgets::press_edit`] keeps of an editor's last change
/// The press an editor's last change belonged to, and the frame it was seen in
#[derive(Clone, Copy)]
pub(crate) struct PressEdit {
pub(crate) press: u64,
pub(crate) frame: u64,
}
+2 -1
View File
@@ -75,13 +75,14 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection};
pub(crate) use row_lead::RowLead;
pub(crate) use section_tabs::{
SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope,
room_past_end, section_tabs,
room_past_end, section_tabs, shown_tab_box,
};
pub(crate) use sheet::PropertySheet;
pub(crate) use size_columns_response::SizeColumnsResponse;
pub(crate) use slot_response::SlotResponse;
pub(crate) use stack_slider::StackSlider;
pub(crate) use stacked_rows::{CHECK_SIZE, paint_check};
pub(crate) use switch_control::paint_focus_outline;
pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) {
if response.has_focus() {
@@ -110,7 +110,7 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect {
}
/// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip
fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) {
painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel);
}
@@ -63,7 +63,7 @@ pub(super) fn untinted(_index: usize) -> &'static [Color32] {
&[]
}
pub(super) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) {
pub(crate) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) {
painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(FOCUS_OUTLINE_WIDTH, color), StrokeKind::Inside);
}
@@ -1042,6 +1042,48 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() {
assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening");
}
/// Editing one editor after another, a press at a time, keeps the record of the latest press only (it kept one per editor ever dragged)
#[test]
fn the_editors_of_earlier_presses_are_forgotten() {
const EDITOR_COUNT: usize = 12;
let context = egui::Context::default();
let button =
|pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
for editor in 0..EDITOR_COUNT {
let owner = egui::Id::unique(("distinct editor", editor));
for pressed in [true, false] {
let input = egui::RawInput { events: vec![button(pressed)], ..Default::default() };
context.run_ui(input, |ui| _ = crate::widgets::press_edit(ui, owner, pressed)).textures_delta.clear();
}
}
let kept = context.data(|data| data.count::<crate::press_edit::PressEdit>());
assert!(kept < 2, "{kept} editor records kept after {EDITOR_COUNT} presses");
}
/// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step
#[test]
fn a_drag_stays_one_undo_step_while_another_window_draws() {
let context = egui::Context::default();
let owner = egui::Id::unique("held editor");
let edit = |events| {
let mut result = None;
let mut output = context.run_ui(egui::RawInput { events, ..Default::default() }, |ui| result = crate::widgets::press_edit(ui, owner, true));
output.textures_delta.clear();
result
};
let press = egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
assert_eq!(edit(vec![press]), Some(false), "the press starts an undo step");
let viewport = egui::ViewportId::from_hash_of("floating History");
let floating =
egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() };
context.run_ui(floating, |_| {}).textures_delta.clear();
assert_eq!(edit(Vec::new()), Some(true), "the held press continues its undo step");
}
#[test]
fn section_tabs_show_focus_before_a_keyboard_jump() {
let mut harness = builder(Brightness::MediumDark).build_ui(|ui| {
+5
View File
@@ -12,4 +12,9 @@ pub struct RunningBake {
/// Maps finished so far, and how many the set makes.
pub maps_done: Arc<std::sync::atomic::AtomicUsize>,
pub maps_total: usize,
/// The maps received so far, kept when the bake is canceled even if the preview has closed
pub finished: texturecraft_engine::compose::BakedMaps,
/// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps
pub sources: std::collections::BTreeMap<texturecraft_engine::core::BakedMap, texturecraft_engine::core::BakeSource>,
pub painted_stroke: u64,
}
+27 -1
View File
@@ -548,7 +548,7 @@ fn default_true() -> bool {
}
/// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking`
const BAKE_LAYOUT_VERSION: u32 = 2;
const BAKE_LAYOUT_VERSION: u32 = 3;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UiState {
@@ -686,6 +686,12 @@ pub struct UiState {
/// The Log panel's shown channel tab
#[serde(default)]
pub log_channel: crate::log_panel::LogChannel,
/// The Baking Log panel's shown tab
#[serde(default)]
pub baking_log_tab: crate::baking_log::BakingLogTab,
/// Whether the Baking Log keeps only the rows with an issue
#[serde(default)]
pub baking_log_issues_only: bool,
/// The project template the last New project was created from (name or label)
#[serde(default)]
pub last_template: String,
@@ -849,6 +855,8 @@ impl Default for UiState {
bake_preset_name: String::new(),
layout_dialog: None,
log_channel: crate::log_panel::LogChannel::default(),
baking_log_tab: crate::baking_log::BakingLogTab::default(),
baking_log_issues_only: false,
last_template: String::new(),
log_selection: Default::default(),
log_anchor: None,
@@ -1023,6 +1031,24 @@ mod tests {
}
}
#[test]
fn a_saved_bake_dock_with_the_log_at_the_bottom_gets_the_baking_log_there() {
use crate::docking::Panel;
let mut ui = UiState { mode: Mode::Baking, ..UiState::default() };
ui.sync_mode_dock();
ui.dock.close(Panel::BakingLog);
ui.dock.focus(Panel::Log);
let mut saved = serde_json::to_value(&ui).unwrap();
saved["bake_layout_version"] = serde_json::json!(2);
let mut loaded: UiState = serde_json::from_value(saved).unwrap();
loaded.sync_mode_dock();
assert!(loaded.dock.is_visible(Panel::BakingLog), "the Baking Log takes the bottom of the bake layout");
assert!(!loaded.dock.is_open(Panel::Log), "the general Log stays in Window > Views");
}
#[test]
fn the_bake_layout_survives_a_restart_whichever_mode_was_open() {
for mode in [Mode::Painting, Mode::Baking] {
+2 -1
View File
@@ -297,7 +297,8 @@ mod tests {
assert!(!safe_to_close(h.state()), "unsaved changes");
h.state_mut().session.modified = false;
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None });
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None, rebake: None });
assert!(!safe_to_close(h.state()), "a bake");
h.state_mut().bake = None;
+14 -6
View File
@@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, Strok
use crate::drawn_icon::DrawnIcon;
use crate::i18n::tr;
use crate::press_edit::PressEdit;
use crate::theme::Tokens;
/// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike
@@ -31,21 +32,28 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option<bool> {
return None;
}
ui.memory_mut(|memory| {
let edits = memory.caches.cache::<egui::cache::FramePublisher<egui::Id, u64>>();
// Kept in memory, not a frame cache: a floating panel in its own OS window ends a pass of its own inside ours, which would clear it every frame
let frame = ui.ctx().cumulative_frame_nr();
ui.data_mut(|data| {
let id = id.with("pointer edit");
let previous = edits.get(&id).copied();
let previous = data.get_temp::<PressEdit>(id);
let merge = match press {
Some(start) => {
let continuing = previous == Some(start);
let continuing = previous.is_some_and(|previous| previous.press == start);
if changed || continuing {
edits.set(id, start);
// Only the latest press's editors can merge, so its first change forgets every editor of the older ones
let latest_press = egui::Id::unique("pointer edit press");
if data.get_temp::<u64>(latest_press) != Some(start) {
data.remove_by_type::<PressEdit>();
data.insert_temp(latest_press, start);
}
data.insert_temp(id, PressEdit { press: start, frame });
}
continuing
}
// A final movement still belongs to the press that ended
None => release_only && previous.is_some(),
None => release_only && previous.is_some_and(|previous| previous.frame + 1 >= frame),
};
changed.then_some(merge)
})
+11 -2
View File
@@ -71,16 +71,19 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() {
}
#[test]
fn cancelling_restores_the_view_and_leaves_the_document_alone() {
fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() {
let mut harness = harness();
let before = harness.state().session.doc.baked.get(&0).cloned();
// One frame starts the worker; a finished map shows only from the next one
harness.state_mut().start_bake(vec![0]);
harness.run_steps(2);
harness.run_steps(1);
assert!(harness.state().session.bake_preview_active());
let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0));
assert!(harness.state_mut().session.begin_stroke(at, viewport, 1.0).is_err(), "painting is paused");
harness.state_mut().cancel_bake();
harness.run_steps(2);
@@ -134,6 +137,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
total: 1,
mesh_id,
only: None,
rebake: None,
current: Some(RunningBake {
set_index: 0,
progress: Arc::new(Progress::new()),
@@ -141,6 +145,9 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
maps,
maps_done: Arc::new(AtomicUsize::new(MAPS.len())),
maps_total: MAPS.len(),
finished: Default::default(),
sources: Default::default(),
painted_stroke: 0,
}),
});
@@ -149,6 +156,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
assert!(harness.state().bake.is_some(), "an open map stream can still deliver a map");
assert_eq!(harness.state().session.doc.baked, before);
for map in finished_maps {
map_sender.send(map).unwrap();
}
@@ -162,6 +170,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
assert!(harness.state().session.bake_preview_baked(0).unwrap().maps.contains_key(&map));
assert_eq!(harness.state().session.doc.baked, before);
}
harness.run_steps(1);
assert!(harness.state().bake.is_none());
+200
View File
@@ -0,0 +1,200 @@
//! Auto-rebake in the app: a settings change rebakes the auto-rebake map alone, in the background
use egui_kittest::Harness;
use serde_json::json;
use texturecraft_engine::bake::BakeMapState;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::state::Mode;
/// Frames far past the half-second settle wait, at the harness's quarter-second step
const PAST_THE_SETTLE_FRAMES: usize = 60;
/// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map
fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1000.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
harness
}
fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serde_json::Value) {
execute(&mut harness.state_mut().session, "bake.settings", &params).unwrap();
}
#[test]
fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() {
let mut harness = harness(64);
let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone();
change_settings(&mut harness, json!({ "positionMode": "boundingBox" }));
super::step_until(&mut harness, "the rebake", |app| app.bake.is_some());
super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none());
let app = harness.state();
assert!(app.session.doc.project.texture_sets[0].bake_sources.contains_key(&BakedMap::Position), "the rebake records what it read");
assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position));
assert!(std::sync::Arc::ptr_eq(&app.session.baked(0).unwrap().maps[&BakedMap::Id], &id_before), "the ID map was not baked again");
let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect();
assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]);
assert!(app.toasts.is_empty(), "a rebake that went well is quiet");
}
#[test]
fn the_progress_footer_names_the_map_the_rebake_makes() {
let mut harness = harness(64);
change_settings(&mut harness, json!({ "positionMode": "boundingBox" }));
super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some()));
let stage = harness.state().session.bake_preview.as_ref().and_then(|preview| preview.stage());
assert_eq!(stage.map(|stage| (stage.map, stage.total)), Some((BakedMap::Position, 1)), "not the set's first checked map, not all its maps");
}
#[test]
fn nothing_is_rebaked_outside_bake_mode() {
let mut harness = harness(64);
harness.state_mut().ui.mode = Mode::Painting;
change_settings(&mut harness, json!({ "positionMode": "boundingBox" }));
harness.run_steps(120);
assert!(harness.state().bake.is_none());
assert!(!harness.state().session.bake_changes(0, BakedMap::Position).is_empty());
}
#[test]
fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() {
let mut harness = harness(64);
execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["ambientOcclusion"], "ao": { "rays": 1 } })).unwrap();
execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": "ambientOcclusion" })).unwrap();
// A slow rebake, so the next change lands while it runs
change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } }));
super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some()));
change_settings(&mut harness, json!({ "ao": { "rays": 128 } }));
harness.run_steps(1);
let app = harness.state();
assert!(app.bake.is_none(), "the outdated rebake stopped");
let ambient_occlusion = app.session.bake_log.maps.iter().find(|row| row.map == BakedMap::AmbientOcclusion).map(|row| row.state.clone());
assert_eq!(ambient_occlusion, Some(BakeMapState::Canceled));
}
#[test]
fn a_canceled_rebake_holds_back_only_its_own_texture_set() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap();
for set in [0, 1] {
execute(&mut session, "bake.autoRebake", &json!({ "ts": set, "map": "position" })).unwrap();
}
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1000.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
let rebaking = |app: &TextureCraftApp, set: usize| app.bake.as_ref().and_then(|job| job.rebake.as_ref()).is_some_and(|rebake| rebake.0 == set);
change_settings(&mut harness, json!({ "ts": "all", "positionMode": "boundingBox" }));
super::step_until(&mut harness, "the first set's rebake", |app| rebaking(app, 0));
harness.state_mut().cancel_bake();
super::step_until(&mut harness, "the second set's rebake", |app| rebaking(app, 1));
}
#[test]
fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() {
let mut harness = harness(64);
let plane = primitives::builtin("plane").unwrap();
let mut high = String::from("o Part_high\n");
for position in &plane.positions {
high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z);
}
for triangle in plane.indices.as_chunks::<3>().0 {
high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1);
}
let session = &mut harness.state_mut().session;
session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap();
execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap();
harness.run_steps(4);
assert!(harness.state().bake.is_none(), "up to date after the bake");
execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap();
super::step_until(&mut harness, "the rebake", |app| app.bake.is_some());
super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none());
let app = harness.state();
assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke");
let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect();
assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]);
assert!(app.toasts.is_empty(), "a rebake that went well is quiet");
}
#[test]
fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() {
use egui_kittest::kittest::Queryable;
let mut harness = harness(64);
let auto_rebake = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].auto_rebake;
assert_eq!(auto_rebake(&harness), Some(BakedMap::Position));
assert!(harness.query_by_label("Auto-rebake Normal").is_none(), "off: shown only on a hovered, focused or selected row");
harness.get_by_role_and_label(egui::Role::Button, "Normal").hover();
harness.run_steps(2);
harness.get_by_label("Auto-rebake Normal");
// ID is the selected row (the first checked map), which shows its icons
harness.get_by_label("Auto-rebake ID").click();
harness.run_steps(2);
assert_eq!(auto_rebake(&harness), Some(BakedMap::Id), "one map per set: ID replaces Position");
harness.get_by_label("Auto-rebake ID").click();
harness.run_steps(2);
assert_eq!(auto_rebake(&harness), None);
}
#[test]
fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_step() {
let mut harness = harness(64);
change_settings(&mut harness, json!({ "positionMode": "boundingBox" }));
// Held still well past the settle time, as a hand pausing mid-drag, in the window's corner where no control takes the press
let corner = harness.ctx.content_rect().right_bottom() - egui::vec2(10.0, 10.0);
harness.drag_at(corner);
harness.run_steps(120);
assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts");
harness.drop_at(corner);
super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some());
}
#[test]
fn a_rebake_canceled_in_one_project_still_runs_in_the_next_project_opened() {
let mut harness = harness(64);
change_settings(&mut harness, json!({ "positionMode": "boundingBox" }));
super::step_until(&mut harness, "the rebake", |app| app.bake.is_some());
harness.state_mut().cancel_bake();
harness.run_steps(PAST_THE_SETTLE_FRAMES);
assert!(harness.state().bake.is_none(), "a canceled rebake is not tried again in its project");
// The same project opened again: its out-of-date map reads what the canceled one read
let mesh = primitives::builtin("plane").unwrap();
let mut next = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut next, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap();
execute(&mut next, "bake.autoRebake", &json!({ "map": "position" })).unwrap();
execute(&mut next, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
harness.state_mut().session.switch_to(next);
super::step_until(&mut harness, "the rebake in the opened project", |app| app.bake.is_some());
}
+66 -11
View File
@@ -1,15 +1,27 @@
//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps
//! the mesh meanwhile, the job is cancelled and its result is dropped.
//! A bake job belongs to the mesh it started on: when `file.changeMesh` or a reimport swaps the mesh meanwhile, the job is cancelled and its result dropped; a cancel keeps the maps it finished
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::sync::mpsc::Sender;
use egui_kittest::Harness;
use texturecraft_engine::StreamedMap;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::BakedMap;
use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp};
/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`.
/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`
fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) {
let (mut harness, progress, _senders) = running_job(mesh_id);
harness.step();
check(&harness, &progress);
}
/// The ends a test plays the bake worker with: its result (never sent) and its finished maps
type WorkerSenders = (Sender<texturecraft_engine::Result<texturecraft_engine::StreamedBake>>, Sender<StreamedMap>);
/// An app with a running bake job of set 0 started on mesh `mesh_id`, whose worker sends only what the test sends
fn running_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc<Progress>, WorkerSenders) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
@@ -17,15 +29,23 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
let progress = Arc::new(Progress::new());
let (_result_sender, receiver) = std::sync::mpsc::channel();
let (_map_sender, maps) = std::sync::mpsc::channel();
let (result_sender, receiver) = std::sync::mpsc::channel();
let (map_sender, maps) = std::sync::mpsc::channel();
let job_mesh_id = mesh_id(harness.state().session.mesh_id);
let running =
RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 };
harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None });
harness.step();
check(&harness, &progress);
let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let running = RunningBake {
set_index: 0,
progress: progress.clone(),
receiver,
maps,
maps_done,
maps_total: 1,
finished: Default::default(),
sources: Default::default(),
painted_stroke: 0,
};
harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None });
(harness, progress, (result_sender, map_sender))
}
#[test]
@@ -49,3 +69,38 @@ fn a_job_on_the_current_mesh_keeps_running() {
},
);
}
#[test]
fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() {
let (mut harness, _progress, (result_sender, map_sender)) = running_job(|current| current);
let data = Arc::new(vec![0.5; 64 * 64]);
let normal_before = harness.state().session.baked(0).and_then(|baked| baked.maps.get(&BakedMap::Normal).cloned());
assert!(normal_before.is_some(), "the sample's Normal map is baked before the job");
for (index, map) in [BakedMap::Curvature, BakedMap::AmbientOcclusion].into_iter().enumerate() {
map_sender.send(StreamedMap { map, index, total: 2, resolution: 64, height: 64, data: data.clone() }).unwrap();
}
result_sender.send(Err(texturecraft_engine::EngineError::BakeCancelled)).unwrap();
harness.state_mut().cancel_bake();
let baked = harness.state().session.baked(0).unwrap();
for map in [BakedMap::Curvature, BakedMap::AmbientOcclusion] {
assert!(baked.maps.get(&map).is_some_and(|kept| Arc::ptr_eq(kept, &data)), "{map:?} is kept");
}
let normal = baked.maps.get(&BakedMap::Normal);
assert!(normal.zip(normal_before.as_ref()).is_some_and(|(now, before)| Arc::ptr_eq(now, before)), "a map the worker never sent keeps the one baked before");
}
#[test]
fn a_cancel_does_not_keep_maps_from_a_worker_that_already_failed() {
let (mut harness, _progress, (result_sender, map_sender)) = running_job(|current| current);
let map = BakedMap::Normal;
let before = harness.state().session.baked(0).unwrap().maps[&map].clone();
let data = Arc::new(vec![0.5; 64 * 64 * map.components()]);
map_sender.send(StreamedMap { map, index: 0, total: 2, resolution: 64, height: 64, data }).unwrap();
result_sender.send(Err(texturecraft_engine::EngineError::Other("the second map failed".into()))).unwrap();
harness.state_mut().cancel_bake();
let after = &harness.state().session.baked(0).unwrap().maps[&map];
assert!(Arc::ptr_eq(&before, after), "the failed set leaves the previous bake in place");
}
+71 -1
View File
@@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() {
session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
let mesh = session.mesh.clone();
session.doc.bake_meshes.cage =
Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() });
Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 });
let settings = &mut session.doc.project.texture_sets[0].bake;
(settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true);
harness.run_steps(3);
@@ -697,3 +697,73 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() {
assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material");
}
#[test]
fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing() {
use serde_json::json;
use texturecraft_engine::execute;
// Use two sets so the row shows all hover icons alongside the out-of-date clock
let mut harness = harness(None);
execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap();
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
harness.get_by_label("Out of date: Ambient Occlusion");
select_map(&mut harness, "Ambient Occlusion");
assert!(harness.state().bake_progress().is_none(), "the click landed on the row, not its Bake Only icon");
assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings");
harness.get_by_label("Attenuation");
}
#[test]
fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() {
use serde_json::json;
use texturecraft_engine::execute;
let mesh = texturecraft_engine::geom::primitives::builtin("plane").unwrap();
let mut session = texturecraft_engine::Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1200.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
assert!(harness.query_by_label("Out of date: Position").is_none(), "just baked");
execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap();
harness.run_steps(3);
let description = harness.get_by_label("Out of date: Position").accesskit_node().description();
assert!(description.is_some_and(|reasons| !reasons.is_empty()), "what changed is read without hovering");
assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date");
}
#[test]
fn dragging_secondary_rays_is_one_undo_step() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
select_map(&mut harness, "Ambient Occlusion");
let rays_before = harness.state().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays;
let history_steps = harness.state().session.history_labels().len();
let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect();
let at = |share: f32| egui::pos2(track.left() + track.width() * share, track.center().y);
harness.drag_at(at(0.2));
harness.run_steps(crate::DRAG_STEP_FRAMES);
for step in 1..=3 {
harness.hover_at(at(0.2 + 0.15 * step as f32));
harness.run_steps(crate::DRAG_STEP_FRAMES);
}
// The release moves too, and that last change still belongs to the drag
harness.drop_at(at(0.8));
harness.run_steps(crate::SETTLE_FRAMES);
let session = &harness.state().session;
assert_ne!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays, rays_before, "the drag changed the rays");
assert_eq!(session.history_labels().len(), history_steps + 1, "{:?}", session.history_labels());
}
+317
View File
@@ -0,0 +1,317 @@
//! The Baking Log panel: the latest bake, map by map
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair};
use texturecraft_engine::core::{BakeResolution, BakedMap};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
use texturecraft_ui_egui::state::Mode;
fn harness() -> Harness<'static, TextureCraftApp> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
for texture_set in &mut session.doc.project.texture_sets {
texture_set.bake = Default::default();
texture_set.bake.common.resolution = BakeResolution::R64;
texture_set.bake.maps.select([BakedMap::Id, BakedMap::Position]);
}
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1000.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
harness
}
/// Run frames until the bake ends, then a few more for its result to show
fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) {
super::step_until(harness, "the end of the bake", |app| app.bake.is_none());
harness.run_steps(super::SETTLE_FRAMES);
}
/// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails
fn bake_with_set_1_failing(harness: &mut Harness<'static, TextureCraftApp>, failed_set_maps: &[BakedMap]) {
let set = &mut harness.state_mut().session.doc.project.texture_sets[1];
set.uv_tiles = vec![1001];
set.bake_excluded_tiles.insert(1001);
set.bake.maps.select(failed_set_maps.iter().copied());
harness.state_mut().start_bake(vec![0, 1]);
run_to_the_end(harness);
}
#[test]
fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() {
let mut harness = harness();
assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log");
bake_with_set_1_failing(&mut harness, &[BakedMap::Id]);
let names: Vec<String> = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect();
for map in ["ID", "Position"] {
assert!(harness.query_by_label(&format!("{} {map}, Baked", names[0])).is_some(), "set 0's {map} row is ticked");
}
assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed");
}
#[test]
fn a_failed_rows_reason_is_read_without_hovering() {
let mut harness = harness();
bake_with_set_1_failing(&mut harness, &[BakedMap::Id]);
let app = harness.state();
let row = app.session.bake_log.maps.iter().find(|row| row.texture_set == 1).unwrap();
let BakeMapState::Failed(reason) = &row.state else { panic!("set 1's bake failed: {:?}", row.state) };
let label = format!("{} ID, Not baked", row.set_name);
let node = harness.get_by_label(&label);
assert_eq!(node.accesskit_node().description().as_deref(), Some(reason.as_str()), "the row's node carries its tooltip's reason");
}
#[test]
fn a_one_map_bake_lists_only_that_map() {
let mut harness = harness();
harness.state_mut().start_bake_of(vec![0], Some(BakedMap::Position));
run_to_the_end(&mut harness);
let name = harness.state().session.doc.project.texture_sets[0].name.clone();
assert!(harness.query_by_label(&format!("{name} Position, Baked")).is_some(), "the baked map is ticked");
assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row");
}
#[test]
fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() {
let mut harness = harness();
let before = harness.state().session.baked(0).cloned().unwrap_or_default();
harness.state_mut().start_bake(vec![0, 1]);
// Leaving Bake mode closes the preview; the bake and the maps it finishes go on
harness.state_mut().ui.mode = Mode::Painting;
let state = |app: &TextureCraftApp, set: usize, map: BakedMap| {
app.session.bake_log.maps.iter().find(|row| row.texture_set == set && row.map == map).map(|row| row.state.clone())
};
super::step_until(&mut harness, "set 0's first map", |app| state(app, 0, BakedMap::Id) == Some(BakeMapState::Baked));
assert!(!harness.state().session.bake_preview_active());
harness.state_mut().cancel_bake();
let app = harness.state();
assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick");
for map in [BakedMap::Id, BakedMap::Position] {
assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns");
}
// The worker may have queued Position before cancellation
let row = state(app, 0, BakedMap::Position);
assert!(matches!(row, Some(BakeMapState::Baked | BakeMapState::Canceled)), "set 0's Position is ticked or, unfinished, warns: {row:?}");
let after = app.session.baked(0).cloned().unwrap_or_default();
let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) {
(Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new),
(old, new) => old.is_some() != new.is_some(),
};
for map in [BakedMap::Id, BakedMap::Position] {
let ticked = state(app, 0, map) == Some(BakeMapState::Baked);
assert_eq!(changed(map), ticked, "set 0's {map:?} is in the document exactly when its row is ticked");
}
}
#[test]
fn a_failed_maps_arrow_opens_its_settings() {
let mut harness = harness();
// Three rows fit the docked log without scrolling
harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Id]);
bake_with_set_1_failing(&mut harness, &[BakedMap::Id, BakedMap::Position]);
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
assert_eq!(harness.state().session.ts(), 0);
assert!(harness.query_by_label("Normalization Scale").is_none(), "Position's settings are not shown yet");
let set_name = harness.state().session.doc.project.texture_sets[1].name.clone();
harness.get_by_label(&format!("Open the {set_name} Position settings")).click();
harness.run_steps(3);
assert_eq!(harness.state().session.ts(), 1, "the failed map's texture set is the active one");
assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "the arrow fronts Mesh Map Settings");
harness.get_by_label("Normalization Scale");
assert!(
harness.query_by_label(&format!("Open the {} ID settings", harness.state().session.doc.project.texture_sets[0].name)).is_none(),
"a baked map has no arrow"
);
}
/// Put a finished bake of set 0's ID and Position maps in the log, the Position map ending as `position`
fn log_a_bake(harness: &mut Harness<'static, TextureCraftApp>, position: BakeMapState) -> String {
let set_name = harness.state().session.doc.project.texture_sets[0].name.clone();
let row = |map, state| BakeLogMap { texture_set: 0, set_name: set_name.clone(), map, state };
harness.state_mut().session.bake_log.maps = vec![row(BakedMap::Id, BakeMapState::Baked), row(BakedMap::Position, position)];
harness.run_steps(3);
set_name
}
#[test]
fn the_issues_filter_keeps_only_the_maps_with_a_problem() {
let mut harness = harness();
let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into()));
harness.get_by_label(&format!("{set_name} ID, Baked"));
harness.get_by_label("1, Show only rows with an issue").click();
harness.run_steps(3);
assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out");
harness.get_by_label(&format!("{set_name} Position, Not baked"));
assert!(harness.query_by_label("Turn off the issues filter to see every row.").is_none(), "an issue left: no empty text");
}
#[test]
fn the_issues_filter_says_so_when_nothing_went_wrong() {
let mut harness = harness();
let set_name = log_a_bake(&mut harness, BakeMapState::Baked);
harness.get_by_label("Show only rows with an issue").click();
harness.run_steps(3);
assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none());
harness.get_by_label("Every map so far baked without a problem.");
harness.get_by_label("Turn off the issues filter to see every row.");
harness.get_by_label("Show only rows with an issue").click();
harness.run_steps(3);
harness.get_by_label(&format!("{set_name} ID, Baked"));
assert!(harness.query_by_label("Every map so far baked without a problem.").is_none(), "off again: every row is back");
}
#[test]
fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() {
let mut harness = harness();
harness.state_mut().session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
harness.state_mut().start_bake(vec![0]);
run_to_the_end(&mut harness);
harness.get_by_label("High Poly Parameters").click();
harness.run_steps(3);
let set_name = harness.state().session.doc.project.texture_sets[0].name.clone();
harness.get_by_label("ball_high.obj, Loaded");
let set_row = format!("{set_name}, High poly files");
assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(true));
harness.get_by_label(&set_row).click();
harness.run_steps(3);
assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files");
assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(false), "the row says it is folded");
}
#[test]
fn the_high_poly_tab_counts_and_keeps_its_own_issues() {
let mut harness = harness();
let set_name = log_a_bake(&mut harness, BakeMapState::Baked);
let row = |file: &str, state| BakeLogHigh { texture_set: 0, set_name: set_name.clone(), file: file.into(), state };
harness.state_mut().session.bake_log.highs = vec![row("ball_high.obj", BakeHighState::Loaded), row("bolt_high.obj", BakeHighState::Canceled)];
harness.get_by_label("High Poly Parameters").click();
harness.run_steps(3);
harness.get_by_label("1, Show only rows with an issue").click();
harness.run_steps(3);
assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out");
harness.get_by_label("bolt_high.obj, Canceled");
}
#[test]
fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partner() {
let mut harness = harness();
log_a_bake(&mut harness, BakeMapState::Baked);
let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) };
harness.state_mut().session.bake_log.matching = Some(BakeLogMatching {
low_suffix: "_low".into(),
high_suffix: "_high".into(),
pairs: vec![pair(Some("Barrel_low"), Some("Barrel_high")), pair(Some("Strap_low"), None)],
});
harness.get_by_label("Matching by Name").click();
harness.run_steps(3);
harness.get_by_label("Barrel_low, Barrel_high");
harness.get_by_label("1, Show only rows with an issue").click();
harness.run_steps(3);
assert!(harness.query_by_label("Barrel_low, Barrel_high").is_none(), "a pair is filtered out");
harness.get_by_label("Strap_low, No match");
}
#[test]
fn the_matching_tab_says_when_no_set_matched_by_name() {
let mut harness = harness();
harness.get_by_label("Matching by Name").click();
harness.run_steps(3);
assert!(harness.query_by_label("Set Match to By Mesh Name to pair parts by name.").is_none(), "nothing baked yet: nothing to say");
log_a_bake(&mut harness, BakeMapState::Baked);
harness.get_by_label("Set Match to By Mesh Name to pair parts by name.");
}
#[test]
fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() {
// A window this narrow leaves the docked log less room than its three tabs and the filter take together
const NARROW_WINDOW_WIDTH: f32 = 520.0;
let mut harness = Harness::builder()
.with_size(egui::vec2(NARROW_WINDOW_WIDTH, 1000.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, texturecraft_engine::sample_session(256, 64).unwrap()));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
let filter = harness.get_by_label("Show only rows with an issue").rect();
let strip_start = harness.get_by_role_and_label(Role::Tab, "Baking Process").rect().left();
let last_tab = harness.get_by_role_and_label(Role::Tab, "Matching by Name").rect();
assert!(last_tab.right() > filter.left(), "unscrolled, the tabs {last_tab:?} run past the filter {filter:?}, so they must scroll");
// Frames for the strip's scroll to the focused tab to finish
const SCROLL_FRAMES: usize = 30;
for tab in ["Baking Process", "High Poly Parameters", "Matching by Name"] {
harness.get_by_role_and_label(Role::Tab, tab).focus();
harness.run_steps(SCROLL_FRAMES);
let rect = harness.get_by_role_and_label(Role::Tab, tab).rect();
assert!(rect.right() <= filter.left(), "the focused {tab} tab {rect:?} ends left of the filter {filter:?}");
assert!(rect.left() >= strip_start, "the focused {tab} tab {rect:?} starts inside the log, where the first tab starts unscrolled");
}
}
#[test]
fn a_matching_name_cut_short_shows_in_full_on_hover() {
const LONG_NAME: &str = "Left_shoulder_strap_buckle_with_its_rivets_and_its_stitching_low";
// Frames past the tooltip delay
const TOOLTIP_FRAMES: usize = 60;
let mut harness = harness();
log_a_bake(&mut harness, BakeMapState::Baked);
let pair = NamePair { low: Some(LONG_NAME.into()), high: Some("Strap_high".into()) };
harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { low_suffix: "_low".into(), high_suffix: "_high".into(), pairs: vec![pair] });
harness.get_by_label("Matching by Name").click();
harness.run_steps(3);
let label = format!("{LONG_NAME}, Strap_high");
let row = harness.get_by_label(&label).rect();
assert_eq!(harness.query_all_by_label(&label).count(), 1, "no tooltip before hovering");
harness.hover_at(row.center());
harness.run_steps(TOOLTIP_FRAMES);
assert_eq!(harness.query_all_by_label(&label).count(), 2, "the tooltip carries both names in full");
}
@@ -0,0 +1,84 @@
//! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::core::{BakedMap, LayerId};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, ViewMode, execute};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
/// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask
fn harness() -> Harness<'static, TextureCraftApp> {
harness_with("curvature")
}
/// A plane whose bake makes only the position map, with a `generator` selected in a fill layer's mask
fn harness_with(generator: &str) -> Harness<'static, TextureCraftApp> {
let mesh = primitives::builtin("plane").unwrap();
let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap();
execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap();
let layer = execute(&mut session, "layer.add.fill", &json!({ "color": [0.8, 0.3, 0.1] })).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({})).unwrap();
execute(&mut session, "effect.add.generator", &json!({ "generator": generator })).unwrap();
session.view = ViewMode::Mask(LayerId(layer));
session.update();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 1200.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.dock.close(Panel::Layers);
harness.state_mut().ui.dock.close(Panel::TextureSetSettings);
harness.state_mut().ui.dock.focus(Panel::Properties);
harness.run_steps(6);
harness
}
/// Run frames until the bake ends, then a few more for its result to show
fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) {
super::step_until(harness, "the end of the bake", |app| app.bake.is_none());
harness.run_steps(super::SETTLE_FRAMES);
}
#[test]
fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() {
let mut harness = harness();
let description = harness.get_by_label("Curvature map not baked").accesskit_node().description();
assert!(description.is_some_and(|reasons| !reasons.is_empty()), "why the note shows is read without hovering");
execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap();
harness.run_steps(3);
assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note");
assert!(harness.query_by_label("Curvature map out of date").is_none(), "baked: no note");
execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap();
harness.run_steps(3);
harness.get_by_label("Curvature map out of date");
}
#[test]
fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() {
let mut harness = harness();
assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature));
harness.get_by_label("Bake").click();
harness.run_steps(1);
assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature), "turned on");
assert!(harness.state().bake.is_some(), "a background bake started");
run_to_the_end(&mut harness);
assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature)));
assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note");
}
#[test]
fn rust_runoff_notes_the_occlusion_it_reads_though_no_input_replaces_it() {
let harness = harness_with("Dripping Rust");
harness.get_by_label("Ambient Occlusion map not baked");
}
+21
View File
@@ -3,6 +3,7 @@
mod alpha_parameters;
mod anchor_point;
mod auto_rebake;
mod bake_job_mesh;
mod bake_live_preview;
mod bake_map_rows;
@@ -10,6 +11,7 @@ mod bake_mode;
mod bake_presets;
mod bake_reset_menus;
mod bake_sync;
mod baking_log;
mod brush_drag;
mod brush_section_reset;
mod camera_views;
@@ -43,6 +45,7 @@ mod fill_symmetry_rows;
mod filter_picker;
mod folder_properties;
mod frame_selection;
mod generator_bake_note;
mod generator_panel;
mod generator_picker;
mod help_menu_664;
@@ -194,6 +197,24 @@ fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraf
assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list");
}
/// Maximum frames to wait for a test condition
const STEP_UNTIL_FRAMES: usize = 4000;
/// Time to yield to background workers between frames
const STEP_UNTIL_PAUSE: std::time::Duration = std::time::Duration::from_millis(2);
/// Step frames until `done` holds, up to a generous limit
fn step_until(harness: &mut Harness<'_, TextureCraftApp>, expected_event: &str, done: impl Fn(&TextureCraftApp) -> bool) {
for _ in 0..STEP_UNTIL_FRAMES {
harness.run_steps(1);
if done(harness.state()) {
return;
}
std::thread::sleep(STEP_UNTIL_PAUSE);
}
panic!("{expected_event} did not happen");
}
/// Presses and releases the primary button at `at` without moving, as a pointer click does
fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) {
harness.hover_at(at);
+39 -3
View File
@@ -242,7 +242,7 @@ keeps its state in a throwaway file.
| `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before |
| `ui.reset` | | resets the panels, view settings and interface language without asking for confirmation. Other preferences and shortcuts stay |
| `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running |
| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back |
| `ui.bake.cancel` | | Stops the running bake and restores the previous view mode. Finished sets stay applied. Eligible maps from the current set are kept in one undo step (see *Live bake preview*) |
| `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `BakeMaps`, `BakeSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` |
| `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) |
| `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame |
@@ -285,8 +285,9 @@ bake of its own, so with a high poly the transfer rays are cast once per map; th
same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview.
The streamed maps are held by the session, not the document: nothing enters the undo history
until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking
as it was, while sets that finished before the cancel stay applied. When
until a texture set's bake is applied (one undo step); a cancelled bake applies the maps the set it was
baking had finished in one undo step. A changed output size, a replaced mesh, or a worker failure
discards the current set's partial results. Sets that finished before the cancel stay applied. When
the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back.
Bake setup overlays are hidden during the preview so they cannot cover the maps; their visibility
settings take effect again when the preview ends.
@@ -309,6 +310,41 @@ also `session.inspect`'s `bakePreview`:
`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`)
until `baking` is `null`.
`bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake).
A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`.
`highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`,
`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`. `matching` lists each low poly
part with the high poly part it bakes from, then the high poly parts no set paired with; a `null` side is a part
with no partner. It is `null` when no set of the bake matches by mesh name:
```json
{"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"},
{"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "texture set Head has no UV tiles selected for baking"}],
"highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}],
"matching": {"lowSuffix": "_low", "highSuffix": "_high",
"pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}}
```
Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as
`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`,
`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's
own). The low-poly inputs include its tangent frame. For Opacity and material-color ID maps that
read the low poly's material, a change to the packed mesh file also counts as `lowPoly`.
Imported maps, and maps saved before this record existed, never show:
`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`.
`bake.autoRebake` `{ts?, map: id | null}` turns on Auto-rebake for one mesh map of a texture set
(the active one by default), replacing its previous one, or turns it off with `null`; it is saved
with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web
app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the
background, alone (with every checked map when the output size changed), once what it is baked
from has stopped changing for half a second; a change during that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that
bakes from a high poly makes the app bake its auto-rebake map again only inside the stroke's UV
box and pads the result. Curvature, height, thickness, UV-tiled sets, and resized maps bake
whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its
`normal` map when the set has none, in the stroke's undo step. The headless CLI does not rebake by
itself: run `bake.run` there.
A minimal client (Python, for illustration):
```python
+11
View File
@@ -173,6 +173,17 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
channel with the summary and the message for each failed set.
- **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is
finished; the bake bar follows the newest map, pins a finished one or shows the material.
- **Baking Log** at the bottom of Bake mode: the latest bake map by map (Baking Process), the high
poly files each set loads (High Poly Parameters) and how parts paired by name (Matching by Name),
with an issues filter; a failed or canceled map opens its settings. `bake.log` returns the same rows.
- **Out-of-date mesh maps:** each bake records what every map was baked from; a map whose mesh, high
poly, cage or settings changed since shows a clock in Mesh Map Bakers (`outOfDate` in
`project.inspect`), and a generator reading a missing or out-of-date map shows one line with a
Bake button.
- **Auto-rebake:** one map per texture set (`bake.autoRebake`, a row icon in Mesh Map Bakers) is
baked again in the background in Bake mode once what it is baked from stops changing. On an
eligible map, a skew or cage stroke rebakes the stroke's box and pads the result. The first skew
stroke turns it on for the Normal map if the set has no Auto-rebake map.
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz,
anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in