From 16e70a0145a898b877cd95ab7a73abfff6fbc392 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:27:52 -0500 Subject: [PATCH 1/6] feat(export): choose the colour space of exported colour maps New texturecraft_texel::ColorSpace (sRGB, Linear Rec.709, ACEScg, ACES2065-1): the matrices are derived at first use from the published primaries and white points (BT.709, ACES S-2014-004, SMPTE ST 2065-1) with Bradford adaptation, so nothing is copied from a colour-management library. ExportOptions::color_space (command and dialog: `colorSpace`) converts the colour maps on their way out; data maps (normal, height, roughness...) are never converted. None keeps today's behaviour: sRGB in 8/16-bit files, linear Rec.709 in float files. A linear space in an integer file is written without the sRGB curve; ACEScg and ACES2065-1 in integer files warn that values outside 0-1 are clamped (EXR and HDR keep them). `$colorSpace` in a file name template now also says ACEScg / ACES2065-1. The export dialog gets a Color space combo (label translated in all ten languages). Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 2 +- crates/engine/src/file_cmds.rs | 10 +- crates/engine/tests/export_colour_space.rs | 57 ++++++ crates/formats/src/export/mod.rs | 54 ++++- crates/formats/src/export/tests.rs | 79 ++++++++ crates/texel/src/colorspace.rs | 217 +++++++++++++++++++++ crates/texel/src/lib.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/windows.rs | 12 ++ 18 files changed, 439 insertions(+), 7 deletions(-) create mode 100644 crates/engine/tests/export_colour_space.rs create mode 100644 crates/texel/src/colorspace.rs diff --git a/ROADMAP.md b/ROADMAP.md index 17640da4..7972d22e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -19,7 +19,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | +| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted), `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 95% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 75% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | | **Total** | **100** | **≈ 94%** | | | diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 32ae6b49..4f0c253a 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1)}", always, export_textures ), @@ -60,7 +60,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, size?} → [{ts, map, file, format, bitDepth, warnings}]", + "{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]", always, plan ), @@ -256,6 +256,12 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result return Err(bad(cmd, format!("unknown normal format `{other}`"))), None => None, }; + if let Some(name) = strp(p, "colorSpace") { + o.color_space = Some( + texturecraft_texel::ColorSpace::from_name(name) + .ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?, + ); + } Ok(o) } diff --git a/crates/engine/tests/export_colour_space.rs b/crates/engine/tests/export_colour_space.rs new file mode 100644 index 00000000..d1985ec8 --- /dev/null +++ b/crates/engine/tests/export_colour_space.rs @@ -0,0 +1,57 @@ +//! `file.exportTextures` / `export.plan` with `colorSpace`. + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::ColorSpace; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "layer.add.fill", &json!({ "color": [0.8, 0.2, 0.1] })).unwrap(); + s +} + +fn export(s: &mut Session, tag: &str, extra: Value) -> (Value, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("tc_export_cs_{tag}_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut p = json!({ "dir": dir.display().to_string(), "preset": "glTF PBR Metal Roughness", "format": "exr", "bitDepth": 32, "padding": "infinite" }); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + (execute(s, "file.exportTextures", &p).unwrap(), dir) +} + +fn first_pixel(path: &std::path::Path) -> [f32; 3] { + let img = image::open(path).unwrap().to_rgb32f(); + // The plane's UV layout covers the whole image; read its middle. + let px = img.get_pixel(img.width() / 2, img.height() / 2); + [px[0], px[1], px[2]] +} + +#[test] +fn colour_maps_are_written_in_the_chosen_space() { + let mut s = session(); + let (plain, dir_plain) = export(&mut s, "plain", json!({})); + let (aces, dir_aces) = export(&mut s, "aces", json!({ "colorSpace": "ACEScg" })); + let base = + |r: &Value| std::path::PathBuf::from(r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).find(|f| f.contains("BaseColor")).unwrap()); + let (a, b) = (first_pixel(&base(&plain)), first_pixel(&base(&aces))); + let want = ColorSpace::AcesCg.from_linear_rec709(a); + assert!((0..3).all(|k| (b[k] - want[k]).abs() < 1e-3), "{b:?} vs {want:?}"); + assert!((0..3).any(|k| (a[k] - b[k]).abs() > 0.01), "the colour actually changed: {a:?} vs {b:?}"); + for d in [dir_plain, dir_aces] { + let _ = std::fs::remove_dir_all(d); + } +} + +#[test] +fn the_plan_reports_the_space_and_clamping_and_bad_names_are_errors() { + let mut s = session(); + let plan = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg" })).unwrap(); + assert!(plan.as_array().unwrap().iter().any(|f| f["warnings"].as_array().is_some_and(|w| !w.is_empty())), "8-bit ACEScg warns: {plan}"); + let float = execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": "ACEScg", "format": "exr" })).unwrap(); + assert!(float.as_array().unwrap().iter().all(|f| f["warnings"].as_array().is_some_and(Vec::is_empty)), "{float}"); + for bad in ["Display P3", "", "Rec.2020"] { + assert!(execute(&mut s, "export.plan", &json!({ "preset": "glTF PBR Metal Roughness", "colorSpace": bad })).is_err(), "{bad:?}"); + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index d5ff31c6..38f22880 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -20,7 +20,7 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; @@ -323,11 +323,31 @@ pub struct ExportOptions { /// UV-tiled sets: one image of the whole tile atlas per map instead of a file per tile /// (for formats without UDIM support, with the mesh's UVs in atlas space). pub atlas: bool, + /// The colour space of the colour maps (data maps are never converted); None writes sRGB + /// into 8/16-bit files and linear Rec.709 into float files (EXR, HDR). + #[serde(skip)] + pub color_space: Option, +} + +impl ExportOptions { + /// The colour space colour maps are written in when `format` is used. + pub fn space_for(&self, format: FileFormat) -> ColorSpace { + self.color_space.unwrap_or(if format.is_float() { ColorSpace::LinearRec709 } else { ColorSpace::Srgb }) + } } impl ExportOptions { pub fn new(preset: ExportPreset) -> ExportOptions { - ExportOptions { preset, format_override: None, bit_depth_override: None, padding: Padding::Infinite, size: None, normal_format: None, atlas: false } + ExportOptions { + preset, + format_override: None, + bit_depth_override: None, + padding: Padding::Infinite, + size: None, + normal_format: None, + atlas: false, + color_space: None, + } } } @@ -462,7 +482,14 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } let format = opts.format_override.unwrap_or(map.format); let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth)); - let color_space = if is_color(map) && !format.is_float() { "sRGB" } else { "linear" }; + let space = opts.space_for(format); + let color_space = match (is_color(map), space) { + (false, _) | (true, ColorSpace::LinearRec709) => "linear", + (true, ColorSpace::Srgb) => "sRGB", + (true, other) => other.name(), + }; + // Integer files clamp to 0-1, which wide-gamut linear colour can leave. + let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); // One file per UV tile: names without `$udim` get it appended. let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { @@ -477,6 +504,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let ext = format.extension(); let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); + if clamps { + warnings.push(format!( + "{} colours outside 0-1 are clamped in {} files; use EXR or HDR to keep them", + space.name(), + format.extension().to_uppercase() + )); + } // Case-insensitive: Windows and macOS file systems are. let mut k = 2; while used.contains(&name.to_ascii_lowercase()) { @@ -697,7 +731,19 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float()).collect(); + // Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is + // encoded by `encode`; every other case is converted here (float sRGB included). + let space = opts.space_for(p.format); + let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); + let mut data = data; + if is_color(map) && rgb && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709 { + data.par_chunks_mut(n).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb: Vec = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); let mut warnings = p.warnings; let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index c8c53407..babd96db 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -509,3 +509,82 @@ fn lobe_channels_export_as_document_maps_and_gltf_extension_maps() { let plain = Fx::new(&default_channels()).render_preset("glTF PBR Metal Roughness"); assert!(!plain.iter().any(|f| f.name.contains("Clearcoat") || f.name.contains("Sheen")), "sets without the lobes export no extension maps"); } + +#[test] +fn colour_space_converts_colour_maps_only() { + let fx = Fx::new(&default_channels()); + let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); + let want_at = |space: ColorSpace, x, y| space.from_linear_rec709(fx.comp.value(Channel::BaseColor, x, y)); + // ACEScg in a float EXR: the base colour is the converted triple, above-1 values aside. + let mut exr = ExportOptions::new(preset.clone()); + exr.format_override = Some(FileFormat::Exr); + exr.bit_depth_override = Some(32); + exr.color_space = Some(ColorSpace::AcesCg); + let files = fx.render(&exr); + let img = decode(find(&files, "_BaseColor.exr")).to_rgb32f(); + for (x, y) in [(0, 0), (10, 40), (63, 63)] { + let (px, want) = (img.get_pixel(x, y), want_at(ColorSpace::AcesCg, x, y)); + assert!((0..3).all(|k| (px[k] - want[k]).abs() < 1e-4), "({x},{y}) {px:?} vs {want:?}"); + } + // Data maps are never converted: roughness and metalness (packed in the ORM map) are as before. + let default_files = + fx.render(&ExportOptions { format_override: Some(FileFormat::Exr), bit_depth_override: Some(32), ..ExportOptions::new(preset.clone()) }); + assert_eq!(find(&files, "OcclusionRoughnessMetallic").bytes, find(&default_files, "OcclusionRoughnessMetallic").bytes); + assert_eq!(find(&files, "_Normal").bytes, find(&default_files, "_Normal").bytes); + assert_ne!(find(&files, "_BaseColor").bytes, find(&default_files, "_BaseColor").bytes); + + // Linear Rec.709 in an 8-bit PNG: the values are written without the sRGB curve. + let mut lin = ExportOptions::new(preset.clone()); + lin.color_space = Some(ColorSpace::LinearRec709); + let png = decode(find(&fx.render(&lin), "_BaseColor.png")); + let v = fx.comp.value(Channel::BaseColor, 10, 40); + for k in 0..3 { + assert!((png.get_pixel(10, 40)[k] as f32 - v[k] * 255.0).abs() <= 1.0, "[{k}]"); + } + // The default is unchanged: sRGB for integer files (None and explicit sRGB agree). + let default_png = fx.render(&ExportOptions::new(preset.clone())); + let mut srgb = ExportOptions::new(preset.clone()); + srgb.color_space = Some(ColorSpace::Srgb); + assert_eq!(find(&default_png, "_BaseColor.png").bytes, find(&fx.render(&srgb), "_BaseColor.png").bytes); + // An explicit sRGB in a float file is encoded once, not twice. + let mut float_srgb = ExportOptions::new(preset); + float_srgb.format_override = Some(FileFormat::Exr); + float_srgb.bit_depth_override = Some(32); + float_srgb.color_space = Some(ColorSpace::Srgb); + let px = *decode(find(&fx.render(&float_srgb), "_BaseColor.exr")).to_rgb32f().get_pixel(10, 40); + assert!((px[0] - linear_to_srgb(v[0])).abs() < 1e-4, "{px:?}"); +} + +#[test] +fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { + let fx = Fx::new(&default_channels()); + let named = ExportPreset { + name: "named".into(), + maps: vec![MapSpec { + file: "$textureSet_$channel_$colorSpace".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![ + (Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 }), + (Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }), + (Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }), + ], + }], + }; + let plan = |space: Option, format: Option| { + let opts = ExportOptions { color_space: space, format_override: format, ..ExportOptions::new(named.clone()) }; + list_outputs(&fx.project, 0, "sphere", &opts).unwrap().remove(0) + }; + assert!(plan(None, None).name.ends_with("_sRGB.png") && plan(None, Some(FileFormat::Exr)).name.ends_with("_linear.exr"), "defaults keep their names"); + assert!(plan(Some(ColorSpace::LinearRec709), None).name.ends_with("_linear.png")); + let aces = plan(Some(ColorSpace::AcesCg), None); + assert!(aces.name.ends_with("_ACEScg.png"), "{}", aces.name); + assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings); + assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values"); + assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty()); + // The planned names are the rendered names. + let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) }; + let names: Vec = fx.render(&opts).into_iter().map(|f| f.name).collect(); + assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); + assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}"); +} diff --git a/crates/texel/src/colorspace.rs b/crates/texel/src/colorspace.rs new file mode 100644 index 00000000..a685cba5 --- /dev/null +++ b/crates/texel/src/colorspace.rs @@ -0,0 +1,217 @@ +//! Built-in colour spaces as plain maths: sRGB, linear Rec.709, ACEScg and ACES2065-1. +//! +//! The conversion matrices are derived at first use from the published primaries and white points +//! (ITU-R BT.709, ACES S-2014-004 for AP1, SMPTE ST 2065-1 for AP0) with Bradford chromatic +//! adaptation, so nothing is copied from a colour-management library. TextureCraft's colour +//! channels are linear Rec.709 internally; this module converts them for export. +//! +//! Only colour is converted. Data (normal, height, roughness...) has no colour space and never +//! goes through here. + +use std::sync::OnceLock; + +use crate::linear_to_srgb; + +/// The colour space of exported colour images. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum ColorSpace { + /// sRGB-encoded (display-referred, 0–1), Rec.709 primaries. + #[default] + Srgb, + /// Scene-linear Rec.709 / sRGB primaries, D65. + LinearRec709, + /// Scene-linear ACES AP1 primaries. + AcesCg, + /// Scene-linear ACES AP0 primaries (the archival interchange space). + Aces2065, +} + +impl ColorSpace { + pub const ALL: [ColorSpace; 4] = [ColorSpace::Srgb, ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065]; + + pub fn name(self) -> &'static str { + match self { + ColorSpace::Srgb => "sRGB", + ColorSpace::LinearRec709 => "Linear Rec.709", + ColorSpace::AcesCg => "ACEScg", + ColorSpace::Aces2065 => "ACES2065-1", + } + } + + /// A space by name, ignoring case, spaces and punctuation ("linear rec709", "ap1", "srgb_texture"). + pub fn from_name(name: &str) -> Option { + let key: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::().to_ascii_lowercase(); + Some(match key.as_str() { + "srgb" | "srgbtexture" => ColorSpace::Srgb, + "linearrec709" | "linearsrgb" | "linear" | "rec709" => ColorSpace::LinearRec709, + "acescg" | "ap1" => ColorSpace::AcesCg, + "aces20651" | "aces2065" | "ap0" | "aces" => ColorSpace::Aces2065, + _ => return None, + }) + } + + /// Whether values are scene-linear light. + pub fn is_linear(self) -> bool { + self != ColorSpace::Srgb + } + + fn primaries(self) -> Primaries { + match self { + ColorSpace::Srgb | ColorSpace::LinearRec709 => REC709, + ColorSpace::AcesCg => AP1, + ColorSpace::Aces2065 => AP0, + } + } + + /// Linear Rec.709 `rgb` as values in this space: the primaries are converted, and sRGB + /// also gets its transfer curve (clamped to 0–1). Linear spaces keep values outside 0–1. + /// Non-finite input becomes 0. + pub fn from_linear_rec709(self, rgb: [f32; 3]) -> [f32; 3] { + let rgb = rgb.map(|v| if v.is_finite() { v } else { 0.0 }); + let out = match matrix_to(self) { + Some(m) => [0, 1, 2].map(|i| m[i][0] * rgb[0] + m[i][1] * rgb[1] + m[i][2] * rgb[2]), + None => rgb, + }; + if self == ColorSpace::Srgb { out.map(linear_to_srgb) } else { out } + } +} + +type M3 = [[f64; 3]; 3]; + +#[derive(Clone, Copy)] +struct Primaries { + r: [f64; 2], + g: [f64; 2], + b: [f64; 2], + white: [f64; 2], +} + +const D65: [f64; 2] = [0.3127, 0.3290]; +const D60_ACES: [f64; 2] = [0.32168, 0.33767]; +const REC709: Primaries = Primaries { r: [0.640, 0.330], g: [0.300, 0.600], b: [0.150, 0.060], white: D65 }; +const AP1: Primaries = Primaries { r: [0.713, 0.293], g: [0.165, 0.830], b: [0.128, 0.044], white: D60_ACES }; +const AP0: Primaries = Primaries { r: [0.7347, 0.2653], g: [0.0, 1.0], b: [0.0001, -0.0770], white: D60_ACES }; + +const BRADFORD: M3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]; + +fn mul(a: &M3, b: &M3) -> M3 { + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = (0..3).map(|k| a[i][k] * b[k][j]).sum(); + } + } + o +} + +fn apply(m: &M3, v: [f64; 3]) -> [f64; 3] { + [0, 1, 2].map(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) +} + +fn inverse(m: &M3) -> Option { + let c = |r: usize, c: usize| { + let (r1, r2) = ((r + 1) % 3, (r + 2) % 3); + let (c1, c2) = ((c + 1) % 3, (c + 2) % 3); + m[r1][c1] * m[r2][c2] - m[r1][c2] * m[r2][c1] + }; + let det = m[0][0] * c(0, 0) + m[0][1] * c(0, 1) + m[0][2] * c(0, 2); + if det.abs() < 1e-12 || !det.is_finite() { + return None; + } + let mut o = [[0.0; 3]; 3]; + for (i, row) in o.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v = c(j, i) / det; + } + } + Some(o) +} + +fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { + [xy[0] / xy[1], 1.0, (1.0 - xy[0] - xy[1]) / xy[1]] +} + +/// RGB (linear) to XYZ for a set of primaries, scaled so white maps to the white point. +fn rgb_to_xyz(p: &Primaries) -> Option { + let (r, g, b) = (xy_to_xyz(p.r), xy_to_xyz(p.g), xy_to_xyz(p.b)); + let cols = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]]; + let s = apply(&inverse(&cols)?, xy_to_xyz(p.white)); + Some([[r[0] * s[0], g[0] * s[1], b[0] * s[2]], [r[1] * s[0], g[1] * s[1], b[1] * s[2]], [r[2] * s[0], g[2] * s[1], b[2] * s[2]]]) +} + +/// Bradford chromatic adaptation from one white point to another. +fn adapt(from: [f64; 2], to: [f64; 2]) -> Option { + let (cs, cd) = (apply(&BRADFORD, xy_to_xyz(from)), apply(&BRADFORD, xy_to_xyz(to))); + let scale = [[cd[0] / cs[0], 0.0, 0.0], [0.0, cd[1] / cs[1], 0.0], [0.0, 0.0, cd[2] / cs[2]]]; + Some(mul(&inverse(&BRADFORD)?, &mul(&scale, &BRADFORD))) +} + +/// The matrix from linear Rec.709 to the linear primaries of `to` (cached). +fn matrix_to(to: ColorSpace) -> Option<[[f32; 3]; 3]> { + static CACHE: OnceLock<[Option<[[f32; 3]; 3]>; 4]> = OnceLock::new(); + let table = CACHE.get_or_init(|| { + ColorSpace::ALL.map(|s| { + let (from, to) = (REC709, s.primaries()); + let m = mul(&inverse(&rgb_to_xyz(&to)?)?, &mul(&adapt(from.white, to.white)?, &rgb_to_xyz(&from)?)); + Some(m.map(|r| r.map(|v| v as f32))) + }) + }); + let i = ColorSpace::ALL.iter().position(|s| *s == to)?; + table.get(i).copied().flatten() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::srgb_to_linear; + + fn close(a: [f32; 3], b: [f32; 3], tol: f32) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol) + } + + #[test] + fn white_stays_white_in_every_linear_space() { + for s in [ColorSpace::LinearRec709, ColorSpace::AcesCg, ColorSpace::Aces2065] { + assert!(close(s.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-4), "{s:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([1.0; 3]), [1.0; 3], 1e-5)); + } + + #[test] + fn rec709_primaries_in_acescg_match_published_values() { + // Rec.709 red in ACEScg (AP1, D60): the widely published 0.6131 0.0702 0.0206. + assert!(close(ColorSpace::AcesCg.from_linear_rec709([1.0, 0.0, 0.0]), [0.6131, 0.0702, 0.0206], 2e-3)); + // And in ACES2065-1 (AP0): 0.4397 0.0897 0.0175. + assert!(close(ColorSpace::Aces2065.from_linear_rec709([1.0, 0.0, 0.0]), [0.4397, 0.0897, 0.0175], 2e-3)); + } + + #[test] + fn grey_stays_neutral_and_srgb_is_the_transfer_curve() { + for s in ColorSpace::ALL { + let o = s.from_linear_rec709([0.18; 3]); + assert!(close(o, [o[0]; 3], 1e-4), "{s:?} {o:?}"); + } + assert!(close(ColorSpace::Srgb.from_linear_rec709([0.5; 3]), [linear_to_srgb(0.5); 3], 1e-6)); + assert!((srgb_to_linear(ColorSpace::Srgb.from_linear_rec709([0.25; 3])[0]) - 0.25).abs() < 1e-5); + assert_eq!(ColorSpace::LinearRec709.from_linear_rec709([0.3, 2.0, -1.0]), [0.3, 2.0, -1.0], "linear Rec.709 is the identity, values above 1 kept"); + } + + #[test] + fn hostile_values_stay_finite() { + for s in ColorSpace::ALL { + assert!(s.from_linear_rec709([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).iter().all(|v| v.is_finite()), "{s:?}"); + } + } + + #[test] + fn names_round_trip_and_aliases_work() { + for s in ColorSpace::ALL { + assert_eq!(ColorSpace::from_name(s.name()), Some(s)); + } + assert_eq!(ColorSpace::from_name("srgb_texture"), Some(ColorSpace::Srgb)); + assert_eq!(ColorSpace::from_name("AP1"), Some(ColorSpace::AcesCg)); + assert_eq!(ColorSpace::from_name("linear"), Some(ColorSpace::LinearRec709)); + assert_eq!(ColorSpace::from_name("nope"), None); + assert!(!ColorSpace::Srgb.is_linear() && ColorSpace::AcesCg.is_linear()); + } +} diff --git a/crates/texel/src/lib.rs b/crates/texel/src/lib.rs index 329ffaa4..982ca101 100644 --- a/crates/texel/src/lib.rs +++ b/crates/texel/src/lib.rs @@ -6,10 +6,12 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod colorspace; pub mod dilate; pub mod noise; pub mod tile; +pub use colorspace::ColorSpace; pub use dilate::DilationMap; pub use tile::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 976d68cb..79b7654e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -521,6 +521,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "ناظم من الارتفاع"), ("Normal map combine", "دمج خرائط النواظم"), ("Normal map detail", "تفاصيل خريطة النواظم"), + ("Color space", "فضاء الألوان"), ("Normal map format", "صيغة خريطة النواظم"), ("Normal map inverse detail", "عكس تفاصيل خريطة النواظم"), ("Normal: painting uses the flat normal", "عادي: يستخدم الرسم الناظم المسطح"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 383fd770..bbbc7189 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -548,6 +548,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale aus Höhe"), ("Normal map combine", "Normal-Map kombinieren"), ("Normal map detail", "Normal-Map-Detail"), + ("Color space", "Farbraum"), ("Normal map format", "Normal-Map-Format"), ("Normal map inverse detail", "Normal-Map-Detail invertiert"), ("Normal: painting uses the flat normal", "Normale: Malen verwendet die flache Normale"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d2bbe0f8..eca8e7da 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -542,6 +542,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normal desde altura"), ("Normal map combine", "Combinar mapa de normales"), ("Normal map detail", "Detalle de mapa de normales"), + ("Color space", "Espacio de color"), ("Normal map format", "Formato del mapa de normales"), ("Normal map inverse detail", "Detalle inverso de mapa de normales"), ("Normal: painting uses the flat normal", "Normal: la pintura usa la normal plana"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 07cf9981..3130c83c 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -551,6 +551,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale depuis la hauteur"), ("Normal map combine", "Normales : combinaison"), ("Normal map detail", "Normales : détail"), + ("Color space", "Espace colorimétrique"), ("Normal map format", "Format de carte de normales"), ("Normal map inverse detail", "Normales : détail inverse"), ("Normal: painting uses the flat normal", "Normal : la peinture utilise la normale plate"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index d4818eca..114c49d2 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -548,6 +548,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normale da altezza"), ("Normal map combine", "Combina mappa normali"), ("Normal map detail", "Dettaglio mappa normali"), + ("Color space", "Spazio colore"), ("Normal map format", "Formato mappa normali"), ("Normal map inverse detail", "Dettaglio inverso mappa normali"), ("Normal: painting uses the flat normal", "Normale: la pittura usa la normale piatta"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 62c1c15d..b61b239b 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -533,6 +533,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "ハイトからノーマル"), ("Normal map combine", "ノーマルマップ合成"), ("Normal map detail", "ノーマルマップ ディテール"), + ("Color space", "カラースペース"), ("Normal map format", "ノーマルマップ形式"), ("Normal map inverse detail", "ノーマルマップ 逆ディテール"), ("Normal: painting uses the flat normal", "ノーマル: ペイントにはフラットな法線を使用"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index ec37113c..806b41bf 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -527,6 +527,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "높이에서 노멀"), ("Normal map combine", "노멀 맵 결합"), ("Normal map detail", "노멀 맵 디테일"), + ("Color space", "색 공간"), ("Normal map format", "노멀 맵 형식"), ("Normal map inverse detail", "노멀 맵 역 디테일"), ("Normal: painting uses the flat normal", "노멀: 평면 노멀로 페인팅합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 5db5da19..1835047a 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -539,6 +539,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "Normal a partir da altura"), ("Normal map combine", "Combinação de mapa normal"), ("Normal map detail", "Detalhe de mapa normal"), + ("Color space", "Espaço de cor"), ("Normal map format", "Formato do mapa normal"), ("Normal map inverse detail", "Detalhe inverso de mapa normal"), ("Normal: painting uses the flat normal", "Normal: a pintura usa a normal plana"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 895dfc20..5e67cb03 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -482,6 +482,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normal from height", "由高度生成法线"), ("Normal map combine", "法线贴图合并"), ("Normal map detail", "法线贴图细节"), + ("Color space", "色彩空间"), ("Normal map format", "法线贴图格式"), ("Normal map inverse detail", "法线贴图反向细节"), ("Normal: painting uses the flat normal", "法线:绘画使用平坦法线"), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 287be1a3..e335c705 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -167,6 +167,9 @@ pub struct ExportUi { pub size: u32, /// "" (project), openGl or directX. pub normal_format: String, + /// "" (by file format: sRGB, or linear for float files), or a colour space name. + #[serde(default)] + pub color_space: String, /// Texture sets excluded from export. pub skip: Vec, pub tab: u8, @@ -189,6 +192,7 @@ impl Default for ExportUi { dilation: 16, size: 0, normal_format: String::new(), + color_space: String::new(), skip: Vec::new(), tab: 0, draft: None, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eab0046e..adfc1cf2 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1063,6 +1063,9 @@ pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value { if !e.normal_format.is_empty() { p["normalFormat"] = json!(e.normal_format); } + if !e.color_space.is_empty() { + p["colorSpace"] = json!(e.color_space); + } p } @@ -1162,6 +1165,15 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur } }); ui.end_row(); + ui.label(tr("Color space")); + let shown = if app.ui.export.color_space.is_empty() { tr("Default") } else { app.ui.export.color_space.as_str() }; + egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { + ui.selectable_value(&mut app.ui.export.color_space, String::new(), tr("Default")); + for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { + ui.selectable_value(&mut app.ui.export.color_space, name.to_string(), name); + } + }); + ui.end_row(); }); } From 0d2f1873cda17c5d767828b2839e9aeacb4b2c79 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:13:00 +0700 Subject: [PATCH 2/6] Effects: drag to reorder, duplicate Effect rows in the layer stack can be dragged within their stack (a drop lands above the row, or below it from its lower half), and their context menu duplicates an effect just above itself, painted pixels included. effect.move {effect, index} and effect.duplicate {effect} give agents the same. --- crates/engine/src/mask_cmds.rs | 56 +++++++++++++++++++++++++- crates/engine/tests/content_effects.rs | 39 ++++++++++++++++++ crates/ui-egui/src/dock.rs | 47 +++++++++++++++++---- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/tests/effect_rows.rs | 48 ++++++++++++++++++++++ docs/control-protocol.md | 4 +- docs/features.md | 3 +- 15 files changed, 195 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/tests/effect_rows.rs diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index f570c0c9..90d54c0b 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Source, + Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -99,6 +99,8 @@ pub fn specs() -> Vec { set ), cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect), + cmd!("effect.duplicate", "Duplicate effect", [], None, "{effect} → {effect} (the copy, just above it, pixels included)", has_layer, duplicate_effect), + cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), cmd!( "effect.histogram", "Effect input histogram", @@ -456,6 +458,58 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. +fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { + project.layers.values_mut().find_map(|l| { + l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)).find_map(|list| { + let i = list.iter().position(|e| e.id == eid)?; + Some((list, i)) + }) + }) +} + +fn duplicate_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.duplicate"; + let eid = effect_id(p, CMD)?; + let new = s.edit("Duplicate effect", |s| { + let new = s.doc.project.alloc_id(); + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let mut e = list.get(i).cloned().ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + e.id = new; + e.name = format!("{} copy", e.name); + list.insert(i + 1, e); + // Painted effects keep their pixels (copy-on-write tiles: cheap). + let px = &mut s.doc.pixels; + if let Some(img) = px.masks.get(&eid).cloned() { + px.masks.insert(new, img); + } + for c in Channel::ALL { + if let Some(img) = px.layer(eid, c).cloned() { + px.layers.insert((new, c), img); + } + } + Ok(new) + })?; + if s.target == StackTarget::Effect(eid) { + s.target = StackTarget::Effect(new); + } + Ok(json!({ "effect": new.0 })) +} + +fn move_effect(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.move"; + let eid = effect_id(p, CMD)?; + let index = u64p(p, "index").ok_or_else(|| bad(CMD, "`index` is required"))?; + s.edit("Move effect", |s| { + let (list, i) = stack_of(&mut s.doc.project, eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?; + let e = list.remove(i); + let to = usize::try_from(index).unwrap_or(usize::MAX).min(list.len()); + list.insert(to, e); + Ok(()) + })?; + Ok(Value::Null) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { let eid = effect_id(p, "effect.remove")?; s.edit("Remove effect", |s| { diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index 0134b4c0..d67300f7 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -112,6 +112,45 @@ fn painting_into_a_content_paint_effect() { assert!(center(&mut s, Channel::Roughness)[0] > 0.85); } +#[test] +fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3})).unwrap(), "layer"); + let paint = id(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(), "effect"); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let fill = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.2})).unwrap(), "effect"); + let order = |s: &Session| s.doc.project.layer(LayerId(layer)).unwrap().content_effects.iter().map(|e| e.id.0).collect::>(); + assert!(close(center(&mut s, Channel::Roughness), [0.2; 3]), "the fill covers the paint"); + // To the bottom, the paint shows again; an index past the end means the top. + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 0})).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "{:?}", center(&mut s, Channel::Roughness)); + execute(&mut s, "effect.move", &json!({"effect": fill, "index": 99})).unwrap(); + assert_eq!(order(&s), [paint, fill]); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(order(&s), [fill, paint]); + assert!(execute(&mut s, "effect.move", &json!({"effect": fill})).is_err(), "index is required"); + assert!(execute(&mut s, "effect.move", &json!({"effect": 999_999, "index": 0})).is_err()); + // A duplicate sits just above its original with the painted pixels, and takes the selection. + execute(&mut s, "layer.select", &json!({"layer": layer, "target": paint})).unwrap(); + let copy = id(execute(&mut s, "effect.duplicate", &json!({"effect": paint})).unwrap(), "effect"); + assert_eq!(order(&s), [fill, paint, copy]); + assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); + assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); + execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); + assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); + assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); + // Mask effects move within the mask. + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let a = id(execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap(), "effect"); + let b = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect"); + execute(&mut s, "effect.move", &json!({"effect": b, "index": 0})).unwrap(); + let mask: Vec = s.doc.project.layer(LayerId(layer)).unwrap().mask.as_ref().unwrap().effects.iter().map(|e| e.id.0).collect(); + assert_eq!(mask, [b, a]); +} + #[test] fn histogram_counts_what_an_effect_reads() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..018f06cf 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,7 +5,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -255,11 +255,11 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; layer_row(app, ui, &layer, depth); for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::SPHERE); + effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); } if let Some(m) = &layer.mask { for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, e.id, &e.name, e.visible, depth + 1, ic::MAGIC_WAND); + effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); } } if let LayerKind::Group { children, collapsed } = &layer.kind @@ -522,12 +522,16 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } -/// One effect of a layer's content (`glyph` sphere) or mask (`glyph` wand) stack. -#[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, name: &str, visible: bool, depth: usize, glyph: &str) { +/// The drag-and-drop payload of an effect row (the effect id). +struct EffectDrag(u64); + +/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { let tk = Tokens::get(ui.ctx()); + let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( rect.shrink2(vec2(0.0, 1.0)), @@ -548,13 +552,40 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerI let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(11.5), tk.text); + p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); } + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. + if resp.drag_started() { + resp.dnd_set_drag_payload(EffectDrag(eid.0)); + } + let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); + let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); + if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + let y = if below { rect.bottom() } else { rect.top() }; + p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + } + if let Some(src) = dnd_release::(&resp) + && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + && from != to + { + // Rows list the stack top first, so above this row is the next index up. + let index = match (from < to, below) { + (true, false) | (false, true) => to, + (true, true) => to - 1, + (false, false) => to + 1, + }; + app.run("effect.move", json!({"effect": src.0, "index": index})); + } resp.context_menu(|ui| { + if ui.button(tr("Duplicate effect")).clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + app.run("effect.duplicate", json!({"effect": eid.0})); + ui.close(); + } if ui.button(tr("Remove effect")).clicked() { app.run("effect.remove", json!({"effect": eid.0})); ui.close(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..ebd718d3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -264,6 +264,7 @@ pub const TABLE: &[(&str, &str)] = &[ "اسحب الإطار لتحريك الملصق، أو الزاوية لتغيير حجمه، أو المقبض الدائري لتدويره", ), ("Dry streaks", "خطوط جافة"), + ("Duplicate effect", "تكرار التأثير"), ("Duplicate layer(s)", "تكرار الطبقة (الطبقات)"), ("Duplicate the selected template", "تكرار القالب المحدد"), ("Edge Detect", "اكتشاف الحواف"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..6e6fa352 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -282,6 +282,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Rahmen ziehen, um das Decal zu verschieben, eine Ecke zum Skalieren, den runden Griff zum Drehen", ), ("Dry streaks", "Trockene Schlieren"), + ("Duplicate effect", "Effekt duplizieren"), ("Duplicate layer(s)", "Ebene(n) duplizieren"), ("Duplicate the selected template", "Ausgewählte Vorlage duplizieren"), ("Edge Detect", "Kantenerkennung"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..4f6fc01a 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -279,6 +279,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Arrastra el marco para mover la calcomanía, una esquina para escalarla y el tirador redondo para girarla", ), ("Dry streaks", "Trazos secos"), + ("Duplicate effect", "Duplicar efecto"), ("Duplicate layer(s)", "Duplicar capa(s)"), ("Duplicate the selected template", "Duplicar la plantilla seleccionada"), ("Edge Detect", "Detección de bordes"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..2cdf3974 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -282,6 +282,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Faites glisser le cadre pour déplacer le décalque, un coin pour le mettre à l'échelle, la poignée ronde pour le faire pivoter", ), ("Dry streaks", "Traînées sèches"), + ("Duplicate effect", "Dupliquer l'effet"), ("Duplicate layer(s)", "Dupliquer le(s) calque(s)"), ("Duplicate the selected template", "Dupliquer le modèle sélectionné"), ("Edge Detect", "Détection des contours"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..0d3f774e 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -285,6 +285,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Trascina il riquadro per spostare la decal, un angolo per scalarla, la maniglia rotonda per ruotarla", ), ("Dry streaks", "Striature secche"), + ("Duplicate effect", "Duplica effetto"), ("Duplicate layer(s)", "Duplica livello/i"), ("Duplicate the selected template", "Duplica il modello selezionato"), ("Edge Detect", "Rilevamento bordi"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..ab32816f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -273,6 +273,7 @@ pub const TABLE: &[(&str, &str)] = &[ "テクスチャセット「{set}」の {name} を描画します。ソースへの編集はすべてのインスタンスに反映されます。", ), ("Dry streaks", "かすれ"), + ("Duplicate effect", "エフェクトを複製"), ("Duplicate layer(s)", "レイヤーを複製"), ("Duplicate the selected template", "選択中のテンプレートを複製"), ("Edge Detect", "エッジ検出"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..af73d445 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -270,6 +270,7 @@ pub const TABLE: &[(&str, &str)] = &[ "텍스처 세트 \"{set}\"의 {name}을(를) 그립니다. 원본을 편집하면 모든 인스턴스에 반영됩니다.", ), ("Dry streaks", "마른 붓자국"), + ("Duplicate effect", "이펙트 복제"), ("Duplicate layer(s)", "레이어 복제"), ("Duplicate the selected template", "선택한 템플릿을 복제합니다"), ("Edge Detect", "가장자리 검출"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..e80c78f0 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -279,6 +279,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Arraste o quadro para mover o decalque, um canto para redimensioná-lo e a alça redonda para girá-lo", ), ("Dry streaks", "Estrias secas"), + ("Duplicate effect", "Duplicar efeito"), ("Duplicate layer(s)", "Duplicar camada(s)"), ("Duplicate the selected template", "Duplicar o modelo selecionado"), ("Edge Detect", "Detecção de bordas"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..4e2b7200 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -240,6 +240,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Drags the layer stack's values along the stroke into the selected layer.", "沿笔画将图层堆栈的值拖入所选图层。"), ("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", "绘制纹理集“{set}”的 {name}。对源的编辑会显示在每个实例中。"), ("Dry streaks", "干笔条纹"), + ("Duplicate effect", "创建效果副本"), ("Duplicate layer(s)", "创建图层副本"), ("Duplicate the selected template", "创建所选模板的副本"), ("Edge Detect", "边缘检测"), diff --git a/crates/ui-egui/tests/effect_rows.rs b/crates/ui-egui/tests/effect_rows.rs new file mode 100644 index 00000000..218eb0cc --- /dev/null +++ b/crates/ui-egui/tests/effect_rows.rs @@ -0,0 +1,48 @@ +//! Effect rows in the layer stack: dragging one reorders its stack. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. +fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = h.get_by_label(from).rect().center(); + let r = h.get_by_label(to).rect(); + let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); + h.drag_at(start); + h.run_steps(2); + h.hover_at(end); + h.run_steps(2); + h.drop_at(end); + h.run_steps(3); +} + +#[test] +fn dragging_an_effect_row_reorders_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&h), [a, b, c]); + // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. + drag(&mut h, "Effect A", "Effect C", false); + assert_eq!(order(&h), [b, c, a]); + // A dropped on B's lower half goes back to the bottom. + drag(&mut h, "Effect A", "Effect B", true); + assert_eq!(order(&h), [a, b, c]); + // C dropped on A's upper half lands between A and B. + drag(&mut h, "Effect C", "Effect A", false); + assert_eq!(order(&h), [a, c, b]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 86d84ea2..5e63c7f8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -14,7 +14,9 @@ Programmatic calls never open dialogs: a command runs with its defaults. Only `u behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels -effect's input), so an agent can pick its input range from the data. +effect's input), so an agent can pick its input range from the data. `effect.move {effect, +index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies +one just above itself. ## Control channel (desktop app) diff --git a/docs/features.md b/docs/features.md index 5043fcac..90ecf3a3 100644 --- a/docs/features.md +++ b/docs/features.md @@ -42,7 +42,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a - mask to view it alone. + mask to view it alone. Drag an effect to reorder its stack, or right-click it to duplicate it + (painted strokes included). - **Fill layers** take uniform values, **23 procedurals** (clouds, cells, grunge, scratches, wood grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection. From 76b24c4e3d8861a09763a55760b0686c1a236510 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:24:24 +0700 Subject: [PATCH 3/6] Export colour space: tag MaterialX colour maps with it, warn when a colour map is not converted The .mtlx tags colour textures with the export's colour space: srgb_texture, lin_rec709, acescg, or lin_ap0_scene for ACES2065-1 (MaterialX 1.39 has no AP0 space; the export warns). A colour map packed into one channel (L) is not converted and now says so. The $colorSpace variable's description lists every value. --- crates/engine/src/file_cmds.rs | 6 ++++-- crates/engine/tests/materialx.rs | 19 +++++++++++++++++++ crates/formats/src/export/mod.rs | 9 ++++++--- crates/formats/src/export/tests.rs | 9 +++++++++ crates/formats/src/materialx.rs | 19 ++++++++++++++++--- 5 files changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 60d83cf9..8f808ec3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -457,6 +457,9 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: if opts.normal_format == Some(NormalFormat::DirectX) { warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); } + if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) { + warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into()); + } let mut out = Vec::new(); let mut stems = std::collections::HashSet::new(); for &ts in sets { @@ -469,8 +472,7 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: Some(t) => f.name.replacen(&format!(".{t}."), "..", 1), None => f.name.clone(), }; - // Float files hold linear values; 8/16-bit colour maps are sRGB encoded. - let colorspace = if f.format.is_float() { "lin_rec709" } else { "srgb_texture" }; + let colorspace = materialx::colorspace_name(opts.space_for(f.format)); if !textures.iter().any(|t| t.input == input) { textures.push(Texture { input: input.to_owned(), file, colorspace }); } diff --git a/crates/engine/tests/materialx.rs b/crates/engine/tests/materialx.rs index b3e4520f..35ba658a 100644 --- a/crates/engine/tests/materialx.rs +++ b/crates/engine/tests/materialx.rs @@ -82,6 +82,25 @@ fn float_colour_maps_are_tagged_linear() { assert!(text.contains("_base_color.exr\" colorspace=\"lin_rec709\"") && !text.contains("srgb_texture"), "{text}"); } +#[test] +fn colour_maps_are_tagged_with_the_export_colour_space() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for (space, tag, warns) in [("ACEScg", "acescg", false), ("ACES2065-1", "lin_ap0_scene", true), ("sRGB", "srgb_texture", false)] { + let dir = temp(tag); + let r = execute( + &mut s, + "file.exportTextures", + &json!({"dir": dir.display().to_string(), "preset": OPENPBR, "format": "exr", "colorSpace": space, "materialX": true}), + ) + .unwrap(); + let mtlx = files(&r).into_iter().find(|f| f.ends_with(".mtlx")).unwrap(); + let text = std::fs::read_to_string(mtlx).unwrap(); + assert!(text.contains(&format!("_base_color.exr\" colorspace=\"{tag}\"")), "{space}: {text}"); + let warned = r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("ACES2065-1")); + assert_eq!(warned, warns, "{space}: {r}"); + } +} + #[test] fn sets_with_the_same_file_name_warn_instead_of_overwriting() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 38f22880..e4010f20 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -41,7 +41,7 @@ pub const FILE_TOKENS: [(&str, &str); 6] = [ ("$textureSet", "Texture set name"), ("$project", "Project name"), ("$channel", "Channel or map id"), - ("$colorSpace", "sRGB or linear"), + ("$colorSpace", "Colour maps: sRGB, linear, ACEScg or ACES2065-1; data maps: linear"), ("$udim", "UV tile number (1001 for sets without UV tiles)"), ]; @@ -736,15 +736,18 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); let mut data = data; - if is_color(map) && rgb && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709 { + let mut warnings = p.warnings; + let convert = is_color(map) && (space != ColorSpace::Srgb || p.format.is_float()) && space != ColorSpace::LinearRec709; + if convert && rgb { data.par_chunks_mut(n).for_each(|px| { if let [r, g, b, ..] = px { [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); } }); + } else if convert { + warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name())); } let srgb: Vec = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); - let mut warnings = p.warnings; let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) }) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index babd96db..c4966585 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -588,3 +588,12 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); assert!(names[0].ends_with("_ACES2065-1.png"), "{names:?}"); } + +#[test] +fn colour_packed_into_one_channel_warns_instead_of_converting_silently() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { name: "l".into(), maps: vec![gray_map("$textureSet_red", SourceRef::Channel { channel: Channel::BaseColor, component: 0 })] }; + let opts = |space| ExportOptions { color_space: space, format_override: Some(FileFormat::Exr), ..ExportOptions::new(preset.clone()) }; + assert!(fx.render(&opts(Some(ColorSpace::AcesCg)))[0].warnings.iter().any(|w| w.contains("ACEScg"))); + assert!(fx.render(&opts(None))[0].warnings.is_empty(), "linear Rec.709 needs no conversion"); +} diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index d1c0edce..e7440328 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -9,14 +9,15 @@ //! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node //! (OpenGL, +Y up, which is what that node expects). //! -//! Colour textures (base, fuzz and emission colour) are tagged with their file's colour space -//! (`srgb_texture` for 8/16-bit files, `lin_rec709` for float ones); every data map is left -//! untagged (linear). UDIM sets write the `` filename token MaterialX defines. +//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were +//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. //! Texture file names are relative to the document. use std::collections::HashSet; use std::fmt::Write as _; +use texturecraft_texel::ColorSpace; + /// How an OpenPBR input is typed in the document. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { @@ -63,6 +64,18 @@ pub struct Texture { pub colorspace: &'static str, } +/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no +/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the +/// specification, which 1.39 readers may not know. +pub fn colorspace_name(space: ColorSpace) -> &'static str { + match space { + ColorSpace::Srgb => "srgb_texture", + ColorSpace::LinearRec709 => "lin_rec709", + ColorSpace::AcesCg => "acescg", + ColorSpace::Aces2065 => "lin_ap0_scene", + } +} + /// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → /// `base_color`), or None for templates this module has no place for. pub fn input_of_template(template: &str) -> Option<&'static str> { From d71cdfa3ca9f400f476c85a334bf5153b7861ecd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:35:32 +0700 Subject: [PATCH 4/6] Undo: never leave a removed effect selected Undoing an effect's add or duplicate took the selected effect away and left the selection on it, so the row lost its highlight and strokes had no target. The selection now falls back to the stack the effect was in. --- crates/engine/src/session.rs | 8 ++++++++ crates/engine/tests/content_effects.rs | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 14891a8f..baf012b6 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -629,6 +629,14 @@ impl Session { self.modified = true; self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); + // An undone add or duplicate takes the selected effect away: select the stack it was in. + if let StackTarget::Effect(e) = self.target + && self.doc.project.effect(e).is_none() + { + let p = &other.project; + let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); + self.target = if content { StackTarget::Content } else { StackTarget::Mask }; + } } // ----------------------------------------------------------------------------------------- diff --git a/crates/engine/tests/content_effects.rs b/crates/engine/tests/content_effects.rs index d67300f7..dca2378b 100644 --- a/crates/engine/tests/content_effects.rs +++ b/crates/engine/tests/content_effects.rs @@ -139,6 +139,10 @@ fn effects_move_within_their_stack_and_duplicate_with_their_pixels() { assert_eq!(order(&s), [fill, paint, copy]); assert_eq!(s.target, StackTarget::Effect(LayerId(copy))); assert!(s.doc.project.effect(LayerId(copy)).unwrap().1.name.ends_with(" copy")); + // Undoing it leaves no missing effect selected, but the stack it was in. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.target, StackTarget::Content); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); execute(&mut s, "effect.remove", &json!({"effect": paint})).unwrap(); assert!(center(&mut s, Channel::Roughness)[0] > 0.85, "the copy keeps the strokes"); assert!(execute(&mut s, "effect.duplicate", &json!({"effect": 999_999})).is_err()); From 410cf3a14f8a4d17f01a1c703ac98a3642023dcd Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 11:48:32 +0700 Subject: [PATCH 5/6] Brush: Ctrl+drag sets size, hardness, flow and angle Ctrl (Cmd on macOS) + right-drag in the 3D or 2D view changes the brush size (left/right) and hardness (up/down), Ctrl + left-drag its flow and angle, instead of orbiting or painting. The brush cursor stays where the drag began, with the values beside it, and the Brush properties name the gesture. --- crates/ui-egui/src/dock.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 4 ++ crates/ui-egui/src/i18n/de.rs | 4 ++ crates/ui-egui/src/i18n/es.rs | 4 ++ crates/ui-egui/src/i18n/fr.rs | 4 ++ crates/ui-egui/src/i18n/it.rs | 4 ++ crates/ui-egui/src/i18n/ja.rs | 4 ++ crates/ui-egui/src/i18n/ko.rs | 4 ++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++ crates/ui-egui/src/i18n/zh_hans.rs | 4 ++ crates/ui-egui/src/viewport.rs | 85 +++++++++++++++++++++++++--- crates/ui-egui/tests/brush_drag.rs | 46 +++++++++++++++ crates/ui-egui/tests/ui_snapshots.rs | 12 ++++ docs/features.md | 2 + 14 files changed, 175 insertions(+), 8 deletions(-) create mode 100644 crates/ui-egui/tests/brush_drag.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ba2ddcfd..2891f723 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1027,6 +1027,8 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); + let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); + ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); section(ui, "sec_size", tr("Size"), true, |ui| { let mut size = b.size / 0.25 * 100.0; if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 75c795b3..f7fa1ea8 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -206,6 +206,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "صندوق"), ("Create", "إنشاء"), ("Create smart material", "إنشاء مادة ذكية"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+السحب بالزر الأيمن في عرض يضبط الحجم والصلابة، وCtrl+السحب بالزر الأيسر يضبط التدفق والزاوية.", + ), ("Cube", "مكعب"), ("Current layer", "الطبقة الحالية"), ("Curvature", "الانحناء"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b0341184..4aa3f940 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Kiste"), ("Create", "Erstellen"), ("Create smart material", "Smart-Material erstellen"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Strg+Ziehen mit RMT in einer Ansicht stellt Größe und Härte ein, Strg+Ziehen mit LMT Fluss und Winkel.", + ), ("Cube", "Würfel"), ("Current layer", "Aktuelle Ebene"), ("Curvature", "Krümmung"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index df2151d9..dbbaae73 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caja"), ("Create", "Crear"), ("Create smart material", "Crear material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastrar con botón der. en una vista ajusta el tamaño y la dureza; Ctrl+arrastrar con botón izq., el flujo y el ángulo.", + ), ("Cube", "Cubo"), ("Current layer", "Capa actual"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 2b943710..2a0ccd36 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caisse"), ("Create", "Créer"), ("Create smart material", "Créer un matériau intelligent"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+glisser (clic droit) dans une vue règle la taille et la dureté, Ctrl+glisser (clic gauche) le flux et l'angle.", + ), ("Cube", "Cube"), ("Current layer", "Calque actuel"), ("Curvature", "Courbure"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 5192aef7..d5d907c4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -221,6 +221,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Cassa"), ("Create", "Crea"), ("Create smart material", "Crea materiale intelligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+trascina con il tasto destro in una vista per regolare dimensione e durezza, con il sinistro flusso e angolo.", + ), ("Cube", "Cubo"), ("Current layer", "Livello corrente"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 9b1d9be9..65e3df29 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -218,6 +218,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "木箱"), ("Create", "作成"), ("Create smart material", "スマートマテリアルを作成"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "ビューでCtrl+右ドラッグでサイズと硬さ、Ctrl+左ドラッグでフローと角度を設定します。", + ), ("Cube", "立方体"), ("Current layer", "現在のレイヤー"), ("Curvature", "曲率"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index df30e1a5..9ddec591 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -209,6 +209,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "상자"), ("Create", "만들기"), ("Create smart material", "스마트 머티리얼 만들기"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "뷰에서 Ctrl+오른쪽 드래그로 크기와 경도를, Ctrl+왼쪽 드래그로 흐름과 각도를 설정합니다.", + ), ("Cube", "큐브"), ("Current layer", "현재 레이어"), ("Curvature", "곡률"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 097a6e00..65b65087 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -215,6 +215,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "Caixote"), ("Create", "Criar"), ("Create smart material", "Criar material inteligente"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "Ctrl+arrastar com botão direito em uma vista ajusta o tamanho e a dureza; Ctrl+arrastar com botão esquerdo, o fluxo e o ângulo.", + ), ("Cube", "Cubo"), ("Current layer", "Camada atual"), ("Curvature", "Curvatura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index b21bebf9..b21f8549 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -188,6 +188,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Crate", "箱子"), ("Create", "创建"), ("Create smart material", "创建智能材质"), + ( + "Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.", + "在视图中按住 Ctrl 右键拖动可调整大小和硬度,Ctrl 左键拖动可调整流量和角度。", + ), ("Cube", "立方体"), ("Current layer", "当前图层"), ("Curvature", "曲率"), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 06011755..a88fe262 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -199,14 +199,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0)); let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift)); let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top()); - let navigating = alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down()); + let adjusting = brush_drag(app, ui, &resp); + let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down())); // Navigation (S + drag manipulates the projection stencil instead, below). let delta = ui.input(|i| i.pointer.delta()); let s_held = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); - if stencil_drag { - // The stencil moves, turns and scales instead of the camera (handled below). + if stencil_drag || adjusting { + // The stencil moves, turns and scales instead of the camera (handled below), or the + // brush changes. } else if resp.dragged_by(PointerButton::Middle) { app.session.camera.pan(delta.x / size.y, delta.y / size.y); } else if alt && resp.dragged_by(PointerButton::Primary) { @@ -302,8 +304,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The selected decal's frame and handles: drag to move, scale or turn it. let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect); // Painting. - let painting = - app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && !decal_drag; + let painting = app.ui.mode == crate::state::Mode::Painting + && !alt + && !adjusting + && !s_held + && !v_held + && !focus_pick + && placing.is_none() + && touch.is_none() + && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; let vp = app.session.viewport; let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p); @@ -368,8 +377,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Painting && !navigating && resp.hovered() - && matches!(app.session.tool.tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) - && let Some(hp) = resp.hover_pos() + && brush_tool(app.session.tool.tool) + // While a Ctrl+drag changes the brush, its cursor stays where the drag began. + && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() } && let Some(hit) = app.session.pick(local(hp), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); @@ -392,6 +402,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); + brush_readout(app, ui, &resp, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( rect.left_top() + vec2(12.0, 40.0), @@ -754,6 +765,62 @@ fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { } } +/// Tools that paint with the brush (and show its cursor). +fn brush_tool(t: Tool) -> bool { + matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) +} + +/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a +/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True +/// while Ctrl is held with a brush tool and no stroke is under way. +fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool { + let held = + app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command); + if held && let Some(right) = brush_drag_button(resp) { + adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta())); + } + held +} + +/// The button of a drag on `resp`: Some(true) right, Some(false) left. +fn brush_drag_button(resp: &egui::Response) -> Option { + let right = resp.dragged_by(PointerButton::Secondary); + (right || resp.dragged_by(PointerButton::Primary)).then_some(right) +} + +/// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the +/// view; the tool bar and Properties show them too). +fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) { + let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; + let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; + // The pointer would cover the values; the brush cursor stays where the drag began. + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let b = &app.session.tool.brush; + let text = if right { + format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) + } else { + format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle) + }; + let tk = Tokens::get(ui.ctx()); + let p = ui.painter_at(resp.rect); + let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong); + let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0)); + p.rect_filled(r, 3.0, tk.panel); + p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); +} + +/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else +/// the flow (x) and angle (y); dragging up raises hardness and angle. +fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) { + if right { + b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25); + b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999); + } else { + b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0); + b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0; + } +} + fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { let (lo, hi) = app.session.mesh.bounds(); let r = app.session.tool.brush.size * (hi - lo).length(); @@ -791,6 +858,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); let alt = ui.input(|i| i.modifiers.alt); + let adjusting = brush_drag(app, ui, &resp); let delta = ui.input(|i| i.pointer.delta()); if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) { app.ui.uv_pan[0] += delta.x / size.x * 2.0; @@ -836,7 +904,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let uv = to_uv(p); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } - let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; if painting && path_tool { path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show); } else if painting { @@ -898,6 +966,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Painting && path_tool { path_overlay(app, ui, rect, &resp, true, show); } + brush_readout(app, ui, &resp, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); diff --git a/crates/ui-egui/tests/brush_drag.rs b/crates/ui-egui/tests/brush_drag.rs new file mode 100644 index 00000000..9a8b1d10 --- /dev/null +++ b/crates/ui-egui/tests/brush_drag.rs @@ -0,0 +1,46 @@ +//! Ctrl+drag in the 3D view changes the brush instead of painting or orbiting. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +/// Drag with `button` from `from` by `by` in a few moves. +fn drag(h: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + h.run_steps(2); + for k in 1..=4 { + h.hover_at(from + by * (k as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); +} + +#[test] +fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { + 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.run_steps(4); + let c = h.state().viewport_rect.center(); + let (brush, yaw, history) = { + let s = &h.state().session; + (s.tool.brush.clone(), s.camera.yaw, s.history_labels().len()) + }; + // Right drag to the right and up: a bigger, harder brush; the camera stays. + drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::COMMAND); + let b = h.state().session.tool.brush.clone(); + assert!(b.size > brush.size && b.hardness > brush.hardness, "{} {} → {} {}", brush.size, brush.hardness, b.size, b.hardness); + assert_eq!(h.state().session.camera.yaw, yaw, "no orbit"); + // Left drag to the left and up: less flow, a turned brush, and no stroke. + drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND); + let b2 = h.state().session.tool.brush.clone(); + assert!(b2.flow < b.flow && b2.angle != b.angle, "{} {} → {} {}", b.flow, b.angle, b2.flow, b2.angle); + assert_eq!(h.state().session.history_labels().len(), history, "nothing painted"); + // Without Ctrl, a right drag orbits again and the brush keeps its values. + drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::NONE); + assert_ne!(h.state().session.camera.yaw, yaw); + assert_eq!(h.state().session.tool.brush, b2); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2a44f4ff..8b4dae9b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -73,4 +73,16 @@ fn window_snapshots() { texturecraft_engine::execute(s, id, &p).unwrap(); } save(&mut h, &dir, "properties-levels"); + // Ctrl+right drag in the 3D view: the brush cursor where it began and the readout. + let c = h.state().viewport_rect.center(); + let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); + h.event(egui::Event::ModifiersChanged(m)); + h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m }); + for k in 1..=4 { + h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32)); + h.run_steps(1); + } + save(&mut h, &dir, "brush-ctrl-drag"); + h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m }); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } diff --git a/docs/features.md b/docs/features.md index 5043fcac..a1795141 100644 --- a/docs/features.md +++ b/docs/features.md @@ -7,6 +7,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Brushes** with size, flow, stroke opacity, spacing, hardness, angle and follow path; size, angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too) and pen pressure. + Ctrl+drag in a view sets them on the fly: right-drag the size and hardness, left-drag the flow + and angle. **67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha. **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size; save your own brushes there too. From b133186641b545d580a563468f8164a1565bd5da Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 2 Nov 2026 12:00:09 +0700 Subject: [PATCH 6/6] History: click a step to return to it The History panel lists every undone step too (dimmed, next first) and a click on any step goes back or forward to it, the current one highlighted. edit.undo and edit.redo take {steps?} for the same jump. --- crates/engine/src/session.rs | 4 +++ crates/engine/src/view_cmds.rs | 47 ++++++++++++++++++++++++--- crates/engine/tests/session.rs | 24 ++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/windows.rs | 25 ++++++++++---- crates/ui-egui/tests/history_panel.rs | 36 ++++++++++++++++++++ docs/control-protocol.md | 3 ++ docs/features.md | 1 + 16 files changed, 137 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/tests/history_panel.rs diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 14891a8f..de97ce6a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -601,6 +601,10 @@ impl Session { pub fn redo_label(&self) -> Option<&str> { self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. + pub fn redo_labels(&self) -> Vec { + self.redo.iter().rev().map(|(l, _)| l.clone()).collect() + } pub fn history_labels(&self) -> Vec { self.undo.iter().map(|(l, _)| l.clone()).collect() } diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 2237a698..b39c876d 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -5,7 +5,7 @@ use texturecraft_core::project::ENVIRONMENTS; use texturecraft_core::{BakedMap, Channel, ToneMapping}; use texturecraft_geom::glam::Vec3; -use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp}; +use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; use crate::session::ViewMode; use crate::{Result, Session, cmd}; @@ -35,14 +35,51 @@ pub fn specs() -> Vec { pub(crate) fn edit_specs() -> Vec { vec![ - cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))), - cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))), - cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok( - json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::>() }) + cmd!( + "edit.undo", + "Undo", + ["Edit"], + Some("Ctrl+Z"), + "{steps?: 1 (as many as there are)} → {undone: the last step undone, steps}", + can_undo, + |s, p| { + let (last, n) = repeat(s, p, Session::undo)?; + Ok(json!({ "undone": last, "steps": n })) + } + ), + cmd!( + "edit.redo", + "Redo", + ["Edit"], + Some("Ctrl+Y"), + "{steps?: 1 (as many as there are)} → {redone: the last step redone, steps}", + can_redo, + |s, p| { + let (last, n) = repeat(s, p, Session::redo)?; + Ok(json!({ "redone": last, "steps": n })) + } + ), + cmd!("edit.history", "History", [], None, "{} → {undo: steps, oldest first, redo: undone steps, next first}", always, |s, _| Ok( + json!({ "undo": s.history_labels(), "redo": s.redo_labels() }) )), ] } +/// Run `step` (undo or redo) `steps` times (default 1) or until the history runs out: the last +/// step's label and how many ran (the History panel jumps to a step this way). +fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result) -> Result<(String, u64)> { + let steps = u64p(p, "steps").unwrap_or(1).max(1); + let mut last = step(s)?; + let mut n = 1; + while n < steps + && let Ok(l) = step(s) + { + last = l; + n += 1; + } + Ok((last, n)) +} + fn frame(s: &mut Session, _: &Value) -> Result { let (lo, hi) = s.mesh.bounds(); s.camera.frame(lo, hi); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 5e22e610..02be7a8d 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -69,6 +69,30 @@ fn layer_rename_and_undo() { assert_eq!(s.doc.project.layer(layer_id).unwrap().name, "Custom Paint"); } +#[test] +fn undo_and_redo_jump_several_steps() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + let name = |s: &Session| s.doc.project.layer(layer).unwrap().name.clone(); + let first = name(&s); + for n in ["A", "B", "C"] { + execute(&mut s, "layer.rename", &json!({"name": n})).unwrap(); + } + let base = s.history_labels().len() - 3; + // Two back to "A": the undone steps wait to be redone, next first. + assert_eq!(execute(&mut s, "edit.undo", &json!({"steps": 2})).unwrap(), json!({"undone": "Rename layer", "steps": 2})); + assert_eq!(name(&s), "A"); + assert_eq!(s.redo_labels().len(), 2); + assert_eq!(execute(&mut s, "edit.history", &Value::Null).unwrap()["redo"].as_array().unwrap().len(), 2); + // Forward past the end stops at "C"; back past the start stops at the first state. + assert_eq!(execute(&mut s, "edit.redo", &json!({"steps": 99})).unwrap()["steps"], 2); + assert_eq!(name(&s), "C"); + let r = execute(&mut s, "edit.undo", &json!({"steps": 1_000_000})).unwrap(); + assert_eq!(r["steps"].as_u64().unwrap() as usize, base + 3); + assert_eq!(name(&s), first); + assert!(execute(&mut s, "edit.undo", &json!({"steps": 2})).is_err(), "nothing left to undo"); +} + #[test] fn polygon_fill_and_color_picker() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 60a24624..d9659ae5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -657,6 +657,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), ("Return to painting mode", "العودة إلى نمط الرسم"), + ("Return to this step", "العودة إلى هذه الخطوة"), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index b750471d..0be0cc4b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -699,6 +699,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), ("Return to painting mode", "Zurück zum Malmodus"), + ("Return to this step", "Zu diesem Schritt zurückkehren"), ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), ("Rotation", "Drehung"), ("Rotation (degrees)", "Drehung (Grad)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 23366253..0c73dcd0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -687,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), ("Return to painting mode", "Volver al modo de pintura"), + ("Return to this step", "Volver a este paso"), ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), ("Rotation", "Rotación"), ("Rotation (degrees)", "Rotación (grados)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 8fe9ccbb..6dea9b52 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -699,6 +699,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), ("Return to painting mode", "Revenir au mode peinture"), + ("Return to this step", "Revenir à cette étape"), ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), ("Rotation", "Rotation"), ("Rotation (degrees)", "Rotation (degrés)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 62ec183b..c837665d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -696,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), ("Return to painting mode", "Torna alla modalità pittura"), + ("Return to this step", "Torna a questo passaggio"), ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), ("Rotation", "Rotazione"), ("Rotation (degrees)", "Rotazione (gradi)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 7dc6e6e1..e11cb5ed 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -675,6 +675,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), ("Return to painting mode", "ペイントモードに戻る"), + ("Return to this step", "このステップに戻る"), ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), ("Rotation", "回転"), ("Rotation (degrees)", "回転 (度)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f9c167e7..225316a4 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -666,6 +666,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), ("Return to painting mode", "페인팅 모드로 돌아가기"), + ("Return to this step", "이 단계로 돌아가기"), ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), ("Rotation", "회전"), ("Rotation (degrees)", "회전 (도)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index dc7521c3..4a2cb7a9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -684,6 +684,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), ("Return to painting mode", "Voltar ao modo de pintura"), + ("Return to this step", "Voltar a esta etapa"), ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), ("Rotation", "Rotação"), ("Rotation (degrees)", "Rotação (graus)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 41136b04..471c4f3c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -615,6 +615,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), ("Return to painting mode", "返回绘画模式"), + ("Return to this step", "返回到此步骤"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 6d44fc5f..8fa3de0e 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -281,16 +281,27 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { /// The History panel body (a dock tab). pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); - let labels = app.session.history_labels(); + let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative. + let mut jump = 0i64; egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - ui.label(RichText::new(tr("Project opened")).color(tk.text_dim)); - for l in &labels { - ui.label(l); - } - if let Some(r) = app.session.redo_label() { - ui.label(RichText::new(trf("{action} (undone)", &[("action", &r)])).color(tk.text_dim)); + let n = done.len() as i64; + let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim)) + .chain(done.iter().map(RichText::new)) + .chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim))); + for (i, text) in rows.enumerate() { + // Row i is the state after i steps. + let steps = n - i as i64; + if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { + jump = steps; + } } }); + if jump > 0 { + app.run("edit.undo", json!({ "steps": jump })); + } else if jump < 0 { + app.run("edit.redo", json!({ "steps": -jump })); + } ui.horizontal(|ui| { if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { app.run("edit.undo", json!({})); diff --git a/crates/ui-egui/tests/history_panel.rs b/crates/ui-egui/tests/history_panel.rs new file mode 100644 index 00000000..b3f134f0 --- /dev/null +++ b/crates/ui-egui/tests/history_panel.rs @@ -0,0 +1,36 @@ +//! A click on a step of the History panel goes back or forward to it. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +#[test] +fn clicking_a_history_step_returns_to_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + for name in ["Step A", "Step B", "Step C"] { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); + } + let done = session.history_labels().len(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.dock.focus(Panel::History); + h.run_steps(4); + let name = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].name.clone(); + // The first state: everything undone, and listed as undone. + h.get_by_label("Project opened").click(); + h.run_steps(3); + assert!(!h.state().session.can_undo()); + assert_eq!(h.state().session.redo_labels().len(), done); + // The first undone row is the next step: one redo. + h.get_all_by_label("Rename layer (undone)").next().unwrap().click(); + h.run_steps(3); + assert_eq!(h.state().session.history_labels().len(), 1); + assert_eq!(h.state().session.redo_labels().len(), done - 1); + // The last undone row: all the way forward again. + h.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + h.run_steps(3); + assert_eq!(name(&h), "Step C"); + assert!(!h.state().session.can_redo()); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f8048861..5d59d5d1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -16,6 +16,9 @@ painted tile count, so an agent can verify its work without a screenshot. `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. +`edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far +as the history reaches); `edit.history` lists the steps done and the undone ones, next first. + ## Control channel (desktop app) ```sh diff --git a/docs/features.md b/docs/features.md index 7b858cfe..d76b0a55 100644 --- a/docs/features.md +++ b/docs/features.md @@ -120,6 +120,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - A **start window** at launch: a new project, a project file, a recent project or the sample (Settings › Interface › Start window). - A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip. +- A **History** panel: click any step to go back to it, or forward again to an undone one. - **10 languages:** English, French, German, Spanish, Portuguese, Italian, Japanese, Chinese, Korean and Arabic, switchable live. - **In the browser:** the same app compiled to WebAssembly, on WebGPU or WebGL2, with touch