diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 577da682..b225e4c3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap}; use rayon::prelude::*; use texturecraft_core::{ BakedMap, BlendMode, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, - Mask, MaskBackground, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; @@ -1037,7 +1037,7 @@ impl<'a, 'b> Texel<'a, 'b> { } let (c, _, w) = self.projected(proj); let image = sources.find_map(|s| match s { - Source::Image { name } => self.inp.images.get(name), + Source::Image { name, .. } => self.inp.images.get(name), _ => None, }); w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) @@ -1051,7 +1051,7 @@ impl<'a, 'b> Texel<'a, 'b> { let t = procedural(pattern, proj, &c); mix3(*low, *high, t) } - Source::Image { name } => { + Source::Image { name, normal_format } => { let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; let (c, proj, _) = self.projected(proj); let mut acc = [0.0f32; 4]; @@ -1063,6 +1063,8 @@ impl<'a, 'b> Texel<'a, 'b> { } match kind { ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], ChannelKind::Scalar => [acc[0]; 3], ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], @@ -2450,7 +2452,7 @@ soft {soft:?}" }; let id = f.project.alloc_id(); let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::Image { name: "decal".into() }); + fill.sources.insert(Channel::BaseColor, Source::image("decal")); f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); let composite = |alpha: f32| { let img = crate::store::ImageRes { width: 2, height: 2, rgba: vec![[1.0, 0.0, 0.0, alpha]; 4], srgb: false }; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ebc89517..551c9803 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -336,8 +336,13 @@ pub enum Source { Uniform([f32; 3]), /// A procedural pattern mixing two values. Procedural { pattern: Procedural, low: [f32; 3], high: [f32; 3] }, - /// An imported image resource, by name. - Image { name: String }, + /// An imported image resource, by name. `normal_format` is the convention of a normal map + /// image (DirectX images have their green flipped where a normal channel samples them). + Image { + name: String, + #[serde(default)] + normal_format: crate::NormalFormat, + }, /// The stack value recorded by an anchor point effect (`anchor` is the effect id) for /// `channel`; colors read as gray where a scalar is needed. Anchor { anchor: LayerId, channel: Channel }, @@ -348,6 +353,11 @@ impl Source { Source::Uniform(c.default_value()) } + /// Image resource `name` (an OpenGL normal map where a normal channel samples it). + pub fn image(name: impl Into) -> Source { + Source::Image { name: name.into(), normal_format: crate::NormalFormat::OpenGl } + } + /// The anchor point this source reads, if any. pub fn anchor(&self) -> Option { match self { diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 74c3a6ba..37cab07b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -3,7 +3,7 @@ //! the menu structure (see `menu_catalog`). use serde_json::{Value, json}; -use texturecraft_core::{BlendMode, Channel}; +use texturecraft_core::{BlendMode, Channel, NormalFormat}; use crate::{EngineError, Result, Session}; @@ -137,6 +137,16 @@ pub(crate) fn boolp(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_bool) } +/// The `normalFormat` param (`openGl` or `directX`), if given. +pub(crate) fn normal_format_param(cmd: &str, p: &Value) -> Result> { + match strp(p, "normalFormat") { + Some("openGl") | Some("opengl") => Ok(Some(NormalFormat::OpenGl)), + Some("directX") | Some("directx") => Ok(Some(NormalFormat::DirectX)), + Some(other) => Err(bad(cmd, format!("unknown normal format `{other}`"))), + None => Ok(None), + } +} + pub(crate) fn strp<'a>(p: &'a Value, key: &str) -> Option<&'a str> { p.get(key).and_then(Value::as_str) } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 28815f31..e937b6f5 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -117,7 +117,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let id = s.edit("Add decal", |s| { let id = s.doc.project.alloc_id(); let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::Image { name: image.clone() }); + fill.sources.insert(Channel::BaseColor, Source::image(image.clone())); crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor])) })?; Ok(json!({ "layer": id.0, "decal": decal })) @@ -166,7 +166,7 @@ fn set(s: &mut Session, p: &Value) -> Result { if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind { f.projection = Projection::Decal(d); if let Some(name) = image { - f.sources.insert(Channel::BaseColor, Source::Image { name }); + f.sources.insert(Channel::BaseColor, Source::image(name)); } } Ok(()) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a33c283a..a8aa62b2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -8,7 +8,7 @@ use texturecraft_core::{NormalFormat, Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; -use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; @@ -265,12 +265,7 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result Some(NormalFormat::OpenGl), - Some("directX") | Some("directx") => Some(NormalFormat::DirectX), - Some(other) => return Err(bad(cmd, format!("unknown normal format `{other}`"))), - None => None, - }; + o.normal_format = normal_format_param(cmd, p)?; match p.get("colorSpace") { None | Some(Value::Null) => {} Some(Value::String(name)) => { diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 83eb5226..228d37e1 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source}; use crate::Session; use crate::session::StackTarget; @@ -13,7 +13,8 @@ fn source_json(s: &Source) -> Value { Source::Procedural { pattern, low, high } => json!({ "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high }), - Source::Image { name } => json!({ "image": name }), + Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }), + Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }), Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }), } } diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index b992e255..239ce201 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -4,7 +4,9 @@ use serde_json::{Value, json}; use texturecraft_core::{BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Projection, Source}; -use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::commands::{ + CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p, +}; use crate::{EngineError, Result, Session, cmd, session::StackTarget}; pub fn specs() -> Vec { @@ -25,7 +27,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -306,6 +308,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { // `solo`: this channel on, every other one off. let solo = boolp(p, "solo") == Some(true); let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; + let normal_format = normal_format_param("layer.fill.set", p)?; let source = if let Some(kind) = strp(p, "procedural") { let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; let mut pr = Procedural::new(kind); @@ -326,7 +329,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { } else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) { Some(Source::Uniform(c)) } else if let Some(name) = strp(p, "image") { - Some(Source::Image { name: name.to_string() }) + Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) } else if let Some(a) = u64p(p, "anchor") { let reader = match target { FillTarget::Layer(id) => Some(id), @@ -335,13 +338,20 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?; let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch); Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?) - } else if enabled.is_some() { + } else if enabled.is_some() || normal_format.is_some() { None } else { - return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `enabled` or `solo`")); + return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `normalFormat`, `enabled` or `solo`")); }; s.edit("Set fill", |s| { let f = fill_mut(s, target)?; + // `normalFormat` alone: the convention of the channel's image. + if let (None, Some(nf)) = (&source, normal_format) { + match f.sources.get_mut(&ch) { + Some(Source::Image { normal_format, .. }) => *normal_format = nf, + _ => return Err(bad("layer.fill.set", "`normalFormat` needs an image on the channel")), + } + } match target { // A fill effect's channel is on while it has a source. FillTarget::Effect(_) if enabled == Some(false) => { diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 988e842f..3efe62bf 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -392,7 +392,8 @@ impl Session { } link.size = m.manifest.size[0]; let stem = texturecraft_formats::sanitize_resource_name(&link.name); - let old: Vec = fill.sources.values().filter_map(|src| if let Source::Image { name } = src { Some(name.clone()) } else { None }).collect(); + let old: Vec = + fill.sources.values().filter_map(|src| if let Source::Image { name, .. } = src { Some(name.clone()) } else { None }).collect(); let names = put_maps(s, &stem, &maps, &mut fill); s.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill); // Old maps go unless another layer (a duplicate) still shows them. @@ -433,7 +434,7 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft for (c, bytes, _) in maps { let name = unique(s, &format!("{stem}_{}_{cook}.png", c.id())); s.doc.resources.insert(name.clone(), Arc::new(bytes.clone())); - fill.sources.insert(*c, Source::Image { name: name.clone() }); + fill.sources.insert(*c, Source::image(name.clone())); names.push(name); } names diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index daa38a59..8a59b186 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -44,14 +44,14 @@ pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec, depth let Some(l) = p.layers.get(&id) else { return }; if let LayerKind::Fill(f) = &l.kind { for s in f.sources.values() { - if let Source::Image { name } = s { + if let Source::Image { name, .. } = s { out.push(name.clone()); } } out.extend(f.link.as_ref().map(|link| link.package.clone())); } for e in l.mask.iter().flat_map(|m| m.effects.iter()) { - if let EffectKind::Fill { source: Source::Image { name }, .. } = &e.kind { + if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind { out.push(name.clone()); } } diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 6bcbde9b..06c5ba75 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -78,7 +78,7 @@ impl Session { unique } }; - Source::Image { name: resource } + Source::image(resource) } }; fill.sources.insert(*channel, source); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index ad1c52ae..87f6d50f 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -160,7 +160,7 @@ fn add_image_fill(s: &mut Session, p: &Value) -> Result { let id = s.edit("Add image fill", |s| { let id = s.doc.project.alloc_id(); let mut fill = Fill { projection, ..Fill::default() }; - fill.sources.insert(ch, Source::Image { name: name.clone() }); + fill.sources.insert(ch, Source::image(name.clone())); crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &[ch])) })?; Ok(json!({ "layer": id.0 })) diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index c793f443..1d9cc7f0 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,13 +1,13 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelBlend, ChannelFormat, NormalFormat}; +use texturecraft_core::{Channel, ChannelBlend, ChannelFormat}; use std::sync::Arc; use texturecraft_geom::Mesh; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, normal_format_param, strp, u64p}; use crate::session::{Document, SetCache, StackTarget, check_resolution}; use crate::{Result, Session, cmd}; @@ -258,12 +258,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; - let nf = match strp(p, "normalFormat") { - Some("openGl") | Some("opengl") => Some(NormalFormat::OpenGl), - Some("directX") | Some("directx") => Some(NormalFormat::DirectX), - Some(o) => return Err(bad("textureSet.settings", format!("unknown normal format `{o}`"))), - None => None, - }; + let nf = normal_format_param("textureSet.settings", p)?; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; diff --git a/crates/engine/tests/materialcraft_link.rs b/crates/engine/tests/materialcraft_link.rs index dc4d25c7..91b86253 100644 --- a/crates/engine/tests/materialcraft_link.rs +++ b/crates/engine/tests/materialcraft_link.rs @@ -68,7 +68,7 @@ fn link(s: &Session, id: LayerId) -> texturecraft_engine::core::MaterialLink { fn map_name(s: &Session, id: LayerId, c: Channel) -> String { match &s.doc.project.layer(id).unwrap().kind { LayerKind::Fill(f) => match f.sources.get(&c) { - Some(Source::Image { name }) => name.clone(), + Some(Source::Image { name, .. }) => name.clone(), other => panic!("{other:?}"), }, _ => panic!("not a fill"), diff --git a/crates/engine/tests/materialx_import.rs b/crates/engine/tests/materialx_import.rs index c3b159b4..44084fec 100644 --- a/crates/engine/tests/materialx_import.rs +++ b/crates/engine/tests/materialx_import.rs @@ -71,8 +71,8 @@ fn a_material_becomes_one_fill_layer_in_one_undo_step() { // The one image used twice is one resource; the constant is uniform. assert_eq!(r["resources"].as_array().unwrap().len(), 1, "{r}"); let name = r["resources"][0].as_str().unwrap().to_string(); - assert!(matches!(fill.sources.get(&Channel::BaseColor), Some(Source::Image { name: n }) if *n == name)); - assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { name: n }) if *n == name)); + assert!(matches!(fill.sources.get(&Channel::BaseColor), Some(Source::Image { name: n, .. }) if *n == name)); + assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { name: n, .. }) if *n == name)); assert_eq!(fill.sources.get(&Channel::Metallic), Some(&Source::Uniform([1.0; 3]))); assert!(matches!(fill.projection, texturecraft_engine::core::Projection::Uv { scale, .. } if scale == [3.0, 3.0]), "{:?}", fill.projection); assert_eq!(s.doc.resources.len(), before + 1); diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 428a3666..18957128 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -446,3 +446,33 @@ fn fill_projection_edits_keep_what_they_do_not_change() { let after = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!((before[0] - after[0]).abs() > 0.5, "one checker cell over: {before:?} -> {after:?}"); } + +/// A fill's normal image is OpenGL unless marked DirectX, which flips its green; inspect shows +/// the mark, and a project saved before the mark existed reads its images as OpenGL. +#[test] +fn directx_normal_images_flip_green() { + let mut s = session(); + let name = s.import_resource_bytes("n.png", png(4, 4, |_, _| [128, 204, 255, 255])).unwrap(); + let layer = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + let fill = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + p["channel"] = json!("normal"); + execute(s, "layer.fill.set", &p) + }; + let green = |s: &mut Session| at(s, Channel::Normal, 200.0, 200.0)[1]; + fill(&mut s, json!({"image": name})).unwrap(); + assert!((green(&mut s) - 0.8).abs() < 0.02, "OpenGL by default: {}", green(&mut s)); + fill(&mut s, json!({"normalFormat": "directX"})).unwrap(); + assert!((green(&mut s) - 0.2).abs() < 0.02, "DirectX flips green: {}", green(&mut s)); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["sources"]["normal"], json!({"image": name, "normalFormat": "directX"})); + fill(&mut s, json!({"image": name, "normalFormat": "openGl"})).unwrap(); + assert!((green(&mut s) - 0.8).abs() < 0.02); + assert!(fill(&mut s, json!({"normalFormat": "sideways"})).is_err()); + fill(&mut s, json!({"value": [0.5, 0.5, 1.0]})).unwrap(); + assert!(fill(&mut s, json!({"normalFormat": "directX"})).is_err(), "no image on the channel"); + let old: texturecraft_engine::core::Source = serde_json::from_value(json!({"Image": {"name": "n"}})).unwrap(); + assert_eq!(old, texturecraft_engine::core::Source::image("n")); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1ddd12f3..471f164d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1819,8 +1819,18 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } } - Source::Image { name } => { + Source::Image { name, normal_format } => { ui.label(trf("Image: {name}", &[("name", &name)])); + if c.kind() == ChannelKind::NormalMap { + let mut directx = normal_format == texturecraft_engine::core::NormalFormat::DirectX; + if ui + .checkbox(&mut directx, tr("DirectX normal map")) + .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")) + .changed() + { + app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); + } + } } Source::Anchor { anchor, channel } => { ui.label(RichText::new(anchor_label(app, anchor, channel)).color(tk.text_dim)); @@ -1902,7 +1912,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Source::Anchor { anchor, channel } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), - Source::Image { name } => trf("Image: {name}", &[("name", name)]), + Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), }; combo(ui, tr("Source"), current, |ui| { if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index a42c15ae..213b3eed 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -248,6 +248,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "تمديد لا نهائي"), ("Dilation width", "عرض التمديد"), ("Direction {axis}", "الاتجاه {axis}"), + ("DirectX normal map", "خريطة نواظم DirectX"), ("Dirt", "أوساخ"), ("Disable", "تعطيل"), ("Dismiss", "تجاهل"), @@ -331,6 +332,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "ضوضاء دقيقة"), ("Fingerprints", "بصمات أصابع"), ("Flatten layer", "تسطيح الطبقة"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "يقلب القناة الخضراء للصورة، لخرائط النواظم المصنوعة ومحور Y يشير إلى الأسفل", + ), ("Flow", "التدفق"), ("Flow and opacity", "التدفق والعتامة"), ("Flow jitter", "اضطراب التدفق"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index d717d4fb..b71dd05b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -263,6 +263,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "Dilatation unendlich"), ("Dilation width", "Dilatationsbreite"), ("Direction {axis}", "Richtung {axis}"), + ("DirectX normal map", "DirectX-Normal-Map"), ("Dirt", "Schmutz"), ("Disable", "Deaktivieren"), ("Dismiss", "Schließen"), @@ -355,6 +356,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "Feines Rauschen"), ("Fingerprints", "Fingerabdrücke"), ("Flatten layer", "Ebene reduzieren"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Kehrt den Grünkanal des Bildes um, für Normal-Maps mit nach unten zeigendem Y", + ), ("Flow", "Fluss"), ("Flow and opacity", "Fluss und Deckkraft"), ("Flow jitter", "Flussstreuung"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index ae7fca54..a570b9a4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -260,6 +260,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "Dilatación infinita"), ("Dilation width", "Ancho de dilatación"), ("Direction {axis}", "Dirección {axis}"), + ("DirectX normal map", "Mapa de normales DirectX"), ("Dirt", "Suciedad"), ("Disable", "Desactivado"), ("Dismiss", "Cerrar"), @@ -346,6 +347,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "Ruido fino"), ("Fingerprints", "Huellas dactilares"), ("Flatten layer", "Acoplar capa"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Invierte el canal verde de la imagen, para mapas de normales hechos con Y hacia abajo", + ), ("Flow", "Flujo"), ("Flow and opacity", "Flujo y opacidad"), ("Flow jitter", "Variación de flujo"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index b73b79f2..8f0f7d57 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -266,6 +266,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "Dilatation infinie"), ("Dilation width", "Largeur de dilatation"), ("Direction {axis}", "Direction {axis}"), + ("DirectX normal map", "Carte de normales DirectX"), ("Dirt", "Saleté"), ("Disable", "Désactivé"), ("Dismiss", "Fermer"), @@ -358,6 +359,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "Bruit fin"), ("Fingerprints", "Empreintes digitales"), ("Flatten layer", "Aplatir le calque"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverse le canal vert de l'image, pour les cartes de normales faites avec Y vers le bas", + ), ("Flow", "Flux"), ("Flow and opacity", "Flux et opacité"), ("Flow jitter", "Variation du flux"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 0fb284f7..eb68df2e 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -266,6 +266,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "Dilatazione infinita"), ("Dilation width", "Ampiezza dilatazione"), ("Direction {axis}", "Direzione {axis}"), + ("DirectX normal map", "Mappa normali DirectX"), ("Dirt", "Sporco"), ("Disable", "Disattiva"), ("Dismiss", "Chiudi"), @@ -352,6 +353,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "Rumore fine"), ("Fingerprints", "Impronte digitali"), ("Flatten layer", "Appiattisci livello"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverte il canale verde dell'immagine, per mappe normali create con Y rivolto verso il basso", + ), ("Flow", "Flusso"), ("Flow and opacity", "Flusso e opacità"), ("Flow jitter", "Variazione flusso"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 53a63092..33638d84 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -263,6 +263,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "ダイレーション (無限)"), ("Dilation width", "ダイレーション幅"), ("Direction {axis}", "方向 {axis}"), + ("DirectX normal map", "DirectX ノーマルマップ"), ("Dirt", "汚れ"), ("Disable", "無効"), ("Dismiss", "閉じる"), @@ -343,6 +344,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "細かいノイズ"), ("Fingerprints", "指紋"), ("Flatten layer", "レイヤーを統合"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"), ("Flow", "フロー"), ("Flow and opacity", "フローと不透明度"), ("Flow jitter", "フロージッター"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 534eacdd..1cb65d4b 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -257,6 +257,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "무한 확장"), ("Dilation width", "확장 폭"), ("Direction {axis}", "방향 {axis}"), + ("DirectX normal map", "DirectX 노멀 맵"), ("Dirt", "먼지"), ("Disable", "비활성화"), ("Dismiss", "닫기"), @@ -340,6 +341,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "미세 노이즈"), ("Fingerprints", "지문"), ("Flatten layer", "레이어 병합"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"), ("Flow", "흐름"), ("Flow and opacity", "흐름 및 불투명도"), ("Flow jitter", "흐름 지터"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 941a884d..0a3398e2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -260,6 +260,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "Dilatação infinita"), ("Dilation width", "Largura da dilatação"), ("Direction {axis}", "Direção {axis}"), + ("DirectX normal map", "Mapa normal DirectX"), ("Dirt", "Sujeira"), ("Disable", "Desativado"), ("Dismiss", "Fechar"), @@ -346,6 +347,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "Ruído fino"), ("Fingerprints", "Impressões digitais"), ("Flatten layer", "Achatar camada"), + ( + "Flips the image's green channel, for normal maps made with Y pointing down", + "Inverte o canal verde da imagem, para mapas normais feitos com Y apontando para baixo", + ), ("Flow", "Fluxo"), ("Flow and opacity", "Fluxo e opacidade"), ("Flow jitter", "Variação de fluxo"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index fa4ac037..e4d73f95 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -230,6 +230,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation infinite", "无限扩张"), ("Dilation width", "扩张宽度"), ("Direction {axis}", "方向 {axis}"), + ("DirectX normal map", "DirectX 法线贴图"), ("Dirt", "污垢"), ("Disable", "禁用"), ("Dismiss", "关闭"), @@ -304,6 +305,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fine noise", "细噪波"), ("Fingerprints", "指纹"), ("Flatten layer", "合并图层"), + ("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"), ("Flow", "流量"), ("Flow and opacity", "流量与不透明度"), ("Flow jitter", "流量抖动"), diff --git a/crates/ui-egui/tests/fill_channel_image.rs b/crates/ui-egui/tests/fill_channel_image.rs index a57a66f6..e498b224 100644 --- a/crates/ui-egui/tests/fill_channel_image.rs +++ b/crates/ui-egui/tests/fill_channel_image.rs @@ -36,5 +36,28 @@ fn a_fill_channel_takes_an_image_from_its_source_menu() { h.run_steps(3); let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - assert_eq!(fill.source(Channel::Roughness), Source::Image { name }); + assert_eq!(fill.source(Channel::Roughness), Source::image(name)); +} + +/// An image on a fill's Normal channel offers a DirectX toggle that flips its green. +#[test] +fn a_normal_image_can_be_marked_directx() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("normal_dx.png", png).unwrap(); + let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let layer = LayerId(out["layer"].as_u64().unwrap()); + texturecraft_engine::execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "normal", "image": name})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + h.get_by_label("DirectX normal map").scroll_to_me(); + h.run_steps(30); + h.get_by_label("DirectX normal map").click(); + h.run_steps(3); + + let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; + assert_eq!(fill.source(Channel::Normal), Source::Image { name, normal_format: texturecraft_engine::core::NormalFormat::DirectX }); } diff --git a/docs/features.md b/docs/features.md index 281f97f0..aa7a6b98 100644 --- a/docs/features.md +++ b/docs/features.md @@ -52,7 +52,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection, with the UV scale, rotation and offset, the tri-planar blend sharpness and offset, the planar axis and offset, and the cylindrical axis in the fill's properties. Each channel takes its own image (a normal, roughness or height map, say): pick it in the channel's - source menu, which also imports one, or drop it from the Assets panel onto the channel. + source menu, which also imports one, or drop it from the Assets panel onto the channel. A + normal map image made for DirectX (Y down) is marked with **DirectX normal map** under it. Alt+click a material channel (of a fill or the brush) to keep that channel alone. - **63 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, velvet, skin, wax, glass, ice, woods, bark, stone, sand, mud, snow, bone, plastics, fabric,