diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ad50f615..ef7be82c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -611,8 +611,22 @@ fn export_textures(s: &mut Session, p: &Value) -> Result { let opts = export_options(s, p, "file.exportTextures")?; let sets = sets_param(s, p, "file.exportTextures")?; std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?; - let files = s.export_files(&sets, &opts)?; + let mut files = s.export_files(&sets, &opts)?; let mut warnings: Vec = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect(); + + // A file named like one an earlier texture set exports would replace it: it is not written. + // Case-insensitive, as Windows and macOS file systems are; one set's names never repeat. + let mut names = std::collections::HashSet::new(); + files.retain(|f| { + let unique = names.insert(f.name.to_ascii_lowercase()); + if !unique { + warnings.push(format!( + "\"{}\" has the name of a file an earlier texture set exports, so it was not written; add $textureSet to the template's file names or rename a texture set", + f.name + )); + } + unique + }); let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?; if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) { written.extend(write_materialx(s, &sets, &opts, std::path::Path::new(&dir), &mut warnings)?); diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index 25942b1b..dee174cb 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -43,3 +43,21 @@ fn a_map_index_outside_the_preset_is_refused() { assert!(e.to_string().contains("`map` must be the index"), "{e}"); assert!(execute(&mut s, "export.plan", &json!({"maps": [{"map": 0, "format": "nope"}]})).is_err()); } + +#[test] +fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { + let mut s = session(); + assert!(s.set_count() >= 2); + + // A template without $textureSet gives every set the same file name + let preset = json!({"name": "same", "maps": [{"file": "same", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]}); + let plan = execute(&mut s, "export.plan", &json!({"preset": preset, "ts": "all"})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), s.set_count(), "every set has roughness: {plan}"); + let dir = std::env::temp_dir().join(format!("tc_export_same_name_{}", std::process::id())); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "ts": "all"})).unwrap(); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect(); + assert_eq!(files.len(), 1, "only the first set's file is written: {r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert_eq!(warnings.iter().filter(|w| w.as_str().unwrap().contains("an earlier texture set exports")).count(), s.set_count() - 1, "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index a932662d..34882d40 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -913,13 +913,14 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !float && space == ColorSpace::Srgb).collect(); diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 998b318f..dac83fb8 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -927,6 +927,15 @@ fn pgm_is_a_binary_graymap() { let want = (linear_to_srgb(0.2126 * r + 0.7152 * g + 0.0722 * b) * 255.0).round(); assert!((f32::from(f.bytes[header.len() + 63]) - want).abs() <= 1.0, "{} vs {want}", f.bytes[header.len() + 63]); + // In another colour space the luminance is still that of the colour, not of its converted primaries + let opts = ExportOptions { color_space: Some(ColorSpace::AcesCg), ..one_map(FileFormat::Pgm, 16, rgba_half_alpha()) }; + let f = find(&fx.render(&opts), "out.pgm").bytes.clone(); + let header = b"P5\n64 64\n65535\n"; + let at = header.len() + 63 * 2; + let got = f32::from(u16::from_be_bytes([f[at], f[at + 1]])) / 65535.0; + let want = 0.2126 * r + 0.7152 * g + 0.0722 * b; + assert!((got - want).abs() < 1e-3, "ACEScg luminance {got} vs {want}"); + // Gray + alpha only loses the alpha let la = vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 }), (Dest::A, SourceRef::Constant(0.5))]; let f = &fx.render(&one_map(FileFormat::Pgm, 8, la))[0]; diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 5e9c9ca8..740d6c77 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -185,6 +185,7 @@ fn sync_draft(app: &mut TextureCraftApp) { Some(saved) => { if e.draft.as_ref().is_none_or(|d| d.name != saved.name || (d != saved && d.validate().is_ok())) { e.draft = Some(saved.clone()); + e.draft_maps = (0..saved.maps.len()).map(Some).collect(); } } } @@ -618,31 +619,55 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); ui.label(RichText::new(tr("Drag and drop maps on output's channels to setup your export.")).color(tk.text_dim)); - ui.label(trf("{n} output maps will be exported.", &[("n", &n)])); + // The maps the current texture set has sources for (no count when the plan fails) + if let Ok(names) = &preview { + let exported = names.iter().flatten().count(); + ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); + } if !editable { return; } + + // Where each map came from in the saved template, moved along with the maps + let mut origin = app.ui.export.draft_maps.clone(); + if origin.len() != n { + origin = (0..n).map(Some).collect(); + } match action { - Some(MapAction::Add(l)) => preset.maps.push(new_map(l)), - Some(MapAction::Up(i)) if i > 0 && i < n => preset.maps.swap(i, i - 1), - Some(MapAction::Down(i)) if i + 1 < n => preset.maps.swap(i, i + 1), + Some(MapAction::Add(l)) => { + preset.maps.push(new_map(l)); + origin.push(None); + } + Some(MapAction::Up(i)) if i > 0 && i < n => { + preset.maps.swap(i, i - 1); + origin.swap(i, i - 1); + } + Some(MapAction::Down(i)) if i + 1 < n => { + preset.maps.swap(i, i + 1); + origin.swap(i, i + 1); + } Some(MapAction::Remove(i)) if i < n => { preset.maps.remove(i); + origin.remove(i); } _ if !changed => return, _ => {} } - commit(app, preset); + commit(app, preset, origin); } -/// Keep the edited draft; save it when valid. -fn commit(app: &mut TextureCraftApp, preset: ExportPreset) { +/// Keep the edited draft; save it when valid. `origin` gives each map's index in the saved +/// template: once saved, the texture set overrides of the maps follow them. +fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec>) { if preset.validate().is_ok() && let Ok(v) = serde_json::to_value(&preset) + && app.run("export.preset.save", json!({ "preset": v })).is_some() { - app.run("export.preset.save", json!({ "preset": v })); + crate::export_window::template_maps_moved(&mut app.ui.export, &preset.name, &origin); + origin = (0..preset.maps.len()).map(Some).collect(); } app.ui.export.draft = Some(preset); + app.ui.export.draft_maps = origin; } /// The file each map produces for the current texture set with the dialog's settings (None: diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 83b25970..bb48db07 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -204,16 +204,57 @@ fn export_selection(app: &TextureCraftApp) -> Vec { } /// Start exporting the selected texture sets: the window shows LIST OF EXPORTS, the console and -/// a progress bar, and writes one texture set per frame. +/// a progress bar, and writes one texture set per frame. Each set's settings and the output +/// folder are taken now, so changing them while it runs does not change what it writes. #[cfg(not(target_arch = "wasm32"))] fn start_export(app: &mut TextureCraftApp) { - let pending = export_selection(app); + let selection = export_selection(app); + if selection.is_empty() { + return; + } + let dir = app.ui.export.dir.clone(); + let pending: Vec<(usize, serde_json::Value)> = selection + .into_iter() + .map(|ts| { + let mut p = set_params(app, ts); + p["dir"] = json!(dir); + (ts, p) + }) + .collect(); + let clash = name_clash(app, &pending); let e = &mut app.ui.export; e.tab = 2; e.console = vec![ConsoleLine::Step(tr("Preparing export...").into())]; + if let Some(error) = clash { + e.console.push(ConsoleLine::Step(error.clone())); + app.toast(error, true); + return; + } e.job = Some(crate::state::ExportJob { total: pending.len(), pending, written: Vec::new(), frame: 0 }); } +/// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS +/// do): the later one would replace the earlier one's file, so the export does not start. +#[cfg(not(target_arch = "wasm32"))] +fn name_clash(app: &mut TextureCraftApp, pending: &[(usize, serde_json::Value)]) -> Option { + let mut seen: std::collections::HashMap = std::collections::HashMap::new(); + for (ts, params) in pending { + // A plan that fails stops the export at that set with its own error + let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", params) else { continue }; + for file in plan.as_array().into_iter().flatten().filter_map(|f| f.get("file").and_then(serde_json::Value::as_str)) { + let first = *seen.entry(file.to_ascii_lowercase()).or_insert(*ts); + if first != *ts { + let name = |i: usize| app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); + return Some(trf( + "Texture sets {first} and {second} both export {file}: add $textureSet to the template's file names or rename a texture set", + &[("first", &name(first)), ("second", &name(*ts)), ("file", &file)], + )); + } + } + } + None +} + /// In the browser the textures download (one zip for several files). #[cfg(target_arch = "wasm32")] fn start_export(app: &mut TextureCraftApp) { @@ -242,12 +283,13 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { app.ui.export.job = None; return; } - let ts = job.pending.remove(0); + let (ts, mut p) = job.pending.remove(0); let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); let set = || ConsoleLine::Set(name.clone()); app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Computing textures results").into())]); - let mut p = set_params(app, ts); - p["dir"] = json!(app.ui.export.dir); + + // The settings taken at Export; the set's index may have moved since + p["ts"] = json!(ts); let Some(r) = app.run("file.exportTextures", p) else { app.ui.export.job = None; return; @@ -306,7 +348,8 @@ pub(crate) fn set_params(app: &TextureCraftApp, ts: usize) -> serde_json::Value if let Some(preset) = &o.preset { p["preset"] = json!(preset); } - if let Some(t) = &o.file_type { + // An empty file type keeps the template's + if let Some(t) = o.file_type.as_ref().filter(|t| !t.format.is_empty()) { p["format"] = json!(t.format); p["bitDepth"] = json!(t.bit_depth); p["dithering"] = json!(t.dithering); @@ -705,6 +748,16 @@ fn inherited(app: &TextureCraftApp, ts: usize) -> Inherited { Inherited { preset: e.preset.clone(), file_type: FileType { format, bit_depth, dithering }, size, padding: (e.padding.clone(), e.dilation) } } +/// The file type texture set `ts` gets from its output template: the one its maps share, or an +/// empty one when they differ (the override keeps the template's file types until one is picked) +fn template_file_type(app: &mut TextureCraftApp, ts: usize) -> FileType { + let rows = map_rows(app, ts); + match rows.split_first() { + Some((first, rest)) if rest.iter().all(|r| r.inherited == first.inherited) => first.inherited.clone(), + _ => FileType { format: String::new(), bit_depth: 0, dithering: false }, + } +} + /// Switch one override of `o` on (from what the set inherits) or off fn toggle(o: &mut SetExport, row: usize, from: &Inherited) { match row { @@ -722,7 +775,12 @@ fn file_type_combo(ui: &mut Ui, id: (&str, usize, usize), t: &mut FileType) { /// A texture set's page: its overrides of the global settings fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[ExportPreset]) { - let from = inherited(app, ts); + let mut from = inherited(app, ts); + + // "Based on output template": the override starts from what the template writes + if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|o| o.file_type.is_none()) { + from.file_type = template_file_type(app, ts); + } let own = app.session.doc.project.texture_sets.get(ts).map_or(1024, |t| t.resolution); let (first, rest) = template_groups(app, builtins); let first: Vec<(&str, bool)> = first.into_iter().filter(|(n, _)| !NOT_PER_SET.contains(n)).collect(); @@ -929,7 +987,8 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { } /// Keep the texture set ticks and overrides with their texture sets: dropped for another project, -/// moved with a texture set by name, dropped with a removed one +/// moved with a texture set by name, dropped with a removed one. A running export follows its +/// texture sets the same way; another project stops it. fn follow_texture_sets(app: &mut TextureCraftApp) { let project = &app.session.doc.project; let mut owner = vec![project.name.clone()]; @@ -939,6 +998,14 @@ fn follow_texture_sets(app: &mut TextureCraftApp) { if e.owner == owner && e.owner_id == Some(id) { return; } + + // Settings saved before they named their project keep their ticks and overrides (when the + // window opens; Reset all keeps the owner) + if e.owner.is_empty() && e.opened_with.is_none() { + e.owner = owner; + e.owner_id = Some(id); + return; + } let same_project = match e.owner_id { Some(was) => was == id, None => e.owner.first() == owner.first(), @@ -954,6 +1021,15 @@ fn follow_texture_sets(app: &mut TextureCraftApp) { follow(e); if let Some(before) = e.opened_with.as_deref_mut() { follow(before); + (before.owner, before.owner_id) = (owner.clone(), Some(id)); + } + if let Some(job) = e.job.as_mut() { + if same_project { + job.pending = std::mem::take(&mut job.pending).into_iter().filter_map(|(i, p)| moved(i).map(|j| (j, p))).collect(); + } else { + e.job = None; + e.console.push(ConsoleLine::Step(tr("Export stopped: another project was opened").into())); + } } e.owner = owner; e.owner_id = Some(id); @@ -1000,6 +1076,22 @@ pub(crate) fn template_renamed(e: &mut ExportUi, old: &str, new: Option<&str>) { } } +/// The maps of template `template` were saved in a new order: `origin` gives each map's index +/// before. The texture set overrides of its maps follow them (removed maps lose theirs), in the +/// settings the window opened with too. +pub(crate) fn template_maps_moved(e: &mut ExportUi, template: &str, origin: &[Option]) { + let follow = |e: &mut ExportUi| { + for o in e.sets.values_mut().filter(|o| o.maps_template == template) { + o.maps = std::mem::take(&mut o.maps).into_iter().filter_map(|(i, m)| origin.iter().position(|x| *x == Some(i)).map(|j| (j, m))).collect(); + } + e.sets.retain(|_, o| !o.is_default()); + }; + follow(e); + if let Some(before) = e.opened_with.as_deref_mut() { + follow(before); + } +} + /// Go back to the settings the window opened with fn cancel(app: &mut TextureCraftApp) { if let Some(before) = app.ui.export.opened_with.take() { @@ -1133,11 +1225,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { - let opened_with = app.ui.export.opened_with.take(); - app.ui.export = ExportUi { opened_with, ..ExportUi::default() }; + // The settings stay the project's: its ticks and overrides in `opened_with` stay too + let e = &mut app.ui.export; + let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { + // Nothing to write without a ticked texture set + let any = !export_selection(app).is_empty(); + if ui.add_enabled(any, primary_button(ui, tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } @@ -1154,6 +1250,13 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); crate::export_templates::ask(app, ctx); + // Closing the window is Cancel; it stops an export before it writes another texture set + if canceled || !open { + app.ui.export.job = None; + cancel(app); + return; + } + // One texture set per frame, after the window showed the state before it if app.ui.export.job.is_some() && !do_export { export_step(app, ctx.cumulative_frame_nr()); @@ -1166,9 +1269,4 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } ctx.request_repaint(); } - - // Closing the window is Cancel - if canceled || !open { - cancel(app); - } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7a377645..f5a63a72 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -379,7 +379,9 @@ impl SetExport { /// A running texture export: the texture sets still to write, one per frame. #[derive(Clone, Debug, Default, PartialEq)] pub struct ExportJob { - pub pending: Vec, + /// Each texture set still to write with its `file.exportTextures` parameters (output folder + /// included), taken when Export was clicked: later edits of the settings do not reach them. + pub pending: Vec<(usize, serde_json::Value)>, pub total: usize, /// File names written so far. pub written: Vec, @@ -441,6 +443,10 @@ pub struct ExportUi { /// Output templates tab: the selected user preset being edited (saved whenever it is valid). #[serde(skip)] pub draft: Option, + /// Output templates tab: for each map of `draft`, its index in the saved template (None: added + /// since), so the texture set overrides of a map follow it when the draft is saved. + #[serde(skip)] + pub draft_maps: Vec>, /// Output templates tab: the new name while renaming the selected preset. #[serde(skip)] pub renaming: Option, @@ -483,6 +489,7 @@ impl Default for ExportUi { tab: 0, page: None, draft: None, + draft_maps: Vec::new(), renaming: None, rename_key: false, ask: None, diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 62e6d137..f1394908 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -4,7 +4,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::SetExport; +use texturecraft_ui_egui::state::{ConsoleLine, FileType, SetExport}; /// The Export textures window open on the first texture set's page fn harness() -> Harness<'static, TextureCraftApp> { @@ -98,7 +98,8 @@ fn the_header_menu_switches_every_override() { click(&mut h, "Enable override for all items"); let o = overrides(&h); assert!(o.preset.is_some() && o.file_type.is_some() && o.size.is_some() && o.padding.is_some(), "{o:?}"); - assert_eq!(o.file_type.unwrap().format, "png"); + // The default template writes 8- and 16-bit files: the override keeps them until a type is picked + assert_eq!(o.file_type.unwrap().format, ""); page_menu(&mut h); click(&mut h, "Disable override for all items"); assert!(h.state().ui.export.sets.is_empty()); @@ -132,6 +133,8 @@ fn export_writes_each_set_with_its_overrides_and_cancel_drops_them() { h.run_steps(1); } h.run_steps(2); + let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Export successfully finished")); + assert!(h.state().ui.export.job.is_none() && finished, "the export finished"); let sets: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| format!("_{}_", t.name)).collect(); let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "png")).collect(); let of = |set: &str| files.iter().filter(|f| f.file_name().unwrap().to_string_lossy().contains(set)).collect::>(); @@ -142,6 +145,7 @@ fn export_writes_each_set_with_its_overrides_and_cancel_drops_them() { // The other sets keep their own size for set in &sets[1..] { + assert!(!of(set).is_empty(), "{set} was written"); for f in of(set) { assert_eq!(png_width(f), 256, "{}", f.display()); } @@ -184,3 +188,73 @@ fn overrides_stay_with_their_texture_set_and_their_project() { h.run_steps(4); assert!(h.state().ui.export.sets.is_empty() && h.state().ui.export.skip.is_empty()); } + +#[test] +fn a_file_type_override_starts_from_the_type_of_the_template() { + let mut h = harness(); + let library = folder("library"); + std::fs::create_dir_all(&library).unwrap(); + h.state_mut().session.load_export_presets(library.clone()); + let maps = serde_json::json!([{"file": "$textureSet_rough", "format": "Exr", "bit_depth": 32, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]); + h.state_mut().run("export.preset.save", serde_json::json!({"preset": {"name": "One EXR", "maps": maps}})).unwrap(); + h.state_mut().ui.export.preset = "One EXR".into(); + h.run_steps(4); + assert!(h.state().ui.export.format.is_empty(), "Based on output template"); + toggle(&mut h, 1); + assert_eq!(overrides(&h).file_type, Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), "not png"); + let _ = std::fs::remove_dir_all(&library); +} + +#[test] +fn cancel_keeps_each_tick_with_its_texture_set_after_they_trade_names() { + let mut h = harness(); + let names: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect(); + h.state_mut().ui.export.skip = vec![1]; + click(&mut h, "Save settings"); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + + // While the window is open the two texture sets trade names: the tick follows the name + for (ts, name) in [(0, "swap"), (1, names[0].as_str()), (0, names[1].as_str())] { + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &serde_json::json!({"ts": ts, "name": name})).unwrap(); + } + h.run_steps(4); + assert_eq!(h.state().ui.export.skip, vec![0]); + click(&mut h, "Cancel"); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + assert_eq!(h.state().ui.export.skip, vec![0], "Cancel and reopening keep the tick off the set named {}", names[1]); +} + +#[test] +fn reset_all_then_cancel_restores_the_ticks_and_overrides() { + let mut h = harness(); + let e = &mut h.state_mut().ui.export; + e.skip = vec![1]; + e.sets.insert(1, SetExport { size: Some(128), ..SetExport::default() }); + click(&mut h, "Save settings"); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + click(&mut h, "Reset all"); + assert!(h.state().ui.export.skip.is_empty() && h.state().ui.export.sets.is_empty(), "Reset all clears them"); + click(&mut h, "Cancel"); + assert_eq!(h.state().ui.export.skip, vec![1]); + assert_eq!(h.state().ui.export.sets.get(&1).and_then(|o| o.size), Some(128), "Cancel brings the override back"); +} + +#[test] +fn ticks_saved_before_settings_named_their_project_are_kept() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + // Older settings: a tick off, no owner + let e = &mut h.state_mut().ui.export; + (e.skip, e.owner, e.owner_id) = (vec![1], Vec::new(), None); + e.sets.insert(1, SetExport { size: Some(128), ..SetExport::default() }); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + assert_eq!(h.state().ui.export.skip, vec![1]); + assert_eq!(h.state().ui.export.sets.get(&1).and_then(|o| o.size), Some(128)); +} diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 23201f8f..f620c767 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -3,6 +3,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; +use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{ConsoleLine, ExportJob}; @@ -72,16 +73,36 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { let _ = std::fs::remove_dir_all(&dir); } -#[test] -fn cancel_export_stops_the_export() { - let (mut h, dir) = harness("cancel"); - - // A long export: the texture sets several times over +/// A long export: the texture sets several times over, into `dir` +fn long_export(h: &mut Harness<'_, TextureCraftApp>, dir: &std::path::Path) { let sets: Vec = (0..h.state().session.set_count()).collect(); - let pending: Vec = sets.iter().copied().cycle().take(sets.len() * 8).collect(); + let params = json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = sets.iter().copied().cycle().take(sets.len() * 8).map(|ts| (ts, params.clone())).collect(); let e = &mut h.state_mut().ui.export; e.tab = 2; e.job = Some(ExportJob { total: pending.len(), pending, ..ExportJob::default() }); +} + +/// How many texture sets the session wrote so far +fn exports(h: &Harness<'_, TextureCraftApp>) -> usize { + h.state().session.log.iter().filter(|l| l.starts_with("Exported ")).count() +} + +/// Run frames until the export ends (or a bound) +fn finish(h: &mut Harness<'_, TextureCraftApp>) { + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + h.run_steps(1); + } + h.run_steps(2); +} + +#[test] +fn cancel_export_stops_the_export() { + let (mut h, dir) = harness("cancel"); + long_export(&mut h, &dir); h.run_steps(2); assert!(h.query_by_label("Cancel Export").is_some()); assert!(h.query_all_by_label_contains("%").next().is_some(), "the bar shows the percent"); @@ -139,3 +160,95 @@ fn open_output_directory_asks_the_system_to_show_the_folder() { assert!(dir.is_dir(), "a missing folder is created first"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn the_settings_at_export_are_kept_while_it_runs() { + let (mut h, dir) = harness("frozen"); + let moved = dir.with_extension("moved"); + let _ = std::fs::remove_dir_all(&moved); + click(&mut h, "Export"); + h.run_steps(1); + assert!(h.state().ui.export.job.is_some()); + + // Another folder and size chosen while it runs reach none of the files + h.state_mut().ui.export.dir = moved.display().to_string(); + h.state_mut().ui.export.size = 128; + finish(&mut h); + assert!(!moved.exists(), "nothing was written to the folder chosen later"); + let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect(); + let sets = h.state().session.set_count(); + assert_eq!(exports(&h), sets, "every texture set was written"); + for f in written.iter().filter(|p| p.extension().is_some_and(|e| e == "png")) { + let width = u32::from_be_bytes(std::fs::read(f).unwrap()[16..20].try_into().unwrap()); + assert_eq!(width, 256, "{} keeps the size of the start", f.display()); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { + let (mut h, dir) = harness("clash"); + + // A template without $textureSet gives every set the same file name (kept in a scratch library) + let library = dir.with_extension("library"); + let _ = std::fs::remove_dir_all(&library); + std::fs::create_dir_all(&library).unwrap(); + h.state_mut().session.load_export_presets(library.clone()); + let maps = json!([{"file": "same", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]); + h.state_mut().run("export.preset.save", json!({"preset": {"name": "Same", "maps": maps}})).unwrap(); + h.state_mut().ui.export.preset = "Same".into(); + h.run_steps(4); + click(&mut h, "Export"); + h.run_steps(2); + assert!(h.state().ui.export.job.is_none(), "no export runs"); + assert_eq!(exports(&h), 0); + assert!(!dir.join("same.png").exists()); + assert!(console(&h).iter().any(|l| l.contains("both export same.png")), "{:?}", console(&h)); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&library); +} + +#[test] +fn opening_another_project_stops_the_export() { + let (mut h, dir) = harness("project"); + long_export(&mut h, &dir); + h.run_steps(2); + let before = exports(&h); + assert!(before > 0 && h.state().ui.export.job.is_some()); + + h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + h.run_steps(4); + assert!(h.state().ui.export.job.is_none()); + assert_eq!(exports(&h), 0, "the new project exported nothing"); + assert!(console(&h).iter().any(|l| l == "Export stopped: another project was opened"), "{:?}", console(&h)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn export_is_disabled_without_a_ticked_texture_set() { + let (mut h, dir) = harness("none"); + let sets = h.state().session.set_count(); + h.state_mut().ui.export.skip = (0..sets).collect(); + h.run_steps(2); + click(&mut h, "Export"); + h.run_steps(2); + let e = &h.state().ui.export; + assert!(e.job.is_none() && e.console.is_empty() && e.tab == 0, "Export did nothing"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn closing_the_window_writes_no_further_texture_set() { + let (mut h, dir) = harness("close"); + long_export(&mut h, &dir); + h.run_steps(2); + let before = exports(&h); + assert!(h.state().ui.export.job.is_some()); + h.get_by_role_and_label(egui::Role::Button, "Close window").click(); + h.run_steps(1); + assert!(!h.state().ui.windows.export); + h.run_steps(2); + assert_eq!(exports(&h), before, "the frame that closed the window wrote nothing"); + assert!(h.state().ui.export.job.is_none()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 906bc7ff..44402f4b 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{MapExport, SetExport}; /// A user template library folder removed with its owner struct Library(std::path::PathBuf); @@ -62,7 +63,10 @@ fn the_tab_has_the_reference_layout_and_texts() { } assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); let maps = h.state().session.export_preset("Mine").unwrap().maps.len(); - assert!(h.query_by_label(&format!("{maps} output maps will be exported.")).is_some()); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); + let exported = plan.as_array().unwrap().len(); + assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some()); for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] { assert!(h.query_by_label(create).is_some(), "{create}"); } @@ -193,3 +197,41 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { click(&mut h, "Cancel"); assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine"))); } + +#[test] +fn the_footer_counts_only_the_maps_the_texture_set_exports() { + let library = Library::new("count"); + let mut h = harness(&library); + + // Two maps; the texture set has no sheen, so only roughness is written + let channel = |c: &str| json!([["L", {"Channel": {"channel": c}}]]); + let maps = json!([ + {"file": "$textureSet_rough", "format": "Png", "bit_depth": 8, "channels": channel("Roughness")}, + {"file": "$textureSet_sheen", "format": "Png", "bit_depth": 8, "channels": channel("SheenWeight")}, + ]); + h.state_mut().run("export.preset.save", json!({"preset": {"name": "Mine", "maps": maps}})).unwrap(); + h.run_steps(4); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); + assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen card says so"); + assert!(h.query_by_label("1 output maps will be exported.").is_some()); + assert!(h.query_by_label("2 output maps will be exported.").is_none()); +} + +#[test] +fn per_map_settings_follow_their_map_when_the_template_reorders_it() { + let library = Library::new("reorder"); + let mut h = harness(&library); + + // The first texture set leaves out the template's first map + let off = MapExport { enabled: false, file_type: None }; + h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); + h.run_steps(2); + let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); + h.get_all_by_label("Move down").next().unwrap().click(); + h.run_steps(4); + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[1].file, first, "the map moved down"); + let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); + assert_eq!(maps, [(1, off)].into(), "the setting moved with its map"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2ebc0786..3cad06aa 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -43,7 +43,9 @@ grayscale image (the whole tile atlas for a UV-tiled set). `file.exportTextures` and `export.plan` take `maps: [{map, enabled?, format?, bitDepth?}]`: per map of the template (`map` is its index in the template's maps) its own file type and bit depth, which win over the export's `format` and `bitDepth`, or `enabled: false` to leave it out. A -left-out map keeps its file name reserved, so the other maps keep theirs. The Export textures +left-out map keeps its file name reserved, so the other maps keep theirs. A file of +`file.exportTextures` named like one an earlier texture set of the same call exports (ignoring +case) is not written, with a warning, instead of replacing it. The Export textures window's Output maps rows send it. `format` takes the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `webp`, `psd`) or the extensions; `bitDepth` 32 is float for TIFF, EXR and HDR. `dithering: true` (also per map) dithers 8-bit integer files with diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9d7f1fe0..447e004e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -242,7 +242,10 @@ Free rotation uses the same Alt+left drag (and right drag) as the constrained on tree per texture set (file, size such as "1024x1024 (Texture Set size)", file type, bit depth; the full path as tooltip) with *Open output directory* at the top right. The files are written when a texture set is done, so its "Writing ..." lines follow its work instead of - coming one by one. + coming one by one. Each set's settings and the output directory are taken when Export is + clicked; Export is greyed with no texture set ticked. Two texture sets that would write a file + of the same name stop the export before it writes anything (the console and a message say + which); closing the window or opening another project stops it. - **OUTPUT TEMPLATES** ([#674](https://github.com/storytold/texturecraft/issues/674)): the left list is titled *Presets* and lists the templates sorted by name, without the template list's first group. A right click on a preset offers *Rename*, *Duplicate* and *Remove* (Rename and