From 0203f23ee097e9b6b1615dadfc0c6f49516541fc Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:00:04 +0100 Subject: [PATCH 01/20] Export UI parity: drop SEND TO from the Export dock, restore the reference texts, 1100x740 window The Export dock shows EXPORT only. The export window, its console lines, tooltips and the Output templates texts read as in the reference again, and the window has the reference size. --- crates/ui-egui/src/export_panel.rs | 37 +--------- crates/ui-egui/src/export_templates.rs | 6 +- crates/ui-egui/src/export_window.rs | 52 +++++++------- .../ui-egui/tests/it/export_map_overrides.rs | 4 +- crates/ui-egui/tests/it/export_materialx.rs | 2 +- crates/ui-egui/tests/it/export_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 18 ++--- .../tests/it/export_reference_texts.rs | 69 +++++++++++++++++++ crates/ui-egui/tests/it/export_settings.rs | 4 +- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/output_templates.rs | 6 +- crates/ui-egui/tests/it/side_panels.rs | 8 ++- docs/ui-parity.md | 18 ++--- 13 files changed, 136 insertions(+), 95 deletions(-) create mode 100644 crates/ui-egui/tests/it/export_reference_texts.rs diff --git a/crates/ui-egui/src/export_panel.rs b/crates/ui-egui/src/export_panel.rs index a9f63f17..13dc88a7 100644 --- a/crates/ui-egui/src/export_panel.rs +++ b/crates/ui-egui/src/export_panel.rs @@ -1,48 +1,17 @@ -//! The Export panel on the rail: where to send the project, then Export Mesh and Export Textures +//! The Export panel on the rail: Export Mesh and Export Textures -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; +use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; -use crate::theme::{Tokens, caption}; -use crate::unavailable; +use crate::theme::caption; use crate::widgets::primary_button; -/// The SEND TO rows: none has a counterpart in TextureCraft yet -pub const SEND_TO: [&str; 3] = ["Export to image editor", "Send to compositing app", "Send to 3D staging app"]; - /// Width of the Export Mesh and Export Textures buttons const EXPORT_BUTTON_WIDTH: f32 = 176.0; -/// Size of the Configure button beside a SEND TO row -const CONFIGURE_SIZE: f32 = 20.0; - -/// Space between the SEND TO and EXPORT parts -const PART_GAP: f32 = 12.0; - /// The Export panel body (a rail popup or dock tab); its buttons need an open project pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - ui.label(caption(&tr("Send to").to_uppercase())); - for (index, target) in SEND_TO.into_iter().enumerate() { - ui.horizontal(|ui| { - unavailable::greyed(ui, |ui| ui.add(egui::Button::new(tr(target)).frame(false))); - - // The reference's second row has a Configure button - if index == 1 { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - unavailable::greyed(ui, |ui| { - ui.add( - egui::Button::new(RichText::new(ic::GEAR).color(tokens.text_dim)).frame(false).min_size(egui::vec2(CONFIGURE_SIZE, CONFIGURE_SIZE)), - ) - }); - }); - } - }); - } - - ui.add_space(PART_GAP); ui.label(caption(&tr("Export").to_uppercase())); let project_open = app.session.project_open; ui.vertical_centered(|ui| { diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index c1c0eddc..f6fb56df 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -273,8 +273,8 @@ fn naming_pattern(ui: &mut Ui) { } }); ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Choose how the input maps are named in this editor.")); - ui.label(tr("The active texture set’s shader can affect the available map names.")); + ui.label(tr("Select the naming pattern used to display the input maps on this page.")); + ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); }); } @@ -641,7 +641,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); + ui.label(RichText::new(tr("Drag and drop maps on output's channels to setup your export.")).color(tokens.text_dim)); // Count only maps that have sources in the current set if let Ok(names) = &preview { diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3aee5ed8..ba01ae14 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -22,7 +22,7 @@ use inherited_settings::InheritedSettings; use map_row::MapRow; /// Height of the window's tab body, above its buttons -const BODY_HEIGHT: f32 = 440.0; +const BODY_HEIGHT: f32 = 660.0; /// Width of the texture set list const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; @@ -177,7 +177,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b ui.add_enabled(false, egui::Button::selectable(false, *name)).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); + ui.separator().on_hover_text(tr("This preset is not available for the current project")); for name in rest { changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); } @@ -241,7 +241,7 @@ fn start_export(app: &mut TextureCraftApp) { let e = &mut app.ui.export; e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; + e.console = vec![ConsoleLine::Step(tr("Preparing export...").into())]; if let Some(error) = error { e.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); @@ -299,14 +299,14 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { if job.pending.is_empty() { let written = std::mem::take(&mut job.written); let console = &mut app.ui.export.console; - console.push(ConsoleLine::Step(tr("All selected texture sets processed").into())); + console.push(ConsoleLine::Step(tr("Bitmaps write finalization...").into())); if written.is_empty() { console.push(ConsoleLine::Step(tr("No files were written").into())); } else { console.extend([ - ConsoleLine::Step(tr("Collecting the exported files").into()), - ConsoleLine::Done(tr("Texture export complete").into()), - ConsoleLine::Done(tr("Files saved").into()), + ConsoleLine::Step(tr("Finalizing export...").into()), + ConsoleLine::Done(tr("Export successfully finished").into()), + ConsoleLine::Done(tr("Successfully exported:").into()), ]); console.extend(written.into_iter().map(ConsoleLine::Done)); } @@ -332,7 +332,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } let set = || ConsoleLine::Set(name.clone()); - app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); + app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Computing textures results").into())]); // Protect concrete files and UDIM references from earlier texture sets if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { @@ -347,11 +347,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; for file in &files { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); - lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); + lines.push(ConsoleLine::Step(trf("Writing {file} texture on disk", &[("file", &stem)]))); } // The export's warnings go to the console and the log, each once per export @@ -368,7 +368,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); } - lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); + lines.extend([set(), ConsoleLine::Step(tr("Finalizing textures writing").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { job.written.extend(files); @@ -526,7 +526,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { } } ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + for (i, label) in [tr("Enable override for all items"), tr("Disable override for all items")].into_iter().enumerate() { if ui.button(label).clicked() { menu = Some(3 + i); } @@ -644,7 +644,7 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); + r.response.on_disabled_hover_text(tr("Dilation cannot be applied to selected padding type")); } } @@ -661,7 +661,7 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { let mut reset = false; header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); + reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Resets all settings to default values"), false, ICON).clicked(); }); if reset { let defaults = ExportUi::default(); @@ -732,8 +732,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] }); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); // The browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -874,10 +874,10 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor let mut all = None; header(ui, tr("General Export Parameters"), |ui| { list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { + if ui.button(tr("Enable override for all items")).clicked() { all = Some(true); } - if ui.button(tr("Clear all overrides")).clicked() { + if ui.button(tr("Disable override for all items")).clicked() { all = Some(false); } ui.separator(); @@ -1005,9 +1005,9 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// "Texture set " with the name in bold +/// "Exporting texture set ..." with the name in bold fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { - let text = tr("Texture set {set}"); + let text = tr("Exporting texture set {set}..."); let (before, after) = text.split_once("{set}").unwrap_or((text, "")); let font = egui::TextStyle::Body.resolve(ui.style()); let plain = egui::TextFormat::simple(font.clone(), tk.text); @@ -1266,7 +1266,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(900.0, 520.0)).show(ctx, |ui| { + crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(1100.0, 740.0)).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); @@ -1290,7 +1290,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.button(tr("Open output directory")).clicked() { open_output_directory(app); } - } else if ui.button(tr("Include all")).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); @@ -1346,7 +1346,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let selected = selected_texture_count(app); ui.horizontal(|ui| { // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 && ui.button(tr("Reset all")).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { + 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() { // Keep ownership so Cancel can restore the opening settings 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); @@ -1355,15 +1355,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // 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("Write the selected textures using the settings above")).clicked() { + 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; } // Saving closes the window without starting an export - if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() { + if ui.button(tr("Save settings")).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } - if ui.button(tr("Cancel")).on_hover_text(tr("Restore the settings from when you opened this window")).clicked() { + if ui.button(tr("Cancel")).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } ui.label(trf("{n} textures selected for export", &[("n", &selected)])); diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 77d67503..8e627895 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -104,10 +104,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Override every item"); + click(&mut h, "Enable override for all items"); assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Clear all overrides"); + click(&mut h, "Disable override for all items"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 9a26f2be..b90d785e 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -161,7 +161,7 @@ fn restoring_the_default_parameters_unticks_export_materialx() { app_harness.run_steps(3); assert!(app_harness.state().ui.export.materialx); - app_harness.get_by_label("Restore the default export parameters").click(); + app_harness.get_by_label("Resets all settings to default values").click(); app_harness.run_steps(3); assert!(!app_harness.state().ui.export.materialx); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 9edb2ee5..2ca24b0d 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -117,14 +117,14 @@ fn the_header_menu_switches_every_override() { // The set list has the same menu button; the page header's is the second page_menu(&mut h); - click(&mut h, "Override every item"); + 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:?}"); // 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, "Clear all overrides"); + click(&mut h, "Disable override for all items"); assert!(h.state().ui.export.sets.is_empty()); } @@ -157,7 +157,7 @@ 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 == "Texture export complete")); + 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(); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 84015102..46cee48f 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -34,7 +34,7 @@ fn console(h: &Harness<'_, TextureCraftApp>) -> Vec { .iter() .map(|l| match l { ConsoleLine::Step(t) | ConsoleLine::Done(t) => t.clone(), - ConsoleLine::Set(name) => format!("Texture set {name}"), + ConsoleLine::Set(name) => format!("Exporting texture set {name}..."), }) .collect() } @@ -48,7 +48,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); - assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); + assert_eq!(console(&h).first().map(String::as_str), Some("Preparing export...")); for _ in 0..64 { if h.state().ui.export.job.is_none() { @@ -61,14 +61,14 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); - let set = format!("Texture set {}", sets[0]); + let set = format!("Exporting texture set {}...", sets[0]); let start = lines.iter().position(|l| *l == set).unwrap(); - assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Rendering the selected maps".into(), set.clone(), "Saving texture files".into()]); - assert!(lines[start + 6].starts_with("Saved texture "), "{lines:?}"); + assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Computing textures results".into(), set.clone(), "Preparing textures writing".into()]); + assert!(lines[start + 6].starts_with("Writing ") && lines[start + 6].ends_with(" texture on disk"), "{lines:?}"); let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); - let finished = lines.iter().position(|l| l == "Texture export complete").unwrap(); - assert_eq!(&lines[finished - 3..finished], ["Finished writing this texture set", "All selected texture sets processed", "Collecting the exported files"]); - assert_eq!(lines[finished + 1], "Files saved"); + let finished = lines.iter().position(|l| l == "Export successfully finished").unwrap(); + assert_eq!(&lines[finished - 3..finished], ["Finalizing textures writing", "Bitmaps write finalization...", "Finalizing export..."]); + assert_eq!(lines[finished + 1], "Successfully exported:"); assert_eq!(lines.len() - finished - 2, written.len(), "every written file is listed"); assert!(matches!(h.state().ui.export.console.last(), Some(ConsoleLine::Done(_))), "in green"); let _ = std::fs::remove_dir_all(&dir); @@ -113,7 +113,7 @@ fn cancel_export_stops_the_export() { assert!(h.state().ui.export.job.is_none()); assert!(h.state().ui.windows.export); let lines = console(&h); - assert!(!lines.iter().any(|l| l == "Collecting the exported files" || l == "Texture export complete"), "the export did not finish: {lines:?}"); + assert!(!lines.iter().any(|l| l == "Finalizing export..." || l == "Export successfully finished"), "the export did not finish: {lines:?}"); assert!(h.query_by_label("Cancel").is_some(), "the buttons are back"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs new file mode 100644 index 00000000..39d9b959 --- /dev/null +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -0,0 +1,69 @@ +//! Export textures window (texturecraft #789): the reference's size, tab labels, button tooltips +//! and settings texts, word for word. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +/// The Export textures window open on SETTINGS +fn harness() -> Harness<'static, TextureCraftApp> { + 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); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + h +} + +/// Hover the newest node labelled `label` until its tooltip shows +fn hover(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let center = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); + h.hover_at(center); + h.run_steps(30); +} + +/// Hover `label` and check that its tooltip says `tooltip` +fn tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { + hover(h, label); + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); +} + +#[test] +fn the_window_is_as_wide_as_the_reference_window() { + let h = harness(); + let reset = h.get_by_label("Reset all").rect(); + let save = h.get_by_label("Save settings").rect(); + + // The reference window is 1100 wide; the buttons sit at its two ends (it was 900 wide) + assert!(save.max.x - reset.min.x > 900.0, "{reset:?} {save:?}"); +} + +#[test] +fn the_tabs_read_in_capitals() { + let h = harness(); + for tab in ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS"] { + assert!(h.query_by_label(tab).is_some(), "{tab}"); + } +} + +#[test] +fn the_buttons_carry_the_reference_tooltips() { + let mut h = harness(); + tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); + tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); + tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); + tooltip_is(&mut h, "Save settings", "Closes the export window and saves changes"); + tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); +} + +#[test] +fn the_unavailable_checkboxes_carry_the_reference_texts() { + let mut h = harness(); + tooltip_is( + &mut h, + "Export USD asset", + "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", + ); + tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); +} diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 98af3660..afabdee1 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -143,7 +143,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); - assert!(h.query_by_label("This padding mode does not use a dilation width").is_some()); + assert!(h.query_by_label("Dilation cannot be applied to selected padding type").is_some()); h.state_mut().ui.export.padding = "dilation".into(); h.run_steps(3); hover(&mut h, "16"); @@ -166,7 +166,7 @@ fn the_page_reset_puts_the_parameters_back() { e.padding = "none".into(); e.skip = vec![0]; h.run_steps(3); - click(&mut h, "Restore the default export parameters"); + click(&mut h, "Resets all settings to default values"); let e = &h.state().ui.export; assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index d9ed98f0..a4bbd233 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -25,6 +25,7 @@ mod export_map_overrides; mod export_materialx; mod export_overrides; mod export_progress; +mod export_reference_texts; mod export_settings; mod export_template_guards; mod file_dialogs; diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index aaf66fce..bb9c5d5e 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -45,7 +45,7 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drag and drop maps on output's channels to setup your export."] { assert!(h.query_by_label(text).is_some(), "{text}"); } assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); @@ -63,8 +63,8 @@ fn the_tab_shows_the_preset_tools_and_map_editor() { let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); - assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); - assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); + assert!(h.query_by_label("Select the naming pattern used to display the input maps on this page.").is_some()); + assert!(h.query_by_label("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.").is_some()); } #[test] diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index d05f19a1..052068a6 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -101,10 +101,12 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert_eq!(harness.state().ui.rail_panel, Some(Panel::Export)); assert!(!harness.state().ui.windows.export, "the rail opens the Export panel, not a window"); - for label in ["SEND TO", "EXPORT", "Export to image editor", "Send to compositing app", "Send to 3D staging app"] { - assert!(harness.query_all_by_label(label).next().is_some(), "{label}"); + assert!(harness.query_all_by_label("EXPORT").next().is_some(), "the EXPORT caption"); + for label in ["SEND TO", "Export to image editor", "Send to compositing app", "Send to 3D staging app"] { + assert!(harness.query_all_by_label(label).next().is_none(), "the dock has no {label} row"); } - assert!(says_not_available(&mut harness, "Send to compositing app")); + assert!(harness.query_all_by_label_contains("Send to").next().is_none(), "no SEND TO text at all"); + button_left_of_rail(&harness, "Export Mesh..."); button_left_of_rail(&harness, "Export Textures...").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b8e6d060..8c392573 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -63,9 +63,8 @@ when it is not docked). Each opens a popup beside the bar with its title in capi button that turns it into a floating window, and *Close*. A floating rail panel has a *Dock* button that closes it back onto the bar; the float is saved with the UI state. -- **Export:** SEND TO lists three targets and a Configure button, all greyed with "Not available - yet". The reference names other products there; TextureCraft says *Export to image editor*, - *Send to compositing app* and *Send to 3D staging app*. EXPORT has *Export Mesh...* (the +- **Export:** the dock shows EXPORT only (the reference's SEND TO part has no counterpart here and + is left out, [#789](https://github.com/storytold/texturecraft/issues/789)). EXPORT has *Export Mesh...* (the *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected @@ -280,24 +279,25 @@ that numbers hide once a tile is under 40 points on screen. - **SETTINGS** ([#671](https://github.com/storytold/texturecraft/issues/671)): the texture set list has the reference's menu (*Check all*, *Uncheck all*, *Invert all*); *General Export - Parameters* has its reset button ("Restore the default export parameters"). *Output directory* + Parameters* has its reset button ("Resets all settings to default values"). *Output directory* is a button showing the path (it opens the folder picker) with an *R* button ("Reset to default"). The template list starts with the reference's first group (TextureCraft has "Document channels + Normal + AO (No Alpha)", the new name of its default template, and "glTF PBR Metal Roughness"; the others are greyed with "Not available yet"; one entry names another - vendor's product and is left out), then a separator ("Some templates in this list are unavailable") and every other template sorted by name. File type lists "Based on output + vendor's product and is left out), then a separator ("This preset is not available for the current project") and every other template sorted by name. File type lists "Based on output template", then the types in the reference order and names ("targa", "jpeg", "tiff"). Size adds "Maximum size for all Texture Sets" and 128. Padding uses the reference order; the dilation width is a button with a "Dilation (pixels)" slider, greyed for paddings without a - width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry - tooltips explaining which settings are applied, kept or restored. + width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry the + reference's tooltips word for word. The window is 1100 x 740 as in the reference + ([#789](https://github.com/storytold/texturecraft/issues/789)). Cancel, and closing the window, go back to the settings the window opened with; the window always opens on SETTINGS. - **Texture set pages** ([#669](https://github.com/storytold/texturecraft/issues/669)): a click on a texture set row shows its *General Export Parameters*: Output template, File type, Size and Padding with the inherited value as text (for example "1024x1024 (Texture Set size)"). The pencil button ("Enable override") turns a row into its list; a set with an override gets "*" - ("Override(s) active"). The header menu has *Override every item* and *Disable + ("Override(s) active"). The header menu has *Enable override for all items* and *Disable override for all items*. The template list leaves out the entries the reference leaves out there; sizes read "128x128" ... "8192x8192". Export, the footer count and LIST OF EXPORTS use each set's own settings. Ticks and overrides belong to the project and follow each texture set @@ -307,7 +307,7 @@ that numbers hide once a tile is under 40 points on screen. parameters, one row per map the set exports: a tick, the file name pattern (cut at the front with "…" when long, the whole pattern as tooltip), its own *Enable override* and the inherited "png 8 bits". An override gives the map its own file type and bit depth (`maps` of - `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Override every item* and *Clear all overrides*; *Include all* ticks every map + `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Enable override for all items* and *Disable override for all items*; *Include all* ticks every map again. The patterns are cut after 26 characters (the reference cuts by pixel width). - **File types** ([#672](https://github.com/storytold/texturecraft/issues/672)): File type lists bmp, jpeg, jng, pgm, png, targa, tiff, hdr, exr, j2k, jp2, webp, psd and sbsar; j2k, jp2 From 7e129c3968011dc976e6b9e85213d4bfd917c086 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:00:35 +0100 Subject: [PATCH 02/20] Put the MaterialX export option directly below the USD one --- crates/ui-egui/src/export_window.rs | 4 ++-- crates/ui-egui/tests/it/export_materialx.rs | 10 ++++++++++ docs/ui-parity.md | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index ba01ae14..4c1d87ae 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -733,13 +733,13 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // Unavailable export controls stay disabled unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); - unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); - // The browser downloads the textures only + // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); #[cfg(target_arch = "wasm32")] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index b90d785e..328078aa 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -47,6 +47,16 @@ fn mtlx_files(dir: &std::path::Path) -> Vec { files } +#[test] +fn export_materialx_sits_directly_below_the_usd_option() { + let (app_harness, _dir) = harness("order"); + let usd = app_harness.get_by_label("Export USD asset").rect().min.y; + let materialx = checkbox(&app_harness).rect().min.y; + let shaders = app_harness.get_by_label("Export shaders parameters").rect().min.y; + + assert!(usd < materialx && materialx < shaders, "USD {usd}, MaterialX {materialx}, shaders {shaders}"); +} + #[test] fn the_window_offers_export_materialx_off_by_default() { let (app_harness, _dir) = harness("offer"); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8c392573..3cb62522 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -68,7 +68,7 @@ that closes it back onto the bar; the float is saved with the UI state. *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected - for export"). *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` + for export"). *Export MaterialX* below *Export USD asset* is a TextureCraft addition: it adds `materialX: true` to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are greyed; TextureCraft exports the mesh as it is. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the From 81627ab8c71ec62e52fad7142bd7bdc649aee354 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:09:54 +0100 Subject: [PATCH 03/20] Fit the export window to small screens and tighten its tests --- crates/ui-egui/src/export_window.rs | 34 +++++--- crates/ui-egui/src/state/console_line.rs | 2 +- .../tests/it/export_reference_texts.rs | 86 +++++++++++++------ 3 files changed, 84 insertions(+), 38 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 4c1d87ae..3fe1b4e1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -21,8 +21,14 @@ mod map_row; use inherited_settings::InheritedSettings; use map_row::MapRow; -/// Height of the window's tab body, above its buttons -const BODY_HEIGHT: f32 = 660.0; +/// The reference window's size; a smaller screen gets a smaller window +const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); +/// Space kept free around the content on a small screen: the title bar, the frame and a gap +const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; +/// Height of the tab row, the separators and the bottom bar around the tab body +const WINDOW_CHROME_HEIGHT_POINTS: f32 = 80.0; +/// The smallest tab body, so the lists and pages stay usable +const MIN_BODY_HEIGHT_POINTS: f32 = 160.0; /// Width of the texture set list const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; @@ -732,7 +738,11 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] }); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export USD asset"), tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + unavailable_checkbox( + ui, + tr("Export USD asset"), + tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + ); // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -769,7 +779,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] /// The left column: Global settings, then a row per texture set with its export tick; a click /// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); }); @@ -779,7 +789,7 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { } // Many texture sets scroll inside the list; the footer stays in view - let list_height = BODY_HEIGHT - header.rect.height() - ui.spacing().item_spacing.y; + let list_height = body_height - header.rect.height() - ui.spacing().item_spacing.y; egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); } @@ -1266,7 +1276,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(1100.0, 740.0)).show(ctx, |ui| { + let window_size = REFERENCE_WINDOW_SIZE_POINTS.min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); + let body_height = (window_size.y - WINDOW_CHROME_HEIGHT_POINTS).max(MIN_BODY_HEIGHT_POINTS); + crate::windows::dialog("export_textures", tr("Export textures"), &mut open).fixed_size(window_size).show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { ui.label(tr("No project is open")); @@ -1300,8 +1312,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); ui.separator(); - ui.allocate_ui_with_layout(vec2(ui.available_width(), BODY_HEIGHT), egui::Layout::left_to_right(egui::Align::Min), |ui| { - ui.set_height(BODY_HEIGHT); + ui.allocate_ui_with_layout(vec2(ui.available_width(), body_height), egui::Layout::left_to_right(egui::Align::Min), |ui| { + ui.set_height(body_height); match app.ui.export.tab { 1 => { crate::export_templates::tab(app, ui, &presets); @@ -1316,7 +1328,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.vertical(|ui| { ui.set_width(LIST_WIDTH); - set_list(app, ui); + set_list(app, ui, body_height); }); ui.separator(); ui.vertical(|ui| match app.ui.export.page { @@ -1346,7 +1358,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let selected = selected_texture_count(app); ui.horizontal(|ui| { // Not on LIST OF EXPORTS - 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() { + 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() + { // Keep ownership so Cancel can restore the opening settings 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); diff --git a/crates/ui-egui/src/state/console_line.rs b/crates/ui-egui/src/state/console_line.rs index 196a5b60..26baa2ce 100644 --- a/crates/ui-egui/src/state/console_line.rs +++ b/crates/ui-egui/src/state/console_line.rs @@ -2,7 +2,7 @@ #[derive(Clone, Debug, PartialEq)] pub enum ConsoleLine { Step(String), - /// "Texture set " with the name in bold. + /// "Exporting texture set ..." with the name in bold. Set(String), /// A success line, in green. Done(String), diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 39d9b959..6c176f56 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -1,14 +1,24 @@ -//! Export textures window (texturecraft #789): the reference's size, tab labels, button tooltips -//! and settings texts, word for word. +//! Export textures window (texturecraft #789): the reference's size, button tooltips and settings +//! texts, word for word. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; -/// The Export textures window open on SETTINGS -fn harness() -> Harness<'static, TextureCraftApp> { +/// The reference window's content size in points +const REFERENCE_WINDOW_WIDTH_POINTS: f32 = 1100.0; +const REFERENCE_WINDOW_HEIGHT_POINTS: f32 = 740.0; + +/// How far the measured content may differ from the reference size (item spacing, borders) +const SIZE_TOLERANCE_POINTS: f32 = 40.0; + +/// The right bar is the last 38 points of the window +const RAIL_WIDTH_POINTS: f32 = 38.0; + +/// The Export textures window open on SETTINGS in a screen of `screen_size` +fn harness(screen_size: egui::Vec2) -> Harness<'static, TextureCraftApp> { 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)); + let mut h = Harness::builder().with_size(screen_size).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); h.state_mut().ui.windows.export = true; @@ -16,40 +26,53 @@ fn harness() -> Harness<'static, TextureCraftApp> { h } -/// Hover the newest node labelled `label` until its tooltip shows -fn hover(h: &mut Harness<'_, TextureCraftApp>, label: &str) { - let center = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); - h.hover_at(center); - h.run_steps(30); +/// The rectangle of the window's button named `label`; the rail has an Export icon of its own +fn window_button_rect(h: &Harness<'_, TextureCraftApp>, label: &str, screen_width: f32) -> egui::Rect { + h.get_all_by_role(egui::Role::Button) + .filter(|button| button.rect().max.x < screen_width - RAIL_WIDTH_POINTS && button.accesskit_node().label().as_deref() == Some(label)) + .map(|button| button.rect()) + .next_back() + .unwrap_or_else(|| panic!("no {label} button in the window")) } -/// Hover `label` and check that its tooltip says `tooltip` +/// Hover the window's button `label` and check that its tooltip says `tooltip` fn tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { - hover(h, label); + let screen_width = h.ctx.content_rect().width(); + h.hover_at(window_button_rect(h, label, screen_width).center()); + h.run_steps(30); + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); } #[test] -fn the_window_is_as_wide_as_the_reference_window() { - let h = harness(); - let reset = h.get_by_label("Reset all").rect(); - let save = h.get_by_label("Save settings").rect(); +fn the_window_has_the_reference_size() { + let h = harness(egui::vec2(1600.0, 960.0)); + let reset = window_button_rect(&h, "Reset all", 1600.0); + let export = window_button_rect(&h, "Export", 1600.0); + let tabs = h.get_by_label("SETTINGS").rect(); - // The reference window is 1100 wide; the buttons sit at its two ends (it was 900 wide) - assert!(save.max.x - reset.min.x > 900.0, "{reset:?} {save:?}"); + let width = export.max.x - reset.min.x; + let height = export.max.y - tabs.min.y; + + assert!((width - REFERENCE_WINDOW_WIDTH_POINTS).abs() < SIZE_TOLERANCE_POINTS, "width {width}"); + assert!((height - REFERENCE_WINDOW_HEIGHT_POINTS).abs() < SIZE_TOLERANCE_POINTS, "height {height}"); } #[test] -fn the_tabs_read_in_capitals() { - let h = harness(); - for tab in ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS"] { - assert!(h.query_by_label(tab).is_some(), "{tab}"); +fn on_a_small_screen_the_window_fits_with_its_buttons_in_view() { + let screen = egui::vec2(1000.0, 700.0); + let h = harness(screen); + + for label in ["Reset all", "Cancel", "Save settings", "Export"] { + let rect = window_button_rect(&h, label, screen.x); + assert!(rect.min.x >= 0.0 && rect.max.x <= screen.x, "{label} {rect:?}"); + assert!(rect.min.y >= 0.0 && rect.max.y <= screen.y, "{label} {rect:?}"); } } #[test] fn the_buttons_carry_the_reference_tooltips() { - let mut h = harness(); + let mut h = harness(egui::vec2(1600.0, 960.0)); tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); @@ -57,13 +80,22 @@ fn the_buttons_carry_the_reference_tooltips() { tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); } +/// Hover the checkbox `label` and check that its tooltip says `tooltip` +fn checkbox_tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, tooltip: &str) { + let center = h.get_by_role_and_label(egui::Role::CheckBox, label).rect().center(); + h.hover_at(center); + h.run_steps(30); + + assert!(h.query_all_by_label(tooltip).next().is_some(), "{label}: {tooltip}"); +} + #[test] fn the_unavailable_checkboxes_carry_the_reference_texts() { - let mut h = harness(); - tooltip_is( + let mut h = harness(egui::vec2(1600.0, 960.0)); + checkbox_tooltip_is( &mut h, "Export USD asset", "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", ); - tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); + checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); } From cfc4b8b3a72732e2bd496eb7dd5fbdfa34c15081 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:29:18 +0100 Subject: [PATCH 04/20] Export textures and Mesh Export Options: plain Export buttons, fixed footer widths, reference dock buttons --- crates/ui-egui/src/export_panel.rs | 21 +++++++++++++------ crates/ui-egui/src/export_window.rs | 17 ++++++++++----- crates/ui-egui/src/mesh_export_options.rs | 14 ++++++++++--- .../tests/it/export_reference_texts.rs | 9 ++++++++ 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/export_panel.rs b/crates/ui-egui/src/export_panel.rs index 13dc88a7..d845d4d5 100644 --- a/crates/ui-egui/src/export_panel.rs +++ b/crates/ui-egui/src/export_panel.rs @@ -4,23 +4,32 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; -use crate::theme::caption; +use crate::theme::{Tokens, caption}; use crate::widgets::primary_button; -/// Width of the Export Mesh and Export Textures buttons -const EXPORT_BUTTON_WIDTH: f32 = 176.0; +/// Space around each button's text, so the buttons are as wide as their text as in the reference +const EXPORT_BUTTON_PADDING: egui::Vec2 = egui::vec2(18.0, 5.0); + +/// Gap between the Export Mesh and Export Textures buttons +const EXPORT_BUTTON_GAP: f32 = 12.0; /// The Export panel body (a rail popup or dock tab); its buttons need an open project pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(caption(&tr("Export").to_uppercase())); let project_open = app.session.project_open; + let tokens = Tokens::get(ui.ctx()); ui.vertical_centered(|ui| { - let size = [EXPORT_BUTTON_WIDTH, ui.spacing().interact_size.y]; - if ui.add_enabled(project_open, egui::Button::new(tr("Export Mesh...")).min_size(size.into())).clicked() { + ui.spacing_mut().button_padding = EXPORT_BUTTON_PADDING; + ui.spacing_mut().item_spacing.y = EXPORT_BUTTON_GAP; + + // Fully rounded: Export Mesh outlined, Export Textures filled + let pill = ui.spacing().interact_size.y + 2.0 * EXPORT_BUTTON_PADDING.y; + let outlined = egui::Button::new(tr("Export Mesh...")).fill(egui::Color32::TRANSPARENT).stroke(egui::Stroke::new(1.0, tokens.button_border)); + if ui.add_enabled(project_open, outlined.corner_radius(pill / 2.0)).clicked() { app.ui.windows.mesh_export_options = Some(app.session.project_id); app.ui.rail_panel = None; } - if ui.add_enabled(project_open, primary_button(ui, tr("Export Textures...")).min_size(size.into())).clicked() { + if ui.add_enabled(project_open, primary_button(ui, tr("Export Textures...")).corner_radius(pill / 2.0)).clicked() { app.ui.windows.export = true; app.ui.rail_panel = None; } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3fe1b4e1..cec6252c 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -14,7 +14,7 @@ use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; use crate::theme::{Tokens, caption}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{icon_button, primary_button}; +use crate::widgets::icon_button; mod inherited_settings; mod map_row; @@ -34,6 +34,8 @@ const LIST_WIDTH: f32 = 180.0; const ICON: f32 = 20.0; /// Width of the value column of the parameter rows const VALUE_WIDTH: f32 = 360.0; +/// Width of the bottom bar's buttons, the same for all as in the reference +const FOOTER_BUTTON_WIDTH: f32 = 125.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -584,6 +586,11 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// A bottom bar button, as wide as the others +fn footer_button(text: &str) -> egui::Button<'_> { + egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) +} + /// A header with a menu or tool at its right end fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { ui.horizontal(|ui| { @@ -1359,7 +1366,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { // Not on LIST OF EXPORTS 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() + && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; @@ -1369,15 +1376,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // 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() { + if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } // Saving closes the window without starting an export - if ui.button(tr("Save settings")).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if ui.add(footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } - if ui.button(tr("Cancel")).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { + if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } ui.label(trf("{n} textures selected for export", &[("n", &selected)])); diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 3c8a4ef4..95e2bae7 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -5,13 +5,18 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; use crate::unavailable; -use crate::widgets::primary_button; /// Indent of an option's checkbox under its choice const OPTION_INDENT: f32 = 20.0; /// Width of the Cancel and Export buttons -const BUTTON_WIDTH: f32 = 130.0; +const BUTTON_WIDTH: f32 = 110.0; + +/// The reference dialog's content width +const DIALOG_WIDTH: f32 = 510.0; + +/// Gap between the two option groups, as in the reference +const GROUP_GAP: f32 = 25.0; /// The prompt, while File > Export Mesh waits on it pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { @@ -23,9 +28,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut export, mut cancel) = (false, false); crate::windows::dialog("mesh_export_options", tr("Mesh Export Options"), &mut open).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + // TextureCraft exports the mesh as it is: triangulated, without displacement ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); option(ui, true, tr("Apply triangulation")); + ui.add_space(GROUP_GAP); unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); option(ui, true, tr("Recompute vertex normals")); ui.add_space(8.0); @@ -34,7 +42,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let size = egui::vec2(BUTTON_WIDTH, ui.spacing().interact_size.y); - export = ui.add(primary_button(ui, tr("Export")).min_size(size)).clicked(); + export = ui.add(egui::Button::new(tr("Export")).min_size(size)).clicked(); cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(size)).clicked(); }); }); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 6c176f56..46dcd4b9 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -99,3 +99,12 @@ fn the_unavailable_checkboxes_carry_the_reference_texts() { ); checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); } + +#[test] +fn the_bottom_bar_buttons_share_one_width() { + let h = harness(egui::vec2(1600.0, 960.0)); + + let widths: Vec = ["Reset all", "Cancel", "Save settings", "Export"].iter().map(|label| window_button_rect(&h, label, 1600.0).width()).collect(); + + assert!(widths.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 1.0), "{widths:?}"); +} From e83c3f88c83bb694ba3ea8bd2d76c8cc4e390f3c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:29:43 +0100 Subject: [PATCH 05/20] Output templates tab: Naming pattern on the tab row, no Include all, Reset all or count, Save settings and Export greyed --- crates/ui-egui/src/export_templates.rs | 27 +++++++++---------- crates/ui-egui/src/export_window.rs | 18 ++++++++----- crates/ui-egui/tests/it/output_templates.rs | 30 +++++++++++++++++++++ 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index f6fb56df..eea551c6 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -73,6 +73,8 @@ const CREATE: [(&str, Layout); 5] = /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; +/// Width of the Naming pattern list +const NAMING_PATTERN_WIDTH: f32 = 150.0; /// The input maps palette: (group, [(label, source)]). type Palette = [(&'static str, Vec<(&'static str, SourceRef)>); 4]; @@ -244,7 +246,6 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { ui.vertical(|ui| { ui.set_width(INPUTS_WIDTH); ui.set_height(height); - naming_pattern(ui); input_maps(ui); }); if let Some(a) = list_action { @@ -262,21 +263,19 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon -fn naming_pattern(ui: &mut Ui) { +/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) +pub(crate) fn naming_pattern(ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(tr("Naming pattern")); - egui::ComboBox::from_id_salt("exp_naming").width(90.0).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { - for p in NAMING_PATTERNS { - let _ = ui.selectable_label(true, p); - } - }); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Select the naming pattern used to display the input maps on this page.")); - ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); - }); + ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { + ui.label(tr("Select the naming pattern used to display the input maps on this page.")); + ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); + egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + for p in NAMING_PATTERNS { + let _ = ui.selectable_label(true, p); + } + }); + ui.label(tr("Naming pattern")); } /// The Presets list: the templates sorted by name (built-in and user); a right click offers diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index cec6252c..82bdbb4d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1309,6 +1309,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.button(tr("Open output directory")).clicked() { open_output_directory(app); } + } else if app.ui.export.tab == 1 { + crate::export_templates::naming_pattern(ui); } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { @@ -1362,10 +1364,12 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - let selected = selected_texture_count(app); + // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there + let templates_tab = app.ui.export.tab == 1; + let selected = if templates_tab { 0 } else { selected_texture_count(app) }; ui.horizontal(|ui| { - // Not on LIST OF EXPORTS - if app.ui.export.tab != 2 + // Only on SETTINGS + if app.ui.export.tab == 0 && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() { // Keep ownership so Cancel can restore the opening settings @@ -1375,19 +1379,21 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty(); + let any = !export_selection(app).is_empty() && !templates_tab; if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { do_export = true; } // Saving closes the window without starting an export - if ui.add(footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { canceled = true; } - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + if !templates_tab { + ui.label(trf("{n} textures selected for export", &[("n", &selected)])); + } }); }); }); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index bb9c5d5e..2831dc9c 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -30,6 +30,9 @@ fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> { h } +/// Left edge of the right rail in the 1600 point wide harness +const RAIL_LEFT_EDGE: f32 = 1560.0; + fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click(); h.run_steps(4); @@ -284,3 +287,30 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { assert_eq!(current, saved, "the corrected draft was saved in its own order"); assert_eq!(harness.state().ui.export.sets[&0].maps, [(1, disabled)].into()); } + +#[test] +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { + let library = TemplateLibrary::new("bottom-bar"); + let h = harness(&library); + + let naming = h.get_by_label("Naming pattern").rect(); + let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let presets = h.get_by_label("Presets").rect(); + + assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); + assert!(naming.left() > presets.right(), "at the right end"); + for absent in ["Include all", "Reset all"] { + assert!(h.query_by_label(absent).is_none(), "{absent}"); + } + assert!(h.query_by_label_contains("textures selected for export").is_none()); + for greyed in ["Save settings", "Export"] { + // The rail at the right edge has an Export button of its own + let button = h + .get_all_by_role(egui::Role::Button) + .filter(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)) + .last() + .unwrap(); + assert!(button.accesskit_node().is_disabled(), "{greyed}"); + } + assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); +} From 043de59f340f7268c8861d0e9bac77d1d57124cb Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:42:37 +0100 Subject: [PATCH 06/20] Output templates: reference map panes, channel swatches with the From popup, reference output map rows and Presets row --- crates/ui-egui/src/export_templates.rs | 1008 ++++++++++++----- .../src/export_templates/channel_target.rs | 24 + .../ui-egui/src/export_templates/map_drag.rs | 3 + .../ui-egui/src/export_templates/map_lists.rs | 150 +++ .../src/export_templates/pending_drop.rs | 14 + .../ui-egui/src/export_templates/row_edit.rs | 11 + crates/ui-egui/src/export_window.rs | 6 +- crates/ui-egui/src/state.rs | 14 + crates/ui-egui/tests/it/output_templates.rs | 185 ++- crates/ui-egui/tests/it/template_invert.rs | 30 +- 10 files changed, 1163 insertions(+), 282 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/channel_target.rs create mode 100644 crates/ui-egui/src/export_templates/map_drag.rs create mode 100644 crates/ui-egui/src/export_templates/map_lists.rs create mode 100644 crates/ui-egui/src/export_templates/pending_drop.rs create mode 100644 crates/ui-egui/src/export_templates/row_edit.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index eea551c6..2e109a1c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1,10 +1,10 @@ //! Export dialog › Output templates: create and edit export presets. Built-in presets are //! read-only; the selected user preset is edited as a draft that is saved through //! `export.preset.save` whenever it validates, so a half-typed file name never reaches disk. +//! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's +//! channel swatches fill its channels. -use std::sync::LazyLock; - -use egui::{RichText, Ui, vec2}; +use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -14,15 +14,84 @@ use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, Sour use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, icon_button}; +use crate::unavailable::NOT_AVAILABLE; +use crate::widgets::{chip, icon_button_without_tooltip}; + +mod channel_target; +mod map_drag; +mod map_lists; +mod pending_drop; +mod row_edit; + +pub use channel_target::ChannelTarget; +use map_drag::MapDrag; +use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +pub use pending_drop::PendingDrop; +use row_edit::RowEdit; const ICON: f32 = 20.0; -const LIST_WIDTH: f32 = 190.0; +const LIST_WIDTH: f32 = 220.0; +/// Width of the Input maps pane const INPUTS_WIDTH: f32 = 170.0; +/// Width of the pane with Mesh maps above Converted maps +const SIDE_MAPS_WIDTH: f32 = 165.0; +/// Share of the side pane's height that Mesh maps take; Converted maps get the rest +const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; /// The name "+" gives a new template, as in the reference const NEW_PRESET: &str = "new_export_preset"; -const RGB: [&str; 3] = ["R", "G", "B"]; + +/// Height of a Presets list row, and where its icon and name start +const PRESET_ROW_HEIGHT: f32 = 18.0; +const PRESET_ICON_INDENT: f32 = 2.0; +const PRESET_TEXT_INDENT: f32 = 20.0; + +/// Height of a map list entry, the gap between entries, and where its marker and name sit +const ENTRY_HEIGHT: f32 = 21.0; +const ENTRY_GAP: f32 = 2.0; +const ENTRY_TEXT_INDENT: f32 = 22.0; +const ENTRY_TEXT_SIZE: f32 = 12.0; +const MARKER_INDENT: f32 = 10.0; +const MARKER_SIZE: f32 = 10.0; +/// How strongly a map TextureCraft does not have yet is dimmed +const UNAVAILABLE_FADE: f32 = 0.6; + +/// An output map row: padding, gap below it, grip width, file name field width, icon size +const ROW_MARGIN: f32 = 6.0; +const ROW_GAP: f32 = 4.0; +const GRIP_WIDTH: f32 = 5.0; +const NAME_FIELD_WIDTH: f32 = 150.0; +const ROW_ICON: f32 = 16.0; + +/// A channel swatch: its side, the label's size and offset from the top, and the bars that show +/// which channels of the source it reads +const SWATCH_SIZE: f32 = 32.0; +const SWATCH_TEXT_SIZE: f32 = 11.0; +const SWATCH_TEXT_TOP: f32 = 3.0; +const SWATCH_BAR_WIDTH: f32 = 18.0; +const SWATCH_BAR_HEIGHT: f32 = 2.0; +const SWATCH_BAR_BOTTOM: f32 = 9.0; + +/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to +/// keep the white label readable +const HUE_STEP: f32 = 0.618_034; +const SWATCH_SATURATION: f32 = 0.45; +const SWATCH_VALUE_DARK: f32 = 0.42; +const SWATCH_VALUE_LIGHT: f32 = 0.62; + +/// The bars of the R, G and B channels a swatch reads +const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; + +/// What a cleared channel writes: black, or opaque in the alpha channel +const CLEARED_VALUE: f32 = 0.0; +const CLEARED_ALPHA: f32 = 1.0; + +/// The reference's file name variables in its order; ones TextureCraft does not have are greyed +const REFERENCE_TOKENS: [&str; 6] = ["$project", "$mesh", "$textureSet", "$udim", "$uvTileName", "$colorSpace"]; + +/// The file types an output map lists, by extension in the reference order; the ones that +/// TextureCraft cannot write yet are greyed +const MAP_FILE_TYPES: [&str; 14] = ["bmp", "jpg", "jng", "pgm", "png", "tga", "tif", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; /// An output file's channel layout. #[derive(Clone, Copy, Debug, PartialEq)] @@ -34,17 +103,6 @@ enum Layout { } impl Layout { - const ALL: [Layout; 4] = [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha]; - - fn label(self) -> &'static str { - match self { - Layout::Rgb => "RGB", - Layout::Rgba => "RGBA", - Layout::Gray => n_("Gray"), - Layout::GrayAlpha => n_("Gray + A"), - } - } - fn dests(self) -> &'static [Dest] { match self { Layout::Rgb => &[Dest::R, Dest::G, Dest::B], @@ -65,10 +123,15 @@ impl Layout { } } -/// The reference's Create buttons: (label, the layout the new output map gets). The split ones -/// ("R+G+B", "R+G+B+A") make the same map; each channel can take its own source in either. -const CREATE: [(&str, Layout); 5] = - [(n_("Gray"), Layout::Gray), ("RGB", Layout::Rgb), ("R+G+B", Layout::Rgb), ("RGB+A", Layout::Rgba), ("R+G+B+A", Layout::Rgba)]; +/// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and +/// B show as separate swatches) +const CREATE: [(&str, Layout, bool); 5] = [ + (n_("Gray"), Layout::Gray, false), + ("RGB", Layout::Rgb, false), + ("R+G+B", Layout::Rgb, true), + ("RGB+A", Layout::Rgba, false), + ("R+G+B+A", Layout::Rgba, true), +]; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) @@ -76,27 +139,6 @@ const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; /// Width of the Naming pattern list const NAMING_PATTERN_WIDTH: f32 = 150.0; -/// The input maps palette: (group, [(label, source)]). -type Palette = [(&'static str, Vec<(&'static str, SourceRef)>); 4]; - -static PALETTE: LazyLock = LazyLock::new(|| { - [ - (n_("Texture set channels"), Channel::ALL.iter().map(|&channel| (channel.label(), SourceRef::Channel { channel, component: 0 })).collect()), - (n_("Converted maps"), VirtualMap::ALL.iter().map(|&map| (map.label(), SourceRef::Virtual { map, component: 0 })).collect()), - (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), SourceRef::Baked { map, component: 0 })).collect()), - (n_("Constants"), vec![(n_("Black"), SourceRef::Constant(0.0)), (n_("Gray 50%"), SourceRef::Constant(0.5)), (n_("White"), SourceRef::Constant(1.0))]), - ] -}); - -fn source_label(s: &SourceRef) -> &'static str { - match s { - SourceRef::Channel { channel, .. } => channel.label(), - SourceRef::Virtual { map, .. } => map.label(), - SourceRef::Baked { map, .. } => crate::i18n::baked_map_label(*map), - SourceRef::Constant(_) => n_("Constant"), - } -} - /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { let k = if s.components() == 3 { k.min(2) } else { 0 }; @@ -107,6 +149,14 @@ fn with_component(s: &SourceRef, k: u8) -> SourceRef { s } +/// The component `s` reads (0 for constants). +fn component_of(s: &SourceRef) -> u8 { + match s { + SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } => *component, + SourceRef::Constant(_) => 0, + } +} + /// Same input map (any component), or the same constant. fn same_source(a: &SourceRef, b: &SourceRef) -> bool { match (a, b) { @@ -187,12 +237,18 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft = None; e.draft_maps.clear(); e.draft_base = None; + e.draft_split.clear(); + e.active_map = None; + e.pending_drop = None; } 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(); e.draft_base = Some(saved.clone()); + e.draft_split.clear(); + e.active_map = None; + e.pending_drop = None; } else if e.draft_base.as_ref() != Some(saved) { // Match only unambiguous maps from the previous saved order for origin in &mut e.draft_maps { @@ -218,13 +274,15 @@ pub use crate::ask::Ask; pub use crate::list_action::ListAction; enum MapAction { - Add(Layout), - Up(usize), - Down(usize), + /// A new output map with this layout, its R, G and B split or not + Add(Layout, bool), + Move { from: usize, to: usize }, + Duplicate(usize), Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, input maps. +/// The Output templates tab: template list, the selected template's outputs, then the Input maps +/// pane and the pane with Mesh maps above Converted maps. pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { sync_draft(app); let height = ui.available_height(); @@ -237,16 +295,26 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { }); ui.separator(); ui.vertical(|ui| { - // Leave room for the input maps column and two separators - ui.set_width((ui.available_width() - INPUTS_WIDTH - 5.0 * ui.spacing().item_spacing.x - 4.0).max(200.0)); + // Leave room for the two map panes and three separators + let panes = INPUTS_WIDTH + SIDE_MAPS_WIDTH + 8.0 * ui.spacing().item_spacing.x + 6.0; + ui.set_width((ui.available_width() - panes).max(200.0)); ui.set_height(height); outputs(app, ui); }); + + // The panes mark the sources of the output map edited last + let marked = marked_sources(app, &Tokens::get(ui.ctx())); ui.separator(); ui.vertical(|ui| { ui.set_width(INPUTS_WIDTH); ui.set_height(height); - input_maps(ui); + input_maps(ui, &marked); + }); + ui.separator(); + ui.vertical(|ui| { + ui.set_width(SIDE_MAPS_WIDTH); + ui.set_height(height); + mesh_and_converted_maps(ui, height, &marked); }); if let Some(a) = list_action { apply(app, ui.ctx(), a); @@ -284,28 +352,21 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti let mut act = None; let sel = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.label(caption(tr("Presets"))); ui.horizontal(|ui| { - let tool = |ui: &mut Ui, enabled: bool, icon: &str, tip: &str| ui.add_enabled_ui(enabled, |ui| icon_button(ui, icon, tip, false, ICON)).inner.clicked(); - if tool(ui, true, ic::PLUS, tr("New template")) { - act = Some(ListAction::New); - } - if tool(ui, true, ic::COPY, tr("Duplicate the selected template")) { - act = Some(ListAction::Duplicate(sel.clone())); - } - if tool(ui, user, ic::PENCIL_SIMPLE, tr("Rename the selected template")) { - act = Some(ListAction::StartRename(sel.clone())); - } - if tool(ui, user, ic::TRASH, tr("Delete the selected template")) { - act = Some(ListAction::Remove(sel.clone())); - } - ui.separator(); - if tool(ui, true, ic::DOWNLOAD_SIMPLE, tr("Import a template (.json)")) { - act = Some(ListAction::Import); - } - if tool(ui, true, ic::UPLOAD_SIMPLE, tr("Export the selected template (.json)")) { - act = Some(ListAction::Export); - } + ui.label(caption(tr("Presets"))); + + // Copy, "−" and "+" from left to right, without tooltips as in the reference + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON).clicked() { + act = Some(ListAction::New); + } + if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON)).inner.clicked() { + act = Some(ListAction::Remove(sel.clone())); + } + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON).clicked() { + act = Some(ListAction::Duplicate(sel.clone())); + } + }); }); ui.add_space(2.0); if std::mem::take(&mut app.ui.export.rename_key) && user { @@ -326,7 +387,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti } } None => { - let r = ui.selectable_label(*name == sel, name).on_hover_text(name); + let r = preset_row(ui, name, *name == sel).on_hover_text(name); if r.double_clicked() && is_user { act = Some(ListAction::StartRename(name.clone())); } else if r.clicked() { @@ -343,6 +404,15 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { act = Some(ListAction::Remove(name.clone())); } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + if ui.button(tr("Import a template (.json)")).clicked() { + act = Some(ListAction::Import); + } + if *name == sel && ui.button(tr("Export the selected template (.json)")).clicked() { + act = Some(ListAction::Export); + } }); } } @@ -351,6 +421,28 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti act } +/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in +/// the accent colour +fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); + + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, tokens.radius, tokens.row_hover); + } + let font = egui::TextStyle::Body.resolve(ui.style()); + painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); + let color = if selected { tokens.accent } else { tokens.text }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT); + let galley = painter.layout_job(job); + let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT, rect.center().y - galley.size().y / 2.0); + painter.galley(top_left, galley, color); + response +} + /// The error of the selected template's draft when it does not validate: that edit is not saved. fn unfinished(app: &TextureCraftApp) -> Option { app.ui.export.draft.as_ref().and_then(|d| d.validate().err()).map(|e| e.to_string()) @@ -600,43 +692,54 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } }; let preview = preview_names(app, &preset); - let mut action = None; - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).color(tokens.text_dim)); - ui.label(RichText::new(&preset.name).strong().color(tokens.text_strong)); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - ui.label(caption(tr("Output maps"))); - ui.add_enabled_ui(editable, |ui| { + let mut edit = RowEdit::default(); + + // The selected template in a strip, "Current preset:" in bold + egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN).show(ui, |ui| { + ui.set_width(ui.available_width()); ui.horizontal(|ui| { - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - for (label, layout) in CREATE { - if ui.small_button(tr(label)).clicked() { - action = Some(MapAction::Add(layout)); - } + ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); + ui.label(&preset.name); + if !editable { + ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); } }); }); + + // "Output maps", with the Create buttons at the right end of the same row + ui.horizontal(|ui| { + ui.label(caption(tr("Output maps"))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(editable, |ui| { + for (label, layout, split) in CREATE.iter().rev() { + if ui.button(tr(label)).clicked() { + edit.action = Some(MapAction::Add(*layout, *split)); + } + } + ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); + }); + }); + }); if let Err(e) = &preview { ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); } let mut changed = false; let map_count = preset.maps.len(); + let mut split = app.ui.export.draft_split.clone(); + split.resize(map_count, false); - // Leave room for the footer below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y; + // Leave room for the footer text and the framed count below + let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN; egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - if map_count == 0 { - ui.add_space(8.0); - ui.label(RichText::new(tr("No outputs yet: add one above, then drag input maps onto its channels.")).color(tokens.text_dim)); - } ui.add_enabled_ui(editable, |ui| { - for (map_index, map) in preset.maps.iter_mut().enumerate() { - let file = preview.as_ref().ok().and_then(|names| names.get(map_index).cloned().flatten()); - changed |= output_card(ui, map_index, map_count, map, file.as_deref(), &mut action); - ui.add_space(4.0); + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); + let planned = match file { + Some(file) => format!("{} {file}", ic::ARROW_RIGHT), + None => tr("Not exported: no source in this texture set").to_string(), + }; + changed |= output_row(ui, index, map_count, map, row_split, &planned, &mut edit); + ui.add_space(ROW_GAP); } }); }); @@ -645,38 +748,80 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Count only maps that have sources in the current set if let Ok(names) = &preview { let exported = names.iter().flatten().count(); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); + egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); + }); } if !editable { return; } + // A drop asks for the source channel from the next frame on; one waiting from before shows now + let mut active = edit.touched.or(app.ui.export.active_map); + let mut pending = app.ui.export.pending_drop.take(); + if edit.pending.is_some() { + pending = edit.pending.take(); + ui.ctx().request_repaint(); + } else { + changed |= source_channel_popup(ui, &mut pending, &mut preset.maps, &mut active); + } + // 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() != map_count { origin = (0..map_count).map(Some).collect(); } - match action { - Some(MapAction::Add(layout)) => { + let acted = match edit.action { + Some(MapAction::Add(layout, split_rgb)) => { preset.maps.push(new_map(layout)); origin.push(None); + split.push(split_rgb); + active = Some(map_count); + true } - Some(MapAction::Up(index)) if index > 0 && index < map_count => { - preset.maps.swap(index, index - 1); - origin.swap(index, index - 1); + Some(MapAction::Move { from, to }) if from < map_count && to < map_count && from != to => { + let map = preset.maps.remove(from); + preset.maps.insert(to, map); + let map_origin = origin.remove(from); + origin.insert(to, map_origin); + let map_split = split.remove(from); + split.insert(to, map_split); + active = Some(to); + true } - Some(MapAction::Down(index)) if index + 1 < map_count => { - preset.maps.swap(index, index + 1); - origin.swap(index, index + 1); + Some(MapAction::Duplicate(index)) if index < map_count => { + let copy = preset.maps.get(index).cloned(); + let copy_split = split.get(index).copied().unwrap_or(false); + if let Some(copy) = copy { + preset.maps.insert(index + 1, copy); + origin.insert(index + 1, None); + split.insert(index + 1, copy_split); + active = Some(index + 1); + } + true } Some(MapAction::Remove(index)) if index < map_count => { preset.maps.remove(index); origin.remove(index); + split.remove(index); + active = None; + true } - _ if !changed => return, - _ => {} + _ => false, + }; + + // Indices changed under a waiting drop: it is dropped + if acted { + pending = None; + } + let e = &mut app.ui.export; + e.draft_split = split; + e.active_map = active.filter(|index| *index < preset.maps.len()); + e.pending_drop = pending; + if acted || changed { + commit(app, preset, origin); } - commit(app, preset, origin); } /// Keep the edited draft; save it when valid. `origin` gives each map's index in the saved @@ -715,166 +860,482 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result, action: &mut Option) -> bool { - let tk = Tokens::get(ui.ctx()); +/// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, +/// duplicate and remove. `planned` is the file it writes for the current texture set. +fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { + let tokens = Tokens::get(ui.ctx()); let mut changed = false; - egui::Frame::new().fill(tk.row).corner_radius(tk.radius).inner_margin(6.0).show(ui, |ui| { + let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { - let width = ui.available_width() - 4.0 * (ICON + ui.spacing().item_spacing.x); - changed |= ui - .add(egui::TextEdit::singleline(&mut map.file).font(egui::TextStyle::Monospace).desired_width(width)) - .on_hover_text(tr("File name without extension; variables insert names")) - .changed(); - ui.menu_button(RichText::new(ic::CURRENCY_DOLLAR).size(13.0), |ui| { - for (token, what) in FILE_TOKENS { - if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { - map.file.push_str(token); - changed = true; - ui.close(); + grip(ui, index, count, edit); + let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(NAME_FIELD_WIDTH)).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned); + }); + changed |= name.changed(); + changed |= token_menu(ui, &mut map.file); + changed |= channel_swatches(ui, index, map, split, edit); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.vertical(|ui| { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON).clicked() { + edit.action = Some(MapAction::Duplicate(index)); } - } - }) - .response - .on_hover_text(tr("Insert a variable")); - if ui.add_enabled_ui(mi > 0, |ui| icon_button(ui, ic::ARROW_UP, tr("Move up"), false, ICON)).inner.clicked() { - *action = Some(MapAction::Up(mi)); - } - if ui.add_enabled_ui(mi + 1 < n, |ui| icon_button(ui, ic::ARROW_DOWN, tr("Move down"), false, ICON)).inner.clicked() { - *action = Some(MapAction::Down(mi)); - } - if icon_button(ui, ic::TRASH, tr("Remove this output"), false, ICON).clicked() { - *action = Some(MapAction::Remove(mi)); - } + if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + }); + ui.vertical(|ui| { + changed |= format_menu(ui, map); + changed |= depth_menu(ui, map); + }); + }); }); - ui.horizontal(|ui| { - egui::ComboBox::from_id_salt(("exp_map_fmt", mi)).width(56.0).selected_text(map.format.extension()).show_ui(ui, |ui| { - for f in FileFormat::ALL { - if ui.selectable_value(&mut map.format, f, f.extension()).changed() { - map.bit_depth = f.depth(map.bit_depth); - changed = true; - } - } - }); - egui::ComboBox::from_id_salt(("exp_map_bits", mi)).width(64.0).selected_text(trf("{n} bits", &[("n", &map.bit_depth)])).show_ui(ui, |ui| { - for &d in map.format.bit_depths() { - changed |= ui.selectable_value(&mut map.bit_depth, d, trf("{n} bits", &[("n", &d)])).changed(); - } - }); - let layout = Layout::of(map); - egui::ComboBox::from_id_salt(("exp_map_layout", mi)).width(72.0).selected_text(tr(layout.label())).show_ui(ui, |ui| { - for l in Layout::ALL { - if ui.selectable_label(l == layout, tr(l.label())).clicked() && l != layout { - set_layout(map, l); - changed = true; - } - } - }); - let (text, color) = match file { - Some(f) => (format!("{} {f}", ic::ARROW_RIGHT), tk.text_dim), - None => (tr("Not exported: no source in this texture set").to_string(), tk.text_dim), - }; - ui.add(egui::Label::new(RichText::new(text).size(11.0).color(color)).truncate()); - }); - changed |= channel_slots(ui, mi, map); }); - changed -} -/// A source picker per output channel that also takes input maps dropped from the palette. -fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool { - let tk = Tokens::get(ui.ctx()); - let mut changed = false; - let mut dropped = None; - let MapSpec { channels, inverted, .. } = map; - for (k, (dest, src)) in channels.iter_mut().enumerate() { - ui.horizontal(|ui| { - let dest_name = match *dest { - Dest::L => tr("Gray"), - Dest::A => "A", - d => RGB.get(slot_component(d) as usize).copied().unwrap_or("R"), - }; - ui.add_sized(vec2(30.0, 18.0), egui::Label::new(RichText::new(dest_name).size(11.0).color(tk.text_dim))); - let combo = egui::ComboBox::from_id_salt(("exp_slot", mi, k)).width(170.0).selected_text(tr(source_label(src))).show_ui(ui, |ui| { - for (group, inputs) in PALETTE.iter() { - ui.label(caption(tr(group))); - for (label, s) in inputs { - if ui.selectable_label(same_source(src, s), tr(label)).clicked() { - *src = with_component(s, slot_component(*dest)); - changed = true; - } - } - } - }); - let r = &combo.response; - if r.dnd_hover_payload::().is_some() { - ui.painter().rect_stroke(r.rect.expand(2.0), 3.0, egui::Stroke::new(1.5, tk.accent), egui::StrokeKind::Outside); - } - if let Some(input) = r.dnd_release_payload::() { - dropped = Some((*dest, (*input).clone())); - } - let three = src.components() == 3; - match src { - SourceRef::Constant(v) => { - changed |= ui.add(egui::DragValue::new(v).range(0.0..=1.0).speed(0.005).fixed_decimals(2)).changed(); - } - SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } if three => { - let shown = RGB.get(*component as usize).copied().unwrap_or("R"); - egui::ComboBox::from_id_salt(("exp_slot_c", mi, k)).width(36.0).selected_text(shown).show_ui(ui, |ui| { - for (i, l) in (0u8..).zip(RGB) { - changed |= ui.selectable_value(component, i, l).changed(); - } - }); - } - _ => {} - } - let on = inverted.contains(dest); - if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { - inverted.retain(|x| x != dest); - if !on { - inverted.push(*dest); - } - changed = true; - } - }); + // Another row's grip dropped here moves that row to this place + // Check the payload type before taking it, so a map list drop is not lost + let row = frame.response; + let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + ui.painter().rect_stroke(row.rect, tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); } - if let Some((dest, input)) = dropped { - drop_input(map, dest, &input); - changed = true; + if row_dragged_over + && let Some(from) = row.dnd_release_payload::() + { + edit.action = Some(MapAction::Move { from: from.0, to: index }); + } + if changed { + edit.touched = Some(index); } changed } -/// Input maps to drag onto output channels. -fn input_maps(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Input maps"))); - ui.label(RichText::new(tr("Drag onto an output channel")).size(11.0).color(tk.text_dim)); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { - for (gi, (group, inputs)) in PALETTE.iter().enumerate() { - ui.add_space(4.0); - ui.label(RichText::new(tr(group)).strong().size(11.0)); - ui.horizontal_wrapped(|ui| { - for (k, (label, s)) in inputs.iter().enumerate() { - let label = tr(label); +/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and +/// its right-click menu move it one place +fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { + let tokens = Tokens::get(ui.ctx()); + let enabled = ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH, SWATCH_SIZE), egui::Sense::click_and_drag()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); + let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; + ui.painter().rect_filled(rect, 1.0, color); + let response = response.on_hover_cursor(egui::CursorIcon::Grab); + response.dnd_set_drag_payload(MapDrag(index)); - // `dnd_drag_source` cannot wrap inside `horizontal_wrapped` - let r = chip(ui, label, false).interact(egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); - r.dnd_set_drag_payload(s.clone()); - if r.dragged() - && let Some(at) = r.interact_pointer_pos() - { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::unique(("exp_input_drag", gi, k))) - .order(egui::Order::Tooltip) - .fixed_pos(at + vec2(8.0, 8.0)) - .show(ui.ctx(), |ui| chip(ui, label, true)); - } - } - }); + let mut to = None; + if response.has_focus() { + if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) { + to = index.checked_sub(1); + } + if ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) && index + 1 < count { + to = Some(index + 1); + } + } + response.context_menu(|ui| { + if ui.add_enabled(index > 0, egui::Button::new(tr("Move up"))).clicked() { + to = index.checked_sub(1); + } + if ui.add_enabled(index + 1 < count, egui::Button::new(tr("Move down"))).clicked() { + to = Some(index + 1); } }); + if let Some(to) = to { + edit.action = Some(MapAction::Move { from: index, to }); + } +} + +/// The "$" button: the file name variables, the reference's first, then TextureCraft's own +fn token_menu(ui: &mut Ui, file: &mut String) -> bool { + let mut changed = false; + ui.menu_button("$", |ui| { + let mut add = |ui: &mut Ui, token: &str, what: &str| { + if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { + file.push_str(token); + changed = true; + ui.close(); + } + }; + for token in REFERENCE_TOKENS { + match FILE_TOKENS.iter().find(|(ours, _)| *ours == token) { + Some(&(token, what)) => add(ui, token, what), + None => { + ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } + } + } + for &(token, what) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { + add(ui, token, what); + } + }); + changed +} + +/// The file type menu of an output map ("png˅") +fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { + let mut changed = false; + ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + for extension in MAP_FILE_TYPES { + let Some(format) = FileFormat::from_extension(extension) else { + ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); + continue; + }; + + if ui.selectable_label(map.format == format, extension).clicked() { + changed |= map.format != format; + map.bit_depth = format.depth(map.bit_depth); + map.format = format; + ui.close(); + } + } + }); + changed +} + +/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { + let format = map.format; + let mut changed = false; + let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); + ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + for (depth, dithering) in crate::export_window::depth_options(format) { + let label = crate::export_window::depth_label(Some(format), depth, dithering); + if dithering { + ui.add_enabled(false, egui::Button::selectable(false, label)).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } else if ui.selectable_label(map.bit_depth == depth, label).clicked() { + changed |= map.bit_depth != depth; + map.bit_depth = depth; + ui.close(); + } + } + }); + changed +} + +/// Whether R, G and B read one map as one RGB swatch can show it: a color map's R, G and B, or +/// the same gray map or constant in all three +fn rgb_collapsed(map: &MapSpec) -> bool { + let get = |dest: Dest| map.channels.iter().find(|(d, _)| *d == dest).map(|(_, s)| s); + let (Some(red), Some(green), Some(blue)) = (get(Dest::R), get(Dest::G), get(Dest::B)) else { return true }; + + let one_map = same_source(red, green) && same_source(green, blue); + let spread = red.components() == 3 && [red, green, blue].into_iter().zip(0u8..).all(|(s, k)| component_of(s) == k); + one_map && (spread || red.components() == 1) +} + +/// The swatches an output map shows: Gray, or RGB (R, G, B when split), then A when it has alpha +fn swatch_targets(map: &MapSpec, split: bool) -> Vec { + let layout = Layout::of(map); + let mut targets = match layout { + Layout::Gray | Layout::GrayAlpha => vec![ChannelTarget::One(Dest::L)], + Layout::Rgb | Layout::Rgba if split || !rgb_collapsed(map) => [Dest::R, Dest::G, Dest::B].into_iter().map(ChannelTarget::One).collect(), + Layout::Rgb | Layout::Rgba => vec![ChannelTarget::Rgb], + }; + if matches!(layout, Layout::GrayAlpha | Layout::Rgba) { + targets.push(ChannelTarget::One(Dest::A)); + } + targets +} + +/// The label on a swatch +fn target_label(target: ChannelTarget) -> &'static str { + match target { + ChannelTarget::Rgb => "RGB", + ChannelTarget::One(Dest::R) => "R", + ChannelTarget::One(Dest::G) => "G", + ChannelTarget::One(Dest::B) => "B", + ChannelTarget::One(Dest::A) => "A", + ChannelTarget::One(Dest::L) => tr("Gray"), + } +} + +/// The source the swatch shows (R's for the RGB swatch) +fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { + let dest = target.dests().first()?; + map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) +} + +/// The source channel choices of "From ": (label, the component read; None: not available yet) +fn source_choices(source: &SourceRef) -> Vec<(&'static str, Option)> { + if source.components() == 3 { + vec![(n_("Gray Channel"), None), (n_("R Channel"), Some(0)), (n_("G Channel"), Some(1)), (n_("B Channel"), Some(2)), (n_("A Channel"), None)] + } else { + vec![(n_("Gray Channel"), Some(0)), (n_("A Channel"), None)] + } +} + +/// A source as a swatch names it: the map, and for one channel of a color map that channel +fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { + let map = tr(map_lists::name_of(source)?); + let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); + match picked { + Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])), + _ => Some(map.to_string()), + } +} + +/// The colour of a map on swatches and list markers (None for constants) +fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { + let channels = Channel::ALL.len(); + let converted = VirtualMap::ALL.len(); + let index = match source { + SourceRef::Channel { channel, .. } => Channel::ALL.iter().position(|c| c == channel)?, + SourceRef::Virtual { map, .. } => channels + VirtualMap::ALL.iter().position(|m| m == map)?, + SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, + SourceRef::Constant(_) => return None, + }; + let hue = (index as f32 * HUE_STEP).fract(); + let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; + Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) +} + +/// The bars under a swatch's label: R, G and B for a color map on the RGB swatch, else the one +/// channel read +fn swatch_bars(source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { + match source { + SourceRef::Constant(_) => Vec::new(), + _ if source.components() == 3 && target == ChannelTarget::Rgb => COMPONENT_COLORS.to_vec(), + _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), + _ => vec![tokens.text_strong], + } +} + +/// An output map's channel swatches: drop targets for the map lists; a click opens Clear channel +/// and Split/Collapse RGB, a right click Invert +fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { + let tokens = Tokens::get(ui.ctx()); + let mut changed = false; + let shows_split = *split || !rgb_collapsed(map); + for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { + let Some(source) = source_of(map, target).cloned() else { continue }; + + let label = target_label(target); + let name = match source_name(&source, target) { + Some(source) => trf("{channel}: {map}", &[("channel", &label), ("map", &source)]), + None => label.to_string(), + }; + let response = swatch(ui, label, &name, source_color(&source, &tokens), &swatch_bars(&source, target, &tokens)).on_hover_text(&name); + + // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row + let map_dragged_over = response.dnd_hover_payload::().is_some(); + if map_dragged_over { + ui.painter().rect_stroke(response.rect.expand(2.0), tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + } + if map_dragged_over && let Some(input) = response.dnd_release_payload::() { + edit.touched = Some(index); + if target == ChannelTarget::Rgb && input.components() == 3 { + drop_input(map, Dest::R, &input); + changed = true; + } else { + edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); + } + } + + let rgb = matches!(target, ChannelTarget::Rgb | ChannelTarget::One(Dest::R | Dest::G | Dest::B)); + let menu_id = ui.make_persistent_id(("exp_swatch_menu", index, slot)); + egui::Popup::menu(&response).id(menu_id).show(|ui| { + if ui.button(tr("Clear channel")).clicked() { + clear_channel(map, target); + changed = true; + edit.touched = Some(index); + } + if rgb && ui.button(tr("Split/Collapse RGB")).clicked() { + changed |= split_or_collapse(map, split, shows_split); + edit.touched = Some(index); + } + }); + + // Not in the reference's menu: inverting stays on the right click + response.context_menu(|ui| { + let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); + if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { + map.inverted.retain(|dest| !target.dests().contains(dest)); + if !on { + map.inverted.extend_from_slice(target.dests()); + } + changed = true; + edit.touched = Some(index); + ui.close(); + } + }); + } + changed +} + +/// One channel swatch: `label` on top, filled with the source's colour, bars below for the +/// channels it reads +fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[Color32]) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let enabled = ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE, SWATCH_SIZE), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); + + let painter = ui.painter(); + let border = if response.hovered() { tokens.accent } else { tokens.button_border }; + painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, egui::FontId::proportional(SWATCH_TEXT_SIZE), tokens.text_strong); + let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; + let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; + for (k, color) in bars.iter().enumerate() { + let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM); + painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT)), 0.0, *color); + } + response +} + +/// Clear channel: the swatch's channels write black, or opaque alpha +fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { + for (dest, source) in &mut map.channels { + if target.dests().contains(dest) { + *source = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + } + } +} + +/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones collapse into one RGB +/// swatch reading R's map. True when the map changed. +fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { + if !shows_split { + *split = true; + return false; + } + + *split = false; + if rgb_collapsed(map) { + return false; + } + + let Some(red) = source_of(map, ChannelTarget::One(Dest::R)).map(|s| with_component(s, 0)) else { return false }; + if red.components() == 3 { + drop_input(map, Dest::R, &red); + } else { + for (dest, source) in &mut map.channels { + if is_rgb(*dest) { + *source = red.clone(); + } + } + } + true +} + +/// "From ": which channel of the dropped map the output channel reads. True when the map +/// changed. +fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { + let Some(drop) = pending.clone() else { return false }; + let Some(map) = maps.get_mut(drop.map) else { + *pending = None; + return false; + }; + + let name = map_lists::name_of(&drop.source).map_or_else(String::new, |name| tr(name).to_string()); + let mut picked = None; + let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(drop.position), ui.layer_id()) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); + for (label, component) in source_choices(&drop.source) { + match component { + Some(component) => { + if ui.button(tr(label)).clicked() { + picked = Some(component); + } + } + None => { + ui.add_enabled(false, egui::Button::new(tr(label))).on_disabled_hover_text(tr(NOT_AVAILABLE)); + } + } + } + }); + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + *pending = None; + } + let Some(component) = picked else { return false }; + + let source = with_component(&drop.source, component); + for (dest, channel_source) in &mut map.channels { + if drop.target.dests().contains(dest) { + *channel_source = source.clone(); + } + } + *active = Some(drop.map); + true +} + +/// The sources of the output map edited last, with their colours, for the panes' markers +fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { + let Some(index) = app.ui.export.active_map else { return Vec::new() }; + let Some(map) = app.ui.export.draft.as_ref().and_then(|draft| draft.maps.get(index)) else { return Vec::new() }; + + map.channels.iter().filter_map(|(_, source)| source_color(source, tokens).map(|color| (source.clone(), color))).collect() +} + +/// The Input maps pane: the input maps in their groups +fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { + ui.label(caption(tr("Input maps"))); + egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { + for (group, entries) in INPUT_MAPS.iter() { + ui.label(RichText::new(tr(group)).italics()); + map_entries(ui, entries, marked, false); + } + }); +} + +/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) +fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { + ui.label(caption(tr("Mesh maps"))); + egui::ScrollArea::vertical() + .id_salt("exp_mesh_maps") + .auto_shrink([false; 2]) + .max_height(height * MESH_MAPS_SHARE) + .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); + ui.separator(); + ui.label(caption(tr("Converted maps"))); + egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +} + +fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { + let tokens = Tokens::get(ui.ctx()); + let text_color = if converted { tokens.warning } else { tokens.text }; + for (name, source) in entries { + let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); + map_entry(ui, tr(name), source.as_ref(), text_color, marker); + } +} + +/// A map list entry to drag onto an output channel, with the colour marker of an output map that +/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged +fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { + let tokens = Tokens::get(ui.ctx()); + let available = source.is_some(); + let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT), sense); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + + let painter = ui.painter(); + let row = rect.shrink2(vec2(0.0, ENTRY_GAP / 2.0)); + painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + if let Some(color) = marker { + painter.rect_filled(egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT, 0.0), egui::Vec2::splat(MARKER_SIZE)), 1.0, color); + } + let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + painter.text(row.left_center() + vec2(ENTRY_TEXT_INDENT, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(ENTRY_TEXT_SIZE), color); + let Some(source) = source else { + response.on_hover_text(tr(NOT_AVAILABLE)); + return; + }; + + let response = response.on_hover_cursor(egui::CursorIcon::Grab); + response.dnd_set_drag_payload(source.clone()); + if response.dragged() + && let Some(at) = response.interact_pointer_pos() + { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)).show(ui.ctx(), |ui| chip(ui, name, true)); + } } #[cfg(test)] @@ -899,7 +1360,7 @@ mod tests { assert_eq!(map.channels, vec![(Dest::L, ch(Channel::BaseColor, 0)), (Dest::A, SourceRef::Constant(1.0))]); set_layout(&mut map, Layout::Rgb); assert_eq!(map.channels.get(1), Some(&(Dest::G, ch(Channel::BaseColor, 1))), "gray to RGB spreads a color source"); - for l in Layout::ALL { + for l in [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha] { let m = new_map(l); assert_eq!(Layout::of(&m), l); ExportPreset { name: "t".into(), maps: vec![m] }.validate().unwrap(); @@ -927,4 +1388,43 @@ mod tests { assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list"); ExportPreset { name: "t".into(), maps: vec![map] }.validate().unwrap(); } + + #[test] + fn split_and_collapse_keep_r_g_b_on_one_or_three_swatches() { + let mut map = new_map(Layout::Rgb); + let mut split = false; + assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb], "an empty RGB map shows one swatch"); + + assert!(!split_or_collapse(&mut map, &mut split, false), "splitting changes only the view"); + assert_eq!(swatch_targets(&map, split).len(), 3); + + map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.0))]; + assert!(split_or_collapse(&mut map, &mut split, true)); + assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb]); + assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing spreads R's color map over R, G and B"); + + map.channels = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; + assert_eq!(swatch_targets(&map, false).len(), 3, "different maps in R, G and B show split even when not asked to"); + } + + #[test] + fn clear_channel_writes_black_or_opaque_alpha() { + let mut map = new_map(Layout::Rgba); + drop_input(&mut map, Dest::R, &ch(Channel::BaseColor, 0)); + drop_input(&mut map, Dest::A, &ch(Channel::Opacity, 0)); + + clear_channel(&mut map, ChannelTarget::Rgb); + clear_channel(&mut map, ChannelTarget::One(Dest::A)); + + let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); + assert_eq!(map.channels, cleared); + } + + #[test] + fn a_gray_map_offers_its_gray_channel_and_a_color_map_its_r_g_b() { + let offered = |source: &SourceRef| source_choices(source).into_iter().filter_map(|(label, component)| component.map(|_| label)).collect::>(); + + assert_eq!(offered(&ch(Channel::Metallic, 0)), ["Gray Channel"]); + assert_eq!(offered(&ch(Channel::BaseColor, 0)), ["R Channel", "G Channel", "B Channel"]); + } } diff --git a/crates/ui-egui/src/export_templates/channel_target.rs b/crates/ui-egui/src/export_templates/channel_target.rs new file mode 100644 index 00000000..61da155b --- /dev/null +++ b/crates/ui-egui/src/export_templates/channel_target.rs @@ -0,0 +1,24 @@ +use texturecraft_engine::formats::Dest; + +/// The channel swatch of an output map that a map was dropped on. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ChannelTarget { + /// The single RGB swatch: R, G and B together. + Rgb, + /// One destination channel: R, G, B, A or the gray channel. + One(Dest), +} + +impl ChannelTarget { + /// The destination channels the swatch writes. + pub fn dests(self) -> &'static [Dest] { + match self { + ChannelTarget::Rgb => &[Dest::R, Dest::G, Dest::B], + ChannelTarget::One(Dest::R) => &[Dest::R], + ChannelTarget::One(Dest::G) => &[Dest::G], + ChannelTarget::One(Dest::B) => &[Dest::B], + ChannelTarget::One(Dest::A) => &[Dest::A], + ChannelTarget::One(Dest::L) => &[Dest::L], + } + } +} diff --git a/crates/ui-egui/src/export_templates/map_drag.rs b/crates/ui-egui/src/export_templates/map_drag.rs new file mode 100644 index 00000000..0df33947 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_drag.rs @@ -0,0 +1,3 @@ +/// The drag payload of an output map row's grip: the row's index. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MapDrag(pub usize); diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs new file mode 100644 index 00000000..7690e805 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -0,0 +1,150 @@ +//! The maps the Output templates tab lists for dragging onto output channels, with the reference's +//! names (naming pattern OpenPBR). An entry without a source names a map TextureCraft does not +//! have yet; it is listed greyed. + +use std::sync::LazyLock; + +use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::formats::{SourceRef, VirtualMap}; + +use crate::i18n::n_; + +/// One entry of a map list: its name and what it reads (None: not available yet). +pub type MapEntry = (&'static str, Option); + +fn channel(channel: Channel) -> Option { + Some(SourceRef::Channel { channel, component: 0 }) +} + +fn converted(map: VirtualMap) -> Option { + Some(SourceRef::Virtual { map, component: 0 }) +} + +fn mesh(map: BakedMap) -> Option { + Some(SourceRef::Baked { map, component: 0 }) +} + +/// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are +/// cut off in the reference screenshots and use the OpenPBR names of the channels left over. +pub static INPUT_MAPS: LazyLock)>> = LazyLock::new(|| { + vec![ + ( + n_("Base"), + vec![ + (n_("Base weight"), None), + (n_("Base color"), channel(Channel::BaseColor)), + (n_("Base metalness"), channel(Channel::Metallic)), + (n_("Base diffuse roughness"), None), + ], + ), + ( + n_("Specular"), + vec![ + (n_("Specular weight"), None), + (n_("Specular color"), None), + (n_("Specular roughness"), channel(Channel::Roughness)), + (n_("Specular level"), channel(Channel::SpecularLevel)), + (n_("Specular anisotropy"), channel(Channel::AnisotropyLevel)), + (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), + ], + ), + (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Transmission color"), None)]), + ( + n_("Subsurface"), + vec![(n_("Subsurface weight"), channel(Channel::ScatterWeight)), (n_("Subsurface color"), None), (n_("Subsurface radius scale"), None)], + ), + ( + n_("Coat"), + vec![ + (n_("Coat weight"), channel(Channel::CoatWeight)), + (n_("Coat color"), None), + (n_("Coat roughness"), channel(Channel::CoatRoughness)), + (n_("Coat anisotropy"), None), + (n_("Coat specular level"), None), + (n_("Coat normal"), channel(Channel::CoatNormal)), + (n_("Coat tangent"), None), + ], + ), + ( + n_("Fuzz/Sheen"), + vec![(n_("Fuzz weight"), channel(Channel::SheenWeight)), (n_("Fuzz color"), channel(Channel::SheenColor)), (n_("Fuzz roughness"), channel(Channel::SheenRoughness))], + ), + (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), + (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), + ( + n_("Other"), + vec![ + (n_("Height"), channel(Channel::Height)), + (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), + (n_("Specular"), channel(Channel::Specular)), + (n_("Glossiness"), channel(Channel::Glossiness)), + ], + ), + ] +}); + +/// Mesh maps, in the reference order and case. +pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { + vec![ + (n_("Normal"), mesh(BakedMap::Normal)), + (n_("World space normal"), mesh(BakedMap::WorldNormal)), + (n_("ID"), mesh(BakedMap::Id)), + (n_("Ambient occlusion"), mesh(BakedMap::AmbientOcclusion)), + (n_("Curvature"), mesh(BakedMap::Curvature)), + (n_("Position"), mesh(BakedMap::Position)), + (n_("Thickness"), mesh(BakedMap::Thickness)), + (n_("Height"), mesh(BakedMap::Height)), + (n_("Bent normals"), mesh(BakedMap::BentNormal)), + (n_("Opacity"), mesh(BakedMap::Opacity)), + ] +}); + +/// Converted maps in the reference order, then the ones only TextureCraft has (templates use them). +pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { + vec![ + ("1/ior", None), + (n_("Mixed AO"), converted(VirtualMap::AoMixed)), + (n_("Diffuse"), None), + ("f0", converted(VirtualMap::F0)), + (n_("Glossiness"), converted(VirtualMap::Glossiness)), + (n_("Glossiness²"), None), + (n_("Normal DirectX"), converted(VirtualMap::NormalDirectX)), + (n_("Normal OpenGL"), converted(VirtualMap::NormalOpenGl)), + (n_("Reflection"), None), + (n_("Specular"), None), + ("Unity4 Diffuse", None), + ("Unity4 Gloss", None), + (n_("2D View"), None), + (VirtualMap::HeightNormal.label(), converted(VirtualMap::HeightNormal)), + (VirtualMap::Roughness.label(), converted(VirtualMap::Roughness)), + (VirtualMap::SheenTint.label(), converted(VirtualMap::SheenTint)), + ] +}); + +/// The listed name of `source` (any component), or None for a constant. +pub fn name_of(source: &SourceRef) -> Option<&'static str> { + let lists = INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()); + let mut entries = lists.filter_map(|(name, entry)| entry.as_ref().map(|entry| (*name, entry))); + entries.find(|(_, entry)| super::same_source(entry, source)).map(|(name, _)| name) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_channel_and_map_can_be_dragged() { + let listed: Vec = + INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()).filter_map(|(_, s)| s.clone()).collect(); + + for channel in Channel::ALL { + assert!(listed.contains(&SourceRef::Channel { channel, component: 0 }), "{channel:?}"); + } + for map in BakedMap::ALL { + assert!(listed.contains(&SourceRef::Baked { map, component: 0 }), "{map:?}"); + } + for map in VirtualMap::ALL { + assert!(listed.contains(&SourceRef::Virtual { map, component: 0 }), "{map:?}"); + } + } +} diff --git a/crates/ui-egui/src/export_templates/pending_drop.rs b/crates/ui-egui/src/export_templates/pending_drop.rs new file mode 100644 index 00000000..00b13a84 --- /dev/null +++ b/crates/ui-egui/src/export_templates/pending_drop.rs @@ -0,0 +1,14 @@ +use texturecraft_engine::formats::SourceRef; + +use super::ChannelTarget; + +/// A map dropped on an output channel, waiting for the user to pick which of its channels to use. +#[derive(Clone, Debug, PartialEq)] +pub struct PendingDrop { + /// The output map, by index into the template's maps. + pub map: usize, + pub target: ChannelTarget, + pub source: SourceRef, + /// Where the popup opens. + pub position: egui::Pos2, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs new file mode 100644 index 00000000..e813e574 --- /dev/null +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -0,0 +1,11 @@ +use super::{MapAction, PendingDrop}; + +/// What the output map rows asked for in this frame. +#[derive(Default)] +pub(super) struct RowEdit { + pub(super) action: Option, + /// A map dropped on a channel swatch, to ask which of its channels to use. + pub(super) pending: Option, + /// The row edited last. + pub(super) touched: Option, +} diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 82bdbb4d..59ed790e 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -76,12 +76,12 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ /// The bit depths `format` is written with, as the bit depth list offers them: (bits, /// dithering) -fn depth_options(format: FileFormat) -> Vec<(u8, bool)> { +pub(crate) fn depth_options(format: FileFormat) -> Vec<(u8, bool)> { format.bit_depths().iter().flat_map(|&d| if d == 8 && !format.holds_float(8) { vec![(8, false), (8, true)] } else { vec![(d, false)] }).collect() } /// A bit depth as listed: "8 bits", "8 bits + dithering", "16 bits", "16f bits", "32f bits" -fn depth_label(format: Option, bit_depth: u8, dithering: bool) -> String { +pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: bool) -> String { match (bit_depth, dithering) { (8, true) => tr("8 bits + dithering").to_string(), (16, _) if format == Some(FileFormat::Exr) => tr("16f bits").to_string(), @@ -1238,6 +1238,7 @@ fn cancel(app: &mut TextureCraftApp) { before.draft = None; before.renaming = None; before.ask = None; + before.pending_drop = None; // A template deleted since keeps the default instead if app.session.export_preset(&before.preset).is_none() { @@ -1259,6 +1260,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let e = &mut app.ui.export; e.job = None; e.ask = None; + e.pending_drop = None; e.opened_with = None; e.tab = 0; e.page = None; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8f949d76..89cb751a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -387,6 +387,17 @@ pub struct ExportUi { /// Output templates tab: the saved template `draft_maps` counts from. #[serde(skip)] pub draft_base: Option, + /// Output templates tab: for each map of `draft`, whether its R, G and B show as separate + /// channel swatches (R+G+B) instead of one RGB swatch. + #[serde(skip)] + pub draft_split: Vec, + /// Output templates tab: the output map edited last; the map lists mark its sources. + #[serde(skip)] + pub active_map: Option, + /// Output templates tab: a map dropped on an output channel, waiting for the source channel + /// ("From "). + #[serde(skip)] + pub pending_drop: Option, /// Output templates tab: the new name while renaming the selected preset. #[serde(skip)] pub renaming: Option, @@ -432,6 +443,9 @@ impl Default for ExportUi { draft: None, draft_maps: Vec::new(), draft_base: None, + draft_split: Vec::new(), + active_map: None, + pending_drop: None, renaming: None, rename_key: false, ask: None, diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2831dc9c..53c5daa1 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -1,9 +1,12 @@ //! Export textures › OUTPUT TEMPLATES (texturecraft #674): the reference's layout, names and the //! preset list's right-click menu and F2. +use egui::{Event, Modifiers, PointerButton}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::formats::{Dest, SourceRef}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{MapExport, SetExport}; @@ -38,6 +41,47 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.run_steps(4); } +/// Right-click the grip of output map `index` and pick `item` ("Move up" or "Move down") +fn move_map(h: &mut Harness<'_, TextureCraftApp>, index: usize, item: &str) { + h.get_all_by_label("Reorder").nth(index).unwrap_or_else(|| panic!("no grip {index}")).click_secondary(); + h.run_steps(4); + h.get_by_label(item).click(); + h.run_steps(4); +} + +/// The file name field of output map `index`: the text field on its grip's row +fn name_field(h: &Harness<'_, TextureCraftApp>, index: usize) -> egui::Rect { + let grip = h.get_all_by_label("Reorder").nth(index).unwrap_or_else(|| panic!("no grip {index}")).rect(); + h.get_all_by_role(egui::Role::TextInput) + .map(|field| field.rect()) + .find(|field| (field.center().y - grip.center().y).abs() < 6.0 && field.left() > grip.right()) + .unwrap_or_else(|| panic!("no file name field on row {index}")) +} + +/// Hover the file name field of output map `index` until its tooltip shows +fn hover_name_field(h: &mut Harness<'_, TextureCraftApp>, index: usize) { + let field = name_field(h, index); + h.hover_at(field.center()); + h.run_steps(30); +} + +/// The last button labelled `label` in the window (the newest output map's swatch) +fn last_window_button<'h>(h: &'h Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'h> { + h.get_all_by_role(egui::Role::Button) + .filter(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) + .last() + .unwrap_or_else(|| panic!("no {label} button")) +} + +/// Drop `source` on the point `at`, as a drag from the map lists ends there +fn drop_on(h: &mut Harness<'_, TextureCraftApp>, source: SourceRef, at: egui::Pos2) { + egui::DragAndDrop::set_payload(&h.ctx, source); + h.hover_at(at); + h.run_steps(2); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(4); +} + /// Right-click the Presets list's `label` (listed before the selected one's name in the middle) fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).click_secondary(); @@ -147,7 +191,10 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); - assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).count() >= 2, "both maps show their files"); + for index in 0..2 { + hover_name_field(&mut h, index); + assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).next().is_some(), "map {index} shows its file"); + } } #[test] @@ -205,7 +252,8 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { 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"); + hover_name_field(&mut h, 1); + assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row 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()); } @@ -220,8 +268,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { 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); + move_map(&mut h, 0, "Move down"); 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"); @@ -240,8 +287,7 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { // An unfinished edit (an empty file name is not saved) moves the first map down h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file.clear(); h.run_steps(2); - h.get_all_by_label("Move down").next().unwrap().click(); - h.run_steps(4); + move_map(&mut h, 0, "Move down"); // An agent saves the template in that order meanwhile: overrides now count from it let mut agent = saved.clone(); @@ -252,8 +298,7 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { // Stabilize the layout after fixing the draft so the next click hits the move button h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file = saved.maps[last].file.clone(); h.run_steps(2); - h.get_all_by_label("Move down").next().unwrap().click(); - h.run_steps(4); + move_map(&mut h, 0, "Move down"); let now = h.state().session.export_preset("Mine").unwrap(); assert_eq!(now.maps[1].file, saved.maps[1].file, "{:?}", now.maps.iter().map(|m| &m.file).collect::>()); let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default(); @@ -275,12 +320,8 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { harness.run_steps(3); // Repair the invalid first filename through the editor so the draft commits on that frame - let first_row = harness.get_all_by_label("Move down").next().unwrap().rect().center().y; - harness - .get_all_by_role(egui::Role::TextInput) - .find(|field| (field.rect().center().y - first_row).abs() < 4.0) - .unwrap() - .set_text_value_accesskit(&saved.maps[0].file); + let first_field = name_field(&harness, 0); + harness.get_all_by_role(egui::Role::TextInput).find(|field| field.rect() == first_field).unwrap().set_text_value_accesskit(&saved.maps[0].file); harness.run_steps(4); let current = harness.state().session.export_preset("Mine").unwrap(); @@ -314,3 +355,119 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { } assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } + +#[test] +fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { + let library = TemplateLibrary::new("preset-icons"); + let mut h = harness(&library); + + let presets = h.get_by_label("Presets").rect(); + let icons = ["Duplicate the selected template", "Delete the selected template", "New template"].map(|label| h.get_by_label(label).rect()); + + assert!(icons.iter().all(|icon| (icon.center().y - presets.center().y).abs() < presets.height()), "on the Presets row: {icons:?}"); + assert!(icons.windows(2).all(|pair| pair[0].center().x < pair[1].center().x), "copy, minus, plus from left to right"); + h.hover_at(icons[2].center()); + h.run_steps(30); + assert_eq!(h.query_all_by_label("New template").count(), 1, "no tooltip repeats the name"); + assert!(h.query_by_label("Import a template (.json)").is_none(), "no import button"); + + right_click(&mut h, "Mine"); + assert!(h.query_by_label("Import a template (.json)").is_some(), "import and export stay in the right-click menu"); + assert!(h.query_by_label("Export the selected template (.json)").is_some()); +} + +#[test] +fn the_map_lists_stand_in_three_panes_with_the_reference_names() { + let library = TemplateLibrary::new("panes"); + let h = harness(&library); + + let input = h.get_by_label("Input maps").rect(); + let mesh = h.get_by_label("Mesh maps").rect(); + let converted = h.get_by_label("Converted maps").rect(); + + assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); + assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); + for group in ["Base", "Transmission", "Subsurface", "Coat", "Fuzz/Sheen"] { + assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); + } + for name in ["Base metalness", "Specular roughness", "Coat normal", "Fuzz weight", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); + assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); + } + for name in ["Base weight", "Coat tangent", "1/ior", "Glossiness²", "2D View"] { + let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); + assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); + } + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal"] { + assert!(h.query_by_label(gone).is_none(), "{gone}"); + } +} + +#[test] +fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { + let library = TemplateLibrary::new("drop"); + let mut h = harness(&library); + click(&mut h, "R+G+B+A"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + + let green = last_window_button(&h, "G").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); + + assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); + for choice in ["R Channel", "G Channel", "B Channel"] { + assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); + } + for greyed in ["Gray Channel", "A Channel"] { + assert!(h.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed}"); + } + h.get_by_label("B Channel").click(); + h.run_steps(4); + + let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); + assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); + assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); + assert!(h.query_all_by_label("G: Base color (B Channel)").next().is_some(), "the swatch names its map"); + assert_eq!(h.state().ui.export.active_map, Some(last), "the lists mark this map's sources"); +} + +#[test] +fn a_gray_map_dropped_on_a_channel_offers_its_gray_channel() { + let library = TemplateLibrary::new("drop-gray"); + let mut h = harness(&library); + click(&mut h, "R+G+B+A"); + + let alpha = last_window_button(&h, "A").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, alpha); + + assert!(h.query_by_label("From Base metalness").is_some()); + assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); + assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); + assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); +} + +#[test] +fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_invert() { + let library = TemplateLibrary::new("swatch-menu"); + let mut h = harness(&library); + click(&mut h, "RGB"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + + // The RGB swatch is the last "RGB" button, after the Create button of that name + last_window_button(&h, "RGB").click(); + h.run_steps(4); + assert!(h.query_by_label("Clear channel").is_some()); + h.get_by_label("Split/Collapse RGB").click(); + h.run_steps(4); + assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); + + let green = last_window_button(&h, "G"); + let at = green.rect().center(); + green.click_secondary(); + h.run_steps(4); + + // The properties panel has Invert controls of its own: take the menu's, next to the swatch + let invert = h.get_all_by_label("Invert").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); + invert.click(); + h.run_steps(4); + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); +} diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index 748d5035..fc8f19f6 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -1,4 +1,5 @@ -//! Export dialog › Output templates: each output channel has an Invert toggle that is saved in the template. +//! Export dialog › Output templates: each output channel can be inverted from its swatch's +//! right-click menu, and the inversion is saved in the template. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -26,12 +27,17 @@ fn harness() -> (Harness<'static, TextureCraftApp>, Library) { (h, Library(dir)) } -/// The channel toggles of the open dialog (the dialog sits left of the properties panel, which has its own Invert controls) -fn toggles<'h>(h: &'h Harness<'_, TextureCraftApp>) -> Vec> { - h.get_all_by_label("Invert").filter(|n| n.rect().max.x < DIALOG_RIGHT_EDGE).collect() -} +/// Right-click the swatch `swatch` and click the Invert of its menu (the properties panel has Invert controls of its own) +fn toggle_invert(h: &mut Harness<'_, TextureCraftApp>, swatch: &str) { + let node = h.get_all_by_label(swatch).next().unwrap_or_else(|| panic!("no {swatch} swatch")); + let at = node.rect().center(); + node.click_secondary(); + h.run_steps(4); -const DIALOG_RIGHT_EDGE: f32 = 1200.0; + let invert = h.get_all_by_label("Invert").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); + invert.click(); + h.run_steps(4); +} fn template() -> ExportPreset { let ch = |channel| SourceRef::Channel { channel, component: 0 }; @@ -60,12 +66,12 @@ fn invert_toggle_changes_the_saved_template() { let saved = |h: &Harness<'_, TextureCraftApp>| h.state().session.export_preset(TEMPLATE).unwrap().maps[0].inverted.clone(); assert!(saved(&h).is_empty()); - // One Invert toggle per channel: R, G, B - assert_eq!(toggles(&h).len(), 3); - toggles(&h)[1].click(); - h.run_steps(4); + // Three maps in R, G and B: one swatch per channel + for swatch in ["R: Specular roughness", "G: Base metalness", "B"] { + assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); + } + toggle_invert(&mut h, "G: Base metalness"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggles(&h)[1].click(); - h.run_steps(4); + toggle_invert(&mut h, "G: Base metalness"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 2cea24fe7135a84a289eeb983e69d10cf050cd45 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:44:49 +0100 Subject: [PATCH 07/20] Export textures: boxed tabs, full-width Global settings, reference label column, dilation arrow, console header band and bold set names, one name per output map row --- crates/ui-egui/src/export_window.rs | 161 +++++++++++++++--- .../ui-egui/tests/it/export_map_overrides.rs | 11 ++ 2 files changed, 148 insertions(+), 24 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 59ed790e..3c3ae50a 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -5,14 +5,14 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::formats::{ExportPreset, FileFormat}; +use texturecraft_engine::formats::{ExportPreset, FileFormat, MapSpec, SourceRef}; use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption}; +use crate::theme::{Tokens, caption, semibold}; use crate::unavailable::NOT_AVAILABLE; use crate::widgets::icon_button; @@ -30,10 +30,26 @@ const WINDOW_CHROME_HEIGHT_POINTS: f32 = 80.0; /// The smallest tab body, so the lists and pages stay usable const MIN_BODY_HEIGHT_POINTS: f32 = 160.0; /// Width of the texture set list -const LIST_WIDTH: f32 = 180.0; +const LIST_WIDTH: f32 = 250.0; const ICON: f32 = 20.0; +/// Width of the label column of the parameter rows, as in the reference +const LABEL_COLUMN_WIDTH: f32 = 200.0; /// Width of the value column of the parameter rows const VALUE_WIDTH: f32 = 360.0; +/// Width of the first File type list; the bit depth list fills the rest of the row +const FILE_TYPE_WIDTH: f32 = 166.0; +/// Width of the dilation button, with room for its drop-down arrow +const DILATION_BUTTON_WIDTH: f32 = 60.0; +/// Size of a drop-down arrow, and its distance from the button's right edge +const CARET_SIZE: f32 = 10.0; +const CARET_INSET: f32 = 6.0; +/// A tab: padding around its name, the accent line on top of the open one, the name's size +const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); +const TAB_ACCENT_HEIGHT: f32 = 2.0; +const TAB_TEXT_SIZE: f32 = 12.5; +/// Height of a full-width row of the texture set list and where its text starts +const LIST_ROW_HEIGHT: f32 = 24.0; +const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference const FOOTER_BUTTON_WIDTH: f32 = 125.0; @@ -104,7 +120,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { 166.0 } else { 90.0 }).height(f32::INFINITY); + let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); list.selected_text(shown).show_ui(ui, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { @@ -130,7 +146,9 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; ui.add_enabled_ui(options.len() > 1, |ui| { - egui::ComboBox::from_id_salt(("bits", id)).width(if from_template { 160.0 } else { 120.0 }).selected_text(shown).show_ui(ui, |ui| { + // On the global page the bit depth list fills the row + let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; + egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { for (d, dither) in options { if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { (*bit_depth, *dithering) = (d, dither); @@ -510,12 +528,23 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.clone()).unwrap_or_default(); + let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.replace("$channel", channel_id(m))).unwrap_or_default(); rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); } rows } +/// What `$channel` becomes in `map`'s file name: the id of its first map, as the export names it +fn channel_id(map: &MapSpec) -> &'static str { + let first = map.channels.iter().find_map(|(_, source)| match source { + SourceRef::Channel { channel, .. } => Some(channel.id()), + SourceRef::Virtual { map, .. } => Some(map.id()), + SourceRef::Baked { map, .. } => Some(map.id()), + SourceRef::Constant(_) => None, + }); + first.unwrap_or("constant") +} + /// The Output maps section of texture set `ts`'s page fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { let rows = map_rows(app, ts); @@ -586,6 +615,28 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// A window tab: a box, lighter and with an accent line on top when open +fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let color = if selected { tokens.text_strong } else { tokens.text }; + let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); + let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); + + let painter = ui.painter(); + let fill = match (selected, response.hovered()) { + (true, _) => tokens.panel, + (false, true) => tokens.row_hover, + (false, false) => tokens.row, + }; + painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); + if selected { + painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); + } + painter.galley(rect.min + TAB_PADDING, galley, color); + response +} + /// A bottom bar button, as wide as the others fn footer_button(text: &str) -> egui::Button<'_> { egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) @@ -649,11 +700,18 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { // The menu stays open while the slider is used let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); let r = ui.add_enabled_ui(enabled, |ui| { - egui::containers::menu::MenuButton::new(dilation.to_string()).config(config).ui(ui, |ui| { + let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); + egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { ui.label(tr("Dilation (pixels)")); ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); }) }); + + // The drop-down arrow is drawn apart, so the button's name stays the number + let tokens = Tokens::get(ui.ctx()); + let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; + let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); + ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { @@ -705,7 +763,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::export_templates::select(app, defaults.preset); } let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { // The browser downloads the files instead #[cfg(not(target_arch = "wasm32"))] output_directory(app, ui); @@ -734,7 +792,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); ui.label(tr("Padding")); ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("exp_pad").width(260.0).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { + let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; + egui::ComboBox::from_id_salt("exp_pad").width(width).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { for (value, label) in PADDINGS { ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); } @@ -758,7 +817,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); - egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; ui.label(tr("Normal map format")); let normal_label = match settings.normal_format.as_str() { @@ -790,7 +849,7 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); }); - let header = ui.selectable_label(app.ui.export.page.is_none(), RichText::new(tr("Global settings")).strong()); + let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); if header.clicked() { app.ui.export.page = None; } @@ -800,6 +859,23 @@ fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, body_height: f32) { egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); } +/// A row across the whole list, its name in bold; the selected one framed +fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); + + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, tokens.row_hover); + } + let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); + painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); + response +} + /// A row per texture set: its export tick, its name and the override mark fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { for i in 0..app.session.set_count() { @@ -822,6 +898,7 @@ fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { }); } }); + ui.separator(); } } @@ -901,7 +978,7 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }); }); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let on = o.preset.is_some(); if override_row(ui, tr("Output template"), on, &from.preset, |ui| { if let Some(p) = &mut o.preset { @@ -974,6 +1051,16 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor /// Width of the LIST OF EXPORTS console const CONSOLE_WIDTH: f32 = 300.0; +/// Width of the strip between the file tree and the console +const SPLITTER_WIDTH: f32 = 14.0; +/// Padding of the CONSOLE header band, about 45 points high as in the reference +const CONSOLE_HEADER_MARGIN_X: i8 = 12; +const CONSOLE_HEADER_MARGIN_Y: i8 = 14; +/// The file tree: indent of the file rows under their texture set, and the row height +const TREE_INDENT: f32 = 35.0; +const TREE_ROW_HEIGHT: f32 = 17.0; +/// Half the width of the tree's chevron +const CHEVRON_HALF_WIDTH: f32 = 4.0; /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { @@ -991,9 +1078,11 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); - // The thin toggle at the console's left edge + // The thin toggle at the console's left edge, on a strip the whole height let toggle = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let r = ui.add_sized(vec2(14.0, ui.available_height()), egui::Button::new(toggle).frame(false)); + let strip = egui::Rect::from_min_size(ui.cursor().min, vec2(SPLITTER_WIDTH, ui.available_height())); + ui.painter().rect_filled(strip, 0.0, tk.chrome); + let r = ui.add_sized(strip.size(), egui::Button::new(toggle).frame(false)); let r = if hidden { r } else { r.on_hover_text(tr("Hide Console")) }; if r.clicked() { app.ui.export.console_hidden = !hidden; @@ -1001,9 +1090,12 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { if !hidden { ui.vertical(|ui| { ui.set_width(CONSOLE_WIDTH); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true).show(ui, |ui| { + egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(caption(&tr("Console").to_uppercase()).strong()); + }); + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { for line in &app.ui.export.console { match line { ConsoleLine::Step(t) => { @@ -1030,7 +1122,7 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { let plain = egui::TextFormat::simple(font.clone(), tk.text); let mut job = egui::text::LayoutJob::default(); job.append(before, 0.0, plain.clone()); - job.append(name, 0.0, egui::TextFormat::simple(font, tk.text_strong)); + job.append(name, 0.0, egui::TextFormat::simple(semibold(font.size), tk.text_strong)); job.append(after, 0.0, plain); job } @@ -1063,9 +1155,11 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) } fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).show(ui, |ui| match &set.files { + ui.spacing_mut().indent = TREE_INDENT; + let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); + header.show(ui, |ui| match &set.files { Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).spacing(vec2(12.0, 4.0)).show(ui, |ui| { + egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { for output in files.as_array().into_iter().flatten() { let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); @@ -1088,6 +1182,21 @@ fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &s }); } +/// The tree's outline chevron: pointing down when open, right (left in right-to-left) when closed +fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { + let color = Tokens::get(ui.ctx()).text; + let center = response.rect.center(); + let half = CHEVRON_HALF_WIDTH; + let points = if openness > 0.5 { + [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] + } else if ui.style().right_to_left { + [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] + } else { + [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] + }; + ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); +} + /// Show the output folder in the system's file manager (created first when missing) #[cfg(not(target_arch = "wasm32"))] fn open_output_directory(app: &mut TextureCraftApp) { @@ -1295,11 +1404,15 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } ui.horizontal(|ui| { - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if ui.selectable_label(app.ui.export.tab == i as u8, caption(&t.to_uppercase())).clicked() { - app.ui.export.tab = i as u8; + // Boxed tabs side by side + ui.scope(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { + if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { + app.ui.export.tab = i as u8; + } } - } + }); // The file list opens the destination folder ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 8e627895..45ce9297 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -152,3 +152,14 @@ fn a_map_the_template_no_longer_has_is_ignored() { h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); } + +#[test] +fn each_row_names_its_own_map() { + let h = harness(); + + // The default template names its maps with $channel: each row shows the map it writes + assert!(h.query_all_by_label_contains("$channel").next().is_none(), "the channel variable is filled in"); + for id in ["baseColor", "metallic", "roughness"] { + assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); + } +} From 52e428300f9ff82f8d26be95c5511d16d51981b9 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:45:11 +0100 Subject: [PATCH 08/20] Describe the reference Output templates tab in the UI parity notes --- docs/ui-parity.md | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 3cb62522..49271c38 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -337,9 +337,30 @@ that numbers hide once a tile is under 40 points on screen. 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 Remove are greyed for built-in templates, which are read-only); F2 renames the selected one. - "+" creates "new_export_preset", Duplicate "_copy". *Naming pattern* (*OpenPBR*; the - reference's second pattern names another vendor's material and is left out) with its info - tooltip sits above the input maps. The middle reads "Current preset: ", *Output maps* - with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A, and a footer with drag-and-drop guidance and the number of output maps. TextureCraft keeps its - own list tools (rename, import, export) and asks before deleting; R+G+B and R+G+B+A create the - same maps as RGB and RGB+A (each channel takes its own source in either). + "+" creates "new_export_preset", Duplicate "_copy". The *Presets* row holds copy, "−" + and "+" without tooltips ([#789](https://github.com/storytold/texturecraft/issues/789)). + *Naming pattern* (*OpenPBR*; the reference's second pattern names another vendor's material and + is left out) with its info tooltip sits at the right end of the tab row; this tab has no + *Include all*, *Reset all* or texture count, and *Save settings* and *Export* are greyed. The + middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, + R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output + maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the + file name, "$" with the file name variables ($project, $mesh, $textureSet, $udim, $uvTileName + greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gray, RGB or R, G, B, + then A), the file type and bit depth lists ("8 bits + dithering" greyed: templates do not keep + it), duplicate and "×". Dropping a map on a swatch opens "From ": a gray map offers *Gray + Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G Channel*, *B Channel* + and *A Channel* (TextureCraft has no alpha or gray of a map yet: those are greyed). A colour + map dropped on the RGB swatch fills R, G and B at once. The swatch then takes the map's + colour, and the map lists mark the maps of the output map edited last with that colour. A + click on a swatch offers *Clear channel* and *Split/Collapse RGB*. The right side has the + *Input maps* pane, grouped as in the reference (Base, Specular, Transmission, Subsurface, + Coat, Fuzz/Sheen; then Emission, Geometry and Other for the channels the reference screenshot + cuts off), and a pane with *Mesh maps* above *Converted maps* (highlighted); maps TextureCraft + does not have yet are greyed and cannot be dragged. TextureCraft keeps a few things the + reference does not show, out of the way: Import and Export of template files at the end of a + preset's right-click menu, Invert in a swatch's right-click menu, *Move up* and *Move down* + in the grip's right-click menu (and the arrow keys on a focused grip), the planned file name + in the file name's tooltip, and three converted maps of its own (Normal from height, Roughness + from glossiness, Sheen color × weight) after the reference's. Built-in templates stay + read-only and deleting asks first. From 0642f1d29e421024ab42d2e454e42ef9d8ab67fa Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 23 Nov 2026 23:46:33 +0100 Subject: [PATCH 09/20] Output templates: shorter lines and a type alias for the map groups --- crates/ui-egui/src/export_templates.rs | 26 +++++++++++-------- .../ui-egui/src/export_templates/map_lists.rs | 15 ++++++++--- crates/ui-egui/src/export_window.rs | 3 ++- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 2e109a1c..73cf3bd4 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1069,7 +1069,9 @@ fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { let map = tr(map_lists::name_of(source)?); let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); match picked { - Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])), + Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => { + Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])) + } _ => Some(map.to_string()), } } @@ -1173,7 +1175,8 @@ fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[C let painter = ui.painter(); let border = if response.hovered() { tokens.accent } else { tokens.button_border }; painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, egui::FontId::proportional(SWATCH_TEXT_SIZE), tokens.text_strong); + let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; for (k, color) in bars.iter().enumerate() { @@ -1221,15 +1224,15 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> /// "From ": which channel of the dropped map the output channel reads. True when the map /// changed. fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { - let Some(drop) = pending.clone() else { return false }; - let Some(map) = maps.get_mut(drop.map) else { + let Some(waiting) = pending.clone() else { return false }; + let Some(map) = maps.get_mut(waiting.map) else { *pending = None; return false; }; - let name = map_lists::name_of(&drop.source).map_or_else(String::new, |name| tr(name).to_string()); + let name = map_lists::name_of(&waiting.source).map_or_else(String::new, |name| tr(name).to_string()); let mut picked = None; - let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(drop.position), ui.layer_id()) + let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) .kind(egui::PopupKind::Menu) .layout(egui::Layout::top_down_justified(egui::Align::Min)) .style(egui::containers::menu::menu_style) @@ -1237,7 +1240,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); - for (label, component) in source_choices(&drop.source) { + for (label, component) in source_choices(&waiting.source) { match component { Some(component) => { if ui.button(tr(label)).clicked() { @@ -1255,13 +1258,13 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } let Some(component) = picked else { return false }; - let source = with_component(&drop.source, component); + let source = with_component(&waiting.source, component); for (dest, channel_source) in &mut map.channels { - if drop.target.dests().contains(dest) { + if waiting.target.dests().contains(dest) { *channel_source = source.clone(); } } - *active = Some(drop.map); + *active = Some(waiting.map); true } @@ -1334,7 +1337,8 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co && let Some(at) = response.interact_pointer_pos() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)).show(ui.ctx(), |ui| chip(ui, name, true)); + let dragged = egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); + dragged.show(ui.ctx(), |ui| chip(ui, name, true)); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index 7690e805..1595c440 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -12,6 +12,9 @@ use crate::i18n::n_; /// One entry of a map list: its name and what it reads (None: not available yet). pub type MapEntry = (&'static str, Option); +/// A group of the Input maps pane: its name and entries. +pub type MapGroup = (&'static str, Vec); + fn channel(channel: Channel) -> Option { Some(SourceRef::Channel { channel, component: 0 }) } @@ -26,7 +29,7 @@ fn mesh(map: BakedMap) -> Option { /// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are /// cut off in the reference screenshots and use the OpenPBR names of the channels left over. -pub static INPUT_MAPS: LazyLock)>> = LazyLock::new(|| { +pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ ( n_("Base"), @@ -67,7 +70,11 @@ pub static INPUT_MAPS: LazyLock)>> = LazyLock:: ), ( n_("Fuzz/Sheen"), - vec![(n_("Fuzz weight"), channel(Channel::SheenWeight)), (n_("Fuzz color"), channel(Channel::SheenColor)), (n_("Fuzz roughness"), channel(Channel::SheenRoughness))], + vec![ + (n_("Fuzz weight"), channel(Channel::SheenWeight)), + (n_("Fuzz color"), channel(Channel::SheenColor)), + (n_("Fuzz roughness"), channel(Channel::SheenRoughness)), + ], ), (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), @@ -134,8 +141,8 @@ mod tests { #[test] fn every_channel_and_map_can_be_dragged() { - let listed: Vec = - INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()).filter_map(|(_, s)| s.clone()).collect(); + let entries = INPUT_MAPS.iter().flat_map(|(_, entries)| entries.iter()).chain(MESH_MAPS.iter()).chain(CONVERTED_MAPS.iter()); + let listed: Vec = entries.filter_map(|(_, source)| source.clone()).collect(); for channel in Channel::ALL { assert!(listed.contains(&SourceRef::Channel { channel, component: 0 }), "{channel:?}"); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3c3ae50a..f9088406 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1500,7 +1500,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Saving closes the window without starting an export - if ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))).on_hover_text(tr("Closes the export window and saves changes")).clicked() { + let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); + if save.on_hover_text(tr("Closes the export window and saves changes")).clicked() { app.ui.windows.export = false; } if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { From e4a377e5022c9a00b7223c3fd2945e92e937a32d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:24 +0100 Subject: [PATCH 10/20] Export textures: rows on the texture set page use the export's channel ids, the console strip drags and toggles, buttons 126 wide --- crates/formats/src/export/mod.rs | 3 +- crates/ui-egui/src/export_window.rs | 60 +++++++++++++++++------------ 2 files changed, 38 insertions(+), 25 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f92ebbb4..8c56e0e2 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -546,7 +546,8 @@ fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> out } -fn channel_label(map: &MapSpec) -> &'static str { +/// What `$channel` becomes in `map`'s file names: the id of its first non-constant source. +pub fn channel_label(map: &MapSpec) -> &'static str { map.channels .iter() .find_map(|(_, s)| match s { diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f9088406..c02948b1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -5,7 +5,7 @@ use egui::{RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::formats::{ExportPreset, FileFormat, MapSpec, SourceRef}; +use texturecraft_engine::formats::{ExportPreset, FileFormat}; use crate::TextureCraftApp; #[cfg(not(target_arch = "wasm32"))] @@ -51,7 +51,7 @@ const TAB_TEXT_SIZE: f32 = 12.5; const LIST_ROW_HEIGHT: f32 = 24.0; const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 125.0; +const FOOTER_BUTTON_WIDTH: f32 = 126.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -528,23 +528,16 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset.as_ref().and_then(|p| p.maps.get(map)).map(|m| m.file.replace("$channel", channel_id(m))).unwrap_or_default(); + let pattern = preset + .as_ref() + .and_then(|p| p.maps.get(map)) + .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) + .unwrap_or_default(); rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); } rows } -/// What `$channel` becomes in `map`'s file name: the id of its first map, as the export names it -fn channel_id(map: &MapSpec) -> &'static str { - let first = map.channels.iter().find_map(|(_, source)| match source { - SourceRef::Channel { channel, .. } => Some(channel.id()), - SourceRef::Virtual { map, .. } => Some(map.id()), - SourceRef::Baked { map, .. } => Some(map.id()), - SourceRef::Constant(_) => None, - }); - first.unwrap_or("constant") -} - /// The Output maps section of texture set `ts`'s page fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { let rows = map_rows(app, ts); @@ -1049,8 +1042,9 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor } } -/// Width of the LIST OF EXPORTS console +/// The LIST OF EXPORTS console's and file tree's least width, as in the reference const CONSOLE_WIDTH: f32 = 300.0; +const MIN_TREE_WIDTH: f32 = 300.0; /// Width of the strip between the file tree and the console const SPLITTER_WIDTH: f32 = 14.0; /// Padding of the CONSOLE header band, about 45 points high as in the reference @@ -1072,24 +1066,37 @@ fn success(tk: &Tokens) -> egui::Color32 { fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - let tree_width = ui.available_width() - if hidden { 24.0 } else { CONSOLE_WIDTH + 24.0 }; + + // Tree and console keep at least their reference width + let spacing = ui.spacing().item_spacing.x; + let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); + let tree_width = if hidden { room } else { room - console_width }; ui.vertical(|ui| { ui.set_width(tree_width); egui::ScrollArea::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); - // The thin toggle at the console's left edge, on a strip the whole height - let toggle = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let strip = egui::Rect::from_min_size(ui.cursor().min, vec2(SPLITTER_WIDTH, ui.available_height())); + // The strip at the console's left edge: a click hides or shows the console, a drag resizes it + let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); + let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; + let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); - let r = ui.add_sized(strip.size(), egui::Button::new(toggle).frame(false)); - let r = if hidden { r } else { r.on_hover_text(tr("Hide Console")) }; - if r.clicked() { + ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + let response = response.on_hover_text(tooltip); + if !hidden && (response.hovered() || response.dragged()) { + ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); + } + if response.dragged() && !hidden { + app.ui.export.console_width = (console_width - response.drag_delta().x).min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); + } else if response.clicked() { app.ui.export.console_hidden = !hidden; } if !hidden { ui.vertical(|ui| { - ui.set_width(CONSOLE_WIDTH); + ui.set_width(console_width); egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(caption(&tr("Console").to_uppercase()).strong()); @@ -1384,6 +1391,11 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } keep_file_type_visible(&mut app.ui.export); follow_texture_sets(app); + + // A map waiting for its source channel belongs to the OUTPUT TEMPLATES tab + if app.ui.export.tab != 1 { + app.ui.export.pending_drop = None; + } if app.ui.export.opened_with.is_none() { let mut now = app.ui.export.clone(); now.draft = None; @@ -1426,7 +1438,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } else if app.ui.export.tab == 1 { crate::export_templates::naming_pattern(ui); - } else if ui.button(tr("Include all")).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { + } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); From 36c6cd597e8ad1888a5d97d7b9a123f2d95019c0 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:31 +0100 Subject: [PATCH 11/20] Output templates: the reference's map lists, From popup, swatch texts and menus, row names and tooltips; narrow windows keep rows whole --- crates/ui-egui/src/export_templates.rs | 660 ++++++++++++------ .../ui-egui/src/export_templates/map_lists.rs | 61 +- .../ui-egui/src/export_templates/row_edit.rs | 2 - .../src/export_templates/source_pick.rs | 8 + .../src/export_templates/swatch_look.rs | 10 + crates/ui-egui/src/state.rs | 13 +- crates/ui-egui/tests/it/export_progress.rs | 13 +- crates/ui-egui/tests/it/output_templates.rs | 131 +++- crates/ui-egui/tests/it/template_invert.rs | 6 +- 9 files changed, 626 insertions(+), 278 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/source_pick.rs create mode 100644 crates/ui-egui/src/export_templates/swatch_look.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 73cf3bd4..79f713e0 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -22,19 +22,30 @@ mod map_drag; mod map_lists; mod pending_drop; mod row_edit; +mod source_pick; +mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; pub use pending_drop::PendingDrop; use row_edit::RowEdit; +use source_pick::SourcePick; +use swatch_look::SwatchLook; -const ICON: f32 = 20.0; -const LIST_WIDTH: f32 = 220.0; +const ICON_POINTS: f32 = 20.0; +/// Width of the Presets list +const LIST_WIDTH_POINTS: f32 = 220.0; +/// The tab's width in the reference-size window: a narrower window narrows the side panes in +/// proportion, so the output rows keep their room +const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; +/// The middle column's least width, and room for the separators and their spacing +const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; +const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; /// Width of the Input maps pane -const INPUTS_WIDTH: f32 = 170.0; +const INPUTS_WIDTH_POINTS: f32 = 170.0; /// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH: f32 = 165.0; +const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; /// Share of the side pane's height that Mesh maps take; Converted maps get the rest const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; @@ -42,35 +53,46 @@ const RENAME_ID: &str = "exp_rename"; const NEW_PRESET: &str = "new_export_preset"; /// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT: f32 = 18.0; -const PRESET_ICON_INDENT: f32 = 2.0; -const PRESET_TEXT_INDENT: f32 = 20.0; +const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; +const PRESET_ICON_INDENT_POINTS: f32 = 2.0; +const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; /// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT: f32 = 21.0; -const ENTRY_GAP: f32 = 2.0; -const ENTRY_TEXT_INDENT: f32 = 22.0; -const ENTRY_TEXT_SIZE: f32 = 12.0; -const MARKER_INDENT: f32 = 10.0; -const MARKER_SIZE: f32 = 10.0; +const ENTRY_HEIGHT_POINTS: f32 = 21.0; +const ENTRY_GAP_POINTS: f32 = 2.0; +const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; +const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; +const MARKER_INDENT_POINTS: f32 = 10.0; +const MARKER_SIZE_POINTS: f32 = 10.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; /// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN: f32 = 6.0; -const ROW_GAP: f32 = 4.0; -const GRIP_WIDTH: f32 = 5.0; -const NAME_FIELD_WIDTH: f32 = 150.0; -const ROW_ICON: f32 = 16.0; +const ROW_MARGIN_POINTS: f32 = 6.0; +const ROW_GAP_POINTS: f32 = 4.0; +const GRIP_WIDTH_POINTS: f32 = 5.0; +const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; +const ROW_ICON_POINTS: f32 = 16.0; +/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a +/// row's right end, and the gaps between a row's controls (besides the swatches') +const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; +const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; +const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; +const ROW_GAPS: f32 = 4.0; +/// The accent frame around a drop target: its stroke and its gap to the target +const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; +const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; +/// Side of the corner mark of an inverted swatch +const INVERTED_MARK_POINTS: f32 = 8.0; /// A channel swatch: its side, the label's size and offset from the top, and the bars that show /// which channels of the source it reads -const SWATCH_SIZE: f32 = 32.0; -const SWATCH_TEXT_SIZE: f32 = 11.0; -const SWATCH_TEXT_TOP: f32 = 3.0; -const SWATCH_BAR_WIDTH: f32 = 18.0; -const SWATCH_BAR_HEIGHT: f32 = 2.0; -const SWATCH_BAR_BOTTOM: f32 = 9.0; +const SWATCH_SIZE_POINTS: f32 = 32.0; +const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; +const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; +const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; +const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; +const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; /// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to /// keep the white label readable @@ -103,6 +125,17 @@ enum Layout { } impl Layout { + const ALL: [Layout; 4] = [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha]; + + fn label(self) -> &'static str { + match self { + Layout::Rgb => "RGB", + Layout::Rgba => "RGBA", + Layout::Gray => n_("Gray"), + Layout::GrayAlpha => n_("Gray + A"), + } + } + fn dests(self) -> &'static [Dest] { match self { Layout::Rgb => &[Dest::R, Dest::G, Dest::B], @@ -124,20 +157,25 @@ impl Layout { } /// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and -/// B show as separate swatches) -const CREATE: [(&str, Layout, bool); 5] = [ - (n_("Gray"), Layout::Gray, false), - ("RGB", Layout::Rgb, false), - ("R+G+B", Layout::Rgb, true), - ("RGB+A", Layout::Rgba, false), - ("R+G+B+A", Layout::Rgba, true), +/// B show as separate swatches, the new map's file name) +const CREATE: [(&str, Layout, bool, &str); 5] = [ + (n_("Gray"), Layout::Gray, false, "Grayscale"), + ("RGB", Layout::Rgb, false, "RGB"), + ("R+G+B", Layout::Rgb, true, "RGB"), + ("RGB+A", Layout::Rgba, false, "RGB Alpha"), + ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), ]; +/// The swatch right-click menu's constants: (label, value) +const CONSTANTS: [(&str, f32); 3] = [(n_("Black"), 0.0), (n_("Gray 50%"), 0.5), (n_("White"), 1.0)]; +/// How fast dragging changes a constant +const CONSTANT_DRAG_SPEED: f64 = 0.005; + /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; /// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH: f32 = 150.0; +const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -206,12 +244,23 @@ fn set_layout(map: &mut MapSpec, layout: Layout) { map.inverted = inverted; } -fn new_map(layout: Layout) -> MapSpec { - let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() }; +/// A new empty png / 8 bits output map named `file` +fn new_map(layout: Layout, file: &str) -> MapSpec { + let mut map = MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() }; set_layout(&mut map, layout); map } +/// `name`, or with "_1", "_2", ... when a map of `maps` already has it, as the reference names new rows +fn unique_file(maps: &[MapSpec], name: &str) -> String { + let taken = |file: &str| maps.iter().any(|map| map.file == file); + if !taken(name) { + return name.to_string(); + } + + (1..).map(|n| format!("{name}_{n}")).find(|file| !taken(file)).unwrap_or_else(|| name.to_string()) +} + /// An input map dropped on channel `dest`: a color or normal input dropped on R, G or B fills /// all three. fn drop_input(map: &mut MapSpec, dest: Dest, input: &SourceRef) { @@ -238,7 +287,6 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft_maps.clear(); e.draft_base = None; e.draft_split.clear(); - e.active_map = None; e.pending_drop = None; } Some(saved) => { @@ -247,7 +295,6 @@ fn sync_draft(app: &mut TextureCraftApp) { e.draft_maps = (0..saved.maps.len()).map(Some).collect(); e.draft_base = Some(saved.clone()); e.draft_split.clear(); - e.active_map = None; e.pending_drop = None; } else if e.draft_base.as_ref() != Some(saved) { // Match only unambiguous maps from the previous saved order @@ -274,9 +321,12 @@ pub use crate::ask::Ask; pub use crate::list_action::ListAction; enum MapAction { - /// A new output map with this layout, its R, G and B split or not - Add(Layout, bool), - Move { from: usize, to: usize }, + /// A new output map with this layout, its R, G and B split or not, and this file name + Add(Layout, bool, &'static str), + Move { + from: usize, + to: usize, + }, Duplicate(usize), Remove(usize), } @@ -287,32 +337,34 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { sync_draft(app); let height = ui.available_height(); let names = crate::export_window::template_groups(app, builtins).1; + let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); + let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); let mut list_action = None; ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); + ui.set_width(list_width); ui.set_height(height); list_action = preset_list(app, ui, &names); }); ui.separator(); ui.vertical(|ui| { // Leave room for the two map panes and three separators - let panes = INPUTS_WIDTH + SIDE_MAPS_WIDTH + 8.0 * ui.spacing().item_spacing.x + 6.0; - ui.set_width((ui.available_width() - panes).max(200.0)); + let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; + ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); ui.set_height(height); outputs(app, ui); }); - // The panes mark the sources of the output map edited last + // The panes mark the maps the selected template's outputs read let marked = marked_sources(app, &Tokens::get(ui.ctx())); ui.separator(); ui.vertical(|ui| { - ui.set_width(INPUTS_WIDTH); + ui.set_width(inputs_width); ui.set_height(height); input_maps(ui, &marked); }); ui.separator(); ui.vertical(|ui| { - ui.set_width(SIDE_MAPS_WIDTH); + ui.set_width(side_width); ui.set_height(height); mesh_and_converted_maps(ui, height, &marked); }); @@ -338,7 +390,7 @@ pub(crate) fn naming_pattern(ui: &mut Ui) { ui.label(tr("Select the naming pattern used to display the input maps on this page.")); ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } @@ -357,13 +409,14 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti // Copy, "−" and "+" from left to right, without tooltips as in the reference ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON).clicked() { + if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { act = Some(ListAction::New); } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON)).inner.clicked() { + if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() + { act = Some(ListAction::Remove(sel.clone())); } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON).clicked() { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { act = Some(ListAction::Duplicate(sel.clone())); } }); @@ -425,7 +478,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti /// the accent colour fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT), egui::Sense::click()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); let painter = ui.painter(); @@ -433,12 +486,12 @@ fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { painter.rect_filled(rect, tokens.radius, tokens.row_hover); } let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); + painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); let color = if selected { tokens.accent } else { tokens.text }; let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT, rect.center().y - galley.size().y / 2.0); + let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); painter.galley(top_left, galley, color); response } @@ -695,7 +748,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { let mut edit = RowEdit::default(); // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN).show(ui, |ui| { + egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); @@ -711,9 +764,9 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(caption(tr("Output maps"))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_enabled_ui(editable, |ui| { - for (label, layout, split) in CREATE.iter().rev() { + for (label, layout, split, file) in CREATE.iter().rev() { if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split)); + edit.action = Some(MapAction::Add(*layout, *split, file)); } } ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); @@ -729,7 +782,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { split.resize(map_count, false); // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN; + let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { ui.add_enabled_ui(editable, |ui| { for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { @@ -739,7 +792,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { None => tr("Not exported: no source in this texture set").to_string(), }; changed |= output_row(ui, index, map_count, map, row_split, &planned, &mut edit); - ui.add_space(ROW_GAP); + ui.add_space(ROW_GAP_POINTS); } }); }); @@ -748,7 +801,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Count only maps that have sources in the current set if let Ok(names) = &preview { let exported = names.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN).show(ui, |ui| { + egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); }); @@ -758,13 +811,12 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } // A drop asks for the source channel from the next frame on; one waiting from before shows now - let mut active = edit.touched.or(app.ui.export.active_map); let mut pending = app.ui.export.pending_drop.take(); if edit.pending.is_some() { pending = edit.pending.take(); ui.ctx().request_repaint(); } else { - changed |= source_channel_popup(ui, &mut pending, &mut preset.maps, &mut active); + changed |= source_channel_popup(ui, &mut pending, &mut preset.maps); } // Where each map came from in the saved template, moved along with the maps @@ -773,11 +825,11 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { origin = (0..map_count).map(Some).collect(); } let acted = match edit.action { - Some(MapAction::Add(layout, split_rgb)) => { - preset.maps.push(new_map(layout)); + Some(MapAction::Add(layout, split_rgb, file)) => { + let file = unique_file(&preset.maps, file); + preset.maps.push(new_map(layout, &file)); origin.push(None); split.push(split_rgb); - active = Some(map_count); true } Some(MapAction::Move { from, to }) if from < map_count && to < map_count && from != to => { @@ -787,7 +839,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { origin.insert(to, map_origin); let map_split = split.remove(from); split.insert(to, map_split); - active = Some(to); true } Some(MapAction::Duplicate(index)) if index < map_count => { @@ -797,7 +848,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { preset.maps.insert(index + 1, copy); origin.insert(index + 1, None); split.insert(index + 1, copy_split); - active = Some(index + 1); } true } @@ -805,7 +855,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { preset.maps.remove(index); origin.remove(index); split.remove(index); - active = None; true } _ => false, @@ -817,7 +866,6 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let e = &mut app.ui.export; e.draft_split = split; - e.active_map = active.filter(|index| *index < preset.maps.len()); e.pending_drop = pending; if acted || changed { commit(app, preset, origin); @@ -865,11 +913,17 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN).show(ui, |ui| { + let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { + // The name field gives way in a narrow window, so the swatches and lists stay in the row + let swatches = swatch_targets(map, *split).len() as f32; + let spacing = ui.spacing().item_spacing.x; + let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; + let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(NAME_FIELD_WIDTH)).on_hover_ui(|ui| { + let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { ui.label(tr("File name without extension; variables insert names")); ui.label(planned); }); @@ -878,10 +932,10 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: changed |= channel_swatches(ui, index, map, split, edit); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.vertical(|ui| { - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON).clicked() { + if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Duplicate(index)); } - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON).clicked() { + if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Remove(index)); } }); @@ -893,21 +947,15 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: }); }); - // Another row's grip dropped here moves that row to this place - // Check the payload type before taking it, so a map list drop is not lost + // Another row's grip dropped here moves that row here (the type check keeps a map list drop) let row = frame.response; let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); if row_dragged_over { - ui.painter().rect_stroke(row.rect, tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + drop_highlight(ui, row.rect, &tokens); } - if row_dragged_over - && let Some(from) = row.dnd_release_payload::() - { + if row_dragged_over && let Some(from) = row.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } - if changed { - edit.touched = Some(index); - } changed } @@ -916,15 +964,18 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { let tokens = Tokens::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH, SWATCH_SIZE), egui::Sense::click_and_drag()); + let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; ui.painter().rect_filled(rect, 1.0, color); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); + // Up and down arrows move the focused grip's map instead of the focus let mut to = None; if response.has_focus() { + let arrows = egui::EventFilter { vertical_arrows: true, ..Default::default() }; + ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, arrows)); if ui.input(|i| i.key_pressed(egui::Key::ArrowUp)) { to = index.checked_sub(1); } @@ -945,50 +996,54 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables, the reference's first, then TextureCraft's own +/// The "$" button: the reference's file name variables, then TextureCraft's own ($channel) fn token_menu(ui: &mut Ui, file: &mut String) -> bool { let mut changed = false; - ui.menu_button("$", |ui| { - let mut add = |ui: &mut Ui, token: &str, what: &str| { - if ui.button(RichText::new(token).monospace()).on_hover_text(what).clicked() { + let menu = ui.menu_button("$", |ui| { + let mut add = |ui: &mut Ui, token: &str| { + if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); changed = true; ui.close(); } }; for token in REFERENCE_TOKENS { - match FILE_TOKENS.iter().find(|(ours, _)| *ours == token) { - Some(&(token, what)) => add(ui, token, what), - None => { - ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); - } + if FILE_TOKENS.iter().any(|(ours, _)| *ours == token) { + add(ui, token); + } else { + ui.add_enabled(false, egui::Button::new(RichText::new(token).monospace())).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - for &(token, what) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { - add(ui, token, what); + for &(token, _) in FILE_TOKENS.iter().filter(|(token, _)| !REFERENCE_TOKENS.contains(token)) { + add(ui, token); } }); + menu.response.on_hover_text(tr("Add expressions in the path that will be replaced during export")); changed } /// The file type menu of an output map ("png˅") fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { let mut changed = false; - ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); continue; }; + // A new format starts at its default bit depth, as in the reference if ui.selectable_label(map.format == format, extension).clicked() { - changed |= map.format != format; - map.bit_depth = format.depth(map.bit_depth); - map.format = format; + if map.format != format { + map.bit_depth = format.default_depth(); + map.format = format; + changed = true; + } ui.close(); } } }); + menu.response.on_hover_text(tr("File format")); changed } @@ -997,7 +1052,7 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1009,21 +1064,40 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); + menu.response.on_hover_text(tr("Bit depth")); changed } -/// Whether R, G and B read one map as one RGB swatch can show it: a color map's R, G and B, or -/// the same gray map or constant in all three -fn rgb_collapsed(map: &MapSpec) -> bool { +/// R, G and B's sources, when the map has them +fn rgb_sources(map: &MapSpec) -> Option<[&SourceRef; 3]> { let get = |dest: Dest| map.channels.iter().find(|(d, _)| *d == dest).map(|(_, s)| s); - let (Some(red), Some(green), Some(blue)) = (get(Dest::R), get(Dest::G), get(Dest::B)) else { return true }; - - let one_map = same_source(red, green) && same_source(green, blue); - let spread = red.components() == 3 && [red, green, blue].into_iter().zip(0u8..).all(|(s, k)| component_of(s) == k); - one_map && (spread || red.components() == 1) + Some([get(Dest::R)?, get(Dest::G)?, get(Dest::B)?]) } -/// The swatches an output map shows: Gray, or RGB (R, G, B when split), then A when it has alpha +/// Whether R, G and B read one map (or one constant) and are inverted alike, so one RGB swatch +/// can stand for them +fn rgb_one_map(map: &MapSpec) -> bool { + let Some([red, green, blue]) = rgb_sources(map) else { return true }; + + let inverted = [Dest::R, Dest::G, Dest::B].map(|dest| map.inverted.contains(&dest)); + same_source(red, green) && same_source(green, blue) && inverted.iter().all(|on| *on == inverted[0]) +} + +/// Whether R, G and B read a colour map's R, G and B in that order +fn rgb_spread(map: &MapSpec) -> bool { + rgb_sources(map).is_some_and(|sources| sources.iter().zip(0u8..).all(|(source, k)| source.components() == 3 && component_of(source) == k)) +} + +/// Whether one RGB swatch shows R, G and B: one map, read as its R, G and B or as one channel in +/// all three +fn rgb_collapsed(map: &MapSpec) -> bool { + let Some(sources) = rgb_sources(map) else { return true }; + + let one_component = sources.iter().all(|source| component_of(source) == component_of(sources[0])); + rgb_one_map(map) && (rgb_spread(map) || one_component) +} + +/// The swatches an output map shows: Gr, or RGB (R, G, B when split), then A when it has alpha fn swatch_targets(map: &MapSpec, split: bool) -> Vec { let layout = Layout::of(map); let mut targets = match layout { @@ -1037,7 +1111,7 @@ fn swatch_targets(map: &MapSpec, split: bool) -> Vec { targets } -/// The label on a swatch +/// The letters on a swatch, as in the reference fn target_label(target: ChannelTarget) -> &'static str { match target { ChannelTarget::Rgb => "RGB", @@ -1045,7 +1119,7 @@ fn target_label(target: ChannelTarget) -> &'static str { ChannelTarget::One(Dest::G) => "G", ChannelTarget::One(Dest::B) => "B", ChannelTarget::One(Dest::A) => "A", - ChannelTarget::One(Dest::L) => tr("Gray"), + ChannelTarget::One(Dest::L) => "Gr", } } @@ -1055,24 +1129,71 @@ fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) } -/// The source channel choices of "From ": (label, the component read; None: not available yet) -fn source_choices(source: &SourceRef) -> Vec<(&'static str, Option)> { - if source.components() == 3 { - vec![(n_("Gray Channel"), None), (n_("R Channel"), Some(0)), (n_("G Channel"), Some(1)), (n_("B Channel"), Some(2)), (n_("A Channel"), None)] - } else { - vec![(n_("Gray Channel"), Some(0)), (n_("A Channel"), None)] +/// The choices of "From " in the reference order: "RGB Channels" only for a colour map on +/// the RGB swatch; None marks a choice TextureCraft cannot read yet (a map's gray or alpha) +fn source_choices(source: &SourceRef, target: ChannelTarget) -> Vec<(&'static str, Option)> { + if source.components() != 3 { + return vec![(n_("Gray Channel"), Some(SourcePick::Component(0))), (n_("A Channel"), None)]; + } + + let mut choices = Vec::new(); + if target == ChannelTarget::Rgb { + choices.push((n_("RGB Channels"), Some(SourcePick::AllRgb))); + } + choices.extend([ + (n_("Gray Channel"), None), + (n_("R Channel"), Some(SourcePick::Component(0))), + (n_("G Channel"), Some(SourcePick::Component(1))), + (n_("B Channel"), Some(SourcePick::Component(2))), + (n_("A Channel"), None), + ]); + choices +} + +/// Fill the swatch `target` from `source` as `pick` says +fn apply_pick(map: &mut MapSpec, target: ChannelTarget, source: &SourceRef, pick: SourcePick) { + for (dest, channel_source) in &mut map.channels { + if !target.dests().contains(dest) { + continue; + } + + let component = match pick { + SourcePick::AllRgb => slot_component(*dest), + SourcePick::Component(component) => component, + }; + *channel_source = with_component(source, component); } } -/// A source as a swatch names it: the map, and for one channel of a color map that channel -fn source_name(source: &SourceRef, target: ChannelTarget) -> Option { - let map = tr(map_lists::name_of(source)?); - let picked = source_choices(source).into_iter().find(|(_, component)| *component == Some(component_of(source))); - match picked { - Some((channel, _)) if source.components() == 3 && target != ChannelTarget::Rgb => { - Some(trf("{map} ({channel})", &[("map", &map), ("channel", &tr(channel))])) +/// The channel of the source a swatch reads, as the reference's swatch tooltip names it +fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> &'static str { + if source.components() != 3 { + return n_("Grayscale"); + } + + if target == ChannelTarget::Rgb && rgb_spread(map) { + return "RGB"; + } + + match component_of(source) { + 0 => n_("Red"), + 1 => n_("Green"), + _ => n_("Blue"), + } +} + +/// A swatch's tooltip in the reference's words: "Default black" or "Default white" when empty, +/// else " ()"; another constant (TextureCraft's own) gives its value +fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { + let alpha = target == ChannelTarget::One(Dest::A); + match source { + SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Default white").to_string(), + SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Default black").to_string(), + SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), + _ => { + let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); + trf("{map} ({channel})", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) } - _ => Some(map.to_string()), } } @@ -1091,19 +1212,19 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) } -/// The bars under a swatch's label: R, G and B for a color map on the RGB swatch, else the one -/// channel read -fn swatch_bars(source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { +/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one +/// channel read (white for gray) +fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { match source { SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb => COMPONENT_COLORS.to_vec(), + _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), _ => vec![tokens.text_strong], } } -/// An output map's channel swatches: drop targets for the map lists; a click opens Clear channel -/// and Split/Collapse RGB, a right click Invert +/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel +/// (and Split/Collapse RGB on R, G, B), a right click TextureCraft's own tools. fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; @@ -1112,25 +1233,27 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let Some(source) = source_of(map, target).cloned() else { continue }; let label = target_label(target); - let name = match source_name(&source, target) { - Some(source) => trf("{channel}: {map}", &[("channel", &label), ("map", &source)]), - None => label.to_string(), - }; - let response = swatch(ui, label, &name, source_color(&source, &tokens), &swatch_bars(&source, target, &tokens)).on_hover_text(&name); + let inverted = target.dests().iter().all(|dest| map.inverted.contains(dest)); + let tooltip = swatch_tooltip(map, &source, target); + let mut name = trf("{channel}: {tooltip}", &[("channel", &label), ("tooltip", &tooltip)]); + if inverted { + name = trf("{swatch}, inverted", &[("swatch", &name)]); + } + let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; + let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + ui.label(&tooltip); + if inverted { + ui.label(tr("Inverted")); + } + }); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - ui.painter().rect_stroke(response.rect.expand(2.0), tokens.radius, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Outside); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { - edit.touched = Some(index); - if target == ChannelTarget::Rgb && input.components() == 3 { - drop_input(map, Dest::R, &input); - changed = true; - } else { - edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); - } + edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); } let rgb = matches!(target, ChannelTarget::Rgb | ChannelTarget::One(Dest::R | Dest::G | Dest::B)); @@ -1139,66 +1262,122 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if ui.button(tr("Clear channel")).clicked() { clear_channel(map, target); changed = true; - edit.touched = Some(index); } - if rgb && ui.button(tr("Split/Collapse RGB")).clicked() { - changed |= split_or_collapse(map, split, shows_split); - edit.touched = Some(index); - } - }); - - // Not in the reference's menu: inverting stays on the right click - response.context_menu(|ui| { - let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); - if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { - map.inverted.retain(|dest| !target.dests().contains(dest)); - if !on { - map.inverted.extend_from_slice(target.dests()); + if rgb { + // Collapsing would drop maps that R, G and B read differently + let mut checked = shows_split; + let can_toggle = !shows_split || rgb_one_map(map); + let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Split/Collapse RGB"))); + let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to collapse")); + if item.changed() { + changed |= split_or_collapse(map, split, shows_split); } - changed = true; - edit.touched = Some(index); - ui.close(); } }); + response.context_menu(|ui| changed |= swatch_extras_menu(ui, map, target)); } changed } +/// TextureCraft's own swatch tools on the right click (the reference has none there): invert, +/// constants and the output map's channel layout. True when the map changed. +fn swatch_extras_menu(ui: &mut Ui, map: &mut MapSpec, target: ChannelTarget) -> bool { + let mut changed = false; + let on = target.dests().iter().all(|dest| map.inverted.contains(dest)); + if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { + map.inverted.retain(|dest| !target.dests().contains(dest)); + if !on { + map.inverted.extend_from_slice(target.dests()); + } + changed = true; + ui.close(); + } + ui.separator(); + for (label, value) in CONSTANTS { + if ui.button(tr(label)).clicked() { + set_constant(map, target, value); + changed = true; + ui.close(); + } + } + if let Some(SourceRef::Constant(mut value)) = source_of(map, target).cloned() { + let constant = egui::DragValue::new(&mut value).range(0.0..=1.0).speed(CONSTANT_DRAG_SPEED).fixed_decimals(2); + if ui.add(constant).changed() { + set_constant(map, target, value); + changed = true; + } + } + ui.separator(); + ui.menu_button(tr("Layout"), |ui| { + let current = Layout::of(map); + for layout in Layout::ALL { + if ui.selectable_label(layout == current, tr(layout.label())).clicked() && layout != current { + set_layout(map, layout); + changed = true; + ui.close(); + } + } + }); + changed +} + +/// The swatch's channels write the constant `value` +fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { + for (dest, source) in &mut map.channels { + if target.dests().contains(dest) { + *source = SourceRef::Constant(value); + } + } +} + +/// The accent frame around a drop target under a dragged map or row +fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { + ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +} + /// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads -fn swatch(ui: &mut Ui, label: &str, name: &str, fill: Option, bars: &[Color32]) -> egui::Response { +/// channels it reads, a corner mark when inverted +fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { let tokens = Tokens::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE, SWATCH_SIZE), egui::Sense::click()); + let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); let painter = ui.painter(); let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH / bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH / 2.0; - for (k, color) in bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT)), 0.0, *color); + painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); + painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); + let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; + let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; + for (k, color) in look.bars.iter().enumerate() { + let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); + painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + } + if look.inverted { + let corner = rect.right_top(); + let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; + painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); } response } -/// Clear channel: the swatch's channels write black, or opaque alpha +/// Clear channel: the swatch is empty again ("Default black", "Default white" for alpha), not +/// inverted fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { for (dest, source) in &mut map.channels { if target.dests().contains(dest) { *source = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); } } + map.inverted.retain(|dest| !target.dests().contains(dest)); } -/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones collapse into one RGB -/// swatch reading R's map. True when the map changed. +/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones that read one map collapse +/// into one RGB swatch reading that map's R, G and B. R, G and B reading different maps stay split, +/// so no map is dropped. True when the map changed. fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { - if !shows_split { + if !shows_split || !rgb_one_map(map) { *split = true; return false; } @@ -1221,9 +1400,9 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> true } -/// "From ": which channel of the dropped map the output channel reads. True when the map -/// changed. -fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec], active: &mut Option) -> bool { +/// "From ": which channel of the dropped map the swatch reads; Escape or a click elsewhere +/// assigns nothing. True when the map changed. +fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec]) -> bool { let Some(waiting) = pending.clone() else { return false }; let Some(map) = maps.get_mut(waiting.map) else { *pending = None; @@ -1232,7 +1411,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ let name = map_lists::name_of(&waiting.source).map_or_else(String::new, |name| tr(name).to_string()); let mut picked = None; - let shown = egui::Popup::new(egui::Id::new("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) + let shown = egui::Popup::new(egui::Id::unique("exp_source_channel"), ui.ctx().clone(), egui::PopupAnchor::Position(waiting.position), ui.layer_id()) .kind(egui::PopupKind::Menu) .layout(egui::Layout::top_down_justified(egui::Align::Min)) .style(egui::containers::menu::menu_style) @@ -1240,11 +1419,11 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); - for (label, component) in source_choices(&waiting.source) { - match component { - Some(component) => { + for (label, pick) in source_choices(&waiting.source, waiting.target) { + match pick { + Some(pick) => { if ui.button(tr(label)).clicked() { - picked = Some(component); + picked = Some(pick); } } None => { @@ -1253,27 +1432,23 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ } } }); - if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + // The app can consume Escape before the popup sees it, so read the raw event + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if picked.is_some() || escaped || shown.is_none_or(|menu| menu.response.should_close()) { *pending = None; } - let Some(component) = picked else { return false }; + let Some(pick) = picked else { return false }; - let source = with_component(&waiting.source, component); - for (dest, channel_source) in &mut map.channels { - if waiting.target.dests().contains(dest) { - *channel_source = source.clone(); - } - } - *active = Some(waiting.map); + apply_pick(map, waiting.target, &waiting.source, pick); true } -/// The sources of the output map edited last, with their colours, for the panes' markers +/// The maps the selected template's outputs read, with their colours, for the panes' markers fn marked_sources(app: &TextureCraftApp, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { - let Some(index) = app.ui.export.active_map else { return Vec::new() }; - let Some(map) = app.ui.export.draft.as_ref().and_then(|draft| draft.maps.get(index)) else { return Vec::new() }; + let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; - map.channels.iter().filter_map(|(_, source)| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); + sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() } /// The Input maps pane: the input maps in their groups @@ -1315,17 +1490,27 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co let tokens = Tokens::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT), sense); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP / 2.0)); + let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); if let Some(color) = marker { - painter.rect_filled(egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT, 0.0), egui::Vec2::splat(MARKER_SIZE)), 1.0, color); + painter.rect_filled( + egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), + 1.0, + color, + ); } let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text(row.left_center() + vec2(ENTRY_TEXT_INDENT, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(ENTRY_TEXT_SIZE), color); + painter.text( + row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), + egui::Align2::LEFT_CENTER, + name, + egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), + color, + ); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; @@ -1337,7 +1522,7 @@ fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Co && let Some(at) = response.interact_pointer_pos() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); - let dragged = egui::Area::new(egui::Id::new(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); + let dragged = egui::Area::new(egui::Id::unique(("exp_map_drag", name))).order(egui::Order::Tooltip).fixed_pos(at + vec2(8.0, 8.0)); dragged.show(ui.ctx(), |ui| chip(ui, name, true)); } } @@ -1352,7 +1537,7 @@ mod tests { #[test] fn layouts_keep_sources_and_drops_fill_rgb() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); drop_input(&mut map, Dest::G, &ch(Channel::BaseColor, 0)); assert_eq!(map.channels, vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 1)), (Dest::B, ch(Channel::BaseColor, 2))]); drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0)); @@ -1365,7 +1550,7 @@ mod tests { set_layout(&mut map, Layout::Rgb); assert_eq!(map.channels.get(1), Some(&(Dest::G, ch(Channel::BaseColor, 1))), "gray to RGB spreads a color source"); for l in [Layout::Rgb, Layout::Rgba, Layout::Gray, Layout::GrayAlpha] { - let m = new_map(l); + let m = new_map(l, "t"); assert_eq!(Layout::of(&m), l); ExportPreset { name: "t".into(), maps: vec![m] }.validate().unwrap(); } @@ -1375,7 +1560,7 @@ mod tests { #[test] fn inversion_follows_its_source_through_layouts_and_drops() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); map.inverted = vec![Dest::R]; set_layout(&mut map, Layout::Gray); assert_eq!(map.inverted, vec![Dest::L], "the colour source keeps its inversion on L"); @@ -1386,7 +1571,7 @@ mod tests { map.inverted = vec![Dest::G]; set_layout(&mut map, Layout::GrayAlpha); assert!(map.inverted.is_empty(), "channels that leave take their inversion with them"); - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); map.inverted = vec![Dest::B]; drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0)); assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list"); @@ -1395,40 +1580,83 @@ mod tests { #[test] fn split_and_collapse_keep_r_g_b_on_one_or_three_swatches() { - let mut map = new_map(Layout::Rgb); + let mut map = new_map(Layout::Rgb, "t"); let mut split = false; assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb], "an empty RGB map shows one swatch"); assert!(!split_or_collapse(&mut map, &mut split, false), "splitting changes only the view"); assert_eq!(swatch_targets(&map, split).len(), 3); - map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.0))]; + map.channels = vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 0)), (Dest::B, ch(Channel::BaseColor, 1))]; assert!(split_or_collapse(&mut map, &mut split, true)); assert_eq!(swatch_targets(&map, split), vec![ChannelTarget::Rgb]); - assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing spreads R's color map over R, G and B"); - - map.channels = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; - assert_eq!(swatch_targets(&map, false).len(), 3, "different maps in R, G and B show split even when not asked to"); + assert_eq!(map.channels.get(2), Some(&(Dest::B, ch(Channel::BaseColor, 2))), "collapsing reads the map's R, G and B"); } #[test] - fn clear_channel_writes_black_or_opaque_alpha() { - let mut map = new_map(Layout::Rgba); + fn r_g_b_reading_different_maps_or_inverted_apart_stay_split() { + let differing = vec![(Dest::R, ch(Channel::Roughness, 0)), (Dest::G, ch(Channel::Metallic, 0)), (Dest::B, SourceRef::Constant(0.5))]; + let mut map = new_map(Layout::Rgb, "t"); + map.channels = differing.clone(); + let mut split = true; + + assert!(!split_or_collapse(&mut map, &mut split, true), "collapsing would drop maps"); + + assert_eq!(map.channels, differing); + assert_eq!(swatch_targets(&map, split).len(), 3); + let mut color = new_map(Layout::Rgb, "t"); + drop_input(&mut color, Dest::R, &ch(Channel::BaseColor, 0)); + color.inverted = vec![Dest::G]; + assert_eq!(swatch_targets(&color, false).len(), 3, "one map inverted in G only shows R, G and B apart"); + } + + #[test] + fn clear_channel_empties_the_swatch_and_its_inversion() { + let mut map = new_map(Layout::Rgba, "t"); drop_input(&mut map, Dest::R, &ch(Channel::BaseColor, 0)); drop_input(&mut map, Dest::A, &ch(Channel::Opacity, 0)); + map.inverted = vec![Dest::R, Dest::G, Dest::B, Dest::A]; clear_channel(&mut map, ChannelTarget::Rgb); clear_channel(&mut map, ChannelTarget::One(Dest::A)); let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); + assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Default black"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Default white"); } #[test] - fn a_gray_map_offers_its_gray_channel_and_a_color_map_its_r_g_b() { - let offered = |source: &SourceRef| source_choices(source).into_iter().filter_map(|(label, component)| component.map(|_| label)).collect::>(); + fn the_from_popup_offers_the_reference_choices() { + let offered = |source: &SourceRef, target| source_choices(source, target).into_iter().map(|(label, pick)| (label, pick.is_some())).collect::>(); - assert_eq!(offered(&ch(Channel::Metallic, 0)), ["Gray Channel"]); - assert_eq!(offered(&ch(Channel::BaseColor, 0)), ["R Channel", "G Channel", "B Channel"]); + assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray Channel", true), ("A Channel", false)]); + let color_on_gray = [("Gray Channel", false), ("R Channel", true), ("G Channel", true), ("B Channel", true), ("A Channel", false)]; + assert_eq!(offered(&ch(Channel::BaseColor, 0), ChannelTarget::One(Dest::L)), color_on_gray); + let color_on_rgb = offered(&ch(Channel::BaseColor, 0), ChannelTarget::Rgb); + assert_eq!(color_on_rgb.first(), Some(&("RGB Channels", true)), "only the RGB swatch offers RGB Channels"); + assert_eq!(color_on_rgb.get(1..), Some(color_on_gray.as_slice())); + } + + #[test] + fn rgb_channels_fill_r_g_b_and_one_channel_fills_every_swatch_channel() { + let mut map = new_map(Layout::Rgb, "t"); + + apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); + assert!(rgb_spread(&map)); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (RGB)"); + + apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); + assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (Red)"); + } + + #[test] + fn new_rows_take_the_reference_names_with_a_number_when_taken() { + let maps = vec![new_map(Layout::Rgb, "RGB"), new_map(Layout::Rgb, "RGB_1")]; + + assert_eq!(unique_file(&maps, "Grayscale"), "Grayscale"); + assert_eq!(unique_file(&maps, "RGB"), "RGB_2"); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index 1595c440..afe9e2aa 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -27,8 +27,15 @@ fn mesh(map: BakedMap) -> Option { Some(SourceRef::Baked { map, component: 0 }) } -/// Input maps in groups, as the reference lists them up to Fuzz/Sheen; the groups after it are -/// cut off in the reference screenshots and use the OpenPBR names of the channels left over. +/// The reference's user channels, listed greyed: TextureCraft has no user channels yet +const USER_CHANNELS: [&str; 32] = [ + "User0", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10", "User11", "User12", "User13", "User14", "User15", + "User16", "User17", "User18", "User19", "User20", "User21", "User22", "User23", "User24", "User25", "User26", "User27", "User28", "User29", "User30", + "User31", +]; + +/// Input maps in the reference's groups and order (naming pattern OpenPBR); entries without a +/// TextureCraft channel are listed greyed. pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ ( @@ -36,7 +43,7 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ (n_("Base weight"), None), (n_("Base color"), channel(Channel::BaseColor)), - (n_("Base metalness"), channel(Channel::Metallic)), + (n_("Metallic"), channel(Channel::Metallic)), (n_("Base diffuse roughness"), None), ], ), @@ -44,22 +51,19 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { n_("Specular"), vec![ (n_("Specular weight"), None), - (n_("Specular color"), None), - (n_("Specular roughness"), channel(Channel::Roughness)), + (n_("Specular edge color"), None), + (n_("Roughness"), channel(Channel::Roughness)), (n_("Specular level"), channel(Channel::SpecularLevel)), - (n_("Specular anisotropy"), channel(Channel::AnisotropyLevel)), + (n_("Anisotropy level"), channel(Channel::AnisotropyLevel)), (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), ], ), - (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Transmission color"), None)]), - ( - n_("Subsurface"), - vec![(n_("Subsurface weight"), channel(Channel::ScatterWeight)), (n_("Subsurface color"), None), (n_("Subsurface radius scale"), None)], - ), + (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Absorption color"), None)]), + (n_("Subsurface"), vec![(n_("Translucency"), None), (n_("Scattering color"), None), (n_("Scattering"), channel(Channel::ScatterWeight))]), ( n_("Coat"), vec![ - (n_("Coat weight"), channel(Channel::CoatWeight)), + (n_("Coat opacity"), channel(Channel::CoatWeight)), (n_("Coat color"), None), (n_("Coat roughness"), channel(Channel::CoatRoughness)), (n_("Coat anisotropy"), None), @@ -71,22 +75,37 @@ pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { ( n_("Fuzz/Sheen"), vec![ - (n_("Fuzz weight"), channel(Channel::SheenWeight)), - (n_("Fuzz color"), channel(Channel::SheenColor)), - (n_("Fuzz roughness"), channel(Channel::SheenRoughness)), + (n_("Sheen opacity"), channel(Channel::SheenWeight)), + (n_("Sheen color"), channel(Channel::SheenColor)), + (n_("Sheen roughness"), channel(Channel::SheenRoughness)), ], ), - (n_("Emission"), vec![(n_("Emission color"), channel(Channel::Emissive))]), - (n_("Geometry"), vec![(n_("Geometry opacity"), channel(Channel::Opacity)), (n_("Geometry normal"), channel(Channel::Normal))]), + (n_("Emission"), vec![(n_("Emissive"), channel(Channel::Emissive))]), + (n_("Thin-film"), vec![(n_("Thin-film weight"), None)]), ( - n_("Other"), + n_("Geometry"), vec![ + (n_("Opacity"), channel(Channel::Opacity)), (n_("Height"), channel(Channel::Height)), + (n_("Normal"), channel(Channel::Normal)), + (n_("Tangent"), None), (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), - (n_("Specular"), channel(Channel::Specular)), - (n_("Glossiness"), channel(Channel::Glossiness)), ], ), + ( + n_("Miscellaneous"), + vec![ + (n_("Blending mask"), None), + (n_("Diffuse"), None), + (n_("Displacement"), None), + (n_("Glossiness"), channel(Channel::Glossiness)), + ("Ior", None), + (n_("Reflection"), None), + (n_("Specular"), channel(Channel::Specular)), + (n_("Transmissive"), None), + ], + ), + (n_("User Channels"), USER_CHANNELS.iter().map(|name| (*name, None)).collect()), ] }); @@ -106,7 +125,7 @@ pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { ] }); -/// Converted maps in the reference order, then the ones only TextureCraft has (templates use them). +/// Converted maps in the reference order, then the ones only TextureCraft has (built-in templates use them). pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { vec![ ("1/ior", None), diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index e813e574..6568dac9 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,6 +6,4 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, - /// The row edited last. - pub(super) touched: Option, } diff --git a/crates/ui-egui/src/export_templates/source_pick.rs b/crates/ui-egui/src/export_templates/source_pick.rs new file mode 100644 index 00000000..89dc4769 --- /dev/null +++ b/crates/ui-egui/src/export_templates/source_pick.rs @@ -0,0 +1,8 @@ +/// What a "From " choice reads from the dropped map. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SourcePick { + /// "RGB Channels": the map's R, G and B into the swatch's R, G and B. + AllRgb, + /// One component of the map in every channel of the swatch. + Component(u8), +} diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs new file mode 100644 index 00000000..99d81b19 --- /dev/null +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -0,0 +1,10 @@ +use egui::Color32; + +/// How a channel swatch is drawn. +pub(super) struct SwatchLook { + /// The source map's colour (None: empty or a constant). + pub(super) fill: Option, + /// One bar per channel of the source the swatch reads. + pub(super) bars: Vec, + pub(super) inverted: bool, +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89cb751a..5acd63cf 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -391,9 +391,9 @@ pub struct ExportUi { /// channel swatches (R+G+B) instead of one RGB swatch. #[serde(skip)] pub draft_split: Vec, - /// Output templates tab: the output map edited last; the map lists mark its sources. - #[serde(skip)] - pub active_map: Option, + /// LIST OF EXPORTS: the console's width, set by dragging the strip at its left edge. + #[serde(skip, default = "default_console_width")] + pub console_width: f32, /// Output templates tab: a map dropped on an output channel, waiting for the source channel /// ("From "). #[serde(skip)] @@ -444,7 +444,7 @@ impl Default for ExportUi { draft_maps: Vec::new(), draft_base: None, draft_split: Vec::new(), - active_map: None, + console_width: default_console_width(), pending_drop: None, renaming: None, rename_key: false, @@ -457,6 +457,11 @@ impl Default for ExportUi { } } +/// The LIST OF EXPORTS console's width when the window opens, as in the reference +fn default_console_width() -> f32 { + 300.0 +} + fn default_export_dir() -> String { #[cfg(not(target_arch = "wasm32"))] { diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 46cee48f..5210742a 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -139,14 +139,13 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { h.run_steps(30); assert!(h.query_by_label(&dir.join(&file).display().to_string()).is_some()); - // The console's toggle hides it - let toggle = h.get_by_label(egui_phosphor::regular::CARET_DOUBLE_RIGHT).rect().center(); - h.hover_at(toggle); - h.run_steps(30); - assert!(h.query_by_label("Hide Console").is_some()); - click(&mut h, egui_phosphor::regular::CARET_DOUBLE_RIGHT); - h.run_steps(2); + // The strip at the console's edge hides it, then shows it again + h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); + h.run_steps(4); assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); + h.run_steps(4); + assert!(!h.state().ui.export.console_hidden); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 53c5daa1..2b888752 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -68,8 +68,7 @@ fn hover_name_field(h: &mut Harness<'_, TextureCraftApp>, index: usize) { /// The last button labelled `label` in the window (the newest output map's swatch) fn last_window_button<'h>(h: &'h Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'h> { h.get_all_by_role(egui::Role::Button) - .filter(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) - .last() + .rfind(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some(label)) .unwrap_or_else(|| panic!("no {label} button")) } @@ -191,9 +190,12 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show"); + let plan = h.state_mut().run("export.plan", json!({"preset": "Two", "ts": ts})).unwrap(); for index in 0..2 { + let file = plan.as_array().unwrap().iter().find(|f| f["map"] == index).unwrap()["file"].as_str().unwrap().to_string(); hover_name_field(&mut h, index); - assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).next().is_some(), "map {index} shows its file"); + let planned = format!("{} {file}", egui_phosphor::regular::ARROW_RIGHT); + assert!(h.query_all_by_label(&planned).next().is_some(), "map {index} shows its own file {file}"); } } @@ -346,11 +348,8 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label_contains("textures selected for export").is_none()); for greyed in ["Save settings", "Export"] { // The rail at the right edge has an Export button of its own - let button = h - .get_all_by_role(egui::Role::Button) - .filter(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)) - .last() - .unwrap(); + let button = + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); assert!(button.accesskit_node().is_disabled(), "{greyed}"); } assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); @@ -382,23 +381,24 @@ fn the_map_lists_stand_in_three_panes_with_the_reference_names() { let h = harness(&library); let input = h.get_by_label("Input maps").rect(); - let mesh = h.get_by_label("Mesh maps").rect(); + // A built-in template is called "Mesh maps" too: the pane's title comes after the Presets list + let mesh = h.get_all_by_label("Mesh maps").last().unwrap().rect(); let converted = h.get_by_label("Converted maps").rect(); assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Base", "Transmission", "Subsurface", "Coat", "Fuzz/Sheen"] { + for group in ["Transmission", "Subsurface", "Fuzz/Sheen", "Thin-film", "Miscellaneous", "User Channels"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Base metalness", "Specular roughness", "Coat normal", "Fuzz weight", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + for name in ["Specular level", "Sheen opacity", "Coat normal", "Emissive", "World space normal", "Bent normals", "Normal DirectX", "f0"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "1/ior", "Glossiness²", "2D View"] { + for name in ["Base weight", "Coat tangent", "Thin-film weight", "User31", "1/ior", "Glossiness²", "2D View"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } - for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal"] { + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal", "Emission color", "Other"] { assert!(h.query_by_label(gone).is_none(), "{gone}"); } } @@ -410,10 +410,11 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { click(&mut h, "R+G+B+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let green = last_window_button(&h, "G").rect().center(); + let green = last_window_button(&h, "G: Default black").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); + assert!(h.query_by_label("RGB Channels").is_none(), "only the RGB swatch offers RGB Channels"); for choice in ["R Channel", "G Channel", "B Channel"] { assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); } @@ -426,23 +427,72 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); - assert!(h.query_all_by_label("G: Base color (B Channel)").next().is_some(), "the swatch names its map"); - assert_eq!(h.state().ui.export.active_map, Some(last), "the lists mark this map's sources"); + assert!(h.query_all_by_label("G: Base color (Blue)").next().is_some(), "the swatch names its map and channel"); } #[test] -fn a_gray_map_dropped_on_a_channel_offers_its_gray_channel() { - let library = TemplateLibrary::new("drop-gray"); +fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { + let library = TemplateLibrary::new("drop-rgb"); let mut h = harness(&library); - click(&mut h, "R+G+B+A"); + click(&mut h, "RGB+A"); + let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let alpha = last_window_button(&h, "A").rect().center(); - drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, alpha); + let rgb = last_window_button(&h, "RGB: Default black").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, rgb); + h.get_by_label("RGB Channels").click(); + h.run_steps(4); - assert!(h.query_by_label("From Base metalness").is_some()); + let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); + let spread: Vec<_> = (0..3).map(|component| SourceRef::Channel { channel: Channel::BaseColor, component }).collect(); + assert_eq!(map.channels.iter().take(3).map(|(_, source)| source.clone()).collect::>(), spread); + assert!(h.query_all_by_label("RGB: Base color (RGB)").next().is_some()); +} + +#[test] +fn escape_closes_the_from_popup_without_assigning() { + let library = TemplateLibrary::new("drop-escape"); + let mut h = harness(&library); + click(&mut h, "Gray"); + let before = h.state().session.export_preset("Mine").unwrap(); + + let gray = last_window_button(&h, "Gr: Default black").rect().center(); + drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, gray); + assert!(h.query_by_label("From Metallic").is_some()); assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("From Metallic").is_none(), "Escape closes the popup"); + assert!(h.state().ui.export.pending_drop.is_none()); + assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); +} + +#[test] +fn dragging_a_grip_onto_another_row_moves_that_map_there() { + let library = TemplateLibrary::new("grip-drag"); + let mut h = harness(&library); + let files = |h: &Harness<'_, TextureCraftApp>| h.state().session.export_preset("Mine").unwrap().maps.iter().map(|m| m.file.clone()).collect::>(); + let before = files(&h); + + let from = h.get_all_by_label("Reorder").last().unwrap().rect().center(); + let to = h.get_all_by_label("Reorder").next().unwrap().rect().center(); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(2); + for step in 1..=4 { + h.hover_at(from + (to - from) * (step as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(4); + + let mut expected = before.clone(); + let moved = expected.pop().unwrap(); + expected.insert(0, moved); + assert_eq!(files(&h), expected, "the last map is first now"); } #[test] @@ -451,16 +501,16 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv let mut h = harness(&library); click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; + assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].file, "RGB", "the reference's name for a new RGB row"); - // The RGB swatch is the last "RGB" button, after the Create button of that name - last_window_button(&h, "RGB").click(); + last_window_button(&h, "RGB: Default black").click(); h.run_steps(4); assert!(h.query_by_label("Clear channel").is_some()); h.get_by_label("Split/Collapse RGB").click(); h.run_steps(4); assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); - let green = last_window_button(&h, "G"); + let green = last_window_button(&h, "G: Default black"); let at = green.rect().center(); green.click_secondary(); h.run_steps(4); @@ -470,4 +520,35 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); + assert!(h.query_all_by_label("G: Default black, inverted").next().is_some(), "the swatch says it is inverted"); +} + +#[test] +fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let library = TemplateLibrary::new("small-screen"); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h.state_mut().session.load_export_presets(library.0.clone()); + let base = texturecraft_engine::formats::builtin_preset("Unreal Engine (Packed)").unwrap(); + h.state_mut().run("export.preset.save", json!({ "preset": texturecraft_engine::formats::ExportPreset { name: "Mine".into(), ..base } })).unwrap(); + let ui = &mut h.state_mut().ui; + ui.windows.export = true; + ui.export.tab = 1; + ui.export.preset = "Mine".into(); + h.run_steps(4); + click(&mut h, "R+G+B+A"); + + let input_maps = h.get_by_label("Input maps").rect(); + let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); + let alpha = last_window_button(&h, "A: Default white").rect(); + + assert!(!removes.is_empty()); + for remove in removes { + assert!(remove.right() < input_maps.left(), "a row's × stays left of the Input maps pane: {remove:?} {input_maps:?}"); + } + assert!(alpha.right() < input_maps.left(), "the last swatch too: {alpha:?}"); + let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); + assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); } diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index fc8f19f6..be849be0 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -67,11 +67,11 @@ fn invert_toggle_changes_the_saved_template() { assert!(saved(&h).is_empty()); // Three maps in R, G and B: one swatch per channel - for swatch in ["R: Specular roughness", "G: Base metalness", "B"] { + for swatch in ["R: Roughness (Grayscale)", "G: Metallic (Grayscale)", "B: Constant 0.50"] { assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); } - toggle_invert(&mut h, "G: Base metalness"); + toggle_invert(&mut h, "G: Metallic (Grayscale)"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggle_invert(&mut h, "G: Base metalness"); + toggle_invert(&mut h, "G: Metallic (Grayscale), inverted"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 740616c354bb17331926be66d6890b828faee461 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 01:23:31 +0100 Subject: [PATCH 12/20] Mesh Export Options: the reference's info icons; parity notes for the Output templates tab --- crates/ui-egui/src/mesh_export_options.rs | 43 +++++++++++++++++++--- docs/ui-parity.md | 45 +++++++++++++---------- 2 files changed, 63 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 95e2bae7..702589b3 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -4,6 +4,7 @@ use egui::Ui; use crate::TextureCraftApp; use crate::i18n::tr; +use crate::theme::Tokens; use crate::unavailable; /// Indent of an option's checkbox under its choice @@ -13,7 +14,10 @@ const OPTION_INDENT: f32 = 20.0; const BUTTON_WIDTH: f32 = 110.0; /// The reference dialog's content width -const DIALOG_WIDTH: f32 = 510.0; +const DIALOG_WIDTH: f32 = 500.0; + +/// Width of an info icon's tooltip, as in the reference +const INFO_TOOLTIP_WIDTH: f32 = 250.0; /// Gap between the two option groups, as in the reference const GROUP_GAP: f32 = 25.0; @@ -32,10 +36,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // TextureCraft exports the mesh as it is: triangulated, without displacement ui.add(egui::RadioButton::new(true, tr("Without displacement/tessellation"))); - option(ui, true, tr("Apply triangulation")); + option( + ui, + true, + tr("Apply triangulation"), + &[ + tr("Triangulation converts all mesh polygons with more than 3 sides to triangles (but doesn't change the triangular ones)."), + tr("Choosing to apply triangulation for export avoids unexpected results when rendering the mesh in another application."), + ], + ); ui.add_space(GROUP_GAP); unavailable::greyed(ui, |ui| ui.add(egui::RadioButton::new(false, tr("With displacement/tessellation")))); - option(ui, true, tr("Recompute vertex normals")); + option( + ui, + true, + tr("Recompute vertex normals"), + &[ + tr("Recomputing vertex normals is recommended if you don't plan on using the normal map in the target application."), + tr("Otherwise, keeping the original vertex normals is recommended if you plan on using the normal map in the target application."), + ], + ); ui.add_space(8.0); // One row keeps the window to its contents; a bare right-to-left layout fills the screen height @@ -56,10 +76,23 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// A greyed option under a choice, ticked as the reference shows it -fn option(ui: &mut Ui, checked: bool, label: &str) { +/// A greyed option under a choice, ticked as the reference shows it, with an info icon at the +/// row's right end whose tooltip has the paragraphs `info` +fn option(ui: &mut Ui, checked: bool, label: &str, info: &[&str]) { ui.horizontal(|ui| { ui.add_space(OPTION_INDENT); unavailable::checkbox(ui, checked, label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let icon = ui.label(egui::RichText::new(egui_phosphor::regular::INFO).color(Tokens::get(ui.ctx()).text_dim)); + icon.on_hover_ui(|ui| { + ui.set_max_width(INFO_TOOLTIP_WIDTH); + for (k, paragraph) in info.iter().enumerate() { + if k > 0 { + ui.add_space(ui.text_style_height(&egui::TextStyle::Body)); + } + ui.label(*paragraph); + } + }); + }); }); } diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 49271c38..2c04591e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -70,7 +70,8 @@ that closes it back onto the bar; the float is saved with the UI state. and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). *Export MaterialX* below *Export USD asset* is a TextureCraft addition: it adds `materialX: true` to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. + greyed; TextureCraft exports the mesh as it is. The two (i) icons carry the reference's + tooltips. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ", @@ -345,22 +346,26 @@ that numbers hide once a tile is under 40 points on screen. middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the - file name, "$" with the file name variables ($project, $mesh, $textureSet, $udim, $uvTileName - greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gray, RGB or R, G, B, - then A), the file type and bit depth lists ("8 bits + dithering" greyed: templates do not keep - it), duplicate and "×". Dropping a map on a swatch opens "From ": a gray map offers *Gray - Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G Channel*, *B Channel* - and *A Channel* (TextureCraft has no alpha or gray of a map yet: those are greyed). A colour - map dropped on the RGB swatch fills R, G and B at once. The swatch then takes the map's - colour, and the map lists mark the maps of the output map edited last with that colour. A - click on a swatch offers *Clear channel* and *Split/Collapse RGB*. The right side has the - *Input maps* pane, grouped as in the reference (Base, Specular, Transmission, Subsurface, - Coat, Fuzz/Sheen; then Emission, Geometry and Other for the channels the reference screenshot - cuts off), and a pane with *Mesh maps* above *Converted maps* (highlighted); maps TextureCraft - does not have yet are greyed and cannot be dragged. TextureCraft keeps a few things the - reference does not show, out of the way: Import and Export of template files at the end of a - preset's right-click menu, Invert in a swatch's right-click menu, *Move up* and *Move down* - in the grip's right-click menu (and the arrow keys on a focused grip), the planned file name - in the file name's tooltip, and three converted maps of its own (Normal from height, Roughness - from glossiness, Sheen color × weight) after the reference's. Built-in templates stay - read-only and deleting asks first. + file name, "$" ("Add expressions in the path that will be replaced during export": $project, + $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the + channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth + ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". + Create names new rows "Grayscale", "RGB" and "RGB Alpha", with "_1", "_2" when taken. An + empty swatch reads "Default black" ("Default white" for A), a filled one " ()", + e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": + a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G + Channel*, *B Channel* and *A Channel*, on the RGB swatch first *RGB Channels*; Escape assigns + nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A + click on a swatch offers *Clear channel*, on RGB, R, G and B also *Split/Collapse RGB*; R, G + and B that read different maps cannot collapse (the item is greyed). The right side has the + *Input maps* pane in the reference's groups and names (Base ... Miscellaneous, User Channels), + and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template + uses get a square in their swatch's colour. Input and converted maps TextureCraft does not have + are greyed and cannot be dragged (the reference lists them all alike). TextureCraft keeps + some things the reference does not have, out of the way: Import and Export of template files + at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted + swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout + (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the + arrow keys on a focused grip; the planned file name in the file name's tooltip; and three + converted maps of its own (Normal from height, Roughness from glossiness, Sheen color × weight) + after the reference's. Built-in templates stay read-only and deleting asks first. From 5fe8fe7ae297a1794d5d29be1598bf5df6c10686 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 02:05:50 +0100 Subject: [PATCH 13/20] Output templates: rows keep one line, the Create buttons move below the title in a narrow column --- crates/ui-egui/src/export_templates.rs | 36 +++++++++++++++------ crates/ui-egui/tests/it/output_templates.rs | 16 +++++++++ 2 files changed, 42 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 79f713e0..0dd0d996 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -73,6 +73,8 @@ const ROW_GAP_POINTS: f32 = 4.0; const GRIP_WIDTH_POINTS: f32 = 5.0; const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; const ROW_ICON_POINTS: f32 = 16.0; +/// Width the "Output maps" title and the Create buttons need on one row +const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; /// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a /// row's right end, and the gaps between a row's controls (besides the swatches') const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; @@ -759,9 +761,9 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { }); }); - // "Output maps", with the Create buttons at the right end of the same row - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); + // "Output maps", with the Create buttons at the right end of the same row, or of the next one + // when the column is too narrow for both + let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_enabled_ui(editable, |ui| { for (label, layout, split, file) in CREATE.iter().rev() { @@ -772,7 +774,16 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); }); }); - }); + }; + if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { + ui.horizontal(|ui| { + ui.label(caption(tr("Output maps"))); + create_buttons(ui, &mut edit); + }); + } else { + ui.label(caption(tr("Output maps"))); + ui.horizontal(|ui| create_buttons(ui, &mut edit)); + } if let Err(e) = &preview { ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); } @@ -916,6 +927,8 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.horizontal(|ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + // The name field gives way in a narrow window, so the swatches and lists stay in the row let swatches = swatch_targets(map, *split).len() as f32; let spacing = ui.spacing().item_spacing.x; @@ -930,19 +943,22 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: changed |= name.changed(); changed |= token_menu(ui, &mut map.file); changed |= channel_swatches(ui, index, map, split, edit); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.vertical(|ui| { + + // The lists and icons at the row's right end: file format and duplicate, bit depth and remove + ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); + ui.vertical(|ui| { + ui.horizontal(|ui| { + changed |= format_menu(ui, map); if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Duplicate(index)); } + }); + ui.horizontal(|ui| { + changed |= depth_menu(ui, map); if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { edit.action = Some(MapAction::Remove(index)); } }); - ui.vertical(|ui| { - changed |= format_menu(ui, map); - changed |= depth_menu(ui, map); - }); }); }); }); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2b888752..e8bb3af9 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -549,6 +549,22 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { assert!(remove.right() < input_maps.left(), "a row's × stays left of the Input maps pane: {remove:?} {input_maps:?}"); } assert!(alpha.right() < input_maps.left(), "the last swatch too: {alpha:?}"); + + // Each row stays one line: its controls do not wrap into a tall row + let grips: Vec = h.get_all_by_label("Reorder").map(|grip| grip.rect()).collect(); + for pair in grips.windows(2) { + assert!(pair[1].top() - pair[0].top() < 2.5 * pair[0].height(), "row height {pair:?}"); + } + + // The row's file format list starts right of its last swatch instead of covering it + let format = + h.get_all_by_role(egui::Role::Button).rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))).unwrap().rect(); + assert!(alpha.right() <= format.left(), "the swatches and the lists do not overlap: {alpha:?} {format:?}"); + + // The panes stay inside the window: the side pane ends where the bottom bar's buttons end let cancel = h.get_all_by_label("Cancel").last().unwrap().rect(); + let export = last_window_button(&h, "Export").rect(); + let converted = h.get_by_label("Converted maps").rect(); assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); + assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } From 87a00221ec3b2711221134468321ad084278622e Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:08 +0100 Subject: [PATCH 14/20] Export window: restore the #789 wording the main merge dropped Merging main (c6894cc6) resolved three conflicts in export_window.rs with main's text, undoing this PR's renames, so five ui-egui tests failed: - the console step after rendering is "Preparing textures writing" again (main had brought back "Saving texture files"); - the greyed checkbox is "Export shaders parameters" with its tooltip again (main had "Export shader settings"); - the now working Export USD asset checkbox keeps this PR's tooltip. Note for review: TextureCraft always writes the mesh, so its "References the original mesh if possible" part never applies. Tests from #788 that named strings this PR renames on purpose follow the rename, as the PR already did for the MaterialX tests: - export_usd_asset: "Restore the default export parameters" is now "Resets all settings to default values"; "Saved texture " is now "Writing texture on disk" (both the positive and the negative check, so neither turns vacuous); - side_panels: "Export shader settings" is now "Export shaders parameters". Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 13 +++++++++---- crates/ui-egui/tests/it/export_usd_asset.rs | 9 ++++++--- crates/ui-egui/tests/it/side_panels.rs | 2 +- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 177d5288..3e923404 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -387,7 +387,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); @@ -815,9 +815,14 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // The browser downloads the textures only, so it has no USD asset to add #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")).on_hover_text(tr("Package the mesh, materials and textures together as USD")); + ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) + .on_hover_text(tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); #[cfg(target_arch = "wasm32")] - unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); + unavailable_checkbox( + ui, + tr("Export USD asset"), + tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + ); // The MaterialX export sits below the USD one; the browser downloads the textures only #[cfg(not(target_arch = "wasm32"))] @@ -826,7 +831,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index 68f310df..c8d71ddd 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -132,8 +132,11 @@ fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { let console = &h.state().ui.export.console; assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); - assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); - assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Writing material_ball texture on disk")), "{console:?}"); + assert!( + console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Writing ") && text.ends_with(" texture on disk"))), + "the textures are still listed" + ); } #[test] @@ -179,7 +182,7 @@ fn restoring_the_default_parameters_unticks_export_usd_asset() { checkbox(&h).click(); h.run_steps(3); assert!(h.state().ui.export.usd_asset); - h.get_by_label("Restore the default export parameters").click(); + h.get_by_label("Resets all settings to default values").click(); h.run_steps(3); assert!(!h.state().ui.export.usd_asset); } diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..5728889f 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -119,7 +119,7 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { } assert!(harness.query_by_label_contains("textures selected for export").is_some()); assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shader settings")); + assert!(says_not_available(&mut harness, "Export shaders parameters")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); From 5f4a25e0b122da394402d884c95bab0db83b784f Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:12 +0100 Subject: [PATCH 15/20] Export window: show keyboard focus on the tabs, list rows and console strip The window's drawn tabs, the Global settings row and the console's hide/resize strip take focus by Tab but drew nothing for it. They now draw a 2-point outline in the strong text colour when focused, apart from the accent of the selected tab or row and the hover fill. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3e923404..f8360ecb 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1503,7 +1503,10 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.separator(); ui.vertical(|ui| match app.ui.export.page { Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), + // A short or narrow window scrolls the settings, so the footer and every control stay reachable + _ => { + egui::ScrollArea::both().id_salt("exp_global_scroll").auto_shrink([false; 2]).show(ui, |ui| global_page(app, ui, &presets)); + } }); }); ui.add_space(8.0); From c68e8f9959d36f043a46ca4ce4bd4b019d49968f Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:15 +0100 Subject: [PATCH 16/20] Export window: the Global settings page scrolls on short or narrow screens On a short screen the settings pushed the footer (Cancel, Export) out of the fixed-size window, and at an 800-point-wide screen the 728-point window cut off the right end of the value lists. The page now sits in a scroll area (both directions), as the texture set list already does. The new test at 800x480 fails without it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_window.rs | 14 +++++++++ .../tests/it/export_reference_texts.rs | 29 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index f8360ecb..316e4454 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -52,6 +52,8 @@ const LIST_ROW_HEIGHT: f32 = 24.0; const LIST_ROW_INDENT: f32 = 16.0; /// Width of the bottom bar's buttons, the same for all as in the reference const FOOTER_BUTTON_WIDTH: f32 = 126.0; +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -623,6 +625,15 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } +/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text +/// colour, so it differs from the accent of the selected one and the fill of the hovered one +fn paint_focus(ui: &Ui, response: &egui::Response) { + if response.has_focus() { + let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); + ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); + } +} + /// A window tab: a box, lighter and with an accent line on top when open fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { let tokens = Tokens::get(ui.ctx()); @@ -642,6 +653,7 @@ fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); } painter.galley(rect.min + TAB_PADDING, galley, color); + paint_focus(ui, &response); response } @@ -889,6 +901,7 @@ fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { } let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); + paint_focus(ui, &response); response } @@ -1108,6 +1121,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 46dcd4b9..1c5d5c23 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -108,3 +108,32 @@ fn the_bottom_bar_buttons_share_one_width() { assert!(widths.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 1.0), "{widths:?}"); } + +/// The Size list of the Global settings page +fn size_list<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_all_by_role(egui::Role::ComboBox) + .find(|list| list.accesskit_node().value().as_deref() == Some("Based on each Texture Set's size")) + .expect("the Size list") +} + +#[test] +fn on_a_short_narrow_screen_the_settings_scroll_and_the_footer_stays_in_view() { + let screen = egui::vec2(800.0, 480.0); + let mut h = harness(screen); + for label in ["Cancel", "Export"] { + let rect = window_button_rect(&h, label, screen.x); + assert!(rect.max.x <= screen.x && rect.max.y <= screen.y, "{label} {rect:?}"); + } + let export = window_button_rect(&h, "Export", screen.x); + + // The last setting and the right end of the value lists scroll into the window, above the footer + h.get_by_label("Color space").scroll_to_me(); + h.run_steps(4); + let color_space = h.get_by_label("Color space").rect(); + assert!(color_space.max.y < export.min.y, "Color space {color_space:?}, footer {export:?}"); + + size_list(&h).scroll_to_me(); + h.run_steps(4); + let size = size_list(&h).rect(); + assert!(size.max.x <= export.max.x, "Size {size:?}, window right end {}", export.max.x); +} From 1abb7bda344511935379ebb6d8d52dff33778b14 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 11:41:17 +0100 Subject: [PATCH 17/20] Output templates: new output maps get a per texture set file name Create named new rows just "Grayscale", "RGB" or "RGB Alpha", so every texture set of a multi-set export planned the same file and the export was refused for the name clash. New rows now start with "$mesh_$textureSet_" (as the old "$mesh_$textureSet_Output" default did), followed by the reference's row name. The output_templates test that pinned the bare "RGB" checks the suffix and the set token instead. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_templates.rs | 5 ++++- crates/ui-egui/tests/it/output_templates.rs | 4 +++- docs/ui-parity.md | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 0dd0d996..4a6fd523 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -167,6 +167,9 @@ const CREATE: [(&str, Layout, bool, &str); 5] = [ ("RGB+A", Layout::Rgba, false, "RGB Alpha"), ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), ]; +/// What a new output map's file name starts with, so each texture set (and mesh) writes a file +/// of its own; the reference's row name follows it +const NEW_MAP_PREFIX: &str = "$mesh_$textureSet_"; /// The swatch right-click menu's constants: (label, value) const CONSTANTS: [(&str, f32); 3] = [(n_("Black"), 0.0), (n_("Gray 50%"), 0.5), (n_("White"), 1.0)]; @@ -837,7 +840,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let acted = match edit.action { Some(MapAction::Add(layout, split_rgb, file)) => { - let file = unique_file(&preset.maps, file); + let file = unique_file(&preset.maps, &format!("{NEW_MAP_PREFIX}{file}")); preset.maps.push(new_map(layout, &file)); origin.push(None); split.push(split_rgb); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index e8bb3af9..918bea96 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -501,7 +501,9 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv let mut h = harness(&library); click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].file, "RGB", "the reference's name for a new RGB row"); + let file = &h.state().session.export_preset("Mine").unwrap().maps[last].file; + assert!(file.ends_with("_RGB"), "the reference's name for a new RGB row: {file}"); + assert!(file.contains("$textureSet"), "each texture set writes a file of its own: {file}"); last_window_button(&h, "RGB: Default black").click(); h.run_steps(4); diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1d52846a..573bed16 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -351,7 +351,8 @@ that numbers hide once a tile is under 40 points on screen. $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". - Create names new rows "Grayscale", "RGB" and "RGB Alpha", with "_1", "_2" when taken. An + Create names new rows "Grayscale", "RGB" and "RGB Alpha" after "$mesh_$textureSet_", so the + texture sets of one export do not write the same file, with "_1", "_2" when taken. An empty swatch reads "Default black" ("Default white" for A), a filled one " ()", e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G From 0af0c0f46197323f06f11a06a04f2bab95a78464 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 12:53:55 +0100 Subject: [PATCH 18/20] Export UI: TextureCraft's own wording instead of the reference's texts The export dock, Mesh Export Options and Export textures window keep the reference's layout, but their texts are now our own. Where main had a TextureCraft text for a control (footer tooltips, console lines, override menu, reset button, dilation hint, naming pattern info), it is back. New texts describe what TextureCraft does: the USD tooltip says the mesh is always written, the Mesh Export Options info tooltips say the mesh is always triangles and normals are not recomputed. The drop popup asks "Which part of ?", empty swatches read "Empty (writes black)", new rows are named after their layout (Gray, RGB, RGBA), and the map panes use TextureCraft's channel, bake and converted map names with OpenPBR parameter names for the inputs TextureCraft lacks. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/export_templates.rs | 92 +++++------ .../ui-egui/src/export_templates/map_lists.rs | 148 +++++------------- .../src/export_templates/source_pick.rs | 4 +- crates/ui-egui/src/export_window.rs | 58 +++---- crates/ui-egui/src/mesh_export_options.rs | 8 +- crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/state/console_line.rs | 2 +- .../ui-egui/tests/it/export_map_overrides.rs | 4 +- crates/ui-egui/tests/it/export_materialx.rs | 4 +- crates/ui-egui/tests/it/export_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 18 +-- .../tests/it/export_reference_texts.rs | 22 +-- crates/ui-egui/tests/it/export_settings.rs | 4 +- crates/ui-egui/tests/it/export_usd_asset.rs | 9 +- crates/ui-egui/tests/it/output_templates.rs | 63 ++++---- crates/ui-egui/tests/it/side_panels.rs | 2 +- crates/ui-egui/tests/it/template_invert.rs | 6 +- 17 files changed, 190 insertions(+), 262 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 4a6fd523..9be85946 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -158,17 +158,17 @@ impl Layout { } } -/// The reference's Create buttons: (label, the layout the new output map gets, whether R, G and +/// The Create buttons: (label, the layout the new output map gets, whether R, G and /// B show as separate swatches, the new map's file name) const CREATE: [(&str, Layout, bool, &str); 5] = [ - (n_("Gray"), Layout::Gray, false, "Grayscale"), + (n_("Gray"), Layout::Gray, false, "Gray"), ("RGB", Layout::Rgb, false, "RGB"), ("R+G+B", Layout::Rgb, true, "RGB"), - ("RGB+A", Layout::Rgba, false, "RGB Alpha"), - ("R+G+B+A", Layout::Rgba, true, "RGB Alpha"), + ("RGB+A", Layout::Rgba, false, "RGBA"), + ("R+G+B+A", Layout::Rgba, true, "RGBA"), ]; /// What a new output map's file name starts with, so each texture set (and mesh) writes a file -/// of its own; the reference's row name follows it +/// of its own; the layout's name follows it const NEW_MAP_PREFIX: &str = "$mesh_$textureSet_"; /// The swatch right-click menu's constants: (label, value) @@ -392,8 +392,8 @@ pub fn select(app: &mut TextureCraftApp, name: String) { pub(crate) fn naming_pattern(ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { - ui.label(tr("Select the naming pattern used to display the input maps on this page.")); - ui.label(tr("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.")); + ui.label(tr("Choose how the input maps are named in this editor.")); + ui.label(tr("The active texture set’s shader can affect the available map names.")); }); egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { for p in NAMING_PATTERNS { @@ -810,7 +810,7 @@ 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(tokens.text_dim)); + ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); // Count only maps that have sources in the current set if let Ok(names) = &preview { @@ -1015,7 +1015,7 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the reference's file name variables, then TextureCraft's own ($channel) +/// The "$" button: the file name variables in the reference's order, then $channel fn token_menu(ui: &mut Ui, file: &mut String) -> bool { let mut changed = false; let menu = ui.menu_button("$", |ui| { @@ -1037,7 +1037,7 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Add expressions in the path that will be replaced during export")); + menu.response.on_hover_text(tr("Insert a variable")); changed } @@ -1130,7 +1130,7 @@ fn swatch_targets(map: &MapSpec, split: bool) -> Vec { targets } -/// The letters on a swatch, as in the reference +/// The letters on a swatch fn target_label(target: ChannelTarget) -> &'static str { match target { ChannelTarget::Rgb => "RGB", @@ -1148,23 +1148,23 @@ fn source_of(map: &MapSpec, target: ChannelTarget) -> Option<&SourceRef> { map.channels.iter().find(|(d, _)| d == dest).map(|(_, s)| s) } -/// The choices of "From " in the reference order: "RGB Channels" only for a colour map on +/// The choices of the drop popup ("Which part of ?"): "Red, green and blue" only for a colour map on /// the RGB swatch; None marks a choice TextureCraft cannot read yet (a map's gray or alpha) fn source_choices(source: &SourceRef, target: ChannelTarget) -> Vec<(&'static str, Option)> { if source.components() != 3 { - return vec![(n_("Gray Channel"), Some(SourcePick::Component(0))), (n_("A Channel"), None)]; + return vec![(n_("Gray value"), Some(SourcePick::Component(0))), (n_("Alpha channel"), None)]; } let mut choices = Vec::new(); if target == ChannelTarget::Rgb { - choices.push((n_("RGB Channels"), Some(SourcePick::AllRgb))); + choices.push((n_("Red, green and blue"), Some(SourcePick::AllRgb))); } choices.extend([ - (n_("Gray Channel"), None), - (n_("R Channel"), Some(SourcePick::Component(0))), - (n_("G Channel"), Some(SourcePick::Component(1))), - (n_("B Channel"), Some(SourcePick::Component(2))), - (n_("A Channel"), None), + (n_("Gray value"), None), + (n_("Red channel"), Some(SourcePick::Component(0))), + (n_("Green channel"), Some(SourcePick::Component(1))), + (n_("Blue channel"), Some(SourcePick::Component(2))), + (n_("Alpha channel"), None), ]); choices } @@ -1184,10 +1184,10 @@ fn apply_pick(map: &mut MapSpec, target: ChannelTarget, source: &SourceRef, pick } } -/// The channel of the source a swatch reads, as the reference's swatch tooltip names it +/// The part of its source a swatch reads, as its tooltip names it fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> &'static str { if source.components() != 3 { - return n_("Grayscale"); + return n_("gray value"); } if target == ChannelTarget::Rgb && rgb_spread(map) { @@ -1195,23 +1195,23 @@ fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) - } match component_of(source) { - 0 => n_("Red"), - 1 => n_("Green"), - _ => n_("Blue"), + 0 => n_("red channel"), + 1 => n_("green channel"), + _ => n_("blue channel"), } } -/// A swatch's tooltip in the reference's words: "Default black" or "Default white" when empty, -/// else " ()"; another constant (TextureCraft's own) gives its value +/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, +/// else ", "; another constant (TextureCraft's own) gives its value fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { let alpha = target == ChannelTarget::One(Dest::A); match source { - SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Default white").to_string(), - SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Default black").to_string(), + SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Empty (writes white)").to_string(), + SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Empty (writes black)").to_string(), SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), _ => { let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); - trf("{map} ({channel})", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) + trf("{map}, {channel}", &[("map", &name), ("channel", &tr(read_channel_name(map, source, target)))]) } } } @@ -1243,7 +1243,7 @@ fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: } /// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Split/Collapse RGB on R, G, B), a right click TextureCraft's own tools. +/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; @@ -1286,8 +1286,8 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo // Collapsing would drop maps that R, G and B read differently let mut checked = shows_split; let can_toggle = !shows_split || rgb_one_map(map); - let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Split/Collapse RGB"))); - let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to collapse")); + let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Separate R, G and B"))); + let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to join them")); if item.changed() { changed |= split_or_collapse(map, split, shows_split); } @@ -1381,7 +1381,7 @@ fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Resp response } -/// Clear channel: the swatch is empty again ("Default black", "Default white" for alpha), not +/// Clear channel: the swatch is empty again ("Empty (writes black)", white for alpha), not /// inverted fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { for (dest, source) in &mut map.channels { @@ -1392,7 +1392,7 @@ fn clear_channel(map: &mut MapSpec, target: ChannelTarget) { map.inverted.retain(|dest| !target.dests().contains(dest)); } -/// Split/Collapse RGB: the RGB swatch splits into R, G and B; split ones that read one map collapse +/// Separate R, G and B: the RGB swatch splits into R, G and B; split ones that read one map collapse /// into one RGB swatch reading that map's R, G and B. R, G and B reading different maps stay split, /// so no map is dropped. True when the map changed. fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> bool { @@ -1419,7 +1419,7 @@ fn split_or_collapse(map: &mut MapSpec, split: &mut bool, shows_split: bool) -> true } -/// "From ": which channel of the dropped map the swatch reads; Escape or a click elsewhere +/// The drop popup ("Which part of ?"): which channel of the dropped map the swatch reads; Escape or a click elsewhere /// assigns nothing. True when the map changed. fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [MapSpec]) -> bool { let Some(waiting) = pending.clone() else { return false }; @@ -1437,7 +1437,7 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ .open(true) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { - ui.label(RichText::new(trf("From {map}", &[("map", &name)])).strong()); + ui.label(RichText::new(trf("Which part of {map}?", &[("map", &name)])).strong()); for (label, pick) in source_choices(&waiting.source, waiting.target) { match pick { Some(pick) => { @@ -1642,19 +1642,19 @@ mod tests { let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Default black"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Default white"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Empty (writes black)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Empty (writes white)"); } #[test] - fn the_from_popup_offers_the_reference_choices() { + fn the_drop_popup_offers_the_parts_of_the_map_the_swatch_can_take() { let offered = |source: &SourceRef, target| source_choices(source, target).into_iter().map(|(label, pick)| (label, pick.is_some())).collect::>(); - assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray Channel", true), ("A Channel", false)]); - let color_on_gray = [("Gray Channel", false), ("R Channel", true), ("G Channel", true), ("B Channel", true), ("A Channel", false)]; + assert_eq!(offered(&ch(Channel::Metallic, 0), ChannelTarget::Rgb), [("Gray value", true), ("Alpha channel", false)]); + let color_on_gray = [("Gray value", false), ("Red channel", true), ("Green channel", true), ("Blue channel", true), ("Alpha channel", false)]; assert_eq!(offered(&ch(Channel::BaseColor, 0), ChannelTarget::One(Dest::L)), color_on_gray); let color_on_rgb = offered(&ch(Channel::BaseColor, 0), ChannelTarget::Rgb); - assert_eq!(color_on_rgb.first(), Some(&("RGB Channels", true)), "only the RGB swatch offers RGB Channels"); + assert_eq!(color_on_rgb.first(), Some(&("Red, green and blue", true)), "only the RGB swatch offers all three"); assert_eq!(color_on_rgb.get(1..), Some(color_on_gray.as_slice())); } @@ -1664,18 +1664,18 @@ mod tests { apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); assert!(rgb_spread(&map)); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (RGB)"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, RGB"); apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color (Red)"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, red channel"); } #[test] - fn new_rows_take_the_reference_names_with_a_number_when_taken() { + fn new_rows_take_their_layout_name_with_a_number_when_taken() { let maps = vec![new_map(Layout::Rgb, "RGB"), new_map(Layout::Rgb, "RGB_1")]; - assert_eq!(unique_file(&maps, "Grayscale"), "Grayscale"); + assert_eq!(unique_file(&maps, "Gray"), "Gray"); assert_eq!(unique_file(&maps, "RGB"), "RGB_2"); } } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index afe9e2aa..f190370c 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -1,6 +1,6 @@ -//! The maps the Output templates tab lists for dragging onto output channels, with the reference's -//! names (naming pattern OpenPBR). An entry without a source names a map TextureCraft does not -//! have yet; it is listed greyed. +//! The maps the Output templates tab lists for dragging onto output channels. Maps TextureCraft +//! has carry its own names; the input maps it does not have yet carry OpenPBR parameter names +//! (OpenPBR Surface specification, Academy Software Foundation) and are listed greyed. use std::sync::LazyLock; @@ -15,137 +15,63 @@ pub type MapEntry = (&'static str, Option); /// A group of the Input maps pane: its name and entries. pub type MapGroup = (&'static str, Vec); -fn channel(channel: Channel) -> Option { - Some(SourceRef::Channel { channel, component: 0 }) +/// A TextureCraft channel, under its own name +fn channel(channel: Channel) -> MapEntry { + (channel.label(), Some(SourceRef::Channel { channel, component: 0 })) } -fn converted(map: VirtualMap) -> Option { - Some(SourceRef::Virtual { map, component: 0 }) +/// An OpenPBR input TextureCraft has no channel for yet +fn missing(name: &'static str) -> MapEntry { + (name, None) } -fn mesh(map: BakedMap) -> Option { - Some(SourceRef::Baked { map, component: 0 }) -} - -/// The reference's user channels, listed greyed: TextureCraft has no user channels yet -const USER_CHANNELS: [&str; 32] = [ - "User0", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10", "User11", "User12", "User13", "User14", "User15", - "User16", "User17", "User18", "User19", "User20", "User21", "User22", "User23", "User24", "User25", "User26", "User27", "User28", "User29", "User30", - "User31", -]; - -/// Input maps in the reference's groups and order (naming pattern OpenPBR); entries without a -/// TextureCraft channel are listed greyed. +/// Input maps in the OpenPBR parameter groups, then TextureCraft's channels outside OpenPBR pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ - ( - n_("Base"), - vec![ - (n_("Base weight"), None), - (n_("Base color"), channel(Channel::BaseColor)), - (n_("Metallic"), channel(Channel::Metallic)), - (n_("Base diffuse roughness"), None), - ], - ), + (n_("Base"), vec![missing(n_("Base weight")), channel(Channel::BaseColor), channel(Channel::Metallic), missing(n_("Base diffuse roughness"))]), ( n_("Specular"), vec![ - (n_("Specular weight"), None), - (n_("Specular edge color"), None), - (n_("Roughness"), channel(Channel::Roughness)), - (n_("Specular level"), channel(Channel::SpecularLevel)), - (n_("Anisotropy level"), channel(Channel::AnisotropyLevel)), - (n_("Anisotropy angle"), channel(Channel::AnisotropyAngle)), + missing(n_("Specular weight")), + missing(n_("Specular color")), + channel(Channel::Roughness), + channel(Channel::SpecularLevel), + channel(Channel::AnisotropyLevel), + channel(Channel::AnisotropyAngle), ], ), - (n_("Transmission"), vec![(n_("Transmission weight"), channel(Channel::Transmission)), (n_("Absorption color"), None)]), - (n_("Subsurface"), vec![(n_("Translucency"), None), (n_("Scattering color"), None), (n_("Scattering"), channel(Channel::ScatterWeight))]), + (n_("Transmission"), vec![channel(Channel::Transmission), missing(n_("Transmission color"))]), + (n_("Subsurface"), vec![channel(Channel::ScatterWeight), missing(n_("Subsurface color")), missing(n_("Subsurface radius"))]), ( n_("Coat"), vec![ - (n_("Coat opacity"), channel(Channel::CoatWeight)), - (n_("Coat color"), None), - (n_("Coat roughness"), channel(Channel::CoatRoughness)), - (n_("Coat anisotropy"), None), - (n_("Coat specular level"), None), - (n_("Coat normal"), channel(Channel::CoatNormal)), - (n_("Coat tangent"), None), + channel(Channel::CoatWeight), + missing(n_("Coat color")), + channel(Channel::CoatRoughness), + missing(n_("Coat roughness anisotropy")), + missing(n_("Coat IOR")), + channel(Channel::CoatNormal), + missing(n_("Coat tangent")), ], ), - ( - n_("Fuzz/Sheen"), - vec![ - (n_("Sheen opacity"), channel(Channel::SheenWeight)), - (n_("Sheen color"), channel(Channel::SheenColor)), - (n_("Sheen roughness"), channel(Channel::SheenRoughness)), - ], - ), - (n_("Emission"), vec![(n_("Emissive"), channel(Channel::Emissive))]), - (n_("Thin-film"), vec![(n_("Thin-film weight"), None)]), + (n_("Sheen"), vec![channel(Channel::SheenWeight), channel(Channel::SheenColor), channel(Channel::SheenRoughness)]), + (n_("Emission"), vec![channel(Channel::Emissive)]), + (n_("Thin film"), vec![missing(n_("Thin film weight")), missing(n_("Thin film thickness"))]), ( n_("Geometry"), - vec![ - (n_("Opacity"), channel(Channel::Opacity)), - (n_("Height"), channel(Channel::Height)), - (n_("Normal"), channel(Channel::Normal)), - (n_("Tangent"), None), - (n_("Ambient occlusion"), channel(Channel::AmbientOcclusion)), - ], + vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), missing(n_("Tangent")), channel(Channel::AmbientOcclusion)], ), - ( - n_("Miscellaneous"), - vec![ - (n_("Blending mask"), None), - (n_("Diffuse"), None), - (n_("Displacement"), None), - (n_("Glossiness"), channel(Channel::Glossiness)), - ("Ior", None), - (n_("Reflection"), None), - (n_("Specular"), channel(Channel::Specular)), - (n_("Transmissive"), None), - ], - ), - (n_("User Channels"), USER_CHANNELS.iter().map(|name| (*name, None)).collect()), + (n_("Other"), vec![channel(Channel::Glossiness), channel(Channel::Specular)]), ] }); -/// Mesh maps, in the reference order and case. -pub static MESH_MAPS: LazyLock> = LazyLock::new(|| { - vec![ - (n_("Normal"), mesh(BakedMap::Normal)), - (n_("World space normal"), mesh(BakedMap::WorldNormal)), - (n_("ID"), mesh(BakedMap::Id)), - (n_("Ambient occlusion"), mesh(BakedMap::AmbientOcclusion)), - (n_("Curvature"), mesh(BakedMap::Curvature)), - (n_("Position"), mesh(BakedMap::Position)), - (n_("Thickness"), mesh(BakedMap::Thickness)), - (n_("Height"), mesh(BakedMap::Height)), - (n_("Bent normals"), mesh(BakedMap::BentNormal)), - (n_("Opacity"), mesh(BakedMap::Opacity)), - ] -}); +/// Mesh maps, under the names the bake panel gives them. +pub static MESH_MAPS: LazyLock> = + LazyLock::new(|| BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), Some(SourceRef::Baked { map, component: 0 }))).collect()); -/// Converted maps in the reference order, then the ones only TextureCraft has (built-in templates use them). -pub static CONVERTED_MAPS: LazyLock> = LazyLock::new(|| { - vec![ - ("1/ior", None), - (n_("Mixed AO"), converted(VirtualMap::AoMixed)), - (n_("Diffuse"), None), - ("f0", converted(VirtualMap::F0)), - (n_("Glossiness"), converted(VirtualMap::Glossiness)), - (n_("Glossiness²"), None), - (n_("Normal DirectX"), converted(VirtualMap::NormalDirectX)), - (n_("Normal OpenGL"), converted(VirtualMap::NormalOpenGl)), - (n_("Reflection"), None), - (n_("Specular"), None), - ("Unity4 Diffuse", None), - ("Unity4 Gloss", None), - (n_("2D View"), None), - (VirtualMap::HeightNormal.label(), converted(VirtualMap::HeightNormal)), - (VirtualMap::Roughness.label(), converted(VirtualMap::Roughness)), - (VirtualMap::SheenTint.label(), converted(VirtualMap::SheenTint)), - ] -}); +/// Converted maps: the maps TextureCraft computes from others when it exports. +pub static CONVERTED_MAPS: LazyLock> = + LazyLock::new(|| VirtualMap::ALL.iter().map(|&map| (map.label(), Some(SourceRef::Virtual { map, component: 0 }))).collect()); /// The listed name of `source` (any component), or None for a constant. pub fn name_of(source: &SourceRef) -> Option<&'static str> { diff --git a/crates/ui-egui/src/export_templates/source_pick.rs b/crates/ui-egui/src/export_templates/source_pick.rs index 89dc4769..f3bbd650 100644 --- a/crates/ui-egui/src/export_templates/source_pick.rs +++ b/crates/ui-egui/src/export_templates/source_pick.rs @@ -1,7 +1,7 @@ -/// What a "From " choice reads from the dropped map. +/// What a choice of the drop popup ("Which part of ?") reads from the dropped map. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum SourcePick { - /// "RGB Channels": the map's R, G and B into the swatch's R, G and B. + /// "Red, green and blue": the map's R, G and B into the swatch's R, G and B. AllRgb, /// One component of the map in every channel of the swatch. Component(u8), diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 316e4454..246d32c2 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -205,7 +205,7 @@ fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, b ui.add_enabled(false, egui::Button::selectable(false, *name)).on_disabled_hover_text(tr(NOT_AVAILABLE)); } } - ui.separator().on_hover_text(tr("This preset is not available for the current project")); + ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { changed |= ui.selectable_value(current, name.clone(), name).on_hover_text(name).changed(); } @@ -269,7 +269,7 @@ fn start_export(app: &mut TextureCraftApp) { let e = &mut app.ui.export; e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing export...").into())]; + e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; if let Some(error) = error { e.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); @@ -315,7 +315,7 @@ fn start_export(app: &mut TextureCraftApp) { crate::web_files::export_textures(app, &jobs); } -/// Write the next texture set of the running export, logging the steps as the reference does; +/// Write the next texture set of the running export, logging each step; /// the last one finishes the export. A failed command (its error already shown) stops it. fn export_step(app: &mut TextureCraftApp, frame: u64) { let Some(job) = app.ui.export.job.as_mut() else { return }; @@ -327,14 +327,14 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { if job.pending.is_empty() { let written = std::mem::take(&mut job.written); let console = &mut app.ui.export.console; - console.push(ConsoleLine::Step(tr("Bitmaps write finalization...").into())); + console.push(ConsoleLine::Step(tr("All selected texture sets processed").into())); if written.is_empty() { console.push(ConsoleLine::Step(tr("No files were written").into())); } else { console.extend([ - ConsoleLine::Step(tr("Finalizing export...").into()), - ConsoleLine::Done(tr("Export successfully finished").into()), - ConsoleLine::Done(tr("Successfully exported:").into()), + ConsoleLine::Step(tr("Collecting the exported files").into()), + ConsoleLine::Done(tr("Texture export complete").into()), + ConsoleLine::Done(tr("Files saved").into()), ]); console.extend(written.into_iter().map(ConsoleLine::Done)); } @@ -360,7 +360,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } let set = || ConsoleLine::Set(name.clone()); - app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Computing textures results").into())]); + app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]); // Protect concrete files and UDIM references from earlier texture sets if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) { @@ -389,12 +389,12 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; + let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; // The USD asset is no texture: it stays in the list of written files only for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); - lines.push(ConsoleLine::Step(trf("Writing {file} texture on disk", &[("file", &stem)]))); + lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); } // The export's warnings go to the console and the log, each once per export @@ -411,7 +411,7 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { lines.push(ConsoleLine::Step(trf("Warning: {message}", &[("message", &warning)]))); } - lines.extend([set(), ConsoleLine::Step(tr("Finalizing textures writing").into())]); + lines.extend([set(), ConsoleLine::Step(tr("Finished writing this texture set").into())]); app.ui.export.console.extend(lines); if let Some(job) = app.ui.export.job.as_mut() { job.written.extend(files); @@ -573,7 +573,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { } } ui.separator(); - for (i, label) in [tr("Enable override for all items"), tr("Disable override for all items")].into_iter().enumerate() { + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { if ui.button(label).clicked() { menu = Some(3 + i); } @@ -735,11 +735,11 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { if enabled { r.response.on_hover_text(tr("Dilation in pixels")); } else { - r.response.on_disabled_hover_text(tr("Dilation cannot be applied to selected padding type")); + r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); } } -/// A greyed reference checkbox with its tooltip and the "not available" hint +/// A greyed checkbox with its tooltip and the "not available" hint fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -752,7 +752,7 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { let mut reset = false; header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Resets all settings to default values"), false, ICON).clicked(); + reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); }); if reset { let defaults = ExportUi::default(); @@ -828,12 +828,12 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] // The browser downloads the textures only, so it has no USD asset to add #[cfg(not(target_arch = "wasm32"))] ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) - .on_hover_text(tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise")); + .on_hover_text(tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); #[cfg(target_arch = "wasm32")] unavailable_checkbox( ui, tr("Export USD asset"), - tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), + tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), ); // The MaterialX export sits below the USD one; the browser downloads the textures only @@ -843,7 +843,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); + unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; @@ -997,10 +997,10 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor let mut all = None; header(ui, tr("General Export Parameters"), |ui| { list_menu(ui, |ui| { - if ui.button(tr("Enable override for all items")).clicked() { + if ui.button(tr("Override every item")).clicked() { all = Some(true); } - if ui.button(tr("Disable override for all items")).clicked() { + if ui.button(tr("Clear all overrides")).clicked() { all = Some(false); } ui.separator(); @@ -1158,9 +1158,9 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// "Exporting texture set ..." with the name in bold +/// "Texture set " with the name in bold fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { - let text = tr("Exporting texture set {set}..."); + let text = tr("Texture set {set}"); let (before, after) = text.split_once("{set}").unwrap_or((text, "")); let font = egui::TextStyle::Body.resolve(ui.style()); let plain = egui::TextFormat::simple(font.clone(), tk.text); @@ -1486,7 +1486,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } else if app.ui.export.tab == 1 { crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Includes all Texture Sets, UV Tiles and output maps.")).clicked() { + } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { app.ui.export.skip.clear(); for o in app.ui.export.sets.values_mut() { o.maps.values_mut().for_each(|m| m.enabled = true); @@ -1548,7 +1548,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { // Only on SETTINGS if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Resets all settings to their default values, including all textures.")).clicked() + && ui.add(footer_button(tr("Reset all"))).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { // Keep ownership so Cancel can restore the opening settings let e = &mut app.ui.export; @@ -1558,16 +1558,20 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { // Nothing to write without a ticked texture set let any = !export_selection(app).is_empty() && !templates_tab; - if ui.add_enabled(any, footer_button(tr("Export"))).on_hover_text(tr("Exports all selected textures and additional files")).clicked() { + if ui + .add_enabled(any, footer_button(tr("Export"))) + .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) + .clicked() + { do_export = true; } // Saving closes the window without starting an export let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Closes the export window and saves changes")).clicked() { + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { app.ui.windows.export = false; } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Closes the export window and undoes all recent changes")).clicked() { + if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { canceled = true; } if !templates_tab { diff --git a/crates/ui-egui/src/mesh_export_options.rs b/crates/ui-egui/src/mesh_export_options.rs index 702589b3..d8bbdcbd 100644 --- a/crates/ui-egui/src/mesh_export_options.rs +++ b/crates/ui-egui/src/mesh_export_options.rs @@ -41,8 +41,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { true, tr("Apply triangulation"), &[ - tr("Triangulation converts all mesh polygons with more than 3 sides to triangles (but doesn't change the triangular ones)."), - tr("Choosing to apply triangulation for export avoids unexpected results when rendering the mesh in another application."), + tr("Splits every face with more than three corners into triangles; triangles stay as they are."), + tr("TextureCraft keeps meshes as triangles, so the exported mesh is always triangulated."), ], ); ui.add_space(GROUP_GAP); @@ -52,8 +52,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { true, tr("Recompute vertex normals"), &[ - tr("Recomputing vertex normals is recommended if you don't plan on using the normal map in the target application."), - tr("Otherwise, keeping the original vertex normals is recommended if you plan on using the normal map in the target application."), + tr("Replaces the mesh's vertex normals with newly computed ones in the exported file."), + tr("TextureCraft cannot do this yet: it writes the vertex normals the mesh has in the project."), ], ); ui.add_space(8.0); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ce308b37..3da5244e 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -399,7 +399,7 @@ pub struct ExportUi { #[serde(skip, default = "default_console_width")] pub console_width: f32, /// Output templates tab: a map dropped on an output channel, waiting for the source channel - /// ("From "). + /// ("Which part of ?"). #[serde(skip)] pub pending_drop: Option, /// Output templates tab: the new name while renaming the selected preset. diff --git a/crates/ui-egui/src/state/console_line.rs b/crates/ui-egui/src/state/console_line.rs index 26baa2ce..196a5b60 100644 --- a/crates/ui-egui/src/state/console_line.rs +++ b/crates/ui-egui/src/state/console_line.rs @@ -2,7 +2,7 @@ #[derive(Clone, Debug, PartialEq)] pub enum ConsoleLine { Step(String), - /// "Exporting texture set ..." with the name in bold. + /// "Texture set " with the name in bold. Set(String), /// A success line, in green. Done(String), diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 45ce9297..937ce100 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -104,10 +104,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Enable override for all items"); + click(&mut h, "Override every item"); assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); click(&mut h, egui_phosphor::regular::LIST_CHECKS); - click(&mut h, "Disable override for all items"); + click(&mut h, "Clear all overrides"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_materialx.rs b/crates/ui-egui/tests/it/export_materialx.rs index 328078aa..829fc2d6 100644 --- a/crates/ui-egui/tests/it/export_materialx.rs +++ b/crates/ui-egui/tests/it/export_materialx.rs @@ -52,7 +52,7 @@ fn export_materialx_sits_directly_below_the_usd_option() { let (app_harness, _dir) = harness("order"); let usd = app_harness.get_by_label("Export USD asset").rect().min.y; let materialx = checkbox(&app_harness).rect().min.y; - let shaders = app_harness.get_by_label("Export shaders parameters").rect().min.y; + let shaders = app_harness.get_by_label("Export shader settings").rect().min.y; assert!(usd < materialx && materialx < shaders, "USD {usd}, MaterialX {materialx}, shaders {shaders}"); } @@ -171,7 +171,7 @@ fn restoring_the_default_parameters_unticks_export_materialx() { app_harness.run_steps(3); assert!(app_harness.state().ui.export.materialx); - app_harness.get_by_label("Resets all settings to default values").click(); + app_harness.get_by_label("Restore the default export parameters").click(); app_harness.run_steps(3); assert!(!app_harness.state().ui.export.materialx); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 2ca24b0d..9edb2ee5 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -117,14 +117,14 @@ fn the_header_menu_switches_every_override() { // The set list has the same menu button; the page header's is the second page_menu(&mut h); - click(&mut h, "Enable override for all items"); + click(&mut h, "Override every item"); let o = overrides(&h); assert!(o.preset.is_some() && o.file_type.is_some() && o.size.is_some() && o.padding.is_some(), "{o:?}"); // 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"); + click(&mut h, "Clear all overrides"); assert!(h.state().ui.export.sets.is_empty()); } @@ -157,7 +157,7 @@ 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")); + let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Texture export complete")); 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(); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 5210742a..b46b84a1 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -34,7 +34,7 @@ fn console(h: &Harness<'_, TextureCraftApp>) -> Vec { .iter() .map(|l| match l { ConsoleLine::Step(t) | ConsoleLine::Done(t) => t.clone(), - ConsoleLine::Set(name) => format!("Exporting texture set {name}..."), + ConsoleLine::Set(name) => format!("Texture set {name}"), }) .collect() } @@ -48,7 +48,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); assert!(h.query_by_label("Cancel Export").is_some()); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); - assert_eq!(console(&h).first().map(String::as_str), Some("Preparing export...")); + assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export")); for _ in 0..64 { if h.state().ui.export.job.is_none() { @@ -61,14 +61,14 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); - let set = format!("Exporting texture set {}...", sets[0]); + let set = format!("Texture set {}", sets[0]); let start = lines.iter().position(|l| *l == set).unwrap(); - assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Computing textures results".into(), set.clone(), "Preparing textures writing".into()]); - assert!(lines[start + 6].starts_with("Writing ") && lines[start + 6].ends_with(" texture on disk"), "{lines:?}"); + assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Rendering the selected maps".into(), set.clone(), "Saving texture files".into()]); + assert!(lines[start + 6].starts_with("Saved texture "), "{lines:?}"); let written: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); - let finished = lines.iter().position(|l| l == "Export successfully finished").unwrap(); - assert_eq!(&lines[finished - 3..finished], ["Finalizing textures writing", "Bitmaps write finalization...", "Finalizing export..."]); - assert_eq!(lines[finished + 1], "Successfully exported:"); + let finished = lines.iter().position(|l| l == "Texture export complete").unwrap(); + assert_eq!(&lines[finished - 3..finished], ["Finished writing this texture set", "All selected texture sets processed", "Collecting the exported files"]); + assert_eq!(lines[finished + 1], "Files saved"); assert_eq!(lines.len() - finished - 2, written.len(), "every written file is listed"); assert!(matches!(h.state().ui.export.console.last(), Some(ConsoleLine::Done(_))), "in green"); let _ = std::fs::remove_dir_all(&dir); @@ -113,7 +113,7 @@ fn cancel_export_stops_the_export() { assert!(h.state().ui.export.job.is_none()); assert!(h.state().ui.windows.export); let lines = console(&h); - assert!(!lines.iter().any(|l| l == "Finalizing export..." || l == "Export successfully finished"), "the export did not finish: {lines:?}"); + assert!(!lines.iter().any(|l| l == "Collecting the exported files" || l == "Texture export complete"), "the export did not finish: {lines:?}"); assert!(h.query_by_label("Cancel").is_some(), "the buttons are back"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 1c5d5c23..6dd4c494 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -1,5 +1,5 @@ -//! Export textures window (texturecraft #789): the reference's size, button tooltips and settings -//! texts, word for word. +//! Export textures window (texturecraft #789): the reference's size, and the tooltips of the bottom +//! bar's buttons and of the settings' checkboxes. use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; @@ -71,13 +71,13 @@ fn on_a_small_screen_the_window_fits_with_its_buttons_in_view() { } #[test] -fn the_buttons_carry_the_reference_tooltips() { +fn the_buttons_carry_tooltips_saying_what_they_do() { let mut h = harness(egui::vec2(1600.0, 960.0)); - tooltip_is(&mut h, "Include all", "Includes all Texture Sets, UV Tiles and output maps."); - tooltip_is(&mut h, "Reset all", "Resets all settings to their default values, including all textures."); - tooltip_is(&mut h, "Cancel", "Closes the export window and undoes all recent changes"); - tooltip_is(&mut h, "Save settings", "Closes the export window and saves changes"); - tooltip_is(&mut h, "Export", "Exports all selected textures and additional files"); + tooltip_is(&mut h, "Include all", "Select every texture set, UV tile and output map"); + tooltip_is(&mut h, "Reset all", "Restore the export defaults and select every texture"); + tooltip_is(&mut h, "Cancel", "Close the window and go back to the settings it opened with"); + tooltip_is(&mut h, "Save settings", "Keep these settings for the next export and close the window"); + tooltip_is(&mut h, "Export", "Write the selected textures, and the extra files ticked in the settings"); } /// Hover the checkbox `label` and check that its tooltip says `tooltip` @@ -90,14 +90,14 @@ fn checkbox_tooltip_is(h: &mut Harness<'_, TextureCraftApp>, label: &str, toolti } #[test] -fn the_unavailable_checkboxes_carry_the_reference_texts() { +fn the_extra_file_checkboxes_carry_tooltips_saying_what_they_write() { let mut h = harness(egui::vec2(1600.0, 960.0)); checkbox_tooltip_is( &mut h, "Export USD asset", - "Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise", + "Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures", ); - checkbox_tooltip_is(&mut h, "Export shaders parameters", "Exports a JSON file with the settings for all shader instances"); + checkbox_tooltip_is(&mut h, "Export shader settings", "Save the settings of each shader instance in a JSON file"); } #[test] diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index afabdee1..98af3660 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -143,7 +143,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); - assert!(h.query_by_label("Dilation cannot be applied to selected padding type").is_some()); + assert!(h.query_by_label("This padding mode does not use a dilation width").is_some()); h.state_mut().ui.export.padding = "dilation".into(); h.run_steps(3); hover(&mut h, "16"); @@ -166,7 +166,7 @@ fn the_page_reset_puts_the_parameters_back() { e.padding = "none".into(); e.skip = vec![0]; h.run_steps(3); - click(&mut h, "Resets all settings to default values"); + click(&mut h, "Restore the default export parameters"); let e = &h.state().ui.export; assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs index c8d71ddd..68f310df 100644 --- a/crates/ui-egui/tests/it/export_usd_asset.rs +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -132,11 +132,8 @@ fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { let console = &h.state().ui.export.console; assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); - assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Writing material_ball texture on disk")), "{console:?}"); - assert!( - console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Writing ") && text.ends_with(" texture on disk"))), - "the textures are still listed" - ); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); } #[test] @@ -182,7 +179,7 @@ fn restoring_the_default_parameters_unticks_export_usd_asset() { checkbox(&h).click(); h.run_steps(3); assert!(h.state().ui.export.usd_asset); - h.get_by_label("Resets all settings to default values").click(); + h.get_by_label("Restore the default export parameters").click(); h.run_steps(3); assert!(!h.state().ui.export.usd_asset); } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 918bea96..c063ca31 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -91,7 +91,7 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drag and drop maps on output's channels to setup your export."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { assert!(h.query_by_label(text).is_some(), "{text}"); } assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); @@ -109,8 +109,8 @@ fn the_tab_shows_the_preset_tools_and_map_editor() { let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center(); h.hover_at(info); h.run_steps(30); - assert!(h.query_by_label("Select the naming pattern used to display the input maps on this page.").is_some()); - assert!(h.query_by_label("Some input maps (channels) may be named differently depending on the shader used as a Texture Set.").is_some()); + assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some()); + assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some()); } #[test] @@ -376,7 +376,7 @@ fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { } #[test] -fn the_map_lists_stand_in_three_panes_with_the_reference_names() { +fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { let library = TemplateLibrary::new("panes"); let h = harness(&library); @@ -387,18 +387,19 @@ fn the_map_lists_stand_in_three_panes_with_the_reference_names() { assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Transmission", "Subsurface", "Fuzz/Sheen", "Thin-film", "Miscellaneous", "User Channels"] { + for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Specular level", "Sheen opacity", "Coat normal", "Emissive", "World space normal", "Bent normals", "Normal DirectX", "f0"] { + for name in ["Specular level", "Sheen weight", "Coat normal", "Emissive", "World Space Normal", "Bent Normals", "Normal DirectX", "F0 from specular level"] + { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "Thin-film weight", "User31", "1/ior", "Glossiness²", "2D View"] { + for name in ["Base weight", "Coat tangent", "Thin film weight", "Subsurface radius"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } - for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "World Space Normal", "Emission color", "Other"] { + for gone in ["Drag onto an output channel", "Texture set channels", "Constants", "Emission color"] { assert!(h.query_by_label(gone).is_none(), "{gone}"); } } @@ -410,24 +411,24 @@ fn a_map_dropped_on_a_channel_asks_which_of_its_channels_to_use() { click(&mut h, "R+G+B+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let green = last_window_button(&h, "G: Default black").rect().center(); + let green = last_window_button(&h, "G: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, green); - assert!(h.query_by_label("From Base color").is_some(), "the popup names the dropped map"); - assert!(h.query_by_label("RGB Channels").is_none(), "only the RGB swatch offers RGB Channels"); - for choice in ["R Channel", "G Channel", "B Channel"] { + assert!(h.query_by_label("Which part of Base color?").is_some(), "the popup names the dropped map"); + assert!(h.query_by_label("Red, green and blue").is_none(), "only the RGB swatch offers all three"); + for choice in ["Red channel", "Green channel", "Blue channel"] { assert!(!h.get_by_label(choice).accesskit_node().is_disabled(), "{choice}"); } - for greyed in ["Gray Channel", "A Channel"] { + for greyed in ["Gray value", "Alpha channel"] { assert!(h.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed}"); } - h.get_by_label("B Channel").click(); + h.get_by_label("Blue channel").click(); h.run_steps(4); let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); assert!(map.channels.contains(&(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 2 })), "{:?}", map.channels); - assert!(h.query_by_label("From Base color").is_none(), "the popup closed"); - assert!(h.query_all_by_label("G: Base color (Blue)").next().is_some(), "the swatch names its map and channel"); + assert!(h.query_by_label("Which part of Base color?").is_none(), "the popup closed"); + assert!(h.query_all_by_label("G: Base color, blue channel").next().is_some(), "the swatch names its map and channel"); } #[test] @@ -437,15 +438,15 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { click(&mut h, "RGB+A"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; - let rgb = last_window_button(&h, "RGB: Default black").rect().center(); + let rgb = last_window_button(&h, "RGB: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, rgb); - h.get_by_label("RGB Channels").click(); + h.get_by_label("Red, green and blue").click(); h.run_steps(4); let map = h.state().session.export_preset("Mine").unwrap().maps[last].clone(); let spread: Vec<_> = (0..3).map(|component| SourceRef::Channel { channel: Channel::BaseColor, component }).collect(); assert_eq!(map.channels.iter().take(3).map(|(_, source)| source.clone()).collect::>(), spread); - assert!(h.query_all_by_label("RGB: Base color (RGB)").next().is_some()); + assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } #[test] @@ -455,17 +456,17 @@ fn escape_closes_the_from_popup_without_assigning() { click(&mut h, "Gray"); let before = h.state().session.export_preset("Mine").unwrap(); - let gray = last_window_button(&h, "Gr: Default black").rect().center(); + let gray = last_window_button(&h, "Gr: Empty (writes black)").rect().center(); drop_on(&mut h, SourceRef::Channel { channel: Channel::Metallic, component: 0 }, gray); - assert!(h.query_by_label("From Metallic").is_some()); - assert!(!h.get_by_label("Gray Channel").accesskit_node().is_disabled()); - assert!(h.get_by_label("A Channel").accesskit_node().is_disabled()); - assert!(h.query_by_label("R Channel").is_none(), "a gray map has no R, G or B"); + assert!(h.query_by_label("Which part of Metallic?").is_some()); + assert!(!h.get_by_label("Gray value").accesskit_node().is_disabled()); + assert!(h.get_by_label("Alpha channel").accesskit_node().is_disabled()); + assert!(h.query_by_label("Red channel").is_none(), "a gray map has no R, G or B"); h.key_press(egui::Key::Escape); h.run_steps(4); - assert!(h.query_by_label("From Metallic").is_none(), "Escape closes the popup"); + assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } @@ -502,17 +503,17 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv click(&mut h, "RGB"); let last = h.state().session.export_preset("Mine").unwrap().maps.len() - 1; let file = &h.state().session.export_preset("Mine").unwrap().maps[last].file; - assert!(file.ends_with("_RGB"), "the reference's name for a new RGB row: {file}"); + assert!(file.ends_with("_RGB"), "a new RGB row is named after its layout: {file}"); assert!(file.contains("$textureSet"), "each texture set writes a file of its own: {file}"); - last_window_button(&h, "RGB: Default black").click(); + last_window_button(&h, "RGB: Empty (writes black)").click(); h.run_steps(4); assert!(h.query_by_label("Clear channel").is_some()); - h.get_by_label("Split/Collapse RGB").click(); + h.get_by_label("Separate R, G and B").click(); h.run_steps(4); assert_eq!(h.state().ui.export.draft_split.get(last), Some(&true), "R, G and B show apart"); - let green = last_window_button(&h, "G: Default black"); + let green = last_window_button(&h, "G: Empty (writes black)"); let at = green.rect().center(); green.click_secondary(); h.run_steps(4); @@ -522,7 +523,7 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); - assert!(h.query_all_by_label("G: Default black, inverted").next().is_some(), "the swatch says it is inverted"); + assert!(h.query_all_by_label("G: Empty (writes black), inverted").next().is_some(), "the swatch says it is inverted"); } #[test] @@ -544,7 +545,7 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { let input_maps = h.get_by_label("Input maps").rect(); let removes: Vec = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect(); - let alpha = last_window_button(&h, "A: Default white").rect(); + let alpha = last_window_button(&h, "A: Empty (writes white)").rect(); assert!(!removes.is_empty()); for remove in removes { diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 5728889f..aab7c36d 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -119,7 +119,7 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { } assert!(harness.query_by_label_contains("textures selected for export").is_some()); assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shaders parameters")); + assert!(says_not_available(&mut harness, "Export shader settings")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs index be849be0..bdb1ee65 100644 --- a/crates/ui-egui/tests/it/template_invert.rs +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -67,11 +67,11 @@ fn invert_toggle_changes_the_saved_template() { assert!(saved(&h).is_empty()); // Three maps in R, G and B: one swatch per channel - for swatch in ["R: Roughness (Grayscale)", "G: Metallic (Grayscale)", "B: Constant 0.50"] { + for swatch in ["R: Roughness, gray value", "G: Metallic, gray value", "B: Constant 0.50"] { assert!(h.query_all_by_label(swatch).next().is_some(), "{swatch}"); } - toggle_invert(&mut h, "G: Metallic (Grayscale)"); + toggle_invert(&mut h, "G: Metallic, gray value"); assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); - toggle_invert(&mut h, "G: Metallic (Grayscale), inverted"); + toggle_invert(&mut h, "G: Metallic, gray value, inverted"); assert!(saved(&h).is_empty(), "a second click turns it off"); } From 5103d2256a6d5a6e60b9be166f4e3ee155acf730 Mon Sep 17 00:00:00 2001 From: vkleinmp Date: Tue, 24 Nov 2026 12:53:55 +0100 Subject: [PATCH 19/20] ui-parity: describe the export UI's own wording Co-Authored-By: Claude Opus 5.5 --- docs/ui-parity.md | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 573bed16..bba5be33 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -281,17 +281,17 @@ that numbers hide once a tile is under 40 points on screen. - **SETTINGS** ([#671](https://github.com/storytold/texturecraft/issues/671)): the texture set list has the reference's menu (*Check all*, *Uncheck all*, *Invert all*); *General Export - Parameters* has its reset button ("Resets all settings to default values"). *Output directory* + Parameters* has its reset button ("Restore the default export parameters"). *Output directory* is a button showing the path (it opens the folder picker) with an *R* button ("Reset to default"). The template list starts with the reference's first group (TextureCraft has "Document channels + Normal + AO (No Alpha)", the new name of its default template, and "glTF PBR Metal Roughness"; the others are greyed with "Not available yet"; one entry names another - vendor's product and is left out), then a separator ("This preset is not available for the current project") and every other template sorted by name. File type lists "Based on output + vendor's product and is left out), then a separator ("Some templates in this list are unavailable") and every other template sorted by name. File type lists "Based on output template", then the types in the reference order and names ("targa", "jpeg", "tiff"). Size adds "Maximum size for all Texture Sets" and 128. Padding uses the reference order; the dilation width is a button with a "Dilation (pixels)" slider, greyed for paddings without a - width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry the - reference's tooltips word for word. The window is 1100 x 740 as in the reference + width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry + tooltips saying what they select, write, keep or restore. The window is 1100 x 740 as in the reference ([#789](https://github.com/storytold/texturecraft/issues/789)). Cancel, and closing the window, go back to the settings the window opened with; the window always opens on SETTINGS. @@ -299,8 +299,8 @@ that numbers hide once a tile is under 40 points on screen. on a texture set row shows its *General Export Parameters*: Output template, File type, Size and Padding with the inherited value as text (for example "1024x1024 (Texture Set size)"). The pencil button ("Enable override") turns a row into its list; a set with an override gets "*" - ("Override(s) active"). The header menu has *Enable override for all items* and *Disable - override for all items*. The template list leaves out the entries the reference leaves out + ("Override(s) active"). The header menu has *Override every item* and *Clear all + overrides*. The template list leaves out the entries the reference leaves out there; sizes read "128x128" ... "8192x8192". Export, the footer count and LIST OF EXPORTS use each set's own settings. Ticks and overrides belong to the project and follow each texture set by name (another project starts without them); renaming a template on OUTPUT TEMPLATES takes @@ -309,7 +309,7 @@ that numbers hide once a tile is under 40 points on screen. parameters, one row per map the set exports: a tick, the file name pattern (cut at the front with "…" when long, the whole pattern as tooltip), its own *Enable override* and the inherited "png 8 bits". An override gives the map its own file type and bit depth (`maps` of - `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Enable override for all items* and *Disable override for all items*; *Include all* ticks every map + `file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Override every item* and *Clear all overrides*; *Include all* ticks every map again. The patterns are cut after 26 characters (the reference cuts by pixel width). - **File types** ([#672](https://github.com/storytold/texturecraft/issues/672)): File type lists bmp, jpeg, jng, pgm, png, targa, tiff, hdr, exr, j2k, jp2, webp, psd and sbsar; j2k, jp2 @@ -347,27 +347,27 @@ that numbers hide once a tile is under 40 points on screen. middle reads "Current preset: ", *Output maps* with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A on the same row, and a footer with drag-and-drop guidance and the number of output maps. Each output map is one row: a drag grip (drag it onto another row to move the map), the - file name, "$" ("Add expressions in the path that will be replaced during export": $project, + file name, "$" ("Insert a variable": $project, $mesh, $textureSet, $udim, $uvTileName greyed, $colorSpace, then TextureCraft's $channel), the channel swatches (Gr, RGB or R, G, B, then A), the file format ("File format") and bit depth ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". - Create names new rows "Grayscale", "RGB" and "RGB Alpha" after "$mesh_$textureSet_", so the + Create names new rows "Gray", "RGB" and "RGBA" after "$mesh_$textureSet_", so the texture sets of one export do not write the same file, with "_1", "_2" when taken. An - empty swatch reads "Default black" ("Default white" for A), a filled one " ()", - e.g. "Base color (Red)" or "Metallic (Grayscale)". Dropping a map on a swatch opens "From ": - a gray map offers *Gray Channel* and *A Channel*, a colour map *Gray Channel*, *R Channel*, *G - Channel*, *B Channel* and *A Channel*, on the RGB swatch first *RGB Channels*; Escape assigns + empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A), a filled one + ", ", e.g. "Base color, red channel" or "Metallic, gray value". Dropping a map on a + swatch asks "Which part of ?": a gray map offers *Gray value* and *Alpha channel*, a colour map + *Gray value*, *Red channel*, *Green channel*, *Blue channel* and *Alpha channel*, on the RGB swatch first *Red, green and blue*; Escape assigns nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A - click on a swatch offers *Clear channel*, on RGB, R, G and B also *Split/Collapse RGB*; R, G - and B that read different maps cannot collapse (the item is greyed). The right side has the - *Input maps* pane in the reference's groups and names (Base ... Miscellaneous, User Channels), + click on a swatch offers *Clear channel*, on RGB, R, G and B also *Separate R, G and B*; R, G + and B that read different maps cannot be joined (the item is greyed). The right side has the + *Input maps* pane in the OpenPBR parameter groups (Base ... Geometry, then Other for + TextureCraft's channels outside OpenPBR), each map TextureCraft has under its own name, and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template - uses get a square in their swatch's colour. Input and converted maps TextureCraft does not have - are greyed and cannot be dragged (the reference lists them all alike). TextureCraft keeps + uses get a square in their swatch's colour. OpenPBR inputs TextureCraft has no channel for + are greyed and cannot be dragged; *Converted maps* lists the maps TextureCraft computes. TextureCraft keeps some things the reference does not have, out of the way: Import and Export of template files at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the - arrow keys on a focused grip; the planned file name in the file name's tooltip; and three - converted maps of its own (Normal from height, Roughness from glossiness, Sheen color × weight) - after the reference's. Built-in templates stay read-only and deleting asks first. + arrow keys on a focused grip; the planned file name in the file name's tooltip; and + converted maps of its own such as Normal from height, Roughness from glossiness and Sheen color × weight. Built-in templates stay read-only and deleting asks first. From e8473240fd388617f6d55ac44a73a34cc21cf75a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 24 Nov 2026 21:12:52 +0100 Subject: [PATCH 20/20] Output templates: Import and Export reachable from the keyboard, two tooltip fixes The Presets row gets a Template actions button (three dots) that opens a menu with Import and Export of the selected template. It is focusable, opens with Import focused and closes after an action, so no pointer is needed. The row's right-click menu keeps both entries. An inverted empty swatch names the colour it writes after inversion, and the disabled Separate R, G and B item says R, G and B must read the same map and be inverted alike. --- crates/ui-egui/src/export_templates.rs | 66 +++++++++++++++------ crates/ui-egui/tests/it/output_templates.rs | 41 ++++++++++++- docs/ui-parity.md | 8 ++- 3 files changed, 94 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index de25013f..beaf660f 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -424,6 +424,11 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { act = Some(ListAction::Duplicate(sel.clone())); } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); }); }); ui.add_space(2.0); @@ -465,12 +470,7 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti // TextureCraft's template files, after the reference's entries ui.separator(); - if ui.button(tr("Import a template (.json)")).clicked() { - act = Some(ListAction::Import); - } - if *name == sel && ui.button(tr("Export the selected template (.json)")).clicked() { - act = Some(ListAction::Export); - } + template_file_items(ui, &mut act, *name == sel, false); }); } } @@ -479,6 +479,24 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Opti act } +/// Import, and Export of the selected template when `with_export`; `focus_first` moves the keyboard +/// focus to Import so a menu opened from the keyboard can be used without the pointer. A key press +/// does not close a menu like a click does, so the menu closes itself +fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: bool, focus_first: bool) { + let import = ui.button(tr("Import a template (.json)")); + if focus_first { + import.request_focus(); + } + if import.clicked() { + *act = Some(ListAction::Import); + ui.close(); + } + if with_export && ui.button(tr("Export the selected template (.json)")).clicked() { + *act = Some(ListAction::Export); + ui.close(); + } +} + /// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in /// the accent colour fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { @@ -1198,13 +1216,21 @@ fn read_channel_name(map: &MapSpec, source: &SourceRef, target: ChannelTarget) - } } -/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, -/// else ", "; another constant (TextureCraft's own) gives its value -fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget) -> String { +/// A swatch's tooltip: "Empty (writes black)" ("Empty (writes white)" for alpha) when empty, the +/// other way round when the swatch is inverted, else ", "; another constant +/// (TextureCraft's own) gives its value +fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inverted: bool) -> String { let alpha = target == ChannelTarget::One(Dest::A); + let cleared = if alpha { CLEARED_ALPHA } else { CLEARED_VALUE }; + let written = if inverted { 1.0 - cleared } else { cleared }; match source { - SourceRef::Constant(value) if alpha && (*value - CLEARED_ALPHA).abs() < f32::EPSILON => tr("Empty (writes white)").to_string(), - SourceRef::Constant(value) if !alpha && (*value - CLEARED_VALUE).abs() < f32::EPSILON => tr("Empty (writes black)").to_string(), + SourceRef::Constant(value) if (*value - cleared).abs() < f32::EPSILON => { + if written > 0.5 { + tr("Empty (writes white)").to_string() + } else { + tr("Empty (writes black)").to_string() + } + } SourceRef::Constant(value) => trf("Constant {value}", &[("value", &format!("{value:.2}"))]), _ => { let name = map_lists::name_of(source).map_or_else(String::new, |name| tr(name).to_string()); @@ -1250,7 +1276,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let label = target_label(target); let inverted = target.dests().iter().all(|dest| map.inverted.contains(dest)); - let tooltip = swatch_tooltip(map, &source, target); + let tooltip = swatch_tooltip(map, &source, target, inverted); let mut name = trf("{channel}: {tooltip}", &[("channel", &label), ("tooltip", &tooltip)]); if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); @@ -1284,7 +1310,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo let mut checked = shows_split; let can_toggle = !shows_split || rgb_one_map(map); let item = ui.add_enabled(can_toggle, egui::Checkbox::new(&mut checked, tr("Separate R, G and B"))); - let item = item.on_disabled_hover_text(tr("R, G and B read different maps: clear two of them to join them")); + let item = item.on_disabled_hover_text(tr("R, G and B can only be joined when they read the same map and are inverted alike")); if item.changed() { changed |= split_or_collapse(map, split, shows_split); } @@ -1639,8 +1665,14 @@ mod tests { let cleared = [(Dest::R, 0.0), (Dest::G, 0.0), (Dest::B, 0.0), (Dest::A, 1.0)].map(|(dest, value)| (dest, SourceRef::Constant(value))); assert_eq!(map.channels, cleared); assert!(map.inverted.is_empty(), "a cleared channel writes its default, not its inverse"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb), "Empty (writes black)"); - assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A)), "Empty (writes white)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb, false), "Empty (writes black)"); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A), false), "Empty (writes white)"); + assert_eq!( + swatch_tooltip(&map, &SourceRef::Constant(0.0), ChannelTarget::Rgb, true), + "Empty (writes white)", + "inverted, the empty colour writes its inverse" + ); + assert_eq!(swatch_tooltip(&map, &SourceRef::Constant(1.0), ChannelTarget::One(Dest::A), true), "Empty (writes black)"); } #[test] @@ -1661,11 +1693,11 @@ mod tests { apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::AllRgb); assert!(rgb_spread(&map)); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, RGB"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb, false), "Base color, RGB"); apply_pick(&mut map, ChannelTarget::Rgb, &ch(Channel::BaseColor, 0), SourcePick::Component(0)); assert_eq!(swatch_targets(&map, false), vec![ChannelTarget::Rgb], "R of one map in R, G and B stays one swatch"); - assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb), "Base color, red channel"); + assert_eq!(swatch_tooltip(&map, &ch(Channel::BaseColor, 0), ChannelTarget::Rgb, false), "Base color, red channel"); } #[test] diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index c063ca31..1cdba31a 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -8,6 +8,7 @@ use serde_json::json; use texturecraft_engine::core::Channel; use texturecraft_engine::formats::{Dest, SourceRef}; use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; use texturecraft_ui_egui::state::{MapExport, SetExport}; #[path = "output_template/template_library.rs"] @@ -375,6 +376,44 @@ fn the_presets_row_holds_copy_minus_and_plus_without_tooltips() { assert!(h.query_by_label("Export the selected template (.json)").is_some()); } +/// Press `key` with no pointer event +fn press(h: &mut Harness<'_, TextureCraftApp>, key: egui::Key) { + h.key_press(key); + h.run_steps(4); +} + +#[test] +fn import_and_export_are_reachable_from_the_keyboard_alone() { + let library = TemplateLibrary::new("keyboard-actions"); + let mut h = harness(&library); + let file = library.0.join("exported_template.json"); + let answer = file.clone(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + let templates_before = h.state().session.export_presets.list.len(); + + // The actions menu is a named button the keyboard focus reaches + h.get_by_role_and_label(egui::Role::Button, "Template actions").focus(); + h.run_steps(2); + press(&mut h, egui::Key::Enter); + let import = h.get_by_label("Import a template (.json)"); + assert!(import.accesskit_node().is_focused(), "the menu opens with Import focused"); + + press(&mut h, egui::Key::Tab); + assert!(h.get_by_label("Export the selected template (.json)").accesskit_node().is_focused(), "Tab moves on to Export"); + press(&mut h, egui::Key::Enter); + assert!(std::fs::read_to_string(&file).unwrap().contains("\"Mine\""), "Export wrote the selected template"); + + assert!(h.query_by_label("Import a template (.json)").is_none(), "the menu closes after the action"); + + h.get_by_role_and_label(egui::Role::Button, "Template actions").focus(); + h.run_steps(2); + press(&mut h, egui::Key::Enter); + press(&mut h, egui::Key::Enter); + h.run_steps(4); + assert_eq!(h.state().session.export_presets.list.len(), templates_before + 1, "Import added the exported template"); + assert!(h.state().toasts.iter().any(|toast| toast.text.starts_with("Imported template"))); +} + #[test] fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { let library = TemplateLibrary::new("panes"); @@ -523,7 +562,7 @@ fn a_click_on_a_channel_offers_clear_and_split_or_collapse_and_a_right_click_inv invert.click(); h.run_steps(4); assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[last].inverted, vec![Dest::G]); - assert!(h.query_all_by_label("G: Empty (writes black), inverted").next().is_some(), "the swatch says it is inverted"); + assert!(h.query_all_by_label("G: Empty (writes white), inverted").next().is_some(), "the swatch says it is inverted"); } #[test] diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bba5be33..1e45c49d 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -353,20 +353,22 @@ that numbers hide once a tile is under 40 points on screen. ("Bit depth"; "8 bits + dithering" greyed, templates do not keep it) lists, duplicate and "×". Create names new rows "Gray", "RGB" and "RGBA" after "$mesh_$textureSet_", so the texture sets of one export do not write the same file, with "_1", "_2" when taken. An - empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A), a filled one + empty swatch's tooltip reads "Empty (writes black)" ("Empty (writes white)" for A, the other + way round when the swatch is inverted), a filled one ", ", e.g. "Base color, red channel" or "Metallic, gray value". Dropping a map on a swatch asks "Which part of ?": a gray map offers *Gray value* and *Alpha channel*, a colour map *Gray value*, *Red channel*, *Green channel*, *Blue channel* and *Alpha channel*, on the RGB swatch first *Red, green and blue*; Escape assigns nothing. TextureCraft cannot read a map's gray or alpha yet, so those choices are greyed. A click on a swatch offers *Clear channel*, on RGB, R, G and B also *Separate R, G and B*; R, G - and B that read different maps cannot be joined (the item is greyed). The right side has the + and B that read different maps or are inverted differently cannot be joined (the item is greyed). The right side has the *Input maps* pane in the OpenPBR parameter groups (Base ... Geometry, then Other for TextureCraft's channels outside OpenPBR), each map TextureCraft has under its own name, and a pane with *Mesh maps* above *Converted maps* (highlighted). Maps the selected template uses get a square in their swatch's colour. OpenPBR inputs TextureCraft has no channel for are greyed and cannot be dragged; *Converted maps* lists the maps TextureCraft computes. TextureCraft keeps some things the reference does not have, out of the way: Import and Export of template files - at the end of a preset's right-click menu; a swatch's right-click menu with Invert (an inverted + at the end of a preset's right-click menu and in a *Template actions* button (three dots, left of + copy on the *Presets* row) that the keyboard reaches, with Import focused when it opens; a swatch's right-click menu with Invert (an inverted swatch has a corner mark), Black, Gray 50%, White, the constant's value and the map's layout (RGB, RGBA, Gray, Gray + A); *Move up* and *Move down* in the grip's right-click menu and the arrow keys on a focused grip; the planned file name in the file name's tooltip; and