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.
This commit is contained in:
Rebornim committed 2026-11-27 06:12:44 +00:00
1 parent 23f27ba16d
commit ff51384164
15 files changed
+186 -35

No files matched your search

+3 -3
View File
@@ -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<usize>) {
/// The bake stopped: every map still waiting or baking is canceled, and so are the finished maps of `discarded` (the set being baked, when they were not kept)
pub fn cancel(&mut self, discarded: Option<usize>) {
for row in &mut self.maps {
if row.state.is_pending() || (Some(row.texture_set) == current && row.state == BakeMapState::Baked) {
if row.state.is_pending() || (Some(row.texture_set) == discarded && row.state == BakeMapState::Baked) {
row.state = BakeMapState::Canceled;
}
}
+37
View File
@@ -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<BakedMap, BakeSource>,
painted_stroke: u64,
) -> Result<Vec<BakedMap>> {
let Some(height) = finished.maps.keys().next().map(|map| finished.height(*map)) else { return Ok(Vec::new()) };
let resized = self.doc.baked.get(&texture_set).is_some_and(|stored| {
!stored.maps.is_empty() && (stored.resolution != finished.resolution || stored.maps.keys().any(|map| stored.height(*map) != height))
});
if resized {
return Ok(Vec::new());
}
// A map the bake did not finish keeps the record of what its stored pixels were baked from
let kept_sources: BTreeMap<BakedMap, BakeSource> =
sources.iter().filter(|(map, _)| finished.maps.contains_key(*map)).map(|(map, source)| (*map, *source)).collect();
let kept: Vec<BakedMap> = finished.maps.keys().copied().collect();
self.edit("Bake mesh maps", |session| {
session.store_bake_maps(texture_set, finished.resolution, height, finished.maps, Some((&kept_sources, painted_stroke)))
})?;
self.log.info("Baker", format!("Kept {} baked maps of texture set {texture_set} from the canceled bake", kept.len()));
Ok(kept)
}
}
+1 -1
View File
@@ -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,
+1
View File
@@ -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;
+2 -2
View File
@@ -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;
+2 -2
View File
@@ -1,5 +1,5 @@
//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back,
//! painting is paused, a cancelled bake leaves the set it was baking alone (sets finished before it
//! painting is paused, ending the preview leaves the set it was baking alone (sets finished before it
//! stay applied), the streamed pixels are the ones a single bake makes, and the preview and the
//! document share each map's buffer instead of holding two copies.
@@ -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);
+31
View File
@@ -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::<Vec<_>>()), Some(before.maps.keys().copied().collect()));
assert_eq!(session.baked(0).map(|baked| baked.resolution), Some(before.resolution));
}
#[test]
fn a_canceled_bake_keeps_the_out_of_date_mark_of_a_map_it_did_not_finish() {
let mut session = sample_session(256, 64).unwrap();
execute(&mut session, "bake.run", &json!({ "resolution": 64, "maps": ["id", "position"], "dilation": 0 })).unwrap();
execute(&mut session, "bake.settings", &json!({ "positionMode": "boundingBox" })).unwrap();
let task = session.bake_task_for(0, &[BakedMap::Id, BakedMap::Position]).unwrap();
let stored = session.baked(0).cloned().unwrap();
let finished = BakedMaps { resolution: stored.resolution, maps: [(BakedMap::Id, stored.maps[&BakedMap::Id].clone())].into() };
let kept = session.keep_canceled_bake(0, finished, &task.sources, task.painted_stroke).unwrap();
assert_eq!(kept, [BakedMap::Id]);
assert!(!session.bake_changes(0, BakedMap::Position).is_empty(), "Position still has its old pixels, so it stays out of date");
}
+4 -9
View File
@@ -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) });
}
+37 -11
View File
@@ -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();
}
+5
View File
@@ -12,4 +12,9 @@ pub struct RunningBake {
/// Maps finished so far, and how many the set makes.
pub maps_done: Arc<std::sync::atomic::AtomicUsize>,
pub maps_total: usize,
/// The maps received so far, kept when the bake is canceled even if the preview has closed
pub finished: texturecraft_engine::compose::BakedMaps,
/// What the task bakes from and the newest stroke it saw, recorded with the finished maps a cancel keeps
pub sources: std::collections::BTreeMap<texturecraft_engine::core::BakedMap, texturecraft_engine::core::BakeSource>,
pub painted_stroke: u64,
}
+6 -2
View File
@@ -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,
}),
});
+11
View File
@@ -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);
+12 -2
View File
@@ -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();
+30
View File
@@ -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();
+4 -3
View File
@@ -242,7 +242,7 @@ keeps its state in a throwaway file.
| `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before |
| `ui.reset` | | resets the panels, view settings and interface language without asking for confirmation. Other preferences and shortcuts stay |
| `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running |
| `ui.bake.cancel` | | Stops the running bake; the set being baked keeps the maps it had, sets already finished stay applied, and the previous view mode comes back |
| `ui.bake.cancel` | | Stops the running bake; 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.