From 76e8f110ab2d02d92e76c7c5436a5af9527ddb1a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 00:12:11 +0100 Subject: [PATCH 1/5] New project and Project configuration windows follow the reference layout New project now has BASIC SETTINGS (Select... a mesh file, project template, document resolution) and a collapsible ADVANCED SETTINGS section with normal map format, tangent space per fragment, UV tile settings, import settings, Import baked maps, Physical size and Color management, each row with an info icon. The form scrolls while Cancel and Create stay fixed below it; Create waits for a mesh file. The built-in mesh dropdown, the Name field and the save-as-template controls are gone; the project is named after the mesh file. Use UV Tile workflow, Import cameras (new importCameras parameter on file.new), the template, resolution, normal map format and baked maps reach the created project. Settings TextureCraft does not have yet are shown disabled with a "Not available yet" hint; OpenColorIO can be chosen to see its settings, but the project stays Legacy. In the browser, Select... uses the browser's file picker. Edit > Project Configuration gets the same section names and order, the disabled rows, Physical size (collapsed) and Color management, and the reference's recompute note above Cancel and OK. Part of #636. --- README.md | 2 +- crates/engine/src/file_cmds.rs | 38 ++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 2 +- crates/ui-egui/src/new_project_advanced.rs | 281 ++++++++++++++---- crates/ui-egui/src/project_config.rs | 252 +++++++++------- crates/ui-egui/src/project_form.rs | 281 ++++++++++++++++++ crates/ui-egui/src/state.rs | 30 +- crates/ui-egui/src/state/project_config.rs | 2 + crates/ui-egui/src/web_files.rs | 16 +- crates/ui-egui/src/windows.rs | 136 +-------- crates/ui-egui/tests/it/main.rs | 1 + .../tests/it/new_project_baked_maps.rs | 56 ++-- crates/ui-egui/tests/it/new_project_window.rs | 261 ++++++++++++++++ crates/ui-egui/tests/it/project_config.rs | 84 +++++- docs/features.md | 13 +- docs/ui-parity.md | 2 +- 17 files changed, 1111 insertions(+), 347 deletions(-) create mode 100644 crates/ui-egui/src/project_form.rs create mode 100644 crates/ui-egui/tests/it/new_project_window.rs diff --git a/README.md b/README.md index 69cd720c..dc354a99 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ cargo xtask ci # fmt, clippy, test ``` You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts -from a built-in mesh, a project template or your own mesh file (UVs are generated if it has none). +from your own mesh file and a project template (UVs are generated if it has none). Japanese, Chinese, Korean and Arabic interface text uses the fonts of [storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index e4d17f53..b5c215dc 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "New project from a mesh file", [], None, - "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name}", + "{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}", always, new_from_mesh ), @@ -384,8 +384,8 @@ mod native { #[cfg(not(target_arch = "wasm32"))] pub use native::{absolute, open_path, read_mesh}; -/// `file.new {mesh, name?, resolution?, uvTiles?, template?}`: a new project from the mesh file `mesh`, -/// remembering its path for Reimport mesh. +/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the +/// mesh file `mesh`, remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let path = native::path_param(p, "mesh", "file.new")?; @@ -396,6 +396,9 @@ fn new_from_mesh(s: &mut Session, p: &Value) -> Result { let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?; next.doc.project.mesh_path = native::absolute(path); next.log.extend(f.warnings); + if crate::commands::boolp(p, "importCameras") == Some(false) { + next.doc.project.cameras.clear(); + } if let Some(t) = &template { next.apply_template(t); } @@ -669,6 +672,35 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + /// `file.new` keeps the cameras stored in the mesh file unless `importCameras` is false. + #[test] + fn new_from_mesh_imports_cameras_unless_told_not_to() { + let dir = std::env::temp_dir().join(format!("tc_new_cameras_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("shot.gltf"); + let gltf = json!({ + "asset": {"version": "2.0"}, + "buffers": [{"byteLength": 36, "uri": "data:application/octet-stream;base64,AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA"}], + "bufferViews": [{"buffer": 0, "byteLength": 36}], + "accessors": [{"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0]}], + "meshes": [{"primitives": [{"attributes": {"POSITION": 0}}]}], + "cameras": [{"name": "Shot", "type": "perspective", "perspective": {"yfov": 0.8, "znear": 0.1}}], + "nodes": [{"mesh": 0}, {"camera": 0, "translation": [0.5, 0.5, 4.0]}], + "scenes": [{"nodes": [0, 1]}], + "scene": 0 + }); + std::fs::write(&file, serde_json::to_vec(&gltf).unwrap()).unwrap(); + let path = file.display().to_string(); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128})).unwrap(); + assert_eq!(s.doc.project.cameras.len(), 1, "the file's camera comes along by default"); + + crate::execute(&mut s, "file.new", &json!({"mesh": path, "resolution": 128, "importCameras": false})).unwrap(); + assert!(s.doc.project.cameras.is_empty(), "importCameras false leaves the cameras out"); + let _ = std::fs::remove_dir_all(&dir); + } + /// Reimport mesh reads the mesh file again from where it was imported, so a change saved to /// the file since shows up (it used to re-read the project's own copy and change nothing). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 28d8b44f..9f0da289 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,7 @@ mod preview_worker; pub mod profile; #[cfg(not(target_arch = "wasm32"))] mod project_config; +pub mod project_form; pub mod properties_popup; mod rail_popup; pub mod render_mode; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9c66fd45..9c429075 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -163,7 +163,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { } match id { - "ui.newProject" => app.ui.windows.new_project = true, + "ui.newProject" => crate::new_project_advanced::open(app), "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 3247fc8e..835eb41b 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -1,68 +1,219 @@ -//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation +//! File > New project: BASIC SETTINGS (mesh file, template, resolution), ADVANCED SETTINGS (normal +//! map format, UV tiles, import settings, baked maps imported at creation, physical size, color +//! management), and Cancel / Create fixed below the scrolling form. use std::collections::BTreeSet; -use egui::{RichText, Sense, Ui, vec2}; +use egui::{RichText, Ui, vec2}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; -use crate::state::NewProject; +use crate::project_form::{ + FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, + uv_tile_radios, +}; +use crate::state::{Mode, NewProject}; use crate::theme::{Tokens, caption}; -use crate::widgets::{section, section_chevron}; -use crate::windows::file_dialogs_available; - -/// Labels of every New project form row, so Basic and Advanced share one label column -const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; +use crate::widgets::primary_button; +use crate::windows::{dialog, file_dialogs_available}; /// Each normal map format with its command id and label const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; -/// Width of the dialog's dropdowns -pub(crate) const COMBO_WIDTH: f32 = 200.0; +/// Document resolutions offered (texture sets range from 128 to 8192 px) +const RESOLUTIONS: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; -/// Width of the Add... and Clear buttons +/// Width of the dialog's form +const DIALOG_WIDTH: f32 = 560.0; + +/// Leave space around the centered dialog on short viewports +const DIALOG_VIEWPORT_MARGIN: f32 = 32.0; + +/// Room for the title bar and the button row below the scrolling form +const DIALOG_CHROME_HEIGHT: f32 = 96.0; + +/// Width of the Add and Clear buttons const FILE_BUTTON_WIDTH: f32 = 96.0; -/// Tallest the list of added files grows before it scrolls -const FILE_LIST_HEIGHT: f32 = 160.0; +/// Height of the list of added baked map files (it scrolls when longer) +const FILE_LIST_HEIGHT: f32 = 120.0; -/// Width of the widest form label, for the label column of every form grid in the dialog -pub(crate) fn form_label_width(ui: &Ui) -> f32 { - let font = egui::TextStyle::Body.resolve(ui.style()); - FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +/// Width of the Cancel and Create buttons +const BUTTON_WIDTH: f32 = 90.0; + +/// File > New project...: a fresh form (files listed for a failed baked map import stay listed). +pub(crate) fn open(app: &mut TextureCraftApp) { + let baked_maps = std::mem::take(&mut app.ui.new_project.baked_maps); + app.ui.new_project = NewProject { baked_maps, ..NewProject::default() }; + app.ui.windows.new_project = true; } -/// The collapsible Advanced settings section (closed until opened) -pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { - let id = ui.make_persistent_id("np_advanced"); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); - let header = ui - .horizontal(|ui| { - ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); - ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); - }) - .response - .interact(Sense::click()); - if header.clicked() { - state.toggle(ui); +/// The New project dialog. +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.new_project { + return; } - state.show_body_unindented(ui, |ui| { - egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { - ui.label(tr("Normal map format")); - normal_format_combo(app, ui); - ui.end_row(); + let mut open = true; + let (mut create, mut cancel) = (false, false); + // A fixed height keeps the centered window still while its sections lay out + let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN - DIALOG_CHROME_HEIGHT).clamp(120.0, crate::project_form::FORM_HEIGHT); + dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + egui::ScrollArea::vertical().id_salt("np_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { + basic_settings(app, ui); + ui.add_space(8.0); + advanced_settings(app, ui); }); - if file_dialogs_available() { - ui.add_space(4.0); - section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| { - if baked_maps(&mut app.ui.new_project, ui) { - ask_baked_map_files(app); - } + ui.separator(); + let can_create = app.ui.new_project.file.is_some(); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + create = ui + .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH, 0.0))) + .on_disabled_hover_text(tr("Select a 3D mesh first")) + .clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH, 0.0))).clicked(); }); + }); + }); + + if create && create_project(app) { + let new_project = app.ui.new_project.clone(); + app.ui.windows.new_project = false; + app.ui.mode = Mode::Painting; + apply_after_create(app, &new_project); + } + if cancel || !open { + app.ui.windows.new_project = false; + } +} + +/// The `file.new` command for the form: the chosen mesh file with the settings the engine takes at +/// creation (the project is named after the file). None until a mesh file is chosen. +pub fn create_command(new_project: &NewProject) -> Option { + let mesh = new_project.file.as_ref()?; + Some(json!({ + "mesh": mesh, + "resolution": new_project.resolution, + "uvTiles": new_project.uv_tiles == Some(true), + "template": new_project.template, + "importCameras": new_project.import_cameras, + })) +} + +/// Create the project; false (with the error reported) when it failed. +#[cfg(not(target_arch = "wasm32"))] +fn create_project(app: &mut TextureCraftApp) -> bool { + create_command(&app.ui.new_project).is_some_and(|params| app.run("file.new", params).is_some()) +} + +/// Create the project from the mesh file's bytes picked in the browser, as `file.new` does on the +/// desktop. +#[cfg(target_arch = "wasm32")] +fn create_project(app: &mut TextureCraftApp) -> bool { + let new_project = &app.ui.new_project; + let (Some(name), Some(bytes)) = (new_project.file.clone(), new_project.file_bytes.clone()) else { return false }; + let stem = std::path::Path::new(&name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); + let template = app.session.template(&new_project.template); + match texturecraft_engine::Session::from_mesh_bytes_tiled(&name, &bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { + Ok(mut next) => { + if !new_project.import_cameras { + next.doc.project.cameras.clear(); + } + if let Some(template) = &template { + next.apply_template(template); + } + app.session.switch_to(next); + app.pbr_import = None; + true } + Err(error) => { + app.toast(trf("Couldn't open {name}: {error}", &[("name", &name), ("error", &error)]), true); + false + } + } +} + +fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(&tr("Basic settings").to_uppercase())); + let mut select = false; + row(ui, tr("3D mesh"), Some(tr("The mesh file to paint. Create is available once one is selected.")), |ui| { + select = ui.add(egui::Button::new(tr("Select...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked(); + match &app.ui.new_project.file { + Some(path) => { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + None => { + ui.label(RichText::new(tr("No file selected")).italics().color(tokens.text_dim)); + } + } + }); + if select { + ask_mesh_file(app, ui.ctx()); + } + + row(ui, tr("Project template"), Some(tr("The channels, resolution, normal map format and display settings a project starts with")), |ui| { + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(FIELD_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; + } + } + }); + }); + + row(ui, tr("Document resolution (px)"), Some(tr("The texture size of every texture set. It can be changed later.")), |ui| { + let resolution = &mut app.ui.new_project.resolution; + egui::ComboBox::from_id_salt("np_res").width(FIELD_WIDTH).selected_text(format!("{0} x {0}", *resolution)).show_ui(ui, |ui| { + for size in RESOLUTIONS { + ui.selectable_value(resolution, size, format!("{size} x {size}")); + } + }); + }); +} + +/// The collapsible ADVANCED SETTINGS section (open at first) +fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + collapsible(ui, "np_advanced_settings", &tr("Advanced settings").to_uppercase(), true, None, |ui| { + row( + ui, + tr("Normal map format"), + Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), + |ui| normal_format_combo(app, ui), + ); + tangent_space_row(ui); + + ui.add_space(4.0); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)"))); + note(ui, tr("You won't be able to change UV Tile settings after creating the project.")); + let new_project = &mut app.ui.new_project; + let mut uv_tiles = new_project.uv_tiles == Some(true); + if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { + new_project.uv_tiles = Some(uv_tiles); + } + uv_tile_radios(ui, uv_tiles, tr("Tick Use UV Tile workflow first")); + + ui.add_space(4.0); + sub_title(ui, tr("Import settings"), None); + check_row(ui, Some(tr("Keep the cameras stored in the mesh file")), |ui| ui.checkbox(&mut new_project.import_cameras, tr("Import cameras")), |_| {}); + auto_unwrap_row(ui); + + ui.add_space(4.0); + collapsible(ui, "np_import_baked_maps", tr("Import baked maps"), true, None, |ui| { + if baked_maps(&mut app.ui.new_project, ui) { + ask_baked_map_files(app); + } + }); + physical_size(ui, "np_physical_size", true); + color_management(ui, "np_color_management", &mut app.ui.new_project.color_management); }); } @@ -71,7 +222,7 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let template_format = app.session.template(&new_project.template).map(|template| template.normal_format).unwrap_or_default(); let current = new_project.normal_format.unwrap_or(template_format); let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); - egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("np_normal_format").width(FIELD_WIDTH).selected_text(current_label).show_ui(ui, |ui| { for (format, _, label) in NORMAL_FORMATS { if ui.selectable_label(format == current, label).clicked() { new_project.normal_format = Some(format); @@ -80,33 +231,38 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -/// The baked map list and its buttons; true when Add was clicked. +/// The baked map hint, buttons, file list and naming scheme; true when Add was clicked. fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { let tokens = Tokens::get(ui.ctx()); let mut add = false; ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_min_width(hint_width); - ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + ui.add(egui::Label::new(tr("Import mesh normal maps and baked maps for all materials.")).wrap()); }); - if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { - add = true; - } + let add_button = ui.add_enabled(file_dialogs_available(), egui::Button::new(tr("Add")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))); + add = unavailable(add_button).clicked(); if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { new_project.baked_maps.clear(); } }); - if new_project.baked_maps.is_empty() { - return add; - } ui.add_space(4.0); - egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { - for path in &new_project.baked_maps { - ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); - } + egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT).auto_shrink([false, false]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.label(RichText::new(tr("Automatic normal maps assignation scheme: $(MATERIAL_NAME)_normal")).color(tokens.text_dim)) + .on_hover_text(tr("Name each file after its texture set, like Body_normal.png")); }); add } @@ -151,6 +307,23 @@ fn file_name(path: &str) -> String { std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) } +#[cfg(not(target_arch = "wasm32"))] +fn ask_mesh_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { + use crate::file_dialogs::{Bound, FileDialog}; + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); + app.ask_file(dialog, Bound::App, |app, paths| { + if let Some(path) = paths.first() { + app.ui.new_project.file = Some(path.display().to_string()); + app.ui.new_project.file_bytes = None; + } + }); +} + +#[cfg(target_arch = "wasm32")] +fn ask_mesh_file(_app: &mut TextureCraftApp, ctx: &egui::Context) { + crate::web_files::pick_new_project_mesh(ctx); +} + #[cfg(not(target_arch = "wasm32"))] fn ask_baked_map_files(app: &mut TextureCraftApp) { use crate::file_dialogs::{Bound, FileDialog}; diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 80942b1b..8acf6cc9 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -1,5 +1,7 @@ -//! Edit > Project Configuration...: the project's settings in sections. Today it has one, the -//! 3D mesh: pick another mesh file for the project, or read the current one again. +//! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh +//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format +//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment, +//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled. use std::sync::atomic::{AtomicU64, Ordering}; @@ -11,18 +13,23 @@ use crate::TextureCraftApp; use crate::dock::info_icon; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; +use crate::project_form::{ + FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, uv_tile_radios, +}; use crate::state::ProjectConfig; -use crate::theme::caption; +use crate::theme::{Tokens, caption}; use crate::widgets::primary_button; /// Room for the Select... button and its info icon beside the path. -const SELECT_BUTTON_WIDTH_POINTS: f32 = 150.0; -/// Room for an info icon at the end of a row. -const INFO_WIDTH_POINTS: f32 = 28.0; +const SELECT_BUTTON_WIDTH_POINTS: f32 = 190.0; +/// Room for the title bar, the note and the button row below the scrolling form. +const DIALOG_CHROME_HEIGHT_POINTS: f32 = 120.0; +/// Width of the Cancel and OK buttons. +const BUTTON_WIDTH_POINTS: f32 = 90.0; /// Keep a usable field when the dialog is narrowed. const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; /// Initial width of the configuration dialog. -const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 460.0; +const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports. const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; @@ -36,6 +43,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { reimport: false, preserve: true, normal_format: None, + color_management: crate::project_form::ColorManagement::Legacy, confirm: false, project: app.session.project_id, opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), @@ -135,122 +143,143 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open) - .default_width(DEFAULT_DIALOG_WIDTH_POINTS) - .max_height((ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS).max(0.0)) - .vscroll(true); + // A fixed height keeps the centered window still while its sections lay out + let form_height = + (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS).clamp(120.0, crate::project_form::FORM_HEIGHT); + let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS); dialog.show(ctx, |ui| { - // Keep the project sections in the order users expect - ui.label(caption(tr("3D MESH"))); - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.label(tr("3D mesh")); - info_icon(ui, tr("The mesh file the project is built on. Hover the path to see it in full.")); + ui.set_width(DEFAULT_DIALOG_WIDTH_POINTS); + egui::ScrollArea::vertical().id_salt("project_config_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { + // Keep the project sections in the order users expect + ui.label(caption(tr("3D MESH"))); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.label(tr("3D mesh")); - let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone()); - let font = egui::TextStyle::Body.resolve(ui.style()); - let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); - let measure = |text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; + let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone()); + let font = egui::TextStyle::Body.resolve(ui.style()); + let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); + let painter = ui.painter().clone(); + let measure = |text: &str| painter.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).rect.width() <= path_width_points; - if display_path.is_empty() { - ui.weak(tr("Built-in mesh")); - } else { - ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The mesh file the project is built on. Select... chooses another one, read when you press OK.")); + select = ui.button(tr("Select...")).clicked(); + if display_path.is_empty() { + ui.weak(tr("Built-in mesh")); + } else { + ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path); + } + }); + }); + if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { + ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - info_icon(ui, tr("Choose another mesh file for the project. It is read when you press OK.")); - select = ui.button(tr("Select...")).clicked(); + // A selected replacement always reads the mesh again + // A missing source file cannot be reimported + let mut reimport = config.reimport || chosen_mesh.is_some(); + let can_reimport_source = chosen_mesh.is_none() && source_file_available; + let reimport_checkbox = check_row( + ui, + Some(tr("Read the mesh file again, keeping the layers and painted strokes")), + |ui| ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))), + |_| {}, + ); + + if can_reimport_source { + config.reimport = reimport; + } else if chosen_mesh.is_none() { + reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); + } + + ui.add_space(12.0); + ui.label(caption(tr("PROJECT SETTINGS"))); + ui.add_space(4.0); + let shown_format = config.normal_format.unwrap_or(current_normal_format); + row( + ui, + tr("Normal map format"), + Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), + |ui| { + egui::ComboBox::from_id_salt(tr("Normal map format")) + .width(FIELD_WIDTH) + .wrap_mode(egui::TextWrapMode::Truncate) + .selected_text(format_name(shown_format)) + .show_ui(ui, |ui| { + for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { + if ui.selectable_label(format == shown_format, format_name(format)).clicked() { + config.normal_format = (format != current_normal_format).then_some(format); + } + } + }) + .response + .on_hover_text(tr( + "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", + )); + }, + ); + tangent_space_row(ui); + + // Texture Set Settings owns UV tile changes + ui.add_space(4.0); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings."))); + note(ui, tr("You can't change UV Tile settings once a project has been created.")); + let has_tiles = texture_set_tiles.iter().any(|(_, tile_text)| tile_text.is_some()); + let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); + check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles.clone(), tr("Use UV Tile workflow"))), |_| {}).on_disabled_hover_text(tiles_hint); + uv_tile_radios(ui, false, tiles_hint); + ui.indent("project_config_tiles", |ui| { + if !has_tiles { + ui.label(egui::RichText::new(tr("No UV tiles")).weak()); + } + for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) { + let tile_list = tile_text.as_deref().unwrap_or_default(); + ui.label( + egui::RichText::new(if texture_set_tiles.len() > 1 { + trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) + } else { + tile_list.to_string() + }) + .weak(), + ); + } + ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); }); + + ui.add_space(4.0); + sub_title(ui, tr("Import settings"), None); + check_row( + ui, + Some(tr("Keep the cameras stored in the mesh file")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Import cameras")))), + |_| {}, + ); + + // Import settings matter only when a mesh will be read + let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); + check_row( + ui, + Some(tr("Painted strokes follow the surface when the new mesh's UVs differ")), + |ui| ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))), + |_| {}, + ); + auto_unwrap_row(ui); + + ui.add_space(4.0); + physical_size(ui, "project_config_physical_size", false); + color_management(ui, "project_config_color_management", &mut config.color_management); }); - if chosen_mesh.is_none() && !current_mesh_path.is_empty() && !source_file_available { - ui.colored_label(ui.visuals().error_fg_color, tr("File not found")); - } - - ui.add_space(4.0); - - // A selected replacement always reads the mesh again - // A missing source file cannot be reimported - let mut reimport = config.reimport || chosen_mesh.is_some(); - let can_reimport_source = chosen_mesh.is_none() && source_file_available; - let reimport_checkbox = ui - .horizontal(|ui| { - let checkbox = ui.add_enabled(can_reimport_source, egui::Checkbox::new(&mut reimport, tr("Reimport mesh"))); - info_icon(ui, tr("Read the mesh file again, keeping the layers and painted strokes")); - checkbox - }) - .inner; - - if can_reimport_source { - config.reimport = reimport; - } else if chosen_mesh.is_none() { - reimport_checkbox.on_disabled_hover_text(tr("There is no mesh file to read again. Select one.")); - } ui.add_space(8.0); - ui.label(caption(tr("Import settings"))); - - // Import settings matter only when a mesh will be read - let importing = chosen_mesh.is_some() || (config.reimport && source_file_available); - ui.horizontal(|ui| { - ui.add_enabled(importing, egui::Checkbox::new(&mut config.preserve, tr("Preserve stroke positions on mesh"))); - info_icon(ui, tr("Painted strokes follow the surface when the new mesh's UVs differ")); - }); - - ui.add_space(12.0); - ui.label(caption(tr("PROJECT SETTINGS"))); - ui.add_space(4.0); - let shown_format = config.normal_format.unwrap_or(current_normal_format); - ui.horizontal(|ui| { - ui.label(tr("Normal map format")); - egui::ComboBox::from_id_salt(tr("Normal map format")) - .width((ui.available_width() - INFO_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS)) - .wrap_mode(egui::TextWrapMode::Truncate) - .selected_text(format_name(shown_format)) - .show_ui(ui, |ui| { - for format in [NormalFormat::OpenGl, NormalFormat::DirectX] { - if ui.selectable_label(format == shown_format, format_name(format)).clicked() { - config.normal_format = (format != current_normal_format).then_some(format); - } - } - }) - .response - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); - info_icon(ui, tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")); - }); - ui.add_space(4.0); - - // Texture Set Settings owns UV tile changes - ui.horizontal(|ui| { - ui.label(tr("UV Tile settings (UDIMs)")); - info_icon(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); - }); - if texture_set_tiles.iter().all(|(_, tile_text)| tile_text.is_none()) { - ui.label(egui::RichText::new(tr("No UV tiles")).weak()); - } - for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) { - let tile_list = tile_text.as_deref().unwrap_or_default(); - ui.label( - egui::RichText::new(if texture_set_tiles.len() > 1 { - trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) - } else { - tile_list.to_string() - }) - .weak(), - ); - } - ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); - - ui.add_space(12.0); - ui.label(egui::RichText::new(tr("Choosing or reimporting a mesh recomputes all channels.")).small().weak()); + ui.label(egui::RichText::new(tr("Please note: Changing any of these settings will cause all channels to be recomputed.")).color(Tokens::get(ui.ctx()).warning)); ui.add_space(4.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ok |= ui.add(primary_button(ui, tr("OK"))).clicked(); - cancel = ui.button(tr("Cancel")).clicked(); + ok |= ui.add(primary_button(ui, tr("OK")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(egui::vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); }); }); @@ -300,7 +329,8 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.project_config = None; } else if let Some(stored) = app.ui.windows.project_config.as_mut() { // A file answer arrives later through the stored state - (stored.reimport, stored.preserve, stored.normal_format, stored.confirm) = (config.reimport, config.preserve, config.normal_format, false); + (stored.reimport, stored.preserve, stored.normal_format, stored.color_management, stored.confirm) = + (config.reimport, config.preserve, config.normal_format, config.color_management, false); // A format retry must not reimport an already changed mesh if ok && mesh_applied { diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs new file mode 100644 index 00000000..1e813ed4 --- /dev/null +++ b/crates/ui-egui/src/project_form.rs @@ -0,0 +1,281 @@ +//! Rows and sections that New project and Edit > Project Configuration share: the label, control +//! and info icon of a setting, collapsible sections, and the settings the engine does not have +//! yet (shown disabled, with a hover hint that says so). + +use egui::{Response, RichText, Sense, Ui}; + +use crate::dock::info_icon; +use crate::i18n::{n_, tr}; +use crate::theme::{Tokens, caption}; +use crate::widgets::section_chevron; + +/// Hover hint of a control whose function TextureCraft does not have yet. +pub const NOT_AVAILABLE: &str = n_("Not available yet"); + +/// Width of the dropdowns and fields at the right of a row. +pub(crate) const FIELD_WIDTH: f32 = 220.0; + +/// Tallest the scrolling form of the two windows grows (the rest scrolls). +pub(crate) const FORM_HEIGHT: f32 = 760.0; + +/// Indent of the rows below a section title. +pub(crate) const ROW_INDENT: f32 = 16.0; + +/// Room kept for the info icon at the end of a row without one. +const INFO_SLOT: f32 = 16.0; + +/// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its +/// settings, but they stay disabled and a project is always created and kept as Legacy. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorManagement { + #[default] + Legacy, + OpenColorIo, +} + +impl ColorManagement { + fn label(self) -> &'static str { + match self { + ColorManagement::Legacy => n_("Legacy"), + ColorManagement::OpenColorIo => "OpenColorIO", + } + } +} + +/// `response` with the not-available hint while it is disabled. +pub(crate) fn unavailable(response: Response) -> Response { + response.on_disabled_hover_text(tr(NOT_AVAILABLE)) +} + +/// A row: `label` at the left, then `control` right-aligned before the info icon (`info`). +pub(crate) fn row(ui: &mut Ui, label: &str, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R) -> R { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.label(label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_slot(ui, info); + control(ui) + }) + .inner + }) + .inner +} + +/// A row that starts with its control (a checkbox or radio button) and ends with the info icon. +/// `trailing` adds a control just before the icon (a button). +pub(crate) fn check_row(ui: &mut Ui, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R, trailing: impl FnOnce(&mut Ui)) -> R { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + let inner = control(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_slot(ui, info); + trailing(ui); + }); + inner + }) + .inner +} + +fn info_slot(ui: &mut Ui, info: Option<&str>) { + match info { + Some(text) => info_icon(ui, text), + None => ui.add_space(INFO_SLOT), + } +} + +/// A bold sub-section title such as Import settings, with an optional info icon at the end. +pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.label(caption(title)); + if let Some(text) = info { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text)); + } + }); +} + +/// A dim italic note in a section. +pub(crate) fn note(ui: &mut Ui, text: &str) { + ui.horizontal(|ui| { + ui.add_space(2.0 * ROW_INDENT); + ui.add(egui::Label::new(RichText::new(text).italics().color(Tokens::get(ui.ctx()).text_dim)).wrap()); + }); +} + +/// A dropdown that cannot be opened, showing `value`, with the not-available hint. +pub(crate) fn disabled_combo(ui: &mut Ui, id: &str, value: &str) -> Response { + let response = ui.add_enabled_ui(false, |ui| egui::ComboBox::from_id_salt(id).width(FIELD_WIDTH).selected_text(value).show_ui(ui, |_| {}).response).inner; + unavailable(response) +} + +/// A collapsible section: a chevron and `title` (clicking either toggles it), an optional info +/// icon at the end of the header, and `body` while open. +pub(crate) fn collapsible(ui: &mut Ui, id: &str, title: &str, default_open: bool, info: Option<&str>, body: impl FnOnce(&mut Ui)) { + let id = ui.make_persistent_id(id); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(title)).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + if let Some(text) = info { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text)); + } + }); + state.show_body_unindented(ui, |ui| { + ui.indent(id.with("body"), body); + }); +} + +/// "Compute tangent space per fragment" (not available yet, so unticked and disabled). +pub(crate) fn tangent_space_row(ui: &mut Ui) { + check_row( + ui, + Some(tr("Compute the tangent space of normal maps per pixel instead of per vertex")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Compute tangent space per fragment")))), + |_| {}, + ); +} + +/// The UV tile workflow radios under "Use UV Tile workflow": per material (what the UV tile +/// workflow does) or one texture set per tile (not available yet). `enabled` while the workflow +/// can be chosen and is on. +pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) { + ui.indent("uv_tile_radios", |ui| { + let preserve = check_row( + ui, + Some(tr("Each material keeps its UV tiles in one texture set, and strokes paint across tiles")), + |ui| ui.add_enabled(enabled, egui::RadioButton::new(true, tr("Preserve UV Tile layout per material and enable painting across tiles"))), + |_| {}, + ); + preserve.on_disabled_hover_text(disabled_hint); + check_row( + ui, + Some(tr("Each UV tile becomes a texture set of its own")), + |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Convert UV Tiles into individual Texture Sets (legacy)")))), + |_| {}, + ); + }); +} + +/// Import settings ▸ Auto-unwrap and its options. Meshes without UVs are always unwrapped, so the +/// box is ticked; turning it off and the options are not available yet. +pub(crate) fn auto_unwrap_row(ui: &mut Ui) { + check_row( + ui, + Some(tr("Generate UVs for meshes that have none")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut true, tr("Auto-unwrap")))), + |ui| { + unavailable(ui.add_enabled(false, egui::Button::new(tr("Auto-unwrap options")))); + }, + ); +} + +/// The Physical size section: the mesh file's own unit scale is what TextureCraft uses; a custom +/// scale and physical-size fill layers are not available yet. +pub(crate) fn physical_size(ui: &mut Ui, id: &str, default_open: bool) { + collapsible(ui, id, tr("Physical size"), default_open, Some(tr("The real-world size of one unit of the mesh")), |ui| { + check_row( + ui, + Some(tr("Use the unit scale stored in the mesh file")), + |ui| ui.radio(true, tr("Use mesh file's internal unit scale (recommended)")), + |_| {}, + ); + check_row( + ui, + Some(tr("Set the size of one unit yourself")), + |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Custom unit scale")))), + |_| {}, + ); + ui.horizontal(|ui| { + ui.add_space(3.0 * ROW_INDENT); + ui.label(tr("1 unit =")); + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(60.0))); + ui.label(tr("cm")); + }); + check_row( + ui, + Some(tr("Fill layers of applied materials are scaled in physical size instead of UV space")), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Switch fill layer scaling to Physical size when assigning materials")))), + |_| {}, + ); + }); +} + +/// Rows of the OpenColorIO settings: (label, shown value, info). They are not available yet. +const OCIO_CONFIGURATION: [(&str, &str, Option<&str>); 1] = + [(n_("OpenColorIO configuration"), "ACES 2.0", Some(n_("The OpenColorIO configuration that defines the color spaces")))]; +const OCIO_IMPORT: [(&str, &str, Option<&str>); 4] = [ + (n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("Floating point images"), "Linear Rec.709 (sRGB)", None), + (n_("Auto detect color spaces"), n_("Parse file name"), Some(n_("Read an imported image's color space from its file name"))), +]; +const OCIO_EXPORT: [(&str, &str, Option<&str>); 3] = [ + (n_("8 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("16 bit images"), "sRGB Encoded Rec.709 (sRGB)", None), + (n_("Floating point images"), "ACEScg", None), +]; + +/// The Color management section. `mode` is the dropdown's choice: Legacy shows the working color +/// space; OpenColorIO shows its settings, all disabled, and a note that it is not available yet +/// (the project stays Legacy whatever is chosen). +pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement) { + collapsible(ui, id, tr("Color management"), true, None, |ui| { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Configuration"))); + row(ui, tr("Color management"), Some(tr("Legacy works in linear sRGB. OpenColorIO manages color through a configuration")), |ui| { + egui::ComboBox::from_id_salt(format!("{id}_mode")).width(FIELD_WIDTH).selected_text(tr(mode.label())).show_ui(ui, |ui| { + for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] { + ui.selectable_value(mode, choice, tr(choice.label())); + } + }); + }); + if *mode == ColorManagement::OpenColorIo { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.add(egui::Label::new(RichText::new(tr("OpenColorIO is not available yet. The project uses Legacy.")).color(tokens.warning)).wrap()); + }); + for (label, value, info) in OCIO_CONFIGURATION { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_{label}"), tr(value))); + } + row(ui, tr("Configuration file"), Some(tr("A custom OpenColorIO configuration file")), |ui| { + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(FIELD_WIDTH))); + }); + } + + ui.add_space(4.0); + ui.label(caption(tr("Color settings"))); + let working_space = if *mode == ColorManagement::OpenColorIo { "ACEScg" } else { "Linear - sRGB Chrominance (ITU-R BT.709)" }; + row(ui, tr("Working color space"), Some(tr("The color space layers are blended in")), |ui| ui.label(working_space)); + if *mode != ColorManagement::OpenColorIo { + return; + } + + row(ui, tr("Standard sRGB color space"), Some(tr("The color space of sRGB images and colors")), |ui| { + disabled_combo(ui, &format!("{id}_srgb"), "sRGB Encoded Rec.709 (sRGB)") + }); + ui.add_space(4.0); + ui.label(caption(tr("Bitmap import color space defaults"))); + for (label, value, info) in OCIO_IMPORT { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_import_{label}"), tr(value))); + } + ui.add_space(4.0); + ui.label(caption(tr("Materials"))); + row(ui, tr("Material color space default"), Some(tr("The color space of material inputs that do not state one")), |ui| { + disabled_combo(ui, &format!("{id}_material"), "sRGB Encoded Rec.709 (sRGB)") + }); + ui.add_space(4.0); + ui.label(caption(tr("Export color spaces"))); + for (label, value, info) in OCIO_EXPORT { + row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_export_{label}"), tr(value))); + } + }); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3b7d7a83..086d4c9d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -166,22 +166,26 @@ impl Prefs { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NewProject { - pub mesh: String, pub resolution: u32, - pub name: String, - /// A mesh file chosen from disk (desktop only). + /// The mesh file chosen with Select... (its path on the desktop, its name in the browser). pub file: Option, - /// UV tile (UDIM) workflow: on, off, or None for when the mesh's UVs leave tile 1001. + /// The browser's copy of the chosen mesh file, read when Create is pressed. + #[serde(skip)] + pub file_bytes: Option>>, + /// Use UV Tile workflow: Some(true) makes UV tile (UDIM) texture sets; otherwise each set paints tile 1001. pub uv_tiles: Option, /// Project template name (built-in or the user's). #[serde(default = "default_template")] pub template: String, - /// Name typed to save the current project's settings as a template. - #[serde(skip)] - pub template_name: String, /// Normal map format of the project and its imported normal maps; None keeps the template's #[serde(default)] pub normal_format: Option, + /// Import settings > Import cameras: keep the cameras stored in the mesh file + #[serde(default = "import_cameras_default")] + pub import_cameras: bool, + /// Color management as chosen in the window (the project is always created as Legacy) + #[serde(skip)] + pub color_management: crate::project_form::ColorManagement, /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) #[serde(skip)] pub baked_maps: Vec, @@ -191,17 +195,21 @@ fn default_template() -> String { texturecraft_engine::template_cmds::DEFAULT_TEMPLATE.into() } +fn import_cameras_default() -> bool { + true +} + impl Default for NewProject { fn default() -> Self { NewProject { - mesh: "material_ball".into(), - resolution: 2048, - name: "Untitled".into(), + resolution: 1024, file: None, + file_bytes: None, uv_tiles: None, template: default_template(), - template_name: String::new(), normal_format: None, + import_cameras: true, + color_management: crate::project_form::ColorManagement::Legacy, baked_maps: Vec::new(), } } diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 33992ec4..174b0987 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -9,6 +9,8 @@ pub struct ProjectConfig { pub preserve: bool, /// The selected normal map format when it differs from the project's pub normal_format: Option, + /// Color management as chosen in the window; nothing is applied (the project stays Legacy) + pub color_management: crate::project_form::ColorManagement, /// Whether Enter requested confirmation in the next frame pub confirm: bool, /// The project that was open when this window opened diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index a436cd01..bf6eb356 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -46,6 +46,8 @@ enum Pick { Cage, /// Export dialog › Output templates: an export template (`.json`). ExportPreset, + /// New project › 3D mesh › Select...: the mesh the project is created from. + NewProjectMesh, } /// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose). @@ -63,6 +65,11 @@ pub fn poll(app: &mut TextureCraftApp) { Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), Pick::HighPoly => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), Pick::Cage => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), + Pick::NewProjectMesh => { + app.ui.new_project.file = Some(name); + app.ui.new_project.file_bytes = Some(std::sync::Arc::new(bytes)); + continue; + } Pick::ExportPreset => { match texturecraft_engine::formats::preset_from_json(&String::from_utf8_lossy(&bytes)) { Ok(p) => crate::export_templates::import(app, &p), @@ -206,8 +213,8 @@ fn zip_files(files: &[ExportedFile]) -> Result, String> { #[cfg(target_arch = "wasm32")] pub use web::{ - download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, save_project, - sync_unsaved, unsaved, + download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, pick_new_project_mesh, + save_project, sync_unsaved, unsaved, }; #[cfg(target_arch = "wasm32")] @@ -260,6 +267,11 @@ mod web { pick(ctx, tr("Export templates"), &["json"], false, Pick::ExportPreset); } + /// New project › Select...: pick the mesh file; Create reads it once it has arrived. + pub fn pick_new_project_mesh(ctx: &egui::Context) { + pick(ctx, tr("3D meshes"), &MESH_EXTENSIONS, false, Pick::NewProjectMesh); + } + fn pick(ctx: &egui::Context, filter: &'static str, exts: &'static [&'static str], multiple: bool, kind: Pick) { let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 5650c4de..306c0266 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -5,7 +5,6 @@ use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::ToneMapping; use texturecraft_engine::core::project::ENV_RESOURCE_PREFIX; -use texturecraft_engine::geom::primitives::BUILTINS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; @@ -13,14 +12,14 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; -use crate::new_project_advanced::COMBO_WIDTH; +#[cfg(not(target_arch = "wasm32"))] use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { start(app, ctx); - new_project(app, ctx); + crate::new_project_advanced::show(app, ctx); about(app, ctx); settings(app, ctx); #[cfg(not(target_arch = "wasm32"))] @@ -461,124 +460,6 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { - if !app.ui.windows.new_project { - return; - } - - let mut open = true; - let mut create = false; - dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { - ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { - ui.label(tr("3D mesh")); - ui.horizontal(|ui| { - let label = app.ui.new_project.file.clone().unwrap_or_else(|| { - BUILTINS - .iter() - .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) - .unwrap_or_default() - }); - egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { - for (id, builtin_label) in BUILTINS { - if ui - .selectable_label( - app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), - trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), - ) - .clicked() - { - app.ui.new_project.mesh = id.to_string(); - app.ui.new_project.file = None; - } - } - }); - if file_dialogs_available() && ui.button(tr("Select...")).clicked() { - ask_mesh_file(app); - } - }); - ui.end_row(); - ui.label(tr("Project template")); - let new_project = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { - let user_templates = app.session.templates.list.iter(); - for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { - if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { - new_project.template = template.name.clone(); - new_project.resolution = template.resolution; - new_project.normal_format = None; - } - } - }); - ui.end_row(); - ui.label(""); - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut app.ui.new_project.template_name).hint_text(tr("Template name")).desired_width(120.0)); - let name = app.ui.new_project.template_name.trim().to_string(); - if ui.add_enabled(!name.is_empty(), egui::Button::new(tr("Save current project as template"))).clicked() - && app.run("project.template.save", json!({"name": name})).is_some() - { - app.ui.new_project.template = name; - app.ui.new_project.template_name.clear(); - } - }); - ui.end_row(); - ui.label(tr("Document resolution")); - egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for size in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); - } - }); - ui.end_row(); - ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |tiles: Option| match tiles { - None => tr("Automatic (from the mesh UVs)"), - Some(true) => tr("On"), - Some(false) => tr("Off"), - }; - egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for tiles in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); - } - }); - ui.end_row(); - ui.label(tr("Name")); - ui.text_edit_singleline(&mut app.ui.new_project.name); - ui.end_row(); - }); - ui.add_space(8.0); - crate::new_project_advanced::advanced_settings(app, ui); - ui.add_space(8.0); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Create"))).clicked() { - create = true; - } - if ui.button(tr("Cancel")).clicked() { - app.ui.windows.new_project = false; - } - }); - }); - }); - if create { - let new_project = app.ui.new_project.clone(); - let (command, mesh) = match &new_project.file { - Some(path) => ("file.new", path.clone()), - None => ("project.new", new_project.mesh.clone()), - }; - let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); - if app.run(command, params).is_some() { - app.ui.windows.new_project = false; - app.ui.mode = Mode::Painting; - crate::new_project_advanced::apply_after_create(app, &new_project); - } - } - if !open { - app.ui.windows.new_project = false; - } -} - #[cfg(not(target_arch = "wasm32"))] fn settings_resources(ctx: &egui::Context) -> (u32, u64) { let id = egui::Id::unique("settings_resources"); @@ -827,19 +708,6 @@ pub fn file_dialogs_available() -> bool { cfg!(not(target_arch = "wasm32")) } -#[cfg(not(target_arch = "wasm32"))] -fn ask_mesh_file(app: &mut TextureCraftApp) { - let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); - app.ask_file(dialog, Bound::App, |app, paths| { - if let Some(p) = paths.first() { - app.ui.new_project.file = Some(p.display().to_string()); - } - }); -} - -#[cfg(target_arch = "wasm32")] -fn ask_mesh_file(_app: &mut TextureCraftApp) {} - /// Remember a project path in File ▸ Recent projects. pub fn remember(app: &mut TextureCraftApp, path: &str) { app.ui.recent.retain(|p| p != path); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4f454304..cdf59747 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -23,6 +23,7 @@ mod layers_panel; mod levels_editor; mod mask_value_swap; mod new_project_baked_maps; +mod new_project_window; mod path_in_view; mod path_list; mod pen_pressure; diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index 39a7c813..9f1c8fee 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -8,23 +8,38 @@ use texturecraft_engine::core::{BakedMap, NormalFormat}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; -fn harness() -> Harness<'static, TextureCraftApp> { +/// Two quads with the materials Ball and Base, like the sample's texture sets +const TWO_MATERIALS: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n\ +usemtl Ball\nf 1/1 2/2 3/3 4/4\nusemtl Base\nf 5/1 6/2 7/3 8/4\n"; + +/// The New project window with `test`'s mesh file (materials Ball and Base) selected +fn harness_for(test: &str) -> Harness<'static, TextureCraftApp> { + let mesh = test_dir(test).join("Ball.obj"); + std::fs::write(&mesh, TWO_MATERIALS).unwrap(); 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.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; - h.run_steps(3); - h.get_by_label("Advanced settings").click(); - h.run_steps(3); - h.get_by_label("Import baked maps").click(); + h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); h.run_steps(3); h } -/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read -fn bake_files(test: &str, files: &[&str]) -> Vec { +fn test_dir(test: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Click Create (fixed below the form) +fn create(h: &mut Harness<'_, TextureCraftApp>) { + h.get_by_label("Create").click(); + h.run_steps(3); +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = test_dir(test); files .iter() .map(|file| { @@ -37,7 +52,7 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { #[test] fn added_files_are_listed_once_and_clear_empties_the_list() { - let mut h = harness(); + let mut h = harness_for("list"); let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); @@ -57,14 +72,13 @@ fn added_files_are_listed_once_and_clear_empties_the_list() { #[test] fn create_imports_the_listed_maps_in_the_chosen_normal_format() { - let mut h = harness(); + let mut h = harness_for("create"); let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths); h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); h.run_steps(3); - h.get_by_label("Create").click(); - h.run_steps(3); + create(&mut h); let state = h.state(); assert!(!state.ui.windows.new_project, "the dialog closes"); @@ -83,19 +97,17 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { #[test] fn a_failed_import_keeps_the_file_list_and_created_project() { - let mut h = harness(); + let mut h = harness_for("failure"); let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]); std::fs::write(&paths[1], b"not an image").unwrap(); add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); - h.state_mut().ui.new_project.name = "Import failure".to_string(); h.run_steps(3); - h.get_by_label("Create").click(); - h.run_steps(3); + create(&mut h); let app = h.state(); assert!(!app.ui.windows.new_project); - assert_eq!(app.session.doc.project.name, "Import failure"); + assert_eq!(app.session.doc.project.name, "Ball", "the project is named after the mesh file"); assert_eq!(app.ui.new_project.baked_maps, paths); assert!(app.session.doc.resources.is_empty() && app.session.images.is_empty()); assert!(app.session.doc.baked.values().all(|baked| baked.maps.is_empty())); @@ -114,12 +126,11 @@ fn new_project_baked_maps_snapshots() { eprintln!("snapshot adapter: {adapter:?}"); TextureCraftApp::new(cc, session) }); + let mesh = test_dir("snapshots").join("Ball.obj"); + std::fs::write(&mesh, TWO_MATERIALS).unwrap(); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; - h.run_steps(6); - h.get_by_label("Advanced settings").click(); - h.run_steps(6); - h.get_by_label("Import baked maps").click(); + h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); h.run_steps(6); let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths); @@ -139,7 +150,7 @@ fn new_project_baked_maps_snapshots() { #[test] fn normal_format_preview_uses_the_same_template_lookup_as_creation() { - let mut h = harness(); + let mut h = harness_for("template"); h.state_mut().session.templates.dir = None; h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap(); @@ -147,7 +158,6 @@ fn normal_format_preview_uses_the_same_template_lookup_as_creation() { h.run_steps(3); h.get_by_value("DirectX"); - h.get_by_label("Create").click(); - h.run_steps(3); + create(&mut h); assert_eq!(h.state().session.doc.project.normal_format, NormalFormat::DirectX); } diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs new file mode 100644 index 00000000..ca81a143 --- /dev/null +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -0,0 +1,261 @@ +//! File > New project: the sections and their order, the defaults, settings shown disabled with a +//! hint until TextureCraft has them, Create waiting for a mesh file, and the settings that reach +//! the `file.new` command. + +use egui::Role; +use egui::accesskit::Toggled; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::template_cmds::DEFAULT_TEMPLATE; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::create_command; +use texturecraft_ui_egui::project_form::NOT_AVAILABLE; + +/// A quad whose UVs lie in UV tile 1002 and a camera-free OBJ +const TILE_1002_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1.1 0.1\nvt 1.9 0.1\nvt 1.9 0.9\nvt 1.1 0.9\nf 1/1 2/2 3/3 4/4\n"; + +/// The app with New project opened from the menu, tall enough to show the whole form +fn harness() -> Harness<'static, TextureCraftApp> { + harness_sized(egui::vec2(1600.0, 2400.0)) +} + +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(2); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(4); + h +} + +fn mesh_file(test: &str, contents: &str) -> String { + let dir = std::env::temp_dir().join(format!("texturecraft-np-window-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("tiles.obj"); + std::fs::write(&path, contents).unwrap(); + path.display().to_string() +} + +fn top(h: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { + h.get_all_by_label(label).map(|node| node.rect().top()).fold(f32::INFINITY, f32::min) +} + +fn disabled(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().is_disabled() +} + +fn ticked(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + h.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(Toggled::True) +} + +#[test] +fn the_sections_follow_the_reference_order() { + let h = harness(); + let order = [ + "BASIC SETTINGS", + "3D mesh", + "Project template", + "Document resolution (px)", + "ADVANCED SETTINGS", + "Normal map format", + "Compute tangent space per fragment", + "UV Tile settings (UDIMs)", + "You won't be able to change UV Tile settings after creating the project.", + "Use UV Tile workflow", + "Preserve UV Tile layout per material and enable painting across tiles", + "Convert UV Tiles into individual Texture Sets (legacy)", + "Import settings", + "Import cameras", + "Auto-unwrap", + "Import baked maps", + "Import mesh normal maps and baked maps for all materials.", + "Automatic normal maps assignation scheme: $(MATERIAL_NAME)_normal", + "Physical size", + "Use mesh file's internal unit scale (recommended)", + "Custom unit scale", + "Switch fill layer scaling to Physical size when assigning materials", + "Color management", + "Working color space", + ]; + let tops: Vec = order.iter().map(|label| top(&h, label)).collect(); + for (pair, labels) in tops.windows(2).zip(order.windows(2)) { + assert!(pair[0] < pair[1], "{} comes before {}: {pair:?}", labels[0], labels[1]); + } + assert!(h.query_by_label("Linear - sRGB Chrominance (ITU-R BT.709)").is_some()); +} + +#[test] +fn the_defaults_match_the_reference() { + let h = harness(); + + assert!(h.query_by_label("No file selected").is_some()); + assert!(h.query_by_value(DEFAULT_TEMPLATE).is_some(), "the default template"); + assert!(h.query_by_value("1024 x 1024").is_some()); + assert!(h.query_by_value("OpenGL").is_some()); + assert!(h.query_by_value("Legacy").is_some()); + assert!(!ticked(&h, Role::CheckBox, "Compute tangent space per fragment")); + assert!(!ticked(&h, Role::CheckBox, "Use UV Tile workflow")); + assert!(ticked(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles")); + assert!(disabled(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles"), "greyed while UV tiles are off"); + assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras")); + assert!(ticked(&h, Role::CheckBox, "Auto-unwrap")); + assert!(ticked(&h, Role::RadioButton, "Use mesh file's internal unit scale (recommended)")); + assert!(!ticked(&h, Role::CheckBox, "Switch fill layer scaling to Physical size when assigning materials")); +} + +#[test] +fn template_controls_name_and_built_in_meshes_are_gone() { + let h = harness(); + + for label in ["Template name", "Save current project as template", "Name", "UV tiles (UDIM)"] { + assert!(h.query_by_label(label).is_none(), "{label} is not in the window"); + } + assert!(h.query_by_label_contains("Built-in:").is_none(), "no built-in mesh dropdown"); +} + +#[test] +fn create_waits_for_a_mesh_file() { + let mut h = harness(); + + assert!(disabled(&h, Role::Button, "Create")); + + h.state_mut().ui.new_project.file = Some(mesh_file("create-enabled", TILE_1002_QUAD)); + h.run_steps(2); + + assert!(!disabled(&h, Role::Button, "Create")); + assert!(h.query_by_label("tiles.obj").is_some(), "the chosen file is shown"); +} + +#[test] +fn settings_not_available_yet_are_disabled_with_a_hint() { + let mut h = harness(); + let unavailable = [ + (Role::CheckBox, "Compute tangent space per fragment"), + (Role::RadioButton, "Convert UV Tiles into individual Texture Sets (legacy)"), + (Role::CheckBox, "Auto-unwrap"), + (Role::Button, "Auto-unwrap options"), + (Role::RadioButton, "Custom unit scale"), + (Role::CheckBox, "Switch fill layer scaling to Physical size when assigning materials"), + ]; + for (role, label) in unavailable { + assert!(disabled(&h, role, label), "{label} is disabled"); + } + assert!(!disabled(&h, Role::RadioButton, "Use mesh file's internal unit scale (recommended)")); + + for (role, label) in unavailable { + let center = h.get_by_role_and_label(role, label).rect().center(); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(2); + assert!(h.query_by_label(NOT_AVAILABLE).is_none(), "no hint before hovering {label}"); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "hovering {label} says it is not available yet"); + } +} + +#[test] +fn opencolorio_shows_its_settings_disabled_and_creates_legacy() { + let mut h = harness(); + + assert!(h.query_by_label("OpenColorIO configuration").is_none(), "Legacy shows only the working color space"); + + h.get_by_value("Legacy").scroll_to_me(); + h.run_steps(3); + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + + assert!(h.query_by_label("OpenColorIO is not available yet. The project uses Legacy.").is_some()); + for label in ["OpenColorIO configuration", "Configuration file", "Standard sRGB color space", "Auto detect color spaces", "Material color space default"] { + assert!(h.query_by_label(label).is_some(), "{label} is shown"); + } + assert!(h.query_by_label("ACEScg").is_some(), "the OpenColorIO working color space"); + let params = create_command(&texturecraft_ui_egui::state::NewProject { file: Some("a.obj".into()), ..h.state().ui.new_project.clone() }).unwrap(); + assert!(params.get("colorManagement").is_none(), "nothing about color management reaches the command"); +} + +#[test] +fn the_menu_opens_a_fresh_form() { + let mut h = harness(); + { + let form = &mut h.state_mut().ui.new_project; + form.file = Some("/old/mesh.obj".into()); + form.resolution = 4096; + form.uv_tiles = Some(true); + form.import_cameras = false; + form.baked_maps = vec!["/maps/Ball_normal.png".into()]; + } + h.state_mut().ui.windows.new_project = false; + h.run_steps(2); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.newProject"); + h.run_steps(3); + + let form = &h.state().ui.new_project; + assert_eq!((form.file.as_deref(), form.resolution, form.uv_tiles, form.import_cameras), (None, 1024, None, true)); + assert_eq!(form.template, DEFAULT_TEMPLATE); + assert_eq!(form.baked_maps, ["/maps/Ball_normal.png"], "files kept after a failed import stay listed"); +} + +#[test] +fn the_supported_settings_reach_the_create_command() { + let mut form = texturecraft_ui_egui::state::NewProject::default(); + + assert!(create_command(&form).is_none(), "no command without a mesh file"); + + form.file = Some("/meshes/robot.fbx".into()); + let params = create_command(&form).unwrap(); + + assert_eq!(params["mesh"], "/meshes/robot.fbx"); + assert_eq!(params["resolution"], 1024); + assert_eq!(params["uvTiles"], false, "UV tiles are off unless ticked"); + assert_eq!(params["importCameras"], true); + assert_eq!(params["template"], DEFAULT_TEMPLATE); + assert!(params.get("name").is_none(), "the project is named after the file"); + + form.uv_tiles = Some(true); + form.import_cameras = false; + form.resolution = 2048; + let params = create_command(&form).unwrap(); + + assert_eq!((params["uvTiles"].as_bool(), params["importCameras"].as_bool(), params["resolution"].as_u64()), (Some(true), Some(false), Some(2048))); +} + +#[test] +fn ticking_uv_tiles_creates_a_uv_tile_project() { + for (tick, expected) in [(false, Vec::::new()), (true, vec![1002])] { + let mut h = harness(); + h.state_mut().ui.new_project.file = Some(mesh_file(&format!("udim-{tick}"), TILE_1002_QUAD)); + h.state_mut().ui.new_project.resolution = 128; + h.run_steps(2); + if tick { + h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click(); + h.run_steps(3); + assert!(!disabled(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles")); + } + h.get_by_role_and_label(Role::CheckBox, "Import cameras").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + let app = h.state(); + assert!(!app.ui.windows.new_project, "the window closes"); + assert_eq!(app.session.doc.project.name, "tiles"); + assert_eq!(app.session.doc.project.texture_sets[0].uv_tiles, expected, "UV tiles ticked: {tick}"); + assert_eq!(app.session.doc.project.texture_sets[0].resolution, 128); + } +} + +#[test] +fn create_stays_on_screen_in_a_short_window() { + let h = harness_sized(egui::vec2(1024.0, 600.0)); + + let create = h.get_by_role_and_label(Role::Button, "Create").rect(); + let cancel = h.get_by_role_and_label(Role::Button, "Cancel").rect(); + + assert!(create.bottom() <= 600.0 && create.top() >= 0.0, "Create is visible without scrolling: {create:?}"); + assert!(cancel.bottom() <= 600.0, "{cancel:?}"); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 969c5e5c..c170b9f4 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -136,20 +136,96 @@ fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; - assert!(h.query_by_label("Choosing or reimporting a mesh recomputes all channels.").is_some(), "the note above the buttons"); - assert_eq!(icons.len(), 6, "mesh path, Select, Reimport mesh, Preserve strokes, Normal map format, UV tiles"); + assert!(h.query_by_label("Please note: Changing any of these settings will cause all channels to be recomputed.").is_some(), "the note above the buttons"); + assert_eq!( + icons.len(), + 13, + "3D mesh, Reimport mesh, Normal map format, tangent space, UV tiles and its two layouts, Import cameras, Preserve strokes, Auto-unwrap, \ + Physical size, Color management, Working color space" + ); assert!(h.query_by_label(tip).is_none(), "no tooltip before hovering"); - // The format icon is fifth in the window's rows + // The format icon is third in the window's rows let mut centers: Vec<_> = icons.iter().map(|n| n.rect().center()).collect(); centers.sort_by(|a, b| a.y.total_cmp(&b.y)); - let format_center = centers[4]; + let format_center = centers[2]; h.hover_at(format_center); h.run_steps(30); assert!(h.query_by_label(tip).is_some(), "hovering the normal map format icon explains it"); } +#[test] +fn the_window_follows_the_reference_layout() { + let dir = temp_dir("layout"); + let mut h = app_on_a_quad(&dir); + h.set_size(egui::vec2(1600.0, 2000.0)); + + open_window(&mut h); + + let order = [ + "3D MESH", + "Reimport mesh", + "PROJECT SETTINGS", + "Compute tangent space per fragment", + "UV Tile settings (UDIMs)", + "You can't change UV Tile settings once a project has been created.", + "Use UV Tile workflow", + "Convert UV Tiles into individual Texture Sets (legacy)", + "Import settings", + "Import cameras", + "Preserve stroke positions on mesh", + "Auto-unwrap", + "Physical size", + "Working color space", + ]; + let top = |label: &str| h.get_all_by_label(label).map(|n| n.rect().top()).fold(f32::INFINITY, f32::min); + for labels in order.windows(2) { + assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]); + } + assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed"); + let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled(); + for (role, label) in [ + (Role::CheckBox, "Compute tangent space per fragment"), + (Role::CheckBox, "Use UV Tile workflow"), + (Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles"), + (Role::RadioButton, "Convert UV Tiles into individual Texture Sets (legacy)"), + (Role::CheckBox, "Import cameras"), + (Role::CheckBox, "Auto-unwrap"), + (Role::Button, "Auto-unwrap options"), + ] { + assert!(disabled(role, label), "{label} is disabled"); + } + + let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center(); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet"); +} + +#[test] +fn opencolorio_can_be_looked_at_but_changes_nothing() { + let dir = temp_dir("ocio"); + let mut h = app_on_a_quad(&dir); + h.set_size(egui::vec2(1600.0, 2000.0)); + open_window(&mut h); + let before = h.state().session.doc.project.clone(); + + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + + assert!(h.query_by_label("OpenColorIO is not available yet. The project uses Legacy.").is_some()); + assert!(h.query_by_label("Bitmap import color space defaults").is_some()); + assert!(h.query_by_label("Export color spaces").is_some()); + + click(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project, before, "OK applies nothing for color management"); +} + #[test] fn another_file_shows_its_path_and_ticks_reimport() { let dir = temp_dir("select"); diff --git a/docs/features.md b/docs/features.md index 1883dbfb..2d1f8098 100644 --- a/docs/features.md +++ b/docs/features.md @@ -81,14 +81,23 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA ## Files and texture sets - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, - OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers + OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* opens the + material ball); UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and - lists its UV tiles (read only; Texture Set Settings changes them). + lists its UV tiles (read only; Texture Set Settings changes them). Physical size and Color management + follow the New project window. +- **File › New project...** follows the reference app's window: BASIC SETTINGS (*Select...* a mesh file, + the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal + map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color + management). The project is named after the mesh file. Settings TextureCraft does not have yet + (tangent space per fragment, UV tiles as separate texture sets, turning auto-unwrap off and its + options, a custom unit scale, OpenColorIO) are shown disabled with a hint; projects use Legacy color + management. In the browser, *Select...* opens the browser's file picker. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e8d6f0bb..e6762be8 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -70,7 +70,7 @@ list, not a feature-completion denominator. | Check | Surface | Result | Observable evidence / limit | |---|---|---|---| -| F01 New project | UI | Pass | Ctrl+N, built-in Cube, 1024 px, Create produced a new project with one empty paint layer. The native mesh-file selection path was not completed in this deeper pass | +| F01 New project | UI | Pass (tests) | The window no longer offers built-in meshes ([#636](https://github.com/storytold/texturecraft/issues/636)). `tests/it/new_project_window.rs` covers the section order, the defaults, the disabled settings and their hint, Create waiting for a mesh file, and a UV tile project created from a mesh file. A manual pass with the native file picker is still to do | | F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles | | F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image | | F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 | From 2416736820077aef7df247ea565b38d027a6d1f2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 00:17:48 +0100 Subject: [PATCH 2/5] Align rows without an info icon, indent the baked map list, and test template selection Rows without an info icon keep an invisible one so their controls line up with the others. The baked map list follows the section indent. New tests pick a saved template, check that the OpenColorIO settings are disabled with the hint, and render Project configuration in both color management modes (ignored GPU snapshot test). --- crates/ui-egui/src/new_project_advanced.rs | 13 ++++++---- crates/ui-egui/src/project_form.rs | 8 +++--- crates/ui-egui/tests/it/new_project_window.rs | 25 ++++++++++++++++++ crates/ui-egui/tests/it/project_config.rs | 26 +++++++++++++++++++ 4 files changed, 63 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 835eb41b..39353eef 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -251,11 +251,14 @@ fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { }); ui.add_space(4.0); - egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT).auto_shrink([false, false]).show(ui, |ui| { - for path in &new_project.baked_maps { - ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); - } + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT).auto_shrink([false, false]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); }); }); ui.add_space(4.0); diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs index 1e813ed4..3cbeca8a 100644 --- a/crates/ui-egui/src/project_form.rs +++ b/crates/ui-egui/src/project_form.rs @@ -21,9 +21,6 @@ pub(crate) const FORM_HEIGHT: f32 = 760.0; /// Indent of the rows below a section title. pub(crate) const ROW_INDENT: f32 = 16.0; -/// Room kept for the info icon at the end of a row without one. -const INFO_SLOT: f32 = 16.0; - /// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its /// settings, but they stay disabled and a project is always created and kept as Legacy. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -79,7 +76,10 @@ pub(crate) fn check_row(ui: &mut Ui, info: Option<&str>, control: impl FnOnce fn info_slot(ui: &mut Ui, info: Option<&str>) { match info { Some(text) => info_icon(ui, text), - None => ui.add_space(INFO_SLOT), + // An invisible icon keeps the controls of rows without one in the same column + None => { + ui.add_visible(false, egui::Label::new(egui_phosphor::regular::INFO)); + } } } diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index ca81a143..c1819775 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -173,6 +173,12 @@ fn opencolorio_shows_its_settings_disabled_and_creates_legacy() { assert!(h.query_by_label(label).is_some(), "{label} is shown"); } assert!(h.query_by_label("ACEScg").is_some(), "the OpenColorIO working color space"); + let ocio_config = h.get_by_value("ACES 2.0"); + assert!(ocio_config.accesskit_node().is_disabled(), "the OpenColorIO settings are disabled"); + let center = ocio_config.rect().center(); + h.hover_at(center); + h.run_steps(30); + assert!(h.query_by_label(NOT_AVAILABLE).is_some(), "with the not-available hint"); let params = create_command(&texturecraft_ui_egui::state::NewProject { file: Some("a.obj".into()), ..h.state().ui.new_project.clone() }).unwrap(); assert!(params.get("colorManagement").is_none(), "nothing about color management reaches the command"); } @@ -259,3 +265,22 @@ fn create_stays_on_screen_in_a_short_window() { assert!(create.bottom() <= 600.0 && create.top() >= 0.0, "Create is visible without scrolling: {create:?}"); assert!(cancel.bottom() <= 600.0, "{cancel:?}"); } + +#[test] +fn picking_a_template_sets_its_resolution_and_normal_map_format() { + let mut h = harness(); + h.state_mut().session.templates.dir = None; + h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); + h.state_mut().run("project.template.save", serde_json::json!({"name": "Small DirectX"})).unwrap(); + h.run_steps(2); + + h.get_by_value(DEFAULT_TEMPLATE).click(); + h.run_steps(3); + h.get_by_label("Small DirectX").click(); + h.run_steps(3); + + assert!(h.query_by_value("Small DirectX").is_some()); + assert!(h.query_by_value("128 x 128").is_some(), "the template's resolution (the open project's 128 px)"); + assert!(h.query_by_value("DirectX").is_some(), "the template's normal map format"); + assert_eq!(h.state().ui.new_project.resolution, 128); +} diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index c170b9f4..bbc07f87 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -793,3 +793,29 @@ fn a_format_the_project_already_has_is_not_set_again() { assert_eq!(project_normal_format(&h), NormalFormat::DirectX); assert_eq!(h.state().session.history_labels().len(), steps, "no extra undo step"); } + +#[test] +#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"] +fn project_config_snapshots() { + let output_dir = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output_dir).unwrap(); + let dir = temp_dir("snapshots"); + let file = dir.join("quad.obj"); + std::fs::write(&file, QUAD).unwrap(); + let mut session = Session::from_mesh_bytes("quad.obj", QUAD.as_bytes(), 128, "quad").unwrap(); + session.doc.project.mesh_path = file.display().to_string(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(6); + open_window(&mut h); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("project-config-legacy.png")).unwrap(); + h.get_by_value("Legacy").scroll_to_me(); + h.run_steps(3); + h.get_by_value("Legacy").click(); + h.run_steps(3); + h.get_by_label("OpenColorIO").click(); + h.run_steps(3); + h.get_by_label("Export color spaces").scroll_to_me(); + h.run_steps(6); + h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); +} From a0f9f81ae616348b4f57e6290f50b2d4096b2b50 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 00:18:28 +0100 Subject: [PATCH 3/5] Import resources window with usage, prefix and filter File > Import resources now opens a window: add files (images and materials), set an optional name prefix and a usage per file, filter by usage, remove selected rows, then Import or Cancel. Texture and undefined import an image resource, environment also lights the scene, alpha also sets the brush alpha. Color LUT, post effect and the user asset library target are listed but disabled. resource.import takes an optional prefix. --- crates/engine/src/resource_cmds.rs | 31 +- crates/ui-egui/src/import_resources.rs | 332 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 3 + crates/ui-egui/src/state.rs | 5 + crates/ui-egui/src/state/import_resources.rs | 81 +++++ crates/ui-egui/src/web_files.rs | 2 +- crates/ui-egui/src/windows.rs | 19 +- crates/ui-egui/tests/it/file_dialogs.rs | 2 +- crates/ui-egui/tests/it/import_resources.rs | 229 +++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/features.md | 5 + docs/ui-parity.md | 9 + 13 files changed, 701 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/import_resources.rs create mode 100644 crates/ui-egui/src/state/import_resources.rs create mode 100644 crates/ui-egui/tests/it/import_resources.rs diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 2c973280..8fe1fe5a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -12,7 +12,15 @@ use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { vec![ - cmd!("resource.import", "Import resources", ["File"], None, "{path} — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)", always, import), + cmd!( + "resource.import", + "Import resources", + ["File"], + None, + "{path — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr), prefix?: put in front of the resource name (anything outside A-Z a-z 0-9 _ . - becomes _)}", + always, + import + ), cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))), cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove), cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused), @@ -38,18 +46,33 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) + self.import_resource_bytes_prefixed("", file_name, bytes) + } + + /// Like [`Self::import_resource_bytes`], with `prefix` put in front of the resource's name + pub fn import_resource_bytes_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |session| session.add_image_resource_prefixed(prefix, file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec, max_texels: u64) -> Result { + self.add_image_resource_prefixed("", file_name, bytes, max_texels) + } + + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); - let base = texturecraft_formats::sanitize_resource_name(leaf); + let mut base = texturecraft_formats::sanitize_resource_name(leaf); + if !prefix.trim().is_empty() { + // Names stay within the sanitized length; the file name keeps its room + let room = 120usize.saturating_sub(base.chars().count()); + let prefix: String = texturecraft_formats::sanitize_resource_name(prefix.trim()).chars().take(room).collect(); + base = format!("{prefix}{base}"); + } let mut name = base.clone(); let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { @@ -101,7 +124,7 @@ fn list(s: &Session) -> Value { fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; let bytes = read_image_file("resource.import", path, MAX_BYTES as u64)?; - let name = s.import_resource_bytes(path, bytes)?; + let name = s.import_resource_bytes_prefixed(strp(p, "prefix").unwrap_or(""), path, bytes)?; Ok(json!({ "name": name })) } diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs new file mode 100644 index 00000000..c08f4973 --- /dev/null +++ b/crates/ui-egui/src/import_resources.rs @@ -0,0 +1,332 @@ +//! File > Import resources...: a window to collect files, set what each is for, and import them +//! together. Images become project resources; materials load as smart materials. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; + +use egui::{Key, Modifiers}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::file_dialogs::{Bound, FileDialog}; +use crate::i18n::{tr, trf}; +use crate::state::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; +use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS}; +use crate::widgets::primary_button; + +/// Width of the window +const WINDOW_WIDTH_POINTS: f32 = 640.0; +/// Height of the file list +const LIST_HEIGHT_POINTS: f32 = 300.0; +/// Width of a row's prefix field and usage dropdown +const PREFIX_WIDTH_POINTS: f32 = 160.0; +const USAGE_WIDTH_POINTS: f32 = 110.0; +/// Room beside the dropdown of the target +const TARGET_WIDTH_POINTS: f32 = 190.0; + +/// Opens the window with an empty list (an open window stays as it is) +pub(crate) fn open(app: &mut TextureCraftApp) { + static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + + if app.ui.windows.import_resources.is_none() { + app.ui.windows.import_resources = Some(ImportResources { + project: app.session.project_id, + opening_id: NEXT_OPENING_ID.fetch_add(1, Ordering::Relaxed), + ..ImportResources::default() + }); + } +} + +/// The keys of the open window: Escape closes it, Enter imports unless a text field or button had +/// the keyboard. An open dropdown takes both first. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool, popup_open: bool) { + if popup_open { + return; + } + + let escape = input.consume_key(Modifiers::NONE, Key::Escape); + let enter = input.consume_key(Modifiers::NONE, Key::Enter); + if escape { + app.ui.windows.import_resources = None; + } else if enter + && nothing_focused + && let Some(window) = app.ui.windows.import_resources.as_mut() + { + window.confirm = true; + } +} + +/// Whether the file is a material (loaded as a smart material, so it has no usage or prefix) +fn is_material(row: &ImportRow) -> bool { + row.path.extension().and_then(|e| e.to_str()).is_some_and(|e| MATERIAL_EXTS.contains(&e.to_ascii_lowercase().as_str())) +} + +fn file_name(row: &ImportRow) -> String { + row.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| row.path.display().to_string()) +} + +/// A click on row `id` of the `visible` rows: plain selects only it, Ctrl toggles it, Shift +/// selects from the anchor to it +fn click_row(window: &mut ImportResources, visible: &[u64], id: u64, modifiers: Modifiers) { + let ctrl = modifiers.command || modifiers.ctrl; + let from = window.anchor.and_then(|anchor| visible.iter().position(|v| *v == anchor)); + let to = visible.iter().position(|v| *v == id); + + match (modifiers.shift, from, to) { + (true, Some(from), Some(to)) => { + let range: BTreeSet = visible[from.min(to)..=from.max(to)].iter().copied().collect(); + if ctrl { + window.selected.extend(range); + } else { + window.selected = range; + } + } + _ if ctrl => { + if !window.selected.remove(&id) { + window.selected.insert(id); + } + window.anchor = Some(id); + } + _ => { + window.selected = BTreeSet::from([id]); + window.anchor = Some(id); + } + } +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut window) = app.ui.windows.import_resources.clone() else { return }; + + // Files chosen for another project cannot be imported here + if window.project != app.session.project_id { + app.ui.windows.import_resources = None; + return; + } + + // A filter whose rows are gone shows everything again + if window.filter.is_some_and(|usage| !window.rows.iter().any(|row| row.usage == usage)) { + window.filter = None; + } + + let mut open = true; + let (mut import, mut cancel, mut add) = (std::mem::take(&mut window.confirm), false, false); + let mut remove = false; + + crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| { + ui.set_min_width(WINDOW_WIDTH_POINTS); + ui.horizontal(|ui| { + ui.label(tr("Import your resources and set their usage")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_enabled_ui(!window.selected.is_empty(), |ui| { + remove = ui.button(tr("Remove selected resources")).clicked(); + }); + add = ui.button(tr("Add resources")).clicked(); + }); + }); + ui.add_space(4.0); + + let all_label = trf("All imported resources ({count})", &[("count", &window.rows.len().to_string())]); + let filter_text = match window.filter { + None => all_label.clone(), + Some(usage) => { + trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|r| r.usage == usage).count().to_string())]) + } + }; + egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { + if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { + window.filter = None; + } + + // Only usages some row has, so the list is never empty by filter + for usage in ResourceUsage::ALL { + let count = window.rows.iter().filter(|row| row.usage == usage).count(); + if count > 0 && ui.selectable_label(window.filter == Some(usage), format!("{} ({count})", usage.name())).clicked() { + window.filter = Some(usage); + } + } + }); + ui.add_space(4.0); + + let visible: Vec = window.rows.iter().filter(|row| window.filter.is_none_or(|usage| row.usage == usage)).map(|row| row.id).collect(); + let modifiers = ui.input(|i| i.modifiers); + let mut clicked = None; + + egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { + for row in window.rows.iter_mut().filter(|row| visible.contains(&row.id)) { + let material = is_material(row); + let selected = window.selected.contains(&row.id); + ui.horizontal(|ui| { + let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(40.0); + let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); + if name.on_hover_text(row.path.display().to_string()).clicked() { + clicked = Some(row.id); + } + + let prefix = ui.add_enabled( + !material, + egui::TextEdit::singleline(&mut row.prefix).hint_text(tr("Optional prefix/path...")).desired_width(PREFIX_WIDTH_POINTS), + ); + if material { + prefix.on_disabled_hover_text(tr("Materials keep their own name")); + } else { + prefix.on_hover_text(tr("Put in front of the resource's name. Characters other than letters, digits and _ . - become _")); + } + + ui.add_enabled_ui(!material, |ui| { + egui::ComboBox::from_id_salt(("import_usage", row.id)).width(USAGE_WIDTH_POINTS).selected_text(row.usage.name()).show_ui(ui, |ui| { + for usage in ResourceUsage::ALL { + let item = ui.add_enabled(usage.available(), egui::Button::selectable(row.usage == usage, usage.name())); + if usage.available() { + if item.clicked() { + row.usage = usage; + ui.close(); + } + } else { + item.on_disabled_hover_text(tr("Not available yet")); + } + } + }); + }) + .response + .on_disabled_hover_text(tr("Materials need no usage")); + }); + } + }); + if let Some(id) = clicked { + click_row(&mut window, &visible, id, modifiers); + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + egui::ComboBox::from_id_salt("import_target") + .width(TARGET_WIDTH_POINTS) + .selected_text(match window.target { + ImportTarget::Session => tr("current session"), + ImportTarget::Library => tr("library 'Your assets'"), + }) + .show_ui(ui, |ui| { + if ui.selectable_label(window.target == ImportTarget::Session, tr("current session")).clicked() { + window.target = ImportTarget::Session; + } + // Your assets hold smart materials and brush presets, not images + ui.add_enabled(false, egui::Button::selectable(false, tr("library 'Your assets'"))).on_disabled_hover_text(tr("Not available yet")); + }); + ui.label(tr("Import your resources to:")); + }); + }); + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel = ui.button(tr("Cancel")).clicked(); + import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); + }); + }); + }); + + if remove { + window.rows.retain(|row| !window.selected.contains(&row.id)); + window.selected.clear(); + window.anchor = None; + } + + if add { + let mut extensions: Vec<&str> = IMAGE_EXTS.to_vec(); + extensions.extend_from_slice(MATERIAL_EXTS); + let opening_id = window.opening_id; + app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { + let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; + for path in paths { + if stored.rows.iter().any(|row| row.path == path) { + continue; + } + stored.rows.push(ImportRow { id: stored.next_row, path, prefix: String::new(), usage: ResourceUsage::Undefined }); + stored.next_row += 1; + } + }); + } + + if import && !window.rows.is_empty() { + import_rows(app, &window); + } + + if (import && !window.rows.is_empty()) || cancel || !open { + app.ui.windows.import_resources = None; + } else { + // A file answer only arrives between frames, so nothing was added meanwhile + app.ui.windows.import_resources = Some(window); + } +} + +/// Imports every row in order, each by its usage +fn import_rows(app: &mut TextureCraftApp, window: &ImportResources) { + for row in &window.rows { + let path = row.path.display().to_string(); + if is_material(row) { + app.run("material.load", json!({ "path": path })); + continue; + } + + let mut params = json!({ "path": path }); + if !row.prefix.trim().is_empty() { + params["prefix"] = json!(row.prefix); + } + let Some(result) = app.run("resource.import", params) else { continue }; + let name = result.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + + match row.usage { + ResourceUsage::Environment => crate::web_files::use_environment(app, &name), + ResourceUsage::Alpha => { + if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() { + app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false); + } + } + ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {} + } + } + app.ui.dock.focus(crate::docking::Panel::Assets); +} + +#[cfg(test)] +mod tests { + use super::*; + + const CTRL: Modifiers = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE }; + + fn selected(window: &ImportResources) -> Vec { + window.selected.iter().copied().collect() + } + + #[test] + fn a_plain_click_selects_one_row() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3], 3, Modifiers::NONE); + + assert_eq!(selected(&window), [3]); + } + + #[test] + fn ctrl_toggles_rows() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3], 1, CTRL); + click_row(&mut window, &[1, 2, 3], 3, CTRL); + assert_eq!(selected(&window), [1, 3]); + + click_row(&mut window, &[1, 2, 3], 1, CTRL); + assert_eq!(selected(&window), [3]); + } + + #[test] + fn shift_selects_from_the_anchor_in_either_direction() { + let mut window = ImportResources::default(); + click_row(&mut window, &[1, 2, 3, 4], 2, Modifiers::NONE); + click_row(&mut window, &[1, 2, 3, 4], 4, SHIFT); + assert_eq!(selected(&window), [2, 3, 4]); + + click_row(&mut window, &[1, 2, 3, 4], 1, SHIFT); + assert_eq!(selected(&window), [1, 2]); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 28d8b44f..06d82216 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -25,6 +25,8 @@ pub mod gpu; mod grid_tile; pub mod i18n; pub mod id_color_pick; +#[cfg(not(target_arch = "wasm32"))] +mod import_resources; pub mod keymap; pub mod layer_panel; mod levels_editor; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9c66fd45..dab82c02 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -385,6 +385,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched #[cfg(not(target_arch = "wasm32"))] crate::project_config::keys_in(app, input, nothing_focused, popup_open); + } else if app.ui.windows.import_resources.is_some() { + #[cfg(not(target_arch = "wasm32"))] + crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3b7d7a83..bf7e7643 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -9,7 +9,9 @@ use crate::saved_search::SavedSearch; use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; +mod import_resources; mod project_config; +pub use import_resources::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; pub use project_config::ProjectConfig; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -85,6 +87,9 @@ pub struct Windows { /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, + /// File > Import resources: the files added so far, imported by Import. + #[serde(skip)] + pub import_resources: Option, /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, diff --git a/crates/ui-egui/src/state/import_resources.rs b/crates/ui-egui/src/state/import_resources.rs new file mode 100644 index 00000000..a3654d0e --- /dev/null +++ b/crates/ui-egui/src/state/import_resources.rs @@ -0,0 +1,81 @@ +use std::collections::BTreeSet; +use std::path::PathBuf; + +/// What an imported resource is for +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ResourceUsage { + /// Imported as an image resource, nothing more + #[default] + Undefined, + /// An image resource that also becomes the brush alpha + Alpha, + /// Color lookup tables (not available yet) + ColorLut, + /// An image resource that also lights the scene + Environment, + /// Post effect resources (not available yet) + PostFx, + /// An image resource for fills and stencils + Texture, +} + +impl ResourceUsage { + /// The usages in the dropdown's order + pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture]; + + /// The name shown in the dropdowns (the same in every language, as in the reference) + pub fn name(self) -> &'static str { + match self { + Self::Undefined => "undefined", + Self::Alpha => "alpha", + Self::ColorLut => "colorlut", + Self::Environment => "environment", + Self::PostFx => "postfx", + Self::Texture => "texture", + } + } + + /// Whether the app can do something with resources of this usage + pub fn available(self) -> bool { + !matches!(self, Self::ColorLut | Self::PostFx) + } +} + +/// Where the resources go +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ImportTarget { + /// The open project's resources + #[default] + Session, + /// The user's asset library (not available for images yet) + Library, +} + +/// One file waiting in the window +#[derive(Clone, Debug, PartialEq)] +pub struct ImportRow { + pub id: u64, + pub path: PathBuf, + pub prefix: String, + pub usage: ResourceUsage, +} + +/// File > Import resources: the files added so far, imported by the Import button +#[derive(Clone, Debug, PartialEq, Default)] +pub struct ImportResources { + pub rows: Vec, + /// Ids of the selected rows + pub selected: BTreeSet, + /// The row a Shift click extends from + pub anchor: Option, + /// The usage the list is narrowed to (None: all) + pub filter: Option, + pub target: ImportTarget, + /// Whether Enter requested the import in the next frame + pub confirm: bool, + /// The project that was open when this window opened + pub project: u64, + /// This opening's identity, used to reject late file picker answers + pub(crate) opening_id: u64, + pub(crate) next_row: u64, +} diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index a436cd01..000a5a4d 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -107,7 +107,7 @@ pub fn import_environment(app: &mut TextureCraftApp, _ctx: &egui::Context) { } /// Make image resource `name` the environment. -fn use_environment(app: &mut TextureCraftApp, name: &str) { +pub(crate) fn use_environment(app: &mut TextureCraftApp, name: &str) { let env = format!("{}{name}", texturecraft_engine::core::project::ENV_RESOURCE_PREFIX); if app.run("display.set", serde_json::json!({ "environment": env })).is_some() { app.toast(trf("Environment: {name}", &[("name", &name)]), false); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 5650c4de..b5115d2b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -24,7 +24,10 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { about(app, ctx); settings(app, ctx); #[cfg(not(target_arch = "wasm32"))] - crate::project_config::show(app, ctx); + { + crate::project_config::show(app, ctx); + crate::import_resources::show(app, ctx); + } crate::keymap::window(app, ctx); crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] @@ -918,19 +921,7 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> true } "file.importResources" | "resource.import" => { - app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::Project, |app, paths| { - if paths.is_empty() { - return; - } - - for p in paths { - if let Some(r) = app.run("resource.import", json!({"path": p.display().to_string()})) { - let name = r.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); - } - } - app.ui.dock.focus(crate::docking::Panel::Assets); - }); + crate::import_resources::open(app); true } "file.importMaterialX" => { diff --git a/crates/ui-egui/tests/it/file_dialogs.rs b/crates/ui-egui/tests/it/file_dialogs.rs index 5c13c6d8..bf21686e 100644 --- a/crates/ui-egui/tests/it/file_dialogs.rs +++ b/crates/ui-egui/tests/it/file_dialogs.rs @@ -146,7 +146,7 @@ fn answered_after_the_project_changed(ask: impl FnOnce(&mut Harness<'_, TextureC #[test] fn every_project_dialog_does_nothing_for_a_replaced_project() { let file = temp_file("replaced-actions", "chosen.obj"); - for id in ["material.load", "resource.import", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { + for id in ["material.load", "file.importMaterialX", "file.exportMesh", "file.reimportMesh"] { let h = answered_after_the_project_changed(|h| invoke(h, id), &file); assert!(h.state().toasts.iter().any(|t| t.error && t.text.starts_with(PROJECT_CHANGED)), "{id}"); assert!(!file.exists(), "{id} wrote nothing"); diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs new file mode 100644 index 00000000..b5b72e75 --- /dev/null +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -0,0 +1,229 @@ +//! File > Import resources...: the window that collects files and imports them together. File +//! pickers are answered by the override, never shown. + +use std::path::{Path, PathBuf}; + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::{Answer, Request}; + +/// A test folder removed when its owner drops +struct TempDir(PathBuf); + +impl TempDir { + fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + + Self(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + +const TITLE: &str = "Import resources"; +/// The prefix field's tooltip, which is its accessible label. +const PREFIX_HINT: &str = "Put in front of the resource's name. Characters other than letters, digits and _ . - become _"; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + h +} + +fn png(dir: &Path, name: &str) -> PathBuf { + let file = dir.join(name); + image::RgbaImage::from_pixel(4, 4, image::Rgba([10, 200, 30, 255])).save(&file).unwrap(); + + file +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "resource.import"); + h.run_steps(3); +} + +fn is_open(h: &Harness<'_, TextureCraftApp>) -> bool { + h.query_by_label(TITLE).is_some() +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + h.get_by_role_and_label(Role::Button, label).click(); + h.run_steps(3); +} + +/// Add resources, answered with `files`. +fn add(h: &mut Harness<'_, TextureCraftApp>, files: &[PathBuf]) { + let files = files.to_vec(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(files.clone())))); + click(h, "Add resources"); +} + +/// The dropdowns showing `value` (they have no label, only a value). +fn combos<'h>(h: &'h Harness<'_, TextureCraftApp>, value: &'h str) -> impl Iterator> { + h.get_all_by_role(Role::ComboBox).filter(move |node| node.value().as_deref() == Some(value)) +} + +fn resources(h: &Harness<'_, TextureCraftApp>) -> Vec { + h.state().session.doc.resources.keys().cloned().collect() +} + +/// Pick `usage` in the dropdown of the `n`th row (the dropdowns show "undefined" until changed). +fn choose_usage(h: &mut Harness<'_, TextureCraftApp>, n: usize, usage: &str) { + let combo = combos(h, "undefined").nth(n).expect("a usage dropdown"); + combo.click(); + h.run_steps(3); + h.get_by_label(usage).click(); + h.run_steps(3); +} + +#[test] +fn the_menu_opens_the_window_without_importing_or_asking() { + let mut h = app(); + invoke(&mut h); + + assert!(is_open(&h)); + assert!(resources(&h).is_empty()); + assert!(h.query_by_label("Import your resources and set their usage").is_some()); + assert!(combos(&h, "All imported resources (0)").next().is_some()); + assert!(h.get_by_label("Remove selected resources").accesskit_node().is_disabled(), "nothing is selected"); +} + +#[test] +fn added_files_are_listed_and_import_keeps_their_names() { + let dir = TempDir::new("import-resources-add"); + let (a, b) = (png(dir.path(), "bluenoise.png"), png(dir.path(), "scratch.png")); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[a.clone(), b]); + + assert!(combos(&h, "All imported resources (2)").next().is_some()); + assert!(h.query_by_label("bluenoise.png").is_some() && h.query_by_label("scratch.png").is_some()); + assert!(resources(&h).is_empty(), "adding only lists"); + + // The same file twice is one row + add(&mut h, &[a]); + assert!(combos(&h, "All imported resources (2)").next().is_some()); + + click(&mut h, "Import"); + assert!(!is_open(&h)); + assert_eq!(resources(&h), ["bluenoise.png", "scratch.png"]); +} + +#[test] +fn remove_selected_drops_only_the_selected_rows() { + let dir = TempDir::new("import-resources-remove"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "one.png"), png(dir.path(), "two.png")]); + + h.get_by_label("one.png").click(); + h.run_steps(3); + click(&mut h, "Remove selected resources"); + + assert!(h.query_by_label("one.png").is_none()); + assert!(h.query_by_label("two.png").is_some()); + assert!(combos(&h, "All imported resources (1)").next().is_some()); + click(&mut h, "Import"); + assert_eq!(resources(&h), ["two.png"]); +} + +#[test] +fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { + let dir = TempDir::new("import-resources-usage"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "plain.png"), png(dir.path(), "brush.png"), png(dir.path(), "sky.png")]); + assert_eq!(combos(&h, "undefined").count(), 3); + + choose_usage(&mut h, 1, "alpha"); + choose_usage(&mut h, 1, "environment"); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["brush.png", "plain.png", "sky.png"]); + let project = &h.state().session.doc.project; + assert_eq!(project.display.environment_resource(), Some("sky.png"), "the environment usage lights the scene"); + assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush.png"), "the alpha usage sets the brush alpha"); +} + +#[test] +fn a_prefix_goes_in_front_of_the_resource_name() { + let dir = TempDir::new("import-resources-prefix"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "dust.png")]); + + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).click(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).type_text("wear/"); + h.run_steps(3); + click(&mut h, "Import"); + + assert_eq!(resources(&h), ["wear_dust.png"]); +} + +#[test] +fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { + let dir = TempDir::new("import-resources-disabled"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "x.png")]); + + combos(&h, "undefined").next().expect("the dropdown").click(); + h.run_steps(3); + for usage in ["colorlut", "postfx"] { + assert!(h.get_by_label(usage).accesskit_node().is_disabled(), "{usage}"); + } + assert!(!h.get_by_label("texture").accesskit_node().is_disabled()); + h.get_by_label("texture").click(); + h.run_steps(3); + + combos(&h, "current session").next().expect("the dropdown").click(); + h.run_steps(3); + assert!(h.get_by_label("library 'Your assets'").accesskit_node().is_disabled()); +} + +#[test] +fn cancel_imports_nothing() { + let dir = TempDir::new("import-resources-cancel"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[png(dir.path(), "never.png")]); + click(&mut h, "Cancel"); + + assert!(!is_open(&h)); + assert!(resources(&h).is_empty()); + + // Reopening starts empty + invoke(&mut h); + assert!(combos(&h, "All imported resources (0)").next().is_some()); +} + +#[test] +fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { + let dir = TempDir::new("import-resources-command"); + let file = png(dir.path(), "tile.png"); + let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + + let plain = texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string()})).unwrap(); + let prefixed = + texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string(), "prefix": "a/b/"})).unwrap(); + + assert_eq!(plain["name"], "tile.png"); + assert_eq!(prefixed["name"], "a_b_tile.png"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4f454304..c0c60a2e 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -17,6 +17,7 @@ mod fill_projection_section; mod filter_picker; mod generator_panel; mod history_panel; +mod import_resources; mod layer_clipboard; mod layer_rename; mod layers_panel; diff --git a/docs/features.md b/docs/features.md index 1883dbfb..66783804 100644 --- a/docs/features.md +++ b/docs/features.md @@ -67,6 +67,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA brick and stone, sun-faded paint…) and **24 smart masks**, all procedural, so they work at any resolution. Drag them from the tabbed, searchable shelf onto the layer stack or straight onto the model. +- **Import resources:** *File › Import resources...* opens a window: *Add resources* (images and + materials), an optional name prefix and a usage per file (texture, environment and alpha also + light the scene or set the brush alpha), a filter by usage, *Remove selected resources*, then + *Import*. Not yet available: the colorlut and postfx usages and the "Your assets" target (shown + disabled). The browser imports images straight from its file picker. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it appears under *My smart materials*, pixels and images included. - **MaterialCraft materials:** *File › Import material*, a drop on the window, or MaterialCraft's diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e8d6f0bb..9a528f9f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -59,6 +59,15 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c | UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | | UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart | +File > Import resources (#638) is a window like the reference's: add files, an optional +name prefix and a usage per file, a filter by usage, Remove selected resources, and Import or +Cancel. Usages `texture` and `undefined` import an image resource, `environment` also lights the +scene with it, `alpha` also makes it the brush alpha. `colorlut` and `postfx` have no feature +behind them and are listed disabled, as is the target "library 'Your assets'" (that library holds +smart materials and brush presets, not images). The prefix goes in front of the resource's name, +because resources have no folders. Materials (`.tcmat`, `.mcmat`, `.mcraft`) can be added too and +load as smart materials. The browser build still imports images straight from its file picker. + Broader properties/filter work remains tracked in [#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking against current code; an open issue is not proof that every control it lists is still missing. From 014e2881a586eae0460cead043e7914a2b5a1f7a Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 00:18:57 +0100 Subject: [PATCH 4/5] UV tile notes say where UV tiles change New project tells the user UV tiles can be changed later in Texture Set Settings, which is true in TextureCraft. Project configuration says the same in one note instead of a separate line under the tile list. --- crates/ui-egui/src/new_project_advanced.rs | 2 +- crates/ui-egui/src/project_config.rs | 3 +-- crates/ui-egui/tests/it/new_project_window.rs | 2 +- crates/ui-egui/tests/it/project_config.rs | 4 ++-- 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 39353eef..2b96b9fb 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -193,7 +193,7 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(4.0); sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)"))); - note(ui, tr("You won't be able to change UV Tile settings after creating the project.")); + note(ui, tr("You can change UV tiles later in Texture Set Settings.")); let new_project = &mut app.ui.new_project; let mut uv_tiles = new_project.uv_tiles == Some(true); if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 8acf6cc9..7475b0b9 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -226,7 +226,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // Texture Set Settings owns UV tile changes ui.add_space(4.0); sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings."))); - note(ui, tr("You can't change UV Tile settings once a project has been created.")); + note(ui, tr("Change UV tiles in Texture Set Settings.")); let has_tiles = texture_set_tiles.iter().any(|(_, tile_text)| tile_text.is_some()); let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles.clone(), tr("Use UV Tile workflow"))), |_| {}).on_disabled_hover_text(tiles_hint); @@ -246,7 +246,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { .weak(), ); } - ui.label(egui::RichText::new(tr("Change them in Texture Set Settings")).small().weak()); }); ui.add_space(4.0); diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index c1819775..71a1602b 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -62,7 +62,7 @@ fn the_sections_follow_the_reference_order() { "Normal map format", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "You won't be able to change UV Tile settings after creating the project.", + "You can change UV tiles later in Texture Set Settings.", "Use UV Tile workflow", "Preserve UV Tile layout per material and enable painting across tiles", "Convert UV Tiles into individual Texture Sets (legacy)", diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index bbc07f87..5c55bcda 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -169,7 +169,7 @@ fn the_window_follows_the_reference_layout() { "PROJECT SETTINGS", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "You can't change UV Tile settings once a project has been created.", + "Change UV tiles in Texture Set Settings.", "Use UV Tile workflow", "Convert UV Tiles into individual Texture Sets (legacy)", "Import settings", @@ -627,7 +627,7 @@ fn uv_tiles_are_shown_read_only() { assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles"); - assert!(h.query_by_label("Change them in Texture Set Settings").is_some()); + assert!(h.query_by_label("Change UV tiles in Texture Set Settings.").is_some()); click(&mut h, Role::Button, "Cancel"); From aa6eaa42aec83c2001951058a6d06c823dbe7230 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 18 Nov 2026 00:23:25 +0100 Subject: [PATCH 5/5] Use the reference texts verbatim in all three windows The UV tile notes are the reference's again, the UV tile title has the tutorial icon (disabled), Import resources names the library 'your_assets' and has the note about adding a library. Texts the reference does not show (the OpenColorIO note, the project's UV tile list) moved into hover hints. --- crates/ui-egui/src/import_resources.rs | 5 ++- crates/ui-egui/src/new_project_advanced.rs | 6 +-- crates/ui-egui/src/project_config.rs | 38 +++++++++--------- crates/ui-egui/src/project_form.rs | 39 +++++++++++++------ crates/ui-egui/tests/it/import_resources.rs | 3 +- crates/ui-egui/tests/it/new_project_window.rs | 8 ++-- crates/ui-egui/tests/it/project_config.rs | 20 +++++++--- 7 files changed, 74 insertions(+), 45 deletions(-) diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index c08f4973..ae3ea3ea 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -203,20 +203,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { .width(TARGET_WIDTH_POINTS) .selected_text(match window.target { ImportTarget::Session => tr("current session"), - ImportTarget::Library => tr("library 'Your assets'"), + ImportTarget::Library => tr("library 'your_assets'"), }) .show_ui(ui, |ui| { if ui.selectable_label(window.target == ImportTarget::Session, tr("current session")).clicked() { window.target = ImportTarget::Session; } // Your assets hold smart materials and brush presets, not images - ui.add_enabled(false, egui::Button::selectable(false, tr("library 'Your assets'"))).on_disabled_hover_text(tr("Not available yet")); + ui.add_enabled(false, egui::Button::selectable(false, tr("library 'your_assets'"))).on_disabled_hover_text(tr("Not available yet")); }); ui.label(tr("Import your resources to:")); }); }); ui.add_space(4.0); ui.horizontal(|ui| { + ui.label(tr("To add a new library, see the Edit / Settings menu")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { cancel = ui.button(tr("Cancel")).clicked(); import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 2b96b9fb..7df3d7d5 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -12,7 +12,7 @@ use crate::TextureCraftApp; use crate::i18n::{tr, trf}; use crate::project_form::{ FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, - uv_tile_radios, + uv_tile_radios, uv_tile_title, }; use crate::state::{Mode, NewProject}; use crate::theme::{Tokens, caption}; @@ -192,8 +192,8 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { tangent_space_row(ui); ui.add_space(4.0); - sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)"))); - note(ui, tr("You can change UV tiles later in Texture Set Settings.")); + uv_tile_title(ui, tr("Paint meshes whose UVs span several UV tiles (UDIMs)")); + note(ui, tr("You won't be able to change UV Tile settings after creating the project.")); let new_project = &mut app.ui.new_project; let mut uv_tiles = new_project.uv_tiles == Some(true); if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 7475b0b9..4e9edfd1 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -15,6 +15,7 @@ use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; use crate::project_form::{ FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, uv_tile_radios, + uv_tile_title, }; use crate::state::ProjectConfig; use crate::theme::{Tokens, caption}; @@ -225,28 +226,27 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // Texture Set Settings owns UV tile changes ui.add_space(4.0); - sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings."))); - note(ui, tr("Change UV tiles in Texture Set Settings.")); + uv_tile_title(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); + note(ui, tr("You can't change UV Tile settings once a project has been created.")); let has_tiles = texture_set_tiles.iter().any(|(_, tile_text)| tile_text.is_some()); let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); - check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles.clone(), tr("Use UV Tile workflow"))), |_| {}).on_disabled_hover_text(tiles_hint); + + // The project's tiles are listed in the hover hint, the window shows only the reference's text + let mut tile_lines: Vec = texture_set_tiles + .iter() + .filter_map(|(name, tile_text)| { + let tile_list = tile_text.as_deref()?; + Some(if texture_set_tiles.len() > 1 { trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) } else { tile_list.to_string() }) + }) + .collect(); + if tile_lines.is_empty() { + tile_lines.push(tr("No UV tiles").to_string()); + } + tile_lines.push(tiles_hint.to_string()); + let tiles_text = tile_lines.join("\n"); + check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles.clone(), tr("Use UV Tile workflow"))), |_| {}) + .on_disabled_hover_text(&tiles_text); uv_tile_radios(ui, false, tiles_hint); - ui.indent("project_config_tiles", |ui| { - if !has_tiles { - ui.label(egui::RichText::new(tr("No UV tiles")).weak()); - } - for (name, tile_text) in texture_set_tiles.iter().filter(|(_, tile_text)| tile_text.is_some()) { - let tile_list = tile_text.as_deref().unwrap_or_default(); - ui.label( - egui::RichText::new(if texture_set_tiles.len() > 1 { - trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) - } else { - tile_list.to_string() - }) - .weak(), - ); - } - }); ui.add_space(4.0); sub_title(ui, tr("Import settings"), None); diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs index 3cbeca8a..3170b31c 100644 --- a/crates/ui-egui/src/project_form.rs +++ b/crates/ui-egui/src/project_form.rs @@ -12,6 +12,9 @@ use crate::widgets::section_chevron; /// Hover hint of a control whose function TextureCraft does not have yet. pub const NOT_AVAILABLE: &str = n_("Not available yet"); +/// Hover hint of the Color management dropdown while OpenColorIO is chosen. +pub const OCIO_NOT_AVAILABLE: &str = n_("OpenColorIO is not available yet. The project uses Legacy."); + /// Width of the dropdowns and fields at the right of a row. pub(crate) const FIELD_WIDTH: f32 = 220.0; @@ -94,6 +97,18 @@ pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) { }); } +/// The "UV Tile settings (UDIMs)" title: the tutorial icon (not available yet) and the info icon. +pub(crate) fn uv_tile_title(ui: &mut Ui, info: &str) { + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT); + ui.label(caption(tr("UV Tile settings (UDIMs)"))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, info); + unavailable(ui.add_enabled(false, egui::Button::new(egui_phosphor::regular::GRADUATION_CAP).frame(false))); + }); + }); +} + /// A dim italic note in a section. pub(crate) fn note(ui: &mut Ui, text: &str) { ui.horizontal(|ui| { @@ -225,24 +240,26 @@ const OCIO_EXPORT: [(&str, &str, Option<&str>); 3] = [ ]; /// The Color management section. `mode` is the dropdown's choice: Legacy shows the working color -/// space; OpenColorIO shows its settings, all disabled, and a note that it is not available yet +/// space; OpenColorIO shows its settings, all disabled, and the dropdown's hover hint says it is not available yet /// (the project stays Legacy whatever is chosen). pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement) { collapsible(ui, id, tr("Color management"), true, None, |ui| { - let tokens = Tokens::get(ui.ctx()); ui.label(caption(tr("Configuration"))); row(ui, tr("Color management"), Some(tr("Legacy works in linear sRGB. OpenColorIO manages color through a configuration")), |ui| { - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(FIELD_WIDTH).selected_text(tr(mode.label())).show_ui(ui, |ui| { - for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] { - ui.selectable_value(mode, choice, tr(choice.label())); - } - }); + let response = egui::ComboBox::from_id_salt(format!("{id}_mode")) + .width(FIELD_WIDTH) + .selected_text(tr(mode.label())) + .show_ui(ui, |ui| { + for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] { + ui.selectable_value(mode, choice, tr(choice.label())); + } + }) + .response; + if *mode == ColorManagement::OpenColorIo { + response.on_hover_text(tr(OCIO_NOT_AVAILABLE)); + } }); if *mode == ColorManagement::OpenColorIo { - ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); - ui.add(egui::Label::new(RichText::new(tr("OpenColorIO is not available yet. The project uses Legacy.")).color(tokens.warning)).wrap()); - }); for (label, value, info) in OCIO_CONFIGURATION { row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_{label}"), tr(value))); } diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index b5b72e75..a88a6eb4 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -195,7 +195,8 @@ fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { combos(&h, "current session").next().expect("the dropdown").click(); h.run_steps(3); - assert!(h.get_by_label("library 'Your assets'").accesskit_node().is_disabled()); + assert!(h.get_by_label("library 'your_assets'").accesskit_node().is_disabled()); + assert!(h.query_by_label("To add a new library, see the Edit / Settings menu").is_some(), "the note at the bottom left"); } #[test] diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 71a1602b..4935ae9c 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -9,7 +9,7 @@ use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::template_cmds::DEFAULT_TEMPLATE; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::new_project_advanced::create_command; -use texturecraft_ui_egui::project_form::NOT_AVAILABLE; +use texturecraft_ui_egui::project_form::{NOT_AVAILABLE, OCIO_NOT_AVAILABLE}; /// A quad whose UVs lie in UV tile 1002 and a camera-free OBJ const TILE_1002_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1.1 0.1\nvt 1.9 0.1\nvt 1.9 0.9\nvt 1.1 0.9\nf 1/1 2/2 3/3 4/4\n"; @@ -62,7 +62,7 @@ fn the_sections_follow_the_reference_order() { "Normal map format", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "You can change UV tiles later in Texture Set Settings.", + "You won't be able to change UV Tile settings after creating the project.", "Use UV Tile workflow", "Preserve UV Tile layout per material and enable painting across tiles", "Convert UV Tiles into individual Texture Sets (legacy)", @@ -133,6 +133,7 @@ fn settings_not_available_yet_are_disabled_with_a_hint() { let mut h = harness(); let unavailable = [ (Role::CheckBox, "Compute tangent space per fragment"), + (Role::Button, egui_phosphor::regular::GRADUATION_CAP), (Role::RadioButton, "Convert UV Tiles into individual Texture Sets (legacy)"), (Role::CheckBox, "Auto-unwrap"), (Role::Button, "Auto-unwrap options"), @@ -160,6 +161,7 @@ fn opencolorio_shows_its_settings_disabled_and_creates_legacy() { let mut h = harness(); assert!(h.query_by_label("OpenColorIO configuration").is_none(), "Legacy shows only the working color space"); + assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_none(), "no OpenColorIO hint while Legacy is chosen"); h.get_by_value("Legacy").scroll_to_me(); h.run_steps(3); @@ -168,7 +170,7 @@ fn opencolorio_shows_its_settings_disabled_and_creates_legacy() { h.get_by_label("OpenColorIO").click(); h.run_steps(3); - assert!(h.query_by_label("OpenColorIO is not available yet. The project uses Legacy.").is_some()); + assert!(h.query_by_label(OCIO_NOT_AVAILABLE).is_some(), "the dropdown's hover hint says OpenColorIO is not available yet"); for label in ["OpenColorIO configuration", "Configuration file", "Standard sRGB color space", "Auto detect color spaces", "Material color space default"] { assert!(h.query_by_label(label).is_some(), "{label} is shown"); } diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index 5c55bcda..ef11d0f2 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -169,7 +169,7 @@ fn the_window_follows_the_reference_layout() { "PROJECT SETTINGS", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "Change UV tiles in Texture Set Settings.", + "You can't change UV Tile settings once a project has been created.", "Use UV Tile workflow", "Convert UV Tiles into individual Texture Sets (legacy)", "Import settings", @@ -216,7 +216,6 @@ fn opencolorio_can_be_looked_at_but_changes_nothing() { h.get_by_label("OpenColorIO").click(); h.run_steps(3); - assert!(h.query_by_label("OpenColorIO is not available yet. The project uses Legacy.").is_some()); assert!(h.query_by_label("Bitmap import color space defaults").is_some()); assert!(h.query_by_label("Export color spaces").is_some()); @@ -626,8 +625,9 @@ fn uv_tiles_are_shown_read_only() { open_window(&mut h); assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); - assert!(h.query_by_label("No UV tiles").is_some(), "a project without UV tiles"); - assert!(h.query_by_label("Change UV tiles in Texture Set Settings.").is_some()); + hover_uv_tile_box(&mut h); + assert!(h.query_by_label_contains("No UV tiles").is_some(), "a project without UV tiles"); + assert!(h.query_by_label("You can't change UV Tile settings once a project has been created.").is_some()); click(&mut h, Role::Button, "Cancel"); @@ -635,8 +635,16 @@ fn uv_tiles_are_shown_read_only() { open_window(&mut h); - assert!(h.query_by_label("No UV tiles").is_none()); - assert!(h.query_by_label("1001").is_some(), "the tile list of a UDIM project"); + hover_uv_tile_box(&mut h); + assert!(h.query_by_label_contains("No UV tiles").is_none()); + assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project"); +} + +/// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles. +fn hover_uv_tile_box(h: &mut Harness<'_, TextureCraftApp>) { + let center = h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").rect().center(); + h.hover_at(center); + h.run_steps(30); } #[test]