From 3f38644c9145044126514f265f2230b8a69ae74d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:49:58 +0000 Subject: [PATCH 01/26] Dock the Baking Log at the bottom of the bake layout The default bake layout put the general Log under the settings columns; the Baking Log now takes that place (the Log stays in Window > Views). The bake layout version moves to 3 so saved bake docks pick up the new layout. --- crates/ui-egui/src/docking.rs | 10 +++++----- crates/ui-egui/src/state.rs | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 6c4f5f97..85edb126 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -308,7 +308,7 @@ impl Dock { self.replaced_unreadable } - /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport + /// Texture sets over the bakers, the two settings tabs, the Baking Log under both, then the viewport pub(crate) fn for_baking() -> Self { let painting = default_workspace(); let mut hidden = painting.hidden().to_vec(); @@ -318,14 +318,14 @@ impl Dock { } } - let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::BakingLog]; hidden.retain(|(panel, _)| !bake_panels.contains(panel)); let gutter_width = f32::from(crate::theme::GUTTER); let list_column = split(Axis::Y, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); let columns = split(Axis::X, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); - let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_over_log = split(Axis::Y, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::BakingLog])); let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; let root = split(Axis::X, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); let workspace = Workspace::from_parts(Layout::new(Some(root), Vec::new()), hidden, painting.floated().to_vec()); @@ -759,12 +759,12 @@ mod tests { } #[test] - fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + fn the_bake_dock_round_trips_with_the_baking_log_under_both_settings_columns() { let dock = Dock::for_baking(); assert!(validate(dock.workspace()).is_ok()); assert_eq!( panels_of(dock.workspace()), - [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::BakingLog, Panel::Viewport] ); assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 54daa752..ff897d80 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -543,7 +543,7 @@ fn default_true() -> bool { } /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` -const BAKE_LAYOUT_VERSION: u32 = 2; +const BAKE_LAYOUT_VERSION: u32 = 3; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { @@ -1018,6 +1018,24 @@ mod tests { } } + #[test] + fn a_saved_bake_dock_with_the_log_at_the_bottom_gets_the_baking_log_there() { + use crate::docking::Panel; + + let mut ui = UiState { mode: Mode::Baking, ..UiState::default() }; + ui.sync_mode_dock(); + ui.dock.close(Panel::BakingLog); + ui.dock.focus(Panel::Log); + let mut saved = serde_json::to_value(&ui).unwrap(); + saved["bake_layout_version"] = serde_json::json!(2); + + let mut loaded: UiState = serde_json::from_value(saved).unwrap(); + loaded.sync_mode_dock(); + + assert!(loaded.dock.is_visible(Panel::BakingLog), "the Baking Log takes the bottom of the bake layout"); + assert!(!loaded.dock.is_open(Panel::Log), "the general Log stays in Window > Views"); + } + #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { From 03600e447a7c1a0338d14f9da293ab54e4714fb7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:52:36 +0000 Subject: [PATCH 02/26] Record each bake map by map for the Baking Log The session keeps the latest bake as one row per texture set and map (waiting, baking, baked, failed, canceled), filled from the bake's own state by the app's background bake and by bake.run, never from Log lines. --- crates/engine/src/bake/bake_log.rs | 81 ++++++++++++++++++++++ crates/engine/src/bake/bake_log_map.rs | 15 ++++ crates/engine/src/bake/bake_map_state.rs | 26 +++++++ crates/engine/src/bake/mesh_map_command.rs | 34 +++++++-- crates/engine/src/bake/mod.rs | 6 ++ crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_log.rs | 50 +++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/lib.rs | 11 ++- 9 files changed, 220 insertions(+), 7 deletions(-) create mode 100644 crates/engine/src/bake/bake_log.rs create mode 100644 crates/engine/src/bake/bake_log_map.rs create mode 100644 crates/engine/src/bake/bake_map_state.rs create mode 100644 crates/engine/tests/it/bake_log.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs new file mode 100644 index 00000000..2f263cf2 --- /dev/null +++ b/crates/engine/src/bake/bake_log.rs @@ -0,0 +1,81 @@ +use serde::Serialize; +use texturecraft_core::{BakedMap, Project}; + +use super::{BakeLogMap, BakeMapState}; + +/// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines +#[derive(Clone, Debug, Default, PartialEq, Serialize)] +pub struct BakeLog { + pub maps: Vec, +} + +impl BakeLog { + /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order + pub fn begin(&mut self, project: &Project, sets: &[usize]) { + self.maps = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .flat_map(|(index, set)| { + set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) + }) + .collect(); + } + + /// `set` starts baking: its first map is the one in progress + pub fn set_started(&mut self, set: usize) { + self.start_next(set); + } + + /// `map` of `set` is baked; the set's next map starts + pub fn map_baked(&mut self, set: usize, map: BakedMap) { + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { + row.state = BakeMapState::Baked; + } + self.start_next(set); + } + + /// `set`'s bake was kept: a map it did not hand over is not baked + pub fn set_finished(&mut self, set: usize) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set && row.state.is_pending()) { + row.state = BakeMapState::Canceled; + } + } + + /// Nothing of `set` was kept: every one of its maps failed for `reason` + pub fn set_failed(&mut self, set: usize, reason: &str) { + for row in self.maps.iter_mut().filter(|row| row.texture_set == set) { + row.state = BakeMapState::Failed(reason.to_owned()); + } + } + + /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled + pub fn cancel(&mut self, current: Option) { + for row in &mut self.maps { + if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + row.state = BakeMapState::Canceled; + } + } + } + + /// The whole bake was rolled back: every map that did not fail is canceled + pub fn discard(&mut self) { + for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { + row.state = BakeMapState::Canceled; + } + } + + /// Whether a map is still waiting or baking + pub fn is_running(&self) -> bool { + self.maps.iter().any(|row| row.state.is_pending()) + } + + fn start_next(&mut self, set: usize) { + if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { + return; + } + + if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.state == BakeMapState::Waiting) { + row.state = BakeMapState::Baking; + } + } +} diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs new file mode 100644 index 00000000..4a04bd7d --- /dev/null +++ b/crates/engine/src/bake/bake_log_map.rs @@ -0,0 +1,15 @@ +use serde::Serialize; +use texturecraft_core::BakedMap; + +use super::BakeMapState; + +/// One row of the Baking Log's process list: a map of a texture set in the latest bake +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeLogMap { + pub texture_set: usize, + pub set_name: String, + pub map: BakedMap, + #[serde(flatten)] + pub state: BakeMapState, +} diff --git a/crates/engine/src/bake/bake_map_state.rs b/crates/engine/src/bake/bake_map_state.rs new file mode 100644 index 00000000..fec7583b --- /dev/null +++ b/crates/engine/src/bake/bake_map_state.rs @@ -0,0 +1,26 @@ +use serde::Serialize; + +/// Where one map of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeMapState { + Waiting, + Baking, + Baked, + /// The bake of its texture set failed; the reason is the error + Failed(String), + /// The bake stopped before this map was kept + Canceled, +} + +impl BakeMapState { + /// Whether the map can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Baking) + } + + /// Whether the map counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 844c533a..a76561fb 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,16 +843,21 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } + session.bake_log.begin(&session.doc.project, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { - let mut task = session.bake_task(index)?; - if cpu { - task.tracer = None; + session.bake_log.set_started(index); + let baked = bake_one_set(session, index, cpu); + match baked { + Ok(tracer) => tracers.push(tracer), + Err(error) => { + session.bake_log.set_failed(index, &error.to_string()); + // The edit rolls back the sets baked before this one too + session.bake_log.discard(); + return Err(error); + } } - let output = task.run(&Progress::new())?; - tracers.push(output.tracer.clone()); - session.store_bake(index, output)?; } Ok(tracers) })?; @@ -863,6 +868,23 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { Ok(json!({ "baked": sets, "tracer": tracers })) } +/// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log +fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { + let mut task = session.bake_task(index)?; + if cpu { + task.tracer = None; + } + + let maps = task.maps(); + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + session.store_bake(index, output)?; + for map in maps { + session.bake_log.map_baked(index, map); + } + Ok(tracer) +} + #[cfg(test)] mod named_tracer; diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 1be548db..736b00bb 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,6 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_log; +mod bake_log_map; +mod bake_map_state; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -19,6 +22,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_log::BakeLog; +pub use bake_log_map::BakeLogMap; +pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e1d83ead..f0a8df58 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -451,6 +451,8 @@ pub struct Session { pub solo: Option, /// The live bake preview while the app bakes (see [`crate::bake_preview`]). pub bake_preview: Option, + /// The latest bake, map by map (the Baking Log) + pub bake_log: crate::bake::BakeLog, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -543,6 +545,7 @@ impl Session { view_image: None, solo: None, bake_preview: None, + bake_log: Default::default(), viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs new file mode 100644 index 00000000..965295e1 --- /dev/null +++ b/crates/engine/tests/it/bake_log.rs @@ -0,0 +1,50 @@ +//! The Baking Log's record of the latest bake, map by map + +use std::collections::BTreeSet; + +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute, sample_session}; + +#[test] +fn bake_run_lists_every_checked_map_of_the_set_as_baked() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let set_name = &session.doc.project.texture_sets[0].name; + let rows = &session.bake_log.maps; + let maps: BTreeSet = rows.iter().map(|row| row.map).collect(); + assert_eq!(maps, BTreeSet::from([BakedMap::Position, BakedMap::Opacity])); + assert!(rows.iter().all(|row| row.state == BakeMapState::Baked && &row.set_name == set_name), "{rows:?}"); + assert!(!session.bake_log.is_running()); +} + +#[test] +fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { + let mut session = sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); + } + let log = &mut session.bake_log; + log.begin(&session.doc.project, &[0, 1]); + + log.set_started(0); + log.map_baked(0, BakedMap::Normal); + log.map_baked(0, BakedMap::Curvature); + log.set_finished(0); + log.set_started(1); + log.map_baked(1, BakedMap::Normal); + let baking: Vec<_> = log.maps.iter().filter(|row| row.state == BakeMapState::Baking).map(|row| (row.texture_set, row.map)).collect(); + assert_eq!(baking, [(1, BakedMap::Curvature)], "the next map of the running set is the one in progress"); + + log.cancel(Some(1)); + + let state_of = |set: usize| log.maps.iter().filter(move |row| row.texture_set == set).map(|row| row.state.clone()).collect::>(); + assert!(state_of(0).iter().all(|state| *state == BakeMapState::Baked), "{:?}", log.maps); + assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); + assert!(!log.is_running()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b1879df3..11b199c9 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -4,6 +4,7 @@ mod add_mask_items; mod bake; mod bake_checks; +mod bake_log; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9f0b6d70..16cbee1e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -706,6 +706,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); + self.session.bake_log.begin(&self.session.doc.project, &sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } @@ -824,6 +825,7 @@ impl TextureCraftApp { if let Some(running) = &job.current { running.progress.cancel.store(true, Ordering::Relaxed); } + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); self.bake = None; return; } @@ -835,6 +837,7 @@ impl TextureCraftApp { // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; } @@ -848,7 +851,10 @@ impl TextureCraftApp { job.current = None; match self.session.apply_streamed_bake(set_index, output) { - Ok(()) => self.bake_report.map_count += maps_baked, + Ok(()) => { + self.session.bake_log.set_finished(set_index); + self.bake_report.map_count += maps_baked; + } Err(error) => self.bake_failed(set_index, &error.to_string()), } } @@ -882,6 +888,7 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); + self.session.bake_log.set_started(set_index); let task = match only { Some(map) => self.session.bake_task_only(set_index, map), None => self.session.bake_task(set_index), @@ -914,6 +921,7 @@ impl TextureCraftApp { /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); + self.session.bake_log.set_failed(set_index, error); self.bake_report.failed_set_count += 1; } @@ -937,6 +945,7 @@ impl TextureCraftApp { pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; + self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); } From e24f4e28d89abc09bb654a701ae880e6b31e2302 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:55:44 +0000 Subject: [PATCH 03/26] Show the latest bake in the Baking Log's tabs The Baking Log gets the three tabs from the issue's mock-ups (Baking Process, High Poly Parameters, Matching by Name) in the Properties section-tab look. Baking Process lists one row per texture set and map: a tick when baked, orange dots and bold for the map being baked (kept in view), dim while waiting, a red cross or a warning when not kept, with the reason on hover. The tab's icon turns into orange dots while a bake runs. --- crates/ui-egui/src/baking_log.rs | 146 ++++++++++++++++++ .../ui-egui/src/baking_log/baking_log_tab.rs | 36 +++++ crates/ui-egui/src/docking.rs | 8 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/property_sheet/mod.rs | 3 +- .../src/property_sheet/section_tabs.rs | 2 +- .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 60 +++++++ crates/ui-egui/tests/it/main.rs | 1 + 10 files changed, 253 insertions(+), 10 deletions(-) create mode 100644 crates/ui-egui/src/baking_log.rs create mode 100644 crates/ui-egui/src/baking_log/baking_log_tab.rs create mode 100644 crates/ui-egui/tests/it/baking_log.rs diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs new file mode 100644 index 00000000..bacf194e --- /dev/null +++ b/crates/ui-egui/src/baking_log.rs @@ -0,0 +1,146 @@ +//! The Baking Log panel: the latest bake under three tabs, read from the session's bake record + +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; +use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; +use crate::theme::{Tokens, semibold}; + +mod baking_log_tab; + +pub use baking_log_tab::BakingLogTab; + +/// Height of the tab strip, as the Properties section tabs +const STRIP_HEIGHT: f32 = 30.0; + +/// How far the first tab reaches left of the rows' side padding, as the Properties section tabs +const FIRST_TAB_OUTDENT: f32 = 4.0; + +/// Height of one row of a list +const ROW_HEIGHT: f32 = 24.0; + +/// Air above the first row +const LIST_TOP: f32 = 4.0; + +/// How far a hovered row's fill stays inside the panel's sides +const HOVER_INSET: f32 = 3.0; + +/// From the panel's left edge to a row's glyph centre, and to its name +const GLYPH_CENTER: f32 = SIDE_PADDING_POINTS + 6.0; +const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; + +/// Size of a row's glyph and of its name +const GLYPH_SIZE: f32 = 13.0; +const NAME_SIZE: f32 = 12.0; + +pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { + let running = app.session.bake_log.is_running(); + if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + app.ui.baking_log_tab = tab; + } + + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.add_space(LIST_TOP); + if app.ui.baking_log_tab == BakingLogTab::BakingProcess { + baking_process(ui, &app.session.bake_log.maps); + } + }); +} + +/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + + let mut picked = None; + let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + for tab in BakingLogTab::ALL { + let name = tr(tab.name()); + let on = tab == shown; + let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.clicked() { + picked = Some(tab); + } + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = running && tab == BakingLogTab::BakingProcess; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + + left += width + TAB_GAP; + } + picked +} + +/// One row per texture set and map, in bake order; the map being baked stays in view +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap]) { + let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); + let follow_id = Id::unique("baking_log_followed_map"); + let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); + ui.data_mut(|data| data.insert_temp(follow_id, followed)); + + for (index, row) in maps.iter().enumerate() { + let rect = map_row(ui, row); + if newly_followed && followed == Some(index) { + ui.scroll_to_rect(rect, None); + } + } +} + +/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); + let (glyph, glyph_color, state) = match &row.state { + BakeMapState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeMapState::Baking => (ic::DOTS_THREE, tokens.accent, tr("Baking")), + BakeMapState::Baked => (ic::CHECK, tokens.text, tr("Baked")), + BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), + BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeMapState::Baking => (semibold(NAME_SIZE), tokens.text), + BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } + rect +} diff --git a/crates/ui-egui/src/baking_log/baking_log_tab.rs b/crates/ui-egui/src/baking_log/baking_log_tab.rs new file mode 100644 index 00000000..ccff71b0 --- /dev/null +++ b/crates/ui-egui/src/baking_log/baking_log_tab.rs @@ -0,0 +1,36 @@ +use egui_phosphor::regular as ic; +use serde::{Deserialize, Serialize}; + +use crate::i18n::n_; + +/// The Baking Log panel's tabs +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum BakingLogTab { + /// Every map of the latest bake and how it went + #[default] + BakingProcess, + /// The high poly files each texture set bakes from + HighPolyParameters, + /// Which low poly part bakes from which high poly part + MatchingByName, +} + +impl BakingLogTab { + pub const ALL: [BakingLogTab; 3] = [BakingLogTab::BakingProcess, BakingLogTab::HighPolyParameters, BakingLogTab::MatchingByName]; + + pub fn name(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => n_("Baking Process"), + BakingLogTab::HighPolyParameters => n_("High Poly Parameters"), + BakingLogTab::MatchingByName => n_("Matching by Name"), + } + } + + pub(crate) fn icon(self) -> &'static str { + match self { + BakingLogTab::BakingProcess => ic::LIST_CHECKS, + BakingLogTab::HighPolyParameters => ic::CUBE, + BakingLogTab::MatchingByName => ic::ARROWS_LEFT_RIGHT, + } + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 85edb126..f1acd9e7 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -612,13 +612,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), Panel::Log => crate::log_panel::body(app, ui), - Panel::BakingLog => { - egui::ScrollArea::vertical().show(ui, |ui| { - for entry in app.session.log.entries().iter().filter(|entry| entry.source == "Baker") { - ui.label(entry.line()); - } - }); - } + Panel::BakingLog => crate::baking_log::body(app, ui), Panel::Export => crate::export_panel::body(app, ui), Panel::Renderer => crate::render_mode::settings_body(app, ui), Panel::Viewport => {} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16cbee1e..a786eef7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -14,6 +14,7 @@ mod ask; mod autosave_name; mod bake_job; pub mod bake_mode; +pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 51c6ecfb..def4354d 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -75,13 +75,14 @@ pub(crate) use properties_scroll::{PropertiesScroll, PropertiesSelection}; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{ SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, in_scope, - room_past_end, section_tabs, + room_past_end, section_tabs, shown_tab_box, }; pub(crate) use sheet::PropertySheet; pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; +pub(crate) use switch_control::paint_focus_outline; pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) { if response.has_focus() { diff --git a/crates/ui-egui/src/property_sheet/section_tabs.rs b/crates/ui-egui/src/property_sheet/section_tabs.rs index 595116ca..754c3fd2 100644 --- a/crates/ui-egui/src/property_sheet/section_tabs.rs +++ b/crates/ui-egui/src/property_sheet/section_tabs.rs @@ -110,7 +110,7 @@ fn tab_rect(strip: Rect, left: f32, right: f32) -> Rect { } /// The shown tab's box over `tab`: the panel's colour, rounded, so it rises from the panel below the strip -fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { +pub(crate) fn shown_tab_box(painter: &Painter, tokens: &Tokens, tab: Rect) { painter.rect_filled(tab, CornerRadius::same(TAB_ROUNDING), tokens.panel); } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 8f700a6d..c6b8fa18 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -63,7 +63,7 @@ pub(super) fn untinted(_index: usize) -> &'static [Color32] { &[] } -pub(super) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { +pub(crate) fn paint_focus_outline(painter: &Painter, rect: Rect, color: Color32) { painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(FOCUS_OUTLINE_WIDTH, color), StrokeKind::Inside); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ff897d80..6afa5c9b 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -681,6 +681,9 @@ pub struct UiState { /// The Log panel's shown channel tab #[serde(default)] pub log_channel: crate::log_panel::LogChannel, + /// The Baking Log panel's shown tab + #[serde(default)] + pub baking_log_tab: crate::baking_log::BakingLogTab, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -844,6 +847,7 @@ impl Default for UiState { bake_preset_name: String::new(), layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), + baking_log_tab: crate::baking_log::BakingLogTab::default(), last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs new file mode 100644 index 00000000..c69c2fcc --- /dev/null +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -0,0 +1,60 @@ +//! The Baking Log panel: the latest bake, map by map + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.select([BakedMap::Id, BakedMap::Position]); + } + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { + let mut harness = harness(); + { + // Set 1 has no tile left to bake, so its bake fails + 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([BakedMap::Id]); + } + assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(&mut harness); + + let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + for map in ["ID", "Position"] { + assert!(harness.query_by_label(&format!("{} {map}, Baked", names[0])).is_some(), "set 0's {map} row is ticked"); + } + assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0129eb7a..045d3d57 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -10,6 +10,7 @@ mod bake_mode; mod bake_presets; mod bake_reset_menus; mod bake_sync; +mod baking_log; mod brush_drag; mod brush_section_reset; mod camera_views; From d908c4a49e7d40a221ab5c4c666df43f2f137b96 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:04:36 +0000 Subject: [PATCH 04/26] Open a not-baked map's settings from its Baking Log row A failed or canceled row shows an arrow at its right end while hovered or focused; it makes the row's texture set active and shows the map in Mesh Map Settings, as picking it in Mesh Map Bakers does. --- crates/ui-egui/src/baking_log.rs | 85 ++++++++++++++++++++++----- crates/ui-egui/tests/it/baking_log.rs | 46 ++++++++++++--- 2 files changed, 107 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index bacf194e..7d59cd29 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -2,10 +2,13 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; +use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr}; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_TEXT_SIZE, TAB_TOP, shown_tab_box}; use crate::theme::{Tokens, semibold}; @@ -36,18 +39,43 @@ const NAME_LEFT: f32 = SIDE_PADDING_POINTS + 22.0; const GLYPH_SIZE: f32 = 13.0; const NAME_SIZE: f32 = 12.0; +/// Size of the open-settings arrow at an issue row's right end, and of the square it answers clicks in +const OPEN_ICON_SIZE: f32 = 14.0; +const OPEN_BUTTON_SIZE: f32 = 20.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let running = app.session.bake_log.is_running(); if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { app.ui.baking_log_tab = tab; } - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(LIST_TOP); - if app.ui.baking_log_tab == BakingLogTab::BakingProcess { - baking_process(ui, &app.session.bake_log.maps); - } - }); + let opened = egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_space(LIST_TOP); + match app.ui.baking_log_tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + _ => None, + } + }) + .inner; + if let Some((texture_set, map)) = opened { + open_map_settings(app, texture_set, map); + } +} + +/// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does +fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + // The set may have been deleted since the bake + if texture_set >= app.session.set_count() { + return; + } + + if texture_set != app.session.ts() { + app.run("textureSet.select", json!({ "ts": texture_set })); + } + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); } /// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon @@ -89,23 +117,28 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); + let mut opened = None; for (index, row) in maps.iter().enumerate() { - let rect = map_row(ui, row); + let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); } + if open_clicked { + opened = Some((row.texture_set, row.map)); + } } + opened } -/// A map's row: its state's glyph, then " "; a map that was not baked tells why on hover -fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { +/// A map's row: glyph, then " "; a map not baked tells why on hover and has an arrow to its settings; returns the row and whether the arrow was clicked +fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { let tokens = Tokens::get(ui.ctx()); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let name = format!("{} {}", row.set_name, tr(baked_map_label(row.map))); @@ -117,9 +150,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); - if response.hovered() { + if row_hovered { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } let center_y = rect.center().y; @@ -129,7 +164,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { BakeMapState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), _ => (FontId::proportional(NAME_SIZE), tokens.text), }; - painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, &name, font, color); + if let Some(open) = &open + && (row_hovered || open.has_focus()) + { + let color = if open.hovered() || open.has_focus() { tokens.text } else { tokens.text_dim }; + painter.text(open.rect.center(), Align2::CENTER_CENTER, ic::ARROW_SQUARE_OUT, FontId::proportional(OPEN_ICON_SIZE), color); + if open.has_focus() { + crate::property_sheet::paint_focus_outline(painter, open.rect, tokens.text_strong); + } + } let reason = match &row.state { BakeMapState::Failed(reason) => Some(reason.as_str()), @@ -142,5 +186,16 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> Rect { ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); }); } - rect + let open_clicked = open.is_some_and(|open| open.clicked()); + (rect, open_clicked) +} + +/// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus +fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { + let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); + let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); + let label = trf("Open the {name} settings", &[("name", &name)]); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); + response.on_hover_text(label) } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index c69c2fcc..d10d63cc 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -37,20 +37,23 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { panic!("the bake did not finish"); } +/// 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]) { + 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()); + + harness.state_mut().start_bake(vec![0, 1]); + run_to_the_end(harness); +} + #[test] fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { let mut harness = harness(); - { - // Set 1 has no tile left to bake, so its bake fails - 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([BakedMap::Id]); - } assert!(harness.state().ui.dock.is_visible(Panel::BakingLog), "the bake layout shows the Baking Log"); - harness.state_mut().start_bake(vec![0, 1]); - run_to_the_end(&mut harness); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); let names: Vec = harness.state().session.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); for map in ["ID", "Position"] { @@ -58,3 +61,28 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { } assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } + +#[test] +fn a_failed_maps_arrow_opens_its_settings() { + let mut harness = harness(); + + // Three rows fit the docked log without scrolling + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Id]); + bake_with_set_1_failing(&mut harness, &[BakedMap::Id, BakedMap::Position]); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + assert_eq!(harness.state().session.ts(), 0); + assert!(harness.query_by_label("Normalization Scale").is_none(), "Position's settings are not shown yet"); + + let set_name = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_label(&format!("Open the {set_name} Position settings")).click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1, "the failed map's texture set is the active one"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "the arrow fronts Mesh Map Settings"); + harness.get_by_label("Normalization Scale"); + assert!( + harness.query_by_label(&format!("Open the {} ID settings", harness.state().session.doc.project.texture_sets[0].name)).is_none(), + "a baked map has no arrow" + ); +} From ec17def3375aa78e0e2d697c4d44512c9f8456f1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:06:33 +0000 Subject: [PATCH 05/26] Keep only the issues in the Baking Log on demand A warning toggle at the right end of the tab strip counts the shown tab's issues and, while pressed, keeps only the rows with one. With no issue left the tab says so in one line, with how to see every row under it. --- crates/ui-egui/src/baking_log.rs | 111 +++++++++++++++++++++++--- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/tests/it/baking_log.rs | 41 ++++++++++ 3 files changed, 143 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 7d59cd29..1688d940 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -1,6 +1,6 @@ //! The Baking Log panel: the latest bake under three tabs, read from the session's bake record -use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; @@ -43,18 +43,56 @@ const NAME_SIZE: f32 = 12.0; const OPEN_ICON_SIZE: f32 = 14.0; const OPEN_BUTTON_SIZE: f32 = 20.0; +/// Height of the issues filter toggle, and its width without a count +const FILTER_HEIGHT: f32 = 22.0; +const FILTER_BUTTON_WIDTH: f32 = 30.0; + +/// How far the issues filter sits below the strip's centre, and how far it reaches past the side padding +const FILTER_DROP: f32 = 1.0; +const FILTER_OUTDENT: f32 = 4.0; + +/// Corner rounding of the issues filter's pressed and hovered fill +const FILTER_ROUNDING: f32 = 5.0; + +/// From the issues filter's left edge to its glyph's centre and to its count, and the glyph's size +const FILTER_GLYPH_CENTER: f32 = 15.0; +const FILTER_COUNT_LEFT: f32 = 26.0; +const FILTER_GLYPH_SIZE: f32 = 14.0; + +/// Air between the issue count and the toggle's right end +const FILTER_COUNT_GAP: f32 = 4.0; + +/// Height of the two lines the issues filter leaves when nothing is wrong, to centre them +const EMPTY_TEXT_HEIGHT: f32 = 40.0; + pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let running = app.session.bake_log.is_running(); - if let Some(tab) = tab_strip(ui, app.ui.baking_log_tab, running) { + let tokens = Tokens::get(ui.ctx()); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); + ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { app.ui.baking_log_tab = tab; } + let tab = app.ui.baking_log_tab; + let issue_count = match tab { + BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), + _ => 0, + }; + if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { + app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; + } + + let issues_only = app.ui.baking_log_issues_only; + if issues_only && issue_count == 0 { + no_issues(ui, tab); + return; + } let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { ui.add_space(LIST_TOP); - match app.ui.baking_log_tab { - BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps), + match tab { + BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), _ => None, } }) @@ -78,12 +116,9 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option { +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { let tokens = Tokens::get(ui.ctx()); - let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); - ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; for tab in BakingLogTab::ALL { @@ -117,15 +152,65 @@ fn tab_strip(ui: &mut Ui, shown: BakingLogTab, running: bool) -> Option Option<(usize, BakedMap)> { +/// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are +fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let count = (issue_count > 0).then(|| issue_count.to_string()); + let count_width = + count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); + let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; + let center_y = strip.center().y + FILTER_DROP; + let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + + let name = match &count { + Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), + None => tr("Show Only Issues").to_owned(), + }; + let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); + + let painter = ui.painter(); + if on { + painter.rect(rect, FILTER_ROUNDING, tokens.tool_active, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, FILTER_ROUNDING, tokens.row_hover); + } + let glyph_color = if count.is_some() { tokens.warning } else { tokens.text_dim }; + painter.text(pos2(rect.left() + FILTER_GLYPH_CENTER, center_y), Align2::CENTER_CENTER, ic::WARNING, FontId::proportional(FILTER_GLYPH_SIZE), glyph_color); + if let Some(count) = count { + painter.text(pos2(rect.left() + FILTER_COUNT_LEFT, center_y), Align2::LEFT_CENTER, count, semibold(NAME_SIZE), tokens.text); + } + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + response.on_hover_text(tr("Show Only Issues")).clicked() +} + +/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +fn no_issues(ui: &mut Ui, tab: BakingLogTab) { + let tokens = Tokens::get(ui.ctx()); + let message = match tab { + BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), + BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), + BakingLogTab::MatchingByName => tr("No matching issues encountered"), + }; + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); + child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); + child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// One row per texture set and map (with an issue, if `issues_only`) in bake order, following the map being baked; returns the map to open +fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option<(usize, BakedMap)> { let followed = maps.iter().position(|row| row.state == BakeMapState::Baking); let follow_id = Id::unique("baking_log_followed_map"); let newly_followed = followed.is_some() && ui.data(|data| data.get_temp::>(follow_id)) != Some(followed); ui.data_mut(|data| data.insert_temp(follow_id, followed)); let mut opened = None; - for (index, row) in maps.iter().enumerate() { + for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); if newly_followed && followed == Some(index) { ui.scroll_to_rect(rect, None); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 6afa5c9b..c30cb883 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -684,6 +684,9 @@ pub struct UiState { /// The Baking Log panel's shown tab #[serde(default)] pub baking_log_tab: crate::baking_log::BakingLogTab, + /// Whether the Baking Log keeps only the rows with an issue + #[serde(default)] + pub baking_log_issues_only: bool, /// The project template the last New project was created from (name or label) #[serde(default)] pub last_template: String, @@ -848,6 +851,7 @@ impl Default for UiState { layout_dialog: None, log_channel: crate::log_panel::LogChannel::default(), baking_log_tab: crate::baking_log::BakingLogTab::default(), + baking_log_issues_only: false, last_template: String::new(), log_selection: Default::default(), log_anchor: None, diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index d10d63cc..9f56d585 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,6 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -86,3 +87,43 @@ fn a_failed_maps_arrow_opens_its_settings() { "a baked map has no arrow" ); } + +/// Put a finished bake of set 0's ID and Position maps in the log, the Position map ending as `position` +fn log_a_bake(harness: &mut Harness<'static, TextureCraftApp>, position: BakeMapState) -> String { + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + let row = |map, state| BakeLogMap { texture_set: 0, set_name: set_name.clone(), map, state }; + harness.state_mut().session.bake_log.maps = vec![row(BakedMap::Id, BakeMapState::Baked), row(BakedMap::Position, position)]; + harness.run_steps(3); + set_name +} + +#[test] +fn the_issues_filter_keeps_only_the_maps_with_a_problem() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); + harness.get_by_label(&format!("{set_name} ID, Baked")); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); + harness.get_by_label(&format!("{set_name} Position, Not baked")); + assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); +} + +#[test] +fn the_issues_filter_says_so_when_nothing_went_wrong() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); + harness.get_by_label("All textures baked successfully so far."); + harness.get_by_label("Deselect filter to view."); + + harness.get_by_label("Show Only Issues").click(); + harness.run_steps(3); + harness.get_by_label(&format!("{set_name} ID, Baked")); + assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); +} From dfafec43c14e0738ca12c28cb094df48a6b5aa66 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:09:06 +0000 Subject: [PATCH 06/26] Report the Baking Log's rows through bake.log Automation gets the latest bake map by map with each map's state and the error of a failed one, the same rows the Baking Log shows. --- crates/engine/src/bake/bake_log.rs | 3 +-- crates/engine/src/bake/bake_log_map.rs | 5 +--- crates/engine/src/bake_log_cmds.rs | 36 ++++++++++++++++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/tests/it/bake_log.rs | 17 ++++++++++++ docs/control-protocol.md | 8 ++++++ 7 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/bake_log_cmds.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f263cf2..d8705039 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,10 +1,9 @@ -use serde::Serialize; use texturecraft_core::{BakedMap, Project}; use super::{BakeLogMap, BakeMapState}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines -#[derive(Clone, Debug, Default, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, } diff --git a/crates/engine/src/bake/bake_log_map.rs b/crates/engine/src/bake/bake_log_map.rs index 4a04bd7d..6f5d714a 100644 --- a/crates/engine/src/bake/bake_log_map.rs +++ b/crates/engine/src/bake/bake_log_map.rs @@ -1,15 +1,12 @@ -use serde::Serialize; use texturecraft_core::BakedMap; use super::BakeMapState; /// One row of the Baking Log's process list: a map of a texture set in the latest bake -#[derive(Clone, Debug, PartialEq, Serialize)] -#[serde(rename_all = "camelCase")] +#[derive(Clone, Debug, PartialEq)] pub struct BakeLogMap { pub texture_set: usize, pub set_name: String, pub map: BakedMap, - #[serde(flatten)] pub state: BakeMapState, } diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs new file mode 100644 index 00000000..dc8e243e --- /dev/null +++ b/crates/engine/src/bake_log_cmds.rs @@ -0,0 +1,36 @@ +//! The `bake.log` query: the Baking Log's rows for automation + +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.log", + "Baking log", + [], + None, + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + always, + log + )] +} + +fn log(session: &mut Session, _: &Value) -> Result { + let maps = session + .bake_log + .maps + .iter() + .map(|row| { + let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; + if let Some(fields) = entry.as_object_mut() { + fields.insert("textureSet".into(), json!(row.texture_set)); + fields.insert("setName".into(), json!(row.set_name)); + fields.insert("map".into(), json!(row.map.id())); + } + Ok(entry) + }) + .collect::>>()?; + Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 49cead62..41e7d619 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -139,6 +139,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::project_cmds::specs()); v.extend(crate::bake::specs()); v.extend(crate::bake_preview::specs()); + v.extend(crate::bake_log_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::pbr_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 148af463..ab6319f7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod add_mask_cmds; mod anchored_micro_edit; pub mod bake; +pub mod bake_log_cmds; pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 965295e1..955d5561 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -48,3 +48,20 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { assert!(state_of(1).iter().all(|state| *state == BakeMapState::Canceled), "maps of the set not kept are canceled: {:?}", log.maps); assert!(!log.is_running()); } + +#[test] +fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["opacity", "position"], "dilation": 0 })).unwrap(); + + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["running"], false); + let maps: BTreeSet<&str> = log["maps"].as_array().unwrap().iter().map(|row| row["map"].as_str().unwrap()).collect(); + assert_eq!(maps, BTreeSet::from(["opacity", "position"])); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "baked" && row["textureSet"] == 0 && row.get("reason").is_none()), "{log}"); + + session.bake_log.set_failed(0, "The high poly file could not be read."); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3abb3a97..feb3627f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,14 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). +`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: + +```json +{"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} +``` + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From c0839e873e26ec920b7a8368d3cb8eeea37327bf Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:21:07 +0000 Subject: [PATCH 07/26] List each set's high poly files in the Baking Log --- crates/engine/src/bake/bake_high_state.rs | 27 +++++ crates/engine/src/bake/bake_log.rs | 50 +++++++++- crates/engine/src/bake/bake_log_high.rs | 11 +++ crates/engine/src/bake/mesh_map_command.rs | 3 +- crates/engine/src/bake/mod.rs | 4 + crates/engine/src/bake_log_cmds.rs | 32 +++--- crates/engine/tests/it/bake_log.rs | 37 ++++++- crates/ui-egui/src/baking_log.rs | 22 +++-- .../ui-egui/src/baking_log/high_poly_list.rs | 98 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 35 ++++++- docs/control-protocol.md | 7 +- 12 files changed, 296 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/bake/bake_high_state.rs create mode 100644 crates/engine/src/bake/bake_log_high.rs create mode 100644 crates/ui-egui/src/baking_log/high_poly_list.rs diff --git a/crates/engine/src/bake/bake_high_state.rs b/crates/engine/src/bake/bake_high_state.rs new file mode 100644 index 00000000..8ecbd0a5 --- /dev/null +++ b/crates/engine/src/bake/bake_high_state.rs @@ -0,0 +1,27 @@ +use serde::Serialize; + +/// Where one high poly file of a bake stands, as the Baking Log shows it +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "state", content = "reason")] +pub enum BakeHighState { + /// Its texture set has not started baking + Waiting, + Loading, + Loaded, + /// Its texture set's bake failed while getting the high polys ready; the reason is the error + Failed(String), + /// The bake stopped before the file was loaded + Canceled, +} + +impl BakeHighState { + /// Whether the file can still change in this bake + pub fn is_pending(&self) -> bool { + matches!(self, Self::Waiting | Self::Loading) + } + + /// Whether the file counts as an issue in the log + pub fn is_issue(&self) -> bool { + matches!(self, Self::Failed(_) | Self::Canceled) + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index d8705039..82f63c90 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,16 +1,18 @@ use texturecraft_core::{BakedMap, Project}; -use super::{BakeLogMap, BakeMapState}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] pub struct BakeLog { pub maps: Vec, + /// Each high poly file of each texture set that bakes from the high polys, in bake order + pub highs: Vec, } impl BakeLog { - /// Start over for a bake of `sets`: every checked map of each set, waiting, in bake order - pub fn begin(&mut self, project: &Project, sets: &[usize]) { + /// Start over for a bake of `sets`: every checked map of each set and the `high_polys` of each set that bakes from them, waiting, in bake order + pub fn begin(&mut self, project: &Project, high_polys: &[BakeMesh], sets: &[usize]) { self.maps = sets .iter() .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) @@ -18,13 +20,36 @@ impl BakeLog { set.bake.maps.enabled().map(move |map| BakeLogMap { texture_set: index, set_name: set.name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); + self.highs = sets + .iter() + .filter_map(|index| project.texture_sets.get(*index).map(|set| (*index, set))) + .filter(|(_, set)| !set.bake.high_poly.use_low_as_high) + .flat_map(|(index, set)| { + high_polys.iter().map(move |high| BakeLogHigh { + texture_set: index, + set_name: set.name.clone(), + file: high.name.clone(), + state: BakeHighState::Waiting, + }) + }) + .collect(); } - /// `set` starts baking: its first map is the one in progress + /// `set` starts baking: its high polys load and its first map is the one in progress pub fn set_started(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Waiting) { + row.state = BakeHighState::Loading; + } self.start_next(set); } + /// `set`'s bake has its high polys ready + pub fn high_polys_loaded(&mut self, set: usize) { + for row in self.highs.iter_mut().filter(|row| row.texture_set == set && row.state == BakeHighState::Loading) { + row.state = BakeHighState::Loaded; + } + } + /// `map` of `set` is baked; the set's next map starts pub fn map_baked(&mut self, set: usize, map: BakedMap) { if let Some(row) = self.maps.iter_mut().find(|row| row.texture_set == set && row.map == map) { @@ -45,6 +70,10 @@ 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()); + } } /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled @@ -54,6 +83,7 @@ impl BakeLog { row.state = BakeMapState::Canceled; } } + self.cancel_pending_highs(); } /// The whole bake was rolled back: every map that did not fail is canceled @@ -61,6 +91,7 @@ impl BakeLog { for row in self.maps.iter_mut().filter(|row| !matches!(row.state, BakeMapState::Failed(_))) { row.state = BakeMapState::Canceled; } + self.cancel_pending_highs(); } /// Whether a map is still waiting or baking @@ -68,6 +99,17 @@ impl BakeLog { self.maps.iter().any(|row| row.state.is_pending()) } + /// Whether a high poly file is still waiting or loading + pub fn is_loading_high_polys(&self) -> bool { + self.highs.iter().any(|row| row.state.is_pending()) + } + + fn cancel_pending_highs(&mut self) { + for row in self.highs.iter_mut().filter(|row| row.state.is_pending()) { + row.state = BakeHighState::Canceled; + } + } + fn start_next(&mut self, set: usize) { if self.maps.iter().any(|row| row.texture_set == set && row.state == BakeMapState::Baking) { return; diff --git a/crates/engine/src/bake/bake_log_high.rs b/crates/engine/src/bake/bake_log_high.rs new file mode 100644 index 00000000..7c6de83d --- /dev/null +++ b/crates/engine/src/bake/bake_log_high.rs @@ -0,0 +1,11 @@ +use super::BakeHighState; + +/// One row of the Baking Log's high poly list: a high poly file a texture set bakes from in the latest bake +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogHigh { + pub texture_set: usize, + pub set_name: String, + /// The file's name as the project keeps it (the project carries the file itself, not where it came from) + pub file: String, + pub state: BakeHighState, +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index a76561fb..e3f16c22 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &sets); + session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { @@ -871,6 +871,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { /// Bake every checked map of texture set `index` at once, store them and mark them baked in the Baking Log fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result { let mut task = session.bake_task(index)?; + session.bake_log.high_polys_loaded(index); if cpu { task.tracer = None; } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 736b00bb..873c2f35 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -2,7 +2,9 @@ mod bake_cage_inputs; mod bake_checks; +mod bake_high_state; mod bake_log; +mod bake_log_high; mod bake_log_map; mod bake_map_state; mod bake_mesh; @@ -22,7 +24,9 @@ mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; +pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; +pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index dc8e243e..edfbd15a 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,26 +11,26 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, as the Baking Log shows it; `reason` says why a map failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", always, log )] } fn log(session: &mut Session, _: &Value) -> Result { - let maps = session - .bake_log - .maps - .iter() - .map(|row| { - let mut entry = serde_json::to_value(&row.state).map_err(|error| bad("bake.log", error.to_string()))?; - if let Some(fields) = entry.as_object_mut() { - fields.insert("textureSet".into(), json!(row.texture_set)); - fields.insert("setName".into(), json!(row.set_name)); - fields.insert("map".into(), json!(row.map.id())); - } - Ok(entry) - }) - .collect::>>()?; - Ok(json!({ "running": session.bake_log.is_running(), "maps": maps })) + 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::>>()?; + let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; + Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) +} + +/// 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 { + 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); + } + Ok(entry) } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 955d5561..36ce7772 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,7 +3,7 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::bake::{BakeHighState, BakeMapState}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -30,7 +30,7 @@ fn a_canceled_bake_keeps_the_finished_sets_and_cancels_the_rest() { set.bake.maps.select([BakedMap::Normal, BakedMap::Curvature]); } let log = &mut session.bake_log; - log.begin(&session.doc.project, &[0, 1]); + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); log.set_started(0); log.map_baked(0, BakedMap::Normal); @@ -65,3 +65,36 @@ fn bake_log_reports_each_map_with_its_state_and_a_failures_reason() { let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert!(log["maps"].as_array().unwrap().iter().all(|row| row["state"] == "failed" && row["reason"] == "The high poly file could not be read."), "{log}"); } + +#[test] +fn a_bake_lists_the_high_polys_each_set_loads_and_skips_a_set_baking_from_its_low_poly() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + session.doc.project.texture_sets[1].bake.high_poly.use_low_as_high = true; + + execute(&mut session, "bake.run", &json!({ "ts": [0, 1], "resolution": 64, "maps": ["opacity"], "dilation": 0 })).unwrap(); + + let highs: Vec<_> = session.bake_log.highs.iter().map(|row| (row.texture_set, row.file.as_str(), row.state.clone())).collect(); + assert_eq!(highs, [(0, "ball_high.obj", BakeHighState::Loaded)]); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["highPolys"][0]["state"], "loaded", "{log}"); +} + +#[test] +fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_cancel_the_rest_canceled() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let log = &mut session.bake_log; + log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + + log.set_started(0); + assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert!(log.is_loading_high_polys()); + log.set_failed(0, "The cage file could not be read."); + log.set_started(1); + log.cancel(Some(1)); + + assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); + assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert!(!log.is_loading_high_polys()); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1688d940..9b2e0257 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -13,6 +13,7 @@ use crate::property_sheet::{SIDE_PADDING_POINTS, TAB_GAP, TAB_ICON_CENTER, TAB_I use crate::theme::{Tokens, semibold}; mod baking_log_tab; +mod high_poly_list; pub use baking_log_tab::BakingLogTab; @@ -69,13 +70,14 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, app.session.bake_log.is_running()) { + if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - _ => 0, + BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => 0, }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; @@ -93,7 +95,11 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), - _ => None, + BakingLogTab::HighPolyParameters => { + high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); + None + } + BakingLogTab::MatchingByName => None, } }) .inner; @@ -117,7 +123,7 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa } /// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon -fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option { +fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); let mut picked = None; let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; @@ -137,7 +143,11 @@ fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, running: bool) -> Option< shown_tab_box(painter, &tokens, rect); } let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = running && tab == BakingLogTab::BakingProcess; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; let center_y = strip.center().y + TAB_TOP / 2.0; painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs new file mode 100644 index 00000000..5f4f5977 --- /dev/null +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -0,0 +1,98 @@ +//! The Baking Log's High Poly Parameters tab: each texture set of the latest bake and the high poly files it loads + +use egui::{Align2, CornerRadius, FontId, Id, Role, Sense, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh}; + +use super::{GLYPH_CENTER, GLYPH_SIZE, HOVER_INSET, NAME_LEFT, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, semibold}; + +/// How far a file's row sits right of its texture set's row +const FILE_INDENT: f32 = 22.0; + +/// A row per texture set that loads high polys, folding open onto a row per file (with an issue, if `issues_only`) +pub(super) fn high_poly_list(ui: &mut Ui, highs: &[BakeLogHigh], issues_only: bool) { + let mut start = 0; + while start < highs.len() { + let set = highs[start].texture_set; + let end = highs[start..].iter().position(|row| row.texture_set != set).map_or(highs.len(), |length| start + length); + let files: Vec<&BakeLogHigh> = highs[start..end].iter().filter(|row| !issues_only || row.state.is_issue()).collect(); + start = end; + if files.is_empty() { + continue; + } + + if set_row(ui, set, &files[0].set_name) { + for row in files { + file_row(ui, row); + } + } + } +} + +/// A texture set's row: a caret and its name in SemiBold, named for what it holds; a click folds it. Returns whether it is open +fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { + let tokens = Tokens::get(ui.ctx()); + let id = Id::unique(("baking_log_high_poly_set", set)); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, trf("{set}, High poly files", &[("set", &name)]))); + let mut open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + if response.clicked() { + open = !open; + ui.data_mut(|data| data.insert_temp(id, open)); + } + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + let caret = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(rect.left() + GLYPH_CENTER, center_y), Align2::CENTER_CENTER, caret, FontId::proportional(GLYPH_SIZE), tokens.text_dim); + painter.text(pos2(rect.left() + NAME_LEFT, center_y), Align2::LEFT_CENTER, name, semibold(NAME_SIZE), tokens.text); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + open +} + +/// A high poly file's row under its texture set: glyph and file name; a file not loaded tells why on hover +fn file_row(ui: &mut Ui, row: &BakeLogHigh) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let (glyph, glyph_color, state) = match &row.state { + BakeHighState::Waiting => (ic::CIRCLE_DASHED, tokens.text_dim, tr("Waiting")), + BakeHighState::Loading => (ic::DOTS_THREE, tokens.accent, tr("Loading")), + BakeHighState::Loaded => (ic::CHECK, tokens.text, tr("Loaded")), + BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), + BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), + }; + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); + } + let center_y = rect.center().y; + painter.text(pos2(rect.left() + GLYPH_CENTER + FILE_INDENT, center_y), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), glyph_color); + let (font, color) = match row.state { + BakeHighState::Loading => (semibold(NAME_SIZE), tokens.text), + BakeHighState::Waiting => (FontId::proportional(NAME_SIZE), tokens.text_dim), + _ => (FontId::proportional(NAME_SIZE), tokens.text), + }; + painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); + + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a786eef7..f825ba7e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &sets); + self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } @@ -896,6 +896,7 @@ impl TextureCraftApp { }; match task { Ok(task) => { + self.session.bake_log.high_polys_loaded(set_index); let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 9f56d585..837e3403 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -127,3 +127,36 @@ fn the_issues_filter_says_so_when_nothing_went_wrong() { harness.get_by_label(&format!("{set_name} ID, Baked")); assert!(harness.query_by_label("All textures baked successfully so far.").is_none(), "off again: every row is back"); } + +#[test] +fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { + let mut harness = harness(); + harness.state_mut().session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); + harness.get_by_label("ball_high.obj, Loaded"); + + harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.run_steps(3); + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); +} + +#[test] +fn the_high_poly_tab_counts_and_keeps_its_own_issues() { + let mut harness = harness(); + let set_name = log_a_bake(&mut harness, BakeMapState::Baked); + let row = |file: &str, state| BakeLogHigh { texture_set: 0, set_name: set_name.clone(), file: file.into(), state }; + harness.state_mut().session.bake_log.highs = vec![row("ball_high.obj", BakeHighState::Loaded), row("bolt_high.obj", BakeHighState::Canceled)]; + harness.get_by_label("High Poly Parameters").click(); + harness.run_steps(3); + + harness.get_by_label("1, Show Only Issues").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); + harness.get_by_label("bolt_high.obj, Canceled"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index feb3627f..d97cd2bf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -306,11 +306,14 @@ also `session.inspect`'s `bakePreview`: ``` `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). -`state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`: +A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. +`highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}]} + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 373159ec5ebccb0eefb2078a8dbeed36cdc9cba3 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:38:32 +0000 Subject: [PATCH 08/26] List how the bake paired parts by name in the Baking Log --- crates/engine/src/bake/bake_log.rs | 49 +++++++++++- crates/engine/src/bake/bake_log_matching.rs | 18 +++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 3 + crates/engine/src/bake_log_cmds.rs | 8 +- crates/engine/tests/it/bake_log.rs | 39 +++++++-- crates/ui-egui/src/baking_log.rs | 62 +++++++++++---- .../ui-egui/src/baking_log/matching_list.rs | 79 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 51 +++++++++--- docs/control-protocol.md | 8 +- 11 files changed, 286 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/bake_log_matching.rs create mode 100644 crates/ui-egui/src/baking_log/matching_list.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 82f63c90..7203b7c1 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,6 +1,10 @@ +use std::collections::HashSet; + +use texturecraft_bake::NamePair; use texturecraft_core::{BakedMap, Project}; -use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState, BakeMesh}; +use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; +use crate::Session; /// The latest bake map by map for the Baking Log, kept from the bake's own state, never from Log lines #[derive(Clone, Debug, Default, PartialEq)] @@ -8,6 +12,8 @@ pub struct BakeLog { pub maps: Vec, /// Each high poly file of each texture set that bakes from the high polys, in bake order pub highs: Vec, + /// How the parts paired by name; `None` when no set of the bake matches "By Mesh Name" + pub matching: Option, } impl BakeLog { @@ -33,6 +39,7 @@ impl BakeLog { }) }) .collect(); + self.matching = None; } /// `set` starts baking: its high polys load and its first map is the one in progress @@ -120,3 +127,43 @@ impl BakeLog { } } } + +impl Session { + /// Start the Baking Log over for a bake of `sets` ([`BakeLog::begin`]), with how their parts pair by name + pub fn begin_bake_log(&mut self, sets: &[usize]) { + let matching = self.bake_log_matching(sets); + self.bake_log.begin(&self.doc.project, &self.doc.bake_meshes.high, sets); + self.bake_log.matching = matching; + } + + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + fn bake_log_matching(&self, sets: &[usize]) -> Option { + let mut matching: Option = None; + let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + for &set in sets { + let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + let settings = &texture_set.bake.high_poly; + let matching = matching.get_or_insert_with(|| BakeLogMatching { + low_suffix: settings.low_suffix.clone(), + high_suffix: settings.high_suffix.clone(), + pairs: Vec::new(), + }); + for pair in pairs { + match (&pair.low, &pair.high) { + (None, Some(high)) if !unpaired_highs.contains(high) => unpaired_highs.push(high.clone()), + (None, _) => {} + (Some(_), high) => { + paired_highs.extend(high.clone()); + matching.pairs.push(pair); + } + } + } + } + + if let Some(matching) = &mut matching { + let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); + matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); + } + matching + } +} diff --git a/crates/engine/src/bake/bake_log_matching.rs b/crates/engine/src/bake/bake_log_matching.rs new file mode 100644 index 00000000..9e0ef379 --- /dev/null +++ b/crates/engine/src/bake/bake_log_matching.rs @@ -0,0 +1,18 @@ +use texturecraft_bake::NamePair; + +/// The Baking Log's matching list: how the latest bake paired low poly parts with high poly parts by name +#[derive(Clone, Debug, PartialEq)] +pub struct BakeLogMatching { + /// The suffixes the first set matching by name strips, for the column captions + pub low_suffix: String, + pub high_suffix: String, + /// Each low poly part with the high poly part it bakes from, then the high poly parts no set of the bake pairs with + pub pairs: Vec, +} + +impl BakeLogMatching { + /// How many parts found no partner + pub fn issue_count(&self) -> usize { + self.pairs.iter().filter(|pair| pair.unpaired()).count() + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e3f16c22..fef806b1 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -843,7 +843,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } - session.bake_log.begin(&session.doc.project, &session.bake_meshes.high, &sets); + session.begin_bake_log(&sets); let mut tracers = Vec::with_capacity(sets.len()); for &index in &sets { diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 873c2f35..e5edcc07 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -6,6 +6,7 @@ mod bake_high_state; mod bake_log; mod bake_log_high; mod bake_log_map; +mod bake_log_matching; mod bake_map_state; mod bake_mesh; mod bake_meshes; @@ -28,6 +29,7 @@ pub use bake_high_state::BakeHighState; pub use bake_log::BakeLog; pub use bake_log_high::BakeLogHigh; pub use bake_log_map::BakeLogMap; +pub use bake_log_matching::BakeLogMatching; pub use bake_map_state::BakeMapState; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; @@ -39,6 +41,7 @@ pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, pub use model_patch::settings_patch; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; +pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake_log_cmds.rs b/crates/engine/src/bake_log_cmds.rs index edfbd15a..4be8c268 100644 --- a/crates/engine/src/bake_log_cmds.rs +++ b/crates/engine/src/bake_log_cmds.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Baking log", [], None, - "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}]}. The latest bake map by map in bake order, and the high poly files each set bakes from, as the Baking Log shows them; `reason` says why a map or file failed. Empty before the first bake", + "{} → {running, maps: [{textureSet, setName, map, state: \"waiting\" | \"baking\" | \"baked\" | \"failed\" | \"canceled\", reason?}], highPolys: [{textureSet, setName, file, state: \"waiting\" | \"loading\" | \"loaded\" | \"failed\" | \"canceled\", reason?}], matching: null | {lowSuffix, highSuffix, pairs: [{low: name | null, high: name | null}]}}. The latest bake map by map in bake order, the high poly files each set bakes from, and how parts paired by name, as the Baking Log shows them; `reason` says why a map or file failed; a `null` side of a pair is a part with no partner; `matching` is null when no set matched by mesh name. Empty before the first bake", always, log )] @@ -21,7 +21,11 @@ fn log(session: &mut Session, _: &Value) -> Result { 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::>>()?; let highs = log.highs.iter().map(|row| entry(&row.state, row.texture_set, &row.set_name, "file", json!(row.file))).collect::>>()?; - Ok(json!({ "running": log.is_running() || log.is_loading_high_polys(), "maps": maps, "highPolys": highs })) + let matching = log.matching.as_ref().map(|matching| { + let pairs: Vec = 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 })) } /// One row: its `state` (and `reason`), its texture set, and what it is under `key` diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 36ce7772..419ce6b4 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -3,8 +3,8 @@ use std::collections::BTreeSet; use serde_json::json; -use texturecraft_engine::bake::{BakeHighState, BakeMapState}; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -86,15 +86,44 @@ fn a_set_that_fails_before_its_high_polys_are_ready_marks_them_failed_and_a_canc session.add_high_poly_bytes("ball_high.obj", b"o Ball_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let log = &mut session.bake_log; log.begin(&session.doc.project, &session.doc.bake_meshes.high, &[0, 1]); + let state = |log: &BakeLog, set: usize| log.highs.iter().find(|high| high.texture_set == set).map(|high| high.state.clone()); log.set_started(0); - assert_eq!(log.highs[0].state, BakeHighState::Loading); + assert_eq!(state(log, 0), Some(BakeHighState::Loading)); assert!(log.is_loading_high_polys()); log.set_failed(0, "The cage file could not be read."); log.set_started(1); log.cancel(Some(1)); - assert_eq!(log.highs[0].state, BakeHighState::Failed("The cage file could not be read.".into())); - assert_eq!(log.highs[1].state, BakeHighState::Canceled); + assert_eq!(state(log, 0), Some(BakeHighState::Failed("The cage file could not be read.".into()))); + assert_eq!(state(log, 1), Some(BakeHighState::Canceled)); assert!(!log.is_loading_high_polys()); } + +#[test] +fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_with() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.begin_bake_log(&[0, 1]); + assert_eq!(session.bake_log.matching, None, "matching \"Always\" lists no pairs"); + + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + } + session.begin_bake_log(&[0, 1]); + + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + let matching = session.bake_log.matching.clone().unwrap(); + assert_eq!( + matching.pairs, + [pair(Some("Box_low"), Some("Box_high")), pair(Some("Lid_low"), None), pair(None, Some("Extra_high"))], + "Box_high is paired by the other set" + ); + assert_eq!(matching.issue_count(), 2); + let log = execute(&mut session, "bake.log", &json!({})).unwrap(); + assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 9b2e0257..1ee11974 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -14,6 +14,7 @@ use crate::theme::{Tokens, semibold}; mod baking_log_tab; mod high_poly_list; +mod matching_list; pub use baking_log_tab::BakingLogTab; @@ -77,13 +78,19 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let issue_count = match tab { BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => 0, + BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), }; if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } let issues_only = app.ui.baking_log_issues_only; + let log = &app.session.bake_log; + let baked = !log.maps.is_empty(); + if tab == BakingLogTab::MatchingByName && baked && log.matching.is_none() { + matching_not_enabled(ui); + return; + } if issues_only && issue_count == 0 { no_issues(ui, tab); return; @@ -92,6 +99,8 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let opened = egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { + // Rows sit edge to edge at ROW_HEIGHT, as the matching list's rules need + ui.spacing_mut().item_spacing.y = 0.0; ui.add_space(LIST_TOP); match tab { BakingLogTab::BakingProcess => baking_process(ui, &app.session.bake_log.maps, issues_only), @@ -99,7 +108,12 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { high_poly_list::high_poly_list(ui, &app.session.bake_log.highs, issues_only); None } - BakingLogTab::MatchingByName => None, + BakingLogTab::MatchingByName => { + if let Some(matching) = &app.session.bake_log.matching { + matching_list::matching_list(ui, matching, issues_only); + } + None + } } }) .inner; @@ -173,8 +187,8 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { - Some(count) => trf("{count}, Show Only Issues", &[("count", count)]), - None => tr("Show Only Issues").to_owned(), + Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), + None => tr("Show only rows with an issue").to_owned(), }; let response = ui.interact(rect, ui.scope_id().with("baking_log_issues_filter"), Sense::click()); response.widget_info(|| WidgetInfo::selected(Role::Button, true, on, &name)); @@ -193,22 +207,41 @@ fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool if response.has_focus() { crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); } - response.on_hover_text(tr("Show Only Issues")).clicked() + response.on_hover_text(tr("Show only rows with an issue")).clicked() } -/// What the issues filter leaves when `tab` has no issue: the reference's words for that tab, and how to see every row +/// What the issues filter leaves when `tab` has no issue: one line for that tab, and how to see every row fn no_issues(ui: &mut Ui, tab: BakingLogTab) { let tokens = Tokens::get(ui.ctx()); let message = match tab { - BakingLogTab::BakingProcess => tr("All textures baked successfully so far."), - BakingLogTab::HighPolyParameters => tr("No issues encountered so far."), - BakingLogTab::MatchingByName => tr("No matching issues encountered"), + BakingLogTab::BakingProcess => tr("Every map so far baked without a problem."), + BakingLogTab::HighPolyParameters => tr("Every high poly file so far loaded."), + BakingLogTab::MatchingByName => tr("Every part so far has its partner."), }; let area = ui.available_rect_before_wrap(); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); child.add_space((area.height() - EMPTY_TEXT_HEIGHT).max(0.0) / 2.0); child.label(egui::RichText::new(message).font(semibold(NAME_SIZE)).color(tokens.text)); - child.label(egui::RichText::new(tr("Deselect filter to view.")).size(NAME_SIZE).color(tokens.text_dim)); + child.label(egui::RichText::new(tr("Turn off the issues filter to see every row.")).size(NAME_SIZE).color(tokens.text_dim)); + ui.allocate_rect(area, Sense::hover()); +} + +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +fn matching_not_enabled(ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let mut text = egui::text::LayoutJob::default(); + let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; + // One sentence to translate, its setting kept apart to set it in SemiBold + let sentence = tr("{setting} was off for this bake."); + let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); + + let area = ui.available_rect_before_wrap(); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area).layout(egui::Layout::top_down(egui::Align::Center))); + child.add_space((area.height() - EMPTY_TEXT_HEIGHT / 2.0).max(0.0) / 2.0); + child.label(text); ui.allocate_rect(area, Sense::hover()); } @@ -222,8 +255,9 @@ fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option let mut opened = None; for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) { let (rect, open_clicked) = map_row(ui, row); + // Bring the next map into view too, so the list shows what comes after the map being baked if newly_followed && followed == Some(index) { - ui.scroll_to_rect(rect, None); + ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None); } if open_clicked { opened = Some((row.texture_set, row.map)); @@ -245,7 +279,7 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); - let open = row.state.is_issue().then(|| open_settings_button(ui, rect, &name)); + let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); let painter = ui.painter(); @@ -286,11 +320,11 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus -fn open_settings_button(ui: &mut Ui, row: Rect, name: &str) -> egui::Response { +fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); let rect = Rect::from_center_size(center, vec2(OPEN_BUTTON_SIZE, OPEN_BUTTON_SIZE)); let label = trf("Open the {name} settings", &[("name", &name)]); - let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", name)), Sense::click()); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_open", set_map)), Sense::click()); response.widget_info(|| WidgetInfo::labeled(Role::Button, true, &label)); response.on_hover_text(label) } diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs new file mode 100644 index 00000000..22ad6c46 --- /dev/null +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -0,0 +1,79 @@ +//! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part + +use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::bake::{BakeLogMatching, NamePair}; + +use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; +use crate::i18n::{tr, trf}; +use crate::property_sheet::SIDE_PADDING_POINTS; +use crate::theme::{Tokens, semibold}; + +/// Size of the column captions +const CAPTION_SIZE: f32 = 11.0; + +/// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below +pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; + for (left, caption) in columns(rect).into_iter().zip(captions) { + ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + } + rule(ui, rect); + + for pair in matching.pairs.iter().filter(|pair| !issues_only || pair.unpaired()) { + pair_row(ui, pair); + } +} + +/// A column caption in capitals, with the set's `suffix` kept as typed +fn caption(template: &str, suffix: &str) -> String { + template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) +} + +/// The left edges of the low and high poly columns of `row` +fn columns(row: Rect) -> [f32; 2] { + [row.left() + SIDE_PADDING_POINTS, row.center().x] +} + +/// The hairline under `row`, inside the side padding +fn rule(ui: &Ui, row: Rect) { + let tokens = Tokens::get(ui.ctx()); + let x = row.left() + SIDE_PADDING_POINTS..=row.right() - SIDE_PADDING_POINTS; + ui.painter().hline(x, row.bottom() - 0.5, Stroke::new(1.0, tokens.separator)); +} + +/// A pair's row: the low poly part, then the high poly part; a side with no partner is a warning glyph that tells why on hover +fn pair_row(ui: &mut Ui, pair: &NamePair) { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let no_match = tr("No match"); + let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + + 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; + for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + match part { + Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), + None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), + }; + } + rule(ui, rect); + + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; + if let Some(reason) = reason { + response.on_hover_ui(|ui| { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f825ba7e..4346c304 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -707,7 +707,7 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.bake_log.begin(&self.session.doc.project, &self.session.bake_meshes.high, &sets); + self.session.begin_bake_log(&sets); self.bake_report = bake_report::BakeReport::started(self.last_time); self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 837e3403..3d098b6f 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -2,7 +2,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; -use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -103,29 +103,29 @@ fn the_issues_filter_keeps_only_the_maps_with_a_problem() { let set_name = log_a_bake(&mut harness, BakeMapState::Failed("The high poly file could not be read.".into())); harness.get_by_label(&format!("{set_name} ID, Baked")); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none(), "a baked map is filtered out"); harness.get_by_label(&format!("{set_name} Position, Not baked")); - assert!(harness.query_by_label("Deselect filter to view.").is_none(), "an issue left: no empty text"); + assert!(harness.query_by_label("Turn off the issues filter to see every row.").is_none(), "an issue left: no empty text"); } #[test] fn the_issues_filter_says_so_when_nothing_went_wrong() { let mut harness = harness(); let set_name = log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Show Only Issues").click(); + harness.get_by_label("Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label(&format!("{set_name} ID, Baked")).is_none()); - harness.get_by_label("All textures baked successfully so far."); - harness.get_by_label("Deselect filter to view."); + harness.get_by_label("Every map so far baked without a problem."); + harness.get_by_label("Turn off the issues filter to see every row."); - harness.get_by_label("Show Only Issues").click(); + 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("All textures baked successfully so far.").is_none(), "off again: every row is back"); + assert!(harness.query_by_label("Every map so far baked without a problem.").is_none(), "off again: every row is back"); } #[test] @@ -154,9 +154,42 @@ fn the_high_poly_tab_counts_and_keeps_its_own_issues() { harness.get_by_label("High Poly Parameters").click(); harness.run_steps(3); - harness.get_by_label("1, Show Only Issues").click(); + harness.get_by_label("1, Show only rows with an issue").click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a loaded file is filtered out"); harness.get_by_label("bolt_high.obj, Canceled"); } + +#[test] +fn the_matching_tab_lists_the_pairs_and_its_filter_keeps_the_parts_with_no_partner() { + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = |low: Option<&str>, high: Option<&str>| NamePair { low: low.map(Into::into), high: high.map(Into::into) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![pair(Some("Barrel_low"), Some("Barrel_high")), pair(Some("Strap_low"), None)], + }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + harness.get_by_label("Barrel_low, Barrel_high"); + + harness.get_by_label("1, Show only rows with an issue").click(); + harness.run_steps(3); + + assert!(harness.query_by_label("Barrel_low, Barrel_high").is_none(), "a pair is filtered out"); + harness.get_by_label("Strap_low, No match"); +} + +#[test] +fn the_matching_tab_says_when_no_set_matched_by_name() { + let mut harness = harness(); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + assert!(harness.query_by_label("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + + log_a_bake(&mut harness, BakeMapState::Baked); + + harness.get_by_label("Matching by name was off for this bake."); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d97cd2bf..a682a901 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -308,12 +308,16 @@ also `session.inspect`'s `bakePreview`: `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, -`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`: +`loading`, `loaded`, `failed` (with the error as `reason`) or `canceled`. `matching` lists each low poly +part with the high poly part it bakes from, then the high poly parts no set paired with; a `null` side is a part +with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], - "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}]} + "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], + "matching": {"lowSuffix": "_low", "highSuffix": "_high", + "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with From 530541a97a06a737b5aaaeb4b4bbf72555eef61e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:52:29 +0000 Subject: [PATCH 09/26] Remember what each baked map was baked from Each bake records, per map, fingerprints of the low poly geometry, the high poly and cage files, the settings every map shares (with the UV tiles baked) and the map's own settings, taken when the set's bake starts. A map whose inputs differ now is out of date, with what changed; project.inspect lists those per texture set as outOfDate. The record is saved with the project and left out when empty, so projects saved before it open unchanged and their maps never show out of date. Imported maps keep no record either. --- crates/core/src/bake.rs | 4 + crates/core/src/bake/bake_change.rs | 25 ++++ crates/core/src/bake/bake_source.rs | 69 +++++++++++ crates/core/src/bake/mesh_map_settings.rs | 16 +++ crates/core/src/lib.rs | 11 +- crates/core/src/project.rs | 19 ++- crates/engine/src/bake/bake_mesh.rs | 2 + crates/engine/src/bake/bake_sources.rs | 65 ++++++++++ crates/engine/src/bake/bake_task.rs | 11 +- crates/engine/src/bake/mesh_map_command.rs | 35 ++++-- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake/streamed_bake.rs | 4 +- crates/engine/src/file_cmds.rs | 9 +- crates/engine/src/inspect.rs | 1 + crates/engine/src/meshmap_cmds.rs | 41 ++++--- crates/engine/src/session.rs | 3 + crates/engine/tests/it/bake_out_of_date.rs | 136 +++++++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/tests/it/bake_mode.rs | 2 +- docs/control-protocol.md | 6 + 20 files changed, 422 insertions(+), 39 deletions(-) create mode 100644 crates/core/src/bake/bake_change.rs create mode 100644 crates/core/src/bake/bake_source.rs create mode 100644 crates/engine/src/bake/bake_sources.rs create mode 100644 crates/engine/tests/it/bake_out_of_date.rs diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index a40f5ab0..8289ef42 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,9 +4,11 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_change; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_source; mod bake_sync; mod bake_sync_group; mod mesh_match_mode; @@ -45,8 +47,10 @@ pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; pub use ambient_occlusion_settings::AmbientOcclusionSettings; pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; +pub use bake_change::BakeChange; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_source::{BakeSource, fingerprint, fingerprint_words}; pub use bake_sync::BakeSync; pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; diff --git a/crates/core/src/bake/bake_change.rs b/crates/core/src/bake/bake_change.rs new file mode 100644 index 00000000..bb73b1f2 --- /dev/null +++ b/crates/core/src/bake/bake_change.rs @@ -0,0 +1,25 @@ +use serde::{Deserialize, Serialize}; + +/// What changed since a mesh map was baked, which makes it out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum BakeChange { + LowPoly, + HighPoly, + Cage, + Settings, + MapSettings, +} + +impl BakeChange { + /// Identifier in automation replies + pub fn id(self) -> &'static str { + match self { + BakeChange::LowPoly => "lowPoly", + BakeChange::HighPoly => "highPoly", + BakeChange::Cage => "cage", + BakeChange::Settings => "settings", + BakeChange::MapSettings => "mapSettings", + } + } +} diff --git a/crates/core/src/bake/bake_source.rs b/crates/core/src/bake/bake_source.rs new file mode 100644 index 00000000..9cc59c44 --- /dev/null +++ b/crates/core/src/bake/bake_source.rs @@ -0,0 +1,69 @@ +use super::BakeChange; +use serde::{Deserialize, Serialize}; + +/// Fingerprints of what one mesh map was baked from: a later change to any of them shows the map out of date +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BakeSource { + /// The low poly's geometry + pub low_poly: u64, + /// The high poly files, in list order (0: none, the set bakes from the low poly) + pub high_poly: u64, + /// The cage file (0: none) + pub cage: u64, + /// The settings every map of the set shares (size, high poly, cage, skew) and its UV tiles + pub settings: u64, + /// The map's own settings + pub map_settings: u64, +} + +impl BakeSource { + /// What differs in `current` from this record, in [`BakeChange`] order (empty: up to date) + pub fn changes(&self, current: &BakeSource) -> Vec { + [ + (self.low_poly != current.low_poly, BakeChange::LowPoly), + (self.high_poly != current.high_poly, BakeChange::HighPoly), + (self.cage != current.cage, BakeChange::Cage), + (self.settings != current.settings, BakeChange::Settings), + (self.map_settings != current.map_settings, BakeChange::MapSettings), + ] + .into_iter() + .filter_map(|(changed, change)| changed.then_some(change)) + .collect() + } +} + +/// A fingerprint of `bytes` that stays the same across runs, platforms and Rust versions (unlike `std::hash`) +pub fn fingerprint(bytes: &[u8]) -> u64 { + let words = bytes.chunks(8).map(|chunk| { + let mut word_bytes = [0; 8]; + word_bytes[..chunk.len()].copy_from_slice(chunk); + u64::from_le_bytes(word_bytes) + }); + fingerprint_words(words.chain([bytes.len() as u64])) +} + +/// [`fingerprint`] of a sequence of words: FNV-1a taking a 64-bit word per step +pub fn fingerprint_words(words: impl IntoIterator) -> u64 { + // FNV-1a 64-bit offset basis and prime + const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + words.into_iter().fold(OFFSET_BASIS, |hash, word| (hash ^ word).wrapping_mul(PRIME)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fingerprint_changes_with_any_byte_and_with_the_length() { + let bytes: Vec = (0..=20).collect(); + let mut changed = bytes.clone(); + changed[17] ^= 1; + + assert_ne!(fingerprint(&bytes), fingerprint(&changed)); + assert_ne!(fingerprint(&bytes), fingerprint(&bytes[..20])); + assert_ne!(fingerprint(&[]), fingerprint(&[0])); + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index 281d5c98..579141e7 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -84,6 +84,22 @@ impl MeshMapSettings { } } + /// `map`'s typed parameters as JSON + pub fn parameters_json(&self, map: BakedMap) -> serde_json::Value { + let parameters = match map { + // These maps have no parameters of their own + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => return serde_json::Value::Null, + BakedMap::Id => serde_json::to_value(self.id.parameters), + BakedMap::AmbientOcclusion => serde_json::to_value(self.ao.parameters), + BakedMap::Curvature => serde_json::to_value(self.curvature.parameters), + BakedMap::Position => serde_json::to_value(self.position.parameters), + BakedMap::Thickness => serde_json::to_value(self.thickness.parameters), + BakedMap::Height => serde_json::to_value(self.height.parameters), + BakedMap::BentNormal => serde_json::to_value(self.bent_normal.parameters), + }; + parameters.unwrap_or_default() + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eedf93ec..772653e4 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,12 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, - BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, - HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, - MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, - SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeChange, BakePaintTarget, BakeResolution, BakeSettings, + BakeSource, BakeSync, BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, + GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, + MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, + PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, fingerprint, + fingerprint_words, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 0a4bf868..69437007 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -69,6 +69,9 @@ pub struct TextureSet { /// Mesh maps that have been baked (pixels live with the engine / project file). #[serde(default)] pub baked: BTreeSet, + /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub bake_sources: BTreeMap, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -171,6 +174,7 @@ impl TextureSet { height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), + bake_sources: BTreeMap::new(), visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), @@ -187,6 +191,19 @@ impl TextureSet { self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) } + /// Fingerprint of the shared bake settings (not the set's check) and baked UV tiles (not their working resolutions) + pub fn bake_settings_fingerprint(&self) -> u64 { + let mut common = self.bake.common; + common.is_enabled = true; + let shared = (common, &self.bake.high_poly, &self.bake.cage, &self.bake.skew, &self.uv_tiles, &self.bake_excluded_tiles); + crate::fingerprint(serde_json::to_string(&shared).unwrap_or_default().as_bytes()) + } + + /// Fingerprint of `map`'s own bake settings (not whether it is checked) + pub fn map_settings_fingerprint(&self, map: BakedMap) -> u64 { + crate::fingerprint(self.bake.maps.parameters_json(map).to_string().as_bytes()) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index bcdb2bcc..d4dbfeeb 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -11,4 +11,6 @@ pub struct BakeMesh { pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, + /// [`texturecraft_core::fingerprint`] of `bytes`: what bakes from this file record + pub fingerprint: u64, } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs new file mode 100644 index 00000000..70f7665c --- /dev/null +++ b/crates/engine/src/bake/bake_sources.rs @@ -0,0 +1,65 @@ +//! What each baked map was baked from, and which maps are out of date since + +use std::collections::BTreeMap; + +use texturecraft_core::{BakeChange, BakeSource, BakedMap, CageType, 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 { + let set = self.doc.project.texture_set(texture_set)?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + let high_poly = match from_high { + true => fingerprint_words(self.doc.bake_meshes.high.iter().map(|high| high.fingerprint)), + false => 0, + }; + let reads_cage = from_high && set.bake.cage.kind == CageType::CustomFile; + let cage = self.doc.bake_meshes.cage.as_ref().filter(|_| reads_cage).map_or(0, |cage| cage.fingerprint); + + Ok(BakeSource { + low_poly: self.low_poly_fingerprint(), + high_poly, + cage, + settings: set.bake_settings_fingerprint(), + map_settings: set.map_settings_fingerprint(map), + }) + } + + /// 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 { + 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(¤t)).unwrap_or_default() + } + + /// The out-of-date maps of texture set `texture_set`, each with what changed + pub fn out_of_date_maps(&self, texture_set: usize) -> BTreeMap> { + BakedMap::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + } + + /// Fingerprint of the low poly's own geometry (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) + }) + } + + /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record + pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + let set = self.doc.project.texture_set_mut(texture_set)?; + match sources { + Some(sources) => set.bake_sources.extend(sources), + None => set.bake_sources.retain(|map, _| !stored.contains(map)), + } + + let baked = &set.baked; + set.bake_sources.retain(|map, _| baked.contains(map)); + Ok(()) + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index a617d97b..3c0cb59e 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -26,6 +26,8 @@ pub struct BakeTask { pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, + /// What each map this task makes is baked from, taken when the task was made + pub sources: std::collections::BTreeMap, } impl BakeTask { @@ -66,7 +68,13 @@ impl BakeTask { // A resized partial bake also returns unchecked maps that must survive application let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); retained.insert(map, data); - combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); + combined = Some(StreamedBake { + resolution: output.resolution, + height: output.height, + maps: retained, + tracer: output.tracer, + sources: self.sources.clone(), + }); } } } @@ -80,6 +88,7 @@ impl BakeTask { height: output.height, maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, + sources: self.sources.clone(), }) } } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef806b1..49ec4ec0 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -15,8 +15,8 @@ use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, - SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSource, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, + RaySettings, SelfOcclusion, }; use texturecraft_geom::Mesh; @@ -121,7 +121,8 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); - Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color }) + let fingerprint = texturecraft_core::fingerprint(&bytes); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color, fingerprint }) } impl Session { @@ -183,6 +184,7 @@ 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 = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, @@ -198,6 +200,7 @@ impl Session { excluded_tiles, previous_maps, tracer, + sources, }) } @@ -260,7 +263,7 @@ impl Session { /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, None))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } @@ -269,17 +272,26 @@ impl Session { /// preview that showed them holds the same ones) pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps))?; + self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + /// Store `output`, recording what its maps were baked from when `sources` are known + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) } - fn store_bake_maps(&mut self, texture_set: usize, resolution: u32, height: u32, maps: std::collections::BTreeMap>>) -> Result<()> { + fn store_bake_maps( + &mut self, + texture_set: usize, + resolution: u32, + height: u32, + maps: BTreeMap>>, + sources: Option<&BTreeMap>, + ) -> Result<()> { + let stored: Vec = 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) { entry.maps.clear(); @@ -288,7 +300,7 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - Ok(()) + self.record_bake_sources(texture_set, sources, &stored) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. @@ -299,7 +311,8 @@ impl Session { } let out = task.run(&Progress::new())?; let tracer = out.tracer.clone(); - self.apply_bake(ts, out)?; + self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -879,7 +892,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result>>, pub tracer: String, + /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) + pub sources: BTreeMap, } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9c447c3c..5cfc235b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1655,7 +1655,14 @@ f 1/1 2/2 3/3 let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + let cage = crate::bake::BakeMesh { + name: "cage".into(), + folder: None, + bytes: Default::default(), + mesh: s.mesh.clone(), + base_color: Vec::new(), + fingerprint: 0, + }; s.doc.bake_meshes.cage = Some(cage); let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index a4258463..e9c3b2e5 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -276,6 +276,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index f08d34c4..5736c5ca 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,19 +53,19 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = s.doc.project.texture_set(ts)?; +pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = session.doc.project.texture_set(ts)?; let grid = texture_set.tile_grid(); if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { - return Err(bad(cmd, format!("no image for UV tile {tile}"))); + return Err(bad(command, format!("no image for UV tile {tile}"))); } - let (width, height) = image_map_size(s, cmd, ts)?; + let (width, height) = image_map_size(session, command, ts)?; // 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) && s.doc.project.normal_format == NormalFormat::DirectX; + 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(cmd, "no image to use")), + (_, 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| { @@ -74,10 +74,13 @@ pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, i }), }; - let entry = s.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(ts).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); + // An imported map is never out of date: nothing records what it was made from + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.insert(map); + set.bake_sources.remove(&map); Ok(width) } @@ -153,18 +156,20 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( out } -fn clear(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.meshMap.clear"; - let ts = ts_param(s, p, CMD)?; - let map = map_param(p, CMD)?; - if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); +fn clear(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.meshMap.clear"; + let ts = ts_param(session, params, COMMAND)?; + let map = map_param(params, COMMAND)?; + if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { + return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); } - s.edit("Clear mesh map", |s| { - if let Some(b) = s.doc.baked.get_mut(&ts) { - b.maps.remove(&map); + session.edit("Clear mesh map", |session| { + if let Some(baked) = session.doc.baked.get_mut(&ts) { + baked.maps.remove(&map); } - s.doc.project.texture_set_mut(ts)?.baked.remove(&map); + let set = session.doc.project.texture_set_mut(ts)?; + set.baked.remove(&map); + set.bake_sources.remove(&map); Ok(()) })?; Ok(Value::Null) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index f0a8df58..05a0c779 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -425,6 +425,8 @@ 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, + /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it + pub(crate) low_poly_fingerprint: std::sync::OnceLock, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -527,6 +529,7 @@ impl Session { mesh_id: next_mesh_id(), project_id: next_mesh_id(), source, + low_poly_fingerprint: Default::default(), mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/bake_out_of_date.rs b/crates/engine/tests/it/bake_out_of_date.rs new file mode 100644 index 00000000..9a5c1dcd --- /dev/null +++ b/crates/engine/tests/it/bake_out_of_date.rs @@ -0,0 +1,136 @@ +//! Out-of-date mesh maps: what each map was baked from, compared with what a bake would read now + +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeChange, BakedMap, CageType}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position map baked by `bake.run` +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + session +} + +fn changes(session: &Session) -> Vec { + session.bake_changes(0, BakedMap::Position) +} + +#[test] +fn a_map_goes_out_of_date_when_its_settings_or_the_shared_ones_change_and_a_bake_brings_it_back() { + let mut session = baked_plane(); + assert!(changes(&session).is_empty(), "fresh bake: {:?}", changes(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(changes(&session), [BakeChange::MapSettings]); + execute(&mut session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + assert_eq!(changes(&session), [BakeChange::Settings, BakeChange::MapSettings]); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["outOfDate"], json!({ "position": ["settings", "mapSettings"] })); + + execute(&mut session, "bake.run", &json!({})).unwrap(); + assert!(changes(&session).is_empty(), "rebaked: {:?}", changes(&session)); +} + +#[test] +fn the_record_is_saved_with_the_project() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(changes(&reopened), [BakeChange::MapSettings]); +} + +#[test] +fn maps_saved_before_records_existed_and_imported_maps_never_go_out_of_date() { + let mut old = baked_plane(); + old.doc.project.texture_sets[0].bake_sources.clear(); + let mut old = Session::from_project_bytes(&old.to_project_bytes().unwrap()).unwrap(); + execute(&mut old, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&old).is_empty(), "{:?}", changes(&old)); + + let mut imported = baked_plane(); + let mut png = Vec::new(); + image::RgbImage::from_pixel(4, 4, image::Rgb([128, 64, 32])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + imported.import_resource_bytes("position.png", png).unwrap(); + execute(&mut imported, "textureSet.meshMap.set", &json!({ "map": "position", "image": "position.png" })).unwrap(); + execute(&mut imported, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert!(changes(&imported).is_empty(), "{:?}", changes(&imported)); +} + +#[test] +fn adding_a_high_poly_puts_the_maps_out_of_date() { + let mut session = baked_plane(); + + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + + assert_eq!(changes(&session), [BakeChange::HighPoly]); +} + +#[test] +fn a_cage_file_counts_only_for_sets_that_bake_with_it() { + let mut session = baked_plane(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let cage: String = (0..session.mesh.triangle_count()).map(|_| "v 0 0 0\nv 1 0 0\nv 0 1 0\nf -3 -2 -1\n").collect(); + session.set_cage_bytes("cage.obj", cage.into_bytes()).unwrap(); + assert!(changes(&session).is_empty(), "the cage type is not Custom File: {:?}", changes(&session)); + + session.doc.project.texture_sets[0].bake.cage.kind = CageType::CustomFile; + assert!(changes(&session).contains(&BakeChange::Cage), "{:?}", changes(&session)); +} + +#[test] +fn a_setting_changed_while_the_bake_runs_leaves_the_new_map_out_of_date() { + let mut session = baked_plane(); + let task = session.bake_task(0).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + + let streamed_once = AtomicBool::new(false); + let output = task.run_streaming(&Progress::new(), &mut |_| streamed_once.store(true, Ordering::Relaxed)).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(streamed_once.load(Ordering::Relaxed)); + assert_eq!(changes(&session), [BakeChange::MapSettings]); +} + +/// Two quads side by side, one texture set each, lifted by `lift` where a high poly or cage stands off the low poly +fn two_parts(lift: f32) -> String { + let mut obj = String::new(); + for left in [0.0, 2.0] { + let right = left + 1.0; + obj += &format!("v {left} 0 {lift}\nv {right} 0 {lift}\nv {right} 1 {lift}\nv {left} 1 {lift}\n"); + } + obj += "vt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n"; + obj += "usemtl Left\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\nusemtl Right\nf 5/1 6/2 7/3\nf 5/1 7/3 8/4\n"; + obj +} + +#[test] +fn a_reopened_project_keeps_every_sets_maps_up_to_date() { + let mut session = Session::from_mesh_bytes_with_uvs("parts.obj", two_parts(0.0).as_bytes(), 128, "parts", None, false).unwrap(); + session.add_high_poly_bytes("parts_high.obj", two_parts(0.05).into_bytes()).unwrap(); + session.set_cage_bytes("parts_cage.obj", two_parts(0.2).into_bytes()).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake.cage.kind = CageType::CustomFile; + } + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position", "normal"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 1, "map": "normal" })).unwrap(); + let records = |session: &Session| session.doc.project.texture_sets.iter().map(|set| set.bake_sources.clone()).collect::>(); + assert_eq!(session.set_count(), 2); + assert!(records(&session).iter().all(|sources| sources.len() == 2), "both maps of both sets are recorded"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(records(&reopened), records(&session), "the records are saved as they were"); + for texture_set in 0..reopened.set_count() { + assert!(reopened.out_of_date_maps(texture_set).is_empty(), "set {texture_set}: {:?}", reopened.out_of_date_maps(texture_set)); + } + assert!(reopened.auto_rebake_due().is_empty(), "opening the project starts no rebake"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11b199c9..f43035f4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -5,6 +5,7 @@ mod add_mask_items; mod bake; mod bake_checks; mod bake_log; +mod bake_out_of_date; mod bake_resolution; mod bake_settings; mod bake_tiles; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 1f7253ac..720d4c49 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -595,7 +595,7 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mesh = session.mesh.clone(); session.doc.bake_meshes.cage = - Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new(), fingerprint: 0 }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a682a901..91fad894 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -320,6 +320,12 @@ with no partner. It is `null` when no set of the bake matches by mesh name: "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} ``` +Each texture set in `project.inspect` / `session.inspect` lists its out-of-date mesh maps as +`outOfDate`: map id → what changed since that map was baked, any of `lowPoly`, `highPoly`, `cage`, +`settings` (the bake settings every map shares, or the UV tiles baked) and `mapSettings` (the map's +own). Imported maps, and maps saved before this record existed, never show: +`"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 5b4411ee9a5e1c5012f5670bd3558dc257ad23aa Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:20:12 +0000 Subject: [PATCH 10/26] Note a generator's missing or out-of-date mesh map A generator that reads a mesh map the active texture set has not baked, or baked before its mesh, files or settings changed, shows one line under its kind: what is wrong, the reasons on hover, and a Bake button that bakes the set in the background (turning the map on first when it is off). Nothing shows once the map is up to date, and nothing pops up. The line replaces the old warning at the end of the panel, which showed for every generator, even those that read no mesh map. --- crates/ui-egui/src/generator_panel.rs | 6 +- .../ui-egui/src/generator_panel/bake_note.rs | 107 ++++++++++++++++++ .../ui-egui/tests/it/generator_bake_note.rs | 75 ++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 4 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/generator_panel/bake_note.rs create mode 100644 crates/ui-egui/tests/it/generator_bake_note.rs diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 95d3fcd7..745d93fd 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -18,6 +18,8 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +mod bake_note; + /// The outline on the preview while it can open enlarged under the pointer, or is open, in points const ENLARGE_OUTLINE_WIDTH: f32 = 1.0; @@ -35,6 +37,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, PropertySheet::show(ui, ("generator_sheet", id), |sheet| { sheet.section(tr("Generator"), false); slot_card(app, sheet, id, generator); + bake_note::bake_notes(app, sheet, generator); let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); if band.reset { @@ -68,9 +71,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, if sheet.band(tr("Attributes"), false, None, None).open { attributes(sheet, generator.kind); } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators.")); - } }); } diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs new file mode 100644 index 00000000..4953261d --- /dev/null +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -0,0 +1,107 @@ +//! One quiet line under a generator's kind when a mesh map it reads is not baked or out of date, with a Bake button + +use egui::{Align, Layout, RichText, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; +use crate::theme::{Tokens, semibold}; + +/// Height of the note's line, in points (the mock's 28 px row) +const NOTE_HEIGHT: f32 = 28.0; + +/// Height of the Bake button, in points (the panels' 24 px controls) +const BUTTON_HEIGHT: f32 = 24.0; + +/// Size of the tooltip's title and reasons, in points +const TOOLTIP_TEXT_SIZE: f32 = 12.0; + +/// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date +pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { + let texture_set = app.session.ts(); + for map in generator.inputs_in_use() { + if generator.inputs.contains_key(map) { + continue; + } + + let baked = app.session.baked(texture_set).is_some_and(|baked| baked.maps.contains_key(map)); + let changes = if baked { app.session.bake_changes(texture_set, *map) } else { Vec::new() }; + if baked && changes.is_empty() { + continue; + } + + // A full-width line inside the sheet's side padding + let (line, _) = sheet.ui.allocate_exact_size(vec2(sheet.ui.available_width(), NOTE_HEIGHT), egui::Sense::hover()); + let builder = UiBuilder::new().id_salt(map).max_rect(line.shrink2(vec2(SIDE_PADDING_POINTS, 0.0))).layout(Layout::left_to_right(Align::Center)); + sheet.ui.scope_builder(builder, |ui| note(app, ui, (texture_set, *map), &changes)); + } +} + +/// The line for `map` of `texture_set`: not baked when `changes` is empty, else out of date because of them +fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, BakedMap), changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (glyph, text, title) = match changes.is_empty() { + true => (ic::WARNING, trf("{map} map not baked", &[("map", &name)]), tr("Not baked")), + false => (ic::CLOCK, trf("{map} map out of date", &[("map", &name)]), tr("Out of date")), + }; + let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); + + ui.label(RichText::new(glyph).color(tokens.warning)); + ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for reason in reasons(changes, checked) { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); + let bake = ui + .with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = egui::Button::new(tr("Bake")).stroke(Stroke::new(1.0, tokens.button_border)).min_size(vec2(0.0, BUTTON_HEIGHT)); + ui.add_enabled(app.bake.is_none(), button) + .on_hover_text(tr("Bake this texture set's mesh maps in the background")) + .on_disabled_hover_text(tr("A bake is already running")) + }) + .inner; + + if bake.clicked() { + bake_map(app, texture_set, map); + } +} + +/// Why the line shows: what changed since the bake, or what a missing map does to the generator +fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { + if changes.is_empty() { + let mut reasons = vec![tr("The generator reads a flat value until this map is baked.")]; + if !checked { + reasons.push(tr("Bake turns this map on in the bake settings first.")); + } + return reasons; + } + + changes + .iter() + .map(|change| match change { + BakeChange::LowPoly => tr("The mesh changed after this bake."), + BakeChange::HighPoly => tr("The high poly files changed after this bake."), + BakeChange::Cage => tr("The cage changed after this bake."), + BakeChange::Settings => tr("The common bake settings changed after this bake."), + BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), + }) + .collect() +} + +/// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off +fn bake_map(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { + let Some(before) = app.session.doc.project.texture_sets.get(texture_set).map(|set| set.bake.clone()) else { return }; + + if !before.maps.is_enabled(map) { + let mut after = before.clone(); + after.maps.set_enabled(map, true); + app.run("bake.settings", json!({ "ts": texture_set, "patch": settings_patch(&before, &after) })); + } + app.start_bake(vec![texture_set]); +} diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs new file mode 100644 index 00000000..d26019c7 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -0,0 +1,75 @@ +//! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +/// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({ "color": [0.8, 0.3, 0.1] })).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness +} + +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..4000 { + harness.run_steps(1); + if harness.state().bake.is_none() { + harness.run_steps(2); + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { + let mut harness = harness(); + harness.get_by_label("Curvature map not baked"); + + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); + assert!(harness.query_by_label("Curvature map out of date").is_none(), "baked: no note"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Curvature map out of date"); +} + +#[test] +fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { + let mut harness = harness(); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature)); + + harness.get_by_label("Bake").click(); + harness.run_steps(1); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.is_enabled(BakedMap::Curvature), "turned on"); + assert!(harness.state().bake.is_some(), "a background bake started"); + run_to_the_end(&mut harness); + + assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); + assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 045d3d57..0abd9441 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -44,6 +44,7 @@ mod fill_symmetry_rows; mod filter_picker; mod folder_properties; mod frame_selection; +mod generator_bake_note; mod generator_panel; mod generator_picker; mod help_menu_664; From 9e36885648d969560d050f30704bff97c98ef6ef Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:41:02 +0000 Subject: [PATCH 11/26] Rebake the auto-rebake map when its settings change Each texture set can turn on Auto-rebake for one mesh map (bake.autoRebake, saved with the project; older projects have none). In Bake mode the app rebakes that map alone in the background once what it is baked from has stopped changing for half a second; a change during that bake cancels it and the newest settings bake instead. Only a failed rebake makes a toast. --- crates/core/src/project.rs | 4 + crates/engine/src/bake/auto_rebake.rs | 51 +++++++++++++ crates/engine/src/bake/bake_log.rs | 13 ++++ crates/engine/src/bake/mesh_map_command.rs | 15 ++-- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/inspect.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 68 +++++++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/auto_rebake.rs | 79 ++++++++++++++++++++ crates/ui-egui/src/bake_job.rs | 2 + crates/ui-egui/src/bake_report.rs | 6 +- crates/ui-egui/src/lib.rs | 27 +++++-- crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/tests/bake_preview.rs | 1 + crates/ui-egui/tests/it/auto_rebake.rs | 87 ++++++++++++++++++++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- crates/ui-egui/tests/it/baking_log.rs | 12 +++ crates/ui-egui/tests/it/main.rs | 1 + docs/control-protocol.md | 7 ++ 19 files changed, 365 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/bake/auto_rebake.rs create mode 100644 crates/engine/tests/it/auto_rebake.rs create mode 100644 crates/ui-egui/src/auto_rebake.rs create mode 100644 crates/ui-egui/tests/it/auto_rebake.rs diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 69437007..ca70f6ff 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -72,6 +72,9 @@ pub struct TextureSet { /// What each baked map was baked from; a map without a record (imported, or older project) is never out of date #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub bake_sources: BTreeMap, + /// The one mesh map the app rebakes by itself when what it is baked from changes + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auto_rebake: Option, #[serde(default = "yes")] pub visible: bool, /// UDIM numbers of the UV tiles this set paints, ascending (UV tiles mode); @@ -175,6 +178,7 @@ impl TextureSet { bake: BakeSettings::default(), baked: BTreeSet::new(), bake_sources: BTreeMap::new(), + auto_rebake: None, visible: true, uv_tiles: Vec::new(), bake_excluded_tiles: BTreeSet::new(), diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs new file mode 100644 index 00000000..45831b82 --- /dev/null +++ b/crates/engine/src/bake/auto_rebake.rs @@ -0,0 +1,51 @@ +//! Auto-rebake: the one mesh map per texture set that is baked again whenever what it is baked from changes + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.autoRebake", + "Auto-rebake", + [], + None, + "{ts?: index (default: the active set), map: id | null} → {ts, autoRebake: id | null}. Turn on Auto-rebake for one mesh map of the set (it replaces the set's previous one), or turn it off with null. The app then rebakes that map in the background once what it is baked from changes", + always, + set_auto_rebake + )] +} + +fn set_auto_rebake(session: &mut Session, params: &Value) -> Result { + 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`"))?, + }; + let map = match params.get("map") { + Some(Value::Null) => None, + Some(_) => Some(strp(params, "map").and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, "`map` must be a mesh map id or null"))?), + None => return Err(bad(COMMAND, "`map` is required (a mesh map id or null)")), + }; + + if session.doc.project.texture_set(texture_set)?.auto_rebake != map { + session.edit("Auto-rebake", |session| { + session.doc.project.texture_set_mut(texture_set)?.auto_rebake = map; + Ok(()) + })?; + } + Ok(json!({ "ts": texture_set, "autoRebake": map.map(BakedMap::id) })) +} + +impl Session { + /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) + pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { + let sets = self.doc.project.texture_sets.iter().enumerate(); + sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) + .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) + .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) + .collect() + } +} diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 7203b7c1..18ab8e2a 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,6 +136,19 @@ impl Session { self.bake_log.matching = matching; } + /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + self.begin_bake_log(sets); + let project = &self.doc.project; + self.bake_log.maps = sets + .iter() + .filter_map(|&texture_set| { + let set_name = project.texture_sets.get(texture_set)?.name.clone(); + Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + }) + .collect(); + } + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49ec4ec0..474a5266 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -131,9 +131,14 @@ impl Session { self.bake_task_of(texture_set, None) } + /// A task that bakes only `maps` of texture set `texture_set`, checked or not; its other baked maps stay as they are + pub fn bake_task_for(&self, texture_set: usize, maps: &[BakedMap]) -> Result { + self.bake_task_of(texture_set, Some(maps)) + } + /// The bake of texture set `texture_set`'s map `map` alone, checked or not pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { - self.bake_task_of(texture_set, Some(map)) + self.bake_task_of(texture_set, Some(&[map])) } /// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles @@ -143,15 +148,15 @@ impl Session { Ok(task) } - fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { + fn bake_task_of(&self, texture_set: usize, only: Option<&[BakedMap]>) -> Result { let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } let mut settings = set.bake.clone(); - if let Some(map) = only { - settings.maps.select([map]); + if let Some(maps) = only { + settings.maps.select(maps.iter().copied()); } // Read from the maps that bake, so a map baked alone while unchecked still gets the colours @@ -184,7 +189,7 @@ 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 = set.bake.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; + let sources = settings.maps.enabled().map(|map| Ok((map, self.bake_source(texture_set, map)?))).collect::>()?; Ok(BakeTask { low_base_color, ts: texture_set, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ee75d670..da0599bd 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod auto_rebake; mod bake_cage_inputs; mod bake_checks; mod bake_high_state; @@ -52,6 +53,7 @@ type MaterialColors = std::sync::Arc Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); + commands.extend(auto_rebake::specs()); commands.extend(tile_command::specs()); commands.extend(sync_command::specs()); commands diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index e9c3b2e5..04af908b 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -277,6 +277,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), }) diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs new file mode 100644 index 00000000..c424ef47 --- /dev/null +++ b/crates/engine/tests/it/auto_rebake.rs @@ -0,0 +1,68 @@ +//! Auto-rebake: one map per texture set, due when it goes out of date, rebaked alone + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A plane with its position and ID maps baked +fn baked_plane() -> Session { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + session +} + +fn due_maps(session: &Session) -> Vec<(usize, BakedMap)> { + session.auto_rebake_due().into_iter().map(|(set, map, _)| (set, map)).collect() +} + +#[test] +fn one_map_per_set_is_auto_rebaked_and_it_is_due_only_once_out_of_date() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "id" })).unwrap(); + let turned_on = execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert_eq!(turned_on, json!({ "ts": 0, "autoRebake": "position" }), "the second map replaces the first"); + assert!(due_maps(&session).is_empty(), "up to date: {:?}", due_maps(&session)); + + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + assert_eq!(due_maps(&session), [(0, BakedMap::Position)]); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + assert!(due_maps(&session).is_empty(), "turned off: {:?}", due_maps(&session)); + assert!(execute(&mut session, "bake.autoRebake", &json!({ "map": "glow" })).is_err()); +} + +#[test] +fn the_auto_rebake_map_is_saved_with_the_project_and_undone_like_an_edit() { + let mut session = baked_plane(); + let before = session.to_project_bytes().unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position)); + let inspect = execute(&mut session, "project.inspect", &json!({})).unwrap(); + assert_eq!(inspect["textureSets"][0]["autoRebake"], json!("position")); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None); + assert_eq!(Session::from_project_bytes(&before).unwrap().doc.project.texture_sets[0].auto_rebake, None, "older projects have none"); +} + +#[test] +fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { + let mut session = baked_plane(); + execute(&mut session, "bake.settings", &json!({ "maps": ["id"], "positionMode": "boundingBox" })).unwrap(); + let id_before = session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + + let task = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + assert_eq!(task.maps(), [BakedMap::Position], "an unchecked map bakes when asked for"); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + assert!(session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", session.bake_changes(0, BakedMap::Position)); + let baked = session.baked(0).unwrap(); + assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index f43035f4..843ab3d3 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone session.rs target remains available. mod add_mask_items; +mod auto_rebake; mod bake; mod bake_checks; mod bake_log; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs new file mode 100644 index 00000000..8f20e7b0 --- /dev/null +++ b/crates/ui-egui/src/auto_rebake.rs @@ -0,0 +1,79 @@ +//! Auto-rebake: a texture set's auto-rebake map is baked again in the background once what it is baked from has stopped changing + +use texturecraft_engine::core::{BakeSource, BakedMap}; + +use crate::{BakeJob, TextureCraftApp, bake_report, state}; + +/// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts +const SETTLE_SECONDS: f64 = 0.5; + +/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now +pub type Due = (usize, BakedMap, BakeSource); + +/// What the app has seen of the out-of-date auto-rebake maps +#[derive(Default)] +pub struct AutoRebake { + /// The due maps and the frame time they were first seen as they are + pending: Option<(Vec, f64)>, + /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes + started: Vec, +} + +/// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.ui.mode != state::Mode::Baking { + app.auto_rebake.pending = None; + return; + } + + let due = app.session.auto_rebake_due(); + if let Some(job) = &app.bake { + // Newest wins: a rebake whose map changed again while it ran starts over with the new settings + if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + app.cancel_bake(); + } + return; + } + + if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.pending = None; + return; + } + + let now = app.last_time; + ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + match &app.auto_rebake.pending { + Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == due => return, + _ => { + app.auto_rebake.pending = Some((due, now)); + return; + } + } + + app.auto_rebake.pending = None; + app.auto_rebake.started = due.clone(); + if let Some(rebake) = due.first().copied() { + start(app, rebake); + } +} + +/// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake +fn start(app: &mut TextureCraftApp, rebake: Due) { + let (set, map, _) = rebake; + let orders = match app.session.bake_preview_orders(&[set], Some(map)) { + Ok(orders) => orders, + Err(error) => { + app.toast(error.to_string(), true); + return; + } + }; + + // Restore the previous view before the rebake takes it over + app.live_preview.release(&mut app.session); + crate::id_color_pick::IdColorPick::end(app); + app.session.bake_preview_begin(orders); + app.session.begin_map_bake_log(&[set], map); + app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 97dd4610..431999db 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -11,4 +11,6 @@ pub struct BakeJob { pub mesh_id: u64, /// The one map to bake (a row's quick bake) instead of the checked ones pub only: Option, + /// An auto-rebake: the set, the one map it bakes and what that map was baked from when it started; `None` bakes every checked map + pub rebake: Option, } diff --git a/crates/ui-egui/src/bake_report.rs b/crates/ui-egui/src/bake_report.rs index d0423de9..89e1ebf6 100644 --- a/crates/ui-egui/src/bake_report.rs +++ b/crates/ui-egui/src/bake_report.rs @@ -10,6 +10,8 @@ pub struct BakeReport { pub map_count: usize, /// Number of texture sets whose bake failed pub failed_set_count: usize, + /// A rebake the app started by itself (Auto-rebake): only a failure makes a toast + pub auto_rebake: bool, } impl BakeReport { @@ -57,7 +59,7 @@ mod tests { #[test] fn success_names_maps_and_time() { - let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0 }; + let report = BakeReport { started_at_seconds: 10.0, map_count: 6, failed_set_count: 0, auto_rebake: false }; let (text, line, failed) = report.summary(22.34); @@ -68,7 +70,7 @@ mod tests { #[test] fn failures_are_counted_and_point_to_the_log() { - let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2 }; + let report = BakeReport { started_at_seconds: 0.0, map_count: 3, failed_set_count: 2, auto_rebake: false }; let (text, _, failed) = report.summary(125.0); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4346c304..2816c247 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,15 +10,16 @@ mod anchor_properties; mod angle_dial; mod ask; +mod auto_rebake; #[cfg(not(target_arch = "wasm32"))] mod autosave_name; mod bake_job; pub mod bake_mode; -pub mod baking_log; mod bake_preset; pub mod bake_presets; mod bake_report; mod bake_scene; +pub mod baking_log; mod color_management; mod color_picker; mod color_selection_editor; @@ -290,6 +291,8 @@ pub struct TextureCraftApp { pub bake: Option, /// What the bake running now has done so far, for the summary when it ends pub bake_report: bake_report::BakeReport, + /// When the out-of-date auto-rebake maps are rebaked + auto_rebake: auto_rebake::AutoRebake, /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, @@ -466,6 +469,7 @@ impl TextureCraftApp { gpu_memory: (Vec::new(), None), bake: None, bake_report: Default::default(), + auto_rebake: Default::default(), pbr_import: None, resize: None, #[cfg(not(target_arch = "wasm32"))] @@ -707,9 +711,12 @@ impl TextureCraftApp { self.session.bake_preview_begin(orders); let total = sets.len(); - self.session.begin_bake_log(&sets); + match only { + Some(map) => self.session.begin_map_bake_log(&sets, map), + None => self.session.begin_bake_log(&sets), + } self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only, rebake: None }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -886,13 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let only = job.only; + let (only, rebake) = (job.only, job.rebake); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); - let task = match only { - Some(map) => self.session.bake_task_only(set_index, map), - None => self.session.bake_task(set_index), + let task = match (rebake, only) { + (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (None, Some(map)) => self.session.bake_task_only(set_index, map), + (None, None) => self.session.bake_task(set_index), }; match task { Ok(task) => { @@ -936,6 +944,10 @@ impl TextureCraftApp { self.session.log.info("Baker", line); } + if self.bake_report.auto_rebake && !failed { + return; + } + self.toast(text, failed); if let Some(toast) = self.toasts.last_mut() { toast.show_log = failed; @@ -1223,6 +1235,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.bake_map_thumbnails.retain_mesh(self.session.mesh_id); bake_mode::poll_live_preview(self, ctx); + auto_rebake::poll(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index aeaaea1f..ce719304 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -297,7 +297,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None, rebake: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6de467e4..9bb1eae2 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -134,6 +134,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { total: 1, mesh_id, only: None, + rebake: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs new file mode 100644 index 00000000..5358fcf1 --- /dev/null +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -0,0 +1,87 @@ +//! Auto-rebake in the app: a settings change rebakes the auto-rebake map alone, in the background + +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::bake::BakeMapState; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +/// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map +fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { + let mesh = primitives::builtin("plane").unwrap(); + let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness +} + +fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serde_json::Value) { + execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); +} + +/// Step frames until `done` holds, up to a generous limit +fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { + for _ in 0..4000 { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("{what} did not happen"); +} + +#[test] +fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { + let mut harness = harness(64); + let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); + assert!(std::sync::Arc::ptr_eq(&app.session.baked(0).unwrap().maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} + +#[test] +fn nothing_is_rebaked_outside_bake_mode() { + let mut harness = harness(64); + harness.state_mut().ui.mode = Mode::Painting; + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + harness.run_steps(120); + + assert!(harness.state().bake.is_none()); + assert!(!harness.state().session.bake_changes(0, BakedMap::Position).is_empty()); +} + +#[test] +fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { + let mut harness = harness(64); + execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["ambientOcclusion"], "ao": { "rays": 1 } })).unwrap(); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": "ambientOcclusion" })).unwrap(); + + // A slow rebake, so the next change lands while it runs + change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); + step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); + harness.run_steps(1); + + let app = harness.state(); + assert!(app.bake.is_none(), "the outdated rebake stopped"); + assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); + execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 309bb67e..f805bfc9 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -22,7 +22,7 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let job_mesh_id = mesh_id(harness.state().session.mesh_id); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None }); + harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); check(&harness, &progress); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 3d098b6f..11251da2 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -63,6 +63,18 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_one_map_bake_lists_only_that_map() { + let mut harness = harness(); + + harness.state_mut().start_bake_of(vec![0], Some(BakedMap::Position)); + run_to_the_end(&mut harness); + + let name = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_label(&format!("{name} Position, Baked")).is_some(), "the baked map is ticked"); + assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0abd9441..0aa4441d 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -3,6 +3,7 @@ mod alpha_parameters; mod anchor_point; +mod auto_rebake; mod bake_job_mesh; mod bake_live_preview; mod bake_map_rows; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 91fad894..308849f3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -326,6 +326,13 @@ Each texture set in `project.inspect` / `session.inspect` lists its out-of-date own). Imported maps, and maps saved before this record existed, never show: `"outOfDate": {"ambientOcclusion": ["mapSettings"]}`. +`bake.autoRebake` `{ts?, map: id | null}` turns on Auto-rebake for one mesh map of a texture set +(the active one by default), replacing its previous one, or turns it off with `null`; it is saved +with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web +app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the +background, alone, once its settings have stopped changing for half a second; a change during +that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. + `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) until `baking` is `null`. From 4a56683bb9a5cadf297fcdfdfa856704e01dddc9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:03:40 +0000 Subject: [PATCH 12/26] Rebake the auto-rebake map inside a skew or cage stroke A skew or cage stroke on a set that bakes from a high poly marks its UV box; in Bake mode the app then bakes the set's auto-rebake map again only there (one texel wider, for the paint map's sampling), keeps the rest of the stored map and pads the whole map, so its pixels match a whole bake. Maps scaled by their whole range (curvature, height, thickness), UV-tiled sets and a map stored at another size bake whole. A stroke painted while that bake runs is baked by the next one. The bake crate gains bake_tiles_in with a texel box. --- crates/bake/src/bake_passes.rs | 19 +++++- crates/bake/src/lib.rs | 60 ++++++++++++++++-- crates/bake/src/progress.rs | 5 +- crates/bake/src/region_bake.rs | 12 ++++ crates/bake/src/test/tile_selection.rs | 2 +- crates/bake/src/tests.rs | 2 +- crates/bake/src/texel_box.rs | 27 ++++++++ crates/engine/src/bake/auto_rebake.rs | 12 ++++ crates/engine/src/bake/bake_log.rs | 10 +-- crates/engine/src/bake/bake_sources.rs | 19 ++++-- crates/engine/src/bake/bake_task.rs | 33 ++++++---- crates/engine/src/bake/mesh_map_command.rs | 30 +++++---- crates/engine/src/bake/mod.rs | 2 + crates/engine/src/bake/paint_command.rs | 9 +++ crates/engine/src/bake/painted_region.rs | 74 ++++++++++++++++++++++ crates/engine/src/bake/streamed_bake.rs | 2 + crates/engine/src/session.rs | 6 ++ crates/engine/tests/it/auto_rebake.rs | 73 +++++++++++++++++++++ crates/engine/tests/it/bake.rs | 2 +- crates/ui-egui/src/auto_rebake.rs | 33 ++++++---- crates/ui-egui/src/lib.rs | 11 ++-- crates/ui-egui/tests/it/auto_rebake.rs | 28 ++++++++ docs/control-protocol.md | 5 +- 23 files changed, 406 insertions(+), 70 deletions(-) create mode 100644 crates/bake/src/region_bake.rs create mode 100644 crates/bake/src/texel_box.rs create mode 100644 crates/engine/src/bake/painted_region.rs diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs index eb7d5846..503bd45d 100644 --- a/crates/bake/src/bake_passes.rs +++ b/crates/bake/src/bake_passes.rs @@ -1,7 +1,7 @@ use crate::cage::RayFrame; use crate::map::BakeContext; use crate::tracing::{CpuTracer, Tracer}; -use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress, RegionBake}; use std::sync::atomic::Ordering::Relaxed; use texturecraft_core::{BakeSettings, BakedMap}; @@ -23,10 +23,22 @@ impl<'a> BakePasses<'a> { progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>, + ) -> Result { + self.bake_map_in(map, progress, excluded_tiles, None, tracer) + } + + /// [`BakePasses::bake_map`] sampling only `region`'s texels, as [`crate::bake_tiles_in`] does + pub fn bake_map_in( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, ) -> Result { let mut settings = self.request.settings.clone(); settings.maps.select([map]); - self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + self.run(&settings, progress, excluded_tiles, region, tracer, super::STRIP_TEXELS) } pub(super) fn run( @@ -34,6 +46,7 @@ impl<'a> BakePasses<'a> { settings: &BakeSettings, progress: &Progress, excluded_tiles: &[(u32, u32)], + region: Option, tracer: Option<&dyn Tracer>, strip_texels: usize, ) -> Result { @@ -56,7 +69,7 @@ impl<'a> BakePasses<'a> { } }; let context = BakeContext::with_frame(&request, *extent, frame); - let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles, region); match tracer { Some(tracer) => match bake(tracer) { Err(BakeError::Tracer(error)) => { diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 5c8c3ba8..50f2f54c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -12,6 +12,8 @@ mod high_poly; mod mesh_extent; mod name_pair; mod progress; +mod region_bake; +mod texel_box; pub use bake_error::BakeError; pub use bake_output::BakeOutput; @@ -22,6 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; +pub use region_bake::RegionBake; +pub use texel_box::{TexelBox, region_keeps_pixels}; mod map; mod skew; @@ -50,6 +54,8 @@ const STRIP_TEXELS: usize = 1 << 24; const BATCH: usize = 1 << 18; // Curvature batches stay small so progress and cancellation remain responsive const CURVATURE_BATCH: usize = 1 << 15; +/// Smallest mesh extent the maps are normalized by, so a flat mesh never divides by zero +const MIN_MESH_EXTENT: f32 = 1e-6; fn validate(request: &BakeRequest) -> Result<(), BakeError> { let settings = request.settings; @@ -161,7 +167,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) + bake_tiles_in(request, progress, excluded_tiles, None, tracer) +} + +/// [`bake_tiles`] sampling only `region`'s texels and padding a whole map; equal to a whole bake for [`region_keeps_pixels`] maps +pub fn bake_tiles_in( + request: &BakeRequest, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + region: Option, + tracer: Option<&dyn Tracer>, +) -> Result { + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; @@ -173,8 +190,9 @@ fn bake_in_strips( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { - BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, region, Some(tracer), strip_texels) } fn bake_prepared( @@ -184,6 +202,7 @@ fn bake_prepared( strip_texels: usize, tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], + region: Option, ) -> Result { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); @@ -211,7 +230,7 @@ fn bake_prepared( let mut padding_map = None; let total_rows = height.max(1) as u64; let mut rows_done = 0u64; - let strip_error = || BakeError::Invalid("strip output of range".into()); + let strip_error = || BakeError::Invalid("strip output out of range".into()); let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis); let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height); @@ -250,6 +269,18 @@ fn bake_prepared( } }); + // Coverage stays the whole map's, so padding matches a whole bake; only the region is sampled + if let Some(region) = region { + for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { + let y = (sample_start_y + row_index) / samples_per_axis; + for (sample_x, triangle) in row.iter_mut().enumerate() { + if !region.texels.contains(sample_x / samples_per_axis, y) { + *triangle = NO_TRI; + } + } + } + } + let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); for (map, data) in maps.iter().zip(buffers.iter_mut()) { let component_count = map.components(); @@ -258,6 +289,7 @@ fn bake_prepared( row.push(chunk); } } + let mut bake_strip = || { for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { @@ -276,10 +308,11 @@ fn bake_prepared( (width, samples_per_axis, sample_start_y * sample_width), )?; rows_done += batch.len() as u64; - progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(u64::from(Progress::DONE)) / total_rows).min(u64::from(Progress::DONE)) as u32, Relaxed); } Ok(()) }; + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { @@ -291,6 +324,19 @@ fn bake_prepared( } } + if let Some(region) = region { + for (map, pixels) in maps.iter().zip(buffers.iter_mut()) { + let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); + let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; + let components = map.components(); + for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { + if !region.texels.contains(index % width, index / width) { + pixel.copy_from_slice(kept); + } + } + } + } + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { let world_normal = @@ -306,7 +352,8 @@ fn bake_prepared( } let (bounds_min, bounds_max) = request.mesh.bounds(); - map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); + map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(MIN_MESH_EXTENT)); + if let Some(padding_map) = padding_map { for (map, data) in output.iter_mut() { padding_map.apply(data, map.components()); @@ -315,11 +362,12 @@ fn bake_prepared( } } } + if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - progress.done.store(10_000, Relaxed); + progress.done.store(Progress::DONE, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs index 5bb924ec..4f0a740c 100644 --- a/crates/bake/src/progress.rs +++ b/crates/bake/src/progress.rs @@ -8,12 +8,15 @@ pub struct Progress { } impl Progress { + /// The basis points of a finished bake + pub const DONE: u32 = 10_000; + pub fn new() -> Self { Self::default() } pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + self.done.load(Relaxed).min(Self::DONE) as f32 / Self::DONE as f32 } pub fn cancel(&self) { diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs new file mode 100644 index 00000000..20a14849 --- /dev/null +++ b/crates/bake/src/region_bake.rs @@ -0,0 +1,12 @@ +use std::collections::BTreeMap; +use std::sync::Arc; +use texturecraft_core::BakedMap; + +use crate::TexelBox; + +/// A bake that samples only `texels` and takes every other texel from `previous`, a whole bake of the same size +#[derive(Clone, Copy, Debug)] +pub struct RegionBake<'a> { + pub texels: TexelBox, + pub previous: &'a BTreeMap>>, +} diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs index 18f13968..a1176668 100644 --- a/crates/bake/src/test/tile_selection.rs +++ b/crates/bake/src/test/tile_selection.rs @@ -31,7 +31,7 @@ fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { let full = bake(&request, &Progress::new()).unwrap(); for excluded in [[(0, 0)], [(1, 0)]] { let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); - let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded, None).unwrap(); let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); assert_eq!(strips.maps, partial.maps); assert_eq!(fallback.maps, partial.maps); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 7d94031e..e0d63b05 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -390,7 +390,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).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(); diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs new file mode 100644 index 00000000..85be4fc0 --- /dev/null +++ b/crates/bake/src/texel_box.rs @@ -0,0 +1,27 @@ +/// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TexelBox { + pub min: (u32, u32), + pub max: (u32, u32), +} + +impl TexelBox { + /// Whether texel (`x`, `y`) lies inside the box + pub fn contains(&self, x: usize, y: usize) -> bool { + (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) + } + + /// The box grown by `texels` on every side, kept inside a `width` x `height` image + pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { + TexelBox { + min: (self.min.0.saturating_sub(texels), self.min.1.saturating_sub(texels)), + max: (self.max.0.saturating_add(texels).min(width), self.max.1.saturating_add(texels).min(height)), + } + } +} + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { + use texturecraft_core::BakedMap; + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 45831b82..e1e3cb1f 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -48,4 +48,16 @@ impl Session { .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) .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) + pub fn auto_rebake_maps(&self, texture_set: usize, map: BakedMap) -> Vec { + let Ok(set) = self.doc.project.texture_set(texture_set) else { return vec![map] }; + let (width, height) = set.bake.common.output_size(); + let stored = self.doc.baked.get(&texture_set); + let resized = stored.is_some_and(|stored| stored.resolution != width || stored.maps.keys().any(|baked| stored.height(*baked) != height)); + match resized { + true => BakedMap::ALL.into_iter().filter(|baked| *baked == map || set.bake.maps.is_enabled(*baked)).collect(), + false => vec![map], + } + } } diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 18ab8e2a..90e8feaf 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -136,15 +136,15 @@ impl Session { self.bake_log.matching = matching; } - /// Start the Baking Log for a bake of only `map` of each of `sets`, checked or not - pub fn begin_map_bake_log(&mut self, sets: &[usize], map: BakedMap) { + /// Start the Baking Log for a bake of only `maps` of each of `sets`, checked or not + pub fn begin_map_bake_log(&mut self, sets: &[usize], maps: &[BakedMap]) { self.begin_bake_log(sets); let project = &self.doc.project; self.bake_log.maps = sets .iter() - .filter_map(|&texture_set| { - let set_name = project.texture_sets.get(texture_set)?.name.clone(); - Some(BakeLogMap { texture_set, set_name, map, state: BakeMapState::Waiting }) + .filter_map(|&texture_set| Some((texture_set, project.texture_sets.get(texture_set)?.name.clone()))) + .flat_map(|(texture_set, set_name)| { + maps.iter().map(move |&map| BakeLogMap { texture_set, set_name: set_name.clone(), map, state: BakeMapState::Waiting }) }) .collect(); } diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index 70f7665c..e835c97c 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -44,22 +44,31 @@ impl Session { 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 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) }) } - /// Keep `sources` as what maps of `texture_set` were baked from; without them the `stored` maps lose their record - pub(super) fn record_bake_sources(&mut self, texture_set: usize, sources: Option<&BTreeMap>, stored: &[BakedMap]) -> Result<()> { + /// Keep what the `stored` maps of `texture_set` were baked from and the newest stroke their bake saw; without it they lose their record + pub(super) fn record_bake_sources( + &mut self, + texture_set: usize, + recorded: Option<(&BTreeMap, u64)>, + stored: &[BakedMap], + ) -> Result<()> { let set = self.doc.project.texture_set_mut(texture_set)?; - match sources { - Some(sources) => set.bake_sources.extend(sources), + match recorded { + Some((sources, _)) => set.bake_sources.extend(sources), None => set.bake_sources.retain(|map, _| !stored.contains(map)), } let baked = &set.baked; set.bake_sources.retain(|map, _| baked.contains(map)); + if let Some((_, painted_stroke)) = recorded { + self.forget_painted_region(texture_set, stored, painted_stroke); + } Ok(()) } } diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 3c0cb59e..35bee3b4 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,12 +1,12 @@ use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, RegionBake, TexelBox, bake_tiles_in, tracing::Tracer}; use texturecraft_compose::BakedMaps; use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; -/// A self-contained bake task that can run on another thread. +/// A self-contained bake task that can run on another thread pub struct BakeTask { pub low_base_color: super::MaterialColors, pub ts: usize, @@ -14,20 +14,24 @@ pub struct BakeTask { pub bvh: Arc, pub material: usize, pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. + /// The merged high polys, unless the set bakes from the low poly pub high: Option, pub cage: Option>, pub skew: Option>, pub cage_paint: Option>, - /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. + /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles pub tiles: (u32, u32), /// Snapshot of tile selection and pixels to retain while the worker runs pub excluded_tiles: Vec<(u32, u32)>, pub previous_maps: BakedMaps, - /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). + /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`) pub tracer: Option>, /// What each map this task makes is baked from, taken when the task was made pub sources: std::collections::BTreeMap, + /// The newest skew or cage stroke when the task was made; a later stroke still needs a rebake + pub painted_stroke: u64, + /// Sample only these texels and take the rest from `previous_maps` (the same size); `None` samples every texel + pub region: Option, } impl BakeTask { @@ -36,13 +40,7 @@ impl BakeTask { self.settings.maps.enabled().collect() } - /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, - /// and return all of them together. Each map is a bake of its own, so with a high poly - /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several - /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. - /// The handed-over buffers are the returned ones too (no copy is made), so a preview that - /// keeps them costs no second set of maps. A cancel or an error leaves the maps already - /// handed over whole. + /// Bake the maps one by one (same pixels as [`BakeTask::run`], rays cast per map), handing each padded map's shared buffer to `on_map`, then return them all pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { let maps = self.maps(); let total = maps.len(); @@ -50,7 +48,7 @@ impl BakeTask { let mut passes = BakePasses::new(self.request()); for (index, map) in maps.iter().copied().enumerate() { - let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = passes.bake_map_in(map, progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; let Some(data) = output.maps.remove(&map) else { continue }; if combined.is_none() { @@ -74,6 +72,7 @@ impl BakeTask { maps: retained, tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }); } } @@ -89,18 +88,24 @@ impl BakeTask { maps: output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(), tracer: output.tracer, sources: self.sources.clone(), + painted_stroke: self.painted_stroke, }) } } } pub fn run(&self, progress: &Progress) -> Result { - let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + let mut output = bake_tiles_in(&self.request(), progress, &self.excluded_tiles, self.region(), self.tracer.as_deref()).map_err(bake_error)?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; Ok(output) } + /// The texels to sample, with the stored maps to take the rest from; `None` samples every texel + fn region(&self) -> Option> { + self.region.map(|texels| RegionBake { texels, previous: &self.previous_maps.maps }) + } + fn request(&self) -> BakeRequest<'_> { let high = self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 474a5266..49d25503 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -206,6 +206,8 @@ impl Session { previous_maps, tracer, sources, + painted_stroke: self.painted_strokes, + region: None, }) } @@ -273,19 +275,20 @@ impl Session { Ok(()) } - /// Apply a streamed bake like [`Session::apply_bake`], keeping the maps' shared buffers (the - /// preview that showed them holds the same ones) + /// Apply a streamed bake like [`Session::apply_bake`], keeping the buffers the preview that showed them shares pub fn apply_streamed_bake(&mut self, texture_set: usize, output: StreamedBake) -> Result<()> { let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some(&output.sources)))?; + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, output.resolution, output.height, output.maps, Some((&output.sources, output.painted_stroke))) + })?; self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(()) } - /// Store `output`, recording what its maps were baked from when `sources` are known - fn store_bake(&mut self, texture_set: usize, output: BakeOutput, sources: Option<&BTreeMap>) -> Result<()> { + /// Store `output`, recording what its maps were baked from when known (see [`Session::record_bake_sources`]) + fn store_bake(&mut self, texture_set: usize, output: BakeOutput, recorded: Option<(&BTreeMap, u64)>) -> Result<()> { let maps = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); - self.store_bake_maps(texture_set, output.resolution, output.height, maps, sources) + self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } fn store_bake_maps( @@ -294,7 +297,7 @@ impl Session { resolution: u32, height: u32, maps: BTreeMap>>, - sources: Option<&BTreeMap>, + recorded: Option<(&BTreeMap, u64)>, ) -> Result<()> { let stored: Vec = maps.keys().copied().collect(); let entry = self.doc.baked.entry(texture_set).or_default(); @@ -305,18 +308,19 @@ impl Session { entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); - self.record_bake_sources(texture_set, sources, &stored) + self.record_bake_sources(texture_set, recorded, &stored) } - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. + /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; } - let out = task.run(&Progress::new())?; - let tracer = out.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, out, Some(&task.sources)))?; + + let output = task.run(&Progress::new())?; + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); Ok(tracer) } @@ -897,7 +901,7 @@ fn bake_one_set(session: &mut Session, index: usize, cpu: bool) -> Result Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; + session.note_bake_paint(texture_set, None); Ok(super::meshes_json(session)) } @@ -75,6 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> session.doc.bake_paint.remove(&(texture_set, target)); Ok(()) })?; + session.note_bake_paint(texture_set, None); } Ok(super::meshes_json(session)) } @@ -123,6 +125,13 @@ 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 + 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))); Ok(super::meshes_json(session)) } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs new file mode 100644 index 00000000..4c31b533 --- /dev/null +++ b/crates/engine/src/bake/painted_region.rs @@ -0,0 +1,74 @@ +//! Where skew or cage painting changed what a texture set's transfer rays read since its maps were baked + +use texturecraft_bake::{TexelBox, region_keeps_pixels}; +use texturecraft_core::{BakeSource, BakedMap}; +use texturecraft_geom::glam::Vec2; + +use crate::{Result, Session}; + +/// The UV box painted since the last bake of a texture set's auto-rebake map +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PaintedRegion { + pub uv_min: Vec2, + pub uv_max: Vec2, + /// Counts up with every stroke, so a rebake can tell a newer stroke from the one it bakes + pub stroke: u64, +} + +/// Texels added around a painted box: bilinear sampling of the paint map and antialiasing samples reach one texel past it +const MARGIN_TEXELS: u32 = 1; + +impl Session { + /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) + pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { + let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); + let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), + None => (uv_min, uv_max), + }; + self.painted_strokes += 1; + self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + } + + /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` + pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { + let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); + let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { + self.painted_regions.remove(&texture_set); + } + } + + /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) + pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { + let regions = self.painted_regions.iter(); + regions + .filter_map(|(index, region)| { + let set = self.doc.project.texture_sets.get(*index)?; + let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; + let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); + (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; + Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + }) + .collect() + } + + /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map + pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { + let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; + let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + let (width, height) = task.settings.common.output_size(); + let stored = + self.doc.baked.get(&texture_set).filter(|stored| stored.resolution == width && stored.height(map) == height && stored.maps.contains_key(&map)); + let Some(stored) = stored.filter(|_| task.tiles == (1, 1) && region_keeps_pixels(map)) else { return Ok(task) }; + + let texel = |uv: f32, size: u32, round: fn(f32) -> f32| (round(uv.clamp(0.0, 1.0) * size as f32) as u32).min(size); + let painted = TexelBox { + min: (texel(region.uv_min.x, width, f32::floor), texel(region.uv_min.y, height, f32::floor)), + max: (texel(region.uv_max.x, width, f32::ceil), texel(region.uv_max.y, height, f32::ceil)), + }; + task.previous_maps = stored.clone(); + task.region = Some(painted.grown(MARGIN_TEXELS, width, height)); + Ok(task) + } +} diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs index 67d9be30..4b2895df 100644 --- a/crates/engine/src/bake/streamed_bake.rs +++ b/crates/engine/src/bake/streamed_bake.rs @@ -13,4 +13,6 @@ pub struct StreamedBake { pub tracer: String, /// What the baked maps were baked from (the task's [`crate::BakeTask::sources`]) pub sources: BTreeMap, + /// The task's [`crate::BakeTask::painted_stroke`] + pub painted_stroke: u64, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 05a0c779..35922e64 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -427,6 +427,10 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, + /// Where skew or cage painting changed each texture set since its auto-rebake map was baked + pub(crate) painted_regions: std::collections::BTreeMap, + /// Skew and cage strokes so far + pub(crate) painted_strokes: u64, pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Arc>)>, @@ -530,6 +534,8 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), + painted_regions: Default::default(), + painted_strokes: 0, mesh, bvh: Arc::new(bvh), mesh_source: mesh_source.map(|(extension, bytes)| (extension, Arc::new(bytes))), diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index c424ef47..e5f9978a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -66,3 +66,76 @@ fn a_one_map_bake_brings_that_map_up_to_date_and_leaves_the_others_alone() { assert!(std::sync::Arc::ptr_eq(&baked.maps[&BakedMap::Id], &id_before), "the ID map was not baked again"); assert_eq!(session.doc.project.texture_sets[0].bake.maps.enabled().collect::>(), [BakedMap::Id], "the checks stay"); } + +#[test] +fn a_new_output_size_rebakes_every_checked_map_so_none_is_lost() { + let mut session = baked_plane(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "resolution": 128 })).unwrap(); + + let maps = session.auto_rebake_maps(0, BakedMap::Position); + let output = session.bake_task_for(0, &maps).unwrap().run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let baked = session.baked(0).unwrap(); + assert!(baked.maps.contains_key(&BakedMap::Id), "the ID map survives the new size: {:?}", baked.maps.keys().collect::>()); + assert!(session.out_of_date_maps(0).is_empty(), "{:?}", session.out_of_date_maps(0)); +} + +#[test] +fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "nothing painted since the bake"); + let before = session.baked(0).unwrap().maps[&BakedMap::Position].clone(); + + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3], [0.4, 0.35]], "radius": 0.05, "size": 64 })).unwrap(); + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)]); + assert!(session.auto_rebake_due().is_empty(), "painting is not a settings change: {:?}", due_maps(&session)); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let region = task.region.expect("a stroke rebakes only its box"); + let mut whole = session.bake_task_for(0, &[BakedMap::Position]).unwrap(); + whole.tracer = None; + let whole = whole.run(&Progress::new()).unwrap().maps.remove(&BakedMap::Position).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + + let width = output.resolution as usize; + assert!(((region.max.0 - region.min.0) as usize) < width / 2, "the box is far smaller than the map: {region:?}"); + let components = BakedMap::Position.components(); + let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); + let mut changed = 0; + for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + if region.contains(index % width, index / width) { + assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); + changed += usize::from(rebaked != kept); + } else { + assert_eq!(rebaked, kept, "texel {index} outside the box"); + } + } + assert!(changed > 0, "the stroke changed the map inside its box"); + + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); +} + +#[test] +fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + let stroke = |at: f32| json!({ "points": [[at, at]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.skew.paint", &stroke(0.3)).unwrap(); + + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + execute(&mut session, "bake.skew.paint", &stroke(0.7)).unwrap(); + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); +} diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4035c0f1..ef79a439 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -527,7 +527,7 @@ fn opacity_samples_textures_next_to_a_high_poly() { } /// A plane session whose vertex normals lean, with a high poly plane `dy` above it. -fn leaning_session(lean: bool) -> Session { +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()]; diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8f20e7b0..49221003 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -7,16 +7,16 @@ use crate::{BakeJob, TextureCraftApp, bake_report, state}; /// How long what an out-of-date auto-rebake map is baked from must stay the same before the rebake starts const SETTLE_SECONDS: f64 = 0.5; -/// An out-of-date auto-rebake map: its texture set, the map and what a bake would read now -pub type Due = (usize, BakedMap, BakeSource); +/// An out-of-date auto-rebake map: set, map, what a bake reads now, and the newest stroke when only painting changed it +pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, - /// The due maps when the last rebake started: a failed or canceled rebake is not tried again until something changes - started: Vec, + /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes + tried: Vec, } /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed @@ -26,16 +26,20 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - let due = app.session.auto_rebake_due(); + let stale = app.session.auto_rebake_due().into_iter().map(|(set, map, source)| (set, map, source, None)); + let painted = app.session.auto_rebake_painted().into_iter().map(|(set, map, source, stroke)| (set, map, source, Some(stroke))); + let due: Vec = stale.chain(painted).collect(); if let Some(job) = &app.bake { // Newest wins: a rebake whose map changed again while it ran starts over with the new settings - if job.rebake.is_some_and(|rebake| !due.contains(&rebake)) { + if job.rebake.as_ref().is_some_and(|rebake| !due.contains(rebake)) { app.cancel_bake(); } return; } - if due.is_empty() || due == app.auto_rebake.started { + app.auto_rebake.tried.retain(|tried| due.contains(tried)); + let waiting: Vec = due.into_iter().filter(|due| !app.auto_rebake.tried.contains(due)).collect(); + if waiting.is_empty() { app.auto_rebake.pending = None; return; } @@ -43,24 +47,24 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); match &app.auto_rebake.pending { - Some((seen, since)) if *seen == due && now - since >= SETTLE_SECONDS => {} - Some((seen, _)) if *seen == due => return, + Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} + Some((seen, _)) if *seen == waiting => return, _ => { - app.auto_rebake.pending = Some((due, now)); + app.auto_rebake.pending = Some((waiting, now)); return; } } app.auto_rebake.pending = None; - app.auto_rebake.started = due.clone(); - if let Some(rebake) = due.first().copied() { + if let Some(rebake) = waiting.first().copied() { + app.auto_rebake.tried.push(rebake); start(app, rebake); } } /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map, _) = rebake; + let (set, map) = (rebake.0, rebake.1); let orders = match app.session.bake_preview_orders(&[set], Some(map)) { Ok(orders) => orders, Err(error) => { @@ -73,7 +77,8 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); app.session.bake_preview_begin(orders); - app.session.begin_map_bake_log(&[set], map); + let maps = app.session.auto_rebake_maps(set, map); + app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2816c247..24373d2e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -712,7 +712,7 @@ impl TextureCraftApp { let total = sets.len(); match only { - Some(map) => self.session.begin_map_bake_log(&sets, map), + Some(map) => self.session.begin_map_bake_log(&sets, &[map]), None => self.session.begin_bake_log(&sets), } self.bake_report = bake_report::BakeReport::started(self.last_time); @@ -893,12 +893,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); - let (only, rebake) = (job.only, job.rebake); + let only = job.only; + let rebake = job.rebake.as_ref().map(|(_, map, _, stroke)| (*map, stroke.is_some())); self.session.bake_preview_set_current(set_index); self.session.bake_log.set_started(set_index); let task = match (rebake, only) { - (Some((_, map, _)), _) => self.session.bake_task_for(set_index, &[map]), + (Some((map, true)), _) => self.session.bake_painted_task(set_index, map), + (Some((map, false)), _) => self.session.bake_task_for(set_index, &self.session.auto_rebake_maps(set_index, map)), (None, Some(map)) => self.session.bake_task_only(set_index, map), (None, None) => self.session.bake_task(set_index), }; @@ -954,8 +956,7 @@ impl TextureCraftApp { } } - /// Cancel the active worker, discard queued sets and restore the view. The current set's - /// preview maps are discarded; previously applied sets keep their results and undo steps. + /// Cancel the running set's bake and the queued ones and restore the view; sets already applied keep their maps and undo steps pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 5358fcf1..af6062e2 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -85,3 +85,31 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); } + +#[test] +fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { + let mut harness = harness(64); + let plane = primitives::builtin("plane").unwrap(); + let mut high = String::from("o Part_high\n"); + for position in &plane.positions { + high += &format!("v {} {} {}\n", position.x, position.y + 0.1, position.z); + } + for triangle in plane.indices.as_chunks::<3>().0 { + high += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); + } + let session = &mut harness.state_mut().session; + session.add_high_poly_bytes("high.obj", high.into_bytes()).unwrap(); + execute(session, "bake.run", &json!({ "maps": ["position"] })).unwrap(); + harness.run_steps(4); + assert!(harness.state().bake.is_none(), "up to date after the bake"); + + execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + + let app = harness.state(); + assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + let rows: Vec<_> = app.session.bake_log.maps.iter().map(|row| (row.map, row.state.clone())).collect(); + assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); + assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 308849f3..fa72d973 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -331,7 +331,10 @@ own). Imported maps, and maps saved before this record existed, never show: with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the background, alone, once its settings have stopped changing for half a second; a change during -that bake restarts it. The headless CLI does not rebake by itself: run `bake.run` there. +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 +whole. The headless CLI does not rebake by itself: run `bake.run` there. `{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with `ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) From f39e99069c5dd436251b0a4c08bf4b2c430b1613 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:05:31 +0000 Subject: [PATCH 13/26] Turn Auto-rebake on for the Normal map when skew painting starts The first skew stroke of a texture set turns Auto-rebake on for its Normal map, unless the set already has an auto-rebake map; it is part of the stroke's undo step. --- crates/engine/src/bake/mesh_map_command.rs | 7 ++-- crates/engine/src/bake/paint_command.rs | 32 +++++++++++++---- crates/engine/tests/it/auto_rebake.rs | 40 +++++++++++++++++++++- docs/control-protocol.md | 16 +++++---- 4 files changed, 78 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 49d25503..70b9fe7d 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -861,7 +861,9 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - let tracers = session.edit("Bake mesh maps", |session| { + // The painted boxes are not in the document, so a rolled-back bake puts them back by hand + let painted_regions = session.painted_regions.clone(); + let baked = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -882,7 +884,8 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - })?; + }); + let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 2f6c6fc0..840b097e 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -3,7 +3,7 @@ use crate::{Result, Session, cmd}; use serde_json::Value; use std::sync::Arc; use texturecraft_bake::BakePaintMap; -use texturecraft_core::BakePaintTarget; +use texturecraft_core::{BakePaintTarget, BakedMap}; use texturecraft_geom::glam::Vec2; pub(super) fn specs() -> Vec { @@ -81,14 +81,22 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(super::meshes_json(session)) } +/// Most UV points one `bake.paint` call takes +const MAX_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; +/// 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 = 16..=4096; + fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { - const MAX_POINTS: usize = 100_000; let texture_set = texture_set(session, parameters)?; let points = parameters .get("points") .and_then(Value::as_array) .filter(|points| !points.is_empty() && points.len() <= MAX_POINTS) - .ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?; + .ok_or_else(|| bad("bake.paint", format!("points must contain 1 to {MAX_POINTS} UV coordinates")))?; let points = points .iter() .map(|point| { @@ -99,17 +107,19 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } }) .collect::>>()?; + let value = number(parameters, "value", 1.0, 0.0, 1.0)?; - let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?; + let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { - None => 1024, + None => DEFAULT_PAINT_SIZE, Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?, }; - if !(16..=4096).contains(&size) { - return Err(bad("bake.paint", "size must be between 16 and 4096")); + if !PAINT_SIZES.contains(&size) { + return Err(bad("bake.paint", format!("size must be between {} and {}", PAINT_SIZES.start(), PAINT_SIZES.end()))); } + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0, @@ -118,7 +128,15 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> BakePaintTarget::Cage => "Paint Cage", BakePaintTarget::Skew => "Paint Skew Correction", }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + // Skew painting starts with Auto-rebake on for the Normal map, which shows the skew best, unless the set picked one + let first_skew = target == BakePaintTarget::Skew && !session.doc.bake_paint.contains_key(&(texture_set, target)); + let set = session.doc.project.texture_set_mut(texture_set)?; + if first_skew && set.auto_rebake.is_none() { + set.auto_rebake = Some(BakedMap::Normal); + } + let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default))); if map.values.len() == 1 { *map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index e5f9978a..8dd1d80a 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -4,7 +4,7 @@ use serde_json::json; use texturecraft_engine::bake::Progress; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, execute, sample_session}; /// A plane with its position and ID maps baked fn baked_plane() -> Session { @@ -139,3 +139,41 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } + +#[test] +fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { + let mut session = sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("detail_high.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "ts": 0, "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "ts": 0, "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake.maps.ao; + second.is_enabled = true; + second.parameters.rays.rays = 0; + + assert!(execute(&mut session, "bake.run", &json!({ "ts": "all" })).is_err(), "set 1's AO has no rays to cast"); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "set 0's stroke is still waiting for its rebake"); +} + +#[test] +fn the_first_skew_stroke_turns_auto_rebake_on_for_the_normal_map_once() { + let mut session = super::bake::leaning_session(true); + let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 }); + execute(&mut session, "bake.cage.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "cage painting leaves it alone"); + + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Normal)); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "undone with the stroke"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, Some(BakedMap::Position), "a map picked before stays"); + + execute(&mut session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + execute(&mut session, "bake.skew.paint", &stroke).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].auto_rebake, None, "turned off after skew painting started, it stays off"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index fa72d973..8c74d39a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -305,6 +305,10 @@ also `session.inspect`'s `bakePreview`: "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} ``` +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + `bake.log` `{}` returns the latest bake map by map, as the Baking Log shows it (empty before the first bake). A map's `state` is `waiting`, `baking`, `baked`, `failed` (with the error as `reason`) or `canceled`. `highPolys` lists the high poly files of each set that bakes from them; a file's `state` is `waiting`, @@ -314,7 +318,7 @@ with no partner. It is `null` when no set of the bake matches by mesh name: ```json {"running": false, "maps": [{"textureSet": 0, "setName": "Body", "map": "normal", "state": "baked"}, - {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "no UV tile left to bake"}], + {"textureSet": 1, "setName": "Head", "map": "normal", "state": "failed", "reason": "texture set Head has no UV tiles selected for baking"}], "highPolys": [{"textureSet": 0, "setName": "Body", "file": "body_high.fbx", "state": "loaded"}], "matching": {"lowSuffix": "_low", "highSuffix": "_high", "pairs": [{"low": "Arm_low", "high": "Arm_high"}, {"low": "Strap_low", "high": null}]}} @@ -330,15 +334,13 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone, once its settings have stopped changing for half a second; a change during +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 -whole. The headless CLI does not rebake by itself: run `bake.run` there. - -`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with -`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) -until `baking` is `null`. +whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its +`normal` map when the set has none, in the stroke's undo step. The headless CLI does not rebake by +itself: run `bake.run` there. A minimal client (Python, for illustration): From 7f3b16d434552acd984d96b4c899254cd1cf939f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:32:34 +0000 Subject: [PATCH 14/26] Mark out-of-date maps in Mesh Map Bakers A baked map whose mesh, high poly, cage or settings changed after its bake gets a yellow clock at the right end of its row; hovering it lists what changed. The reasons are shared with the generator's bake note. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 52 ++++++++++++++----- .../ui-egui/src/generator_panel/bake_note.rs | 13 +---- crates/ui-egui/src/i18n.rs | 13 +++++ crates/ui-egui/tests/it/bake_mode.rs | 22 ++++++++ 4 files changed, 77 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 7ec44f70..d6a7d741 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,15 +1,15 @@ -use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::ViewMode; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{CHECK_SIZE, paint_check}; use crate::theme::{Tokens, semibold}; @@ -46,6 +46,8 @@ const ROW_RADIUS: u8 = 4; const HOVER_FACE_OPACITY: f32 = 0.5; /// Air above and below the hairline under Check All const RULE_AIR: f32 = 4.0; +/// Size of a row icon's tooltip title and reasons +const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { @@ -85,8 +87,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); + let out_of_date = app.session.out_of_date_maps(app.session.ts()); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } @@ -239,13 +243,14 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +/// One baker row, with a clock at its right end while `changes` make the map out of date (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked fn row( app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, + changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, ) -> bool { @@ -253,7 +258,7 @@ fn row( let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_selected, name)); let hovered = ui.rect_contains_pointer(rect); if is_selected { @@ -280,18 +285,17 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let mut icons_left = rect.right(); + if !changes.is_empty() { + let clock = icon_slot(&mut icons_left, rect.center().y); + out_of_date_mark(ui, clock, name, changes); + } let focus_in_row = || { ui.memory(|memory| memory.focused()) .and_then(|id| ui.ctx().read_response(id)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; if is_selected || hovered || focus_in_row() { - let mut next_icon = || { - let slot = - Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - icons_left = slot.left() - ROW_INSET / 2.0; - slot - }; + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); if several_sets { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; @@ -430,3 +434,27 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); response } + +/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed +fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let title = tr("Out of date"); + let label = trf("Out of date: {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + for change in changes { + ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + } + }); +} + +/// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it +fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { + let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + *icons_left = slot.left() - ROW_INSET / 2.0; + slot +} diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 4953261d..2e46ef22 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -7,7 +7,7 @@ use texturecraft_engine::bake::settings_patch; use texturecraft_engine::core::{BakeChange, BakedMap, Generator}; use crate::TextureCraftApp; -use crate::i18n::{baked_map_label, tr, trf}; +use crate::i18n::{bake_change_reason, baked_map_label, tr, trf}; use crate::property_sheet::{PropertySheet, SIDE_PADDING_POINTS}; use crate::theme::{Tokens, semibold}; @@ -82,16 +82,7 @@ fn reasons(changes: &[BakeChange], checked: bool) -> Vec<&'static str> { return reasons; } - changes - .iter() - .map(|change| match change { - BakeChange::LowPoly => tr("The mesh changed after this bake."), - BakeChange::HighPoly => tr("The high poly files changed after this bake."), - BakeChange::Cage => tr("The cage changed after this bake."), - BakeChange::Settings => tr("The common bake settings changed after this bake."), - BakeChange::MapSettings => tr("This map's bake settings changed after this bake."), - }) - .collect() + changes.iter().map(|change| tr(bake_change_reason(*change))).collect() } /// Bake `texture_set` in the background, turning `map` on in its bake settings first when it is off diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2210638e..0b94a4fe 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -96,6 +96,19 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta } } +/// Why a baked map is out of date: one sentence for what changed after its bake +pub(crate) fn bake_change_reason(change: texturecraft_engine::core::BakeChange) -> &'static str { + use texturecraft_engine::core::BakeChange; + + match change { + BakeChange::LowPoly => n_("The mesh changed after this bake."), + BakeChange::HighPoly => n_("The high poly files changed after this bake."), + BakeChange::Cage => n_("The cage changed after this bake."), + BakeChange::Settings => n_("The common bake settings changed after this bake."), + BakeChange::MapSettings => n_("This map's bake settings changed after this bake."), + } +} + /// The saved language that follows the operating system's (Settings > Language > Default (System Language)). pub const SYSTEM_LANGUAGE: &str = ""; diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 720d4c49..ca4cede4 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -697,3 +697,25 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } + +#[test] +fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { + use serde_json::json; + use texturecraft_engine::execute; + + let mesh = texturecraft_engine::geom::primitives::builtin("plane").unwrap(); + let mut session = texturecraft_engine::Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1200.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + assert!(harness.query_by_label("Out of date: Position").is_none(), "just baked"); + + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.run_steps(3); + harness.get_by_label("Out of date: Position"); + assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); +} From 23f27ba16d22d9dbeac2c20addadb83192ccb4c4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:35:55 +0000 Subject: [PATCH 15/26] Toggle Auto-rebake from a Mesh Map Bakers row Each row gets an Auto-rebake icon at its right end. It stays shown and bright on the set's auto-rebake map; on the other rows it shows dim while the row is hovered, and bright while the icon is hovered or has focus. Clicking it makes that map the set's auto-rebake map, or turns Auto-rebake off. --- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 104 +++++++++++++----- crates/ui-egui/src/bake_mode/mod.rs | 1 + crates/ui-egui/src/bake_mode/row_click.rs | 5 + crates/ui-egui/src/baking_log.rs | 15 ++- crates/ui-egui/tests/it/auto_rebake.rs | 77 +++++++++---- crates/ui-egui/tests/it/bake_mode.rs | 18 +++ crates/ui-egui/tests/it/baking_log.rs | 17 +-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +-- crates/ui-egui/tests/it/main.rs | 17 +++ 9 files changed, 193 insertions(+), 74 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/row_click.rs diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index d6a7d741..afea363c 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,10 +1,11 @@ use egui::{Align, Align2, CornerRadius, FontId, Layout, Pos2, Rect, RichText, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Value, json}; use texturecraft_engine::ViewMode; use texturecraft_engine::core::{BakeChange, BakeSettings, BakeSyncGroup, BakedMap}; use super::glyph_look::GlyphLook; +use super::row_click::RowClick; use super::set_picker::SetPicker; use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; @@ -34,8 +35,13 @@ const ROW_INSET: f32 = 6.0; /// Side of a row's map thumbnail, and the air on its sides const THUMBNAIL_SIZE: f32 = 22.0; const THUMBNAIL_AIR: f32 = 9.0; -/// Side of a row's icon buttons and of the list menu button +/// Side of the header icon slots and of the list menu button const ROW_BUTTON_SIZE: f32 = 20.0; +/// Side of a row's hover icons, and the air right of each: four icons stay right of the row's middle in the Bakers column, so a click there selects the row +const ROW_ICON_SIZE: f32 = 18.0; +const ROW_ICON_GAP: f32 = 1.0; +/// Radius of the out-of-date clock on a thumbnail's corner +const CLOCK_BADGE_RADIUS: f32 = 6.0; /// Size of a row's glyphs const ROW_GLYPH_SIZE: f32 = 14.0; /// Size of the map names @@ -49,7 +55,7 @@ const RULE_AIR: f32 = 4.0; /// Size of a row icon's tooltip title and reasons const TOOLTIP_TEXT_SIZE: f32 = 12.0; -/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects, a hover icon toggles Auto-rebake) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { let several_sets = app.session.doc.project.texture_sets.len() > 1; ui.add_space(HEADER_AIR); @@ -87,12 +93,18 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); - let out_of_date = app.session.out_of_date_maps(app.session.ts()); + let texture_set = app.session.ts(); for map in BakedMap::ALL { - let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, changes, &mut check_drag, drag_from)).inner { - app.ui.selected_baked_map = Some(map); - app.ui.dock.focus(Panel::MeshMapSettings); + match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + Some(RowClick::Row) => { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + Some(RowClick::AutoRebake) => { + let 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 })); + } + None => {} } } @@ -243,17 +255,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row, with a clock at its right end while `changes` make the map out of date (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, - changes: &[BakeChange], check_drag: &mut Option, drag_from: Option, -) -> bool { +) -> Option { let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); @@ -284,27 +295,36 @@ fn row( let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); thumbnail(ui, thumbnail_rect, texture.as_ref()); - let mut icons_left = rect.right(); + let texture_set = app.session.ts(); + let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - let clock = icon_slot(&mut icons_left, rect.center().y); - out_of_date_mark(ui, clock, name, changes); + 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)) .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) }; - if is_selected || hovered || focus_in_row() { - let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); - if several_sets { + let is_active = is_selected || hovered || focus_in_row(); + let is_auto_rebake = auto_rebake_map(app, texture_set) == Some(map); + let mut icons_left = rect.right(); + let mut next_icon = || icon_slot(&mut icons_left, rect.center().y); + let sync_slot = several_sets.then(&mut next_icon); + let toggle = next_icon(); + let mut toggled = false; + if is_active { + if let Some(slot) = sync_slot { let shares = settings.sync.shares(BakeSyncGroup::Map(map)); let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; - let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); + let sync = glyph_button(ui, slot, glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); if sync.clicked() { SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); } } + toggled = auto_rebake_toggle(ui, toggle, name, is_auto_rebake).clicked(); let baking = app.bake_progress().is_some(); let bolt = next_icon(); let bolt_label = trf("Bake {map} Only", &[("map", &name)]); @@ -318,6 +338,10 @@ fn row( let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; app.run("viewport.view", json!({ "mode": mode })); } + } else if is_auto_rebake { + toggled = auto_rebake_toggle(ui, toggle, name, true).clicked(); + } else { + icons_left = rect.right(); } let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; @@ -360,7 +384,35 @@ fn row( response.request_focus(); } - response.clicked() + if toggled { + Some(RowClick::AutoRebake) + } else if response.clicked() { + Some(RowClick::Row) + } else { + None + } +} + +/// The map texture set `texture_set` rebakes on its own, if any +fn auto_rebake_map(app: &TextureCraftApp, texture_set: usize) -> Option { + app.session.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake) +} + +/// The Auto-rebake toggle in `rect`: bright while on or pointed at, dim while off +fn auto_rebake_toggle(ui: &mut Ui, rect: Rect, name: &str, is_on: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("auto_rebake"), Sense::click()); + let title = tr("Auto-rebake"); + let label = trf("Auto-rebake {map}", &[("map", &name)]); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, is_on, &label)); + + let is_pointed = response.hovered() || response.has_focus(); + let color = if is_on || is_pointed { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::ARROWS_CLOCKWISE, FontId::proportional(ROW_GLYPH_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response.on_hover_ui(|ui| { + ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); + }) } /// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` @@ -435,14 +487,16 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock in `rect` of a map that `changes` made out of date since its bake; hover tells what changed -fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) { +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with("out_of_date"), Sense::hover()); + let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); - ui.painter().text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(ROW_GLYPH_SIZE), tokens.warning); + let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; + ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); + ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); @@ -454,7 +508,7 @@ fn out_of_date_mark(ui: &mut Ui, rect: Rect, name: &str, changes: &[BakeChange]) /// The next icon slot leftwards from `icons_left`, centred on `center_y`; moves `icons_left` past it fn icon_slot(icons_left: &mut f32, center_y: f32) -> Rect { - let slot = Rect::from_center_size(pos2(*icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, center_y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); - *icons_left = slot.left() - ROW_INSET / 2.0; + let slot = Rect::from_center_size(pos2(*icons_left - ROW_ICON_SIZE / 2.0 - ROW_ICON_GAP, center_y), vec2(ROW_ICON_SIZE, ROW_ICON_SIZE)); + *icons_left = slot.left(); slot } diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1efb19d3..cf81d8d1 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -23,6 +23,7 @@ mod map_settings; mod map_thumbnails; mod mesh_map_bakers; pub use map_thumbnails::MapThumbnails; +mod row_click; mod set_picker; mod set_picker_purpose; mod set_picker_row; diff --git a/crates/ui-egui/src/bake_mode/row_click.rs b/crates/ui-egui/src/bake_mode/row_click.rs new file mode 100644 index 00000000..5f77dfd0 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/row_click.rs @@ -0,0 +1,5 @@ +/// What a click on a Mesh Map Bakers row hit +pub(super) enum RowClick { + Row, + AutoRebake, +} diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index 1ee11974..e490ff85 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -124,7 +124,7 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { /// Show `map`'s settings of `texture_set` in Mesh Map Settings, as picking it in Mesh Map Bakers does fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMap) { - // The set may have been deleted since the bake + // A guard against a row naming a set the session no longer has if texture_set >= app.session.set_count() { return; } @@ -226,16 +226,19 @@ fn no_issues(ui: &mut Ui, tab: BakingLogTab) { ui.allocate_rect(area, Sense::hover()); } -/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting's name in SemiBold +/// What the Matching by Name tab says when no texture set of the latest bake matched by mesh name: the setting and its value in SemiBold fn matching_not_enabled(ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let mut text = egui::text::LayoutJob::default(); let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() }; - // One sentence to translate, its setting kept apart to set it in SemiBold - let sentence = tr("{setting} was off for this bake."); - let (before, after) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + // One sentence to translate, its setting and value kept apart to set them in SemiBold + let sentence = tr("Set {setting} to {value} to pair parts by name."); + let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence)); + let (between, after) = rest.split_once("{value}").unwrap_or((rest, "")); text.append(before, 0.0, format(FontId::proportional(NAME_SIZE))); - text.append(tr("Matching by name"), 0.0, format(semibold(NAME_SIZE))); + text.append(tr("Match"), 0.0, format(semibold(NAME_SIZE))); + text.append(between, 0.0, format(FontId::proportional(NAME_SIZE))); + text.append(tr("By Mesh Name"), 0.0, format(semibold(NAME_SIZE))); text.append(after, 0.0, format(FontId::proportional(NAME_SIZE))); let area = ui.available_rect_before_wrap(); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index af6062e2..027b3243 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -16,7 +16,10 @@ fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { execute(&mut session, "bake.run", &json!({ "resolution": resolution, "maps": ["position", "id"], "dilation": 0 })).unwrap(); execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1000.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); harness @@ -26,27 +29,14 @@ fn change_settings(harness: &mut Harness<'static, TextureCraftApp>, params: serd execute(&mut harness.state_mut().session, "bake.settings", ¶ms).unwrap(); } -/// Step frames until `done` holds, up to a generous limit -fn step_until(harness: &mut Harness<'static, TextureCraftApp>, what: &str, done: impl Fn(&TextureCraftApp) -> bool) { - for _ in 0..4000 { - harness.run_steps(1); - if done(harness.state()) { - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("{what} did not happen"); -} - #[test] fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { let mut harness = harness(64); let id_before = harness.state().session.baked(0).unwrap().maps[&BakedMap::Id].clone(); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.bake_changes(0, BakedMap::Position).is_empty(), "{:?}", app.session.bake_changes(0, BakedMap::Position)); @@ -76,14 +66,36 @@ fn a_change_while_the_rebake_runs_cancels_it_so_the_newest_settings_win() { // A slow rebake, so the next change lands while it runs change_settings(&mut harness, json!({ "resolution": 2048, "ao": { "rays": 256 } })); - step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); change_settings(&mut harness, json!({ "ao": { "rays": 128 } })); harness.run_steps(1); let app = harness.state(); assert!(app.bake.is_none(), "the outdated rebake stopped"); - assert_eq!(app.session.bake_log.maps[0].state, BakeMapState::Canceled); - execute(&mut harness.state_mut().session, "bake.autoRebake", &json!({ "map": null })).unwrap(); + let ambient_occlusion = app.session.bake_log.maps.iter().find(|row| row.map == BakedMap::AmbientOcclusion).map(|row| row.state.clone()); + assert_eq!(ambient_occlusion, Some(BakeMapState::Canceled)); +} + +#[test] +fn a_canceled_rebake_holds_back_only_its_own_texture_set() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "ts": "all", "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + for set in [0, 1] { + execute(&mut session, "bake.autoRebake", &json!({ "ts": set, "map": "position" })).unwrap(); + } + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let rebaking = |app: &TextureCraftApp, set: usize| app.bake.as_ref().and_then(|job| job.rebake.as_ref()).is_some_and(|rebake| rebake.0 == set); + + change_settings(&mut harness, json!({ "ts": "all", "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the first set's rebake", |app| rebaking(app, 0)); + harness.state_mut().cancel_bake(); + + super::step_until(&mut harness, "the second set's rebake", |app| rebaking(app, 1)); } #[test] @@ -104,8 +116,8 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert!(harness.state().bake.is_none(), "up to date after the bake"); execute(&mut harness.state_mut().session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); - step_until(&mut harness, "the rebake", |app| app.bake.is_some()); - step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + super::step_until(&mut harness, "the end of the rebake", |app| app.bake.is_none()); let app = harness.state(); assert!(app.session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); @@ -113,3 +125,26 @@ fn a_skew_stroke_rebakes_the_auto_rebake_map_inside_the_stroke() { assert_eq!(rows, [(BakedMap::Position, BakeMapState::Baked)]); assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } + +#[test] +fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { + use egui_kittest::kittest::Queryable; + + let mut harness = harness(64); + let auto_rebake = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].auto_rebake; + assert_eq!(auto_rebake(&harness), Some(BakedMap::Position)); + + assert!(harness.query_by_label("Auto-rebake Normal").is_none(), "off: shown only on a hovered, focused or selected row"); + harness.get_by_role_and_label(egui::Role::Button, "Normal").hover(); + harness.run_steps(2); + harness.get_by_label("Auto-rebake Normal"); + + // ID is the selected row (the first checked map), which shows its icons + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), Some(BakedMap::Id), "one map per set: ID replaces Position"); + + harness.get_by_label("Auto-rebake ID").click(); + harness.run_steps(2); + assert_eq!(auto_rebake(&harness), None); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index ca4cede4..43096b28 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -698,6 +698,24 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() { assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode still opens on the neutral material"); } +#[test] +fn a_click_on_the_middle_of_an_out_of_date_row_selects_its_map_and_bakes_nothing() { + use serde_json::json; + use texturecraft_engine::execute; + + // Two sets show every hover icon (sync, Auto-rebake, bolt, eye) and the changed settings add the out-of-date clock + let mut harness = harness(None); + execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_label("Out of date: Ambient Occlusion"); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().bake_progress().is_none(), "the click landed on the row, not its Bake Only icon"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); +} + #[test] fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { use serde_json::json; diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 11251da2..133ac592 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -25,17 +25,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } /// Bake sets 0 and 1, where set 1 has no tile left to bake, so its bake fails @@ -199,9 +192,9 @@ 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("Matching by name was off for this bake.").is_none(), "nothing baked yet: nothing to say"); + assert!(harness.query_by_label("Set Match to By Mesh Name to pair parts by name.").is_none(), "nothing baked yet: nothing to say"); log_a_bake(&mut harness, BakeMapState::Baked); - harness.get_by_label("Matching by name was off for this bake."); + harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index d26019c7..aa049fdc 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -31,17 +31,10 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } +/// Run frames until the bake ends, then a few more for its result to show fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { - for _ in 0..4000 { - harness.run_steps(1); - if harness.state().bake.is_none() { - harness.run_steps(2); - return; - } - - std::thread::sleep(std::time::Duration::from_millis(2)); - } - panic!("the bake did not finish"); + super::step_until(harness, "the end of the bake", |app| app.bake.is_none()); + harness.run_steps(super::SETTLE_FRAMES); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 0aa4441d..bdb3c483 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -196,6 +196,23 @@ 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 +const STEP_UNTIL_FRAMES: usize = 4000; +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) { + for _ in 0..STEP_UNTIL_FRAMES { + harness.run_steps(1); + if done(harness.state()) { + return; + } + + std::thread::sleep(STEP_UNTIL_PAUSE); + } + panic!("{what} did not happen"); +} + /// Presses and releases the primary button at `at` without moving, as a pointer click does fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.hover_at(at); From ff513841646f362aebbd9db41e8a90b9aa35e1d7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:18:22 +0000 Subject: [PATCH 16/26] Keep a canceled bake's finished maps and name the rebaked map in the footer Cancelling a bake threw away the maps the running texture set had already finished, so the Baking Log turned their ticks into warnings. The set now keeps them as one undo step, also when the preview closed because Bake mode was left; only maps that had not finished warn, and a map it did not finish keeps its out-of-date mark. A bake at a new output size keeps none, since storing them would drop the set's other maps. An auto-rebake started its preview with every checked map of the set, so the progress footer named the set's first map ("Baking Normal (1/7)") while it rebaked AO. The preview now lists only the maps the rebake makes. --- crates/engine/src/bake/bake_log.rs | 6 +-- crates/engine/src/bake/canceled_bake.rs | 37 +++++++++++++++++ crates/engine/src/bake/mesh_map_command.rs | 2 +- crates/engine/src/bake/mod.rs | 1 + crates/engine/src/bake_preview.rs | 4 +- crates/engine/tests/bake_preview.rs | 4 +- crates/engine/tests/it/bake_log.rs | 31 ++++++++++++++ crates/ui-egui/src/auto_rebake.rs | 13 ++---- crates/ui-egui/src/lib.rs | 48 +++++++++++++++++----- crates/ui-egui/src/running_bake.rs | 5 +++ crates/ui-egui/tests/bake_preview.rs | 8 +++- crates/ui-egui/tests/it/auto_rebake.rs | 11 +++++ crates/ui-egui/tests/it/bake_job_mesh.rs | 14 ++++++- crates/ui-egui/tests/it/baking_log.rs | 30 ++++++++++++++ docs/control-protocol.md | 7 ++-- 15 files changed, 186 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/bake/canceled_bake.rs diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 90e8feaf..2f7936c8 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -83,10 +83,10 @@ impl BakeLog { } } - /// The bake stopped: the maps of `current` (the set being baked, not kept) and every map still waiting are canceled - pub fn cancel(&mut self, current: Option) { + /// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept) + pub fn cancel(&mut self, discarded: Option) { for row in &mut self.maps { - if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) { + if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) { row.state = BakeMapState::Canceled; } } diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs new file mode 100644 index 00000000..ed9d8a98 --- /dev/null +++ b/crates/engine/src/bake/canceled_bake.rs @@ -0,0 +1,37 @@ +//! A canceled bake keeps the maps it finished: the Baking Log ticked them and the 3D view may have shown them + +use std::collections::BTreeMap; + +use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeSource, BakedMap}; + +use crate::{Result, Session}; + +impl Session { + /// Store the maps the canceled bake of `texture_set` `finished` as one undo step and return them; none at a new output size, which would drop the set's other maps + pub fn keep_canceled_bake( + &mut self, + texture_set: usize, + finished: BakedMaps, + sources: &BTreeMap, + painted_stroke: u64, + ) -> Result> { + let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) }; + let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| { + !stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height)) + }); + if resized { + return Ok(Vec::new()); + } + + // A map the bake did not finish keeps the record of what its stored pixels were baked from + let kept_sources: BTreeMap = + sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect(); + let kept: Vec = finished.maps.keys().copied().collect(); + self.edit("Bake mesh maps", |session| { + session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) + })?; + self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + Ok(kept) + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 70b9fe7d..c4361180 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -291,7 +291,7 @@ impl Session { self.store_bake_maps(texture_set, output.resolution, output.height, maps, recorded) } - fn store_bake_maps( + pub(super) fn store_bake_maps( &mut self, texture_set: usize, resolution: u32, diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 8ee7bc98..6065034f 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -13,6 +13,7 @@ mod bake_mesh; mod bake_meshes; mod bake_sources; mod bake_task; +mod canceled_bake; mod high_poly_load; mod high_poly_missed; mod layout; diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index d8a03d8b..6835d13b 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already -//! applied keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`Session::apply_streamed_bake`]). Cancellation keeps the maps the current set finished +//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets 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. mod preview_set; diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index d416e183..e4c6a031 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -1,5 +1,5 @@ //! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, -//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it +//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it //! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the //! document share each map's buffer instead of holding two copies. @@ -215,7 +215,7 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { assert!(**data == full.maps[map], "{map:?}"); } - // What the app does on cancel: end the preview; the document keeps what it had + // Ending the preview alone leaves the document as it was; the app keeps finished maps through keep_canceled_bake session.bake_preview_end(); assert_eq!(session.doc.baked.get(&0).cloned(), before); diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index 419ce6b4..d79d0430 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -4,6 +4,7 @@ use std::collections::BTreeSet; use serde_json::json; use texturecraft_engine::bake::{BakeHighState, BakeLog, BakeMapState, NamePair}; +use texturecraft_engine::compose::BakedMaps; use texturecraft_engine::core::{BakedMap, MeshMatchMode}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute, sample_session}; @@ -127,3 +128,33 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ let log = execute(&mut session, "bake.log", &json!({})).unwrap(); assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } + +#[test] +fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { + let mut session = sample_session(256, 64).unwrap(); + let before = session.baked(0).cloned().unwrap(); + let resolution = before.resolution * 2; + let data = std::sync::Arc::new(vec![0.5; (resolution * resolution) as usize * BakedMap::Normal.components()]); + let finished = BakedMaps { resolution, maps: [(BakedMap::Normal, data)].into() }; + + let kept = session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + assert!(kept.is_empty(), "{kept:?}"); + assert_eq!(session.baked(0).map(|baked| baked.maps.keys().copied().collect::>()), Some(before.maps.keys().copied().collect())); + assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution)); +} + +#[test] +fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { + let mut session = sample_session(256, 64).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() }; + + let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap(); + + assert_eq!(kept, [BakedMap::Id]); + assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 49221003..8d16ca41 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -65,20 +65,15 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map) = (rebake.0, rebake.1); - let orders = match app.session.bake_preview_orders(&[set], Some(map)) { - Ok(orders) => orders, - Err(error) => { - app.toast(error.to_string(), true); - return; - } - }; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); crate::id_color_pick::IdColorPick::end(app); - app.session.bake_preview_begin(orders); + + // The progress footer names the maps this rebake makes, not every checked map of the set let maps = app.session.auto_rebake_maps(set, map); + app.session.bake_preview_begin(vec![(set, maps.clone())]); app.session.begin_map_bake_log(&[set], &maps); app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; - app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: Some(map), rebake: Some(rebake) }); + app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 24373d2e..cb772815 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -839,12 +839,14 @@ impl TextureCraftApp { } ctx.request_repaint_after(BAKE_POLL_INTERVAL); - if let Some(running) = &job.current { + if let Some(running) = &mut job.current { let set_index = running.set_index; // Wait for the sender to close so the last map also gets a preview frame match running.maps.try_recv() { Ok(map) => { + running.finished.resolution = map.resolution; + running.finished.maps.insert(map.map, map.data.clone()); self.session.bake_log.map_baked(set_index, map.map); self.session.bake_preview_map(set_index, map); return; @@ -868,16 +870,12 @@ impl TextureCraftApp { } Ok(Err(error)) => { // The worker's error ends the whole bake; the maps of the sets before it stay - self.bake_failed(set_index, &error.to_string()); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, &error.to_string()); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.bake_failed(set_index, i18n::tr("The bake worker stopped")); - self.cancel_bake(); - self.finish_bake_report(); + self.end_failed_bake(set_index, i18n::tr("The bake worker stopped")); return; } } @@ -910,6 +908,7 @@ impl TextureCraftApp { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); + let (sources, painted_stroke) = (task.sources.clone(), task.painted_stroke); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let worker_done = maps_done.clone(); let (sender, maps) = std::sync::mpsc::channel(); @@ -923,13 +922,25 @@ impl TextureCraftApp { }); if let Some(job) = self.bake.as_mut() { - job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); + job.current = + Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total, finished: Default::default(), sources, painted_stroke }); } } Err(error) => self.bake_failed(set_index, &error.to_string()), } } + /// End the bake at texture set `set_index`, whose worker failed: none of its maps are kept, the queued sets are canceled + fn end_failed_bake(&mut self, set_index: usize, error: &str) { + if let Some(job) = &mut self.bake { + job.current = None; + } + + self.bake_failed(set_index, error); + self.cancel_bake(); + self.finish_bake_report(); + } + /// Note a texture set whose bake failed: one Log line, counted in the summary fn bake_failed(&mut self, set_index: usize, error: &str) { self.session.log.error("Baker", format!("Bake of texture set {set_index} failed: {error}")); @@ -956,16 +967,31 @@ 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 + /// 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 pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - self.session.bake_log.cancel(job.current.as_ref().map(|running| running.set_index)); + let mut discarded = None; if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + + // 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() + }) + } + false => Vec::new(), + }; + if kept.is_empty() { + discarded = Some(running.set_index); + } } - // Only the current set is uncommitted; completed sets remain applied + self.session.bake_log.cancel(discarded); self.session.bake_preview_end(); } diff --git a/crates/ui-egui/src/running_bake.rs b/crates/ui-egui/src/running_bake.rs index 512af28a..76427ad4 100644 --- a/crates/ui-egui/src/running_bake.rs +++ b/crates/ui-egui/src/running_bake.rs @@ -12,4 +12,9 @@ pub struct RunningBake { /// Maps finished so far, and how many the set makes. pub maps_done: Arc, pub maps_total: usize, + /// The maps received so far, kept when the bake is canceled even if the preview has closed + pub finished: texturecraft_engine::compose::BakedMaps, + /// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps + pub sources: std::collections::BTreeMap, + pub painted_stroke: u64, } diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 9bb1eae2..ce7be5e7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -71,12 +71,13 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { } #[test] -fn cancelling_restores_the_view_and_leaves_the_document_alone() { +fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + // One frame starts the worker; a finished map shows only from the next one harness.state_mut().start_bake(vec![0]); - harness.run_steps(2); + harness.run_steps(1); assert!(harness.state().session.bake_preview_active()); let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); @@ -142,6 +143,9 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { maps, maps_done: Arc::new(AtomicUsize::new(MAPS.len())), maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, }), }); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 027b3243..4e74f0be 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -46,6 +46,17 @@ fn a_settings_change_rebakes_only_the_auto_rebake_map_without_a_toast() { assert!(app.toasts.is_empty(), "a rebake that went well is quiet"); } +#[test] +fn the_progress_footer_names_the_map_the_rebake_makes() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + super::step_until(&mut harness, "the rebake", |app| app.bake.as_ref().is_some_and(|job| job.current.is_some())); + + let stage = harness.state().session.bake_preview.as_ref().and_then(|preview| preview.stage()); + assert_eq!(stage.map(|stage| (stage.map, stage.total)), Some((BakedMap::Position, 1)), "not the set's first checked map, not all its maps"); +} + #[test] fn nothing_is_rebaked_outside_bake_mode() { let mut harness = harness(64); diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index f805bfc9..c3292beb 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -20,8 +20,18 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes let (_result_sender, receiver) = std::sync::mpsc::channel(); let (_map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); - let running = - RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let running = RunningBake { + set_index: 0, + progress: progress.clone(), + receiver, + maps, + maps_done, + maps_total: 1, + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); harness.step(); diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 133ac592..29099a64 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -68,6 +68,36 @@ fn a_one_map_bake_lists_only_that_map() { assert!(harness.query_by_label_contains(&format!("{name} ID")).is_none(), "a checked map the bake left alone has no row"); } +#[test] +fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { + let mut harness = harness(); + let before = harness.state().session.baked(0).cloned().unwrap_or_default(); + harness.state_mut().start_bake(vec![0, 1]); + + // Leaving Bake mode closes the preview; the bake and the maps it finishes go on + harness.state_mut().ui.mode = Mode::Painting; + let state = |app: &TextureCraftApp, set: usize, map: BakedMap| { + app.session.bake_log.maps.iter().find(|row| row.texture_set == set && row.map == map).map(|row| row.state.clone()) + }; + super::step_until(&mut harness, "set 0's first map", |app| state(app, 0, BakedMap::Id) == Some(BakeMapState::Baked)); + assert!(!harness.state().session.bake_preview_active()); + + harness.state_mut().cancel_bake(); + + let app = harness.state(); + assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); + for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { + assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + } + let after = app.session.baked(0).cloned().unwrap_or_default(); + let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { + (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), + (old, new) => old.is_some() != new.is_some(), + }; + assert!(changed(BakedMap::Id), "the ticked map is in the document"); + assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); +} + #[test] fn a_failed_maps_arrow_opens_its_settings() { let mut harness = harness(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 8c74d39a..b68a5c77 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -242,7 +242,7 @@ keeps its state in a throwaway file. | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | | `ui.reset` | | resets the panels, view settings and interface language without asking for confirmation. Other preferences and shortcuts stay | | `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | -| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back | +| `ui.bake.cancel` | | Stops the running bake; 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.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History`, `Log`, `BakingLog`, `MeshMapBakers`, `BakeMaps`, `BakeSettings`, `Export` and `Renderer` (a floating window holding one right-bar panel is that panel undocked); `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds), `log_channel` the Log panel's tab (`General` or `Assets`) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -285,8 +285,9 @@ bake of its own, so with a high poly the transfer rays are cast once per map; th same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. The streamed maps are held by the session, not the document: nothing enters the undo history -until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking -as it was, while sets that finished before the cancel stay applied. When +until a texture set's bake is applied (one undo step); a cancelled bake applies the maps the set it was +baking had finished (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 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. From cb8a46deb7037525de9340c81d5ca1b9f313ce54 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:40:27 +0000 Subject: [PATCH 17/26] Name the set in a canceled bake's log line, make a bake setting drag one undo step and hold Auto-rebake while it is held A drag stays one undo step while a panel is open in its own floating window: the press is kept in egui memory, not in a frame cache that the floating window's own pass clears every frame. --- crates/engine/src/bake/canceled_bake.rs | 4 +++- crates/engine/tests/it/bake_log.rs | 14 ++++++++++++ crates/ui-egui/src/auto_rebake.rs | 6 ++++++ crates/ui-egui/src/bake_mode/mod.rs | 8 +++---- crates/ui-egui/src/property_sheet/tests.rs | 22 +++++++++++++++++++ crates/ui-egui/src/widgets.rs | 20 +++++++++++------ crates/ui-egui/tests/it/auto_rebake.rs | 15 +++++++++++++ crates/ui-egui/tests/it/bake_mode.rs | 25 ++++++++++++++++++++++ 8 files changed, 103 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/bake/canceled_bake.rs b/crates/engine/src/bake/canceled_bake.rs index ed9d8a98..08cc2bf9 100644 --- a/crates/engine/src/bake/canceled_bake.rs +++ b/crates/engine/src/bake/canceled_bake.rs @@ -31,7 +31,9 @@ impl Session { self.edit("Bake mesh maps", |session| { session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke))) })?; - self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len())); + // Named like the Texture Set List and the progress footer, which count sets from 1 + let name = self.doc.project.texture_sets.get(texture_set).map_or_else(|| format!("{}", texture_set + 1), |set| set.name.clone()); + self.log.info("Baker", format!("Kept {} baked maps of texture set {name} from the canceled bake", kept.len())); Ok(kept) } } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index d79d0430..ee26594a 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -158,3 +158,17 @@ fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() { assert_eq!(kept, [BakedMap::Id]); assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date"); } + +#[test] +fn a_canceled_bakes_log_line_names_the_set_as_the_texture_set_list_does() { + let mut session = sample_session(256, 64).unwrap(); + let stored = session.baked(0).cloned().unwrap(); + let (map, data) = stored.maps.iter().next().map(|(map, data)| (*map, data.clone())).unwrap(); + let finished = BakedMaps { resolution: stored.resolution, maps: [(map, data)].into() }; + + session.keep_canceled_bake(0, finished, &Default::default(), 0).unwrap(); + + let name = session.doc.project.texture_sets[0].name.clone(); + let line = session.log.iter().find(|line| line.contains("canceled bake")).map(|line| line.message.clone()).unwrap(); + assert!(line.contains(&format!("texture set {name} ")), "the first set is not numbered 0: {line}"); +} diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 8d16ca41..a18ffae0 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -46,6 +46,12 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { let now = app.last_time; ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); + + // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go + if ctx.input(|input| input.pointer.any_down()) { + app.auto_rebake.pending = Some((waiting, now)); + return; + } match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index cf81d8d1..07a5c544 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -231,15 +231,15 @@ fn edit_settings( let mut settings = before.clone(); let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; - if settings == before && reset.is_none() { - return false; - } + + // One drag is one undo step: a press's later changes continue its first one + let Some(merge) = crate::widgets::press_edit(ui, ui.make_persistent_id((scroll_id, "press")), settings != before || reset.is_some()) else { return false }; let mut patch = settings_patch(&before, &settings); if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { fields.extend(reset); } - app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch, "merge": merge })); true } diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 10c7ecfd..d7d45b32 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,28 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step +#[test] +fn a_drag_stays_one_undo_step_while_another_window_draws() { + let context = egui::Context::default(); + let owner = egui::Id::unique("held editor"); + let edit = |events| { + let mut result = None; + let mut output = context.run_ui(egui::RawInput { events, ..Default::default() }, |ui| result = crate::widgets::press_edit(ui, owner, true)); + output.textures_delta.clear(); + result + }; + let press = egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + + assert_eq!(edit(vec![press]), Some(false), "the press starts an undo step"); + let viewport = egui::ViewportId::from_hash_of("floating History"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + context.run_ui(floating, |_| {}).textures_delta.clear(); + + assert_eq!(edit(Vec::new()), Some(true), "the held press continues its undo step"); +} + #[test] fn section_tabs_show_focus_before_a_keyboard_jump() { let mut harness = builder(Brightness::MediumDark).build_ui(|ui| { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 991585dc..b09f71d2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -31,26 +31,34 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { return None; } - ui.memory_mut(|memory| { - let edits = memory.caches.cache::>(); + // Kept in memory, not a frame cache: a floating panel in its own OS window ends a pass of its own inside ours, which would clear it every frame + let frame = ui.ctx().cumulative_frame_nr(); + ui.data_mut(|data| { let id = id.with("pointer edit"); - let previous = edits.get(&id).copied(); + let previous = data.get_temp::(id); let merge = match press { Some(start) => { - let continuing = previous == Some(start); + let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { - edits.set(id, start); + data.insert_temp(id, PressEdit { press: start, frame }); } continuing } // A final movement still belongs to the press that ended - None => release_only && previous.is_some(), + None => release_only && previous.is_some_and(|previous| previous.frame + 1 >= frame), }; changed.then_some(merge) }) } +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +struct PressEdit { + press: u64, + frame: u64, +} + /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 4e74f0be..faf87c78 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -159,3 +159,18 @@ fn the_rows_icon_turns_auto_rebake_on_for_its_map_and_off_again() { harness.run_steps(2); assert_eq!(auto_rebake(&harness), None); } + +#[test] +fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_step() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + + // Held still well past the settle time, as a hand pausing mid-drag + let corner = egui::pos2(1590.0, 990.0); + harness.drag_at(corner); + harness.run_steps(120); + assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); + + harness.drop_at(corner); + super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 43096b28..972dc919 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -737,3 +737,28 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { harness.get_by_label("Out of date: Position"); assert!(harness.query_by_label("Out of date: Normal").is_none(), "never baked: not out of date"); } + +#[test] +fn dragging_secondary_rays_is_one_undo_step() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + select_map(&mut harness, "Ambient Occlusion"); + let rays_before = harness.state().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays; + let history_steps = harness.state().session.history_labels().len(); + + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let at = |share: f32| egui::pos2(track.left() + track.width() * share, track.center().y); + harness.drag_at(at(0.2)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + for step in 1..=3 { + harness.hover_at(at(0.2 + 0.15 * step as f32)); + harness.run_steps(crate::DRAG_STEP_FRAMES); + } + + // The release moves too, and that last change still belongs to the drag + harness.drop_at(at(0.8)); + harness.run_steps(crate::SETTLE_FRAMES); + + let session = &harness.state().session; + assert_ne!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays, rays_before, "the drag changed the rays"); + assert_eq!(session.history_labels().len(), history_steps + 1, "{:?}", session.history_labels()); +} From de7515bf1a2b1b199e9432c919330cc1f8336bcd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:54:13 +0000 Subject: [PATCH 18/26] Keep a stroke's box and the stroke count through undo and reimport, and give the bake rows' reasons to screen readers The painted box of an auto-rebake map now lives in the document, so undoing the rebake of a stroke makes the map due again (the stroke stays painted while the map goes back to its pixels from before it), and a rolled-back bake.run needs no hand-kept copy. A mesh reimport carries the stroke count on; before, a bake after a reimport saw every earlier stroke as newer and kept its box. The Baking Log rows, the out-of-date clock and the generator's bake note put their reasons in the accessibility tree, not only in a tooltip, and a folding high poly row exposes whether it is expanded. bake.log is kept off the shortcut list. PressEdit gets its own file, region_keeps_pixels moves beside RegionBake, and auto_rebake_due computes each map's source once. --- crates/bake/src/lib.rs | 4 +- crates/bake/src/region_bake.rs | 5 +++ crates/bake/src/texel_box.rs | 6 --- crates/engine/src/bake/auto_rebake.rs | 11 ++++-- crates/engine/src/bake/mesh_map_command.rs | 17 ++++----- crates/engine/src/bake/mod.rs | 1 - crates/engine/src/bake/paint_command.rs | 4 +- crates/engine/src/bake/painted_region.rs | 12 +++--- crates/engine/src/bake_preview.rs | 4 +- crates/engine/src/commands.rs | 16 +++++++- crates/engine/src/file_cmds.rs | 3 ++ crates/engine/src/inspect.rs | 4 +- crates/engine/src/material_lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 24 ++++++------ crates/engine/src/session.rs | 6 +-- crates/engine/src/smart_masks.rs | 1 + crates/engine/tests/it/auto_rebake.rs | 38 ++++++++++++++++++- crates/ui-egui/src/auto_rebake.rs | 2 +- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 8 ++-- crates/ui-egui/src/baking_log.rs | 18 ++++++--- .../ui-egui/src/baking_log/high_poly_list.rs | 12 +++--- .../ui-egui/src/baking_log/matching_list.rs | 11 +++--- .../ui-egui/src/generator_panel/bake_note.rs | 7 +++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/press_edit.rs | 8 ++++ crates/ui-egui/src/widgets.rs | 8 +--- crates/ui-egui/tests/it/auto_rebake.rs | 4 +- crates/ui-egui/tests/it/bake_mode.rs | 3 +- crates/ui-egui/tests/it/baking_log.rs | 21 +++++++++- .../ui-egui/tests/it/generator_bake_note.rs | 5 ++- docs/control-protocol.md | 4 +- 31 files changed, 182 insertions(+), 88 deletions(-) create mode 100644 crates/ui-egui/src/press_edit.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 50f2f54c..73847b5b 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -24,8 +24,8 @@ pub use high_poly::HighPoly; pub(crate) use mesh_extent::MeshExtent; pub use name_pair::NamePair; pub use progress::Progress; -pub use region_bake::RegionBake; -pub use texel_box::{TexelBox, region_keeps_pixels}; +pub use region_bake::{RegionBake, region_keeps_pixels}; +pub use texel_box::TexelBox; mod map; mod skew; diff --git a/crates/bake/src/region_bake.rs b/crates/bake/src/region_bake.rs index 20a14849..224202f3 100644 --- a/crates/bake/src/region_bake.rs +++ b/crates/bake/src/region_bake.rs @@ -10,3 +10,8 @@ pub struct RegionBake<'a> { pub texels: TexelBox, pub previous: &'a BTreeMap>>, } + +/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours +pub fn region_keeps_pixels(map: BakedMap) -> bool { + !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) +} diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 85be4fc0..3dc062cf 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -19,9 +19,3 @@ impl TexelBox { } } } - -/// Whether a region bake gives `map` a whole bake's pixels: not for maps scaled by their whole range or read from neighbours -pub fn region_keeps_pixels(map: texturecraft_core::BakedMap) -> bool { - use texturecraft_core::BakedMap; - !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) -} diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index e1e3cb1f..3f50f672 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -43,10 +43,13 @@ impl Session { /// The auto-rebake maps that are out of date now, as (texture set, map, what a bake would read now) pub fn auto_rebake_due(&self) -> Vec<(usize, BakedMap, BakeSource)> { let sets = self.doc.project.texture_sets.iter().enumerate(); - sets.filter_map(|(index, set)| Some((index, set.auto_rebake?))) - .filter(|(index, map)| !self.bake_changes(*index, *map).is_empty()) - .filter_map(|(index, map)| Some((index, map, self.bake_source(index, map).ok()?))) - .collect() + sets.filter_map(|(index, set)| { + let map = set.auto_rebake?; + let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; + let current = self.bake_source(index, map).ok()?; + (!record.changes(¤t).is_empty()).then_some((index, map, current)) + }) + .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) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index c4361180..da66bdc2 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -311,17 +311,17 @@ impl Session { self.record_bake_sources(texture_set, recorded, &stored) } - /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran - pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { - let mut task = self.bake_task(ts)?; + /// Bake texture set `texture_set` now (blocking), on the CPU when `cpu`; returns where the rays ran + pub fn bake_now(&mut self, texture_set: usize, cpu: bool) -> Result { + let mut task = self.bake_task(texture_set)?; if cpu { task.tracer = None; } let output = task.run(&Progress::new())?; let tracer = output.tracer.clone(); - self.edit("Bake mesh maps", |session| session.store_bake(ts, output, Some((&task.sources, task.painted_stroke))))?; - self.log.info("Baker", format!("Baked texture set {ts} ({tracer})")); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output, Some((&task.sources, task.painted_stroke))))?; + self.log.info("Baker", format!("Baked texture set {texture_set} ({tracer})")); Ok(tracer) } @@ -861,9 +861,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { let next = with_sync_partners(&session.doc.project, next, "bake.run")?; let cpu = boolp(params, "cpu") == Some(true); - // The painted boxes are not in the document, so a rolled-back bake puts them back by hand - let painted_regions = session.painted_regions.clone(); - let baked = session.edit("Bake mesh maps", |session| { + let tracers = session.edit("Bake mesh maps", |session| { for (index, settings) in next { session.doc.project.texture_set_mut(index)?.bake = settings; } @@ -884,8 +882,7 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { } } Ok(tracers) - }); - let tracers = baked.inspect_err(|_| session.painted_regions = painted_regions)?; + })?; for (index, tracer) in sets.iter().zip(&tracers) { session.log.info("Baker", format!("Baked texture set {index} ({tracer})")); } diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 6065034f..54fa0faf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -46,7 +46,6 @@ pub use model_patch::settings_patch; pub use painted_region::PaintedRegion; pub use streamed_bake::StreamedBake; pub use streamed_map::StreamedMap; -pub use texturecraft_bake::NamePair; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake/paint_command.rs b/crates/engine/src/bake/paint_command.rs index 840b097e..f8edd524 100644 --- a/crates/engine/src/bake/paint_command.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -86,6 +86,8 @@ const MAX_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 = 16..=4096; @@ -110,7 +112,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> let value = number(parameters, "value", 1.0, 0.0, 1.0)?; let radius = number(parameters, "radius", DEFAULT_RADIUS, MIN_RADIUS, 1.0)?; - let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; + let hardness = number(parameters, "hardness", DEFAULT_HARDNESS, 0.0, 1.0)?; let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; let size = match parameters.get("size") { None => DEFAULT_PAINT_SIZE, diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index 4c31b533..c19db7a3 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -22,26 +22,26 @@ impl Session { /// Note that the bake paint of `texture_set` changed inside `uv_min`..`uv_max` (the whole map when `None`) pub(super) fn note_bake_paint(&mut self, texture_set: usize, uv_box: Option<(Vec2, Vec2)>) { let (uv_min, uv_max) = uv_box.unwrap_or((Vec2::ZERO, Vec2::ONE)); - let (uv_min, uv_max) = match self.painted_regions.get(&texture_set) { + let (uv_min, uv_max) = match self.doc.painted_regions.get(&texture_set) { Some(region) => (region.uv_min.min(uv_min), region.uv_max.max(uv_max)), None => (uv_min, uv_max), }; self.painted_strokes += 1; - self.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); + self.doc.painted_regions.insert(texture_set, PaintedRegion { uv_min, uv_max, stroke: self.painted_strokes }); } /// Forget the painted box of `texture_set` once its auto-rebake map is baked again, unless a stroke came after `painted_stroke` pub(super) fn forget_painted_region(&mut self, texture_set: usize, stored: &[BakedMap], painted_stroke: u64) { let auto = self.doc.project.texture_sets.get(texture_set).and_then(|set| set.auto_rebake); - let painted_since = self.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); + let painted_since = self.doc.painted_regions.get(&texture_set).is_some_and(|region| region.stroke > painted_stroke); if !painted_since && auto.is_none_or(|map| stored.contains(&map)) { - self.painted_regions.remove(&texture_set); + self.doc.painted_regions.remove(&texture_set); } } /// Baked auto-rebake maps changed only by painting since, as (set, map, what a bake reads now, newest stroke) pub fn auto_rebake_painted(&self) -> Vec<(usize, BakedMap, BakeSource, u64)> { - let regions = self.painted_regions.iter(); + let regions = self.doc.painted_regions.iter(); regions .filter_map(|(index, region)| { let set = self.doc.project.texture_sets.get(*index)?; @@ -56,7 +56,7 @@ impl Session { /// A task that bakes `map` again only where painting changed it, keeping the rest; else the whole map pub fn bake_painted_task(&self, texture_set: usize, map: BakedMap) -> Result { let mut task = self.bake_task_for(texture_set, &self.auto_rebake_maps(texture_set, map))?; - let Some(region) = self.painted_regions.get(&texture_set) else { return Ok(task) }; + 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)); diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 6835d13b..b0a3eac8 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,8 +1,8 @@ //! 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 -//! ([`Session::keep_canceled_bake`], even when the preview closed); applied sets keep their results and undo steps. The preview shows one map at a time, raw on the +//! ([`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. mod preview_set; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 41e7d619..0fb3959d 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -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; 13] = [ + const NOT_FROM_A_KEY: [&str; 14] = [ "project.inspect", "project.templates", "project.new", @@ -43,6 +43,7 @@ impl CommandSpec { "textureSet.parts", "bake.settings", "bake.preview", + "bake.log", "camera.set", "textureSet.settings", ]; @@ -372,7 +373,18 @@ mod tests { ] { assert!(!bindable(id), "{id} needs a parameter"); } - for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] { + for id in [ + "layer.move", + "layer.list", + "project.inspect", + "edit.history", + "export.presets", + "tool.state", + "project.new", + "camera.set", + "layer.blend", + "bake.log", + ] { assert!(!bindable(id), "{id} is a query or has several forms"); } } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 5cfc235b..e5f0df92 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -289,6 +289,7 @@ impl Session { pixels: project_file.pixels, baked: project_file.baked, resources, + painted_regions: Default::default(), }, mesh, project_file.mesh, @@ -740,6 +741,8 @@ 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 + 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 diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 04af908b..b914b4e7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -264,6 +264,8 @@ pub fn texture_set(session: &Session, index: usize) -> Value { }) }) .collect(); + let out_of_date: std::collections::BTreeMap<_, Vec<_>> = + session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect())).collect(); json!({ "index": index, "name": texture_set.name, @@ -276,7 +278,7 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), - "outOfDate": session.out_of_date_maps(index).into_iter().map(|(map, changes)| (map.id(), changes.iter().map(|change| change.id()).collect::>())).collect::>(), + "outOfDate": out_of_date, "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, "active": index == session.ts(), diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 758ee3b6..da5b3ea6 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -77,6 +77,7 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), } } @@ -145,6 +146,7 @@ impl Session { project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), + painted_regions: Default::default(), resources, }; diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 5736c5ca..55b110e0 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -53,14 +53,14 @@ fn set(s: &mut Session, p: &Value) -> Result { pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); /// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width -pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { - let texture_set = session.doc.project.texture_set(ts)?; - let grid = texture_set.tile_grid(); - if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { +pub(crate) fn use_images(session: &mut Session, command: &str, texture_set: usize, map: BakedMap, images: &BTreeMap>) -> Result { + 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, ts)?; + 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; @@ -74,11 +74,11 @@ pub(crate) fn use_images(session: &mut Session, command: &str, ts: usize, map: B }), }; - let entry = session.doc.baked.entry(ts).or_default(); + let entry = session.doc.baked.entry(texture_set).or_default(); entry.resolution = width; entry.maps.insert(map, Arc::new(data)); // An imported map is never out of date: nothing records what it was made from - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.insert(map); set.bake_sources.remove(&map); Ok(width) @@ -158,16 +158,16 @@ fn resample(comps: usize, (w, h): (u32, u32), flip_green: bool, sample: impl Fn( fn clear(session: &mut Session, params: &Value) -> Result { const COMMAND: &str = "textureSet.meshMap.clear"; - let ts = ts_param(session, params, COMMAND)?; + let texture_set = ts_param(session, params, COMMAND)?; let map = map_param(params, COMMAND)?; - if !session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) { - return Err(bad(COMMAND, format!("texture set {ts} has no {} map", map.id()))); + 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(&ts) { + if let Some(baked) = session.doc.baked.get_mut(&texture_set) { baked.maps.remove(&map); } - let set = session.doc.project.texture_set_mut(ts)?; + let set = session.doc.project.texture_set_mut(texture_set)?; set.baked.remove(&map); set.bake_sources.remove(&map); Ok(()) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 35922e64..670b0cfb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -33,6 +33,8 @@ pub struct Document { pub resources: BTreeMap>>, /// 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 + pub(crate) painted_regions: BTreeMap, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -427,8 +429,6 @@ pub struct Session { pub(crate) source: Arc, /// Fingerprint of `source`'s geometry, once a bake or an out-of-date check needs it pub(crate) low_poly_fingerprint: std::sync::OnceLock, - /// Where skew or cage painting changed each texture set since its auto-rebake map was baked - pub(crate) painted_regions: std::collections::BTreeMap, /// Skew and cage strokes so far pub(crate) painted_strokes: u64, pub bvh: Arc, @@ -534,7 +534,6 @@ impl Session { project_id: next_mesh_id(), source, low_poly_fingerprint: Default::default(), - painted_regions: Default::default(), painted_strokes: 0, mesh, bvh: Arc::new(bvh), @@ -656,6 +655,7 @@ impl Session { pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }, mesh, mesh_source, diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index bbe0e243..f50026a8 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -243,6 +243,7 @@ impl Session { pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), + painted_regions: Default::default(), }; let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/engine/tests/it/auto_rebake.rs b/crates/engine/tests/it/auto_rebake.rs index 8dd1d80a..9164a5ad 100644 --- a/crates/engine/tests/it/auto_rebake.rs +++ b/crates/engine/tests/it/auto_rebake.rs @@ -109,8 +109,8 @@ fn a_skew_stroke_rebakes_only_its_box_and_the_box_matches_a_whole_bake() { let pixels = output.maps[&BakedMap::Position].chunks(components).zip(before.chunks(components)).zip(whole.chunks(components)); let mut changed = 0; for (index, ((rebaked, kept), baked_whole)) in pixels.enumerate() { + assert_eq!(rebaked, baked_whole, "texel {index} matches a whole bake"); if region.contains(index % width, index / width) { - assert_eq!(rebaked, baked_whole, "texel {index} inside the box"); changed += usize::from(rebaked != kept); } else { assert_eq!(rebaked, kept, "texel {index} outside the box"); @@ -140,6 +140,42 @@ fn a_stroke_painted_while_the_rebake_runs_waits_for_the_next_one() { assert_eq!(painted, [(0, BakedMap::Position)], "the second stroke is not in the stored map yet"); } +#[test] +fn undoing_the_rebake_of_a_stroke_makes_its_box_due_again() { + let mut session = super::bake::leaning_session(true); + execute(&mut session, "bake.run", &json!({ "maps": ["position"], "dilation": 2 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.3, 0.3]], "radius": 0.05, "size": 64 })).unwrap(); + let mut task = session.bake_painted_task(0, BakedMap::Position).unwrap(); + task.tracer = None; + let output = task.run_streaming(&Progress::new(), &mut |_| {}).unwrap(); + session.apply_streamed_bake(0, output).unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "the rebake took the stroke"); + + session.undo().unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert_eq!(painted, [(0, BakedMap::Position)], "the map is back to its pixels from before the stroke, which is still painted"); + session.redo().unwrap(); + assert!(session.auto_rebake_painted().is_empty(), "redo brings the rebake back"); +} + +#[test] +fn a_bake_after_a_mesh_reimport_takes_the_strokes_painted_before_it() { + let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3\nf 1/1 3/3 4/4\n"; + let mut session = Session::from_mesh_bytes_with_uvs("quad.obj", quad.as_bytes(), 128, "quad", None, false).unwrap(); + session.add_high_poly_bytes("quad_high.obj", quad.replace("v 1 1 0", "v 1 1 0.1").into_bytes()).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 32, "maps": ["position"], "dilation": 0 })).unwrap(); + execute(&mut session, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.05, "size": 64 })).unwrap(); + + session.reimport_mesh(None, false).unwrap(); + execute(&mut session, "bake.run", &json!({})).unwrap(); + + let painted: Vec<_> = session.auto_rebake_painted().into_iter().map(|(set, map, _, _)| (set, map)).collect(); + assert!(painted.is_empty(), "the bake after the reimport took the stroke: {painted:?}"); +} + #[test] fn a_failed_bake_keeps_the_painted_box_of_the_sets_it_rolled_back() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index a18ffae0..07bbcaab 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -70,7 +70,7 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { - let (set, map) = (rebake.0, rebake.1); + let (set, map, ..) = rebake; // Restore the previous view before the rebake takes it over app.live_preview.release(&mut app.session); diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index afea363c..fd58b9a4 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -487,21 +487,23 @@ fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { response } -/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail tells what changed +/// The yellow clock on the corner of `thumbnail`, of a map that `changes` made out of date since its bake; hovering the thumbnail, or its node's description, tells what changed fn out_of_date_mark(ui: &mut Ui, thumbnail: Rect, name: &str, changes: &[BakeChange]) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(thumbnail, ui.scope_id().with("out_of_date"), Sense::hover()); let title = tr("Out of date"); let label = trf("Out of date: {map}", &[("map", &name)]); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &label)); + let reasons: Vec<&str> = changes.iter().map(|change| tr(bake_change_reason(*change))).collect(); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reasons.join(" "))); let badge = thumbnail.right_bottom() - vec2(CLOCK_BADGE_RADIUS, CLOCK_BADGE_RADIUS) * 0.5; ui.painter().circle_filled(badge, CLOCK_BADGE_RADIUS, tokens.panel); ui.painter().text(badge, Align2::CENTER_CENTER, icon::CLOCK, FontId::proportional(CLOCK_BADGE_RADIUS * 2.0), tokens.warning); response.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for change in changes { - ui.label(RichText::new(tr(bake_change_reason(*change))).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); + for reason in reasons { + ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); } diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index e490ff85..db0db2a7 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -281,7 +281,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { BakeMapState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not baked")), BakeMapState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeMapState::Failed(reason) => Some(reason.as_str()), + BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{name}, {state}"))); + describe(ui, &response, reason); let open = row.state.is_issue().then(|| open_settings_button(ui, rect, (row.texture_set, row.map), &name)); let row_hovered = response.hovered() || open.as_ref().is_some_and(|open| open.hovered()); @@ -307,11 +313,6 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { } } - let reason = match &row.state { - BakeMapState::Failed(reason) => Some(reason.as_str()), - BakeMapState::Canceled => Some(tr("The bake was canceled before this map was kept.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); @@ -322,6 +323,13 @@ fn map_row(ui: &mut Ui, row: &BakeLogMap) -> (Rect, bool) { (rect, open_clicked) } +/// Give a row's node the `reason` its tooltip shows, so a screen reader reads it without hovering +pub(super) fn describe(ui: &Ui, response: &egui::Response, reason: Option<&str>) { + if let Some(reason) = reason { + ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(reason)); + } +} + /// The open-settings arrow's square at the right end of `row`; it shows only while the row is hovered or it has focus fn open_settings_button(ui: &mut Ui, row: Rect, set_map: (usize, BakedMap), name: &str) -> egui::Response { let center = pos2(row.right() - SIDE_PADDING_POINTS - OPEN_BUTTON_SIZE / 2.0, row.center().y); diff --git a/crates/ui-egui/src/baking_log/high_poly_list.rs b/crates/ui-egui/src/baking_log/high_poly_list.rs index 5f4f5977..ab6307ad 100644 --- a/crates/ui-egui/src/baking_log/high_poly_list.rs +++ b/crates/ui-egui/src/baking_log/high_poly_list.rs @@ -43,6 +43,7 @@ fn set_row(ui: &mut Ui, set: usize, name: &str) -> bool { 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() { @@ -69,7 +70,13 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { BakeHighState::Failed(_) => (ic::X_CIRCLE, tokens.danger, tr("Not loaded")), BakeHighState::Canceled => (ic::WARNING, tokens.warning, tr("Canceled")), }; + let reason = match &row.state { + BakeHighState::Failed(reason) => Some(reason.as_str()), + BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, format!("{}, {state}", row.file))); + super::describe(ui, &response, reason); let painter = ui.painter(); if response.hovered() { @@ -84,11 +91,6 @@ fn file_row(ui: &mut Ui, row: &BakeLogHigh) { }; painter.text(pos2(rect.left() + NAME_LEFT + FILE_INDENT, center_y), Align2::LEFT_CENTER, &row.file, font, color); - let reason = match &row.state { - BakeHighState::Failed(reason) => Some(reason.as_str()), - BakeHighState::Canceled => Some(tr("The bake was canceled before this file was loaded.")), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(state).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index 22ad6c46..b64565cb 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -50,7 +50,13 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let no_match = tr("No match"); let name = format!("{}, {}", pair.low.as_deref().unwrap_or(no_match), pair.high.as_deref().unwrap_or(no_match)); + let reason = match (&pair.low, &pair.high) { + (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), + (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), + _ => None, + }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); + super::describe(ui, &response, reason.as_deref()); let painter = ui.painter(); if response.hovered() { @@ -65,11 +71,6 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { } rule(ui, rect); - let reason = match (&pair.low, &pair.high) { - (Some(low), None) => Some(trf("No high poly part pairs with {part} by name, so it bakes from none.", &[("part", low)])), - (None, Some(high)) => Some(trf("No low poly part pairs with {part} by name, so no texture set bakes from it.", &[("part", high)])), - _ => None, - }; if let Some(reason) = reason { response.on_hover_ui(|ui| { ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 2e46ef22..44a9b4f7 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -52,9 +52,12 @@ fn note(app: &mut TextureCraftApp, ui: &mut Ui, (texture_set, map): (usize, Bake let checked = app.session.doc.project.texture_sets.get(texture_set).is_some_and(|set| set.bake.maps.is_enabled(map)); ui.label(RichText::new(glyph).color(tokens.warning)); - ui.add(egui::Label::new(&text).truncate()).on_hover_ui(|ui| { + let reasons = reasons(changes, checked); + let line = ui.add(egui::Label::new(&text).truncate()); + ui.ctx().accesskit_node_builder(line.id, |node| node.set_description(reasons.join(" "))); + line.on_hover_ui(|ui| { ui.label(RichText::new(title).font(semibold(TOOLTIP_TEXT_SIZE)).color(tokens.text)); - for reason in reasons(changes, checked) { + for reason in reasons { ui.label(RichText::new(reason).size(TOOLTIP_TEXT_SIZE).color(tokens.text_dim)); } }); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cb772815..4d6ff3eb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -123,6 +123,7 @@ mod placed_fill_slot; mod placement; mod pointer_lock; mod popup_drag; +mod press_edit; mod preview_dots; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/press_edit.rs b/crates/ui-egui/src/press_edit.rs new file mode 100644 index 00000000..22376088 --- /dev/null +++ b/crates/ui-egui/src/press_edit.rs @@ -0,0 +1,8 @@ +//! What [`crate::widgets::press_edit`] keeps of an editor's last change + +/// The press an editor's last change belonged to, and the frame it was seen in +#[derive(Clone, Copy)] +pub(crate) struct PressEdit { + pub(crate) press: u64, + pub(crate) frame: u64, +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b09f71d2..743f7fbe 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -5,6 +5,7 @@ use egui::{Color32, CornerRadius, Rect, Response, RichText, Sense, Stroke, Strok use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; +use crate::press_edit::PressEdit; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -52,13 +53,6 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { }) } -/// The press an editor's last change belonged to, and the frame it was seen in -#[derive(Clone, Copy)] -struct PressEdit { - press: u64, - frame: u64, -} - /// [`slider`] for a value re-read from the document every frame: `Some(merge)` on every frame /// that changes `value` (live while dragging, a click on the track, a typed value). `merge` is /// true for the later changes of one drag, so the edit that applies them (with the command's diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index faf87c78..398e93b8 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -165,8 +165,8 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st let mut harness = harness(64); change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); - // Held still well past the settle time, as a hand pausing mid-drag - let corner = egui::pos2(1590.0, 990.0); + // Held still well past the settle time, as a hand pausing mid-drag, in the window's corner where no control takes the press + let corner = harness.ctx.content_rect().right_bottom() - egui::vec2(10.0, 10.0); harness.drag_at(corner); harness.run_steps(120); assert!(harness.state().bake.is_none(), "the edit is not over while the press lasts"); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 972dc919..ad8fbe24 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -734,7 +734,8 @@ fn a_baked_maps_row_shows_out_of_date_once_its_settings_change() { execute(&mut harness.state_mut().session, "bake.settings", &json!({ "dilation": 4 })).unwrap(); harness.run_steps(3); - harness.get_by_label("Out of date: Position"); + 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"); } diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 29099a64..f52fe624 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,7 +1,7 @@ //! The Baking Log panel: the latest bake, map by map use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_ui_egui::TextureCraftApp; @@ -56,6 +56,20 @@ fn the_baking_process_tab_lists_each_set_and_map_with_how_it_went() { assert!(harness.query_by_label(&format!("{} ID, Not baked", names[1])).is_some(), "set 1's row failed"); } +#[test] +fn a_failed_rows_reason_is_read_without_hovering() { + let mut harness = harness(); + + bake_with_set_1_failing(&mut harness, &[BakedMap::Id]); + + let app = harness.state(); + let row = app.session.bake_log.maps.iter().find(|row| row.texture_set == 1).unwrap(); + let BakeMapState::Failed(reason) = &row.state else { panic!("set 1's bake failed: {:?}", row.state) }; + let label = format!("{} ID, Not baked", row.set_name); + let node = harness.get_by_label(&label); + assert_eq!(node.accesskit_node().description().as_deref(), Some(reason.as_str()), "the row's node carries its tooltip's reason"); +} + #[test] fn a_one_map_bake_lists_only_that_map() { let mut harness = harness(); @@ -174,10 +188,13 @@ fn the_high_poly_tab_lists_each_sets_high_poly_files_under_a_row_that_folds() { harness.run_steps(3); let set_name = harness.state().session.doc.project.texture_sets[0].name.clone(); harness.get_by_label("ball_high.obj, Loaded"); + let set_row = format!("{set_name}, High poly files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(true)); - harness.get_by_label(&format!("{set_name}, High poly files")).click(); + harness.get_by_label(&set_row).click(); harness.run_steps(3); assert!(harness.query_by_label("ball_high.obj, Loaded").is_none(), "a folded set hides its files"); + assert_eq!(harness.get_by_label(&set_row).accesskit_node().data().is_expanded(), Some(false), "the row says it is folded"); } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index aa049fdc..6c879100 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -1,7 +1,7 @@ //! The generator's note when a mesh map it reads is not baked or out of date, and its Bake button use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::{BakedMap, LayerId}; use texturecraft_engine::geom::primitives; @@ -40,7 +40,8 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) { #[test] fn the_note_shows_while_the_curvature_map_is_missing_or_out_of_date_only() { let mut harness = harness(); - harness.get_by_label("Curvature map not baked"); + let description = harness.get_by_label("Curvature map not baked").accesskit_node().description(); + assert!(description.is_some_and(|reasons| !reasons.is_empty()), "why the note shows is read without hovering"); execute(&mut harness.state_mut().session, "bake.run", &json!({ "maps": ["curvature"] })).unwrap(); harness.run_steps(3); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b68a5c77..5c8c38a1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -335,8 +335,8 @@ own). Imported maps, and maps saved before this record existed, never show: (the active one by default), replacing its previous one, or turns it off with `null`; it is saved with the project and shows as the set's `autoRebake` in `project.inspect`. While the desktop or web app is in Bake mode, an auto-rebake map that goes out of date is baked again on its own in the -background, alone (with every checked map when the output size changed), once what it is baked from has stopped changing for half a second; a change during -that bake restarts it. A skew or cage stroke (`bake.skew.paint`, `bake.cage.paint`) on a set that +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 whole. The first `bake.skew.paint` stroke of a set (no skew map yet) turns Auto-rebake on for its From e3c299963bea5af7298d2ac38fe8caabd56a5f18 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:26:39 +0000 Subject: [PATCH 19/26] List the Baking Log, out-of-date mesh maps and Auto-rebake in the features --- docs/features.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/features.md b/docs/features.md index 2826868c..d2992ba1 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,6 +164,16 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA channel with the summary and the message for each failed set. - **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is finished; the bake bar follows the newest map, pins a finished one or shows the material. +- **Baking Log** at the bottom of Bake mode: the latest bake map by map (Baking Process), the high + poly files each set loads (High Poly Parameters) and how parts paired by name (Matching by Name), + with an issues filter; a failed or canceled map opens its settings. `bake.log` returns the same rows. +- **Out-of-date mesh maps:** each bake records what every map was baked from; a map whose mesh, high + poly, cage or settings changed since shows a clock in Mesh Map Bakers (`outOfDate` in + `project.inspect`), and a generator reading a missing or out-of-date map shows one line with a + Bake button. +- **Auto-rebake:** one map per texture set (`bake.autoRebake`, a row icon in Mesh Map Bakers) is + baked again in the background in Bake mode once what it is baked from stops changing; a skew or + cage stroke rebakes only the stroke's box. The first skew stroke turns it on for the Normal 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 From 67c8ec6470a4bfe9cf168b59cccb0f62c2a084d0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 20/26] Mask and restore a region bake's texels row by row instead of dividing per sample --- crates/bake/src/lib.rs | 15 ++++++++------- crates/bake/src/texel_box.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 73847b5b..d67c684c 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -273,10 +273,8 @@ fn bake_prepared( if let Some(region) = region { for (row_index, row) in gbuffer.tri.chunks_mut(sample_width).enumerate() { let y = (sample_start_y + row_index) / samples_per_axis; - for (sample_x, triangle) in row.iter_mut().enumerate() { - if !region.texels.contains(sample_x / samples_per_axis, y) { - *triangle = NO_TRI; - } + for outside in region.texels.outside_row(y, samples_per_axis, row.len()) { + row.get_mut(outside).unwrap_or_default().fill(NO_TRI); } } } @@ -329,9 +327,12 @@ fn bake_prepared( let previous = region.previous.get(map).filter(|previous| previous.len() == pixels.len()); let previous = previous.ok_or_else(|| BakeError::Invalid(format!("no whole {} map of this size to bake a region of", map.id())))?; let components = map.components(); - for (index, (pixel, kept)) in pixels.chunks_exact_mut(components).zip(previous.chunks_exact(components)).enumerate() { - if !region.texels.contains(index % width, index / width) { - pixel.copy_from_slice(kept); + let row_len = (width * components).max(1); + for (y, (row, kept)) in pixels.chunks_exact_mut(row_len).zip(previous.chunks_exact(row_len)).enumerate() { + for outside in region.texels.outside_row(y, components, row_len) { + if let (Some(row), Some(kept)) = (row.get_mut(outside.clone()), kept.get(outside)) { + row.copy_from_slice(kept); + } } } } diff --git a/crates/bake/src/texel_box.rs b/crates/bake/src/texel_box.rs index 3dc062cf..306dd04b 100644 --- a/crates/bake/src/texel_box.rs +++ b/crates/bake/src/texel_box.rs @@ -1,3 +1,5 @@ +use std::ops::Range; + /// A rectangle of output texels, from `min` (inclusive) to `max` (exclusive), in atlas pixels #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TexelBox { @@ -11,6 +13,15 @@ impl TexelBox { (self.min.0 as usize..self.max.0 as usize).contains(&x) && (self.min.1 as usize..self.max.1 as usize).contains(&y) } + /// The items of texel row `y` outside the box, in a row of `len` items with `scale` items per texel: those before the box and those after it + pub fn outside_row(&self, y: usize, scale: usize, len: usize) -> [Range; 2] { + let (start, end) = match (self.min.1 as usize..self.max.1 as usize).contains(&y) { + true => ((self.min.0 as usize * scale).min(len), (self.max.0 as usize * scale).min(len)), + false => (len, len), + }; + [0..start, end.max(start)..len] + } + /// The box grown by `texels` on every side, kept inside a `width` x `height` image pub fn grown(&self, texels: u32, width: u32, height: u32) -> TexelBox { TexelBox { @@ -19,3 +30,28 @@ impl TexelBox { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_items_outside_a_row_are_the_ones_contains_leaves_out() { + let (width, scale) = (6, 2); + let boxes = [ + TexelBox { min: (1, 1), max: (4, 3) }, + TexelBox { min: (0, 0), max: (6, 4) }, + TexelBox { min: (3, 1), max: (9, 2) }, + TexelBox { min: (4, 1), max: (2, 3) }, + ]; + for texels in boxes { + for y in 0..4 { + let outside = texels.outside_row(y, scale, width * scale); + for item in 0..width * scale { + let is_outside = outside.iter().any(|range| range.contains(&item)); + assert_eq!(is_outside, !texels.contains(item / scale, y), "{texels:?} row {y} item {item}"); + } + } + } + } +} From 6399d008223af6b970efb5944ac7cd67abe6fccd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 21/26] Take a set's shared bake fingerprints once for all its maps, once per Mesh Map Bakers frame --- crates/engine/src/bake/bake_sources.rs | 22 ++++++++++++------- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 11 +++++----- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/bake/bake_sources.rs b/crates/engine/src/bake/bake_sources.rs index e835c97c..4235f5f8 100644 --- a/crates/engine/src/bake/bake_sources.rs +++ b/crates/engine/src/bake/bake_sources.rs @@ -9,6 +9,12 @@ 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 { + let map_settings = self.doc.project.texture_set(texture_set)?.map_settings_fingerprint(map); + Ok(BakeSource { map_settings, ..self.set_bake_source(texture_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 { let set = self.doc.project.texture_set(texture_set)?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); let high_poly = match from_high { @@ -18,13 +24,7 @@ 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: set.map_settings_fingerprint(map), - }) + Ok(BakeSource { low_poly: self.low_poly_fingerprint(), high_poly, cage, settings: set.bake_settings_fingerprint(), map_settings: 0 }) } /// What changed since `map` of texture set `texture_set` was baked; empty when up to date, not baked or without a record @@ -37,7 +37,13 @@ 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::ALL.into_iter().map(|map| (map, self.bake_changes(texture_set, map))).filter(|(_, changes)| !changes.is_empty()).collect() + 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 }))); + changes.filter(|(_, changes)| !changes.is_empty()).collect() } /// Fingerprint of the low poly's own geometry (computed once per loaded mesh) diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index fd58b9a4..d2442917 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -94,8 +94,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); let drag_from: Option = 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 { - match ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { + let changes = out_of_date.get(&map).map_or(&[][..], Vec::as_slice); + match ui.push_id(map, |ui| row(app, ui, (map, changes), settings, map == selected, &mut check_drag, drag_from)).inner { Some(RowClick::Row) => { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); @@ -255,11 +257,11 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, w } } -/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check +/// One baker row: its hover icons end in the Auto-rebake toggle, which stays while on, and an out-of-date map's thumbnail carries a clock naming its `changes` (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns what was clicked, if not the check fn row( app: &mut TextureCraftApp, ui: &mut Ui, - map: BakedMap, + (map, changes): (BakedMap, &[BakeChange]), settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option, @@ -296,9 +298,8 @@ fn row( thumbnail(ui, thumbnail_rect, texture.as_ref()); let texture_set = app.session.ts(); - let changes = app.session.bake_changes(texture_set, map); if !changes.is_empty() { - out_of_date_mark(ui, thumbnail_rect, name, &changes); + 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 From 1ab2f153497c59e40290d25a0c311be12310d055 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:36:14 +0000 Subject: [PATCH 22/26] Read each auto-rebake map's bake source once per poll and compare it with its record directly --- crates/engine/src/bake/auto_rebake.rs | 2 +- crates/engine/src/bake/painted_region.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/bake/auto_rebake.rs b/crates/engine/src/bake/auto_rebake.rs index 3f50f672..8f5704a2 100644 --- a/crates/engine/src/bake/auto_rebake.rs +++ b/crates/engine/src/bake/auto_rebake.rs @@ -47,7 +47,7 @@ impl Session { let map = set.auto_rebake?; let record = set.bake_sources.get(&map).filter(|_| set.baked.contains(&map))?; let current = self.bake_source(index, map).ok()?; - (!record.changes(¤t).is_empty()).then_some((index, map, current)) + (*record != current).then_some((index, map, current)) }) .collect() } diff --git a/crates/engine/src/bake/painted_region.rs b/crates/engine/src/bake/painted_region.rs index c19db7a3..0747cf0a 100644 --- a/crates/engine/src/bake/painted_region.rs +++ b/crates/engine/src/bake/painted_region.rs @@ -47,8 +47,12 @@ impl Session { let set = self.doc.project.texture_sets.get(*index)?; let map = set.auto_rebake.filter(|map| set.baked.contains(map))?; let from_high = !set.bake.high_poly.use_low_as_high && !self.doc.bake_meshes.high.is_empty(); - (from_high && self.bake_changes(*index, map).is_empty()).then_some(())?; - Some((*index, map, self.bake_source(*index, map).ok()?, region.stroke)) + from_high.then_some(())?; + let current = self.bake_source(*index, map).ok()?; + + // Only painting changed it: a map without a record is never out of date + let up_to_date = set.bake_sources.get(&map).is_none_or(|record| *record == current); + up_to_date.then_some((*index, map, current, region.stroke)) }) .collect() } From 8d8993aae4588a97b6f6a6d484f617d2c0b71bb0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:45:33 +0000 Subject: [PATCH 23/26] Forget the press records of earlier presses, so editors dragged once no longer stay in memory --- crates/ui-egui/src/property_sheet/tests.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index d7d45b32..28b126c4 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1042,6 +1042,26 @@ fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { assert_eq!(edit(Some(owner), true), Some(false), "a separate press starts an undo step after reopening"); } +/// Editing one editor after another, a press at a time, keeps the record of the latest press only (it kept one per editor ever dragged) +#[test] +fn the_editors_of_earlier_presses_are_forgotten() { + const EDITOR_COUNT: usize = 12; + let context = egui::Context::default(); + let button = + |pressed| egui::Event::PointerButton { pos: egui::Pos2::ZERO, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + + for editor in 0..EDITOR_COUNT { + let owner = egui::Id::unique(("distinct editor", editor)); + for pressed in [true, false] { + let input = egui::RawInput { events: vec![button(pressed)], ..Default::default() }; + context.run_ui(input, |ui| _ = crate::widgets::press_edit(ui, owner, pressed)).textures_delta.clear(); + } + } + + let kept = context.data(|data| data.count::()); + assert!(kept < 2, "{kept} editor records kept after {EDITOR_COUNT} presses"); +} + /// A floating panel in its own OS window runs a pass of its own between two frames of the main window: the drag stays one undo step #[test] fn a_drag_stays_one_undo_step_while_another_window_draws() { diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 743f7fbe..abba3370 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -41,6 +41,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { Some(start) => { let continuing = previous.is_some_and(|previous| previous.press == start); if changed || continuing { + // Only the latest press's editors can merge, so its first change forgets every editor of the older ones + let latest_press = egui::Id::unique("pointer edit press"); + if data.get_temp::(latest_press) != Some(start) { + data.remove_by_type::(); + data.insert_temp(latest_press, start); + } data.insert_temp(id, PressEdit { press: start, frame }); } continuing From fe0208f5d3db30f31a10589a1e7201f43e071bad Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:19:40 +0000 Subject: [PATCH 24/26] Count no high part as unused while a set matching "Always" bakes from it, note the occlusion Rust Runoff reads, and keep the maps still queued when a bake is canceled --- crates/core/src/layer.rs | 8 ++++ crates/engine/src/bake/bake_log.rs | 11 +++-- crates/engine/tests/it/bake_log.rs | 16 +++++++ .../ui-egui/src/generator_panel/bake_note.rs | 2 +- crates/ui-egui/src/lib.rs | 9 +++- crates/ui-egui/tests/it/bake_job_mesh.rs | 45 +++++++++++++++---- crates/ui-egui/tests/it/baking_log.rs | 14 ++++-- .../ui-egui/tests/it/generator_bake_note.rs | 13 +++++- 8 files changed, 99 insertions(+), 19 deletions(-) diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 158a1b6a..56a8ebb0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1268,6 +1268,14 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The mesh maps the generator reads that a bake makes: its inputs in use, and the occlusion Dripping Rust reads whole, which no input replaces + pub fn baked_maps_read(&self) -> &'static [BakedMap] { + match self.kind { + GeneratorKind::DrippingRust => &[BakedMap::AmbientOcclusion], + _ => self.inputs_in_use(), + } + } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity pub fn texture_in_use(&self) -> Option<&TextureLayer> { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) diff --git a/crates/engine/src/bake/bake_log.rs b/crates/engine/src/bake/bake_log.rs index 2f7936c8..c03315e7 100644 --- a/crates/engine/src/bake/bake_log.rs +++ b/crates/engine/src/bake/bake_log.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use texturecraft_bake::NamePair; -use texturecraft_core::{BakedMap, Project}; +use texturecraft_core::{BakedMap, MeshMatchMode, Project}; use super::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, BakeMesh}; use crate::Session; @@ -149,13 +149,16 @@ impl Session { .collect(); } - /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it + /// The name pairs of each of `sets` that matches "By Mesh Name"; a high poly part counts as unpaired only when none of them pairs with it and no set matching "Always" bakes from every part fn bake_log_matching(&self, sets: &[usize]) -> Option { let mut matching: Option = None; let (mut paired_highs, mut unpaired_highs) = (HashSet::new(), Vec::new()); + let mut every_high_used = false; for &set in sets { - let (Ok(Some(pairs)), Ok(texture_set)) = (self.bake_name_pairs(set), self.doc.project.texture_set(set)) else { continue }; + 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(), @@ -173,7 +176,7 @@ impl Session { } } - if let Some(matching) = &mut matching { + if let Some(matching) = matching.as_mut().filter(|_| !every_high_used) { let unpaired = unpaired_highs.into_iter().filter(|high| !paired_highs.contains(high)); matching.pairs.extend(unpaired.map(|high| NamePair { low: None, high: Some(high) })); } diff --git a/crates/engine/tests/it/bake_log.rs b/crates/engine/tests/it/bake_log.rs index ee26594a..2fbd461b 100644 --- a/crates/engine/tests/it/bake_log.rs +++ b/crates/engine/tests/it/bake_log.rs @@ -129,6 +129,22 @@ fn a_bake_matching_by_name_lists_its_pairs_and_only_the_high_parts_no_set_pairs_ assert_eq!(log["matching"]["pairs"][1], json!({ "low": "Lid_low", "high": null }), "{log}"); } +#[test] +fn a_high_part_counts_as_unused_only_when_no_set_of_the_bake_matches_always() { + let obj = "o Box_low\nusemtl Body\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ + o Lid_low\nusemtl Lid\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + let mut session = Session::from_mesh_bytes("sets.obj", obj.as_bytes(), 128, "sets").unwrap(); + session + .add_high_poly_bytes("high.obj", b"o Box_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\no Extra_high\nv 2 0 0\nv 3 0 0\nv 2 1 0\nf 4 5 6\n".to_vec()) + .unwrap(); + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + session.begin_bake_log(&[0, 1]); + + let matching = session.bake_log.matching.clone().unwrap(); + assert!(matching.pairs.iter().all(|pair| pair.low.is_some()), "the set matching \"Always\" bakes from Extra_high: {:?}", matching.pairs); + assert_eq!(matching.issue_count(), 0); +} + #[test] fn a_canceled_bake_at_a_new_output_size_keeps_none_of_its_maps_so_the_sets_others_stay() { let mut session = sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/src/generator_panel/bake_note.rs b/crates/ui-egui/src/generator_panel/bake_note.rs index 44a9b4f7..4d576753 100644 --- a/crates/ui-egui/src/generator_panel/bake_note.rs +++ b/crates/ui-egui/src/generator_panel/bake_note.rs @@ -23,7 +23,7 @@ const TOOLTIP_TEXT_SIZE: f32 = 12.0; /// The note for each mesh map `generator` reads from the active texture set that is not baked or out of date pub(super) fn bake_notes(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, generator: &Generator) { let texture_set = app.session.ts(); - for map in generator.inputs_in_use() { + for map in generator.baked_maps_read() { if generator.inputs.contains_key(map) { continue; } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4d6ff3eb..5e793a7c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -973,9 +973,16 @@ impl TextureCraftApp { let Some(job) = self.bake.take() else { return }; let mut discarded = None; - if let Some(running) = job.current { + if let Some(mut running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); + // 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); + } + // 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 { diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index c3292beb..8b3971b2 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -1,15 +1,27 @@ -//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps -//! the mesh meanwhile, the job is cancelled and its result is dropped. +//! A bake job belongs to the mesh it started on: when `file.changeMesh` or a reimport swaps the mesh meanwhile, the job is cancelled and its result dropped; a cancel keeps the maps it finished use std::sync::Arc; use std::sync::atomic::Ordering; +use std::sync::mpsc::Sender; use egui_kittest::Harness; +use texturecraft_engine::StreamedMap; use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; -/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id` fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { + let (mut harness, progress, _senders) = running_job(mesh_id); + harness.step(); + check(&harness, &progress); +} + +/// The ends a test plays the bake worker with: its result (never sent) and its finished maps +type WorkerSenders = (Sender>, Sender); + +/// An app with a running bake job of set 0 started on mesh `mesh_id`, whose worker sends only what the test sends +fn running_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc, WorkerSenders) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = Harness::builder() .with_size(egui::vec2(1600.0, 960.0)) @@ -17,8 +29,8 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes .build_eframe(|context| TextureCraftApp::new(context, session)); harness.run_steps(4); let progress = Arc::new(Progress::new()); - let (_result_sender, receiver) = std::sync::mpsc::channel(); - let (_map_sender, maps) = std::sync::mpsc::channel(); + let (result_sender, receiver) = std::sync::mpsc::channel(); + let (map_sender, maps) = std::sync::mpsc::channel(); let job_mesh_id = mesh_id(harness.state().session.mesh_id); let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let running = RunningBake { @@ -33,9 +45,7 @@ fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harnes painted_stroke: 0, }; harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None, rebake: None }); - - harness.step(); - check(&harness, &progress); + (harness, progress, (result_sender, map_sender)) } #[test] @@ -59,3 +69,22 @@ fn a_job_on_the_current_mesh_keeps_running() { }, ); } + +#[test] +fn a_cancel_keeps_the_maps_the_worker_sent_before_any_frame_took_them() { + let (mut harness, _progress, (_result_sender, map_sender)) = running_job(|current| current); + let data = Arc::new(vec![0.5; 64 * 64]); + let normal_before = harness.state().session.baked(0).and_then(|baked| baked.maps.get(&BakedMap::Normal).cloned()); + assert!(normal_before.is_some(), "the sample's Normal map is baked before the job"); + for (index, map) in [BakedMap::Curvature, BakedMap::AmbientOcclusion].into_iter().enumerate() { + map_sender.send(StreamedMap { map, index, total: 2, resolution: 64, height: 64, data: data.clone() }).unwrap(); + } + + harness.state_mut().cancel_bake(); + let baked = harness.state().session.baked(0).unwrap(); + for map in [BakedMap::Curvature, BakedMap::AmbientOcclusion] { + assert!(baked.maps.get(&map).is_some_and(|kept| Arc::ptr_eq(kept, &data)), "{map:?} is kept"); + } + let normal = baked.maps.get(&BakedMap::Normal); + assert!(normal.zip(normal_before.as_ref()).is_some_and(|(now, before)| Arc::ptr_eq(now, before)), "a map the worker never sent keeps the one baked before"); +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index f52fe624..5e7e9681 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -100,16 +100,22 @@ fn a_canceled_bake_keeps_the_maps_it_finished_and_warns_only_on_the_rest() { let app = harness.state(); assert_eq!(state(app, 0, BakedMap::Id), Some(BakeMapState::Baked), "a ticked map keeps its tick"); - for (set, map) in [(0, BakedMap::Position), (1, BakedMap::Id), (1, BakedMap::Position)] { - assert_eq!(state(app, set, map), Some(BakeMapState::Canceled), "set {set}'s unfinished {map:?} warns"); + for map in [BakedMap::Id, BakedMap::Position] { + assert_eq!(state(app, 1, map), Some(BakeMapState::Canceled), "set 1 was still queued, so its {map:?} warns"); } + + // A map the worker sent before the cancel is kept too, so whether set 0's Position finished depends on timing + let row = state(app, 0, BakedMap::Position); + assert!(matches!(row, Some(BakeMapState::Baked | BakeMapState::Canceled)), "set 0's Position is ticked or, unfinished, warns: {row:?}"); let after = app.session.baked(0).cloned().unwrap_or_default(); let changed = |map: BakedMap| match (before.maps.get(&map), after.maps.get(&map)) { (Some(old), Some(new)) => !std::sync::Arc::ptr_eq(old, new), (old, new) => old.is_some() != new.is_some(), }; - assert!(changed(BakedMap::Id), "the ticked map is in the document"); - assert!(!changed(BakedMap::Position), "the unfinished map stays as it was"); + for map in [BakedMap::Id, BakedMap::Position] { + let ticked = state(app, 0, map) == Some(BakeMapState::Baked); + assert_eq!(changed(map), ticked, "set 0's {map:?} is in the document exactly when its row is ticked"); + } } #[test] diff --git a/crates/ui-egui/tests/it/generator_bake_note.rs b/crates/ui-egui/tests/it/generator_bake_note.rs index 6c879100..b4c2be8a 100644 --- a/crates/ui-egui/tests/it/generator_bake_note.rs +++ b/crates/ui-egui/tests/it/generator_bake_note.rs @@ -11,12 +11,17 @@ use texturecraft_ui_egui::docking::Panel; /// A plane whose bake makes only the position map, with a curvature generator selected in a fill layer's mask fn harness() -> Harness<'static, TextureCraftApp> { + harness_with("curvature") +} + +/// A plane whose bake makes only the position map, with a `generator` selected in a fill layer's mask +fn harness_with(generator: &str) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); let mut session = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); execute(&mut session, "bake.settings", &json!({ "resolution": 64, "maps": ["position"], "dilation": 0 })).unwrap(); let layer = execute(&mut session, "layer.add.fill", &json!({ "color": [0.8, 0.3, 0.1] })).unwrap()["layer"].as_u64().unwrap(); execute(&mut session, "mask.add.black", &json!({})).unwrap(); - execute(&mut session, "effect.add.generator", &json!({ "generator": "curvature" })).unwrap(); + execute(&mut session, "effect.add.generator", &json!({ "generator": generator })).unwrap(); session.view = ViewMode::Mask(LayerId(layer)); session.update(); @@ -67,3 +72,9 @@ fn the_notes_bake_button_turns_the_map_on_and_bakes_it_in_the_background() { assert!(harness.state().session.baked(0).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Curvature))); assert!(harness.query_by_label("Curvature map not baked").is_none(), "baked: no note"); } + +#[test] +fn rust_runoff_notes_the_occlusion_it_reads_though_no_input_replaces_it() { + let harness = harness_with("Dripping Rust"); + harness.get_by_label("Ambient Occlusion map not baked"); +} From 57ffd56a039794a4a8bc220f0e47668a0e47a4b6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:42:53 +0000 Subject: [PATCH 25/26] Start an auto-rebake canceled in one project again in the next project opened, and wait while a press is held in a floating panel's window --- crates/ui-egui/src/auto_rebake.rs | 60 +++++++++++++++++++++++++- crates/ui-egui/src/docking.rs | 25 +++++++---- crates/ui-egui/tests/it/auto_rebake.rs | 23 ++++++++++ 3 files changed, 98 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/auto_rebake.rs b/crates/ui-egui/src/auto_rebake.rs index 07bbcaab..473e80ce 100644 --- a/crates/ui-egui/src/auto_rebake.rs +++ b/crates/ui-egui/src/auto_rebake.rs @@ -13,6 +13,8 @@ pub type Due = (usize, BakedMap, BakeSource, Option); /// What the app has seen of the out-of-date auto-rebake maps #[derive(Default)] pub struct AutoRebake { + /// The project these records are of: another project starts with none + project: u64, /// The due maps and the frame time they were first seen as they are pending: Option<(Vec, f64)>, /// Rebakes started that are still due: one that failed or was canceled is not tried again until something changes @@ -21,6 +23,10 @@ pub struct AutoRebake { /// Start, or restart, the rebake of an out-of-date auto-rebake map; only in Bake mode, where its settings are changed pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + if app.auto_rebake.project != app.session.project_id { + app.auto_rebake = AutoRebake { project: app.session.project_id, ..AutoRebake::default() }; + } + if app.ui.mode != state::Mode::Baking { app.auto_rebake.pending = None; return; @@ -48,10 +54,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_secs_f64(SETTLE_SECONDS)); // A held press (a slider dragged and paused) is still editing: the wait starts once it is let go - if ctx.input(|input| input.pointer.any_down()) { + if pointer_held(ctx, app.docks.floating_windows()) { app.auto_rebake.pending = Some((waiting, now)); return; } + match &app.auto_rebake.pending { Some((seen, since)) if *seen == waiting && now - since >= SETTLE_SECONDS => {} Some((seen, _)) if *seen == waiting => return, @@ -68,6 +75,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +/// Whether a mouse button is down in the main window or in one of the floating panels' own `windows` +fn pointer_held(ctx: &egui::Context, windows: &[egui::ViewportId]) -> bool { + ctx.input(|input| input.pointer.any_down()) || windows.iter().any(|window| ctx.input_for(*window, |input| input.pointer.any_down())) +} + /// Rebake only the map of `rebake`'s texture set in the background, shown in the Baking Log like any bake fn start(app: &mut TextureCraftApp, rebake: Due) { let (set, map, ..) = rebake; @@ -83,3 +95,49 @@ fn start(app: &mut TextureCraftApp, rebake: Due) { app.bake_report = bake_report::BakeReport { auto_rebake: true, ..bake_report::BakeReport::started(app.last_time) }; app.bake = Some(BakeJob { queue: vec![set], current: None, total: 1, mesh_id: app.session.mesh_id, only: None, rebake: Some(rebake) }); } + +#[cfg(test)] +mod tests { + use super::*; + + /// Whether a press is held, seen from the main window after a button went down in a floating panel's window (`window_listed`) + fn held_after_a_press_in_a_floating_window(window_listed: bool) -> bool { + use std::{cell::RefCell, rc::Rc}; + + let window = egui::ViewportId::from_hash_of("floating panel"); + let context = egui::Context::default(); + context.set_embed_viewports(false); + + // Runs the window's pass inside its parent's, as eframe does + let arriving = Rc::new(RefCell::new(Vec::new())); + let queued = Rc::clone(&arriving); + egui::Context::set_immediate_viewport_renderer(move |context, viewport| { + let mut input = egui::RawInput { viewport_id: viewport.ids.this, events: queued.take(), ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo { parent: Some(viewport.ids.parent), ..Default::default() }); + let mut output = context.run_ui(input, viewport.viewport_ui_cb); + output.textures_delta.clear(); + }); + + let at = egui::pos2(20.0, 20.0); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + *arriving.borrow_mut() = vec![egui::Event::PointerMoved(at), press]; + let windows: &[egui::ViewportId] = if window_listed { &[window] } else { &[] }; + let mut held = false; + + // The first pass hands the press to the window after the hold was read; the second reads it + for _ in 0..2 { + let mut output = context.run_ui(egui::RawInput::default(), |ui| { + held = pointer_held(ui.ctx(), windows); + ui.ctx().show_viewport_immediate(window, egui::ViewportBuilder::default(), |_, _| {}); + }); + output.textures_delta.clear(); + } + held + } + + #[test] + fn a_press_held_in_a_floating_panels_window_counts_as_held() { + assert!(held_after_a_press_in_a_floating_window(true), "the slider dragged in a floating panel is still editing"); + assert!(!held_after_a_press_in_a_floating_window(false), "the main window's own pointer is up"); + } +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f1acd9e7..5f75aaae 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -391,23 +391,29 @@ impl Dock { } } -/// What the dock area keeps between passes: the workspace it shows and the panels' specs. +/// What the dock area keeps between passes: the workspace it shows and the panels' specs #[derive(Default)] pub(crate) struct LiveDock { shown: Option>, specs: Tracked, - /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window. + /// The panel whose floating window takes over the held press in the next pass, with the grab point inside the window continue_move: Option<(Panel, egui::Vec2)>, + /// The OS windows of the floating panels, as the last pass's dock drew them + floating_windows: Vec, } impl LiveDock { - /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab`. + /// The OS windows the last pass's dock drew floating panels in + pub(crate) fn floating_windows(&self) -> &[ViewportId] { + &self.floating_windows + } + + /// Asks the next pass's dock to let the window holding `panel` follow the held pointer from `grab` pub(crate) fn hand_over(&mut self, panel: Panel, grab: egui::Vec2) { self.continue_move = Some((panel, grab)); } - /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, - /// so an idle pass keeps the workspace's revision and the dock reads no spec. + /// The `Arc` the dock shows for `workspace`: the last one while the arrangement is the same, so an idle pass reads no spec fn shown(&mut self, workspace: &Workspace) -> Arc { if let Some(shown) = self.shown.as_ref().filter(|shown| ***shown == *workspace) { return Arc::clone(shown); @@ -470,7 +476,7 @@ pub(crate) fn input_blocked(app: &TextureCraftApp, context: &egui::Context) -> b modal } -/// Draw the dock (viewport and panels) into `ui`. +/// Draw the dock (viewport and panels) into `ui` pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { // Rendering keeps disabled panels visible because it shares the painting dock let dock_mode = if app.ui.mode == crate::state::Mode::Rendering { crate::state::Mode::Painting } else { app.ui.mode }; @@ -484,12 +490,11 @@ 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. + // The specs leave the app while its panels borrow it, and come back with their revision let specs = std::mem::take(&mut app.docks.specs); let hand_over = app.docks.continue_move.take(); let raise = app.ui.dock.raise.take(); - // Panels arrange in a split tree around the viewport; floating title bars only move windows. - // Each closable tab has its close button, as each group header had one for its shown panel. + // Panels split around the viewport, floating title bars only move windows, and each closable tab has its close button 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); @@ -505,6 +510,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { (output, panels.focused_windows) }; app.docks.specs = specs; + app.docks.floating_windows.clear(); + app.docks.floating_windows.extend(output.windows.iter().map(|(_, viewport)| *viewport)); // The popup needs the viewport the dock recorded this frame crate::rail_popup::show(app, &context); diff --git a/crates/ui-egui/tests/it/auto_rebake.rs b/crates/ui-egui/tests/it/auto_rebake.rs index 398e93b8..15534f76 100644 --- a/crates/ui-egui/tests/it/auto_rebake.rs +++ b/crates/ui-egui/tests/it/auto_rebake.rs @@ -9,6 +9,9 @@ use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::Mode; +/// Frames far past the half-second settle wait, at the harness's quarter-second step +const PAST_THE_SETTLE_FRAMES: usize = 60; + /// A plane in Bake mode with its position and ID maps baked and Auto-rebake on for the position map fn harness(resolution: u32) -> Harness<'static, TextureCraftApp> { let mesh = primitives::builtin("plane").unwrap(); @@ -174,3 +177,23 @@ fn no_rebake_starts_while_the_pointer_is_held_so_a_paused_drag_stays_one_undo_st harness.drop_at(corner); super::step_until(&mut harness, "the rebake after the release", |app| app.bake.is_some()); } + +#[test] +fn a_rebake_canceled_in_one_project_still_runs_in_the_next_project_opened() { + let mut harness = harness(64); + change_settings(&mut harness, json!({ "positionMode": "boundingBox" })); + super::step_until(&mut harness, "the rebake", |app| app.bake.is_some()); + harness.state_mut().cancel_bake(); + harness.run_steps(PAST_THE_SETTLE_FRAMES); + assert!(harness.state().bake.is_none(), "a canceled rebake is not tried again in its project"); + + // The same project opened again: its out-of-date map reads what the canceled one read + let mesh = primitives::builtin("plane").unwrap(); + let mut next = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + execute(&mut next, "bake.run", &json!({ "resolution": 64, "maps": ["position", "id"], "dilation": 0 })).unwrap(); + execute(&mut next, "bake.autoRebake", &json!({ "map": "position" })).unwrap(); + execute(&mut next, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap(); + harness.state_mut().session.switch_to(next); + + super::step_until(&mut harness, "the rebake in the opened project", |app| app.bake.is_some()); +} From ba1d3aebc33c42621d70943f838d68165cc1cae7 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:03:15 +0000 Subject: [PATCH 26/26] Keep the Baking Log tabs clear of the issues filter on a narrow dock, scrolling them when they don't fit, and cut Matching by Name's part names short to their column, in full on hover --- crates/ui-egui/src/baking_log.rs | 122 ++++++++++++------ .../ui-egui/src/baking_log/matching_list.rs | 86 ++++++++++-- crates/ui-egui/tests/it/baking_log.rs | 53 ++++++++ 3 files changed, 204 insertions(+), 57 deletions(-) diff --git a/crates/ui-egui/src/baking_log.rs b/crates/ui-egui/src/baking_log.rs index db0db2a7..affb1803 100644 --- a/crates/ui-egui/src/baking_log.rs +++ b/crates/ui-egui/src/baking_log.rs @@ -3,7 +3,7 @@ use egui::{Align2, CornerRadius, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeMapState}; +use texturecraft_engine::bake::{BakeLog, BakeLogMap, BakeLogMatching, BakeMapState}; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; @@ -71,15 +71,15 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), STRIP_HEIGHT), Sense::hover()); ui.painter().rect_filled(strip, CornerRadius::ZERO, tokens.chrome); - if let Some(tab) = tabs(ui, strip, app.ui.baking_log_tab, &app.session.bake_log) { + + // The tabs keep clear of the issues filter at its widest, so picking a tab never moves the edge they scroll under + let filter_room = BakingLogTab::ALL.into_iter().map(|tab| filter_width(ui, issue_count(&app.session.bake_log, tab))).fold(0.0, f32::max); + let tabs_right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT - filter_room - TAB_GAP; + if let Some(tab) = tabs(ui, strip.with_max_x(tabs_right.max(strip.left())), app.ui.baking_log_tab, &app.session.bake_log) { app.ui.baking_log_tab = tab; } let tab = app.ui.baking_log_tab; - let issue_count = match tab { - BakingLogTab::BakingProcess => app.session.bake_log.maps.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::HighPolyParameters => app.session.bake_log.highs.iter().filter(|row| row.state.is_issue()).count(), - BakingLogTab::MatchingByName => app.session.bake_log.matching.as_ref().map_or(0, |matching| matching.issue_count()), - }; + let issue_count = issue_count(&app.session.bake_log, tab); if issues_filter(ui, strip, issue_count, app.ui.baking_log_issues_only) { app.ui.baking_log_issues_only = !app.ui.baking_log_issues_only; } @@ -136,55 +136,91 @@ fn open_map_settings(app: &mut TextureCraftApp, texture_set: usize, map: BakedMa app.ui.dock.focus(Panel::MeshMapSettings); } -/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; a tab with work in progress shows dots for its icon +/// How many rows of `tab` have an issue, for the issues filter's count +fn issue_count(log: &BakeLog, tab: BakingLogTab) -> usize { + match tab { + BakingLogTab::BakingProcess => log.maps.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::HighPolyParameters => log.highs.iter().filter(|row| row.state.is_issue()).count(), + BakingLogTab::MatchingByName => log.matching.as_ref().map_or(0, BakeLogMatching::issue_count), + } +} + +/// The tabs on the `strip` along the panel's top edge, as the Properties section tabs; they scroll sideways when wider than it fn tabs(ui: &mut Ui, strip: Rect, shown: BakingLogTab, log: &BakeLog) -> Option { let tokens = Tokens::get(ui.ctx()); - let mut picked = None; - let mut left = strip.left() + SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; - for tab in BakingLogTab::ALL { - let name = tr(tab.name()); - let on = tab == shown; - let width = ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING; - let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); - let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); - response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); - if response.clicked() { - picked = Some(tab); - } + let names = BakingLogTab::ALL.map(|tab| tr(tab.name())); + let widths = names.map(|name| ui.painter().layout_no_wrap(name.to_owned(), semibold(TAB_TEXT_SIZE), tokens.text).size().x + TAB_PADDING); + let first_left = SIDE_PADDING_POINTS - FIRST_TAB_OUTDENT; + let content_width = first_left + widths.iter().sum::() + TAB_GAP * (widths.len() - 1) as f32; - let painter = ui.painter(); - if on { - shown_tab_box(painter, &tokens, rect); - } - let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; - let in_progress = match tab { - BakingLogTab::BakingProcess => log.is_running(), - BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), - BakingLogTab::MatchingByName => false, - }; - let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; - let center_y = strip.center().y + TAB_TOP / 2.0; - painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); - let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; - painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); - if response.has_focus() { - crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); - } + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip).id_salt("baking_log_tabs")); + egui::ScrollArea::horizontal() + .id_salt("baking_log_tabs") + .auto_shrink([false, false]) + .show(&mut strip_ui, |ui| { + let (content, _) = ui.allocate_exact_size(vec2(content_width, strip.height()), Sense::hover()); + let mut picked = None; + let mut left = content.left() + first_left; + for ((tab, name), width) in BakingLogTab::ALL.into_iter().zip(names).zip(widths) { + if tab_button(ui, content, left, width, (tab, name), tab == shown, log) { + picked = Some(tab); + } + left += width + TAB_GAP; + } + picked + }) + .inner +} - left += width + TAB_GAP; +/// One tab `width` wide from `left` on the `strip`, scrolled into view when the focus reaches it; dots for its icon while its work runs +fn tab_button(ui: &mut Ui, strip: Rect, left: f32, width: f32, (tab, name): (BakingLogTab, &str), on: bool, log: &BakeLog) -> bool { + let tokens = Tokens::get(ui.ctx()); + let rect = Rect::from_min_max(pos2(left, strip.top() + TAB_TOP), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, ui.scope_id().with(("baking_log_tab", tab)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, on, name)); + if response.gained_focus() { + response.scroll_to_me(None); } - picked + + let painter = ui.painter(); + if on { + shown_tab_box(painter, &tokens, rect); + } + let color = if on || response.hovered() { tokens.text } else { tokens.text_dim }; + let in_progress = match tab { + BakingLogTab::BakingProcess => log.is_running(), + BakingLogTab::HighPolyParameters => log.is_loading_high_polys(), + BakingLogTab::MatchingByName => false, + }; + let (icon, icon_color) = if in_progress { (ic::DOTS_THREE, tokens.accent) } else { (tab.icon(), color) }; + let center_y = strip.center().y + TAB_TOP / 2.0; + painter.text(pos2(left + TAB_ICON_CENTER, center_y), Align2::CENTER_CENTER, icon, FontId::proportional(TAB_ICON_SIZE), icon_color); + let font = if on { semibold(TAB_TEXT_SIZE) } else { FontId::proportional(TAB_TEXT_SIZE) }; + painter.text(pos2(left + TAB_NAME_LEFT, center_y), Align2::LEFT_CENTER, name, font, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, response.rect, tokens.text_strong); + } + response.clicked() +} + +/// The issues filter's width when it counts `issue_count` rows +fn filter_width(ui: &Ui, issue_count: usize) -> f32 { + let count_width = if issue_count == 0 { + 0.0 + } else { + let tokens = Tokens::get(ui.ctx()); + ui.painter().layout_no_wrap(issue_count.to_string(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP + }; + FILTER_BUTTON_WIDTH + count_width } /// The toggle at the `strip`'s right end that keeps only the rows with an issue: a warning glyph and how many there are fn issues_filter(ui: &mut Ui, strip: Rect, issue_count: usize, on: bool) -> bool { let tokens = Tokens::get(ui.ctx()); let count = (issue_count > 0).then(|| issue_count.to_string()); - let count_width = - count.as_ref().map_or(0.0, |count| ui.painter().layout_no_wrap(count.clone(), semibold(NAME_SIZE), tokens.text).size().x + FILTER_COUNT_GAP); let right = strip.right() - SIDE_PADDING_POINTS + FILTER_OUTDENT; let center_y = strip.center().y + FILTER_DROP; - let rect = Rect::from_min_max(pos2(right - FILTER_BUTTON_WIDTH - count_width, center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); + let rect = Rect::from_min_max(pos2(right - filter_width(ui, issue_count), center_y - FILTER_HEIGHT / 2.0), pos2(right, center_y + FILTER_HEIGHT / 2.0)); let name = match &count { Some(count) => trf("{count}, Show only rows with an issue", &[("count", count)]), diff --git a/crates/ui-egui/src/baking_log/matching_list.rs b/crates/ui-egui/src/baking_log/matching_list.rs index b64565cb..8f4e278b 100644 --- a/crates/ui-egui/src/baking_log/matching_list.rs +++ b/crates/ui-egui/src/baking_log/matching_list.rs @@ -1,6 +1,6 @@ //! The Baking Log's Matching by Name tab: which low poly part the latest bake paired with which high poly part -use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Role, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use texturecraft_engine::bake::{BakeLogMatching, NamePair}; @@ -8,17 +8,21 @@ use super::{GLYPH_SIZE, HOVER_INSET, NAME_SIZE, ROW_HEIGHT}; use crate::i18n::{tr, trf}; use crate::property_sheet::SIDE_PADDING_POINTS; use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; /// Size of the column captions const CAPTION_SIZE: f32 = 11.0; +/// Air between the end of a low poly name and the high poly column +const COLUMN_GAP: f32 = 8.0; + /// The two columns' captions and a row per pair (only the parts with no partner, if `issues_only`), each ruled off below pub(super) fn matching_list(ui: &mut Ui, matching: &BakeLogMatching, issues_only: bool) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); let captions = [caption(tr("Low poly mesh ({suffix})"), &matching.low_suffix), caption(tr("High poly mesh ({suffix})"), &matching.high_suffix)]; - for (left, caption) in columns(rect).into_iter().zip(captions) { - ui.painter().text(pos2(left, rect.center().y), Align2::LEFT_CENTER, caption, FontId::proportional(CAPTION_SIZE), tokens.text_dim); + for (column, caption) in columns(rect).into_iter().zip(captions) { + column_text(ui, column, caption, CAPTION_SIZE, tokens.text_dim); } rule(ui, rect); @@ -32,9 +36,19 @@ fn caption(template: &str, suffix: &str) -> String { template.split("{suffix}").map(str::to_uppercase).collect::>().join(suffix) } -/// The left edges of the low and high poly columns of `row` -fn columns(row: Rect) -> [f32; 2] { - [row.left() + SIDE_PADDING_POINTS, row.center().x] +/// The low and high poly columns of `row`, each ending a gap short of the next column or the side padding +fn columns(row: Rect) -> [Rect; 2] { + let low = row.with_min_x(row.left() + SIDE_PADDING_POINTS).with_max_x(row.center().x - COLUMN_GAP); + let high = row.with_min_x(row.center().x).with_max_x(row.right() - SIDE_PADDING_POINTS); + [low, high] +} + +/// Paint `text` in `color` at the left end of `column`, centred on its height and cut short to its width; whether it was cut +fn column_text(ui: &Ui, column: Rect, text: String, size: f32, color: Color32) -> bool { + let galley = elided(ui.painter(), text, size, color, column.width()); + let cut_short = galley.elided; + ui.painter().galley(pos2(column.left(), column.center().y - galley.size().y / 2.0), galley, color); + cut_short } /// The hairline under `row`, inside the side padding @@ -62,19 +76,63 @@ fn pair_row(ui: &mut Ui, pair: &NamePair) { if response.hovered() { painter.rect_filled(rect.shrink2(vec2(HOVER_INSET, 0.0)), CornerRadius::ZERO, tokens.row_hover); } - let center_y = rect.center().y; - for (left, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { + let mut cut_short = false; + for (column, part) in columns(rect).into_iter().zip([&pair.low, &pair.high]) { match part { - Some(part) => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, part, FontId::proportional(NAME_SIZE), tokens.text), - None => painter.text(pos2(left, center_y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning), - }; + Some(part) => cut_short |= column_text(ui, column, part.clone(), NAME_SIZE, tokens.text), + None => { + painter.text(pos2(column.left(), column.center().y), Align2::LEFT_CENTER, ic::WARNING, FontId::proportional(GLYPH_SIZE), tokens.warning); + } + } } rule(ui, rect); - if let Some(reason) = reason { + // A name cut short shows in full on hover; the row's label carries it in full already + if reason.is_some() || cut_short { response.on_hover_ui(|ui| { - ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); - ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + if cut_short { + ui.label(egui::RichText::new(&name).size(NAME_SIZE).color(tokens.text)); + } + if let Some(reason) = reason { + ui.label(egui::RichText::new(no_match).font(semibold(NAME_SIZE)).color(tokens.text)); + ui.label(egui::RichText::new(reason).size(NAME_SIZE).color(tokens.text_dim)); + } }); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Names longer than their column, in a list as narrow as a small docked log + #[test] + fn long_names_stay_in_their_own_column() { + let long = |side: &str| format!("Left_shoulder_strap_buckle_with_its_rivets_and_stitching_{side}"); + let matching = BakeLogMatching { + low_suffix: "_low".into(), + high_suffix: "_high".into(), + pairs: vec![NamePair { low: Some(long("low")), high: Some(long("high")) }], + }; + let screen = Rect::from_min_size(pos2(0.0, 0.0), vec2(320.0, 200.0)); + let context = egui::Context::default(); + let mut output = context.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| matching_list(ui, &matching, false)); + output.textures_delta.clear(); + + let texts: Vec = output + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 4, "two captions and two names"); + for (index, text) in texts.iter().enumerate() { + assert!(screen.contains_rect(*text), "text {index} {text:?} stays inside the list"); + for other in &texts[index + 1..] { + assert!(!text.intersects(*other), "text {index} {text:?} runs into {other:?}"); + } + } + } +} diff --git a/crates/ui-egui/tests/it/baking_log.rs b/crates/ui-egui/tests/it/baking_log.rs index 5e7e9681..5c616fa5 100644 --- a/crates/ui-egui/tests/it/baking_log.rs +++ b/crates/ui-egui/tests/it/baking_log.rs @@ -1,5 +1,6 @@ //! The Baking Log panel: the latest bake, map by map +use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::bake::{BakeHighState, BakeLogHigh, BakeLogMap, BakeLogMatching, BakeMapState, NamePair}; @@ -251,3 +252,55 @@ fn the_matching_tab_says_when_no_set_matched_by_name() { harness.get_by_label("Set Match to By Mesh Name to pair parts by name."); } + +#[test] +fn on_a_narrow_dock_the_tabs_scroll_clear_of_the_issues_filter() { + // A window this narrow leaves the docked log less room than its three tabs and the filter take together + const NARROW_WINDOW_WIDTH: f32 = 520.0; + + let mut harness = Harness::builder() + .with_size(egui::vec2(NARROW_WINDOW_WIDTH, 1000.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, texturecraft_engine::sample_session(256, 64).unwrap())); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let filter = harness.get_by_label("Show only rows with an issue").rect(); + let strip_start = harness.get_by_role_and_label(Role::Tab, "Baking Process").rect().left(); + let last_tab = harness.get_by_role_and_label(Role::Tab, "Matching by Name").rect(); + assert!(last_tab.right() > filter.left(), "unscrolled, the tabs {last_tab:?} run past the filter {filter:?}, so they must scroll"); + + // Frames for the strip's scroll to the focused tab to finish + const SCROLL_FRAMES: usize = 30; + + for tab in ["Baking Process", "High Poly Parameters", "Matching by Name"] { + harness.get_by_role_and_label(Role::Tab, tab).focus(); + harness.run_steps(SCROLL_FRAMES); + + let rect = harness.get_by_role_and_label(Role::Tab, tab).rect(); + assert!(rect.right() <= filter.left(), "the focused {tab} tab {rect:?} ends left of the filter {filter:?}"); + assert!(rect.left() >= strip_start, "the focused {tab} tab {rect:?} starts inside the log, where the first tab starts unscrolled"); + } +} + +#[test] +fn a_matching_name_cut_short_shows_in_full_on_hover() { + const LONG_NAME: &str = "Left_shoulder_strap_buckle_with_its_rivets_and_its_stitching_low"; + + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + + let mut harness = harness(); + log_a_bake(&mut harness, BakeMapState::Baked); + let pair = NamePair { low: Some(LONG_NAME.into()), high: Some("Strap_high".into()) }; + harness.state_mut().session.bake_log.matching = Some(BakeLogMatching { low_suffix: "_low".into(), high_suffix: "_high".into(), pairs: vec![pair] }); + harness.get_by_label("Matching by Name").click(); + harness.run_steps(3); + let label = format!("{LONG_NAME}, Strap_high"); + let row = harness.get_by_label(&label).rect(); + assert_eq!(harness.query_all_by_label(&label).count(), 1, "no tooltip before hovering"); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + assert_eq!(harness.query_all_by_label(&label).count(), 2, "the tooltip carries both names in full"); +}