Auto: Integrate main and fix bake freshness and cancellation

Preserve Resources Updater links and bake provenance when replacing or clearing mesh maps. Keep unrelated maps on unchanged UV atlases, discard partial results from failed workers, and reject overflowing texture-set indices.

Track vertex colors, part assignments, tangent frames and the packed file used by material-color bakes. Share the common source fingerprint across each task's selected maps. Add reimport, cancellation and atlas regressions, update the control protocol, and clarify the affected code.
This commit is contained in:
chasse20 committed 2026-11-27 21:00:57 +00:00
commit e274358a56
75 files changed
+2726 -219

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
name: Notify Services on Release Change
on:
release:
types:
- published
- unpublished
- created
- edited
- deleted
- prereleased
- released
permissions: {}
jobs:
notify:
uses: storytold/craft-common-actions/.github/workflows/notify-services.yml@main
secrets:
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
+1
View File
@@ -89,6 +89,7 @@ impl Headless {
if steps.len() > MAX_BATCH_STEPS {
return Err(bad(format!("at most {MAX_BATCH_STEPS} steps per batch")));
}
Ok(self.batch(steps))
}
"project.open" => self.open(required(p, "path")?),
+11
View File
@@ -132,6 +132,13 @@ const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"];
/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
// The Resources Updater reads the files a project names, which may lie outside the read root
if matches!(id, "resource.status" | "resource.update" | "resource.relink") {
return Err(bad(format!(
"`{id}` reads the image files the project names on this machine, so it is disabled for automation; re-import changed files with resource_import"
)));
}
let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path));
// `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path
@@ -245,6 +252,10 @@ mod tests {
assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err());
assert!(authorize_command("file.reimportMesh", &json!({})).is_ok());
assert!(authorize_command("file.close", &json!({})).is_ok());
for id in ["resource.status", "resource.update", "resource.relink"] {
let error = authorize_command(id, &json!({})).unwrap_err().to_string();
assert!(error.contains("reads the image files"), "{id}: {error}");
}
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
}
+2
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, 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, &[], None).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());
}
}
+11 -1
View File
@@ -7,6 +7,9 @@ use serde::{Deserialize, Serialize};
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)
@@ -20,8 +23,15 @@ pub struct BakeSource {
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, BakeChange::LowPoly),
(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),
@@ -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,
+4
View File
@@ -39,6 +39,7 @@ pub mod image_input;
pub mod layer;
pub mod lighting_output;
pub mod mask_outline;
pub mod mesh_map_slot;
pub mod mirror;
pub mod mirror_corner;
pub mod mirror_mode;
@@ -51,6 +52,7 @@ pub mod project;
pub mod projector;
pub mod ramp_curve;
pub mod randomized_seed;
pub mod resource_source;
mod saved_decal;
mod saved_projection;
pub mod selection_background;
@@ -122,6 +124,7 @@ pub use layer::{
};
pub use lighting_output::LightingOutput;
pub use mask_outline::MaskOutline;
pub use mesh_map_slot::MeshMapSlot;
pub use mirror::Mirror;
pub use mirror_corner::MirrorCorner;
pub use mirror_mode::MirrorMode;
@@ -136,6 +139,7 @@ pub use project::{
pub use projector::Projector;
pub use ramp_curve::RampCurve;
pub use randomized_seed::RandomizedSeed;
pub use resource_source::ResourceSource;
pub use selection_background::SelectionBackground;
pub use shape_crop::ShapeCrop;
pub use slope_blending::SlopeBlending;
+15
View File
@@ -0,0 +1,15 @@
//! The mesh map an imported image file was resampled into
use serde::{Deserialize, Serialize};
use crate::BakedMap;
/// A mesh map of a texture set, and the UV tile one image of it covers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MeshMapSlot {
/// Index of the texture set.
pub texture_set: usize,
pub map: BakedMap,
/// The UV tile the image covers (1001 on a set without UV tiles).
pub tile: u32,
}
+5
View File
@@ -500,6 +500,10 @@ pub struct Project {
/// The project's colour swatches (linear RGB), in the order they were added; projects without any save none
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub swatches: Vec<[f32; 3]>,
/// The files image resources were imported from, by resource name (the Resources Updater
/// reads them again). Resources made in the app or imported without a file path have none.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub resource_sources: BTreeMap<String, crate::ResourceSource>,
}
impl Project {
@@ -518,6 +522,7 @@ impl Project {
display: DisplaySettings::default(),
cameras: Vec::new(),
swatches: Vec::new(),
resource_sources: BTreeMap::new(),
}
}
+21
View File
@@ -0,0 +1,21 @@
//! Where an image resource was imported from, so the Resources Updater can read it again
use serde::{Deserialize, Serialize};
/// The file an image resource was read from and its modification time then.
///
/// The resource's stored bytes are the file's bytes at that time, so a file whose size or
/// contents differ from them has changed on disk.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceSource {
/// Path of the file on the machine that imported it.
pub path: String,
/// The file's modification time when it was read, in milliseconds since the Unix epoch
/// (0 when unknown). An unchanged time and size skip reading the file again.
#[serde(default)]
pub modified_ms: u64,
/// The mesh map the file was imported as (`textureSet.meshMap.import`): an update resamples it
/// again while the map still holds what this file gave it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mesh_map: Option<crate::MeshMapSlot>,
}
+10 -3
View File
@@ -22,7 +22,10 @@ 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").map(|index| index as usize).filter(|index| *index < session.set_count()).ok_or_else(|| bad(COMMAND, "invalid `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,
@@ -36,6 +39,7 @@ fn set_auto_rebake(session: &mut Session, params: &Value) -> Result<Value> {
Ok(())
})?;
}
Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) }))
}
@@ -52,10 +56,13 @@ impl Session {
.collect()
}
/// The maps an auto-rebake of `map` bakes: that map alone, or with every checked map once the output size changed (storing a new size drops the old maps)
/// 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 (width, height) = set.bake.common.output_size();
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 {
+3
View File
@@ -77,6 +77,7 @@ impl BakeLog {
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());
@@ -156,9 +157,11 @@ impl Session {
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(),
+50 -15
View File
@@ -2,20 +2,25 @@
use std::collections::BTreeMap;
use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, fingerprint_words};
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 map_settings = self.doc.project.texture_set(texture_set)?.map_settings_fingerprint(map);
Ok(BakeSource { map_settings, ..self.set_bake_source(texture_set)? })
let set = self.doc.project.texture_set(texture_set)?;
Ok(self.map_bake_source(set, map, self.set_bake_source(set)))
}
/// What a bake of any map of texture set `texture_set` would read now, without the map's own settings (0)
fn set_bake_source(&self, texture_set: usize) -> Result<BakeSource> {
let set = self.doc.project.texture_set(texture_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)),
@@ -24,12 +29,28 @@ impl Session {
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);
Ok(BakeSource { low_poly: self.low_poly_fingerprint(), high_poly, cage, settings: set.bake_settings_fingerprint(), map_settings: 0 })
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()
@@ -38,22 +59,35 @@ impl Session {
/// 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();
// The fingerprints every map of the set shares are taken once
let Some(shared) = records.peek().and_then(|_| self.set_bake_source(texture_set).ok()) else { return BTreeMap::new() };
let changes = records.map(|(map, record)| (*map, record.changes(&BakeSource { map_settings: set.map_settings_fingerprint(*map), ..shared })));
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 own geometry (computed once per loaded mesh)
/// 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.uvs.iter().flat_map(|uv| uv.to_array()));
let words = floats.map(|float| u64::from(float.to_bits())).chain(source.indices.iter().map(|index| u64::from(*index)));
fingerprint_words(words)
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))
})
}
@@ -75,6 +109,7 @@ impl Session {
if let Some((_, painted_stroke)) = recorded {
self.forget_painted_region(texture_set, stored, painted_stroke);
}
Ok(())
}
}
+4 -1
View File
@@ -125,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)]
+2
View File
@@ -17,6 +17,7 @@ impl Session {
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))
});
@@ -31,6 +32,7 @@ impl Session {
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()));
+6 -4
View File
@@ -160,8 +160,7 @@ impl Session {
}
// 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
@@ -189,7 +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 = settings.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::<Result<_>>()?;
let sources = self.task_bake_sources(set, settings.maps.enabled());
Ok(BakeTask {
low_base_color,
ts: texture_set,
@@ -301,7 +301,9 @@ impl Session {
) -> Result<()> {
let stored: Vec<BakedMap> = maps.keys().copied().collect();
let entry = self.doc.baked.entry(texture_set).or_default();
if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) {
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));
if size_changed {
entry.maps.clear();
}
+18 -12
View File
@@ -61,11 +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))
}
@@ -78,27 +80,29 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
})?;
session.note_bake_paint(texture_set, None);
}
Ok(super::meshes_json(session))
}
/// Most UV points one `bake.paint` call takes
const MAX_POINTS: usize = 100_000;
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: u64 = 1024;
const PAINT_SIZES: std::ops::RangeInclusive<u64> = 16..=4096;
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> {
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", format!("points must contain 1 to {MAX_POINTS} 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| {
@@ -115,11 +119,11 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
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 => DEFAULT_PAINT_SIZE,
None => DEFAULT_PAINT_SIZE_TEXELS,
Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?,
};
if !PAINT_SIZES.contains(&size) {
return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZES.start(), PAINT_SIZES.end())));
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 {
@@ -146,12 +150,14 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
})?;
// The dabs reach `radius` from each point, and the paint map's bilinear sampling one of its texels further
// 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 low = points.iter().fold(Vec2::INFINITY, |low, point| low.min(*point)) - reach;
let high = points.iter().fold(Vec2::NEG_INFINITY, |high, point| high.max(*point)) + reach;
session.note_bake_paint(texture_set, Some((low, high)));
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))
}
+1
View File
@@ -61,6 +61,7 @@ impl Session {
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));
+8 -5
View File
@@ -20,21 +20,24 @@ pub fn specs() -> Vec<CommandSpec> {
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 highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).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": highs, "matching": matching }))
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 what it is under `key`
fn entry(state: &impl serde::Serialize, texture_set: usize, set_name: &str, key: &str, what: Value) -> Result<Value> {
/// 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(), what);
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 keeps the maps the current set finished; 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;
+3 -1
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",
@@ -46,6 +46,7 @@ impl CommandSpec {
"bake.log",
"camera.set",
"textureSet.settings",
"resource.status",
];
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
@@ -146,6 +147,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::file_cmds::specs());
v.extend(crate::preset_cmds::specs());
v.extend(crate::resource_cmds::specs());
v.extend(crate::resource_update_cmds::specs());
v.extend(crate::material_lib::specs());
v.extend(crate::link_cmds::specs());
v.extend(crate::smart_masks::specs());
+25 -10
View File
@@ -157,16 +157,18 @@ impl Session {
/// [`Session::mesh_obj_with_mtl`], optionally replacing normals on the exported copy only.
pub fn mesh_obj_with_mtl_and_normals(&mut self, stem: &str, recompute_normals: bool) -> Result<(Vec<u8>, texturecraft_formats::NamedFiles)> {
// shortcut: UV-tiled sets get no maps (the OBJ keeps the mesh's UDIM UVs and an MTL map is
// one image); their tiles export through Export textures with `$udim` names.
// OBJ keeps UDIM UVs, while each MTL map can hold only one image
// Export tiled textures separately with `$udim` names
let mut mesh = self.source_mesh();
if recompute_normals {
mesh.compute_smooth_normals();
}
// A mesh without materials has one implicit material (and texture set).
// A mesh without materials has one implicit material and texture set
if mesh.materials.is_empty() {
mesh.materials.push("default".into());
}
let files = self.material_files(texturecraft_formats::usd_export_options(), false, mesh.materials.len())?;
texturecraft_formats::obj_with_mtl(&mesh, &self.doc.project.name, stem, &files).map_err(fe)
}
@@ -182,10 +184,11 @@ impl Session {
pub fn mesh_glb_bytes_with_normals(&mut self, recompute_normals: bool) -> Result<Vec<u8>> {
let files = self.material_files(texturecraft_formats::glb_export_options(), true, self.mesh.materials.len())?;
let textures: Vec<_> = files.into_iter().map(texturecraft_formats::GlbTextures::from_files).collect();
let mut mesh = self.mesh.as_ref().clone();
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
if recompute_normals {
mesh.compute_smooth_normals();
mesh.to_mut().compute_smooth_normals();
}
texturecraft_formats::glb_bytes(&mesh, &self.doc.project.name, &textures).map_err(fe)
}
@@ -198,10 +201,11 @@ impl Session {
/// [`Session::mesh_usd`], optionally replacing normals on the exported copy only.
pub fn mesh_usd_with_normals(&mut self, format: texturecraft_formats::UsdFormat, recompute_normals: bool) -> Result<texturecraft_formats::UsdExport> {
let files = self.material_files(texturecraft_formats::usd_export_options(), true, self.mesh.materials.len())?;
let mut mesh = self.mesh.as_ref().clone();
let mut mesh = Cow::Borrowed(self.mesh.as_ref());
if recompute_normals {
mesh.compute_smooth_normals();
mesh.to_mut().compute_smooth_normals();
}
texturecraft_formats::usd_bytes(&mesh, &self.doc.project.name, &files, format).map_err(fe)
}
@@ -741,8 +745,10 @@ impl Session {
next.modified = true;
next.project_id = self.project_id;
// The painted boxes moved with the document, and a bake tells a newer stroke by this count
// 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
@@ -751,6 +757,7 @@ impl Session {
}
self.switch_to(next);
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
}
}
@@ -1257,6 +1264,7 @@ impl Session {
None => "obj".into(),
};
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
let (bytes, textures) = match (ext.as_str(), texturecraft_formats::UsdFormat::from_ext(&ext)) {
("glb", _) => (self.mesh_glb_bytes_with_normals(recompute_normals)?, Vec::new()),
(_, Some(format)) => {
@@ -1265,6 +1273,7 @@ impl Session {
}
_ => self.mesh_obj_with_mtl_and_normals(std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("mesh"), recompute_normals)?,
};
Ok(MeshExport { path, bytes, textures })
}
}
@@ -1466,11 +1475,13 @@ f 1/1 2/2 3/3
let dir = std::env::temp_dir().join(format!("tc_export_recompute_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
for (format, suffix) in [("obj", "obj"), ("glb", "glb"), ("usda", "usda")] {
let path = dir.join(format!("cube-{format}.{suffix}"));
let reply = crate::execute(&mut s, "file.exportMesh", &json!({"path": path, "recomputeNormals": true})).unwrap();
let bytes = std::fs::read(reply["path"].as_str().unwrap()).unwrap();
let back = texturecraft_formats::import_mesh_bytes(&format!("cube.{suffix}"), &bytes).unwrap().mesh;
assert_eq!(back.normals.len(), expected.normals.len(), "{format}: one normal per exported vertex");
for (position, actual) in back.positions.iter().zip(&back.normals) {
let wanted = expected
@@ -1482,8 +1493,10 @@ f 1/1 2/2 3/3
assert!((*actual - wanted).length() < 1e-4, "{format}: actual {actual:?}, wanted {wanted:?}");
}
}
assert!(s.source.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the source project is unchanged");
assert!(s.mesh.normals.iter().all(|n| *n == texturecraft_geom::glam::Vec3::Y), "the render project is unchanged");
let stored_path = dir.join("stored.obj");
let stored = crate::execute(&mut s, "file.exportMesh", &json!({"path": stored_path})).unwrap();
let stored = std::fs::read(stored["path"].as_str().unwrap()).unwrap();
@@ -1496,7 +1509,7 @@ f 1/1 2/2 3/3
fn recomputed_normals_weld_uv_seams_in_exported_mesh() {
use texturecraft_geom::glam::Vec3;
// Two triangles meet along 0--2, but their UV island split duplicates that edge as 3--4.
// The UV seam duplicates edge 0–2 at vertices 3 and 4
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ZERO, Vec3::Y, Vec3::new(-1.0, 0.0, 1.0)];
let mesh = Mesh::from_parts(
positions,
@@ -1507,8 +1520,10 @@ f 1/1 2/2 3/3
)
.unwrap();
let mut s = Session::new_project("seam", mesh, "builtin:seam", None, 128).unwrap();
let bytes = s.mesh_glb_bytes_with_normals(true).unwrap();
let back = texturecraft_formats::import_mesh_bytes("seam.glb", &bytes).unwrap().mesh;
for point in [Vec3::ZERO, Vec3::Y] {
let normals: Vec<_> = back.positions.iter().zip(&back.normals).filter_map(|(position, normal)| (*position == point).then_some(*normal)).collect();
assert!(normals.len() >= 2, "{point:?}: the UV seam must still have two exported vertices");
@@ -1654,7 +1669,7 @@ 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();
+2
View File
@@ -264,8 +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,
+14
View File
@@ -52,6 +52,7 @@ pub mod material_lib;
mod material_preview_pixel;
pub mod materials;
pub mod materialx_cmds;
mod mesh_map_sampler;
pub mod meshmap_cmds;
mod meshmap_file_name;
pub mod meshmap_import_cmds;
@@ -74,7 +75,16 @@ pub mod preview;
mod procedural_params;
pub mod project_cmds;
pub mod quick_mask;
// Reloading resource files reads paths on native targets only
#[cfg(not(target_arch = "wasm32"))]
mod reloaded_file;
// Remembered file comparisons exist on native targets only
#[cfg(not(target_arch = "wasm32"))]
mod resource_check;
pub mod resource_cmds;
pub mod resource_state;
pub mod resource_status;
pub mod resource_update_cmds;
pub mod session;
mod session_log;
pub mod set_cmds;
@@ -103,6 +113,8 @@ pub use fill_mode::FillMode;
pub use log::{LogEntry, LogLevel, SessionLog};
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use resource_state::ResourceState;
pub use resource_status::ResourceStatus;
pub use session::{
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState,
ViewMode, history_label, stroke_template,
@@ -128,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),
}
+1
View File
@@ -623,6 +623,7 @@ impl Session {
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
session.doc.resources.remove(name);
session.doc.project.resource_sources.remove(name);
}
Ok(names)
+1
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(),
+34 -14
View File
@@ -34,17 +34,25 @@ pub fn specs() -> Vec<CommandSpec> {
/// Loads an image file named in the document (relative to it): its bytes, or why not.
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
type LocatedImage = (Vec<u8>, Option<texturecraft_core::ResourceSource>);
type LocatedLoader<'a> = &'a dyn Fn(&str) -> std::result::Result<LocatedImage, String>;
impl Session {
/// Add `material` as a fill layer on the active texture set, loading its images with `load`.
/// Returns the reply of `file.importMaterialX`.
pub fn import_material(&mut self, material: Material, name: Option<&str>, load: Loader) -> Result<Value> {
self.import_material_with_sources(material, name, &|file| load(file).map(|bytes| (bytes, None)))
}
fn import_material_with_sources(&mut self, material: Material, name: Option<&str>, load: LocatedLoader) -> Result<Value> {
let mut warnings = material.warnings.clone();
let ts = self.ts();
let available = self.doc.project.texture_set(ts).map(|t| t.channel_list()).unwrap_or_default();
let mut fill = Fill { projection: Projection::Uv { scale: material.uv_tiling, rotation: 0.0, offset: [0.0, 0.0] }, ..Fill::default() };
// Resources to add (name and encoded bytes), and their decoded images for the session.
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
let mut decoded = Vec::new();
let mut sources = Vec::new();
let mut names: BTreeMap<String, String> = BTreeMap::new();
let mut channels: Vec<Channel> = Vec::new();
for (channel, value) in &material.channels {
@@ -52,15 +60,17 @@ impl Session {
warnings.push(format!("{} was skipped: this texture set has no such channel", channel.id()));
continue;
}
let source = match value {
Mtlx::Constant(c) => Source::Uniform(*c),
Mtlx::Image(file) => {
let resource = match names.get(file) {
Some(n) => n.clone(),
None => {
let loaded =
load(file).and_then(|bytes| texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image)).map_err(|e| e.to_string()));
let (bytes, image) = match loaded {
let loaded = load(file).and_then(|(bytes, source)| {
texturecraft_formats::decode_image(&bytes).map(|image| (bytes, image, source)).map_err(|e| e.to_string())
});
let (bytes, image, source) = match loaded {
Ok(v) => v,
Err(e) => {
warnings.push(format!("{} was skipped: {file}: {e}", channel.id()));
@@ -69,11 +79,11 @@ impl Session {
};
let leaf = file.rsplit(['/', '\\']).next().unwrap_or(file);
let base = texturecraft_formats::sanitize_resource_name(leaf);
let (mut unique, mut n) = (base.clone(), 2);
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
unique = format!("{n}_{base}");
n += 1;
}
let unique = crate::resource_cmds::unique_resource_name(base, |name| {
self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name)
});
sources.extend(source.map(|source| (unique.clone(), source)));
added.push((unique.clone(), Arc::new(bytes)));
decoded.push((unique.clone(), crate::resource_cmds::decoded(image)));
names.insert(file.clone(), unique.clone());
@@ -90,12 +100,14 @@ impl Session {
let why = if warnings.is_empty() { String::new() } else { format!(" ({})", warnings.join("; ")) };
return Err(EngineError::Other(format!("file.importMaterialX: nothing to import from {:?}{why}", material.name)));
}
let layer_name = name.map(str::to_string).unwrap_or_else(|| self.doc.project.next_layer_name(ts, &material.name));
let resource_names: Vec<String> = added.iter().map(|(n, _)| n.clone()).collect();
let id = self.edit("Import MaterialX material", |s| {
for (n, bytes) in &added {
s.doc.resources.insert(n.clone(), bytes.clone());
}
s.doc.project.resource_sources.extend(sources);
let id = s.doc.project.alloc_id();
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &channels))
})?;
@@ -119,34 +131,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
if !meta.is_file() || meta.len() > texturecraft_formats::materialx_read::MAX_BYTES as u64 {
return Err(bad(cmd, format!("{path} is not a MaterialX file of a readable size")));
}
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
let material = texturecraft_formats::materialx_read::read_materialx(&bytes, strp(p, "material")).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let folder = Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
let dir = folder.canonicalize().map_err(|e| bad(cmd, format!("cannot read the folder of {path}: {e}")))?;
let load = |file: &str| -> std::result::Result<Vec<u8>, String> {
// `<UDIM>` stands for a tile number; the first tile is read.
let load = |file: &str| -> std::result::Result<LocatedImage, String> {
// Import the first tile of a UDIM image
let file = file.replace("<UDIM>", "1001");
let rel = Path::new(&file);
let outside = "the file is outside the material's folder";
if rel.is_absolute() || rel.components().any(|c| matches!(c, Component::ParentDir | Component::Prefix(_) | Component::RootDir)) {
return Err(outside.into());
}
let full = dir.join(rel).canonicalize().map_err(|e| e.to_string())?;
if !full.starts_with(&dir) {
return Err(outside.into());
}
let meta = std::fs::metadata(&full).map_err(|e| e.to_string())?;
// A pipe or device in the folder would block the read (a pipe reports no length).
// Avoid blocking on pipes and devices
if !meta.is_file() {
return Err("it is not a regular file".into());
}
let len = meta.len();
if len > crate::resource_cmds::MAX_BYTES as u64 {
return Err(format!("the file is over {} MB", crate::resource_cmds::MAX_BYTES >> 20));
}
std::fs::read(&full).map_err(|e| e.to_string())
let source = full.to_str().map(crate::resource_update_cmds::file_source);
let bytes = std::fs::read(&full).map_err(|e| e.to_string())?;
Ok((bytes, source))
};
s.import_material(material, strp(p, "name"), &load)
s.import_material_with_sources(material, strp(p, "name"), &load)
}
#[cfg(target_arch = "wasm32")]
+79
View File
@@ -0,0 +1,79 @@
//! Sample image resources into a mesh-map atlas or compare them with an existing atlas.
use std::collections::BTreeMap;
use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_compose::ImageRes;
use texturecraft_core::{BakedMap, NormalFormat, TileGrid, udim_at};
use crate::commands::bad;
use crate::{Result, Session};
pub(crate) struct MeshMapSampler<'a> {
width: u32,
height: u32,
components: usize,
flip_green: bool,
grid: Option<TileGrid>,
first: &'a ImageRes,
images: &'a BTreeMap<u32, Arc<ImageRes>>,
}
impl<'a> MeshMapSampler<'a> {
pub(crate) fn new(session: &Session, cmd: &str, texture_set: usize, map: BakedMap, images: &'a BTreeMap<u32, Arc<ImageRes>>) -> Result<Self> {
let set = session.doc.project.texture_set(texture_set)?;
let grid = set.tile_grid();
if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
return Err(bad(cmd, format!("no image for UV tile {tile}")));
}
let (width, height) = crate::meshmap_cmds::image_map_size(session, cmd, texture_set)?;
let first = images.values().next().ok_or_else(|| bad(cmd, "no image to use"))?;
// Both tangent-space normal maps follow the project's green-channel convention
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX;
Ok(Self { width, height, components: map.components(), flip_green, grid, first, images })
}
fn row(&self, y: usize) -> impl Iterator<Item = [f32; 4]> + '_ {
let v = (y as f32 + 0.5) / self.height as f32;
(0..self.width).map(move |x| {
let u = (x as f32 + 0.5) / self.width as f32;
let mut pixel = match self.grid {
None => self.first.sample(u, v),
Some(grid) => {
let uv = grid.from_atlas([u, v]);
udim_at(uv).and_then(|tile| self.images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
}
};
if self.flip_green {
pixel[1] = 1.0 - pixel[1];
}
pixel
})
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn matches(&self, current: &[f32]) -> bool {
let row_len = self.width as usize * self.components;
current.len() == row_len * self.height as usize
&& current
.par_chunks_exact(row_len)
.enumerate()
.all(|(y, row)| row.chunks_exact(self.components).zip(self.row(y)).all(|(stored, sampled)| stored == &sampled[..self.components]))
}
pub(crate) fn render(&self) -> (u32, Vec<f32>) {
let row_len = self.width as usize * self.components;
let mut pixels = vec![0.0; row_len * self.height as usize];
pixels.par_chunks_exact_mut(row_len).enumerate().for_each(|(y, row)| {
for (output, sampled) in row.chunks_exact_mut(self.components).zip(self.row(y)) {
output.copy_from_slice(&sampled[..self.components]);
}
});
(self.width, pixels)
}
}
+27 -44
View File
@@ -4,10 +4,9 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use rayon::prelude::*;
use serde_json::{Value, json};
use texturecraft_compose::{ImageRes, ImageStore};
use texturecraft_core::{BakedMap, MAX_RESOLUTION, NormalFormat, UDIM_RANGE, udim_at};
use texturecraft_core::{BakedMap, MAX_RESOLUTION, Project, UDIM_RANGE};
use crate::commands::{CommandSpec, always, bad, strp};
use crate::set_cmds::ts_param;
@@ -45,42 +44,41 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
None => BTreeMap::from([(FIRST_TILE, image)]),
};
let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?;
let resolution = s.edit("Use image as mesh map", |s| {
let resolution = use_images(s, CMD, ts, map, &images)?;
detach_imported_sources(&mut s.doc.project, ts, |previous| previous == map);
Ok(resolution)
})?;
Ok(json!({ "map": map.id(), "resolution": resolution }))
}
/// A bake, a manual assignment or a clear ends the import link but keeps the image resource
pub(crate) fn detach_imported_sources(project: &mut Project, texture_set: usize, replaced: impl Fn(BakedMap) -> bool) {
for source in project.resource_sources.values_mut() {
if source.mesh_map.is_some_and(|slot| slot.texture_set == texture_set && replaced(slot.map)) {
source.mesh_map = None;
}
}
}
/// 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
/// 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 set = session.doc.project.texture_set(texture_set)?;
let grid = set.tile_grid();
if let Some(tile) = set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) {
return Err(bad(command, format!("no image for UV tile {tile}")));
}
let (width, height) = image_map_size(session, command, texture_set)?;
// Bent normals are tangent-space maps like the normal map, so both follow the project's normal format
let flip_green = matches!(map, BakedMap::Normal | BakedMap::BentNormal) && session.doc.project.normal_format == NormalFormat::DirectX;
let data = match (grid, images.values().next()) {
(_, None) => return Err(bad(command, "no image to use")),
(None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)),
// An atlas texel reads the image of the tile its mesh UV falls in
(Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| {
let uv = grid.from_atlas([u, v]);
udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
}),
};
let (width, data) = crate::mesh_map_sampler::MeshMapSampler::new(session, command, texture_set, map, images)?.render();
let entry = session.doc.baked.entry(texture_set).or_default();
entry.resolution = width;
entry.maps.insert(map, Arc::new(data));
// An imported map is never out of date: nothing records what it was made from
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)
}
@@ -136,26 +134,6 @@ fn udim_in(name: &str) -> Option<usize> {
})
}
/// `w` × `h` texels of `comps` values each from `sample` (atlas UV → RGBA), as stored in the
/// file (mesh maps hold data, not colors, so nothing is linearized); `flip_green` reads a
/// DirectX normal or bent normal map.
fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn(f32, f32) -> [f32; 4] + Sync) -> Vec<f32> {
let mut out = vec![0.0; w as usize * h as usize * comps];
out.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| {
let v = (y as f32 + 0.5) / h as f32;
for (x, texel) in row.chunks_exact_mut(comps).enumerate() {
let mut c = sample((x as f32 + 0.5) / w as f32, v);
if flip_green {
c[1] = 1.0 - c[1];
}
for (o, c) in texel.iter_mut().zip(c) {
*o = c;
}
}
});
out
}
fn clear(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "textureSet.meshMap.clear";
let texture_set = ts_param(session, params, COMMAND)?;
@@ -163,14 +141,19 @@ fn clear(session: &mut Session, params: &Value) -> Result<Value> {
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())));
}
session.edit("Clear mesh map", |session| {
if let Some(baked) = session.doc.baked.get_mut(&texture_set) {
baked.maps.remove(&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)
}
+13 -2
View File
@@ -4,12 +4,13 @@ use std::collections::BTreeMap;
use std::path::Path;
use serde_json::{Value, json};
use texturecraft_core::BakedMap;
use texturecraft_core::{BakedMap, MeshMapSlot, ResourceSource};
use crate::commands::{CommandSpec, always, bad, strp};
use crate::meshmap_cmds::{FIRST_TILE, image_map_size, tile_number, use_images};
use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name};
use crate::resource_cmds::read_image_file;
use crate::resource_update_cmds::file_source;
use crate::{Result, Session, cmd};
const CMD: &str = "textureSet.meshMap.import";
@@ -84,11 +85,20 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
let mut images = BTreeMap::new();
for (tile, path) in tiles {
let slot = MeshMapSlot { texture_set: *ts, map: *map, tile: *tile };
let source = ResourceSource { mesh_map: Some(slot), ..file_source(path) };
let bytes = read_image_file(CMD, path, remaining_bytes)?;
reserve_bytes(&mut remaining_bytes, bytes.len() as u64)?;
let bytes_per_texel = size_of::<[f32; 4]>() as u64;
let name = s.add_image_resource(path, bytes, remaining_bytes / bytes_per_texel)?;
// The slot follows only its latest file
for earlier in s.doc.project.resource_sources.values_mut().filter(|earlier| earlier.mesh_map == Some(slot)) {
earlier.mesh_map = None;
}
s.doc.project.resource_sources.insert(name.clone(), source);
let image = s.images.get(&name).ok_or_else(|| bad(CMD, format!("no decoded image `{name}`")))?;
reserve_bytes(&mut remaining_bytes, u64::from(image.width) * u64::from(image.height) * bytes_per_texel)?;
images.insert(*tile, image.clone());
@@ -98,7 +108,8 @@ fn import_with_budget(s: &mut Session, p: &Value, max_bytes: u64) -> Result<Valu
}
Ok(assigned)
});
// A failed edit leaves the document as it was; forget the images it decoded
// Forget images decoded during an edit that rolled back
if result.is_err() {
s.sync_images();
}
+36 -9
View File
@@ -80,6 +80,9 @@ pub fn specs() -> Vec<CommandSpec> {
pub type FileList = Vec<(String, u64)>;
/// Reads a file of the list by name.
pub type Loader<'a> = &'a dyn Fn(&str) -> std::result::Result<Vec<u8>, String>;
/// The file on disk a file of the list is read from (None: an archive entry or bytes in memory),
/// asked right before reading it.
type Locator<'a> = &'a dyn Fn(&str) -> Option<texturecraft_core::ResourceSource>;
mod pbr_options;
mod take;
@@ -137,10 +140,16 @@ impl Session {
/// Import the maps found among `files` as one fill layer on the active texture set; `load`
/// reads a file by name. Returns the reply of `file.importPbrFolder`.
pub fn import_pbr(&mut self, files: &FileList, load: Loader, options: &PbrOptions) -> Result<Value> {
self.import_pbr_with_budget(files, load, options, import_memory_budget())
self.import_pbr_with_budget(files, load, &|_| None, options, import_memory_budget())
}
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
/// [`Session::import_pbr`] that records the disk files `locate` names, so the Resources Updater can read them again
#[cfg(not(target_arch = "wasm32"))]
fn import_pbr_located(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions) -> Result<Value> {
self.import_pbr_with_budget(files, load, locate, options, import_memory_budget())
}
fn import_pbr_with_budget(&mut self, files: &FileList, load: Loader, locate: Locator, options: &PbrOptions, memory_budget: u64) -> Result<Value> {
let set = detect_with(files, &options.choose)?;
if set.is_empty() {
return Err(EngineError::Other(format!(
@@ -193,6 +202,10 @@ impl Session {
let mut fill = Fill { projection: options.projection.clone(), ..Fill::default() };
let mut added: Vec<(String, Arc<Vec<u8>>)> = Vec::new();
let mut decoded = Vec::new();
// Disk files read by name, and the resources that hold one of them unchanged
let mut file_sources: BTreeMap<String, texturecraft_core::ResourceSource> = BTreeMap::new();
let mut resource_sources: Vec<(String, texturecraft_core::ResourceSource)> = Vec::new();
let mut channels: Vec<Channel> = Vec::new();
let mut total_texels = 0u64;
let mut retained_bytes = 0u64;
@@ -231,6 +244,9 @@ impl Session {
let loaded = if allowed_texels == 0 {
Err("not enough memory is available to import more textures".to_string())
} else {
if let Some(source) = locate(&file) {
file_sources.insert(file.clone(), source);
}
load(&file).and_then(|bytes| {
if bytes.len() as u64 > MAX_FILE_BYTES {
return Err(format!("the file is over {} MB", MAX_FILE_BYTES >> 20));
@@ -288,10 +304,15 @@ impl Session {
}
};
let base = texturecraft_formats::sanitize_resource_name(&resource_name);
let (mut unique, mut suffix_index) = (base.clone(), 2);
while self.doc.resources.contains_key(&unique) || added.iter().any(|(a, _)| *a == unique) {
unique = format!("{suffix_index}_{base}");
suffix_index += 1;
let unique = crate::resource_cmds::unique_resource_name(base, |name| {
self.doc.resources.contains_key(name) || added.iter().any(|(added_name, _)| added_name == name)
});
// Only a resource holding the file's own bytes can be compared with it later
if take == Take::Whole
&& let Some(source) = file_sources.get(&file)
{
resource_sources.push((unique.clone(), source.clone()));
}
added.push((unique.clone(), resource_bytes));
@@ -316,6 +337,7 @@ impl Session {
for (n, bytes) in &added {
s.doc.resources.insert(n.clone(), bytes.clone());
}
s.doc.project.resource_sources.extend(resource_sources);
let id = s.doc.project.alloc_id();
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name.clone(), LayerKind::Fill(fill), &channels))
})?;
@@ -420,7 +442,12 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
if options.name.is_none() {
options.name = found.name.clone();
}
s.import_pbr(&found.files, &|name| found.load(name), &options)
s.import_pbr_located(
&found.files,
&|name| found.load(name),
&|name| found.disk_path(name).map(|path| crate::resource_update_cmds::file_source(&path)),
&options,
)
}
#[cfg(not(target_arch = "wasm32"))]
@@ -462,7 +489,7 @@ mod tests {
let mut session = Session::new_project("test", crate::geom::primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
let load = |_: &str| Ok(bytes.clone());
let result = session.import_pbr_with_budget(&files, &load, &PbrOptions::default(), 64);
let result = session.import_pbr_with_budget(&files, &load, &|_| None, &PbrOptions::default(), 64);
assert!(result.unwrap_err().to_string().contains("more than 1 texels"));
assert!(session.doc.resources.is_empty());
@@ -471,7 +498,7 @@ mod tests {
assert_eq!(allowed_source_texels(256, 64, 3), 2);
let never_load = |_: &str| -> std::result::Result<Vec<u8>, String> { panic!("no source should load after the budget is spent") };
let result = session.import_pbr_with_budget(&files, &never_load, &PbrOptions::default(), 0);
let result = session.import_pbr_with_budget(&files, &never_load, &|_| None, &PbrOptions::default(), 0);
assert!(result.unwrap_err().to_string().contains("not enough memory"));
}
@@ -11,6 +11,16 @@ pub(in crate::pbr_cmds) struct Found {
}
impl Found {
/// The file on disk `name` is read from (None for an archive entry or a name not in the list)
pub(in crate::pbr_cmds) fn disk_path(&self, name: &str) -> Option<String> {
let path = match &self.source {
Origin::Folder { root } => root.join(name),
Origin::Files(paths) => paths.iter().find(|p| p.file_name().is_some_and(|n| n.to_string_lossy() == name))?.clone(),
Origin::Zip(_) => return None,
};
path.to_str().map(str::to_string)
}
/// Reads one file of the list. Archive entries are read through a limit, since their
/// declared size can lie.
pub(in crate::pbr_cmds) fn load(&self, name: &str) -> std::result::Result<Vec<u8>, String> {
+44
View File
@@ -0,0 +1,44 @@
//! An image file read again for a resource, checked before the project changes
use texturecraft_core::ResourceSource;
use texturecraft_formats::DecodedImage;
use crate::Result;
use crate::resource_cmds::{MAX_BYTES, read_image_file};
use crate::resource_update_cmds::file_source;
/// A resource's new bytes, their decoded pixels and the file they came from
pub(crate) struct ReloadedFile {
pub name: String,
pub bytes: Vec<u8>,
pub image: DecodedImage,
pub source: ResourceSource,
}
impl ReloadedFile {
pub(crate) fn read(cmd: &str, name: String, path: &str) -> Result<Self> {
let source = file_source(path);
let bytes = read_image_file(cmd, path, MAX_BYTES as u64)?;
Self::decode(cmd, name, source, bytes)
}
pub(crate) fn read_changed(cmd: &str, name: &str, previous: &ResourceSource, stored: &[u8], decoded: bool) -> Result<Option<Self>> {
let mut source = file_source(&previous.path);
let bytes = read_image_file(cmd, &previous.path, MAX_BYTES as u64)?;
let unchanged = bytes == stored;
if unchanged && decoded {
return Ok(None);
}
source.mesh_map = previous.mesh_map;
let file = Self::decode(cmd, name.to_owned(), source, bytes)?;
Ok((!unchanged).then_some(file))
}
fn decode(cmd: &str, name: String, source: ResourceSource, bytes: Vec<u8>) -> Result<Self> {
let image = texturecraft_formats::decode_image(&bytes).map_err(|error| crate::commands::bad(cmd, format!("{}: {error}", source.path)))?;
Ok(Self { name, bytes, image, source })
}
}
+23
View File
@@ -0,0 +1,23 @@
//! A remembered comparison of a resource with its file, so an unchanged file is not read again
use std::sync::{Arc, Weak};
use crate::resource_status::ResourceStatus;
/// What reading a resource's file found, kept while the file's size and time stay the same
#[derive(Clone, Debug)]
pub(crate) struct ResourceCheck {
pub path: String,
pub size: u64,
pub modified_ms: u64,
/// The resource bytes the file was compared with (an update or undo replaces them)
pub bytes: Weak<Vec<u8>>,
pub status: ResourceStatus,
}
impl ResourceCheck {
/// Whether this verdict still holds for the file and the resource's bytes
pub(crate) fn holds_for(&self, path: &str, size: u64, modified_ms: u64, bytes: &Arc<Vec<u8>>) -> bool {
self.path == path && self.size == size && self.modified_ms == modified_ms && std::ptr::eq(self.bytes.as_ptr(), Arc::as_ptr(bytes))
}
}
+52 -15
View File
@@ -45,6 +45,30 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
}
/// Disambiguate a sanitized resource name without losing its archive key on save.
pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String {
if !taken(&base) {
return base;
}
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |start| base.split_at(start));
let mut index = 2;
loop {
let discriminator = format!("{index}_");
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
// An unusually long extension must leave room for the name itself
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
let stem = &stem[..stem.len().min(available - extension.len())];
let name = format!("{discriminator}{stem}{extension}");
if !taken(&name) {
return name;
}
index += 1;
}
}
impl Session {
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
@@ -79,19 +103,7 @@ impl Session {
base.insert_str(0, &prefix);
}
let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start));
let mut name = base.clone();
let mut duplicate_index = 2;
while self.doc.resources.contains_key(&name) || crate::fill_alpha::library_alpha_of(&name).is_some() {
let discriminator = format!("{duplicate_index}_");
let available = MAX_RESOURCE_NAME_LEN - discriminator.len();
// Leave room for a stem even for names that end in an unusually long extension
let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") };
let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem);
name = format!("{discriminator}{stem}{extension}");
duplicate_index += 1;
}
let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some());
self.doc.resources.insert(name.clone(), Arc::new(bytes));
self.images.insert(name.clone(), decoded(image));
@@ -146,6 +158,16 @@ impl Session {
self.drop_missing_image_view();
}
/// Undo and redo restore resource bytes under the same name (the Resources Updater replaces
/// them in place): the pixels decoded from the bytes `other` held are stale
pub(crate) fn forget_replaced_images(&mut self, other: &crate::Document) {
for (name, bytes) in &self.doc.resources {
if other.resources.get(name).is_some_and(|previous| !Arc::ptr_eq(previous, bytes)) {
self.images.remove(name);
}
}
}
/// The "Other..." view cannot show an image that is gone (removed or renamed): the material comes back
pub(crate) fn drop_missing_image_view(&mut self) {
if self.view == crate::ViewMode::Image && !self.view_image.as_ref().is_some_and(|name| self.images.contains_key(name)) {
@@ -172,8 +194,16 @@ fn list(s: &Session) -> Value {
#[cfg(not(target_arch = "wasm32"))]
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
let prefix = strp(p, "prefix").unwrap_or("");
let source = crate::resource_update_cmds::file_source(path);
let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?;
let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?;
let name = s.edit("Import resource", |session| {
let name = session.add_image_resource_prefixed(prefix, path, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)?;
session.doc.project.resource_sources.insert(name.clone(), source);
Ok(name)
})?;
Ok(json!({ "name": name }))
}
@@ -255,13 +285,14 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Remove resource", |s| {
s.doc.resources.remove(&name);
s.doc.project.resource_sources.remove(&name);
Ok(())
})?;
s.sync_images();
Ok(Value::Null)
}
/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step)
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let mut used = Vec::new();
for set in &s.doc.project.texture_sets {
@@ -273,10 +304,16 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
used.extend(s.tool.brush.alpha_image.clone());
used.extend(s.tool.mask_image.clone());
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
used.extend(s.doc.project.resource_sources.iter().filter_map(|(name, source)| {
let slot = source.mesh_map?;
s.doc.baked.get(&slot.texture_set).is_some_and(|baked| baked.maps.contains_key(&slot.map)).then(|| name.clone())
}));
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
if !unused.is_empty() {
s.edit("Remove unused resources", |s| {
s.doc.resources.retain(|k, _| !unused.contains(k));
s.doc.project.resource_sources.retain(|k, _| !unused.contains(k));
Ok(())
})?;
s.sync_images();
+16
View File
@@ -0,0 +1,16 @@
//! One row of the Resources Updater: an image resource, its file and how they compare
use crate::resource_status::ResourceStatus;
/// An image resource, the file it came from and whether that file changed on disk
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResourceState {
/// The resource's name in the project.
pub name: String,
/// How the resource compares with its file now.
pub status: ResourceStatus,
/// The file it was imported from or relinked to (None: made in the app or imported without a path).
pub path: Option<String>,
/// Why the file could not be checked (with [`ResourceStatus::Missing`]).
pub error: Option<String>,
}
+44
View File
@@ -0,0 +1,44 @@
//! Whether a resource still matches the file it was imported from
/// How a resource compares with its file on disk (materials have none). The order is the Resources Updater's
/// list order: what needs attention first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ResourceStatus {
/// The file changed since it was read: Update reads it again.
Outdated,
/// The file is gone, or cannot be read.
Missing,
/// The file still holds the resource's bytes.
UpToDate,
/// Made in the app or imported without a file path: there is nothing to compare with.
NoSource,
/// A linked MaterialCraft package stored in the project, without a source file to compare.
Material,
}
impl ResourceStatus {
pub const ALL: [ResourceStatus; 5] =
[ResourceStatus::Outdated, ResourceStatus::Missing, ResourceStatus::UpToDate, ResourceStatus::NoSource, ResourceStatus::Material];
/// The id used by the control protocol
pub fn id(self) -> &'static str {
match self {
ResourceStatus::Outdated => "outdated",
ResourceStatus::Missing => "missing",
ResourceStatus::UpToDate => "upToDate",
ResourceStatus::NoSource => "noSource",
ResourceStatus::Material => "material",
}
}
/// The name shown in the Resources Updater (English; the shell translates it)
pub fn label(self) -> &'static str {
match self {
ResourceStatus::Outdated => "Outdated",
ResourceStatus::Missing => "Missing",
ResourceStatus::UpToDate => "Up to date",
ResourceStatus::NoSource => "No source file",
ResourceStatus::Material => "Material",
}
}
}
+395
View File
@@ -0,0 +1,395 @@
//! The Resources Updater: compare image resources with the files they came from, read changed
//! files again and point a resource at another file. Each change is one undo step, and every
//! layer, mask and view using a changed resource recomposites; a mesh map imported from a changed
//! file is resampled while it still holds what the file gave it.
use serde_json::{Value, json};
use texturecraft_core::ResourceSource;
use crate::commands::{CommandSpec, always, bad};
use crate::resource_state::ResourceState;
use crate::resource_status::ResourceStatus;
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"resource.status",
"Check resources on disk",
[],
None,
"{} → {resources: [{name, status: outdated|missing|upToDate|noSource|material, path?, error?}] (outdated first; material: a stored MaterialCraft package), total, outdated}",
always,
|s, _| Ok(status(s))
),
cmd!(
"resource.update",
"Update resources",
[],
None,
"{names?: [resource name] (default: every outdated resource)} → {updated, failed: [{name, error}]} — reads their files again, one undo step",
always,
update
),
cmd!(
"resource.relink",
"Relink resource",
[],
None,
"{name: image resource, path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)} → {name, path} — the resource takes the file's pixels and follows it from now on",
always,
relink
),
]
}
impl Session {
/// Project images and linked MaterialCraft packages, ordered by status and then by name.
/// Equal-size files are compared when their modification time changed or is unknown.
/// A known time lets later checks reuse the verdict.
pub fn resource_states(&mut self) -> Vec<ResourceState> {
let mut states = self.compare_resources();
let materials = self.material_packages().into_iter();
states.extend(materials.map(|name| ResourceState { name, status: ResourceStatus::Material, path: None, error: None }));
states.sort_by(|a, b| a.status.cmp(&b.status).then_with(|| a.name.cmp(&b.name)));
states
}
/// The packages of linked MaterialCraft materials (fill layers and material effects) the project holds
fn material_packages(&self) -> std::collections::BTreeSet<String> {
use texturecraft_core::{EffectKind, Fill, LayerKind};
let package_of = |fill: &Fill| fill.link.as_ref().map(|link| link.package.clone());
let mut packages = std::collections::BTreeSet::new();
for layer in self.doc.project.layers.values() {
if let LayerKind::Fill(fill) = &layer.kind {
packages.extend(package_of(fill));
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
if let EffectKind::Material(fill) = &effect.kind {
packages.extend(package_of(fill));
}
}
}
packages.retain(|name| self.doc.resources.contains_key(name));
packages
}
/// Whether `name` is an image resource the Resources Updater lists
fn is_image_resource(&self, name: &str) -> bool {
self.doc.resources.contains_key(name) && (self.images.contains_key(name) || self.doc.project.resource_sources.contains_key(name))
}
#[cfg(not(target_arch = "wasm32"))]
fn compare_resources(&mut self) -> Vec<ResourceState> {
let mut checks = std::mem::take(&mut self.resource_checks);
let names: Vec<String> = self.doc.resources.keys().filter(|name| self.is_image_resource(name)).cloned().collect();
let mut states = Vec::with_capacity(names.len());
for name in names {
let (Some(bytes), source) = (self.doc.resources.get(&name), self.doc.project.resource_sources.get(&name)) else { continue };
let (status, error) = source.map_or((ResourceStatus::NoSource, None), |source| compare_with_file(&name, source, bytes, &mut checks));
states.push(ResourceState { path: source.map(|source| source.path.clone()), name, status, error });
}
checks.retain(|name, _| self.doc.resources.contains_key(name));
self.resource_checks = checks;
states
}
#[cfg(target_arch = "wasm32")]
fn compare_resources(&mut self) -> Vec<ResourceState> {
let sources = &self.doc.project.resource_sources;
let browser = "file paths are not available in the browser";
let names = self.doc.resources.keys().filter(|name| self.is_image_resource(name));
names
.map(|name| match sources.get(name) {
Some(source) => {
ResourceState { name: name.clone(), status: ResourceStatus::Missing, path: Some(source.path.clone()), error: Some(browser.into()) }
}
None => ResourceState { name: name.clone(), status: ResourceStatus::NoSource, path: None, error: None },
})
.collect()
}
/// Stream changed files into one undo step. A mesh map is compared before its first tile is replaced.
#[cfg(not(target_arch = "wasm32"))]
fn install_reloaded(&mut self, label: &str, files: impl Iterator<Item = crate::reloaded_file::ReloadedFile>) -> Result<Vec<String>> {
let mut files = files.peekable();
if files.peek().is_none() {
return Ok(Vec::new());
}
let mut updated = Vec::new();
let result = self.edit(label, |session| {
let mut slots = std::collections::BTreeMap::new();
for file in files {
if let Some(slot) = file.source.mesh_map {
slots.entry((slot.texture_set, slot.map)).or_insert_with(|| session.mesh_map_matches(slot.texture_set, slot.map));
}
let name = file.name;
if crate::fill_alpha::matches_saved_picture(&name, &file.image) {
session.library_alphas.insert(name.clone());
} else {
session.library_alphas.remove(&name);
}
session.images.insert(name.clone(), crate::resource_cmds::decoded(file.image));
session.doc.resources.insert(name.clone(), std::sync::Arc::new(file.bytes));
session.doc.project.resource_sources.insert(name.clone(), file.source);
updated.push(name);
}
for ((texture_set, map), matches) in slots {
if matches {
let images = session.mesh_map_images(texture_set, map).ok_or_else(|| bad("resource.update", "a mesh map source image is missing"))?;
crate::meshmap_cmds::use_images(session, "resource.update", texture_set, map, &images)?;
}
}
Ok(())
});
if let Err(error) = result {
// The edit restored the encoded bytes, so rebuild any cache entries replaced before rollback
for name in &updated {
self.images.remove(name);
}
self.sync_images();
return Err(error);
}
Ok(updated)
}
#[cfg(not(target_arch = "wasm32"))]
fn mesh_map_images(
&self,
texture_set: usize,
map: texturecraft_core::BakedMap,
) -> Option<std::collections::BTreeMap<u32, std::sync::Arc<texturecraft_compose::ImageRes>>> {
let mut images = std::collections::BTreeMap::new();
for (name, source) in &self.doc.project.resource_sources {
if let Some(slot) = source.mesh_map.filter(|slot| slot.texture_set == texture_set && slot.map == map) {
images.insert(slot.tile, self.images.get(name)?.clone());
}
}
Some(images)
}
#[cfg(not(target_arch = "wasm32"))]
fn mesh_map_matches(&self, texture_set: usize, map: texturecraft_core::BakedMap) -> bool {
let Some(current) = self.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)) else { return false };
let Some(images) = self.mesh_map_images(texture_set, map) else { return false };
crate::mesh_map_sampler::MeshMapSampler::new(self, "resource.update", texture_set, map, &images).is_ok_and(|sampler| sampler.matches(current))
}
}
/// How `stored` (a resource's bytes) compares with the file `source` names now, reusing the
/// remembered verdict in `checks` while the file's size and time stay the same
#[cfg(not(target_arch = "wasm32"))]
fn compare_with_file(
name: &str,
source: &ResourceSource,
stored: &std::sync::Arc<Vec<u8>>,
checks: &mut std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
) -> (ResourceStatus, Option<String>) {
let path = std::path::Path::new(&source.path);
let metadata = match std::fs::metadata(path) {
Ok(metadata) if metadata.is_file() => metadata,
Ok(_) => return (ResourceStatus::Missing, Some(format!("{} is not a regular file", source.path))),
Err(error) => return (ResourceStatus::Missing, Some(format!("{}: {error}", source.path))),
};
let size = metadata.len();
if size != stored.len() as u64 {
return (ResourceStatus::Outdated, None);
}
let modified_ms = modified_ms(&metadata);
if modified_ms != 0 && modified_ms == source.modified_ms {
return (ResourceStatus::UpToDate, None);
}
if let Some(check) = checks.get(name)
&& check.holds_for(&source.path, size, modified_ms, stored)
{
return (check.status, None);
}
// A newer time alone is not a change: the file may have been saved again unchanged
let status = match file_matches(path, stored) {
Ok(true) => ResourceStatus::UpToDate,
Ok(false) => ResourceStatus::Outdated,
Err(error) => return (ResourceStatus::Missing, Some(error.to_string())),
};
if modified_ms == 0 {
// An unknown time cannot establish that the next check sees the same file contents
checks.remove(name);
} else {
let bytes = std::sync::Arc::downgrade(stored);
checks.insert(name.to_string(), crate::resource_check::ResourceCheck { path: source.path.clone(), size, modified_ms, bytes, status });
}
(status, None)
}
/// Compare without allocating a second copy of the resource. Read to the checked end to detect I/O errors and growth.
#[cfg(not(target_arch = "wasm32"))]
fn file_matches(path: &std::path::Path, stored: &[u8]) -> Result<bool> {
use std::io::{ErrorKind, Read};
const CMD: &str = "resource.status";
const CHUNK_BYTES: usize = 32 * 1024;
let read_error = |error| bad(CMD, format!("cannot read {}: {error}", path.display()));
let too_large = || bad(CMD, format!("{} is too large (limit {} bytes)", path.display(), crate::resource_cmds::MAX_BYTES));
let mut file = crate::resource_cmds::open_resource_file(CMD, path)?;
let len = file.metadata().map_err(read_error)?.len();
if len > crate::resource_cmds::MAX_BYTES as u64 {
return Err(too_large());
}
let mut chunk = [0; CHUNK_BYTES];
let mut equal = len == stored.len() as u64;
for start in (0..len as usize).step_by(CHUNK_BYTES) {
let end = (start + CHUNK_BYTES).min(len as usize);
let part = &mut chunk[..end - start];
match file.read_exact(part) {
Ok(()) => equal = equal && stored.get(start..end) == Some(part),
Err(error) if error.kind() == ErrorKind::UnexpectedEof => return Ok(false),
Err(error) => return Err(read_error(error)),
}
}
if file.read(&mut [0]).map_err(read_error)? > 0 {
return Err(too_large());
}
Ok(equal)
}
/// A file's modification time in milliseconds since the Unix epoch (0 when the system has none)
#[cfg(not(target_arch = "wasm32"))]
fn modified_ms(metadata: &std::fs::Metadata) -> u64 {
let since_epoch = metadata.modified().ok().and_then(|modified| modified.duration_since(std::time::UNIX_EPOCH).ok());
since_epoch.map_or(0, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
}
/// The record for an image about to be read from `path`: its absolute path and its current
/// modification time, taken before reading so a write during the read still shows as a change
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn file_source(path: &str) -> ResourceSource {
let absolute = std::path::absolute(path).ok().and_then(|absolute| absolute.to_str().map(str::to_string)).unwrap_or_else(|| path.to_string());
let modified_ms = std::fs::metadata(path).map_or(0, |metadata| modified_ms(&metadata));
ResourceSource { path: absolute, modified_ms, mesh_map: None }
}
/// The browser reads no paths; the record keeps the name it was given
#[cfg(target_arch = "wasm32")]
pub(crate) fn file_source(path: &str) -> ResourceSource {
ResourceSource { path: path.to_string(), modified_ms: 0, mesh_map: None }
}
fn status(s: &mut Session) -> Value {
let states = s.resource_states();
let outdated = states.iter().filter(|state| state.status == ResourceStatus::Outdated).count();
let resources: Vec<Value> = states
.iter()
.map(|state| {
let mut row = json!({"name": state.name, "status": state.status.id()});
if let Some(path) = &state.path {
row["path"] = json!(path);
}
if let Some(error) = &state.error {
row["error"] = json!(error);
}
row
})
.collect();
json!({"resources": resources, "total": states.len(), "outdated": outdated})
}
#[cfg(not(target_arch = "wasm32"))]
fn update(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "resource.update";
let names: Vec<String> = match p.get("names") {
None | Some(Value::Null) => s.resource_states().into_iter().filter(|state| state.status == ResourceStatus::Outdated).map(|state| state.name).collect(),
Some(Value::Array(names)) => {
names.iter().map(|name| name.as_str().map(str::to_string).ok_or_else(|| bad(CMD, "`names` must be resource names"))).collect::<Result<_>>()?
}
Some(_) => return Err(bad(CMD, "`names` must be an array of resource names")),
};
// Validate the complete selection before opening files
let mut selected = Vec::new();
let mut seen = std::collections::HashSet::new();
for name in names {
let bytes = s.doc.resources.get(&name).ok_or_else(|| bad(CMD, format!("no resource `{name}`")))?;
let Some(source) = s.doc.project.resource_sources.get(&name) else {
let reason = if s.images.contains_key(&name) {
format!("`{name}` has no source file: relink it to a file first")
} else {
format!("`{name}` has no source file: only image resources can be relinked")
};
return Err(bad(CMD, reason));
};
if seen.insert(name.clone()) {
let decoded = s.images.contains_key(&name);
selected.push((name, source.clone(), bytes.clone(), decoded));
}
}
let mut failed = Vec::new();
let files = selected.into_iter().filter_map(|(name, source, stored, decoded)| {
match crate::reloaded_file::ReloadedFile::read_changed(CMD, &name, &source, &stored, decoded) {
Ok(file) => file,
Err(error) => {
failed.push(json!({"name": name, "error": error.to_string()}));
None
}
}
});
let updated = s.install_reloaded("Update resources", files)?;
if updated.is_empty() && !failed.is_empty() {
let reasons: Vec<&str> = failed.iter().filter_map(|failure| failure["error"].as_str()).collect();
return Err(bad(CMD, format!("nothing was updated: {}", reasons.join("; "))));
}
Ok(json!({"updated": updated, "failed": failed}))
}
#[cfg(not(target_arch = "wasm32"))]
fn relink(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "resource.relink";
let name = crate::commands::strp(p, "name").ok_or_else(|| bad(CMD, "`name` is required"))?.to_string();
let path = crate::commands::strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
if !s.is_image_resource(&name) {
return Err(bad(CMD, format!("no image resource `{name}`")));
}
// A relinked mesh map file still feeds its mesh map
let mut file = crate::reloaded_file::ReloadedFile::read(CMD, name.clone(), path)?;
file.source.mesh_map = s.doc.project.resource_sources.get(&name).and_then(|source| source.mesh_map);
let path = file.source.path.clone();
s.install_reloaded("Relink resource", std::iter::once(file))?;
Ok(json!({"name": name, "path": path}))
}
#[cfg(target_arch = "wasm32")]
fn update(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("resource.update", "file paths are not available in the browser"))
}
#[cfg(target_arch = "wasm32")]
fn relink(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("resource.relink", "file paths are not available in the browser"))
}
+13 -2
View File
@@ -33,7 +33,8 @@ 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,
/// Where skew or cage painting changed each texture set since its auto-rebake map was baked; undo brings a box back with the maps baked before it, and it is not saved
/// 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>,
}
@@ -427,8 +428,10 @@ 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 `source`'s geometry, once a bake or an out-of-date check needs it
/// 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>,
@@ -470,6 +473,9 @@ pub struct Session {
pub images: texturecraft_compose::ImageStore,
/// Resource names whose decoded pixels match a library alpha.
pub(crate) library_alphas: BTreeSet<String>,
/// Resources whose file was read for the Resources Updater, by name: the verdict stays while the file's size and time do
#[cfg(not(target_arch = "wasm32"))]
pub(crate) resource_checks: std::collections::HashMap<String, crate::resource_check::ResourceCheck>,
/// Temporary texel mask limiting paint strokes (not saved, not in the history).
pub quick_mask: crate::quick_mask::QuickMask,
/// A path sublayer is being repainted from its paths (the only way to paint into one).
@@ -534,6 +540,7 @@ impl Session {
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),
@@ -560,6 +567,8 @@ impl Session {
blending_clipboard: None,
images: Default::default(),
library_alphas: BTreeSet::new(),
#[cfg(not(target_arch = "wasm32"))]
resource_checks: std::collections::HashMap::new(),
quick_mask: Default::default(),
painting_paths: false,
path_cache: None,
@@ -992,6 +1001,7 @@ impl Session {
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.forget_replaced_images(&current);
self.redo.push((label.clone(), current));
self.sync_images();
Ok(label)
@@ -1012,6 +1022,7 @@ impl Session {
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let current = std::mem::replace(&mut self.doc, restored);
self.after_history(&current);
self.forget_replaced_images(&current);
self.undo.push((label.clone(), current));
self.sync_images();
Ok(label)
+2 -2
View File
@@ -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:?}");
}
// Ending the preview alone leaves the document as it was; the app keeps finished maps through keep_canceled_bake
// The UI applies eligible maps separately through keep_canceled_bake
session.bake_preview_end();
assert_eq!(session.doc.baked.get(&0).cloned(), before);
+16
View File
@@ -82,6 +82,22 @@ fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() {
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);
+31 -1
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.
/// 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();
+8
View File
@@ -19,6 +19,7 @@ fn bake_run_lists_every_checked_map_of_the_set_as_baked() {
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());
@@ -39,6 +40,7 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() {
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");
@@ -57,6 +59,7 @@ fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() {
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"]));
@@ -64,6 +67,7 @@ fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() {
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}");
}
@@ -90,8 +94,10 @@ fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_canc
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));
@@ -110,6 +116,7 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_
.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 {
@@ -138,6 +145,7 @@ fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() {
.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();
+54 -1
View File
@@ -4,7 +4,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use serde_json::json;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::{BakeChange, BakedMap, CageType};
use texturecraft_engine::core::{BakeChange, BakedMap, CageType, IdColorSource, MeshMatchMode};
use texturecraft_engine::formats::MeshFile;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
@@ -72,6 +73,58 @@ fn adding_a_high_poly_puts_the_maps_out_of_date() {
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();
+1
View File
@@ -67,6 +67,7 @@ mod perf;
mod polygon_fill;
mod project_recovery;
mod rebuilt_uv_layout;
mod resource_updater;
mod resources_used;
mod sample;
mod solo;
+547
View File
@@ -0,0 +1,547 @@
//! The Resources Updater: image resources remember their files, a changed file shows as outdated,
//! Update reads it again (one undo step, recompositing its layers) and Relink follows another file
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use serde_json::{Value, json};
use texturecraft_engine::core::{BakedMap, Channel};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{ResourceStatus, Session, execute};
const RESOLUTION: u32 = 128;
const SAMPLE_STRIDE: usize = 8;
const RED: [u8; 4] = [255, 0, 0, 255];
const GREEN: [u8; 4] = [0, 255, 0, 255];
fn session() -> Session {
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap()
}
/// Write a `size` × `size` PNG of one colour (sizes differ between versions, so the file size changes too)
fn write_png(path: &Path, size: u32, color: [u8; 4]) {
image::RgbaImage::from_pixel(size, size, image::Rgba(color)).save(path).unwrap();
}
fn text(path: &Path) -> &str {
path.to_str().unwrap()
}
/// Give the file at `path` the modification time `time` without changing its contents
fn set_modified(path: &Path, time: SystemTime) {
std::fs::File::options().write(true).open(path).unwrap().set_modified(time).unwrap();
}
fn modified(path: &Path) -> SystemTime {
std::fs::metadata(path).unwrap().modified().unwrap()
}
fn import(s: &mut Session, path: &Path) -> String {
execute(s, "resource.import", &json!({"path": text(path)})).unwrap()["name"].as_str().unwrap().to_string()
}
/// Import `path` and show it as a base colour fill; returns the resource name
fn import_as_fill(s: &mut Session, path: &Path) -> String {
let name = import(s, path);
execute(s, "layer.add.image", &json!({"name": name})).unwrap();
s.update();
name
}
fn base_colors(s: &Session) -> Vec<[f32; 3]> {
let composite = &s.caches[s.ts()].composite;
let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE);
samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect()
}
fn status_of(s: &mut Session, name: &str) -> ResourceStatus {
s.resource_states().into_iter().find(|state| state.name == name).expect("the resource is listed").status
}
#[test]
fn a_changed_file_is_outdated_and_update_replaces_its_pixels_as_one_undo_step() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("bricks.png");
write_png(&file, 4, RED);
let mut s = session();
let name = import_as_fill(&mut s, &file);
let before = base_colors(&s);
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
write_png(&file, 8, GREEN);
let status = execute(&mut s, "resource.status", &Value::Null).unwrap();
assert_eq!(status["outdated"], json!(1));
assert_eq!(status["resources"][0]["name"], json!(name));
assert_eq!(status["resources"][0]["status"], json!("outdated"));
let steps = s.history_labels().len();
let updated = execute(&mut s, "resource.update", &json!({})).unwrap();
s.update();
let after = base_colors(&s);
assert_eq!(updated["updated"], json!([name]));
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
assert_eq!(s.images[&name].width, 8, "the new pixels are decoded");
assert_ne!(after, before, "the fill using the resource recomposited");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert_eq!(s.images[&name].width, 4, "undo brings back the old pixels under the same name");
assert_eq!(base_colors(&s), before);
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated, "the file on disk is still the new one");
execute(&mut s, "edit.redo", &Value::Null).unwrap();
s.update();
assert_eq!(s.images[&name].width, 8);
assert_eq!(base_colors(&s), after);
}
#[test]
fn outdated_resources_come_first_then_missing_up_to_date_unlinked_and_materials() {
let dir = tempfile::tempdir().unwrap();
let [fine, gone, changed] = ["b_fine.png", "c_gone.png", "d_changed.png"].map(|name| dir.path().join(name));
for file in [&fine, &gone, &changed] {
write_png(file, 4, RED);
}
let mut s = session();
let png = std::fs::read(&fine).unwrap();
s.import_resource_bytes("a_unlinked.png", png).unwrap();
for file in [&fine, &gone, &changed] {
import(&mut s, file);
}
// The environment map and the brush alpha are image resources like any other
let environment = format!("{}b_fine.png", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX);
execute(&mut s, "display.set", &json!({"environment": environment})).unwrap();
execute(&mut s, "tool.brush", &json!({"alpha": {"image": "d_changed.png"}})).unwrap();
// A linked MaterialCraft material keeps its package as a resource without a file
s.doc.resources.insert("a_brick.mcmat".to_string(), Arc::new(b"package".to_vec()));
let layer = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap();
let link = serde_json::from_value(json!({"name": "Brick", "package": "a_brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap();
if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut s.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind {
fill.link = Some(link);
}
std::fs::remove_file(&gone).unwrap();
write_png(&changed, 8, GREEN);
let states = s.resource_states();
let order: Vec<&str> = states.iter().map(|state| state.name.as_str()).collect();
let statuses: Vec<&str> = states.iter().map(|state| state.status.id()).collect();
assert_eq!(order, ["d_changed.png", "c_gone.png", "b_fine.png", "a_unlinked.png", "a_brick.mcmat"], "by status first, against the name order");
assert_eq!(statuses, ["outdated", "missing", "upToDate", "noSource", "material"], "the alpha's and the environment's files are checked too");
let error = execute(&mut s, "resource.update", &json!({"names": ["a_brick.mcmat"]})).unwrap_err();
assert!(error.to_string().contains("only image resources can be relinked"), "{error}");
}
#[test]
fn a_same_size_file_is_compared_by_contents_once_per_time() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("same.png");
write_png(&file, 4, RED);
let mut s = session();
let name = import(&mut s, &file);
let original = std::fs::read(&file).unwrap();
let later = modified(&file) + Duration::from_secs(10);
// Saved again unchanged: a new time alone is no change, and updating adds no step
set_modified(&file, later);
let steps = s.history_labels().len();
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
assert_eq!(execute(&mut s, "resource.update", &json!({})).unwrap()["updated"], json!([]));
assert_eq!(s.history_labels().len(), steps);
// Different bytes of the same size and time are not read again: the verdict for that size and time stands
let mut edited = original.clone();
let last = edited.len() - 1;
edited[last] ^= 0xff;
std::fs::write(&file, &edited).unwrap();
set_modified(&file, later);
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate, "the remembered verdict is used");
// Another time reads the file, and its bytes differ
set_modified(&file, later + Duration::from_secs(10));
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated);
}
#[cfg(unix)]
#[test]
fn a_file_without_a_usable_timestamp_is_compared_on_each_check() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("archived.png");
write_png(&path, 4, RED);
set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(20));
let mut session = session();
let name = import(&mut session, &path);
assert_eq!(status_of(&mut session, &name), ResourceStatus::UpToDate);
let mut changed = std::fs::read(&path).unwrap();
changed[0] ^= 1;
std::fs::write(&path, changed).unwrap();
set_modified(&path, SystemTime::UNIX_EPOCH - Duration::from_secs(10));
assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated);
}
#[test]
fn a_missing_file_is_reported_and_updating_it_changes_nothing() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("gone.png");
write_png(&file, 4, RED);
let mut s = session();
let name = import_as_fill(&mut s, &file);
std::fs::remove_file(&file).unwrap();
let steps = s.history_labels().len();
let state = s.resource_states().into_iter().find(|state| state.name == name).unwrap();
let error = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap_err();
assert_eq!(state.status, ResourceStatus::Missing);
assert!(state.error.is_some(), "the reason is shown");
assert!(error.to_string().contains("nothing was updated"), "{error}");
assert_eq!(s.history_labels().len(), steps);
assert_eq!(s.images[&name].width, 4, "the resource keeps its pixels");
}
#[test]
fn an_unreadable_file_fails_alone_while_the_others_update() {
let dir = tempfile::tempdir().unwrap();
let (kept, gone) = (dir.path().join("kept.png"), dir.path().join("gone.png"));
write_png(&kept, 4, RED);
write_png(&gone, 4, RED);
let mut s = session();
let kept_name = import_as_fill(&mut s, &kept);
let gone_name = import_as_fill(&mut s, &gone);
write_png(&kept, 8, GREEN);
std::fs::remove_file(&gone).unwrap();
let result = execute(&mut s, "resource.update", &json!({"names": [kept_name, gone_name]})).unwrap();
assert_eq!(result["updated"], json!([kept_name]));
assert_eq!(result["failed"][0]["name"], json!(gone_name));
assert_eq!(s.images[&kept_name].width, 8);
}
#[test]
fn relink_reads_another_file_and_follows_it_from_then_on() {
let dir = tempfile::tempdir().unwrap();
let (first, second) = (dir.path().join("first.png"), dir.path().join("second.png"));
write_png(&first, 4, RED);
write_png(&second, 8, GREEN);
let mut s = session();
let name = import_as_fill(&mut s, &first);
let before = base_colors(&s);
let steps = s.history_labels().len();
execute(&mut s, "resource.relink", &json!({"name": name, "path": text(&second)})).unwrap();
s.update();
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
assert_eq!(s.images[&name].width, 8, "the resource keeps its name and takes the new file's pixels");
assert_ne!(base_colors(&s), before);
assert!(s.doc.project.resource_sources[&name].path.ends_with("second.png"));
// The old file no longer matters, the new one does
write_png(&first, 16, GREEN);
assert_eq!(status_of(&mut s, &name), ResourceStatus::UpToDate);
write_png(&second, 16, RED);
assert_eq!(status_of(&mut s, &name), ResourceStatus::Outdated);
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.doc.project.resource_sources[&name].path.ends_with("first.png"), "undo restores the link");
}
#[test]
fn relink_refuses_resources_that_are_not_images() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("picture.png");
write_png(&file, 4, RED);
let mut s = session();
s.doc.resources.insert("material.mcmat".to_string(), Arc::new(vec![1, 2, 3]));
let steps = s.history_labels().len();
let error = execute(&mut s, "resource.relink", &json!({"name": "material.mcmat", "path": text(&file)})).unwrap_err();
assert!(error.to_string().contains("no image resource"), "{error}");
assert_eq!(*s.doc.resources["material.mcmat"], vec![1, 2, 3]);
assert_eq!(s.history_labels().len(), steps);
}
#[test]
fn resources_without_a_file_cannot_update_and_a_reopened_project_keeps_its_links() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("kept.png");
write_png(&file, 4, RED);
let mut s = session();
let linked = import_as_fill(&mut s, &file);
let png = std::fs::read(&file).unwrap();
let unlinked = s.import_resource_bytes("made.png", png).unwrap();
assert_eq!(status_of(&mut s, &unlinked), ResourceStatus::NoSource);
assert!(execute(&mut s, "resource.update", &json!({"names": [unlinked]})).is_err());
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
write_png(&file, 8, GREEN);
assert_eq!(status_of(&mut reopened, &linked), ResourceStatus::Outdated);
}
#[test]
fn a_removed_resource_forgets_its_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("old.png");
write_png(&file, 4, RED);
let mut s = session();
let name = import(&mut s, &file);
execute(&mut s, "resource.remove", &json!({"name": name})).unwrap();
let png = std::fs::read(&file).unwrap();
let reused = s.import_resource_bytes("old.png", png).unwrap();
assert_eq!(reused, name, "the name is free again");
assert_eq!(status_of(&mut s, &reused), ResourceStatus::NoSource, "a new resource under the old name does not inherit the file");
}
/// The material ball: texture sets "Ball" and "Base"
fn ball() -> Session {
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap()
}
fn ambient_occlusion(s: &Session) -> Vec<f32> {
s.doc.baked[&0].maps[&BakedMap::AmbientOcclusion].as_ref().clone()
}
#[test]
fn an_imported_mesh_map_follows_its_changed_file_until_something_else_replaces_it() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Ball_ao.png");
write_png(&file, 4, [60, 60, 60, 255]);
let mut s = ball();
execute(&mut s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
let name = s.doc.project.resource_sources.keys().next().expect("the file is remembered").clone();
let imported = ambient_occlusion(&s);
write_png(&file, 8, [200, 200, 200, 255]);
execute(&mut s, "resource.update", &json!({})).unwrap();
let updated = ambient_occlusion(&s);
assert_ne!(updated, imported, "the mesh map is resampled from the new file");
// Another image in the slot is not overwritten by a later change of the file
let other = dir.path().join("other.png");
write_png(&other, 4, [10, 10, 10, 255]);
let other_name = import(&mut s, &other);
execute(&mut s, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": other_name})).unwrap();
let replaced = ambient_occlusion(&s);
write_png(&file, 16, [120, 120, 120, 255]);
let result = execute(&mut s, "resource.update", &json!({"names": [name]})).unwrap();
assert_eq!(result["updated"], json!([name]), "the resource itself still updates");
assert_eq!(ambient_occlusion(&s), replaced, "the mesh map keeps the image set over it");
}
#[test]
fn an_explicit_mesh_map_replacement_breaks_the_import_link_even_when_pixels_match() {
let dir = tempfile::tempdir().unwrap();
let original = dir.path().join("Ball_ao.png");
let replacement = dir.path().join("replacement.png");
let equal_color = [60, 60, 60, 255];
write_png(&original, 4, equal_color);
write_png(&replacement, 4, equal_color);
let mut session = ball();
let replacement_name = import(&mut session, &replacement);
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&original)}]})).unwrap();
let imported = ambient_occlusion(&session);
execute(&mut session, "textureSet.meshMap.set", &json!({"ts": 0, "map": "ambientOcclusion", "image": replacement_name})).unwrap();
write_png(&original, 8, [200, 200, 200, 255]);
let result = execute(&mut session, "resource.update", &Value::Null).unwrap();
assert_eq!(result["updated"], json!(["Ball_ao.png"]));
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();
let map_file = dir.path().join("Ball_ao.png");
let unused_file = dir.path().join("unused.png");
write_png(&map_file, 4, [60, 60, 60, 255]);
write_png(&unused_file, 4, RED);
let mut session = ball();
let unused_name = import(&mut session, &unused_file);
execute(&mut session, "textureSet.meshMap.import", &json!({"files": [{"path": text(&map_file)}]})).unwrap();
let imported = ambient_occlusion(&session);
let cleanup = execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert_eq!(cleanup["removed"], json!([unused_name]));
write_png(&map_file, 8, [200, 200, 200, 255]);
let update = execute(&mut session, "resource.update", &Value::Null).unwrap();
assert_eq!(update["updated"], json!(["Ball_ao.png"]));
assert_ne!(ambient_occlusion(&session), imported);
}
#[test]
fn updating_duplicate_names_replaces_each_image_once_and_releases_old_pixels() {
let dir = tempfile::tempdir().unwrap();
let files = ["first.png", "second.png"].map(|name| dir.path().join(name));
let mut session = session();
let names = files.each_ref().map(|path| {
write_png(path, 4, RED);
import(&mut session, path)
});
let old_pixels = names.each_ref().map(|name| Arc::downgrade(&session.images[name]));
for file in &files {
write_png(file, 8, GREEN);
}
let result = execute(&mut session, "resource.update", &json!({"names": [&names[0], &names[1], &names[0]]})).unwrap();
assert_eq!(result["updated"], json!(names));
assert!(old_pixels.iter().all(|pixels| pixels.upgrade().is_none()), "history keeps the encoded bytes, so replaced decoded images can drop");
for name in names {
assert_eq!(session.images[&name].width, 8);
}
}
#[test]
fn pbr_folder_and_materialx_imports_remember_their_image_files() {
let dir = tempfile::tempdir().unwrap();
let long_name = |suffix: &str| format!("{}{suffix}", "m".repeat(texturecraft_formats::MAX_RESOURCE_NAME_LEN - suffix.len()));
let color = dir.path().join(long_name("_col.png"));
write_png(&color, 4, RED);
std::fs::create_dir(dir.path().join("tex")).unwrap();
let base_name = long_name("_base.png");
let base = dir.path().join("tex").join(&base_name);
write_png(&base, 4, GREEN);
let mtlx = dir.path().join("m.mtlx");
let document = r#"<?xml version="1.0"?>
<materialx version="1.39" fileprefix="tex/">
<open_pbr_surface name="S" type="surfaceshader"><input name="base_color" type="color3" nodename="a" /></open_pbr_surface>
<tiledimage name="a" type="color3"><input name="file" type="filename" value="base.png" /></tiledimage>
<surfacematerial name="M" type="material"><input name="surfaceshader" type="surfaceshader" nodename="S" /></surfacematerial>
</materialx>"#;
std::fs::write(&mtlx, document.replace("base.png", &base_name)).unwrap();
let mut s = session();
import(&mut s, &color);
import(&mut s, &base);
let pbr = execute(&mut s, "file.importPbrFolder", &json!({"files": [text(&color)]})).unwrap();
let materialx = execute(&mut s, "file.importMaterialX", &json!({"path": text(&mtlx)})).unwrap();
let pbr_name = pbr["resources"][0].as_str().unwrap().to_string();
let materialx_name = materialx["resources"][0].as_str().unwrap().to_string();
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(Path::new(&reopened.doc.project.resource_sources[&pbr_name].path).canonicalize().unwrap(), color.canonicalize().unwrap());
assert_eq!(Path::new(&reopened.doc.project.resource_sources[&materialx_name].path).canonicalize().unwrap(), base.canonicalize().unwrap());
write_png(&color, 8, GREEN);
write_png(&base, 8, RED);
let rows = reopened.resource_states();
let missing: Vec<_> = [&pbr_name, &materialx_name]
.into_iter()
.filter(|name| !rows.iter().any(|row| row.name == name.as_str() && row.status == ResourceStatus::Outdated))
.collect();
assert!(missing.is_empty(), "both material imports must keep their source images after reopening: {missing:?}");
}
#[test]
fn a_mesh_map_imported_twice_follows_the_latest_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Ball_ao.png");
let import_file = |s: &mut Session| execute(s, "textureSet.meshMap.import", &json!({"files": [{"path": text(&file)}]})).unwrap();
let mut s = ball();
write_png(&file, 4, [60, 60, 60, 255]);
import_file(&mut s);
let first = s.doc.project.resource_sources.keys().next().unwrap().clone();
write_png(&file, 8, [200, 200, 200, 255]);
import_file(&mut s);
let latest = s.doc.project.resource_sources.keys().find(|name| **name != first).expect("a second resource").clone();
let imported = ambient_occlusion(&s);
write_png(&file, 16, [10, 10, 10, 255]);
execute(&mut s, "resource.update", &json!({"names": [latest]})).unwrap();
assert_ne!(ambient_occlusion(&s), imported, "the mesh map follows the file imported last");
assert!(s.doc.project.resource_sources[&first].mesh_map.is_none(), "the earlier import no longer feeds the slot");
}
#[test]
fn an_undecodable_saved_resource_is_reported_even_when_its_file_is_unchanged() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("broken.png");
write_png(&file, 4, RED);
let mut session = session();
let name = import(&mut session, &file);
let invalid = b"incomplete image".to_vec();
std::fs::write(&file, &invalid).unwrap();
session.doc.resources.insert(name.clone(), Arc::new(invalid));
session.images.remove(&name);
let result = execute(&mut session, "resource.update", &json!({"names": [name]}));
assert!(result.unwrap_err().to_string().contains("nothing was updated"));
assert!(!session.images.contains_key(&name));
}
#[test]
fn a_rejected_update_restores_all_previously_decoded_images() {
let dir = tempfile::tempdir().unwrap();
let mut session = session();
let names = ["left.png", "right.png"].map(|name| {
let path = dir.path().join(name);
write_png(&path, 4, RED);
let imported = import_as_fill(&mut session, &path);
write_png(&path, 8, GREEN);
imported
});
// Make final document validation fail after both replacements have been processed
let layer = session.doc.project.layers.values_mut().next().unwrap();
layer.kind = texturecraft_engine::core::LayerKind::Instance { source: layer.id };
let steps = session.history_labels().len();
let result = execute(&mut session, "resource.update", &json!({"names": names}));
assert!(result.unwrap_err().to_string().contains("would draw itself"));
assert_eq!(session.history_labels().len(), steps);
for name in names {
assert_eq!(session.images[&name].width, 4);
assert_eq!(status_of(&mut session, &name), ResourceStatus::Outdated);
}
}
@@ -95,6 +95,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
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 {
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 {
@@ -103,8 +104,8 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
app.ui.dock.focus(Panel::MeshMapSettings);
}
Some(RowClick::AutoRebake) => {
let map = if auto_rebake_map(app, texture_set) == Some(map) { Value::Null } else { json!(map.id()) };
app.run("bake.autoRebake", json!({ "ts": texture_set, "map": map }));
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 => {}
}
@@ -117,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 {
@@ -280,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));
@@ -290,9 +291,10 @@ 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());
@@ -302,7 +304,6 @@ fn row(
out_of_date_mark(ui, thumbnail_rect, name, changes);
}
// From the right: sync (with several sets), Auto-rebake, bolt, eye; Auto-rebake alone stays while on
let focus_in_row = || {
ui.memory(|memory| memory.focused())
.and_then(|id| ui.ctx().read_response(id))
@@ -310,11 +311,14 @@ fn row(
};
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));
@@ -325,6 +329,7 @@ fn row(
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();
@@ -333,6 +338,7 @@ 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() {
@@ -477,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;
@@ -497,6 +505,7 @@ fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeCha
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);
+1
View File
@@ -239,6 +239,7 @@ fn edit_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, "merge": merge }));
true
}
+6 -4
View File
@@ -15,13 +15,14 @@ pub struct BakeReport {
}
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 {
@@ -37,6 +38,7 @@ impl BakeReport {
tr("Failures are listed in the Log.")
)
};
(text, line, self.failed_set_count > 0)
}
}
+1
View File
@@ -91,6 +91,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
matching_not_enabled(ui);
return;
}
if issues_only && issue_count == 0 {
no_issues(ui, tab);
return;
@@ -14,11 +14,13 @@ 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;
}
@@ -38,17 +40,20 @@ fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool {
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);
@@ -56,6 +61,7 @@ fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool {
if response.has_focus() {
crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong);
}
open
}
@@ -75,6 +81,7 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) {
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);
@@ -82,6 +89,7 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) {
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 {
+9 -2
View File
@@ -329,6 +329,7 @@ impl Dock {
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 }
}
@@ -418,6 +419,7 @@ impl LiveDock {
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
@@ -490,11 +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 split around the viewport, floating title bars only move windows, and each closable tab has its close button
// 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);
@@ -509,6 +513,7 @@ 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));
@@ -524,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);
}
@@ -770,6 +776,7 @@ mod tests {
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);
}
@@ -45,6 +45,7 @@ pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_
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")),
@@ -61,6 +62,7 @@ fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, Bake
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));
@@ -97,5 +99,6 @@ fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) {
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]);
}
+3
View File
@@ -274,6 +274,9 @@ mod tests {
keys.extend(BlendMode::all().map(|mode| mode.label()));
keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label()));
keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label()));
keys.extend(texturecraft_engine::ResourceStatus::ALL.iter().map(|status| status.label()));
let notice = crate::toast_action::ToastAction::UpdateResources { project: 0 };
keys.extend([notice.label(), notice.accessible_name()]);
keys.extend(texturecraft_engine::HISTORY_TEMPLATES);
keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label()));
keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label()));
+90 -25
View File
@@ -146,6 +146,8 @@ mod resolution_band;
mod resource_panel;
mod resource_picker;
mod resource_picker_item;
#[cfg(not(target_arch = "wasm32"))]
mod resources_updater;
mod round_gizmo;
mod running_bake;
#[cfg(not(target_arch = "wasm32"))]
@@ -181,6 +183,7 @@ pub mod thumbs;
mod tile_edits;
mod tile_picture;
pub mod titlebar;
pub mod toast_action;
pub mod toolbar;
pub mod ui_state_store;
pub mod unavailable;
@@ -262,6 +265,8 @@ pub struct Toast {
pub error: bool,
pub until: f64,
pub show_log: bool,
/// A button after the text that acts on the notice
pub action: Option<toast_action::ToastAction>,
announce: bool,
}
@@ -376,6 +381,12 @@ pub struct TextureCraftApp {
styled: Option<(theme::Brightness, theme::Accent)>,
/// Whether the window had focus last frame.
focused: bool,
/// The outdated resources the last "changed on disk" notice named, so an unchanged set is not announced again
#[cfg(not(target_arch = "wasm32"))]
pub(crate) resources_notified: std::collections::BTreeSet<String>,
/// The project the Resources Updater last checked on opening (see `resources_updater::follow_project`)
#[cfg(not(target_arch = "wasm32"))]
pub(crate) resources_project: Option<u64>,
/// The update check and prompt (desktop only).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) updates_rt: updates_ui::Runtime,
@@ -521,6 +532,10 @@ impl TextureCraftApp {
styled: None,
focused: true,
#[cfg(not(target_arch = "wasm32"))]
resources_notified: std::collections::BTreeSet::new(),
#[cfg(not(target_arch = "wasm32"))]
resources_project: None,
#[cfg(not(target_arch = "wasm32"))]
updates_rt: updates_ui::Runtime::default(),
#[cfg(not(target_arch = "wasm32"))]
file_dialogs: file_dialogs::FileDialogs::new(cc.egui_ctx.clone()),
@@ -678,13 +693,24 @@ impl TextureCraftApp {
}
pub fn toast(&mut self, text: impl Into<String>, error: bool) {
self.toasts.push(Toast { text: text.into(), error, until: self.last_time + if error { 6.0 } else { 3.0 }, show_log: false, announce: false });
const ERROR_SECONDS: f64 = 6.0;
const NOTICE_SECONDS: f64 = 3.0;
let until = self.last_time + if error { ERROR_SECONDS } else { NOTICE_SECONDS };
self.toasts.push(Toast { text: text.into(), error, until, show_log: false, action: None, announce: false });
}
#[cfg(not(target_arch = "wasm32"))]
fn announce_latest_toast(&mut self) {
if let Some(toast) = self.toasts.last_mut() {
toast.announce = true;
}
}
/// An error toast that stays until the user dismisses it (for a problem that persists and
/// is reported once, like a texture set the GPU could not hold).
pub fn toast_sticky(&mut self, text: impl Into<String>) {
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, announce: false });
self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false, action: None, announce: false });
}
/// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything
@@ -968,39 +994,56 @@ impl TextureCraftApp {
}
}
/// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps, the running set keeps the maps it finished
/// 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 };
let mut discarded = None;
let mut worker_failed = false;
if let Some(mut running) = job.current {
running.progress.cancel.store(true, Ordering::Relaxed);
running.progress.cancel();
let set_index = running.set_index;
// The maps the worker sent that no frame has taken yet are finished too
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(running.set_index, map.map);
}
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);
}
// Maps baked for a mesh that has since been replaced are never kept
let same_mesh = job.mesh_id == self.session.mesh_id;
let kept = match same_mesh {
true => {
self.session.keep_canceled_bake(running.set_index, running.finished, &running.sources, running.painted_stroke).unwrap_or_else(|error| {
self.toast(error.to_string(), true);
Vec::new()
})
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);
}
}
}
false => Vec::new(),
};
if kept.is_empty() {
discarded = Some(running.set_index);
}
}
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
@@ -1288,8 +1331,14 @@ impl eframe::App for TextureCraftApp {
let focused = ctx.input(|input| input.viewport().focused).unwrap_or(true);
if focused && !self.focused {
self.library = None;
// Files may have been edited in another app meanwhile
#[cfg(not(target_arch = "wasm32"))]
resources_updater::check_files(self);
}
self.focused = focused;
#[cfg(not(target_arch = "wasm32"))]
resources_updater::follow_project(self);
let scale = self.ui.prefs.ui_scale.clamp(*UI_SCALE_APPLIED.start(), *UI_SCALE_APPLIED.end());
if (ctx.zoom_factor() - scale).abs() > SAME_ZOOM_TOLERANCE {
@@ -1530,14 +1579,17 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
if app.toasts.iter().any(|t| t.until.is_finite()) {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
let tk = theme::Tokens::get(ctx);
let mut dismissed = None;
let mut show_log = false;
let mut clicked_action = None;
// Limit toast dimensions so the dismiss button stays visible
let screen = ctx.content_rect().size();
let max_width = (screen.x - 52.0).clamp(120.0, 360.0);
let max_text_height = (screen.y * 0.35).clamp(48.0, 220.0);
egui::Area::new(egui::Id::unique("toasts")).anchor(egui::Align2::RIGHT_BOTTOM, egui::vec2(-16.0, -36.0)).show(ctx, |ui| {
for (i, t) in app.toasts.iter().enumerate() {
egui::Frame::NONE
@@ -1555,15 +1607,23 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.allocate_ui_with_layout(egui::vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::ScrollArea::vertical().id_salt(("toast", i)).max_height(max_text_height).show(ui, |ui| {
ui.set_max_width(width);
let label = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
if t.announce {
ui.ctx().accesskit_node_builder(label.id, |node| node.set_live(egui::accesskit::Live::Polite));
let message = ui.add(egui::Label::new(egui::RichText::new(&t.text).color(tk.text_strong)).wrap());
if t.announce || t.action.is_some() {
ui.ctx().accesskit_node_builder(message.id, |node| node.set_live(egui::accesskit::Live::Polite));
}
});
if t.show_log && ui.link(i18n::tr("Open Log")).clicked() {
show_log = true;
dismissed = Some(i);
}
if let Some(action) = t.action {
let button = ui.button(i18n::tr(action.label()));
button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, i18n::tr(action.accessible_name())));
if button.clicked() {
clicked_action = Some(action);
dismissed = Some(i);
}
}
});
if sticky && widgets::icon_button(ui, egui_phosphor::regular::X, i18n::tr("Dismiss"), false, 18.0).clicked() {
dismissed = Some(i);
@@ -1573,6 +1633,7 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
ui.add_space(4.0);
}
});
if let Some(i) = dismissed.filter(|i| *i < app.toasts.len()) {
app.toasts.remove(i);
}
@@ -1581,4 +1642,8 @@ fn toasts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.ui.log_channel = log_panel::LogChannel::General;
crate::rail_popup::open(app, crate::docking::Panel::Log);
}
if let Some(action) = clicked_action {
action.run(app);
}
}
+5 -3
View File
@@ -126,9 +126,7 @@ impl TextureCraftApp {
}
}
if let Some(toast) = self.toasts.last_mut() {
toast.announce = true;
}
self.announce_latest_toast();
}
}
@@ -232,6 +230,10 @@ mod tests {
assert!(h.state().session.modified);
assert_eq!(h.state().ui.windows.unsaved, Some(Unsaved::Quit));
assert!(prompt_is_usable(&h), "the prompt answers again after the failed write");
let message = &h.state().toasts.iter().find(|toast| toast.error).expect("the failed write shows an error").text;
let announced = h.get_all_by_label(message).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite);
assert!(announced, "the save error is announced away from focus");
}
#[test]
+442
View File
@@ -0,0 +1,442 @@
//! The Resources Updater: the project's image resources and whether the files they were imported
//! from changed on disk. Update reads a changed file again, Select new resource points a resource
//! at another file, and a notice offers to update when the app gets the focus back after files
//! changed. Everything runs through `resource.status`, `resource.update` and `resource.relink`.
mod row_request;
use std::collections::BTreeSet;
use serde_json::json;
use texturecraft_engine::{ResourceState, ResourceStatus};
use crate::TextureCraftApp;
use crate::file_dialogs::{Bound, FileDialog};
use crate::i18n::{tr, trf};
use crate::state::ResourcesUpdater;
use crate::theme::Tokens;
use crate::toast_action::ToastAction;
use crate::web_files::IMAGE_EXTS;
use row_request::RowRequest;
/// Width of the window
const WINDOW_WIDTH_POINTS: f32 = 640.0;
/// Height of the resource list
const LIST_HEIGHT_POINTS: f32 = 360.0;
/// Initial space for the header, tabs, filters and footer
const WINDOW_CHROME_HEIGHT_POINTS: f32 = 160.0;
/// Side of a row's thumbnail
const THUMBNAIL_POINTS: f32 = 40.0;
/// Width of the name filter field
const NAME_FILTER_WIDTH_POINTS: f32 = 160.0;
/// Width of the status dropdown
const STATUS_WIDTH_POINTS: f32 = 120.0;
/// Space inside a row's frame
const ROW_MARGIN: egui::Margin = egui::Margin::same(4);
/// Strength of the danger tint behind an outdated row (the status text says it too)
const OUTDATED_TINT: f32 = 0.18;
/// How long the "changed on disk" notice stays, in seconds: long enough to reach its button
const NOTICE_SECONDS: f64 = 12.0;
/// Time between two checks while the window is open, in seconds (each check looks at every file; an unchanged one is not read)
const RECHECK_SECONDS: f64 = 0.5;
/// Opens the window, or closes it when it is open (the shelf button)
pub(crate) fn toggle(app: &mut TextureCraftApp) {
if app.ui.windows.resources_updater.take().is_none() {
open(app);
}
}
/// Opens the window with the resources checked now (an open window is checked again)
pub(crate) fn open(app: &mut TextureCraftApp) {
let window = app.ui.windows.resources_updater.take().unwrap_or_default();
app.ui.windows.resources_updater =
Some(ResourcesUpdater { rows: app.session.resource_states(), project: app.session.project_id, checked_at: app.last_time, ..window });
}
/// Check once when another project is open (files may have changed while it was closed), and
/// forget what was announced for the last one
pub(crate) fn follow_project(app: &mut TextureCraftApp) {
if !app.session.project_open || app.resources_project == Some(app.session.project_id) {
return;
}
app.resources_project = Some(app.session.project_id);
app.resources_notified.clear();
check_files(app);
}
/// Check the files again (the app has the focus back, or a project opened) and, when other
/// resources than last time are outdated, show a notice whose button updates them
pub(crate) fn check_files(app: &mut TextureCraftApp) {
if !app.session.project_open {
return;
}
let rows = app.session.resource_states();
let outdated: BTreeSet<String> = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).map(|row| row.name.clone()).collect();
if let Some(window) = app.ui.windows.resources_updater.as_mut() {
window.rows = rows;
window.checked_at = app.last_time;
}
if !outdated.is_empty() && outdated != app.resources_notified {
let text = if outdated.len() == 1 {
tr("1 resource changed on disk").to_string()
} else {
trf("{count} resources changed on disk", &[("count", &outdated.len())])
};
app.toast(text, false);
if let Some(toast) = app.toasts.last_mut() {
toast.until = app.last_time + NOTICE_SECONDS;
toast.action = Some(ToastAction::UpdateResources { project: app.session.project_id });
}
}
app.resources_notified = outdated;
}
/// Read the files of `names` again (every outdated resource when None), one undo step, and say
/// what happened
pub(crate) fn update(app: &mut TextureCraftApp, names: Option<Vec<String>>) {
let params = match names {
Some(names) => json!({ "names": names }),
None => json!({}),
};
let Some(result) = app.run("resource.update", params) else {
app.announce_latest_toast();
return;
};
let updated = result["updated"].as_array().map_or(0, Vec::len);
let failed: Vec<String> = result["failed"]
.as_array()
.into_iter()
.flatten()
.map(|failure| format!("{}: {}", failure["name"].as_str().unwrap_or_default(), failure["error"].as_str().unwrap_or_default()))
.collect();
if failed.is_empty() {
app.toast(trf("Updated {count} resources", &[("count", &updated)]), false);
} else {
app.toast(trf("Updated {count} resources; could not update {failed}", &[("count", &updated), ("failed", &failed.join("; "))]), true);
}
app.announce_latest_toast();
// What was announced is handled; a later change is announced again
app.resources_notified.clear();
}
/// Ask for another file for resource `name`; the resource takes its pixels and follows it
fn select_new_resource(app: &mut TextureCraftApp, name: String) {
let dialog = FileDialog::open().filter(tr("Images"), IMAGE_EXTS);
app.ask_file(dialog, Bound::Project, move |app, paths| {
let Some(path) = paths.first() else { return };
let Some(path) = path.to_str() else {
app.toast(trf("Could not use a path that is not UTF-8: {path}", &[("path", &path.display())]), true);
app.announce_latest_toast();
return;
};
if app.run("resource.relink", json!({ "name": name, "path": path })).is_some() {
app.toast(trf("{name} now reads {path}", &[("name", &name), ("path", &path)]), false);
}
app.announce_latest_toast();
});
}
/// Show the folder holding `path` in the system's file manager
fn show_in_folder(app: &mut TextureCraftApp, path: &str) {
let folder = std::path::Path::new(path).parent().map(std::path::Path::to_path_buf).unwrap_or_default();
if let Err(error) = app.file_dialogs.show_folder(&folder) {
app.toast(trf("Could not show {folder}: {error}", &[("folder", &folder.display()), ("error", &error)]), true);
app.announce_latest_toast();
}
}
/// Whether `row` passes the window's status and name filters
fn shown(window: &ResourcesUpdater, row: &ResourceState) -> bool {
let name_filter = window.name_filter.trim().to_lowercase();
window.status_filter.is_none_or(|status| row.status == status) && (name_filter.is_empty() || row.name.to_lowercase().contains(&name_filter))
}
/// "(N resources, M outdated)"
fn summary(rows: &[ResourceState]) -> String {
let outdated = rows.iter().filter(|row| row.status == ResourceStatus::Outdated).count();
trf("({count} resources, {outdated} outdated)", &[("count", &rows.len()), ("outdated", &outdated)])
}
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(mut window) = app.ui.windows.resources_updater.take() else { return };
// Drop the window state when its project closes or changes
if window.project != app.session.project_id || !app.session.project_open {
return;
}
// Files changed on disk and document changes (undo, a removed resource) show while the window stays open
let wait = window.checked_at + RECHECK_SECONDS - app.last_time;
if wait <= 0.0 {
window.rows = app.session.resource_states();
window.checked_at = app.last_time;
ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK_SECONDS));
} else {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait));
}
// Only close on Escape when the window owned keyboard focus
// Read raw input because egui consumes Escape when it clears focus
let escape = ctx.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
if window.had_keyboard && escape && !egui::Popup::is_any_open(ctx) {
return;
}
let tokens = Tokens::get(ctx);
let mut window_open = true;
let (mut refresh, mut update_all) = (false, false);
let mut request = None;
let shown = crate::windows::dialog(ctx, "resources_updater", tr("Resources Updater"), &mut window_open)
.default_size(egui::vec2(WINDOW_WIDTH_POINTS, LIST_HEIGHT_POINTS + WINDOW_CHROME_HEIGHT_POINTS))
.show(ctx, |ui| {
ui.label(format!("{} {}", tr("Project :"), app.session.doc.project.name));
let tab = ui.add(egui::Button::selectable(true, tr("Resources")));
tab.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, true, tr("Resources")));
ui.separator();
ui.horizontal(|ui| {
let status_label = ui.label(tr("Status:"));
let selected = window.status_filter.map_or(tr("All"), |status| tr(status.label()));
egui::ComboBox::from_id_salt("resources_updater_status")
.width(STATUS_WIDTH_POINTS)
.selected_text(selected)
.show_ui(ui, |ui| {
ui.selectable_value(&mut window.status_filter, None, tr("All"));
for status in ResourceStatus::ALL {
ui.selectable_value(&mut window.status_filter, Some(status), tr(status.label()));
}
})
.response
.labelled_by(status_label.id);
let name_label = ui.label(tr("Name filter:"));
ui.add(egui::TextEdit::singleline(&mut window.name_filter).desired_width(NAME_FILTER_WIDTH_POINTS)).labelled_by(name_label.id);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Bottom")).clicked() {
window.jump = Some(egui::Align::Max);
}
if ui.button(tr("Top")).clicked() {
window.jump = Some(egui::Align::Min);
}
});
});
ui.add_space(4.0);
ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| {
ui.horizontal(|ui| {
let refresh_button = ui.button(tr("Refresh"));
refresh_button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Refresh resources")));
refresh = refresh_button.clicked();
let count = ui.label(summary(&window.rows));
ui.ctx().accesskit_node_builder(count.id, |node| node.set_live(egui::accesskit::Live::Polite));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let outdated = window.rows.iter().any(|row| row.status == ResourceStatus::Outdated);
let label = egui::RichText::new(tr("Update All")).color(tokens.text_strong);
let action = egui::Button::new(label).fill(tokens.accent_dim).stroke(egui::Stroke::new(1.0, tokens.text_dim));
let button = ui.add_enabled(outdated, action);
update_all = button.on_disabled_hover_text(tr("No resource is outdated")).clicked();
});
});
ui.separator();
let list_height = ui.available_height().max(0.0);
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, false]).show(ui, |ui| {
let jump = window.jump.take();
if jump == Some(egui::Align::Min) {
ui.scroll_to_cursor(Some(egui::Align::Min));
}
let visible: Vec<&ResourceState> = window.rows.iter().filter(|row| shown(&window, row)).collect();
if visible.is_empty() {
ui.label(tr("No resources match the filters"));
}
for (index, row) in visible.into_iter().enumerate() {
// Keep keyboard focus with the resource when rows move
let row_scope = egui::UiBuilder::new().scope_id(ui.scope_id().with(("resources_updater_row", &row.name)));
let asked = ui.scope_builder(row_scope, |ui| row_ui(app, ui, &tokens, index + 1, row)).inner;
if let Some(asked) = asked {
request = Some(asked);
}
}
if jump == Some(egui::Align::Max) {
ui.scroll_to_cursor(Some(egui::Align::Max));
}
});
});
});
});
let focused = ctx.memory(|memory| memory.focused()).and_then(|id| ctx.read_response(id));
window.had_keyboard = shown.as_ref().zip(focused.as_ref()).is_some_and(|(shown, focused)| focused.layer_id == shown.response.layer_id);
if !window_open {
return;
}
app.ui.windows.resources_updater = Some(window);
// Its own changes and Refresh show at once
let check_now = refresh || update_all || matches!(request, Some(RowRequest::Update(_)));
if update_all {
update(app, None);
}
match request {
Some(RowRequest::Update(name)) => update(app, Some(vec![name])),
Some(RowRequest::SelectNew(name)) => select_new_resource(app, name),
Some(RowRequest::ShowFolder(path)) => show_in_folder(app, &path),
None => {}
}
if check_now {
open(app);
}
}
/// One resource: its thumbnail, number, name, file and status, and its buttons. Outdated rows are
/// tinted, and their status says so in words too.
fn row_ui(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, number: usize, row: &ResourceState) -> Option<RowRequest> {
let outdated = row.status == ResourceStatus::Outdated;
let (fill, stroke) = if outdated {
(tokens.danger.gamma_multiply(OUTDATED_TINT), egui::Stroke::new(1.0, tokens.danger))
} else {
(egui::Color32::TRANSPARENT, egui::Stroke::NONE)
};
let mut request = None;
egui::Frame::NONE.fill(fill).stroke(stroke).inner_margin(ROW_MARGIN).corner_radius(crate::theme::CARD_RADIUS).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
match app.session.images.get(&row.name) {
Some(image) => {
let (rect, preview) = ui.allocate_exact_size(egui::Vec2::splat(THUMBNAIL_POINTS), egui::Sense::hover());
preview.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, &row.name));
if ui.is_rect_visible(rect) {
let texture = app.thumbs.image(ui.ctx(), &row.name, image);
egui::Image::new(&texture).paint_at(ui, rect);
}
}
// Reserve thumbnail space for images that failed to decode
None => ui.add_space(THUMBNAIL_POINTS),
}
ui.label(number.to_string());
// Reserve space for the buttons before truncating the labels
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let update = ui.add_enabled(outdated, egui::Button::new(tr("Update")));
let update_name = format!("{} {}", tr("Update"), row.name);
update.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, outdated, &update_name));
if update.clicked() {
request = Some(RowRequest::Update(row.name.clone()));
}
// Only images can be relinked to disk
let material = row.status == ResourceStatus::Material;
if !material {
let select = ui.button(tr("Select new resource"));
let select_name = format!("{} {}", tr("Select new resource"), row.name);
select.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &select_name));
if select.clicked() {
request = Some(RowRequest::SelectNew(row.name.clone()));
}
}
if let Some(path) = &row.path {
let folder = ui.button(tr("Show in folder"));
let folder_name = format!("{} {}", tr("Show in folder"), row.name);
folder.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &folder_name));
if folder.clicked() {
request = Some(RowRequest::ShowFolder(path.clone()));
}
}
ui.vertical(|ui| {
ui.add(egui::Label::new(format!("{} {}", tr("Name :"), row.name)).truncate());
ui.label(format!("{} {}", tr("Shelf :"), tr("project")));
let file = row.path.as_deref().unwrap_or(tr("No source file"));
ui.add(egui::Label::new(format!("{} {}", tr("File :"), file)).truncate()).on_hover_text(file);
let status = ui.label(tr(row.status.label()));
let detail = row
.error
.as_deref()
.or_else(|| material.then(|| tr("This MaterialCraft package is stored in the project. Its cooked maps are separate image resources.")));
if let Some(detail) = detail {
ui.ctx().accesskit_node_builder(status.id, |node| node.set_description(detail));
status.on_hover_text(detail);
}
});
});
});
});
request
}
#[cfg(test)]
mod tests {
use std::sync::PoisonError;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT as _, Queryable as _};
use texturecraft_engine::Session;
use super::*;
fn write_png(path: &std::path::Path, size: u32) {
image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(path).unwrap();
}
fn notices(app: &TextureCraftApp) -> Vec<ToastAction> {
app.toasts.iter().filter_map(|toast| toast.action).collect()
}
#[test]
fn a_changed_file_is_announced_once_and_the_notice_updates_it() {
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(PoisonError::into_inner);
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("notice.png");
write_png(&path, 4);
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(2);
let app = harness.state_mut();
let name = app.run("resource.import", json!({ "path": path.to_str().unwrap() })).unwrap()["name"].as_str().unwrap().to_string();
check_files(app);
assert!(notices(app).is_empty(), "nothing changed yet");
write_png(&path, 8);
check_files(app);
check_files(app);
let announced = notices(app);
assert_eq!(announced, [ToastAction::UpdateResources { project: app.session.project_id }], "the same change is announced once");
// A notice about another project does nothing
ToastAction::UpdateResources { project: app.session.project_id + 1 }.run(app);
assert_eq!(app.session.images[&name].width, 4);
harness.run_steps(2);
let message = harness.get_by_label("1 resource changed on disk");
assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite, "the notice is announced away from focus");
harness.get_by_role_and_label(egui::Role::Button, "Update resources").focus();
harness.run_steps(2);
harness.key_press(egui::Key::Enter);
harness.run_steps(2);
let app = harness.state();
assert_eq!(app.session.images[&name].width, 8, "the notice's button updated the resource");
assert_eq!(app.session.history_labels().last().map(String::as_str), Some("Update resources"));
}
}
@@ -0,0 +1,9 @@
/// What a Resources Updater row's buttons asked for, run after the window is drawn
pub(super) enum RowRequest {
/// Update: read the resource's file again
Update(String),
/// Select new resource: ask for another file for the resource
SelectNew(String),
/// Show in folder: the folder holding this file
ShowFolder(String),
}
+5
View File
@@ -14,11 +14,13 @@ mod import_row;
mod library_location;
mod project_config;
mod resource_usage;
mod resources_updater;
pub use import_resources::ImportResources;
pub use import_row::ImportRow;
pub use library_location::LibraryLocation;
pub use project_config::ProjectConfig;
pub use resource_usage::ResourceUsage;
pub use resources_updater::ResourcesUpdater;
mod console_line;
mod export_job;
@@ -115,6 +117,9 @@ pub struct Windows {
/// File > Import resources: the files added so far, imported by Import.
#[serde(skip)]
pub import_resources: Option<ImportResources>,
/// The Resources Updater: the project's image resources and whether their files changed on disk.
#[serde(skip)]
pub resources_updater: Option<ResourcesUpdater>,
/// What waits on the unsaved-changes dialog: save, don't save or cancel.
#[serde(skip)]
pub unsaved: Option<Unsaved>,
@@ -0,0 +1,21 @@
use texturecraft_engine::{ResourceState, ResourceStatus};
/// The Resources Updater window: the project's image resources as last checked, and the filters
#[derive(Clone, Debug, PartialEq, Default)]
pub struct ResourcesUpdater {
/// The resources and how they compare with their files, outdated first (checked on opening,
/// Refresh, twice a second while open and when the app gets the focus back)
pub rows: Vec<ResourceState>,
/// The status the list is narrowed to (None: all)
pub status_filter: Option<ResourceStatus>,
/// Shows only resources whose name contains this, ignoring case
pub name_filter: String,
/// Top or Bottom asked the list to scroll to that end in the next frame
pub jump: Option<egui::Align>,
/// The project that was open when this window opened
pub project: u64,
/// When the rows were checked, in app seconds
pub(crate) checked_at: f64,
/// Whether a control of the window had the keyboard focus when it was last drawn (Escape then closes it)
pub(crate) had_keyboard: bool,
}
+41
View File
@@ -0,0 +1,41 @@
//! A button on a toast that acts on what the toast says
use crate::TextureCraftApp;
/// What a toast's button does
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ToastAction {
/// "Update": read every outdated resource file of `project` again (the desktop's "changed on disk" notice)
UpdateResources {
/// The project the notice is about; the button does nothing once another one is open
project: u64,
},
}
impl ToastAction {
/// The button's text (English; translated where it is drawn)
pub fn label(self) -> &'static str {
match self {
ToastAction::UpdateResources { .. } => "Update",
}
}
/// The button's accessible name, which says what it acts on (English; translated where it is drawn)
pub fn accessible_name(self) -> &'static str {
match self {
ToastAction::UpdateResources { .. } => "Update resources",
}
}
pub(crate) fn run(self, app: &mut TextureCraftApp) {
match self {
// Another project's notice is stale
ToastAction::UpdateResources { project } if project != app.session.project_id => {}
#[cfg(not(target_arch = "wasm32"))]
ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None),
// The browser has no files to read again
#[cfg(target_arch = "wasm32")]
ToastAction::UpdateResources { .. } => {}
}
}
}
+23 -5
View File
@@ -510,15 +510,33 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
ui.add_space(SHELF_GROUP_GAP);
}
for (icon, label) in [(ic::HOURGLASS, "Snooze Autosave"), (ic::ARROWS_CLOCKWISE, "Resources Updater")] {
ui.add_enabled_ui(false, |ui| icon_button(ui, icon, tr(label), false, SHELF_BUTTON_SIZE))
.inner
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
}
ui.add_enabled_ui(false, |ui| icon_button(ui, ic::HOURGLASS, tr("Snooze Autosave"), false, SHELF_BUTTON_SIZE))
.inner
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
resources_updater_button(app, ui);
});
});
}
/// The shelf's Resources Updater button: opens or closes its window while a project is open
#[cfg(not(target_arch = "wasm32"))]
fn resources_updater_button(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
let open = app.ui.windows.resources_updater.is_some();
let label = tr("Resources Updater");
let button = ui.add_enabled_ui(app.session.project_open, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, label, open, SHELF_BUTTON_SIZE)).inner;
if button.on_disabled_hover_text(tr("Open a project to check its resources")).clicked() {
crate::resources_updater::toggle(app);
}
}
/// The browser reads no files from disk, so there is nothing to update
#[cfg(target_arch = "wasm32")]
fn resources_updater_button(_: &mut TextureCraftApp, ui: &mut egui::Ui) {
ui.add_enabled_ui(false, |ui| icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Resources Updater"), false, SHELF_BUTTON_SIZE))
.inner
.on_disabled_hover_text(tr(crate::unavailable::NOT_AVAILABLE));
}
/// Width of the icon rail beside the dock
const RAIL_WIDTH: f32 = 38.0;
+1
View File
@@ -298,6 +298,7 @@ mod tests {
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, rebake: None });
assert!(!safe_to_close(h.state()), "a bake");
h.state_mut().bake = None;
+1
View File
@@ -23,6 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
{
crate::project_config::show(app, ctx);
crate::import_resources::show(app, ctx);
crate::resources_updater::show(app, ctx);
}
crate::keymap::window(app, ctx);
crate::export_window::show(app, ctx);
+4
View File
@@ -80,8 +80,10 @@ fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_al
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);
@@ -154,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();
}
@@ -167,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());
+1
View File
@@ -42,6 +42,7 @@ fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() {
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();
+17 -1
View File
@@ -72,13 +72,14 @@ 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 (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();
@@ -88,3 +89,18 @@ fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() {
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");
}
+5 -1
View File
@@ -703,7 +703,7 @@ 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;
// Two sets show every hover icon (sync, Auto-rebake, bolt, eye) and the changed settings add the out-of-date clock
// 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);
@@ -711,6 +711,7 @@ fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing
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");
@@ -730,10 +731,12 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() {
.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");
@@ -748,6 +751,7 @@ fn dragging_secondary_rays_is_one_undo_step() {
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 {
+14 -3
View File
@@ -33,11 +33,11 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) {
}
/// 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>, set_1_maps: &[BakedMap]) {
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(set_1_maps.iter().copied());
set.bake.maps.select(failed_set_maps.iter().copied());
harness.state_mut().start_bake(vec![0, 1]);
run_to_the_end(harness);
@@ -66,6 +66,7 @@ fn a_failed_rows_reason_is_read_without_hovering() {
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");
@@ -87,6 +88,7 @@ fn a_one_map_bake_lists_only_that_map() {
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
@@ -105,7 +107,7 @@ fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() {
assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns");
}
// A map the worker sent before the cancel is kept too, so whether set 0's Position finished depends on timing
// 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();
@@ -128,6 +130,7 @@ fn a_failed_maps_arrow_opens_its_settings() {
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");
@@ -171,6 +174,7 @@ fn the_issues_filter_keeps_only_the_maps_with_a_problem() {
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);
@@ -180,6 +184,7 @@ fn the_issues_filter_says_so_when_nothing_went_wrong() {
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");
}
@@ -193,6 +198,7 @@ fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() {
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");
@@ -200,6 +206,7 @@ fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() {
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");
}
@@ -244,8 +251,10 @@ fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partn
#[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);
@@ -264,6 +273,7 @@ fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() {
.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();
@@ -295,6 +305,7 @@ fn a_matching_name_cut_short_shows_in_full_on_hover() {
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");
@@ -50,11 +50,13 @@ fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() {
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");
}
@@ -65,8 +67,10 @@ fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() {
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)));
+5 -3
View File
@@ -86,6 +86,7 @@ mod rail;
mod reference_order;
mod rename_anchor;
mod reset_ui;
mod resources_updater;
mod sample_project;
mod settings_window;
mod shelf_click;
@@ -196,12 +197,13 @@ 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");
}
/// Most frames [`step_until`] waits, and its pause between them for background work
/// 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>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) {
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()) {
@@ -210,7 +212,7 @@ fn step_until(harness: &mut Harness<'_, TextureCraftApp>, what: &str, done: impl
std::thread::sleep(STEP_UNTIL_PAUSE);
}
panic!("{what} did not happen");
panic!("{expected_event} did not happen");
}
/// Presses and releases the primary button at `at` without moving, as a pointer click does
@@ -0,0 +1,240 @@
//! The Resources Updater window, driven from the keyboard: the shelf button opens it, outdated
//! resources come first, Update reads a changed file again as one undo step and Select new resource
//! follows another file. File pickers are answered by the override, never shown.
use std::path::{Path, PathBuf};
use egui::{Key, Role, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::file_dialogs::{Answer, Request};
use texturecraft_ui_egui::state::ViewLayout;
use super::temp_dir::TempDir;
fn app() -> Harness<'static, TextureCraftApp> {
let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap();
let mut h = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.prefs.language = "en".into();
h.run_steps(4);
h
}
/// Write a `size` × `size` PNG (each size is a different file size, so a change is seen at once)
fn png(dir: &Path, name: &str, size: u32) -> PathBuf {
let file = dir.join(name);
image::RgbaImage::from_pixel(size, size, image::Rgba([10, 200, 30, 255])).save(&file).unwrap();
file
}
fn import(h: &mut Harness<'_, TextureCraftApp>, file: &Path) {
h.state_mut().run("resource.import", json!({ "path": file.to_str().unwrap() })).unwrap();
h.run_steps(2);
}
fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) {
h.key_press(key);
h.run_steps(3);
}
/// Move the keyboard focus to button `label` and press Enter
fn activate(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
h.get_by_role_and_label(Role::Button, label).focus();
h.run_steps(2);
press(h, Key::Enter);
}
fn shows(h: &Harness<'_, TextureCraftApp>, text: &str) -> bool {
h.query_by_label(text).is_some()
}
fn width_of(h: &Harness<'_, TextureCraftApp>, name: &str) -> u32 {
h.state().session.images[name].width
}
#[test]
fn the_window_opens_from_the_keyboard_and_updates_an_outdated_resource_as_one_undo_step() {
let dir = TempDir::new("resources-updater-update");
let (kept, changed) = (png(&dir, "aa_kept.png", 4), png(&dir, "zz_changed.png", 4));
let mut h = app();
import(&mut h, &kept);
import(&mut h, &changed);
png(&dir, "zz_changed.png", 8);
activate(&mut h, "Resources Updater");
let rows = &h.state().ui.windows.resources_updater.as_ref().expect("the window is open").rows;
assert_eq!(rows[0].name, "zz_changed.png", "outdated resources come first, before names that sort earlier");
assert!(shows(&h, "Project : Test"));
assert_eq!(h.get_all_by_label("Shelf : project").count(), 2, "the reference's shelf line, one per row");
assert!(shows(&h, "(2 resources, 1 outdated)"));
assert!(shows(&h, "Outdated"), "the status is written out, not only coloured");
assert!(h.get_by_role_and_label(Role::Button, "Update aa_kept.png").accesskit_node().is_disabled(), "only outdated resources update");
let steps = h.state().session.history_labels().len();
activate(&mut h, "Update zz_changed.png");
assert_eq!(width_of(&h, "zz_changed.png"), 8, "the new file's pixels are in the project");
assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step");
assert!(shows(&h, "(2 resources, 0 outdated)"));
let result = h.get_by_label("Updated 1 resources");
assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the update result is announced away from focus");
// Undo brings the old pixels back, so Refresh shows the file as changed again
h.state_mut().run("edit.undo", json!({})).unwrap();
activate(&mut h, "Refresh resources");
assert_eq!(width_of(&h, "zz_changed.png"), 4);
assert!(shows(&h, "(2 resources, 1 outdated)"));
activate(&mut h, "Update All");
assert_eq!(width_of(&h, "zz_changed.png"), 8);
// Update All went grey with nothing left to update; the keyboard moves on to another button of the window
h.get_by_role_and_label(Role::Button, "Select new resource aa_kept.png").focus();
h.run_steps(2);
press(&mut h, Key::Escape);
assert!(h.state().ui.windows.resources_updater.is_none(), "Escape closes the window while it has the keyboard");
}
#[test]
fn select_new_resource_follows_the_chosen_file_and_the_name_filter_narrows_the_list() {
let dir = TempDir::new("resources-updater-relink");
let (first, second) = (png(&dir, "first.png", 4), png(&dir, "second.png", 4));
let other = png(&dir, "other.png", 16);
let mut h = app();
import(&mut h, &first);
import(&mut h, &second);
activate(&mut h, "Resources Updater");
h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![other.clone()]))));
activate(&mut h, "Select new resource first.png");
h.run_steps(3);
assert_eq!(width_of(&h, "first.png"), 16, "the resource keeps its name and takes the chosen file's pixels");
let source = &h.state().session.doc.project.resource_sources["first.png"].path;
assert!(source.ends_with("other.png"));
let announcement = format!("first.png now reads {source}");
let result = h.get_by_label(&announcement);
assert_eq!(result.accesskit_node().live(), egui::accesskit::Live::Polite, "the relink result is announced away from focus");
h.get_by_role_and_label(Role::TextInput, "Name filter:").focus();
h.run_steps(2);
h.get_by_role_and_label(Role::TextInput, "Name filter:").type_text("SEC");
h.run_steps(3);
assert!(h.query_by_label("Update first.png").is_none(), "the filter hides other names");
assert!(h.query_by_label("Update second.png").is_some(), "names match ignoring case");
}
#[test]
fn show_in_folder_shows_the_folder_of_the_resource_file_and_materials_have_no_file() {
let dir = TempDir::new("resources-updater-folder");
let file = png(&dir, "bricks.png", 4);
let mut h = app();
import(&mut h, &file);
// A linked MaterialCraft material keeps its package as a resource without a file
let layer = h.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap();
let session = &mut h.state_mut().session;
session.doc.resources.insert("brick.mcmat".to_string(), std::sync::Arc::new(b"package".to_vec()));
let link = serde_json::from_value(json!({"name": "Brick", "package": "brick.mcmat", "graph": "Brick", "params": [], "size": 4})).unwrap();
if let texturecraft_engine::core::LayerKind::Fill(fill) = &mut session.doc.project.layers.get_mut(&texturecraft_engine::core::LayerId(layer)).unwrap().kind
{
fill.link = Some(link);
}
activate(&mut h, "Resources Updater");
activate(&mut h, "Show in folder bricks.png");
let shown = h.state().file_dialogs.shown_folders().to_vec();
assert_eq!(shown.len(), 1);
assert_eq!(shown[0].file_name(), dir.file_name(), "the file's own folder");
assert!(shows(&h, "Name : brick.mcmat"), "the material is listed");
assert!(h.query_by_label("Select new resource brick.mcmat").is_none(), "a material cannot point at an image file");
assert!(h.query_by_label("Show in folder brick.mcmat").is_none(), "it has no file");
assert!(h.get_by_label("Update brick.mcmat").accesskit_node().is_disabled());
assert!(
h.get_all_by_label("Material").any(|node| node.accesskit_node().description().is_some_and(|text| text.contains("stored in the project"))),
"the material status explains the stored package in the accessibility tree"
);
}
#[test]
fn escape_cancels_a_stroke_while_the_window_is_open_without_the_keyboard() {
const FRAMES_PER_DRAG_EVENT: usize = 2;
let mut h = app();
h.state_mut().run("layer.add.paint", json!({})).unwrap();
h.state_mut().ui.layout = ViewLayout::Only3D;
h.run_steps(3);
let center = h.state().viewport_rect.center();
h.drag_at(center);
h.run_steps(FRAMES_PER_DRAG_EVENT);
h.hover_at(center + vec2(20.0, 0.0));
h.run_steps(FRAMES_PER_DRAG_EVENT);
assert!(h.state().session.stroke_active());
// Opened from the shelf mid-stroke, the keyboard stays on the shelf button
activate(&mut h, "Resources Updater");
assert!(h.state().ui.windows.resources_updater.is_some());
assert!(h.state().session.stroke_active());
press(&mut h, Key::Escape);
assert!(!h.state().session.stroke_active(), "Escape cancels the stroke");
assert!(h.state().ui.windows.resources_updater.is_some(), "the window keeps open: its controls do not have the keyboard");
h.drop_at(center + vec2(30.0, 0.0));
h.run_steps(3);
}
#[test]
fn a_file_changed_while_the_window_stays_open_shows_without_refresh() {
/// Steps of the harness's quarter second: over the window's half-second check
const FRAMES: usize = 4;
let dir = TempDir::new("resources-updater-idle");
let file = png(&dir, "bricks.png", 4);
let mut h = app();
import(&mut h, &file);
activate(&mut h, "Resources Updater");
assert!(shows(&h, "(1 resources, 0 outdated)"));
png(&dir, "bricks.png", 8);
h.run_steps(FRAMES);
let summary = h.get_by_label("(1 resources, 1 outdated)");
assert_eq!(summary.accesskit_node().live(), egui::accesskit::Live::Polite, "an idle change is announced away from keyboard focus");
}
#[test]
fn the_keyboard_focus_stays_with_its_resource_when_the_rows_reorder() {
/// Steps of the harness's quarter second: over the window's half-second check
const FRAMES: usize = 4;
const SELECT_LATER: &str = "Select new resource zz_later.png";
let dir = TempDir::new("resources-updater-focus");
let (earlier, later) = (png(&dir, "aa_earlier.png", 4), png(&dir, "zz_later.png", 4));
let mut h = app();
import(&mut h, &earlier);
import(&mut h, &later);
activate(&mut h, "Resources Updater");
h.get_by_role_and_label(Role::Button, SELECT_LATER).focus();
h.run_steps(2);
// The changed file moves to the top of the list
png(&dir, "zz_later.png", 8);
h.run_steps(FRAMES);
let rows = &h.state().ui.windows.resources_updater.as_ref().unwrap().rows;
assert_eq!(rows[0].name, "zz_later.png", "the outdated resource moved up");
assert!(h.get_by_role_and_label(Role::Button, SELECT_LATER).accesskit_node().is_focused(), "the focus moved with it");
}
+35 -7
View File
@@ -235,14 +235,14 @@ keeps its state in a throwaway file.
| `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history |
| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) |
| `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` |
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": "<layout>"}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
| `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": "<layout>"}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave button and the Resources Updater button (enabled while a project is open) stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) |
| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a picker for a `.tcraft` file. On desktop, it copies any missing bundled samples (currently `Material Ball.tcraft`) into `Samples` under the data folder and opens the picker there. If preparation fails, it shows an error and opens the picker without a start folder. In the browser, the picker uses local files. The direct `project.sample` engine command generates a sample for automation. |
| `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled |
| `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft_<version>_<date>_<os>_<gpuMode>.txt` name, a download on the web) |
| `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 finished (one undo step), 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 |
@@ -286,8 +286,8 @@ same as a single bake's. `bake.run` and the CLI bake all maps at once and never
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 applies the maps the set it was
baking had finished (one undo step; none when the bake had a new output size, since they would replace
the set's other maps), while sets that finished before the cancel stay applied. When
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.
@@ -328,7 +328,9 @@ with no partner. It is `null` when no set of the bake matches by mesh name:
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). Imported maps, and maps saved before this record existed, never show:
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
@@ -338,7 +340,7 @@ app is in Bake mode, an auto-rebake map that goes out of date is baked again on
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, keeping the rest; maps scaled by their whole range (curvature, height, thickness) are baked
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.
@@ -402,7 +404,8 @@ A `prefs` object without `language` sets the system language (`""`), the default
File › Save.
Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and
`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in
`file.reimportMesh` without a `path`) is refused, and so are `resource.status`, `resource.update` and `resource.relink` (they read
the files a project names) and any command given a `path` or `dir`, at the top level or in
a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text`
takes a font family, not a path: it reads only the system's font folders.
@@ -524,6 +527,31 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para
'{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve
```
## Resources Updater
An image resource read from a file remembers that file (its absolute path and modification time,
saved with the project): `resource.import {path}`, the images `file.importPbrFolder` stores unchanged
(not ORM channels split out, not archive entries), the images of `file.importMaterialX` and the files of
`textureSet.meshMap.import` (with their mesh map: an update resamples it while it still holds what the
old file gave it, so a bake or another image set over it since is kept). The shelf's Resources Updater
window lists the project's images and linked MaterialCraft packages. It checks image files when it opens, on
Refresh, twice a second while it stays open, once after a project opens and when the app gets the
focus back; a notice ("N resources changed on disk", with an Update button) appears when the set of
outdated resources differs from the last notice. A file whose size matches but whose time changed is
read once. Its verdict is kept until its size or time changes again. When the file has no usable
modification time, each check compares its contents.
| Command | Params and result |
|---|---|
| `resource.status` | `{}` → `{resources: [{name, status, path?, error?}], total, outdated}`; `status` is `outdated` (the file's size or contents differ from the resource), `missing` (the file is gone or unreadable, `error` says why), `upToDate`, `noSource` (made in the app or imported without a path) or `material` (the package of a linked MaterialCraft material, stored in the project without a source file); outdated first, then by name. An equal-size file is compared when its modification time changed or is unknown |
| `resource.update` | `{names?: [name]}` (default: every outdated resource) → `{updated, failed: [{name, error}]}`: reads the files again and replaces the resources' bytes and pixels under the same names, so every layer, mask and view using them recomposites; one undo step, none when nothing changed. A file that cannot be read fails alone; when none could be read the command is an error. Unknown names and resources without a file are refused |
| `resource.relink` | `{name, path}` → `{name, path}`: an image resource takes the image file's pixels (within the image import limits) and follows that file from then on; one undo step |
For linked fill layers, `material.link.cook` refreshes the separate cooked image maps from the stored package.
These commands read host paths stored in the project, so MCP and `serve` refuse them through
`command_run`; the desktop app's control channel and the trusted local CLI run them.
## PBR texture folders
`file.importPbrFolder` turns a folder, a `.zip` or a list of image files of PBR maps into one fill layer
+12 -2
View File
@@ -98,6 +98,15 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
and alpha images become the brush alpha. Filter by role or remove selected rows before importing.
Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are
unavailable. The browser imports images straight from its file picker.
- **Resources Updater:** the desktop tool shelf lists the project's image resources, with outdated
resources first. Filter by status or name, and use *Show in folder* to find a linked file. Images
imported from disk through Import resources, PBR folders, MaterialX and mesh map import remember
their source file. *Update* and *Update All* reread changed files in one undo step. Layers see the
updated image, and an imported mesh map refreshes while it still matches the previous source.
*Select new resource* links an image to another file. The list refreshes while the window is open,
and a notice offers *Update* when changed files are found on opening a project or regaining focus.
Linked MaterialCraft packages appear without a source file. Re-cooking a linked fill layer refreshes
its cooked maps.
- **Your own library:** right-click a layer or folder, choose *Create smart material*, and it
appears under *My smart materials*, pixels and images included. *Create smart mask* in the same
menu saves just the layer's mask (all its effects, painted pixels and images); it appears under
@@ -172,8 +181,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
`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; a skew or
cage stroke rebakes only the stroke's box. The first skew stroke turns it on for the Normal map.
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