From 471b21cb7dd876b263b046c441c56d7641bef117 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 01/54] Generator picker: the reference's names on orb thumbnails, swapping the kind in place Generators carry the reference app's names (Metal Edge Wear, Ambient Occlusion, Light, Position). The generator slot opens the shared resource picker with each kind rendered as a mask on the smart masks' preview orb, a die on seeded kinds, larger thumbnails and no current-item outline. Thin areas stays loadable but is no longer offered. effect.set {generator} swaps a generator's kind in place, keeping its position, blending and opacity. --- crates/core/src/layer.rs | 43 +++++++- crates/engine/src/mask_cmds.rs | 40 +++++++- crates/engine/src/orb_preview.rs | 45 ++++++++- crates/engine/tests/it/generator_swap.rs | 65 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 9 +- crates/ui-egui/src/generator_slot.rs | 50 ++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/preview_request.rs | 3 +- crates/ui-egui/src/preview_worker.rs | 4 +- crates/ui-egui/src/resource_picker.rs | 28 +++++- crates/ui-egui/src/resource_slot.rs | 68 +++++++++++++ crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_preview.rs | 9 +- crates/ui-egui/src/thumbs.rs | 7 +- crates/ui-egui/src/tile_picture.rs | 4 +- crates/ui-egui/tests/it/generator_panel.rs | 8 +- crates/ui-egui/tests/it/generator_picker.rs | 103 ++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + 19 files changed, 463 insertions(+), 29 deletions(-) create mode 100644 crates/engine/tests/it/generator_swap.rs create mode 100644 crates/ui-egui/src/generator_slot.rs create mode 100644 crates/ui-egui/src/resource_slot.rs create mode 100644 crates/ui-egui/tests/it/generator_picker.rs diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index e352bbc0..b3186d4d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -940,16 +940,39 @@ impl GeneratorKind { ]; pub fn label(self) -> &'static str { match self { - GeneratorKind::EdgeWear => "Mask Editor: Edge wear", + GeneratorKind::EdgeWear => "Metal Edge Wear", GeneratorKind::Dirt => "Dirt", GeneratorKind::ThinAreas => "Thin areas", GeneratorKind::Curvature => "Curvature", - GeneratorKind::AmbientOcclusion => "Ambient occlusion", - GeneratorKind::Position => "Position gradient", - GeneratorKind::Direction => "Light / direction", + GeneratorKind::AmbientOcclusion => "Ambient Occlusion", + GeneratorKind::Position => "Position", + GeneratorKind::Direction => "Light", } } + /// The name commands and saved projects use for this kind + pub fn id(self) -> &'static str { + match self { + GeneratorKind::EdgeWear => "EdgeWear", + GeneratorKind::Dirt => "Dirt", + GeneratorKind::ThinAreas => "ThinAreas", + GeneratorKind::Curvature => "Curvature", + GeneratorKind::AmbientOcclusion => "AmbientOcclusion", + GeneratorKind::Position => "Position", + GeneratorKind::Direction => "Direction", + } + } + + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) + pub fn in_picker(self) -> bool { + self != GeneratorKind::ThinAreas + } + + /// Whether the kind's result depends on its seed + pub fn includes_randomness(self) -> bool { + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt) + } + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. pub fn inputs(self) -> &'static [BakedMap] { match self { @@ -962,7 +985,7 @@ impl GeneratorKind { pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); - GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) + GeneratorKind::ALL.into_iter().find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s)) } } @@ -2245,6 +2268,16 @@ mod tests { assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0)); } + #[test] + fn generator_ids_are_the_saved_names_and_parse_back() { + for kind in GeneratorKind::ALL { + assert_eq!(serde_json::to_value(kind).unwrap(), serde_json::json!(kind.id())); + assert_eq!(GeneratorKind::parse(kind.id()), Some(kind)); + assert_eq!(GeneratorKind::parse(kind.label()), Some(kind)); + } + assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 385447a0..8cf8deef 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -785,10 +785,17 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let swaps_filter = swapped.is_some(); let id_map = crate::color_selection_cmds::id_map_param(session, params)?; + let swapped_generator = match strp(params, "generator") { + Some(kind) => swapped_generator_kind(session, effect, kind)?, + None => None, + }; let mesh = session.mesh.clone(); session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some(generator) = swapped_generator { + edited.kind = EffectKind::Generator(generator); + } if let Some((kind, label)) = swapped { if let EffectKind::Filter(old) = &edited.kind && (edited.name == old.label() || Some(edited.name.as_str()) == old.former_label()) @@ -939,6 +946,37 @@ fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { } } +/// A generator of kind `name` at its defaults to replace generator effect `effect`, or None when it is that kind already +fn swapped_generator_kind(s: &Session, effect: LayerId, name: &str) -> Result> { + const CMD: &str = "effect.set"; + let kind = GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))?; + match &s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?.1.kind { + EffectKind::Generator(current) if current.kind == kind => Ok(None), + EffectKind::Generator(current) => Ok(Some(swapped_kind(current, kind))), + other => Err(bad(CMD, format!("`generator` changes generator effects only, not {}", other.name().to_ascii_lowercase()))), + } +} + +/// `current` as a `kind` generator: the settings every kind shares and the inputs `kind` reads stay, its own controls start from `kind`'s defaults +fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { + let mut inputs = current.inputs.clone(); + inputs.retain(|map, _| kind.inputs().contains(map)); + Generator { + level: current.level, + softness: current.softness, + noise_amount: current.noise_amount, + noise_scale: current.noise_scale, + seed: current.seed, + offset: current.offset, + direction: current.direction, + invert: current.invert, + global: current.global, + resolution: current.resolution, + inputs, + ..Generator::new(kind) + } +} + /// Filter `id` built with `p` and its label, to replace filter effect `effect` fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { const CMD: &str = "effect.set"; diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index f29a247d..a0b701a4 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_core::{BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, LayerId, MaskBackground}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; @@ -14,7 +14,7 @@ pub use crate::material_preview_pixel::MaterialPreviewPixel; use crate::orb_camera::OrbCamera; use crate::preview::Sample; use crate::session::Document; -use crate::{EngineError, Result, Session, materials}; +use crate::{EngineError, Result, Session, materials, smart_masks}; /// Bake resolution in texels; 256 loses the thin edge lines const TEXTURE_PX: u32 = 512; @@ -80,7 +80,26 @@ impl OrbPreview { crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; // Previews need no undo history; retaining snapshots grows memory across presets self.session.undo.clear(); + self.mask_pixels(size) + } + /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape + /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each generator goes on the bare shape, not over the previous mask + (self.session.doc, self.session.selected) = self.bare.clone(); + let effects = vec![(EffectKind::Generator(Generator::new(kind)), BlendMode::Normal)]; + let mask = smart_masks::build_mask(&mut self.session.doc.project, MaskBackground::Black, effects); + self.session.doc.project.layer_mut(self.layer).ok()?.mask = Some(mask); + self.mask_pixels(size) + } + + /// Row-major `size²` pixels of the preview layer's current mask, with None outside the shape + fn mask_pixels(&mut self, size: usize) -> Option>> { let camera = camera_for(&mut self.cameras, &self.session, size)?; let values = self.session.mask_at(self.layer, &camera.texels)?; @@ -262,6 +281,28 @@ mod tests { assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); } + #[test] + fn generator_previews_render_on_the_orb_and_each_starts_from_the_bare_shape() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for kind in GeneratorKind::ALL { + let pixels = preview.generator(kind, size).unwrap_or_else(|| panic!("{kind:?}")); + assert_eq!(pixels.len(), size * size, "{kind:?}"); + assert!(pixels[0].is_none(), "{kind:?}: the corners are outside the shape"); + for pixel in pixels.iter().flatten() { + assert!((0.0..=1.0).contains(&pixel.mask) && pixel.normal.is_finite() && pixel.coverage > 0.0, "{kind:?}: {pixel:?}"); + } + } + + let (edges, dirt) = (preview.generator(GeneratorKind::EdgeWear, size).unwrap(), preview.generator(GeneratorKind::Dirt, size).unwrap()); + assert!(difference(&edges, &dirt) > 0.05, "edge wear and dirt differ: {}", difference(&edges, &dirt)); + + // A smart mask rendered in between leaves nothing behind + preview.mask("dirt_cavities", size).unwrap(); + assert_eq!(preview.generator(GeneratorKind::EdgeWear, size).unwrap(), edges); + assert!(preview.generator(GeneratorKind::EdgeWear, 0).is_none()); + } + #[test] fn smart_materials_render_on_the_orb_and_show_their_wear() { let size = 24; diff --git a/crates/engine/tests/it/generator_swap.rs b/crates/engine/tests/it/generator_swap.rs new file mode 100644 index 00000000..a91790d0 --- /dev/null +++ b/crates/engine/tests/it/generator_swap.rs @@ -0,0 +1,65 @@ +//! Swapping a generator effect's kind in place with `effect.set {generator}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + texturecraft_engine::sample_session(128, 64).unwrap() +} + +/// A fill layer whose black mask holds a filter, then a Dirt generator at half opacity, multiplied: (filter, generator) +fn masked(session: &mut Session) -> (u64, u64) { + execute(session, "layer.add.fill", &Value::Null).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let filter = execute(session, "effect.add.filter", &json!({"filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + let generator = + execute(session, "effect.add.generator", &json!({"generator": "Dirt", "level": 0.9, "blend": "multiply"})).unwrap()["effect"].as_u64().unwrap(); + execute(session, "effect.set", &json!({"effect": generator, "opacity": 0.5})).unwrap(); + (filter, generator) +} + +fn effect_kind(session: &Session, effect: u64) -> EffectKind { + session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone() +} + +#[test] +fn another_kind_keeps_the_shared_settings_and_starts_its_own_controls_from_defaults() { + let mut session = session(); + let (_, generator) = masked(&mut session); + let (owner, _) = session.doc.project.effect(LayerId(generator)).unwrap(); + let position = |session: &Session| session.doc.project.layer(owner).unwrap().mask.as_ref().unwrap().effects.iter().position(|e| e.id.0 == generator); + let before = position(&session); + + execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "Curvature"})).unwrap(); + + let defaults = Generator::new(GeneratorKind::Curvature); + let EffectKind::Generator(curvature) = effect_kind(&session, generator) else { panic!("still a generator") }; + assert_eq!(curvature.kind, GeneratorKind::Curvature); + assert_eq!(curvature.level, 0.9, "keeps the shared settings"); + assert_eq!(curvature.detail, defaults.detail, "its own controls start from defaults"); + let (_, swapped) = session.doc.project.effect(LayerId(generator)).unwrap(); + assert_eq!((swapped.blend, swapped.opacity), (BlendMode::Multiply, 0.5), "keeps blending and opacity"); + assert_eq!(position(&session), before, "keeps its place in the mask"); +} + +#[test] +fn naming_the_current_kind_edits_the_generator_without_resetting_it() { + let mut session = session(); + let (_, generator) = masked(&mut session); + + execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "Dirt", "softness": 0.4})).unwrap(); + + let EffectKind::Generator(edited) = effect_kind(&session, generator) else { panic!("still a generator") }; + assert_eq!((edited.level, edited.softness), (0.9, 0.4)); +} + +#[test] +fn only_generator_effects_take_a_generator_kind() { + let mut session = session(); + let (filter, generator) = masked(&mut session); + + assert!(execute(&mut session, "effect.set", &json!({"effect": filter, "generator": "Curvature"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "nope"})).is_err()); + assert!(matches!(effect_kind(&session, filter), EffectKind::Filter(_)), "a refused swap changes nothing"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ce9f1614..bd56a597 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_swap; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bfd9742e..47bf6aa1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -22,14 +22,7 @@ const INPUT_TILE_ICON_SIZE: f32 = 16.0; /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { - for kind in GeneratorKind::ALL { - if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() && kind != generator.kind { - app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")})); - } - } - }); + crate::generator_slot::show(app, ui, id, generator); section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); diff --git a/crates/ui-egui/src/generator_slot.rs b/crates/ui-egui/src/generator_slot.rs new file mode 100644 index 00000000..99c19557 --- /dev/null +++ b/crates/ui-egui/src/generator_slot.rs @@ -0,0 +1,50 @@ +//! The generator slot atop a generator's properties: its orb and name, opening a picker that swaps its kind + +use egui::{Sense, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Generator, GeneratorKind}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::resource_slot::{ResourceSlot, SLOT_HEIGHT}; +use crate::tile_picture::TilePicture; + +/// The slot of generator effect `effect`: a pick runs `effect.set {generator}` +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generator: &Generator) { + let ctx = ui.ctx().clone(); + let current = generator.kind; + let thumbnail = app.thumbs.generator(&ctx, current); + let name = tr(current.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + let popup = ui.make_persistent_id(("generator_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + let slot = ResourceSlot { highlighted, focused: response.has_focus(), thumbnail: thumbnail.as_ref(), caption: tr("Generator"), name }; + slot.paint(ui, rect); + + let tabs = || { + let mut items: Vec> = GeneratorKind::ALL + .into_iter() + .filter(|kind| kind.in_picker()) + .map(|kind| ResourcePickerItem { id: kind, label: tr(kind.label()).to_owned(), caption: None, picture: TilePicture::Generator(kind) }) + .collect(); + + // One kind of resource: one grid in name order, no group captions + items.sort_by_cached_key(|item| item.label.to_lowercase()); + vec![PickerTab { icon: ic::SPARKLE, name: tr("Generators"), groups: vec![PickerGroup { header: None, items }] }] + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, Some(¤t), true, tabs); + if let Some(kind) = picked.filter(|kind| *kind != current) { + app.run("effect.set", json!({"effect": effect, "generator": kind.id()})); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..a8e83fce 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,7 @@ mod folder_properties; pub mod fonts; mod frame_gizmo; mod generator_panel; +mod generator_slot; pub mod gpu; mod gray_slider; mod grid_tile; @@ -124,6 +125,7 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; +mod resource_slot; mod round_gizmo; mod running_bake; pub mod saved_search; diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 7797a7e3..71c925ea 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -19,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the orb on first use for smart masks and smart materials + /// Render the asset, baking the orb on first use for smart masks, generators and smart materials /// Unknown assets and failed bakes return None pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::Generator(kind) => Some(mask_preview_image(self.size_px, &shape.get()?.generator(*kind, self.size_px)?)), ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index e58901b4..57879c71 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -156,6 +156,7 @@ mod tests { use std::collections::HashMap; use std::time::{Duration, Instant}; + use texturecraft_engine::core::GeneratorKind; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -196,6 +197,7 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("generator", ShelfPreview::Generator(GeneratorKind::Dirt)), ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; @@ -217,7 +219,7 @@ mod tests { std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask", "smart material"] { + for key in ["material", "mask", "generator", "smart material"] { let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); assert_eq!(image.size, [size_px, size_px], "{key}"); } diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 311d8049..8c970158 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -45,6 +45,11 @@ const LOADING_GLYPH_SIZE: f32 = 24.0; /// The loading glyph is fainter than the other glyphs: it stands in for a picture still coming const LOADING_GLYPH_OPACITY: f32 = 0.5; const GLYPH_SIZE: f32 = 22.0; +/// The randomness badge: a see-through dark disc at the picture's bottom-right corner holding a die +const BADGE_RADIUS: f32 = 7.0; +const BADGE_ICON_SIZE: f32 = 10.0; +const BADGE_DISC: Color32 = Color32::from_black_alpha(140); +const BADGE_ICON: Color32 = Color32::from_gray(228); /// The bright group header row and the dim sub-caption row const HEADER_HEIGHT: f32 = 24.0; @@ -389,6 +394,7 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz TilePicture::Alpha(alpha) => thumbs.alpha(ui.ctx(), alpha), TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), + TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind), TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, }; @@ -396,7 +402,15 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz (_, Some(texture)) => { egui::Image::from_texture((texture.id(), picture.size())).corner_radius(rounding).paint_at(ui, picture); } - (TilePicture::Material(_) | TilePicture::Filter(_) | TilePicture::Alpha(_) | TilePicture::Image(..) | TilePicture::Procedural(_), None) => { + ( + TilePicture::Material(_) + | TilePicture::Filter(_) + | TilePicture::Alpha(_) + | TilePicture::Image(..) + | TilePicture::Procedural(_) + | TilePicture::Generator(_), + None, + ) => { painter.text( picture.center(), Align2::CENTER_CENTER, @@ -418,11 +432,23 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz painter.text(picture.center(), Align2::CENTER_CENTER, ic::PLUS, FontId::proportional(IMPORT_GLYPH_SIZE), color); } } + if let TilePicture::Generator(kind) = &item.picture + && kind.includes_randomness() + { + randomness_badge(painter, picture); + } name_lines(ui, rect, &item.label, hovered || chosen, chosen); response } +/// A die on a see-through dark disc at `picture`'s bottom-right corner: the item's result depends on a random seed +fn randomness_badge(painter: &egui::Painter, picture: Rect) { + let center = picture.right_bottom() - vec2(BADGE_RADIUS, BADGE_RADIUS); + painter.circle_filled(center, BADGE_RADIUS, BADGE_DISC); + painter.text(center, Align2::CENTER_CENTER, ic::DICE_FIVE, FontId::proportional(BADGE_ICON_SIZE), BADGE_ICON); +} + /// The tile's name under its picture: whole words on the first line, the rest on a second, each cut with "…" when too long fn name_lines(ui: &Ui, rect: Rect, label: &str, bright: bool, bold: bool) { let tokens = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/resource_slot.rs b/crates/ui-egui/src/resource_slot.rs new file mode 100644 index 00000000..e814dd27 --- /dev/null +++ b/crates/ui-egui/src/resource_slot.rs @@ -0,0 +1,68 @@ +//! The box atop an effect's properties that names its resource and opens a picker: thumbnail, a caption over the name, a caret + +use egui::{Align2, FontId, Rect, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; + +use crate::theme::Tokens; +use crate::widgets::elided; + +/// The slot's height in points +pub(crate) const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const BORDER_WIDTH: f32 = 1.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; + +/// What the slot shows and how: highlighted while hovered or its picker is open, outlined while focused +pub(crate) struct ResourceSlot<'a> { + pub highlighted: bool, + pub focused: bool, + pub thumbnail: Option<&'a egui::TextureHandle>, + pub caption: &'a str, + pub name: &'a str, +} + +impl ResourceSlot<'_> { + /// Paints the slot into `rect` + pub(crate) fn paint(&self, ui: &Ui, rect: Rect) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if self.highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); + if self.focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + + if let Some(texture) = self.thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + // Long names are cut short rather than run under the thumbnail or the caret + let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; + let text_right = rect.right() - CARET_INSET * 2.0; + let text_center_x = (text_left + text_right) * 0.5; + let lines = [(self.caption, CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (self.name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + for (text, size, color, offset) in lines { + let galley = elided(painter, text, size, color, text_right - text_left); + painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + } + + let caret_color = if self.highlighted { tk.text } else { tk.text_dim }; + painter.text( + pos2(rect.right() - CARET_INSET, rect.center().y), + Align2::CENTER_CENTER, + ic::CARET_DOWN, + FontId::proportional(CARET_FONT_SIZE), + caret_color, + ); + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 3416a106..bc34317f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,7 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_)); let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 5d06f8e8..20491e3a 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -28,6 +28,8 @@ pub enum ShelfPreview { SmartMaterial(&'static str), /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), + /// A mask generator at its defaults, rendered like a smart mask on the worker's baked orb + Generator(GeneratorKind), /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -72,6 +74,7 @@ impl ShelfPreview { ShelfPreview::Material(id) => format!("mat:{id}"), ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -83,11 +86,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks and smart materials return None here because their bake belongs to the worker + /// Smart masks, generators and smart materials return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 875ac6ae..e847359e 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -9,7 +9,7 @@ use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::Session; use texturecraft_engine::compose::{ImageRes, ImageStore}; -use texturecraft_engine::core::{BakedMap, ProceduralKind}; +use texturecraft_engine::core::{BakedMap, GeneratorKind, ProceduralKind}; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; @@ -295,6 +295,11 @@ impl Thumbs { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } + /// Generator thumbnail on the smart masks' orb; None until the worker returns it + pub fn generator(&mut self, ctx: &egui::Context, kind: GeneratorKind) -> Option { + self.worker_rendered(ctx, ShelfPreview::Generator(kind), SPHERE_PX, false) + } + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs index c3f7dc5b..d031e666 100644 --- a/crates/ui-egui/src/tile_picture.rs +++ b/crates/ui-egui/src/tile_picture.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use egui::Color32; use texturecraft_engine::compose::ImageRes; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; use texturecraft_engine::paint::alphas::LibraryAlpha; /// A tile's picture source. Previews are requested only when its tile is drawn. @@ -14,6 +14,8 @@ pub(crate) enum TilePicture { Alpha(&'static LibraryAlpha), Image(String, Arc), Procedural(ProceduralKind), + /// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result + Generator(GeneratorKind), Swatch(Color32), Glyph(&'static str), Import, diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 796051e8..b256f537 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -83,12 +83,12 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { } #[test] -fn changing_kind_in_the_panel_preserves_the_effect() { +fn picking_a_kind_in_the_panel_is_one_undo_step() { let (mut harness, effect) = harness(false); let history = harness.state().session.history_labels().len(); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Dirt").click(); + harness.get_by_role_and_label(Role::ComboBox, "Curvature").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::ListBoxOption, "Dirt").click(); harness.run_steps(3); assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt); diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs new file mode 100644 index 00000000..d6d31dd8 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -0,0 +1,103 @@ +//! The generator slot in Properties swaps a generator's kind through its picker + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, GeneratorKind, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with a Dirt generator in a fill layer's black mask, selected so Properties shows its slot +fn app_with_dirt() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "Dirt"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of generator effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Option { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => Some(generator.kind), + _ => None, + } +} + +/// Clicks the Dirt slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Dirt").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_generator_kind() { + let (mut harness, effect) = app_with_dirt(); + open_picker(&mut harness); + + harness.event(egui::Event::Text("curv".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Light").count(), 0, "the search hides generators that don't match"); + + harness.get_by_label("Curvature").click(); + harness.run_steps(3); + + assert_eq!(kind(&harness, effect), Some(GeneratorKind::Curvature)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn the_picker_leaves_thin_areas_out() { + let (mut harness, _) = app_with_dirt(); + open_picker(&mut harness); + + for kind in GeneratorKind::ALL { + let offered = harness.query_all_by_label(kind.label()).count() > 0; + assert_eq!(offered, kind.in_picker(), "{kind:?}"); + } +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_picker_snapshots() { + let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&output).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "EdgeWear"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(LayerId(effect["effect"].as_u64().unwrap())); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(20); + harness.get_by_role_and_label(Role::ComboBox, "Metal Edge Wear").click(); + + // The orbs render on the preview worker: give it time to bake and answer + for _ in 0..60 { + harness.run_steps(5); + std::thread::sleep(std::time::Duration::from_millis(500)); + } + for (brightness, name) in + [(texturecraft_ui_egui::theme::Brightness::MediumDark, "generator-picker"), (texturecraft_ui_egui::theme::Brightness::Light, "generator-picker-light")] + { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); + } + + // The Assets shelf may show a Dirt resource too: the picker draws over it, last + harness.query_all_by_label("Dirt").last().expect("the picker offers Dirt").hover(); + for _ in 0..10 { + harness.run_steps(5); + std::thread::sleep(std::time::Duration::from_millis(300)); + } + harness.render().unwrap().save(output.join("generator-picker-hover.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 831a009a..43cf6140 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -39,6 +39,7 @@ mod filter_picker; mod folder_properties; mod frame_selection; mod generator_panel; +mod generator_picker; mod help_menu_664; mod history_panel; mod import_resources; From 606fa3210682a10e3377917f42d7645937cf6449 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 02/54] Generators: Metal Edge Wear, Dirt and Fiber Glass Edge Wear on the reference's wear controls The wear kinds take the reference app's controls (wear level and contrast, grunge amount and scale, triplanar, edges smoothness, ambient occlusion masking, curvature weight, edges masking), computed from curvature, its blurred levels, ambient occlusion and a grunge pattern of our own per kind. Fiber Glass Edge Wear is a new kind. Generators saved before keep their level, softness and noise and render as before; editing a wear control moves one onto the new controls, and level, softness or noise keep an added one on the earlier model. --- crates/compose/src/eval.rs | 80 ++++++-- crates/compose/src/lib.rs | 3 + crates/compose/src/wear.rs | 202 ++++++++++++++++++++ crates/compose/src/wear_inputs.rs | 13 ++ crates/compose/src/wear_scan.rs | 29 +++ crates/core/src/layer.rs | 32 +++- crates/core/src/layer/wear_parameters.rs | 76 ++++++++ crates/core/src/lib.rs | 2 +- crates/engine/src/mask_cmds.rs | 70 ++++++- crates/engine/src/smart_masks.rs | 6 +- crates/engine/tests/it/generator_wear.rs | 69 +++++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/session.rs | 4 +- crates/ui-egui/src/generator_panel.rs | 177 ++++++++++++----- crates/ui-egui/tests/it/effect_sliders.rs | 11 +- crates/ui-egui/tests/it/generator_panel.rs | 44 ++++- crates/ui-egui/tests/it/generator_picker.rs | 7 +- 17 files changed, 740 insertions(+), 86 deletions(-) create mode 100644 crates/compose/src/wear.rs create mode 100644 crates/compose/src/wear_inputs.rs create mode 100644 crates/compose/src/wear_scan.rs create mode 100644 crates/core/src/layer/wear_parameters.rs create mode 100644 crates/engine/tests/it/generator_wear.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3097e768..763af1b9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -16,7 +16,7 @@ use texturecraft_core::{ CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -40,6 +40,8 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; +use crate::wear; +use crate::wear_inputs::WearInputs; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; @@ -2358,12 +2360,24 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } +/// The blurred curvature sizes `generator` reads: its detail sizes and its wear's smoothing +fn curvature_sizes_in_use(generator: &Generator) -> [bool; CurvatureDetail::BLURRED_SIZES] { + let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let wear = wear_parameters(generator).map(|wear| wear::levels_in_use(generator.kind, &wear)).unwrap_or_default(); + std::array::from_fn(|level| detail[level] || wear[level]) +} + +/// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None +fn wear_parameters(generator: &Generator) -> Option { + generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) +} + /// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { - if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { - for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + if let EffectKind::Generator(generator) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { *slot |= in_use; } } @@ -2406,7 +2420,7 @@ fn effect_plans<'a>( None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; let curvature_sizes = match &effect.kind { - EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + EffectKind::Generator(generator) => CurvatureSizes::of(inp, &curvature_sizes_in_use(generator)), _ => None, }; let (depth, covers_all, projection) = match &effect.kind { @@ -3277,6 +3291,10 @@ impl<'a, 'b> Texel<'a, 'b> { } fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + if let Some(wear) = wear_parameters(generator) { + return self.wear_ramp(generator, &wear, curvature_sizes); + } + let coords = self.coords(); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); let signal = match (generator.kind, &generator.detail) { @@ -3286,7 +3304,9 @@ impl<'a, 'b> Texel<'a, 'b> { let curvature = self.generator_input(generator, BakedMap::Curvature); self.curvature_detail(detail, sizes, curvature, micro) } - (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => { + (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0 + } (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), @@ -3323,7 +3343,7 @@ impl<'a, 'b> Texel<'a, 'b> { let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; let response = height.clamp(-1.0, 1.0) * amount; match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::FiberGlassEdgeWear => response, // Dirt gathers in dents; dents are occluded GeneratorKind::Dirt => -response, @@ -3332,6 +3352,41 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); + + // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); + + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); + let grunge = wear::grunge(generator.kind, wear, generator.seed, &self.coords()); + wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) + } + + /// The curvature deviation at this texel blurred to `sigma` (texels at 2K) between the two built levels around it; `curvature` without them + fn blurred_curvature(&self, sigma: f32, curvature_sizes: Option<&CurvatureSizes>, curvature: f32) -> f32 { + let Some((sizes, (baked_x, baked_y))) = curvature_sizes.zip(self.baked_curvature_texel()) else { return curvature }; + + let level = |index: usize| sizes.levels.get(index).and_then(Option::as_deref).map(|level| level.sample(baked_x, baked_y)); + let (narrower, wider, weight) = wear::levels_around(sigma); + let narrower = narrower.map_or(Some(curvature), level); + match (narrower, level(wider)) { + (Some(narrower), Some(wider)) => narrower + (wider - narrower) * weight, + _ => curvature, + } + } + + /// The baked curvature map's texel under this texel (None outside the baked layout) + fn baked_curvature_texel(&self) -> Option<(u32, u32)> { + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = self.inp.block_scales.bake_uv(texel_uv, working_size)?; + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) + } + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); @@ -3362,13 +3417,8 @@ impl<'a, 'b> Texel<'a, 'b> { // Without baked curvature, only painted micro height supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; + let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; - let working_size = (self.res, self.inp.gbuf.height); - let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; - - let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); - let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); let blurred = |index: usize| { curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) }; @@ -5656,7 +5706,7 @@ mod tests { /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). fn ridge_generator() -> Generator { - Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, wear: None, ..Generator::new(GeneratorKind::EdgeWear) } } #[test] @@ -5755,7 +5805,7 @@ mod tests { fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); let value_with = |fixture: &mut Fixture, input: Option| -> f32 { - let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, wear: None, ..Generator::new(GeneratorKind::Dirt) }; if let Some(value) = input { generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); } @@ -5796,7 +5846,7 @@ mod tests { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { for mode in CurvatureMode::ALL { let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), ..Generator::new(kind) }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, ..Generator::new(kind) }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 2f5c0477..6318ea16 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -49,6 +49,9 @@ mod timber; pub mod warp; mod warp_source_sample; mod warp_texel; +mod wear; +mod wear_inputs; +mod wear_scan; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs new file mode 100644 index 00000000..0b075151 --- /dev/null +++ b/crates/compose/src/wear.rs @@ -0,0 +1,202 @@ +//! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results + +use texturecraft_core::{CurvatureDetail, GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; + +use crate::pattern::{Coords, procedural}; + +use crate::wear_inputs::WearInputs; +use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; + +/// The radius of each blurred curvature level, in texels at 2K (the detail sizes after the map itself) +const LEVEL_RADII: [f32; CurvatureDetail::BLURRED_SIZES] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + +/// Gaussian sigma per unit of edges smoothness, in texels at 2K +const EDGE_WEAR_SMOOTHNESS_SIGMA: f32 = 4.6; +const FIBER_GLASS_SMOOTHNESS_SIGMA: f32 = 4.5; +/// The share of the blurred curvature in the smoothed edges +const SMOOTHED_SHARE: f32 = 0.5; +/// Dirt reads its edges and cavities slightly softened, sigma in texels at 2K +const DIRT_CURVATURE_SIGMA: f32 = 1.49; + +/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) +struct GrungePattern { + kind: ProceduralKind, + repeats_per_scale: f32, + rotation: f32, + mean: f32, + spread: f32, +} + +/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt +const EDGE_WEAR_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.037, spread: 0.149 }; +const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, rotation: 45.0, mean: 0.665, spread: 0.21 }; +const DIRT_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.682, spread: 0.242 }; +/// The triplanar seams' sharpness at triplanar contrast 0 and 1 +const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; + +/// The Gaussian sigma (texels at 2K) the kind's blurred curvature is read at +pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { + match kind { + GeneratorKind::Dirt => DIRT_CURVATURE_SIGMA, + GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SMOOTHNESS_SIGMA * wear.edges_smoothness, + _ => EDGE_WEAR_SMOOTHNESS_SIGMA * wear.edges_smoothness, + } +} + +/// The wear's grunge at `coords`, normalised to mean 0 and spread 1 +pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { + let grunge = match kind { + GeneratorKind::Dirt => &DIRT_GRUNGE, + GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, + _ => &EDGE_WEAR_GRUNGE, + }; + let pattern = Procedural { scale: grunge.repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(grunge.kind) }; + let projection = if wear.triplanar { + let sharpness = TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast; + Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] } + } else { + Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } + }; + (procedural(&pattern, &projection, coords) - grunge.mean) / grunge.spread +} + +/// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself +pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { + // Three box blurs of radius r spread like a Gaussian of sigma √(r(r+1)) + let sigmas = LEVEL_RADII.map(|radius| (radius * (radius + 1.0)).sqrt()); + let wider = sigmas.iter().position(|level| *level >= sigma).unwrap_or(sigmas.len() - 1); + let (narrower, narrower_sigma) = match wider.checked_sub(1) { + Some(level) => (Some(level), sigmas[level]), + None => (None, 0.0), + }; + let span = sigmas[wider] - narrower_sigma; + let weight = if span > 0.0 { ((sigma - narrower_sigma) / span).clamp(0.0, 1.0) } else { 1.0 }; + (narrower, wider, weight) +} + +/// Which blurred curvature levels a wear generator reads +pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; CurvatureDetail::BLURRED_SIZES] { + let (narrower, wider, _) = levels_around(blur_sigma(kind, wear)); + std::array::from_fn(|level| level == wider || Some(level) == narrower) +} + +/// The wear value (0..1) of `kind` at a texel +pub(crate) fn wear_value(kind: GeneratorKind, wear: &WearParameters, inputs: &WearInputs) -> f32 { + match kind { + GeneratorKind::Dirt => DIRT_SCAN.apply(dirt_signal(wear, inputs), wear), + GeneratorKind::FiberGlassEdgeWear => FIBER_GLASS_SCAN.apply(fiber_glass_signal(wear, inputs), wear), + _ => EDGE_WEAR_SCAN.apply(edge_wear_signal(wear, inputs), wear), + } +} + +/// Edges sharp and smoothed in equal parts +fn smoothed_edges(inputs: &WearInputs) -> f32 { + (1.0 - SMOOTHED_SHARE) * inputs.curvature + SMOOTHED_SHARE * inputs.blurred_curvature +} + +/// 1 where the area is open enough to wear, 0 where occluded: the cut-off sits at `offset + gain × masking`, softened over `width` +fn open_area(occlusion: f32, masking: f32, (offset, gain, width): (f32, f32, f32)) -> f32 { + ((occlusion - (offset + gain * masking)) / width + 0.5).clamp(0.0, 1.0) +} + +// The signals' coefficients are fitted to the reference app's sweeps on a hard-surface bake +fn edge_wear_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + let edges = smoothed_edges(inputs) * wear.curvature_weight; + let open = open_area(inputs.occlusion, wear.ao_masking, (-0.779, 2.244, 0.935)); + let grunge = wear.grunge_amount; + edges * open * (1.0 + 0.031 * grunge) - 0.009 * grunge + 0.057 * grunge.powf(0.731) * inputs.grunge +} + +fn fiber_glass_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + // The grunge takes over from the edges as it grows + let edges = smoothed_edges(inputs) * wear.curvature_weight * 1.02; + let open = open_area(inputs.occlusion, wear.ao_masking, (0.144, 0.726, 0.669)); + let grunge = wear.grunge_amount; + (edges * (1.0 - 0.989 * grunge) + 0.167 * grunge + 0.094 * grunge.powf(1.64) * inputs.grunge) * open +} + +fn dirt_signal(wear: &WearParameters, inputs: &WearInputs) -> f32 { + let edges = inputs.blurred_curvature; + let grunge = wear.grunge_amount; + 0.486 * (0.869 - inputs.occlusion) - wear.edges_masking * 0.817 * edges.max(0.0) + + 0.203 * (-edges).max(0.0) + + 0.241 * grunge + + 0.0895 * grunge * inputs.grunge +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::{Vec2, Vec3}; + + use super::*; + + fn inputs(curvature: f32, occlusion: f32) -> WearInputs { + WearInputs { curvature, blurred_curvature: curvature, occlusion, grunge: 0.0 } + } + + fn defaults(kind: GeneratorKind) -> WearParameters { + WearParameters { grunge_amount: 0.0, ..WearParameters::defaults(kind).unwrap() } + } + + #[test] + fn edge_wear_shows_on_open_convex_edges_only() { + for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear] { + let wear = WearParameters { curvature_weight: 1.0, ..defaults(kind) }; + let value = |curvature, occlusion| wear_value(kind, &wear, &inputs(curvature, occlusion)); + assert!(value(0.4, 1.0) > 0.9, "{kind:?}: a sharp open edge wears"); + assert!(value(0.0, 1.0) < 0.1, "{kind:?}: a flat face does not"); + assert!(value(-0.4, 1.0) < 0.1, "{kind:?}: nor a cavity"); + assert!(value(0.4, 0.0) < value(0.4, 1.0), "{kind:?}: occlusion masks the wear"); + } + } + + #[test] + fn dirt_gathers_in_occluded_cavities_and_spares_edges() { + let wear = defaults(GeneratorKind::Dirt); + let value = |curvature, occlusion| wear_value(GeneratorKind::Dirt, &wear, &inputs(curvature, occlusion)); + assert!(value(-0.3, 0.2) > value(0.0, 1.0), "occluded cavities collect dirt"); + assert!(value(0.3, 0.6) < value(0.0, 0.6), "edges are masked"); + } + + #[test] + fn a_higher_level_spreads_the_wear_and_a_full_level_is_a_hard_step() { + let low = WearParameters { level: 0.25, ..defaults(GeneratorKind::EdgeWear) }; + let high = WearParameters { level: 0.9, ..low }; + let mild = inputs(0.1, 1.0); + assert!(wear_value(GeneratorKind::EdgeWear, &high, &mild) > wear_value(GeneratorKind::EdgeWear, &low, &mild)); + + let full = WearParameters { level: 1.0, ..low }; + for curvature in [-0.5, 0.0, 0.05, 0.5] { + let value = wear_value(GeneratorKind::EdgeWear, &full, &inputs(curvature, 1.0)); + assert!(value == 0.0 || value == 1.0, "{curvature}: {value}"); + } + } + + #[test] + fn grunge_is_normalised() { + for (kind, pattern) in + [(GeneratorKind::EdgeWear, &EDGE_WEAR_GRUNGE), (GeneratorKind::FiberGlassEdgeWear, &FIBER_GLASS_GRUNGE), (GeneratorKind::Dirt, &DIRT_GRUNGE)] + { + let wear = WearParameters::defaults(kind).unwrap(); + let samples: Vec = (0..256 * 256) + .map(|texel| { + let uv = Vec2::new((texel % 256) as f32 / 256.0, (texel / 256) as f32 / 256.0); + grunge(kind, &wear, 7, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z }) + }) + .collect(); + let mean = samples.iter().sum::() / samples.len() as f32; + let spread = (samples.iter().map(|value| (value - mean).powi(2)).sum::() / samples.len() as f32).sqrt(); + let measured = (pattern.mean + mean * pattern.spread, spread * pattern.spread); + assert!(mean.abs() < 0.1 && (spread - 1.0).abs() < 0.1, "{kind:?}: normalised mean {mean}, spread {spread}; the pattern's own {measured:?}"); + } + } + + #[test] + fn the_blurred_levels_around_a_sigma_bracket_it() { + assert_eq!(levels_around(0.5).0, None, "below the first level the map itself is the narrower one"); + let (narrower, wider, weight) = levels_around(4.6); + assert_eq!((narrower, wider), (Some(2), 3)); + assert!((0.0..=0.1).contains(&weight), "4.6 sits just past radius 4's sigma: {weight}"); + assert_eq!(levels_around(500.0).1, LEVEL_RADII.len() - 1, "wider than every level reads the widest"); + } +} diff --git a/crates/compose/src/wear_inputs.rs b/crates/compose/src/wear_inputs.rs new file mode 100644 index 00000000..e9f83c42 --- /dev/null +++ b/crates/compose/src/wear_inputs.rs @@ -0,0 +1,13 @@ +//! What a wear generator reads at a texel + +/// What a wear generator reads at a texel +pub(crate) struct WearInputs { + /// The curvature map minus its flat 0.5 (above 0 convex, below 0 concave) + pub curvature: f32, + /// The curvature deviation blurred to the sigma the kind asks for ([`crate::wear::blur_sigma`]) + pub blurred_curvature: f32, + /// Ambient occlusion (1 open, 0 occluded) + pub occlusion: f32, + /// The grunge pattern normalised to mean 0 and spread 1 + pub grunge: f32, +} diff --git a/crates/compose/src/wear_scan.rs b/crates/compose/src/wear_scan.rs new file mode 100644 index 00000000..ceac28b9 --- /dev/null +++ b/crates/compose/src/wear_scan.rs @@ -0,0 +1,29 @@ +//! How a wear generator's level and contrast turn its signal into the mask (constants fitted to the reference app's sweeps) + +use texturecraft_core::WearParameters; + +/// Where a kind's level slides its edge and how wide the edge is +pub(crate) struct WearScan { + /// The edge at level 0, falling towards `floor` as the level rises + pub travel: f32, + pub floor: f32, + /// The edge's width at contrast 0, narrowed by (1 − contrast) to the power `narrowing` + pub width: f32, + pub narrowing: f32, +} + +pub(crate) const EDGE_WEAR_SCAN: WearScan = WearScan { travel: 0.284, floor: -0.009, width: 0.504, narrowing: 0.95 }; +pub(crate) const FIBER_GLASS_SCAN: WearScan = WearScan { travel: 0.162, floor: 0.029, width: 0.358, narrowing: 0.872 }; +pub(crate) const DIRT_SCAN: WearScan = WearScan { travel: 0.593, floor: -0.088, width: 1.386, narrowing: 1.42 }; + +/// The narrowest edge, so a level or contrast of 1 is a hard step rather than a division by zero +const MIN_EDGE_WIDTH: f32 = 1e-4; + +impl WearScan { + /// `signal` through the level and contrast: the level brings the edge down and narrows it, the contrast narrows it further + pub(crate) fn apply(&self, signal: f32, wear: &WearParameters) -> f32 { + let remaining = (1.0 - wear.level).max(0.0); + let width = (remaining * self.width * (1.0 - wear.contrast).max(0.0).powf(self.narrowing)).max(MIN_EDGE_WIDTH); + ((signal - self.floor - remaining * self.travel) / width + 0.5).clamp(0.0, 1.0) + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index b3186d4d..6f218f1f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -31,6 +31,7 @@ mod tile_size_mode; mod tile_symmetry; mod uv_transform; mod uv_wrap; +mod wear_parameters; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; @@ -51,6 +52,7 @@ pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; +pub use wear_parameters::WearParameters; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -926,10 +928,12 @@ pub enum GeneratorKind { Position, /// Surfaces facing a direction (e.g. up for dust). Direction, + /// Worn edges of a fibreglass-like coating: the edges fade into its grunge + FiberGlassEdgeWear, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 7] = [ + pub const ALL: [GeneratorKind; 8] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -937,6 +941,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction, + GeneratorKind::FiberGlassEdgeWear, ]; pub fn label(self) -> &'static str { match self { @@ -947,6 +952,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion => "Ambient Occlusion", GeneratorKind::Position => "Position", GeneratorKind::Direction => "Light", + GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", } } @@ -960,6 +966,7 @@ impl GeneratorKind { GeneratorKind::AmbientOcclusion => "AmbientOcclusion", GeneratorKind::Position => "Position", GeneratorKind::Direction => "Direction", + GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", } } @@ -970,14 +977,15 @@ impl GeneratorKind { /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt) + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. pub fn inputs(self) -> &'static [BakedMap] { match self { - GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], - GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => &[BakedMap::Curvature, BakedMap::AmbientOcclusion], + GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], GeneratorKind::Position | GeneratorKind::Direction => &[], } @@ -1021,6 +1029,9 @@ pub struct Generator { /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option, + /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wear: Option, } impl Generator { @@ -1059,6 +1070,7 @@ impl Generator { resolution: OutputResolution::default(), inputs: BTreeMap::new(), micro: None, + wear: WearParameters::defaults(kind), } } @@ -2278,6 +2290,18 @@ mod tests { assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); } + #[test] + fn wear_generators_saved_before_their_wear_controls_load_on_the_earlier_model() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::EdgeWear)).unwrap(); + assert!(saved.get("wear").is_some(), "new wear generators have wear controls"); + + saved.as_object_mut().unwrap().remove("wear"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.wear, None, "level, softness and noise keep driving it"); + let curvature = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(curvature.get("wear").is_none(), "other kinds save no wear controls"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs new file mode 100644 index 00000000..b0c2de19 --- /dev/null +++ b/crates/core/src/layer/wear_parameters.rs @@ -0,0 +1,76 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; + +/// The controls of the wear generators (Metal Edge Wear, Fiber Glass Edge Wear, Dirt) as the reference app lays them out; each kind reads its own +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WearParameters { + /// How far the wear spreads (0..1) + pub level: f32, + /// How hard the wear's edge is (0 soft, 1 a hard step) + pub contrast: f32, + /// How much the grunge breaks the wear up (0..1) + pub grunge_amount: f32, + /// The grunge's size: repeats across the UV square ([`WearParameters::GRUNGE_SCALE_RANGE`]) + pub grunge_scale: f32, + /// The grunge projected from the world's three axes rather than laid out in UV + pub triplanar: bool, + /// How sharply the three projections meet (0..1) + pub triplanar_contrast: f32, + /// How far the worn edges spread over rounded edges ([`WearParameters::EDGES_SMOOTHNESS_RANGE`]; edge wear kinds) + pub edges_smoothness: f32, + /// How much occluded areas are kept clean (0..1; edge wear kinds) + pub ao_masking: f32, + /// How much the edges count against the grunge (0..1; edge wear kinds) + pub curvature_weight: f32, + /// How much convex edges are kept clean (0..1; Dirt) + pub edges_masking: f32, +} + +impl WearParameters { + pub const GRUNGE_SCALE_RANGE: std::ops::RangeInclusive = 1.0..=16.0; + pub const EDGES_SMOOTHNESS_RANGE: std::ops::RangeInclusive = 0.0..=16.0; + + /// The reference app's defaults for `kind`, or None for kinds without wear controls + pub fn defaults(kind: GeneratorKind) -> Option { + let shared = WearParameters { + level: 0.75, + contrast: 0.5, + grunge_amount: 0.3, + grunge_scale: 4.0, + triplanar: false, + triplanar_contrast: 0.5, + edges_smoothness: 1.0, + ao_masking: 0.5, + curvature_weight: 1.0, + edges_masking: 0.5, + }; + match kind { + GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), + GeneratorKind::FiberGlassEdgeWear => Some(WearParameters { curvature_weight: 0.25, ..shared }), + GeneratorKind::ThinAreas | GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction => None, + } + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> WearParameters { + let defaults = WearParameters::defaults(kind).unwrap_or(self); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + let within = |value: f32, default: f32, range: &std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + WearParameters { + level: unit(self.level, defaults.level), + contrast: unit(self.contrast, defaults.contrast), + grunge_amount: unit(self.grunge_amount, defaults.grunge_amount), + grunge_scale: within(self.grunge_scale, defaults.grunge_scale, &WearParameters::GRUNGE_SCALE_RANGE), + triplanar: self.triplanar, + triplanar_contrast: unit(self.triplanar_contrast, defaults.triplanar_contrast), + edges_smoothness: within(self.edges_smoothness, defaults.edges_smoothness, &WearParameters::EDGES_SMOOTHNESS_RANGE), + ao_masking: unit(self.ao_masking, defaults.ao_masking), + curvature_weight: unit(self.curvature_weight, defaults.curvature_weight), + edges_masking: unit(self.edges_masking, defaults.edges_masking), + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..b494aa57 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -114,7 +114,7 @@ pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, + Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 8cf8deef..e7ee6cce 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::{ BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, + GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), level?, softness?, noise?, offset?: -1..1 added to the result (instead keep edgeWear and dirt on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -388,7 +388,71 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { } /// Apply `params` to `generator`, using `command` in errors +/// The parameters that drive the wear generators' earlier model +const EARLIER_WEAR_KEYS: [&str; 5] = ["level", "softness", "noise", "noiseScale", "offset"]; + +/// The wear controls `effect.add.generator` and `effect.set` take +const WEAR_KEYS: [&str; 10] = [ + "wearLevel", + "wearContrast", + "grungeAmount", + "grungeScale", + "triplanar", + "triplanarContrast", + "edgesSmoothness", + "aoMasking", + "curvatureWeight", + "edgesMasking", +]; + +/// The wear controls in `params`: they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model +fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let Some(defaults) = WearParameters::defaults(generator.kind) else { + return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; + }; + + if given(&EARLIER_WEAR_KEYS) { + if given(&WEAR_KEYS) { + return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); + } + if generator.kind == GeneratorKind::FiberGlassEdgeWear { + return Err(bad(command, "Fiber Glass Edge Wear has wear controls only (wearLevel, wearContrast…), no level, softness, noise or offset")); + } + generator.wear = None; + return Ok(()); + } + if !given(&WEAR_KEYS) { + return Ok(()); + } + + // The offset belongs to the earlier model: kept, it would shift the wear controls' result unseen + generator.offset = 0.0; + let wear = generator.wear.get_or_insert(defaults); + for (key, value) in [ + ("wearLevel", &mut wear.level), + ("wearContrast", &mut wear.contrast), + ("grungeAmount", &mut wear.grunge_amount), + ("grungeScale", &mut wear.grunge_scale), + ("triplanarContrast", &mut wear.triplanar_contrast), + ("edgesSmoothness", &mut wear.edges_smoothness), + ("aoMasking", &mut wear.ao_masking), + ("curvatureWeight", &mut wear.curvature_weight), + ("edgesMasking", &mut wear.edges_masking), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(triplanar) = boolp(params, "triplanar") { + wear.triplanar = triplanar; + } + *wear = wear.clamped(generator.kind); + Ok(()) +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + wear_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 8c7a2791..244c412e 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,14 +79,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes). +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or wear controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, wear: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs new file mode 100644 index 00000000..cd49c378 --- /dev/null +++ b/crates/engine/tests/it/generator_wear.rs @@ -0,0 +1,69 @@ +//! The wear generators' controls through `effect.add.generator` and `effect.set`, beside their earlier level, softness and noise + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, GeneratorKind, LayerId, WearParameters}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn new_wear_generators_start_from_the_reference_defaults() { + let mut session = session(); + for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert_eq!(added.wear, WearParameters::defaults(added.kind), "{kind}"); + } +} + +#[test] +fn level_softness_or_noise_keep_a_generator_on_the_earlier_model() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "level": 0.4})); + assert_eq!(generator(&session, effect).wear, None, "agents' earlier parameters still drive it"); + assert_eq!(generator(&session, effect).level, 0.4); +} + +#[test] +fn a_wear_control_moves_an_earlier_generator_onto_the_defaults_with_that_change() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "dirt", "softness": 0.3})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "wearLevel": 0.6, "grungeScale": 99.0})).unwrap(); + + let wear = generator(&session, effect).wear.expect("on the wear controls now"); + let defaults = WearParameters::defaults(GeneratorKind::Dirt).unwrap(); + assert_eq!( + wear, + WearParameters { level: 0.6, grunge_scale: *WearParameters::GRUNGE_SCALE_RANGE.end(), ..defaults }, + "the rest at defaults, values clamped" + ); +} + +#[test] +fn mixing_the_models_or_wear_controls_on_other_kinds_is_refused() { + let mut session = session(); + let edge_wear = add(&mut session, json!({"generator": "edgeWear"})); + let curvature = add(&mut session, json!({"generator": "curvature"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "level": 0.5, "wearLevel": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "wearLevel": 0.5})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"generator": "fiberGlassEdgeWear", "level": 0.5})).is_err()); + assert_eq!(generator(&session, edge_wear).wear, WearParameters::defaults(GeneratorKind::EdgeWear), "a refused edit changes nothing"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index bd56a597..b3a87d44 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod folder_contents; mod frame_selection; mod generator_inputs; mod generator_swap; +mod generator_wear; mod gradient_map; mod high_poly_missed; mod instances; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index dd4972cf..3bbeafe9 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -960,8 +960,8 @@ fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); - let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); - assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "thickness", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion and curvature, not thickness"); let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); assert!(missing_image.is_err(), "the image must be a resource of the project"); let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 47bf6aa1..382a76df 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,7 +4,7 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, + BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, WearParameters, }; use crate::TextureCraftApp; @@ -19,6 +19,9 @@ const INPUT_TILE_SIZE: f32 = 32.0; const INPUT_TILE_ROUNDING: f32 = 2.0; const INPUT_TILE_ICON_SIZE: f32 = 16.0; +/// Width of a False/True button, so the buttons line up under each other +const TOGGLE_WIDTH: f32 = 136.0; + /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -27,10 +30,15 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); section(ui, "generator_parameters", tr("Parameters"), true, |ui| { - global_adjustments(app, ui, id, generator); - ramp_parameters(app, ui, id, generator); - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + if let Some(defaults) = WearParameters::defaults(generator.kind) { + // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them + wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); + } else { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if generator.kind == GeneratorKind::Curvature { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { micro_detail_properties(app, ui, id, generator.micro, layer); @@ -87,24 +95,14 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); let (description, tags) = match kind { - GeneratorKind::EdgeWear => ( - tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], - ), - GeneratorKind::Dirt => ( - tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], - ), - GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), - GeneratorKind::Curvature => ( - tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), - [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], - ), - GeneratorKind::AmbientOcclusion => { - (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) - } - GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), - GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::EdgeWear => (tr("Worn metal edges, scratched."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::FiberGlassEdgeWear => (tr("Worn fibreglass edges."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::Dirt => (tr("Grime in cavities."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => (tr("Convex edges and cavities."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), + GeneratorKind::AmbientOcclusion => (tr("Occluded areas."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), + GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), }; // Wrapped rows: a long line must not widen the panel past its edge @@ -183,6 +181,73 @@ fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator } } +/// The wear controls of generator effect `id` in the reference app's order, showing `wear` +fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, wear: WearParameters) { + seed_row(app, ui, id, generator.seed); + let mut invert = generator.invert; + if true_false(ui, tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let dirt = generator.kind == GeneratorKind::Dirt; + let (level_label, contrast_label) = if dirt { (tr("Dirt level"), tr("Dirt contrast")) } else { (tr("Wear level"), tr("Wear contrast")) }; + let mut edited = wear; + let mut edit = slider_edit(ui, level_label, &mut edited.level, 0.0..=1.0, 2); + edit = edit.or(slider_edit(ui, contrast_label, &mut edited.contrast, 0.0..=1.0, 2)); + let triplanar_edit = true_false(ui, tr("Use triplanar"), &mut edited.triplanar).then_some(false); + edit = edit.or(triplanar_edit).or(slider_edit(ui, tr("Triplanar blending contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Grunge amount"), &mut edited.grunge_amount, 0.0..=1.0, 2)); + if generator.kind != GeneratorKind::FiberGlassEdgeWear { + edit = edit.or(slider_edit(ui, tr("Grunge scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); + } + if dirt { + edit = edit.or(slider_edit(ui, tr("Edges masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); + } else { + edit = edit.or(slider_edit(ui, tr("Edges smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Ambient occlusion masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Curvature weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); + } + + if let Some(merge) = edit { + let mut params = wear_params(&edited); + params["effect"] = json!(id); + params["merge"] = json!(merge); + app.run("effect.set", params); + } +} + +/// The `effect.set` params that set every wear control to `wear` +fn wear_params(wear: &WearParameters) -> Value { + json!({ + "wearLevel": wear.level, + "wearContrast": wear.contrast, + "grungeAmount": wear.grunge_amount, + "grungeScale": wear.grunge_scale, + "triplanar": wear.triplanar, + "triplanarContrast": wear.triplanar_contrast, + "edgesSmoothness": wear.edges_smoothness, + "aoMasking": wear.ao_masking, + "curvatureWeight": wear.curvature_weight, + "edgesMasking": wear.edges_masking, + }) +} + +/// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked +fn true_false(ui: &mut Ui, label: &str, value: &mut bool) -> bool { + let mut clicked = false; + ui.horizontal(|ui| { + ui.label(label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let text = if *value { tr("True") } else { tr("False") }; + if ui.add_sized([TOGGLE_WIDTH, ui.spacing().interact_size.y], egui::Button::new(text)).clicked() { + *value = !*value; + clicked = true; + } + }); + }); + clicked +} + /// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = @@ -230,13 +295,19 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - let mut params = json!({ + // A wear generator restores its wear controls; level, softness, noise and offset would keep it on the earlier model + let mut params = match &defaults.wear { + Some(wear) => wear_params(wear), + None => json!({ + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + }), + }; + let shared = json!({ "effect": id, - "level": defaults.level, - "softness": defaults.softness, - "noise": defaults.noise_amount, - "noiseScale": defaults.noise_scale, - "offset": defaults.offset, "seed": defaults.seed, "direction": defaults.direction, "invert": defaults.invert, @@ -248,6 +319,9 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "resolutionFactor": defaults.resolution.factor, "microAnchor": null, }); + if let (Some(params), Value::Object(shared)) = (params.as_object_mut(), shared) { + params.extend(shared); + } if let Some(detail) = defaults.detail { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); @@ -315,28 +389,31 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } }); }); - combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(&app.session.doc.project, layer); - if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); - } - for (anchor, label) in &anchors { - if ui - .selectable_label( - matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), - trf("Anchor: {name}", &[("name", label)]), - ) - .clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + // Each input's menu needs its own id: the dropdown's id comes from its label + ui.push_id(input, |ui| { + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(&app.session.doc.project, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }) }); if let Some(Source::Uniform(value)) = source { let mut value = value[0]; diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index cf141d3b..30e53995 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -4,10 +4,10 @@ use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{Queryable, by}; use serde_json::json; -use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_engine::core::{EffectKind, LayerId, WearParameters}; use texturecraft_ui_egui::TextureCraftApp; -/// The sample session with its first generator effect selected, and that effect's id +/// The sample session with its first generator other than a wear one selected, and that effect's id fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session @@ -17,7 +17,12 @@ fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { .values() .find_map(|layer| { let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()); - layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.id)) + layer + .content_effects + .iter() + .chain(mask_effects) + .find(|effect| matches!(&effect.kind, EffectKind::Generator(generator) if WearParameters::defaults(generator.kind).is_none())) + .map(|effect| (layer.id, effect.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index b256f537..b53f5012 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source}; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -12,12 +12,17 @@ use texturecraft_ui_egui::theme::Brightness; /// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + harness_with(render, json!({"generator": "curvature"})) +} + +/// The sample session with a fill layer whose black mask holds the generator `added` describes, selected in the properties panel +fn harness_with(render: bool, added: serde_json::Value) -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); session.active_set = 1; session.camera.pitch = 0.5; let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); execute(&mut session, "mask.add.black", &json!({})).unwrap(); - let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + let effect = execute(&mut session, "effect.add.generator", &added).unwrap()["effect"].as_u64().unwrap(); session.view = ViewMode::Mask(LayerId(layer)); session.update(); let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); @@ -95,6 +100,29 @@ fn picking_a_kind_in_the_panel_is_one_undo_step() { assert_eq!(harness.state().session.history_labels().len(), history + 1); } +#[test] +fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear", "level": 0.4})); + assert_eq!(generator(&harness, effect).wear, None, "level keeps it on the earlier model"); + + drag_slider(&mut harness, "Wear level"); + + let wear = generator(&harness, effect).wear.expect("on the wear controls now"); + let defaults = WearParameters::defaults(GeneratorKind::EdgeWear).unwrap(); + assert_ne!(wear.level, defaults.level, "the drag set the level"); + assert_eq!(WearParameters { level: defaults.level, ..wear }, defaults, "the other controls start at their defaults"); +} + +#[test] +fn restore_defaults_keeps_a_wear_generator_on_its_wear_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "dirt", "grungeAmount": 0.9, "seed": 3})); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Dirt)); +} + #[test] fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { let (mut harness, effect) = harness(false); @@ -145,3 +173,15 @@ fn generator_panel_snapshots() { harness.run_steps(12); harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn wear_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind})); + harness.run_steps(12); + harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); + } +} diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index d6d31dd8..c68ebf26 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -47,7 +47,8 @@ fn picking_from_the_slot_swaps_the_generator_kind() { harness.run_steps(3); assert_eq!(harness.query_all_by_label("Light").count(), 0, "the search hides generators that don't match"); - harness.get_by_label("Curvature").click(); + // The panel's Curvature input shares the name as a label; the picker's tile is a list option + harness.get_by_role_and_label(Role::ListBoxOption, "Curvature").click(); harness.run_steps(3); assert_eq!(kind(&harness, effect), Some(GeneratorKind::Curvature)); @@ -93,8 +94,8 @@ fn generator_picker_snapshots() { harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); } - // The Assets shelf may show a Dirt resource too: the picker draws over it, last - harness.query_all_by_label("Dirt").last().expect("the picker offers Dirt").hover(); + // The picker's tile is the button named Dirt + harness.get_by_role_and_label(Role::Button, "Dirt").hover(); for _ in 0..10 { harness.run_steps(5); std::thread::sleep(std::time::Duration::from_millis(300)); From fdd2d72b7c04ffee5ef1db30c88bb7732331cc0e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 03/54] Fiber Glass Edge Wear: its seed breaks the woven grunge up differently The weave the fibreglass grunge uses has no seed, so changing the seed changed nothing. A seeded grunge now varies the weave's strength, and a test checks every wear kind's grunge changes with the seed. --- crates/compose/src/wear.rs | 45 ++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 0b075151..1e737deb 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -23,14 +23,28 @@ struct GrungePattern { kind: ProceduralKind, repeats_per_scale: f32, rotation: f32, + /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change + breakup: Option<(ProceduralKind, f32)>, mean: f32, spread: f32, } /// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt -const EDGE_WEAR_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.037, spread: 0.149 }; -const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, rotation: 45.0, mean: 0.665, spread: 0.21 }; -const DIRT_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, mean: 0.682, spread: 0.242 }; +const EDGE_WEAR_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149 }; +const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { + kind: ProceduralKind::Weave, + repeats_per_scale: 16.0, + rotation: 45.0, + breakup: Some((ProceduralKind::Grunge, 4.0)), + mean: 0.539, + spread: 0.198, +}; +const DIRT_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242 }; +/// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) +const BREAKUP_DEPTH: f32 = 0.6; + /// The triplanar seams' sharpness at triplanar contrast 0 and 1 const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; @@ -57,7 +71,12 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor } else { Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } }; - (procedural(&pattern, &projection, coords) - grunge.mean) / grunge.spread + let mut value = procedural(&pattern, &projection, coords); + if let Some((breakup, repeats_per_scale)) = grunge.breakup { + let breakup = Procedural { scale: repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(breakup) }; + value *= 1.0 - BREAKUP_DEPTH + BREAKUP_DEPTH * procedural(&breakup, &projection, coords); + } + (value - grunge.mean) / grunge.spread } /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself @@ -191,6 +210,24 @@ mod tests { } } + #[test] + fn every_kind_s_grunge_changes_with_the_seed() { + for kind in [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt] { + let wear = WearParameters::defaults(kind).unwrap(); + let sample = |seed| -> Vec { + (0..64 * 64) + .map(|texel| { + let uv = Vec2::new((texel % 64) as f32 / 64.0, (texel / 64) as f32 / 64.0); + grunge(kind, &wear, seed, &Coords { uv, pos: uv.extend(0.0), nrm: Vec3::Z }) + }) + .collect() + }; + let (first, second) = (sample(1), sample(2)); + let difference = first.iter().zip(&second).map(|(a, b)| (a - b).abs()).sum::() / first.len() as f32; + assert!(difference > 0.2, "{kind:?}: another seed barely changes the grunge ({difference})"); + } + } + #[test] fn the_blurred_levels_around_a_sigma_bracket_it() { assert_eq!(levels_around(0.5).0, None, "below the first level the map itself is the narrower one"); From 4d00158fdb390e6f339d5eb5e79146b5cda93719 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 04/54] Wear generators: no dead controls Edges smoothness reached the widest blurred curvature level at about 7 of 16, so the rest of the slider changed nothing: two wider levels cover the whole range. Ambient occlusion masking below 0.14 masked nothing on Metal Edge Wear. Mode and sizes on a new Metal Edge Wear and global blur, balance or contrast on the wear controls were accepted and ignored; they now keep the earlier model or are refused, as are wear controls a kind doesn't have. Only the blurred levels a generator reads are built. The labels before the reference's names parse again. --- crates/compose/src/curvature_sizes.rs | 17 +++++-- crates/compose/src/eval.rs | 26 ++++++---- crates/compose/src/wear.rs | 49 +++++++++++++++---- crates/core/src/layer.rs | 17 ++++++- crates/engine/src/mask_cmds.rs | 23 ++++++++- crates/engine/tests/it/generator_wear.rs | 24 ++++++++++ crates/engine/tests/session.rs | 2 +- crates/ui-egui/src/generator_panel.rs | 53 +++++++++++---------- crates/ui-egui/tests/it/generator_picker.rs | 3 +- 9 files changed, 164 insertions(+), 50 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 0b7138bc..95525331 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -4,13 +4,16 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_core::{BakedMap, BlockScales}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; -/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +/// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches +pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; + +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`]. pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, @@ -70,9 +73,8 @@ impl CurvatureSizes { padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); - let levels = CurvatureDetail::SIZES + let levels = LEVEL_RADII .iter() - .skip(1) .enumerate() .map(|(level, size)| { if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { @@ -247,6 +249,8 @@ fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u3 #[cfg(test)] mod tests { + use texturecraft_core::CurvatureDetail; + use super::*; #[test] @@ -473,4 +477,9 @@ mod tests { } } } + + #[test] + fn the_first_levels_are_the_detail_sizes() { + assert_eq!(LEVEL_RADII[..CurvatureDetail::BLURRED_SIZES], CurvatureDetail::SIZES[1..]); + } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 763af1b9..933f9852 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -24,7 +24,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; -use crate::curvature_sizes::CurvatureSizes; +use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; @@ -508,8 +508,8 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.applied_global().blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1953,7 +1953,7 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + let blur_radius = generator.applied_global().blur_radius_at(uv_tile).round() as usize; if blur_radius > 0 { let mut weights = cover.to_vec(); blur(&mut weights, columns, rows, blur_radius); @@ -2039,7 +2039,7 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, /// A generator's (possibly blurred) ramp after balance, contrast, invert and offset fn finish_generator(generator: &Generator, ramp: f32) -> f32 { - let value = generator.global.apply(ramp); + let value = generator.applied_global().apply(ramp); let value = if generator.invert { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) @@ -2360,11 +2360,17 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } -/// The blurred curvature sizes `generator` reads: its detail sizes and its wear's smoothing -fn curvature_sizes_in_use(generator: &Generator) -> [bool; CurvatureDetail::BLURRED_SIZES] { +/// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) +fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { + if generator.inputs.contains_key(&BakedMap::Curvature) { + return [false; LEVEL_RADII.len()]; + } + if let Some(wear) = wear_parameters(generator) { + return wear::levels_in_use(generator.kind, &wear); + } + let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); - let wear = wear_parameters(generator).map(|wear| wear::levels_in_use(generator.kind, &wear)).unwrap_or_default(); - std::array::from_fn(|level| detail[level] || wear[level]) + std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None @@ -2374,7 +2380,7 @@ fn wear_parameters(generator: &Generator) -> Option { /// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind { for (slot, in_use) in needed.iter_mut().zip(curvature_sizes_in_use(generator)) { diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 1e737deb..b766f3e1 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -1,14 +1,16 @@ //! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results -use texturecraft_core::{CurvatureDetail, GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; +use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; + +use crate::curvature_sizes::LEVEL_RADII; use crate::pattern::{Coords, procedural}; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; -/// The radius of each blurred curvature level, in texels at 2K (the detail sizes after the map itself) -const LEVEL_RADII: [f32; CurvatureDetail::BLURRED_SIZES] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; +/// The Gaussian sigma each blurred curvature level spreads like: three box blurs of radius r spread √(r(r+1)), radii from [`LEVEL_RADII`] +const LEVEL_SIGMAS: [f32; LEVEL_RADII.len()] = [1.414, 2.449, 4.472, 8.485, 16.492, 32.496, 64.498, 128.499]; /// Gaussian sigma per unit of edges smoothness, in texels at 2K const EDGE_WEAR_SMOOTHNESS_SIGMA: f32 = 4.6; @@ -81,8 +83,7 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { - // Three box blurs of radius r spread like a Gaussian of sigma √(r(r+1)) - let sigmas = LEVEL_RADII.map(|radius| (radius * (radius + 1.0)).sqrt()); + let sigmas = LEVEL_SIGMAS; let wider = sigmas.iter().position(|level| *level >= sigma).unwrap_or(sigmas.len() - 1); let (narrower, narrower_sigma) = match wider.checked_sub(1) { Some(level) => (Some(level), sigmas[level]), @@ -94,8 +95,13 @@ pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { } /// Which blurred curvature levels a wear generator reads -pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; CurvatureDetail::BLURRED_SIZES] { - let (narrower, wider, _) = levels_around(blur_sigma(kind, wear)); +pub(crate) fn levels_in_use(kind: GeneratorKind, wear: &WearParameters) -> [bool; LEVEL_RADII.len()] { + let sigma = blur_sigma(kind, wear); + if sigma <= 0.0 { + return [false; LEVEL_RADII.len()]; + } + + let (narrower, wider, _) = levels_around(sigma); std::array::from_fn(|level| level == wider || Some(level) == narrower) } @@ -113,9 +119,19 @@ fn smoothed_edges(inputs: &WearInputs) -> f32 { (1.0 - SMOOTHED_SHARE) * inputs.curvature + SMOOTHED_SHARE * inputs.blurred_curvature } +/// The masking at which the fitted cut-off is pinned, the controls' default +const DEFAULT_MASKING: f32 = 0.5; + /// 1 where the area is open enough to wear, 0 where occluded: the cut-off sits at `offset + gain × masking`, softened over `width` fn open_area(occlusion: f32, masking: f32, (offset, gain, width): (f32, f32, f32)) -> f32 { - ((occlusion - (offset + gain * masking)) / width + 0.5).clamp(0.0, 1.0) + // A cut-off below this leaves every occlusion fully open, so the low end eases from it to the default's cut-off instead of masking nothing + let fully_open = -width * 0.5; + let cut_off = if masking < DEFAULT_MASKING && offset < fully_open { + fully_open + (offset + gain * DEFAULT_MASKING - fully_open) * masking / DEFAULT_MASKING + } else { + offset + gain * masking + }; + ((occlusion - cut_off) / width + 0.5).clamp(0.0, 1.0) } // The signals' coefficients are fitted to the reference app's sweeps on a hard-surface bake @@ -177,6 +193,15 @@ mod tests { assert!(value(0.3, 0.6) < value(0.0, 0.6), "edges are masked"); } + #[test] + fn every_ao_masking_above_0_masks_more_occluded_edges() { + let wear = |ao_masking| WearParameters { ao_masking, ..defaults(GeneratorKind::EdgeWear) }; + let occluded_edge = inputs(0.1, 0.0); + let values: Vec = [0.0, 0.05, 0.1, 0.3].iter().map(|masking| wear_value(GeneratorKind::EdgeWear, &wear(*masking), &occluded_edge)).collect(); + assert!(values.windows(2).all(|pair| pair[1] < pair[0]), "{values:?}"); + assert_eq!(wear_value(GeneratorKind::EdgeWear, &wear(1.0), &occluded_edge), 0.0, "full masking clears occluded areas"); + } + #[test] fn a_higher_level_spreads_the_wear_and_a_full_level_is_a_hard_step() { let low = WearParameters { level: 0.25, ..defaults(GeneratorKind::EdgeWear) }; @@ -235,5 +260,13 @@ mod tests { assert_eq!((narrower, wider), (Some(2), 3)); assert!((0.0..=0.1).contains(&weight), "4.6 sits just past radius 4's sigma: {weight}"); assert_eq!(levels_around(500.0).1, LEVEL_RADII.len() - 1, "wider than every level reads the widest"); + for (radius, sigma) in LEVEL_RADII.iter().zip(LEVEL_SIGMAS) { + assert!(((radius * (radius + 1.0)).sqrt() - sigma).abs() < 0.001, "{radius}: {sigma}"); + } + let widest = super::blur_sigma( + GeneratorKind::EdgeWear, + &WearParameters { edges_smoothness: *WearParameters::EDGES_SMOOTHNESS_RANGE.end(), ..WearParameters::defaults(GeneratorKind::EdgeWear).unwrap() }, + ); + assert!(widest < LEVEL_SIGMAS[LEVEL_RADII.len() - 1], "the whole smoothness range lands between built levels: {widest}"); } } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 6f218f1f..f2b3d7df 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -993,7 +993,16 @@ impl GeneratorKind { pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); - GeneratorKind::ALL.into_iter().find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s)) + // The labels before the reference app's names, which agents may still send + let earlier = |kind: GeneratorKind| match kind { + GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), + GeneratorKind::Position => Some("Position gradient"), + GeneratorKind::Direction => Some("Light / direction"), + _ => None, + }; + GeneratorKind::ALL + .into_iter() + .find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s) || earlier(*k).is_some_and(|label| norm(label) == norm(s))) } } @@ -1042,6 +1051,11 @@ impl Generator { pub const MIN_NOISE_SCALE: f32 = 0.01; pub const MAX_NOISE_SCALE: f32 = 1000.0; + /// The global blur, balance and contrast the generator applies: none on the wear controls, which have no such controls + pub fn applied_global(&self) -> GeneratorGlobal { + if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + } + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -2288,6 +2302,7 @@ mod tests { assert_eq!(GeneratorKind::parse(kind.label()), Some(kind)); } assert!(!GeneratorKind::ThinAreas.in_picker(), "Thin areas only loads from saved projects and smart masks"); + assert_eq!(GeneratorKind::parse("Light / direction"), Some(GeneratorKind::Direction), "earlier labels still parse"); } #[test] diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e7ee6cce..9f5d493f 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -389,7 +389,10 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { /// Apply `params` to `generator`, using `command` in errors /// The parameters that drive the wear generators' earlier model -const EARLIER_WEAR_KEYS: [&str; 5] = ["level", "softness", "noise", "noiseScale", "offset"]; +const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale", "offset", "mode", "sizes"]; + +/// The global adjustments, which the wear kinds don't have +const GLOBAL_KEYS: [&str; 3] = ["blur", "balance", "contrast"]; /// The wear controls `effect.add.generator` and `effect.set` take const WEAR_KEYS: [&str; 10] = [ @@ -412,6 +415,14 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; }; + let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !given(&WEAR_KEYS) && generator.kind != GeneratorKind::FiberGlassEdgeWear); + if given(&GLOBAL_KEYS) && !earlier_model { + return Err(bad(command, format!("{} has no global blur, balance or contrast on its wear controls", generator.kind.label()))); + } + if let Some(unused) = WEAR_KEYS.iter().find(|key| params.get(**key).is_some() && !wear_key_applies(generator.kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", generator.kind.label()))); + } + if given(&EARLIER_WEAR_KEYS) { if given(&WEAR_KEYS) { return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); @@ -451,6 +462,16 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result Ok(()) } +/// Whether wear control `key` changes a generator of `kind` +pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { + match key { + "edgesMasking" => kind == GeneratorKind::Dirt, + "edgesSmoothness" | "aoMasking" | "curvatureWeight" => kind != GeneratorKind::Dirt, + "grungeScale" => kind != GeneratorKind::FiberGlassEdgeWear, + _ => true, + } +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs index cd49c378..c194dfe4 100644 --- a/crates/engine/tests/it/generator_wear.rs +++ b/crates/engine/tests/it/generator_wear.rs @@ -67,3 +67,27 @@ fn mixing_the_models_or_wear_controls_on_other_kinds_is_refused() { assert!(execute(&mut session, "effect.add.generator", &json!({"generator": "fiberGlassEdgeWear", "level": 0.5})).is_err()); assert_eq!(generator(&session, edge_wear).wear, WearParameters::defaults(GeneratorKind::EdgeWear), "a refused edit changes nothing"); } + +#[test] +fn controls_a_kind_does_not_use_are_refused_rather_than_ignored() { + let mut session = session(); + let edge_wear = add(&mut session, json!({"generator": "edgeWear"})); + let dirt = add(&mut session, json!({"generator": "dirt"})); + let fiber_glass = add(&mut session, json!({"generator": "fiberGlassEdgeWear"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "edgesMasking": 0.2})).is_err(), "edge wear has no edges masking"); + assert!(execute(&mut session, "effect.set", &json!({"effect": dirt, "edgesSmoothness": 2.0})).is_err(), "dirt has no edges smoothness"); + assert!(execute(&mut session, "effect.set", &json!({"effect": fiber_glass, "grungeScale": 8.0})).is_err(), "fiber glass has no grunge scale"); + assert!(execute(&mut session, "effect.set", &json!({"effect": edge_wear, "blur": 0.5})).is_err(), "the wear controls have no global blur"); +} + +#[test] +fn mode_and_sizes_keep_edge_wear_on_the_earlier_model_where_they_apply() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "mode": "both"})); + let added = generator(&session, effect); + assert_eq!(added.wear, None, "detail sizes belong to the earlier model"); + assert!(added.detail.is_some()); + execute(&mut session, "effect.set", &json!({"effect": effect, "blur": 0.5})).unwrap(); + assert_eq!(generator(&session, effect).global.blur, 0.5, "the earlier model keeps its global blur"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 3bbeafe9..0fc0b848 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -935,7 +935,7 @@ fn generators_take_blur_balance_and_contrast() { let mut state = session(); execute(&mut state, "layer.add.fill", &json!({})).unwrap(); execute(&mut state, "mask.add.black", &Value::Null).unwrap(); - let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "ambientOcclusion", "blur": 0.25})).unwrap(); let effect = added["effect"].clone(); execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 382a76df..54a2178e 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -209,16 +209,16 @@ fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: & } if let Some(merge) = edit { - let mut params = wear_params(&edited); + let mut params = wear_params(generator.kind, &edited); params["effect"] = json!(id); params["merge"] = json!(merge); app.run("effect.set", params); } } -/// The `effect.set` params that set every wear control to `wear` -fn wear_params(wear: &WearParameters) -> Value { - json!({ +/// The `effect.set` params that set every wear control a generator of `kind` has to `wear` +fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { + let mut params = json!({ "wearLevel": wear.level, "wearContrast": wear.contrast, "grungeAmount": wear.grunge_amount, @@ -229,7 +229,11 @@ fn wear_params(wear: &WearParameters) -> Value { "aoMasking": wear.ao_masking, "curvatureWeight": wear.curvature_weight, "edgesMasking": wear.edges_masking, - }) + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| texturecraft_engine::mask_cmds::wear_key_applies(kind, key)); + } + params } /// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked @@ -295,34 +299,35 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - // A wear generator restores its wear controls; level, softness, noise and offset would keep it on the earlier model - let mut params = match &defaults.wear { - Some(wear) => wear_params(wear), + let mut params = json!({ + "effect": id, + "seed": defaults.seed, + "invert": defaults.invert, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + "microAnchor": null, + }); + + // A wear generator restores its wear controls only: the earlier model's keys would move it back onto that model + let own = match &defaults.wear { + Some(wear) => wear_params(kind, wear), None => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, "noiseScale": defaults.noise_scale, "offset": defaults.offset, + "direction": defaults.direction, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, }), }; - let shared = json!({ - "effect": id, - "seed": defaults.seed, - "direction": defaults.direction, - "invert": defaults.invert, - "blur": defaults.global.blur, - "balance": defaults.global.balance, - "contrast": defaults.global.contrast, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - "microAnchor": null, - }); - if let (Some(params), Value::Object(shared)) = (params.as_object_mut(), shared) { - params.extend(shared); + if let (Some(params), Value::Object(own)) = (params.as_object_mut(), own) { + params.extend(own); } - if let Some(detail) = defaults.detail { + if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); } diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index c68ebf26..b300a7e2 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -60,8 +60,9 @@ fn the_picker_leaves_thin_areas_out() { let (mut harness, _) = app_with_dirt(); open_picker(&mut harness); + // The picker's tiles are the list options named after generators for kind in GeneratorKind::ALL { - let offered = harness.query_all_by_label(kind.label()).count() > 0; + let offered = harness.query_all_by_role_and_label(Role::ListBoxOption, kind.label()).count() > 0; assert_eq!(offered, kind.in_picker(), "{kind:?}"); } } From 2539643ad97257426dc02ae0a4356aa2a8112823 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 05/54] Curvature sizes: comment without a trailing period --- crates/compose/src/curvature_sizes.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 95525331..f47d9fcb 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -13,7 +13,7 @@ use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; /// The blur radius of each level in texels at 2K: the detail sizes of [`texturecraft_core::CurvatureDetail::SIZES`] after the first, then wider ones the wear generators' edges smoothness reaches pub const LEVEL_RADII: [f32; 8] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]; -/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`]. +/// The curvature map padded past its UV islands and blurred at each radius of [`LEVEL_RADII`] pub struct CurvatureSizes { /// One per blurred size, built once a generator gives that size a weight above 0. pub levels: Vec>>, From d7d9f7bc437f8235080581238ee82ad9cc158a2f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 06/54] Generators: global blur reaches 72 texels at 2K The widest global blur matches the reference's: 16 steps of 4.5 texels at 2K, up from 64. Global blur is new in this pass, so no saved project changes. --- crates/core/src/layer/generator_global.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs index 15349e0d..8133652d 100644 --- a/crates/core/src/layer/generator_global.rs +++ b/crates/core/src/layer/generator_global.rs @@ -13,7 +13,7 @@ pub struct GeneratorGlobal { impl GeneratorGlobal { /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. - pub const MAX_BLUR: f32 = 64.0; + pub const MAX_BLUR: f32 = 72.0; /// Narrower than this, the balanced range is a hard step. pub const MIN_RANGE: f32 = 1e-6; /// The texels per side the blur radius is measured at (2K). From 05a0ff5118087e825f904fa191dd790cc7cd7a07 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 07/54] Generators: Position, World Space Normals and Curvature/AO sections on the reference's controls Curvature, Ambient Occlusion, Position and the new World Space Normals take the reference app's section controls under the global ones: invert, blur (occlusion and normals), balance (a power curve on position and normals, linear on occlusion), contrast and brightness, and for position and normals three axes, each inverted, blended over the others with its own mode and weighted. Position reads the baked position map, else the mesh's bounds; World Space Normals the baked world space normal, else the mesh's normal; both can read an image input instead. Generators saved before keep their level, softness and noise and render as before; a section control moves one onto the new controls, and level, softness, noise or direction move it back. The curvature section names its detail sizes Sharp to Huge and its modes Dual and Unprocessed; the global invert is a False/True button. --- crates/compose/src/eval.rs | 106 +++++++-- crates/compose/src/lib.rs | 1 + crates/compose/src/sections.rs | 199 +++++++++++++++++ crates/compose/tests/generator_sections.rs | 201 ++++++++++++++++++ crates/core/src/layer.rs | 49 ++++- crates/core/src/layer/axis_blend.rs | 52 +++++ crates/core/src/layer/axis_layer.rs | 14 ++ crates/core/src/layer/section_parameters.rs | 81 +++++++ crates/core/src/layer/wear_parameters.rs | 7 +- crates/core/src/lib.rs | 4 +- crates/engine/src/mask_cmds.rs | 111 +++++++++- crates/engine/src/smart_masks.rs | 16 +- crates/engine/tests/it/bake_resolution.rs | 6 +- crates/engine/tests/it/generator_sections.rs | 90 ++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 146 ++++++++++--- .../ui-egui/tests/it/curvature_generator.rs | 18 +- crates/ui-egui/tests/it/generator_panel.rs | 75 ++++++- 18 files changed, 1117 insertions(+), 60 deletions(-) create mode 100644 crates/compose/src/sections.rs create mode 100644 crates/compose/tests/generator_sections.rs create mode 100644 crates/core/src/layer/axis_blend.rs create mode 100644 crates/core/src/layer/axis_layer.rs create mode 100644 crates/core/src/layer/section_parameters.rs create mode 100644 crates/engine/tests/it/generator_sections.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 933f9852..896dab07 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -15,7 +15,7 @@ use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, + PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; @@ -36,6 +36,7 @@ use crate::mask_gray::MaskGray; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; +use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; @@ -53,6 +54,9 @@ const COVERED: f32 = 0.9999; /// Largest projected step as a share of the image's longer side for non-UV projections const SEAM_JUMP_SHARE: f32 = 0.25; +/// Narrowest extent of the mesh's bounds a position is normalised across +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; @@ -508,8 +512,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // Use reference-resolution reach so all callers classify the same filters as stages - EffectKind::Generator(generator) if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() => { - Some((index, texels(generator.applied_global().blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + EffectKind::Generator(generator) + if generator.applied_global().blur > 0.0 || generator.resolution.can_reduce() || sections::generator_blur_sigma(generator) > 0.0 => + { + let section_blur = sections::generator_blur_sigma(generator); + let section_reach = if section_blur > 0.0 { texels(section_blur) } else { 0.0 }; + let reach = texels(generator.applied_global().blur_radius()) + section_reach + generator.resolution.largest_cell(res) as f32; + Some((index, reach, Op::Blur(None))) } // A mirror reads anywhere in its UV tile @@ -1953,19 +1962,14 @@ fn generator_region( ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); } - let blur_radius = generator.applied_global().blur_radius_at(uv_tile).round() as usize; - if blur_radius > 0 { - let mut weights = cover.to_vec(); - blur(&mut weights, columns, rows, blur_radius); - let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); - blur(&mut sums, columns, rows, blur_radius); - ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { - if *weight > MIN_READ_WEIGHT { - *ramp = sum / weight; - } - }); + // The section controls act on the signal before the global blur, their own blur first + if let Some(section) = generator.section_controls() { + blur_over_cover(&mut ramps, cover, (columns, rows), sections::blur_radius_at(generator.kind, §ion, uv_tile)); + ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); + // Finished and blended over the stack below, like the generator effect itself stack .par_chunks(2) @@ -1978,6 +1982,22 @@ fn generator_region( .collect() } +/// `values` blurred by three box passes of `radius`, weighted by `cover` so uncovered texels don't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], (columns, rows): (usize, usize), radius: usize) { + if radius == 0 { + return; + } + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, radius); + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + blur(&mut sums, columns, rows, radius); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(value, (sum, weight))| { + if *weight > MIN_READ_WEIGHT { + *value = sum / weight; + } + }); +} + /// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region @@ -2369,10 +2389,16 @@ fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { return wear::levels_in_use(generator.kind, &wear); } - let detail = generator.detail.as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let detail = curvature_detail_in_use(generator).as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } +/// The mode and detail sizes `generator` reads its curvature with: its own, the defaults on Curvature's section controls, else None +fn curvature_detail_in_use(generator: &Generator) -> Option { + let on_section = generator.kind == GeneratorKind::Curvature && generator.section_controls().is_some(); + generator.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) +} + /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) @@ -3296,10 +3322,14 @@ impl<'a, 'b> Texel<'a, 'b> { if needs_gray { [lum(value); 3] } else { value } } + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(section) = generator.section_controls() { + return self.section_signal(generator, §ion, curvature_sizes); + } let coords = self.coords(); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); @@ -3319,6 +3349,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; @@ -3354,10 +3385,39 @@ impl<'a, 'b> Texel<'a, 'b> { // Dirt gathers in dents; dents are occluded GeneratorKind::Dirt => -response, GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => 0.0, } } + /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + match generator.kind { + GeneratorKind::Curvature => { + let detail = curvature_detail_in_use(generator).unwrap_or_default(); + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + self.curvature_detail(&detail, sizes, curvature, micro) + } + GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + GeneratorKind::Position => { + let position = self.generator_input_color(generator, BakedMap::Position).unwrap_or_else(|| self.bounds_position().to_array()); + sections::axes_signal(position, §ion.axes) + } + GeneratorKind::WorldSpaceNormals => { + let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); + sections::axes_signal(normal, §ion.axes) + } + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, + } + } + + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) + fn bounds_position(&self) -> Vec3 { + let (low, high) = self.inp.bounds; + self.world().map_or(Vec3::ZERO, |position| ((position - low) / (high - low).max(Vec3::splat(MIN_BOUNDS_EXTENT))).clamp(Vec3::ZERO, Vec3::ONE)) + } + /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); @@ -3396,7 +3456,8 @@ impl<'a, 'b> Texel<'a, 'b> { /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); - finish_generator(generator, ramp) + let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + finish_generator(generator, adjusted) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). @@ -3408,6 +3469,14 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// Generator input `map` at this texel as three channels (an encoded normal or position): what replaces the mesh map, else the mesh map (None when not baked) + fn generator_input_color(&mut self, generator: &Generator, map: BakedMap) -> Option<[f32; 3]> { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + None => self.baked_color(map), + } + } + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { let combine = |edges: f32, cavities: f32| { @@ -5852,7 +5921,8 @@ mod tests { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { for mode in CurvatureMode::ALL { let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, ..Generator::new(kind) }; + let generator = + Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), wear: None, section: None, ..Generator::new(kind) }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 6318ea16..a2369743 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -36,6 +36,7 @@ pub mod projector_cover; pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; +mod sections; mod shape_distance; mod slope_texel; mod soft_box; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs new file mode 100644 index 00000000..2a6f9294 --- /dev/null +++ b/crates/compose/src/sections.rs @@ -0,0 +1,199 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators + +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; + +/// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] +const BLUR_SIGMA_PER_UNIT: f32 = 4.5; + +/// Base of the section balance's power curve: balance 0 raises the signal to 1/25, balance 1 to 25 +const BALANCE_POWER_BASE: f32 = 25.0; + +/// How far above the middle a signal must be to turn white at full contrast +const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5; + +/// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last +const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK]; + +/// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted +pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { + AXIS_ORDER.iter().fold(0.0, |base, &index| { + let axis = axes[index]; + if axis.weight <= 0.0 { + return base; + } + let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] }; + (base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0) + }) +} + +/// `layer` blended over `base` by `blend`, unclamped +pub(crate) fn blended(blend: AxisBlend, base: f32, layer: f32) -> f32 { + match blend { + AxisBlend::Normal => layer, + AxisBlend::Add => base + layer, + AxisBlend::Subtract => base - layer, + AxisBlend::Multiply => base * layer, + AxisBlend::AddSub => base + 2.0 * layer - 1.0, + AxisBlend::Max => base.max(layer), + } +} + +/// Gaussian sigma of the section blur of a generator of `kind`, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] (0 for kinds without it) +pub(crate) fn blur_sigma(kind: GeneratorKind, section: &SectionParameters) -> f32 { + if SectionParameters::has_blur(kind) { + section.blur.clamp(*SectionParameters::BLUR_RANGE.start(), *SectionParameters::BLUR_RANGE.end()) * BLUR_SIGMA_PER_UNIT + } else { + 0.0 + } +} + +/// Gaussian sigma of `generator`'s section blur in texels at 2K (0 without one) +pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 { + generator.section_controls().map_or(0.0, |section| blur_sigma(generator.kind, §ion)) +} + +/// The radius of the three box passes that blur like the section blur at `resolution` texels per side +pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize { + let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION; + + // Three boxes of radius r spread a texel with variance r (r + 1) + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + +/// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them +pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: f32) -> f32 { + let mut value = signal.clamp(0.0, 1.0); + if SectionParameters::has_balance(kind) { + let balance = section.balance.clamp(0.0, 1.0); + value = if kind == GeneratorKind::AmbientOcclusion { + GeneratorGlobal { balance, ..GeneratorGlobal::default() }.apply(value) + } else { + value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0)) + }; + } + value = contrasted(value, section.contrast.clamp(0.0, 1.0)); + if SectionParameters::has_brightness(kind) { + let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end()); + value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) }; + } + if section.invert { 1.0 - value } else { value } +} + +/// `value` with its range narrowed around the middle by `contrast` (1 a step just above the middle) +fn contrasted(value: f32, contrast: f32) -> f32 { + if contrast <= 0.0 { + return value; + } + let half_range = 0.5 * (1.0 - contrast); + if 2.0 * half_range < GeneratorGlobal::MIN_RANGE { + return if value > 0.5 + FULL_CONTRAST_STEP_OFFSET { 1.0 } else { 0.0 }; + } + ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn axis(blend: AxisBlend, weight: f32) -> AxisLayer { + AxisLayer { invert: false, blend, weight } + } + + fn defaults(kind: GeneratorKind) -> SectionParameters { + SectionParameters::defaults(kind).unwrap() + } + + #[test] + fn each_axis_reads_its_own_channel() { + let channels = [0.2, 0.5, 0.9]; + for (index, expected) in channels.iter().enumerate() { + let mut axes = [axis(AxisBlend::Add, 0.0); 3]; + axes[index].weight = 1.0; + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "axis {index}"); + } + let mut inverted = [axis(AxisBlend::Add, 0.0); 3]; + inverted[SectionParameters::TOP_TO_BOTTOM] = AxisLayer { invert: true, ..axis(AxisBlend::Add, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.5).abs() < 1e-6); + inverted[SectionParameters::RIGHT_TO_LEFT] = AxisLayer { invert: true, ..axis(AxisBlend::Normal, 1.0) }; + assert!((axes_signal(channels, &inverted) - 0.8).abs() < 1e-6, "inverted red replaces the base"); + } + + #[test] + fn right_to_left_blends_over_top_to_bottom_and_front_to_back_goes_last() { + let channels = [0.3, 0.8, 0.6]; + let mut axes = [axis(AxisBlend::Add, 0.0), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + for (blend, expected) in [ + (AxisBlend::Normal, 0.3), + (AxisBlend::Add, 1.0), + (AxisBlend::Subtract, 0.5), + (AxisBlend::Multiply, 0.24), + (AxisBlend::AddSub, 0.4), + (AxisBlend::Max, 0.8), + ] { + axes[SectionParameters::RIGHT_TO_LEFT] = axis(blend, 1.0); + assert!((axes_signal(channels, &axes) - expected).abs() < 1e-6, "{blend:?}"); + } + + axes[SectionParameters::RIGHT_TO_LEFT] = axis(AxisBlend::Normal, 1.0); + axes[SectionParameters::FRONT_TO_BACK] = axis(AxisBlend::Normal, 1.0); + assert!((axes_signal(channels, &axes) - 0.6).abs() < 1e-6, "front to back replaces both"); + } + + #[test] + fn a_weight_lerps_the_unclamped_blend_and_clamps_once() { + let channels = [0.9, 0.8, 0.0]; + let axes = [axis(AxisBlend::Add, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 1.0).abs() < 1e-6, "0.8 + 0.45 clamps to 1"); + let axes = [axis(AxisBlend::Subtract, 0.5), axis(AxisBlend::Add, 1.0), axis(AxisBlend::Add, 0.0)]; + assert!((axes_signal(channels, &axes) - 0.35).abs() < 1e-6); + } + + #[test] + fn position_balance_is_a_power_curve_and_occlusion_balance_is_linear() { + let position = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::Position) }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(0.2)).abs() < 1e-5); + let position = SectionParameters { balance: 0.75, ..position }; + assert!((adjusted(GeneratorKind::Position, &position, 0.5) - 0.5f32.powf(5.0)).abs() < 1e-5); + + let occlusion = SectionParameters { balance: 0.25, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.0, "the lower half goes black"); + assert!((adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.75) - 0.5).abs() < 1e-6); + + let curvature = SectionParameters { balance: 0.0, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &curvature, 0.4), 0.4, "curvature has no balance"); + } + + #[test] + fn contrast_narrows_around_the_middle_and_full_contrast_steps_just_above_it() { + let half = SectionParameters { contrast: 0.5, ..defaults(GeneratorKind::Curvature) }; + assert_eq!(adjusted(GeneratorKind::Curvature, &half, 0.25), 0.0); + assert!((adjusted(GeneratorKind::Curvature, &half, 0.6) - 0.7).abs() < 1e-5); + + let full = SectionParameters { contrast: 1.0, ..half }; + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5), 0.0, "the middle itself stays black"); + assert_eq!(adjusted(GeneratorKind::Curvature, &full, 0.5001), 1.0); + } + + #[test] + fn brightness_lerps_towards_white_or_black_then_invert_flips() { + let brighter = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::WorldSpaceNormals) }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &brighter, 0.4) - 0.7).abs() < 1e-6); + let darker = SectionParameters { brightness: -0.5, ..brighter }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &darker, 0.4) - 0.2).abs() < 1e-6); + let inverted = SectionParameters { invert: true, ..darker }; + assert!((adjusted(GeneratorKind::WorldSpaceNormals, &inverted, 0.4) - 0.8).abs() < 1e-6); + + let occlusion = SectionParameters { brightness: 0.5, ..defaults(GeneratorKind::AmbientOcclusion) }; + assert_eq!(adjusted(GeneratorKind::AmbientOcclusion, &occlusion, 0.4), 0.4, "ambient occlusion has no brightness"); + } + + #[test] + fn only_ambient_occlusion_and_world_space_normals_blur() { + let section = SectionParameters { blur: 16.0, ..defaults(GeneratorKind::Position) }; + assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0); + assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0); + assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0); + let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; + assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); + } +} diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs new file mode 100644 index 00000000..3a9b65c4 --- /dev/null +++ b/crates/compose/tests/generator_sections.rs @@ -0,0 +1,201 @@ +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators on a sphere, beside their earlier model + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + SectionParameters, Source, TextureSet, +}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// How far a mask value may sit from the expected one +const TOLERANCE: f32 = 1e-3; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer, baked: BakedMaps::default() } +} + +/// A baked map of `map` holding `value` everywhere +fn uniform_map(map: BakedMap, value: f32) -> BakedMaps { + BakedMaps { resolution: RES, maps: [(map, Arc::new(vec![value; (RES * RES) as usize * map.components()]))].into() } +} + +/// Every covered texel with its world position and normal +fn surface(fixture: &Fixture) -> Vec<((u32, u32), Vec3, Vec3)> { + (0..RES * RES) + .filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos, surface.nrm))) + .collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// The earlier model's smooth step of `signal` at `generator`'s level and softness +fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { + let threshold = 1.0 - generator.level; + let ramp = ((signal - (threshold - generator.softness)) / (2.0 * generator.softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) +} + +fn earlier(kind: GeneratorKind) -> Generator { + Generator { section: None, ..Generator::new(kind) } +} + +fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { + let mut generator = Generator::new(kind); + let mut section = generator.section.unwrap(); + change(&mut section); + generator.section = Some(section); + generator +} + +fn assert_close(actual: &[f32], expected: &[f32], what: &str) { + for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); + } +} + +#[test] +fn generators_saved_before_their_new_controls_render_as_before() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let (center, radius) = ((low + high) * 0.5, (high - low).length() * 0.5); + + let position = earlier(GeneratorKind::Position); + let expected: Vec = points.iter().map(|(_, pos, _)| earlier_ramp(&position, ((*pos - center) / radius).y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, position, &texels), &expected, "position"); + + let direction = earlier(GeneratorKind::Direction); + let expected: Vec = points.iter().map(|(_, _, nrm)| earlier_ramp(&direction, nrm.y * 0.5 + 0.5)).collect(); + assert_close(&mask(&mut fixture, direction, &texels), &expected, "direction"); + + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.3); + let occlusion = earlier(GeneratorKind::AmbientOcclusion); + let expected = vec![earlier_ramp(&occlusion, 0.3); texels.len()]; + assert_close(&mask(&mut fixture, occlusion, &texels), &expected, "ambient occlusion"); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &texels), &vec![0.3; texels.len()], "new ambient occlusion"); + + fixture.baked = uniform_map(BakedMap::Curvature, 0.7); + let curvature = Generator { detail: None, ..earlier(GeneratorKind::Curvature) }; + let expected = vec![earlier_ramp(&curvature, 0.7); texels.len()]; + assert_close(&mask(&mut fixture, curvature, &texels), &expected, "curvature"); +} + +#[test] +fn world_space_normals_combine_the_axes_of_the_normal() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let channel = |axis: usize| -> Vec { points.iter().map(|(_, _, nrm)| nrm[axis] * 0.5 + 0.5).collect() }; + + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::WorldSpaceNormals), &texels), &channel(1), "top to bottom by default"); + for (index, axis) in [(SectionParameters::RIGHT_TO_LEFT, 0), (SectionParameters::FRONT_TO_BACK, 2)] { + let generator = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::TOP_TO_BOTTOM].weight = 0.0; + section.axes[index].weight = 1.0; + }); + assert_close(&mask(&mut fixture, generator, &texels), &channel(axis), "one axis alone"); + } + + let multiplied = with_section(GeneratorKind::WorldSpaceNormals, |section| { + section.axes[SectionParameters::RIGHT_TO_LEFT] = texturecraft_core::AxisLayer { invert: true, blend: AxisBlend::Multiply, weight: 1.0 }; + }); + let expected: Vec = channel(1).iter().zip(channel(0)).map(|(top, right)| top * (1.0 - right)).collect(); + assert_close(&mask(&mut fixture, multiplied, &texels), &expected, "inverted right to left multiplies top to bottom"); + + // Without a baked map, the generator's own World Space Normal input reads instead of the mesh + let mut uniform = Generator::new(GeneratorKind::WorldSpaceNormals); + uniform.inputs.insert(BakedMap::WorldNormal, Source::Uniform([0.2, 0.9, 0.4])); + assert_close(&mask(&mut fixture, uniform, &texels), &vec![0.9; texels.len()], "a replaced input"); +} + +#[test] +fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { + let mut fixture = fixture(); + let points = surface(&fixture); + let texels: Vec<_> = points.iter().map(|point| point.0).collect(); + let (low, high) = fixture.mesh.bounds(); + let expected: Vec = points.iter().map(|(_, pos, _)| (pos.y - low.y) / (high.y - low.y)).collect(); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "bounds"); + + fixture.baked = uniform_map(BakedMap::Position, 0.25); + let balanced = with_section(GeneratorKind::Position, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance"); +} + +#[test] +fn occlusion_balance_is_linear_and_brightness_lerps() { + let mut fixture = fixture(); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.0).collect(); + fixture.baked = uniform_map(BakedMap::AmbientOcclusion, 0.6); + let balanced = with_section(GeneratorKind::AmbientOcclusion, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.2; texels.len()], "balance 0.25 stretches the upper half"); + + let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true); + assert_close(&mask(&mut fixture, inverted, &texels), &vec![0.4; texels.len()], "section invert"); + + fixture.baked = uniform_map(BakedMap::Position, 0.4); + let brighter = with_section(GeneratorKind::Position, |section| section.brightness = 0.5); + assert_close(&mask(&mut fixture, brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white"); + let darker = with_section(GeneratorKind::Position, |section| section.brightness = -0.5); + assert_close(&mask(&mut fixture, darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value"); +} + +#[test] +fn section_blur_spreads_occlusion_across_a_step() { + let mut fixture = fixture(); + let step: Vec = (0..RES * RES).map(|index| if index % RES < RES / 2 { 0.0 } else { 1.0 }).collect(); + fixture.baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(step))].into() }; + let row: Vec<(u32, u32)> = surface(&fixture).iter().map(|point| point.0).filter(|texel| texel.0.abs_diff(RES / 2) <= 2).collect(); + assert!(!row.is_empty()); + + let sharp = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion), &row); + assert!(sharp.iter().all(|value| *value == 0.0 || *value == 1.0), "unblurred: {sharp:?}"); + let blurred = mask(&mut fixture, with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row); + assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}"); + + let position = with_section(GeneratorKind::Position, |section| section.blur = 16.0); + fixture.baked = uniform_map(BakedMap::Position, 0.3); + assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f2b3d7df..1e0f001d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,8 @@ use crate::{ ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; +mod axis_blend; +mod axis_layer; mod curvature_detail; mod curvature_mode; mod decal_flip; @@ -23,6 +25,7 @@ mod output_resolution; mod resolution_mode; mod sampling; mod scale_mode; +mod section_parameters; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -33,6 +36,8 @@ mod uv_transform; mod uv_wrap; mod wear_parameters; +pub use axis_blend::AxisBlend; +pub use axis_layer::AxisLayer; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; @@ -44,6 +49,7 @@ pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; +pub use section_parameters::SectionParameters; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -930,10 +936,12 @@ pub enum GeneratorKind { Direction, /// Worn edges of a fibreglass-like coating: the edges fade into its grunge FiberGlassEdgeWear, + /// The world space normal's axes combined into one gray + WorldSpaceNormals, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 8] = [ + pub const ALL: [GeneratorKind; 9] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -942,6 +950,7 @@ impl GeneratorKind { GeneratorKind::Position, GeneratorKind::Direction, GeneratorKind::FiberGlassEdgeWear, + GeneratorKind::WorldSpaceNormals, ]; pub fn label(self) -> &'static str { match self { @@ -953,6 +962,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Light", GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", + GeneratorKind::WorldSpaceNormals => "World Space Normals", } } @@ -967,6 +977,7 @@ impl GeneratorKind { GeneratorKind::Position => "Position", GeneratorKind::Direction => "Direction", GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", + GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", } } @@ -987,7 +998,9 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position | GeneratorKind::Direction => &[], + GeneratorKind::Position => &[BakedMap::Position], + GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], + GeneratorKind::Direction => &[], } } @@ -1041,6 +1054,9 @@ pub struct Generator { /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub wear: Option, + /// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub section: Option, } impl Generator { @@ -1056,6 +1072,16 @@ impl Generator { if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } } + /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None + pub fn section_controls(&self) -> Option { + self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) + } + + /// Whether the generator is on the level, softness and noise it had before the reference app's controls + pub fn on_earlier_model(&self) -> bool { + self.wear.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + } + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -1085,6 +1111,7 @@ impl Generator { inputs: BTreeMap::new(), micro: None, wear: WearParameters::defaults(kind), + section: SectionParameters::defaults(kind), } } @@ -2317,6 +2344,24 @@ mod tests { assert!(curvature.get("wear").is_none(), "other kinds save no wear controls"); } + #[test] + fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + let mut saved = serde_json::to_value(Generator::new(kind)).unwrap(); + assert!(saved.get("section").is_some(), "new {kind:?} generators have the reference's controls"); + + saved.as_object_mut().unwrap().remove("section"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it"); + assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments"); + } + + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::WorldSpaceNormals)).unwrap(); + saved.as_object_mut().unwrap().remove("section"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.section_controls(), SectionParameters::defaults(GeneratorKind::WorldSpaceNormals), "it has no earlier model"); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/core/src/layer/axis_blend.rs b/crates/core/src/layer/axis_blend.rs new file mode 100644 index 00000000..bb53925d --- /dev/null +++ b/crates/core/src/layer/axis_blend.rs @@ -0,0 +1,52 @@ +use serde::{Deserialize, Serialize}; + +/// How an axis of a World Space Normals or Position generator combines with the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum AxisBlend { + /// The axis replaces what is below it + Normal, + /// The axis adds to what is below it + Add, + /// The axis is taken from what is below it + Subtract, + /// The axis multiplies what is below it + Multiply, + /// The axis adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the axis and what is below it + Max, +} + +impl AxisBlend { + pub const ALL: [AxisBlend; 6] = [AxisBlend::Normal, AxisBlend::Add, AxisBlend::Subtract, AxisBlend::Multiply, AxisBlend::AddSub, AxisBlend::Max]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + AxisBlend::Normal => "Normal", + AxisBlend::Add => "Linear Dodge (Add)", + AxisBlend::Subtract => "Subtract", + AxisBlend::Multiply => "Multiply", + AxisBlend::AddSub => "Add/Sub", + AxisBlend::Max => "Max (Lighten)", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + AxisBlend::Normal => "normal", + AxisBlend::Add => "add", + AxisBlend::Subtract => "subtract", + AxisBlend::Multiply => "multiply", + AxisBlend::AddSub => "addSub", + AxisBlend::Max => "max", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + AxisBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/axis_layer.rs b/crates/core/src/layer/axis_layer.rs new file mode 100644 index 00000000..58e5bae6 --- /dev/null +++ b/crates/core/src/layer/axis_layer.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +use super::axis_blend::AxisBlend; + +/// One axis of a World Space Normals or Position generator: its channel, inverted or not, blended over the axes before it +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AxisLayer { + /// The axis read from its far side + pub invert: bool, + pub blend: AxisBlend, + /// How much of the blend shows (0..1) + pub weight: f32, +} diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs new file mode 100644 index 00000000..583c4a99 --- /dev/null +++ b/crates/core/src/layer/section_parameters.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; +use super::axis_blend::AxisBlend; +use super::axis_layer::AxisLayer; + +/// The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, applied before the global ones +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SectionParameters { + pub invert: bool, + /// Blur of the signal ([`SectionParameters::BLUR_RANGE`]; Ambient Occlusion and World Space Normals) + pub blur: f32, + /// Shifts the signal darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged (not Curvature) + pub balance: f32, + /// Narrows the signal around its middle (0 unchanged, 1 a hard step) + pub contrast: f32, + /// Lifts the signal towards white (above 0) or black (below 0) ([`SectionParameters::BRIGHTNESS_RANGE`]; not Ambient Occlusion) + pub brightness: f32, + /// Right to left, top to bottom and front to back (Position and World Space Normals) + pub axes: [AxisLayer; 3], +} + +impl SectionParameters { + pub const BLUR_RANGE: std::ops::RangeInclusive = 0.0..=16.0; + pub const BRIGHTNESS_RANGE: std::ops::RangeInclusive = -1.0..=1.0; + /// Index in [`SectionParameters::axes`] of each axis + pub const RIGHT_TO_LEFT: usize = 0; + pub const TOP_TO_BOTTOM: usize = 1; + pub const FRONT_TO_BACK: usize = 2; + + /// The reference app's defaults for `kind`, or None for kinds without section controls + pub fn defaults(kind: GeneratorKind) -> Option { + let axis = |weight: f32| AxisLayer { invert: false, blend: AxisBlend::Add, weight }; + let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] }; + match kind { + GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults), + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => None, + } + } + + /// Whether a generator of `kind` has the section blur + pub fn has_blur(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section balance + pub fn has_balance(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` has the section brightness + pub fn has_brightness(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Curvature | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Whether a generator of `kind` combines the three axes of a map + pub fn has_axes(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Position | GeneratorKind::WorldSpaceNormals) + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> SectionParameters { + let defaults = SectionParameters::defaults(kind).unwrap_or(self); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + let axes = std::array::from_fn(|index| { + let (axis, default) = (self.axes[index], defaults.axes[index]); + AxisLayer { weight: within(axis.weight, default.weight, 0.0..=1.0), ..axis } + }); + SectionParameters { + invert: self.invert, + blur: within(self.blur, defaults.blur, SectionParameters::BLUR_RANGE), + balance: within(self.balance, defaults.balance, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + brightness: within(self.brightness, defaults.brightness, SectionParameters::BRIGHTNESS_RANGE), + axes, + } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index b0c2de19..956dbd1a 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -49,7 +49,12 @@ impl WearParameters { match kind { GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), GeneratorKind::FiberGlassEdgeWear => Some(WearParameters { curvature_weight: 0.25, ..shared }), - GeneratorKind::ThinAreas | GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction => None, + GeneratorKind::ThinAreas + | GeneratorKind::Curvature + | GeneratorKind::AmbientOcclusion + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b494aa57..222613cf 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,10 +111,10 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9f5d493f..1b23275d 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source, WearParameters, + AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, + GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), level?, softness?, noise?, offset?: -1..1 added to the result (instead keep edgeWear and dirt on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear and section controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -472,8 +472,111 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } +/// The parameters that drive the earlier model of the kinds with section controls +const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"]; + +/// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`] +const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance", "sectionContrast", "sectionBrightness"]; + +/// The name of each axis in its keys, in the order of [`SectionParameters::axes`], and what follows it +const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"]; +const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; + +/// The section controls and the axis keys `params` gives +fn given_new_model_keys(params: &Value) -> Vec { + let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); + SECTION_KEYS.iter().map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() +} + +/// The section controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model +fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let kind = generator.kind; + let new_keys = given_new_model_keys(params); + let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some()); + let Some(defaults) = SectionParameters::defaults(kind) else { + return match new_keys.first() { + Some(key) => { + Err(bad(command, format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position and World Space Normals have it", kind.label()))) + } + None => Ok(()), + }; + }; + if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); + } + + if earlier { + if !new_keys.is_empty() { + return Err(bad(command, "level, softness, noise, offset and direction drive the earlier model: give them or the section controls, not both")); + } + if kind == GeneratorKind::WorldSpaceNormals { + return Err(bad( + command, + "World Space Normals has section controls only (sectionBalance, topBottomWeight…), no level, softness, noise, offset or direction", + )); + } + generator.section = None; + return Ok(()); + } + if new_keys.is_empty() { + return Ok(()); + } + + // Moving onto the reference's controls starts from the kind's defaults: the earlier model's values no longer apply + if generator.on_earlier_model() { + let defaults = Generator::new(kind); + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = + (defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale); + (generator.offset, generator.direction) = (defaults.offset, defaults.direction); + } + + let mut section = generator.section_controls().unwrap_or(defaults); + for (key, value) in [ + ("sectionBlur", &mut section.blur), + ("sectionBalance", &mut section.balance), + ("sectionContrast", &mut section.contrast), + ("sectionBrightness", &mut section.brightness), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "sectionInvert") { + section.invert = invert; + } + for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) { + if let Some(invert) = boolp(params, &format!("{name}Invert")) { + axis.invert = invert; + } + if let Some(weight) = f32p(params, &format!("{name}Weight")) { + axis.weight = weight; + } + let blend_key = format!("{name}Blend"); + if let Some(blend) = params.get(&blend_key) { + let blend_name = blend.as_str().ok_or_else(|| bad(command, format!("`{blend_key}` must be a string")))?; + axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?; + } + } + generator.section = Some(section.clamped(kind)); + Ok(()) +} + +/// Whether section control `key` changes a generator of `kind` +pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { + let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); + match key { + "sectionInvert" | "sectionContrast" => SectionParameters::defaults(kind).is_some(), + "sectionBlur" => SectionParameters::has_blur(kind), + "sectionBalance" => SectionParameters::has_balance(kind), + "sectionBrightness" => SectionParameters::has_brightness(kind), + _ if axis_key => SectionParameters::has_axes(kind), + _ => false, + } +} + fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; + section_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 244c412e..ceeb23cf 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,14 +79,24 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or wear controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear and section controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, wear: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { + level, + softness, + noise_amount: noise, + direction, + invert, + detail: None, + wear: None, + section: None, + ..Generator::new(kind) + }) } /// A triplanar grayscale pattern fill diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index 6ea63f2f..b2c88885 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -127,5 +127,9 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); - assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout"); + let expected = [240.0 / 255.0, 20.0 / 255.0]; + assert!( + mask.iter().zip(expected).all(|(value, expected)| (value - expected).abs() < 0.001), + "generators sample the whole bake through the working layout: {mask:?}" + ); } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs new file mode 100644 index 00000000..02c68135 --- /dev/null +++ b/crates/engine/tests/it/generator_sections.rs @@ -0,0 +1,90 @@ +//! The section controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise + +use serde_json::{Value, json}; +use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters}; +use texturecraft_engine::mask_cmds::section_key_applies; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn new_generators_start_on_the_reference_controls() { + let mut session = session(); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); + } + assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_defaults_with_that_change() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None, "level keeps it on the earlier model"); + + let edit = json!({"effect": effect, "sectionBalance": 0.3, "rightLeftBlend": "Max (Lighten)", "frontBackWeight": 4.0, "sectionBrightness": -3.0}); + execute(&mut session, "effect.set", &edit).unwrap(); + + let moved = generator(&session, effect); + let mut expected = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + expected.balance = 0.3; + expected.brightness = -1.0; + expected.axes[SectionParameters::RIGHT_TO_LEFT].blend = AxisBlend::Max; + expected.axes[SectionParameters::FRONT_TO_BACK].weight = 1.0; + assert_eq!(moved.section, Some(expected), "the rest at defaults, values clamped"); + assert_eq!(moved.level, Generator::new(GeneratorKind::Position).level, "the earlier model's values start over"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "noise": 0.5})).unwrap(); + assert_eq!(generator(&session, effect).section, None, "noise moves it back"); +} + +#[test] +fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { + let mut session = session(); + let curvature = add(&mut session, json!({"generator": "curvature"})); + let occlusion = add(&mut session, json!({"generator": "ambientOcclusion"})); + let position = add(&mut session, json!({"generator": "position"})); + let normals = add(&mut session, json!({"generator": "worldSpaceNormals"})); + let dirt = add(&mut session, json!({"generator": "dirt"})); + + for (effect, key) in [ + (curvature, "sectionBalance"), + (curvature, "sectionBlur"), + (curvature, "topBottomWeight"), + (occlusion, "sectionBrightness"), + (occlusion, "rightLeftInvert"), + (position, "sectionBlur"), + (dirt, "sectionContrast"), + ] { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); + } + for (effect, key) in [(curvature, "sectionBrightness"), (occlusion, "sectionBlur"), (normals, "sectionBlur"), (normals, "frontBackWeight")] { + execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).unwrap(); + } + + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "level": 0.5, "sectionContrast": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": normals, "softness": 0.5})).is_err(), "World Space Normals has no earlier model"); + assert!(execute(&mut session, "effect.set", &json!({"effect": position, "topBottomBlend": "overlay"})).is_err()); + assert_eq!(generator(&session, position).section, SectionParameters::defaults(GeneratorKind::Position), "a refused edit changes nothing"); + + assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); + assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index b3a87d44..44effae5 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,6 +36,7 @@ mod filters; mod folder_contents; mod frame_selection; mod generator_inputs; +mod generator_sections; mod generator_swap; mod generator_wear; mod gradient_map; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 54a2178e..e9df3bba 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,7 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, + WearParameters, }; use crate::TextureCraftApp; @@ -35,9 +36,12 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); } else { global_adjustments(app, ui, id, generator); - ramp_parameters(app, ui, id, generator); - if generator.kind == GeneratorKind::Curvature { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + if generator.on_earlier_model() { + ramp_parameters(app, ui, id, generator); + } + // Saved before the section controls, a generator shows them at their defaults: editing one moves it onto them + if let Some(defaults) = SectionParameters::defaults(generator.kind) { + section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { @@ -51,9 +55,9 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); }); }); - if !generator.kind.inputs().is_empty() { + if !inputs_in_use(generator).is_empty() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - for map in generator.kind.inputs() { + for map in inputs_in_use(generator) { input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); } }); @@ -91,6 +95,12 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } +/// The inputs `generator` reads: none for Position on its earlier model, which reads the mesh itself +fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { + let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + if reads_geometry { &[] } else { generator.kind.inputs() } +} + /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -103,6 +113,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::AmbientOcclusion => (tr("Occluded areas."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]), GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), }; // Wrapped rows: a long line must not widen the panel past its edge @@ -169,7 +180,7 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: Outpu /// Global invert, blur, balance and contrast: what every generator applies to its finished value. fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut invert, mut global) = (generator.invert, generator.global); - let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let invert_edit = true_false(ui, tr("Global invert"), &mut invert).then_some(false); let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); @@ -299,7 +310,7 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); - let mut params = json!({ + let params = json!({ "effect": id, "seed": defaults.seed, "invert": defaults.invert, @@ -309,10 +320,12 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "microAnchor": null, }); - // A wear generator restores its wear controls only: the earlier model's keys would move it back onto that model - let own = match &defaults.wear { - Some(wear) => wear_params(kind, wear), - None => json!({ + // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model + let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); + let own = match (&defaults.wear, &defaults.section) { + (Some(wear), _) => wear_params(kind, wear), + (None, Some(section)) => merged(section_params(kind, section), global), + (None, None) => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -324,9 +337,7 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { "contrast": defaults.global.contrast, }), }; - if let (Some(params), Value::Object(own)) = (params.as_object_mut(), own) { - params.extend(own); - } + let mut params = merged(params, own); if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { params["mode"] = json!(format!("{:?}", detail.mode)); params["sizes"] = json!(detail.weights); @@ -334,9 +345,99 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { params } +/// The keys of `extra` added to the object `params` +fn merged(mut params: Value, extra: Value) -> Value { + if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { + params.extend(extra); + } + params +} + +/// The section controls of generator effect `id` under the kind's own heading, showing `shown` +fn section_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, shown: SectionParameters) { + let kind = generator.kind; + let title = match kind { + GeneratorKind::Curvature => tr("Curvature"), + GeneratorKind::AmbientOcclusion => tr("Ambient occlusion"), + GeneratorKind::Position => tr("Position"), + _ => tr("World space normal"), + }; + section(ui, "generator_section", title, true, |ui| { + let mut edited = shown; + let mut edit = true_false(ui, tr("Invert"), &mut edited.invert).then_some(false); + if kind == GeneratorKind::Curvature { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if SectionParameters::has_blur(kind) { + edit = edit.or(slider_edit(ui, tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); + } + if SectionParameters::has_balance(kind) { + edit = edit.or(slider_edit(ui, tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); + } + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + if SectionParameters::has_brightness(kind) { + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); + } + if SectionParameters::has_axes(kind) { + let titles = [tr("Right to left"), tr("Top to bottom"), tr("Front to back")]; + for (index, (axis, title)) in edited.axes.iter_mut().zip(titles).enumerate() { + // Each axis's dropdown needs its own id: the dropdown's id comes from its label + ui.push_id(("generator_axis", index), |ui| { + section(ui, "generator_axis", title, true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut axis.invert).then_some(false)); + combo(ui, tr("Blending mode"), axis_blend_label(axis.blend), |ui| { + for blend in AxisBlend::ALL { + if ui.selectable_label(blend == axis.blend, axis_blend_label(blend)).clicked() { + axis.blend = blend; + edit = Some(false); + } + } + }); + }); + edit = edit.or(slider_edit(ui, title, &mut axis.weight, 0.0..=1.0, 2)); + }); + } + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); + } + }); +} + +/// The `effect.set` params that set every section control a generator of `kind` has to `section` +fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { + let mut params = json!({ + "sectionInvert": section.invert, + "sectionBlur": section.blur, + "sectionBalance": section.balance, + "sectionContrast": section.contrast, + "sectionBrightness": section.brightness, + }); + if let Some(params) = params.as_object_mut() { + for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { + params.insert(format!("{name}Invert"), json!(axis.invert)); + params.insert(format!("{name}Blend"), json!(axis.blend.id())); + params.insert(format!("{name}Weight"), json!(axis.weight)); + } + params.retain(|key, _| texturecraft_engine::mask_cmds::section_key_applies(kind, key)); + } + params +} + +/// The translated name of axis blending mode `blend` +fn axis_blend_label(blend: AxisBlend) -> &'static str { + match blend { + AxisBlend::Normal => tr("Normal"), + AxisBlend::Add => tr("Linear Dodge (Add)"), + AxisBlend::Subtract => tr("Subtract"), + AxisBlend::Multiply => tr("Multiply"), + AxisBlend::AddSub => tr("Add/Sub"), + AxisBlend::Max => tr("Max (Lighten)"), + } +} + /// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let tokens = Tokens::get(ui.ctx()); let shown = detail.cloned().unwrap_or_default(); combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { for mode in CurvatureMode::ALL { @@ -346,18 +447,15 @@ fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, } }); - ui.label(caption(tr("Detail sizes"))); + let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; let mut weights = shown.weights; let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + for (weight, name) in weights.iter_mut().zip(names) { + edit = edit.or(slider_edit(ui, name, weight, 0.0..=1.0, 2)); } if let Some(merge) = edit { app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); - } } /// The translated name of curvature mode `mode`. @@ -365,8 +463,8 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str { match mode { CurvatureMode::Edges => tr("Edges"), CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), + CurvatureMode::Both => tr("Dual"), + CurvatureMode::Raw => tr("Unprocessed"), } } diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index a5b321bc..aae768dc 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -26,10 +26,20 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { (harness, LayerId(effect)) } +/// The name the panel's Mode dropdown gives `mode` +fn mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Dual", + CurvatureMode::Raw => "Unprocessed", + } +} + fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(current.label())).unwrap().click(); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(mode_label(current))).unwrap().click(); harness.run_steps(2); - harness.get_by_label(next.label()).click(); + harness.get_by_label(mode_label(next)).click(); harness.run_steps(4); } @@ -44,9 +54,9 @@ fn mode_and_detail_controls_apply_and_undo() { assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); let previous = detail(&harness); let history = harness.state().session.history_labels().len(); - harness.get_by_label("8 px").scroll_to_me(); + harness.get_by_label("Large").scroll_to_me(); harness.run_steps(3); - let label = harness.get_by_label("8 px").rect(); + let label = harness.get_by_label("Large").rect(); let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); let end = start + egui::vec2(100.0, 0.0); harness.drag_at(start); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index b53f5012..edf21484 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -141,6 +141,67 @@ fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { assert!(generator(&harness, effect).inputs.is_empty()); } +/// How many nodes carry `label` +fn count(harness: &Harness<'_, TextureCraftApp>, label: &str) -> usize { + harness.query_all_by_label(label).count() +} + +#[test] +fn each_kind_shows_its_section_rows_and_no_earlier_ones() { + let rows = [ + ("curvature", &["Sharp", "Huge", "Brightness", "Global contrast"][..], &["Balance", "Blending mode", "Level"][..]), + ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), + ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), + ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ]; + for (kind, shown, hidden) in rows { + let (harness, _) = harness_with(false, json!({"generator": kind})); + for label in shown { + assert!(count(&harness, label) > 0, "{kind} shows {label}"); + } + for label in hidden { + assert_eq!(count(&harness, label), 0, "{kind} hides {label}"); + } + } + + let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + assert_eq!(count(&harness, "Blending mode"), 3); + let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); + assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); +} + +#[test] +fn each_axis_has_its_own_blending_mode_dropdown() { + let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); + let added = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() + }; + assert_eq!(added(&harness), 3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + + let axes = generator(&harness, effect).section.unwrap().axes; + assert_eq!(axes.map(|axis| axis.blend), [AxisBlend::Add, AxisBlend::Add, AxisBlend::Multiply], "only front to back changed"); +} + +#[test] +fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { + let (mut harness, effect) = harness_with(false, json!({"generator": "position", "level": 0.4})); + assert_eq!(generator(&harness, effect).section, None); + + drag_slider(&mut harness, "Balance"); + + let section = generator(&harness, effect).section.expect("on the section controls now"); + let defaults = SectionParameters::defaults(GeneratorKind::Position).unwrap(); + assert_ne!(section.balance, defaults.balance, "the drag set the balance"); + assert_eq!(SectionParameters { balance: defaults.balance, ..section }, defaults, "the other controls start at their defaults"); + assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -185,3 +246,15 @@ fn wear_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); } } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn section_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind})); + harness.run_steps(12); + harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); + } +} From 02bda17b9faaa77ddc270eb87a213bccda23edb5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 08/54] Generators: Light on the reference's angles, highlight and attenuation Light takes the reference app's controls: a horizontal and a vertical angle, each a dial beside an Angle slider in degrees, highlight glossiness and level, and light attenuation. It shades the world space normal (else the mesh's normal) towards the light and fades the side away from it across the position map (else the mesh's bounds); invert shades the far side instead. Both maps can read an image input instead, and Light has no global adjustments. Light generators saved before keep their level, softness, noise and direction and render as before; a light control moves one onto the new controls. --- crates/compose/src/eval.rs | 10 +- crates/compose/src/sections.rs | 83 +++++++++++++- crates/compose/tests/generator_sections.rs | 49 ++++++++- crates/core/src/layer.rs | 23 ++-- crates/core/src/layer/light_parameters.rs | 50 +++++++++ crates/core/src/lib.rs | 2 +- crates/engine/src/mask_cmds.rs | 64 ++++++++--- crates/engine/src/smart_masks.rs | 5 +- crates/engine/tests/it/generator_sections.rs | 33 +++++- crates/ui-egui/src/generator_panel.rs | 109 +++++++++++++++++-- crates/ui-egui/src/widgets.rs | 31 ++++-- crates/ui-egui/tests/it/generator_panel.rs | 34 +++++- 12 files changed, 439 insertions(+), 54 deletions(-) create mode 100644 crates/core/src/layer/light_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 896dab07..1e342957 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2057,10 +2057,10 @@ fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, .collect() } -/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset (the light controls invert their shading themselves) fn finish_generator(generator: &Generator, ramp: f32) -> f32 { let value = generator.applied_global().apply(ramp); - let value = if generator.invert { 1.0 - value } else { value }; + let value = if generator.invert && generator.light.is_none() { 1.0 - value } else { value }; let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; (value + offset).clamp(0.0, 1.0) } @@ -3327,6 +3327,12 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(wear) = wear_parameters(generator) { return self.wear_ramp(generator, &wear, curvature_sizes); } + if let Some(light) = &generator.light { + let normal = + self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let position = self.generator_input_color(generator, BakedMap::Position).map_or_else(|| self.bounds_position(), Vec3::from); + return sections::light_value(light, normal, position, generator.invert); + } if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, curvature_sizes); } diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index 2a6f9294..a9da83bc 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -1,6 +1,7 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators +//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators, and the Light generator's shading -use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, SectionParameters}; +use texturecraft_core::{AxisBlend, AxisLayer, Generator, GeneratorGlobal, GeneratorKind, LightParameters, SectionParameters}; +use texturecraft_geom::glam::Vec3; /// Gaussian sigma of the section blur per unit of its slider, in texels at [`GeneratorGlobal::BLUR_RESOLUTION`] const BLUR_SIGMA_PER_UNIT: f32 = 4.5; @@ -14,6 +15,15 @@ const FULL_CONTRAST_STEP_OFFSET: f32 = 4.6e-5; /// The order the axes combine in, as indices into [`SectionParameters::axes`]: top to bottom is the base, front to back goes last const AXIS_ORDER: [usize; 3] = [SectionParameters::TOP_TO_BOTTOM, SectionParameters::RIGHT_TO_LEFT, SectionParameters::FRONT_TO_BACK]; +/// Distance of a light-facing tangent plane from the centre of the position map's unit cube +const ATTENUATION_PLANE_OFFSET: f32 = 0.5; + +/// Light attenuation above which the falloff fades the whole mesh towards black instead of steepening +const ATTENUATION_STEEPEST: f32 = 0.5; + +/// Shortest decoded normal still given a direction +const MIN_NORMAL_LENGTH: f32 = 1e-6; + /// A map's three channels (0..1) combined by `axes`: each axis read from its channel, inverted, blended over the axes before it and weighted pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { AXIS_ORDER.iter().fold(0.0, |base, &index| { @@ -91,6 +101,35 @@ fn contrasted(value: f32, contrast: f32) -> f32 { ((value - (0.5 - half_range)) / (2.0 * half_range)).clamp(0.0, 1.0) } +/// The direction the light comes from: `horizontal` degrees around the up axis from -X towards +Z, `vertical` degrees above the horizon +pub(crate) fn light_direction(horizontal: f32, vertical: f32) -> Vec3 { + let (horizontal, vertical) = (horizontal.to_radians(), vertical.to_radians()); + Vec3::new(-vertical.cos() * horizontal.cos(), vertical.sin(), vertical.cos() * horizontal.sin()) +} + +/// The Light generator at a texel with world `normal` and `position` (0..1 across the mesh's bounds): lit, highlighted and faded with depth +pub(crate) fn light_value(light: &LightParameters, normal: Vec3, position: Vec3, invert: bool) -> f32 { + let direction = light_direction(light.horizontal, light.vertical); + let normal = if normal.length() > MIN_NORMAL_LENGTH { normal.normalize() } else { Vec3::Y }; + + // Glossiness 0 lights the half facing away too, 0.5 is a plain diffuse falloff + let glossiness = light.glossiness.clamp(*LightParameters::GLOSSINESS_RANGE.start(), *LightParameters::GLOSSINESS_RANGE.end()); + let threshold = 2.0 * glossiness - 1.0; + let diffuse = ((normal.dot(direction) - threshold) / (1.0 - threshold)).clamp(0.0, 1.0); + let highlight_level = light.highlight_level.clamp(0.0, 1.0); + let diffuse = if highlight_level >= 1.0 { if diffuse > 0.0 { 1.0 } else { 0.0 } } else { (diffuse / (1.0 - highlight_level)).clamp(0.0, 1.0) }; + + // Depth from the tangent plane facing the light + let depth = ATTENUATION_PLANE_OFFSET - (position - Vec3::splat(0.5)).dot(direction); + let attenuation = light.attenuation.clamp(0.0, 1.0); + let kept = if attenuation <= ATTENUATION_STEEPEST { + (1.0 - 2.0 * attenuation * depth).clamp(0.0, 1.0) + } else { + (1.0 - depth).clamp(0.0, 1.0) * (2.0 - 2.0 * attenuation) + }; + kept * if invert { 1.0 - diffuse } else { diffuse } +} + #[cfg(test)] mod tests { use super::*; @@ -196,4 +235,44 @@ mod tests { let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); } + + #[test] + fn light_angles_point_at_the_reference_axes() { + let close = |a: Vec3, b: Vec3| (a - b).length() < 1e-5; + assert!(close(light_direction(0.0, 0.0), Vec3::NEG_X)); + assert!(close(light_direction(90.0, 0.0), Vec3::Z)); + assert!(close(light_direction(180.0, 0.0), Vec3::X)); + assert!(close(light_direction(33.0, 90.0), Vec3::Y)); + } + + #[test] + fn light_lights_the_faces_towards_it() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, attenuation: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let middle = Vec3::splat(0.5); + assert_eq!(light_value(&light, Vec3::NEG_X, middle, false), 1.0); + assert_eq!(light_value(&light, Vec3::X, middle, false), 0.0); + assert!((light_value(&light, Vec3::new(-1.0, 1.0, 0.0), middle, false) - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-5, "a plain diffuse falloff"); + assert_eq!(light_value(&light, Vec3::X, middle, true), 1.0, "invert lights the far side"); + + let half_lambert = LightParameters { glossiness: 0.0, ..light }; + assert!((light_value(&half_lambert, Vec3::Y, middle, false) - 0.5).abs() < 1e-6, "glossiness 0 lights the side faces half"); + let highlighted = LightParameters { highlight_level: 0.5, ..light }; + assert!((light_value(&highlighted, Vec3::new(-1.0, 3.0, 0.0), middle, false) - 2.0 * 10f32.sqrt().recip()).abs() < 1e-5); + let saturated = LightParameters { highlight_level: 1.0, ..light }; + assert_eq!(light_value(&saturated, Vec3::new(-0.01, 1.0, 0.0), middle, false), 1.0, "any lit texel is white"); + } + + #[test] + fn attenuation_darkens_the_side_away_from_the_light() { + let light = LightParameters { horizontal: 0.0, vertical: 0.0, glossiness: 0.0, ..LightParameters::defaults(GeneratorKind::Direction).unwrap() }; + let near = light_value(&light, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false); + let far = light_value(&light, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false); + assert!((near - 0.5).abs() < 1e-6, "the face of the bounds towards the light keeps its value"); + assert!((far - 0.25).abs() < 1e-6, "attenuation 0.25 halves it across the bounds"); + + let none = LightParameters { attenuation: 0.0, ..light }; + assert_eq!(light_value(&none, Vec3::Y, Vec3::new(1.0, 0.5, 0.5), false), near); + let full = LightParameters { attenuation: 1.0, ..light }; + assert_eq!(light_value(&full, Vec3::Y, Vec3::new(0.0, 0.5, 0.5), false), 0.0, "attenuation 1 is black everywhere"); + } } diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 3a9b65c4..27693163 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -1,11 +1,11 @@ -//! The section controls of the Curvature, Ambient Occlusion, Position and World Space Normals generators on a sphere, beside their earlier model +//! The section and light controls of the Curvature, Ambient Occlusion, Position, World Space Normals and Light generators on a sphere, beside their earlier model use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, - SectionParameters, Source, TextureSet, + AxisBlend, BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LightParameters, Mask, MaskBackground, + Project, SectionParameters, Source, TextureSet, }; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -77,7 +77,7 @@ fn earlier_ramp(generator: &Generator, signal: f32) -> f32 { } fn earlier(kind: GeneratorKind) -> Generator { - Generator { section: None, ..Generator::new(kind) } + Generator { section: None, light: None, ..Generator::new(kind) } } fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters)) -> Generator { @@ -88,6 +88,14 @@ fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters) generator } +fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { + let mut generator = Generator::new(GeneratorKind::Direction); + let mut light = generator.light.unwrap(); + change(&mut light); + generator.light = Some(light); + generator +} + fn assert_close(actual: &[f32], expected: &[f32], what: &str) { for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); @@ -199,3 +207,36 @@ fn section_blur_spreads_occlusion_across_a_step() { fixture.baked = uniform_map(BakedMap::Position, 0.3); assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); } + +#[test] +fn light_angles_light_the_faces_towards_them() { + let mut fixture = fixture(); + let points = surface(&fixture); + let facing = |axis: Vec3| -> Vec<(u32, u32)> { points.iter().filter(|(_, _, nrm)| nrm.dot(axis) > 0.97).map(|point| point.0).collect() }; + + for (horizontal, vertical, towards) in [(0.0, 0.0, Vec3::NEG_X), (90.0, 0.0, Vec3::Z), (180.0, 0.0, Vec3::X), (0.0, 90.0, Vec3::Y)] { + let light = with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (horizontal, vertical, 0.0)); + let lit = mask(&mut fixture, light.clone(), &facing(towards)); + let dark = mask(&mut fixture, light, &facing(-towards)); + assert!(lit.iter().all(|value| *value > 0.95), "{horizontal}° {vertical}° lights {towards}: {lit:?}"); + assert!(dark.iter().all(|value| *value == 0.0), "{horizontal}° {vertical}° leaves {} dark: {dark:?}", -towards); + } + + let inverted = Generator { invert: true, ..with_light(|light| (light.horizontal, light.vertical, light.attenuation) = (0.0, 0.0, 0.0)) }; + assert!(mask(&mut fixture, inverted, &facing(Vec3::X)).iter().all(|value| *value > 0.95), "invert lights the far side"); +} + +#[test] +fn light_attenuation_darkens_the_side_away_from_the_light() { + let mut fixture = fixture(); + let sides: Vec<(u32, u32)> = surface(&fixture).iter().filter(|(_, _, nrm)| nrm.y > 0.97).map(|point| point.0).collect(); + let half_lit = + |attenuation: f32| with_light(|light| (light.horizontal, light.vertical, light.glossiness, light.attenuation) = (0.0, 0.0, 0.0, attenuation)); + + let kept = mask(&mut fixture, half_lit(0.0), &sides); + let attenuated = mask(&mut fixture, half_lit(0.5), &sides); + for (kept, attenuated) in kept.iter().zip(&attenuated) { + assert!((kept - 0.5).abs() < 0.15, "the top is about half lit from the side: {kept}"); + assert!(*attenuated < kept * 0.75, "halfway across the bounds, attenuation darkens it: {attenuated} vs {kept}"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 1e0f001d..fedcca8a 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod light_parameters; mod micro_detail; mod output_resolution; mod resolution_mode; @@ -44,6 +45,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; @@ -1000,7 +1002,7 @@ impl GeneratorKind { GeneratorKind::ThinAreas => &[BakedMap::Thickness], GeneratorKind::Position => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], - GeneratorKind::Direction => &[], + GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } } @@ -1057,6 +1059,9 @@ pub struct Generator { /// The section controls of Curvature, Ambient Occlusion, Position and World Space Normals (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub section: Option, + /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub light: Option, } impl Generator { @@ -1067,9 +1072,9 @@ impl Generator { pub const MIN_NOISE_SCALE: f32 = 0.01; pub const MAX_NOISE_SCALE: f32 = 1000.0; - /// The global blur, balance and contrast the generator applies: none on the wear controls, which have no such controls + /// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls pub fn applied_global(&self) -> GeneratorGlobal { - if self.wear.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + if self.wear.is_some() || self.light.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } } /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None @@ -1079,7 +1084,7 @@ impl Generator { /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { - self.wear.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear } pub fn new(kind: GeneratorKind) -> Generator { @@ -1112,6 +1117,7 @@ impl Generator { micro: None, wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), + light: LightParameters::defaults(kind), } } @@ -2345,12 +2351,13 @@ mod tests { } #[test] - fn generators_saved_before_their_section_controls_load_on_the_earlier_model() { - for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position] { + fn generators_saved_before_their_section_or_light_controls_load_on_the_earlier_model() { + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::Position, GeneratorKind::Direction] { let mut saved = serde_json::to_value(Generator::new(kind)).unwrap(); - assert!(saved.get("section").is_some(), "new {kind:?} generators have the reference's controls"); + let key = if kind == GeneratorKind::Direction { "light" } else { "section" }; + assert!(saved.get(key).is_some(), "new {kind:?} generators have the reference's controls"); - saved.as_object_mut().unwrap().remove("section"); + saved.as_object_mut().unwrap().remove(key); let loaded: Generator = serde_json::from_value(saved).unwrap(); assert!(loaded.on_earlier_model(), "{kind:?}: level, softness and noise keep driving it"); assert_eq!(loaded.applied_global(), loaded.global, "{kind:?} keeps its global adjustments"); diff --git a/crates/core/src/layer/light_parameters.rs b/crates/core/src/layer/light_parameters.rs new file mode 100644 index 00000000..5334675c --- /dev/null +++ b/crates/core/src/layer/light_parameters.rs @@ -0,0 +1,50 @@ +use serde::{Deserialize, Serialize}; + +use super::GeneratorKind; + +/// The Light generator's controls: where the light comes from, how its highlight spreads and how it fades across the mesh +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LightParameters { + /// Degrees around the up axis (0 from -X, 90 from +Z) + pub horizontal: f32, + /// Degrees above the horizon (90 from straight above) + pub vertical: f32, + /// How narrow the lit area is ([`LightParameters::GLOSSINESS_RANGE`]; 0.5 a plain diffuse falloff) + pub glossiness: f32, + /// How much the lit area is pushed to white (0..1; 1 every lit texel white) + pub highlight_level: f32, + /// How much the side away from the light darkens (0..1) + pub attenuation: f32, +} + +impl LightParameters { + pub const ANGLE_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + pub const GLOSSINESS_RANGE: std::ops::RangeInclusive = 0.0..=0.999; + + /// The reference app's defaults for `kind`, or None for kinds other than Light + pub fn defaults(kind: GeneratorKind) -> Option { + (kind == GeneratorKind::Direction).then_some(LightParameters { + horizontal: 90.0, + vertical: 45.0, + glossiness: 0.5, + highlight_level: 0.0, + attenuation: 0.25, + }) + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> LightParameters { + let defaults = LightParameters::defaults(GeneratorKind::Direction).unwrap_or(self); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + LightParameters { + horizontal: within(self.horizontal, defaults.horizontal, LightParameters::ANGLE_RANGE), + vertical: within(self.vertical, defaults.vertical, LightParameters::ANGLE_RANGE), + glossiness: within(self.glossiness, defaults.glossiness, LightParameters::GLOSSINESS_RANGE), + highlight_level: within(self.highlight_level, defaults.highlight_level, 0.0..=1.0), + attenuation: within(self.attenuation, defaults.attenuation, 0.0..=1.0), + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 222613cf..c5ff7ec3 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,7 +112,7 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 1b23275d..2ed442d1 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::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear and section controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -472,7 +472,7 @@ pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool { } } -/// The parameters that drive the earlier model of the kinds with section controls +/// The parameters that drive the earlier model of the kinds with section or light controls const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"]; /// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`] @@ -482,32 +482,41 @@ const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"]; const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; -/// The section controls and the axis keys `params` gives +/// The Light generator's controls +const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; + +/// The section controls, the axis keys and the light controls `params` gives fn given_new_model_keys(params: &Value) -> Vec { let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); - SECTION_KEYS.iter().map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + SECTION_KEYS.iter().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() } -/// The section controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model +/// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; let new_keys = given_new_model_keys(params); let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some()); - let Some(defaults) = SectionParameters::defaults(kind) else { + let section_defaults = SectionParameters::defaults(kind); + let light_defaults = LightParameters::defaults(kind); + if section_defaults.is_none() && light_defaults.is_none() { return match new_keys.first() { - Some(key) => { - Err(bad(command, format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position and World Space Normals have it", kind.label()))) - } + Some(key) => Err(bad( + command, + format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position, World Space Normals and Light have them", kind.label()), + )), None => Ok(()), }; - }; + } if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } if earlier { if !new_keys.is_empty() { - return Err(bad(command, "level, softness, noise, offset and direction drive the earlier model: give them or the section controls, not both")); + return Err(bad( + command, + "level, softness, noise, offset and direction drive the earlier model: give them or the section and light controls, not both", + )); } if kind == GeneratorKind::WorldSpaceNormals { return Err(bad( @@ -516,8 +525,13 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res )); } generator.section = None; + generator.light = None; return Ok(()); } + let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty()); + if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, "Light has no global blur, balance or contrast on its light controls")); + } if new_keys.is_empty() { return Ok(()); } @@ -528,8 +542,28 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = (defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale); (generator.offset, generator.direction) = (defaults.offset, defaults.direction); + if light_defaults.is_some() { + generator.global = defaults.global; + } + } + if let Some(defaults) = light_defaults { + let light = generator.light.get_or_insert(defaults); + for (key, value) in [ + ("lightHorizontal", &mut light.horizontal), + ("lightVertical", &mut light.vertical), + ("highlightGlossiness", &mut light.glossiness), + ("highlightLevel", &mut light.highlight_level), + ("lightAttenuation", &mut light.attenuation), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + *light = light.clamped(); + return Ok(()); } + let Some(defaults) = section_defaults else { return Ok(()) }; let mut section = generator.section_controls().unwrap_or(defaults); for (key, value) in [ ("sectionBlur", &mut section.blur), @@ -561,7 +595,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res Ok(()) } -/// Whether section control `key` changes a generator of `kind` +/// Whether section or light control `key` changes a generator of `kind` pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); match key { @@ -570,7 +604,7 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), _ if axis_key => SectionParameters::has_axes(kind), - _ => false, + _ => LIGHT_KEYS.contains(&key) && LightParameters::defaults(kind).is_some(), } } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index ceeb23cf..6b98e571 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -79,9 +79,9 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear and section controls) +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear, section and light controls) pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, light: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). @@ -95,6 +95,7 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, detail: None, wear: None, section: None, + light: None, ..Generator::new(kind) }) } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 02c68135..60676684 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -1,7 +1,7 @@ -//! The section controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise +//! The section and light controls through `effect.add.generator` and `effect.set`, beside the earlier level, softness and noise use serde_json::{Value, json}; -use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters}; +use texturecraft_engine::core::{AxisBlend, EffectKind, Generator, GeneratorKind, LayerId, LightParameters, SectionParameters}; use texturecraft_engine::mask_cmds::section_key_applies; use texturecraft_engine::{Session, execute}; @@ -31,6 +31,9 @@ fn new_generators_start_on_the_reference_controls() { let added = generator(&session, effect); assert_eq!(added.section, SectionParameters::defaults(added.kind), "{kind}"); } + let effect = add(&mut session, json!({"generator": "direction"})); + let light = generator(&session, effect); + assert_eq!(light.light, LightParameters::defaults(GeneratorKind::Direction)); assert_eq!(GeneratorKind::parse("World Space Normals"), Some(GeneratorKind::WorldSpaceNormals)); } @@ -72,6 +75,7 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { (occlusion, "sectionBrightness"), (occlusion, "rightLeftInvert"), (position, "sectionBlur"), + (position, "lightHorizontal"), (dirt, "sectionContrast"), ] { assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.5})).is_err(), "{key} on {effect}"); @@ -88,3 +92,28 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); } + +#[test] +fn light_takes_its_controls_and_refuses_the_global_ones() { + let mut session = session(); + let light = add(&mut session, json!({"generator": "direction"})); + execute(&mut session, "effect.set", &json!({"effect": light, "lightHorizontal": 400.0, "highlightGlossiness": 1.0, "invert": true})).unwrap(); + let edited = generator(&session, light); + let expected = LightParameters { + horizontal: 360.0, + glossiness: *LightParameters::GLOSSINESS_RANGE.end(), + ..LightParameters::defaults(GeneratorKind::Direction).unwrap() + }; + assert_eq!(edited.light, Some(expected)); + assert!(edited.invert); + + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "blur": 0.5})).is_err(), "Light has no global blur"); + assert!(execute(&mut session, "effect.set", &json!({"effect": light, "sectionInvert": true})).is_err()); + + let earlier = add(&mut session, json!({"generator": "direction", "level": 0.4, "blur": 0.3})); + assert_eq!(generator(&session, earlier).light, None, "the earlier model keeps its global adjustments"); + execute(&mut session, "effect.set", &json!({"effect": earlier, "lightVertical": 60.0})).unwrap(); + let moved = generator(&session, earlier); + assert_eq!(moved.light.map(|light| light.vertical), Some(60.0)); + assert_eq!(moved.global, Generator::new(GeneratorKind::Direction).global, "the light controls have no global adjustments"); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index e9df3bba..effda2d1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, MicroDetail, OutputResolution, ResolutionMode, SectionParameters, Source, - WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, WearParameters, }; use crate::TextureCraftApp; @@ -13,7 +13,7 @@ use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_be use crate::i18n::{baked_map_label, tr, trf}; use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; use crate::theme::{Tokens, caption}; -use crate::widgets::{combo, section, slider_edit}; +use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. const INPUT_TILE_SIZE: f32 = 32.0; @@ -23,6 +23,14 @@ const INPUT_TILE_ICON_SIZE: f32 = 16.0; /// Width of a False/True button, so the buttons line up under each other const TOGGLE_WIDTH: f32 = 136.0; +/// Edge of a light angle's dial, the width of its needle and the radius of its hub +const DIAL_SIZE: f32 = 36.0; +const DIAL_NEEDLE_WIDTH: f32 = 2.0; +const DIAL_HUB_RADIUS: f32 = 2.0; + +/// Closest to a dial's centre a pointer still turns it, so the angle is defined +const DIAL_DEAD_ZONE: f32 = 1.0; + /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -34,15 +42,20 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer if let Some(defaults) = WearParameters::defaults(generator.kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); + } else if let Some(light) = generator.light { + light_parameters(app, ui, id, Some(generator.invert), light); } else { global_adjustments(app, ui, id, generator); if generator.on_earlier_model() { ramp_parameters(app, ui, id, generator); } - // Saved before the section controls, a generator shows them at their defaults: editing one moves it onto them + // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); } + if let Some(defaults) = LightParameters::defaults(generator.kind) { + light_parameters(app, ui, id, None, defaults); + } } if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { micro_detail_properties(app, ui, id, generator.micro, layer); @@ -95,9 +108,9 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } -/// The inputs `generator` reads: none for Position on its earlier model, which reads the mesh itself +/// The inputs `generator` reads: none for Position and Light on their earlier model, which read the mesh itself fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { - let reads_geometry = generator.on_earlier_model() && generator.kind == GeneratorKind::Position; + let reads_geometry = generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction); if reads_geometry { &[] } else { generator.kind.inputs() } } @@ -322,10 +335,11 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); - let own = match (&defaults.wear, &defaults.section) { - (Some(wear), _) => wear_params(kind, wear), - (None, Some(section)) => merged(section_params(kind, section), global), - (None, None) => json!({ + let own = match (&defaults.wear, &defaults.section, &defaults.light) { + (Some(wear), _, _) => wear_params(kind, wear), + (None, _, Some(light)) => light_params(light), + (None, Some(section), None) => merged(section_params(kind, section), global), + (None, None, None) => json!({ "level": defaults.level, "softness": defaults.softness, "noise": defaults.noise_amount, @@ -436,6 +450,81 @@ fn axis_blend_label(blend: AxisBlend) -> &'static str { } } +/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) +fn light_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, invert: Option, shown: LightParameters) { + if let Some(mut invert) = invert + && true_false(ui, tr("Invert"), &mut invert) + { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + let mut edited = shown; + let mut edit = angle_row(ui, "generator_light_horizontal", tr("Horizontal angle"), &mut edited.horizontal); + edit = edit.or(angle_row(ui, "generator_light_vertical", tr("Vertical angle"), &mut edited.vertical)); + edit = edit.or(slider_edit(ui, tr("Highlight glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Highlight level"), &mut edited.highlight_level, 0.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Light attenuation"), &mut edited.attenuation, 0.0..=1.0, 2)); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); + } +} + +/// The `effect.set` params that set every light control to `light` +fn light_params(light: &LightParameters) -> Value { + json!({ + "lightHorizontal": light.horizontal, + "lightVertical": light.vertical, + "highlightGlossiness": light.glossiness, + "highlightLevel": light.highlight_level, + "lightAttenuation": light.attenuation, + }) +} + +/// A light angle in degrees: its name, then a dial beside an Angle slider; `Some(merge)` when either changes it +fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option { + ui.label(label); + ui.push_id(id, |ui| { + ui.horizontal(|ui| { + let dial = angle_dial(ui, label, degrees); + let slider = ui.vertical(|ui| slider_edit_with_suffix(ui, tr("Angle"), degrees, LightParameters::ANGLE_RANGE, 0, "°")).inner; + dial.or(slider) + }) + .inner + }) + .inner +} + +/// A round dial whose needle points at `degrees` (counterclockwise from the right); dragging it turns it, `Some(merge)` like [`slider_edit`] +fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); + let mut edit = None; + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() + { + let offset = pointer - rect.center(); + let turned = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); + if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { + *degrees = turned; + // Later frames of one drag share its undo step + edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); + } + } + if response.drag_stopped() || response.clicked() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + let shown = *degrees; + response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); + + let painter = ui.painter(); + let radius = DIAL_SIZE * 0.5 - 1.0; + painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); + let (sin, cos) = degrees.to_radians().sin_cos(); + let tip = rect.center() + egui::vec2(cos, -sin) * radius; + painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); + painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); + edit +} + /// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { let shown = detail.cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 126f7be5..809fc048 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,7 +19,7 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { - slider_inner(ui, label, value, range, decimals).0 + slider_inner(ui, label, value, range, decimals, "").0 } /// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) @@ -57,7 +57,12 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { /// true for the later changes of one drag, so the edit that applies them (with the command's /// `merge` param) continues the drag's first undo step. pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { - slider_inner(ui, label, value, range, decimals).1 + slider_inner(ui, label, value, range, decimals, "").1 +} + +/// [`slider_edit`] showing `suffix` after the value (a unit such as °), which a typed value may leave out +pub fn slider_edit_with_suffix(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> Option { + slider_inner(ui, label, value, range, decimals, suffix).1 } /// Least width of a slider's value field, wide enough for a short number @@ -75,12 +80,24 @@ const SLIDER_KNOB_RADIUS: f32 = 4.5; /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { + suffixed_value_header(ui, label, value, range, decimals, "") +} + +/// [`value_header`] showing `suffix` after the value, which a typed value may leave out +fn suffixed_value_header( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + decimals: usize, + suffix: &str, +) -> (egui::Id, Option) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() - .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}{suffix}"), font.clone(), tokens.text).size().x) .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui @@ -88,7 +105,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{value:.decimals$}"); + let shown = format!("{value:.decimals$}{suffix}"); // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); @@ -111,7 +128,7 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std if response.lost_focus() && !escape && text != shown - && let Ok(parsed) = text.trim().parse::() + && let Ok(parsed) = text.trim().strip_suffix(suffix).unwrap_or(text.trim()).trim_end().parse::() && parsed.is_finite() && parsed.clamp(minimum, maximum) != *value { @@ -127,10 +144,10 @@ pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std (field, edit) } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> (Response, Option) { let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); - let (field, mut edit) = value_header(ui, label, value, range, decimals); + let (field, mut edit) = suffixed_value_header(ui, label, value, range, decimals, suffix); let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index edf21484..6d49c460 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -153,6 +153,11 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ( + "direction", + &["Horizontal angle", "Vertical angle", "Highlight glossiness", "Highlight level", "Light attenuation"][..], + &["Global blur", "Level"][..], + ), ]; for (kind, shown, hidden) in rows { let (harness, _) = harness_with(false, json!({"generator": kind})); @@ -166,6 +171,8 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); assert_eq!(count(&harness, "Blending mode"), 3); + let (harness, _) = harness_with(false, json!({"generator": "direction"})); + assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } @@ -202,6 +209,31 @@ fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { assert_eq!(count(&harness, "Level"), 0, "the earlier rows are gone"); } +#[test] +fn the_light_dial_turns_towards_the_pointer() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction"})); + harness.get_by_role_and_label(Role::Slider, "Horizontal angle").scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_role_and_label(Role::Slider, "Horizontal angle").rect(); + let left = egui::pos2(rect.left() + 2.0, rect.center().y); + harness.drag_at(left); + harness.run_steps(2); + harness.drop_at(left); + harness.run_steps(3); + let horizontal = generator(&harness, effect).light.unwrap().horizontal; + assert!((horizontal - 180.0).abs() < 1.0, "a click left of the centre points the needle left: {horizontal}"); +} + +#[test] +fn restore_defaults_puts_a_light_back_on_its_defaults() { + let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Direction)); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -252,7 +284,7 @@ fn wear_panel_snapshots() { fn section_panel_snapshots() { let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); - for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction"] { let (mut harness, _) = harness_with(true, json!({"generator": kind})); harness.run_steps(12); harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); From 35ac5bc2ea563dc2fd8b25167ec2a2613a220ce6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 09/54] Generators: Position and Light read the mesh bounds, review fixes Position and Light read the mesh's own position across its bounds (an image in the Position input still overrides it): the baked Position map's normalisation is a bake setting, bounding sphere by default, which squeezes the reference's 0..1 per axis. The light dials start at 0 on the left and turn clockwise like the reference's. Commands refuse an input the generator does not read and `direction` on kinds that point no way; the detail size hint follows the sizes in use; tests check the exact blur radius, a blurred position and the axis dropdown by its section. --- crates/compose/src/eval.rs | 24 ++++++++++++-------- crates/compose/src/sections.rs | 4 ++-- crates/compose/tests/generator_sections.rs | 23 ++++++++++++------- crates/core/src/layer.rs | 12 ++++++++++ crates/engine/src/mask_cmds.rs | 9 ++++++-- crates/engine/tests/it/generator_sections.rs | 18 +++++++++++++++ crates/ui-egui/src/generator_panel.rs | 21 +++++++---------- crates/ui-egui/tests/it/generator_panel.rs | 16 ++++++++++--- 8 files changed, 89 insertions(+), 38 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1e342957..b0ae6b29 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2389,16 +2389,10 @@ fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { return wear::levels_in_use(generator.kind, &wear); } - let detail = curvature_detail_in_use(generator).as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); + let detail = generator.detail_in_use().as_ref().map(CurvatureDetail::blurred_sizes_in_use).unwrap_or_default(); std::array::from_fn(|level| detail.get(level).copied().unwrap_or(false)) } -/// The mode and detail sizes `generator` reads its curvature with: its own, the defaults on Curvature's section controls, else None -fn curvature_detail_in_use(generator: &Generator) -> Option { - let on_section = generator.kind == GeneratorKind::Curvature && generator.section_controls().is_some(); - generator.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) -} - /// The wear controls `generator` computes with: its own, Fiber Glass Edge Wear's defaults when it has none (it has no earlier model), else None fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) @@ -3330,7 +3324,7 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(light) = &generator.light { let normal = self.generator_input_color(generator, BakedMap::WorldNormal).map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); - let position = self.generator_input_color(generator, BakedMap::Position).map_or_else(|| self.bounds_position(), Vec3::from); + let position = Vec3::from(self.position_input(generator)); return sections::light_value(light, normal, position, generator.invert); } if let Some(section) = generator.section_controls() { @@ -3355,6 +3349,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + // World Space Normals always computes with its section controls: this arm only keeps the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; let signal = @@ -3399,7 +3394,7 @@ impl<'a, 'b> Texel<'a, 'b> { fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { match generator.kind { GeneratorKind::Curvature => { - let detail = curvature_detail_in_use(generator).unwrap_or_default(); + let detail = generator.detail_in_use().unwrap_or_default(); let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; let curvature = self.generator_input(generator, BakedMap::Curvature); let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); @@ -3407,17 +3402,26 @@ impl<'a, 'b> Texel<'a, 'b> { } GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), GeneratorKind::Position => { - let position = self.generator_input_color(generator, BakedMap::Position).unwrap_or_else(|| self.bounds_position().to_array()); + let position = self.position_input(generator); sections::axes_signal(position, §ion.axes) } GeneratorKind::WorldSpaceNormals => { let normal = self.generator_input_color(generator, BakedMap::WorldNormal).unwrap_or_else(|| (self.coords().nrm * 0.5 + 0.5).to_array()); sections::axes_signal(normal, §ion.axes) } + // Only the kinds with section controls reach here: this arm only keeps the match whole GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, } } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds: the baked Position map is not read, its normalisation is a bake setting + fn position_input(&mut self, generator: &Generator) -> [f32; 3] { + match generator.inputs.get(&BakedMap::Position) { + Some(source) => self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + None => self.bounds_position().to_array(), + } + } + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) fn bounds_position(&self) -> Vec3 { let (low, high) = self.inp.bounds; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index a9da83bc..bee4012d 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -232,8 +232,8 @@ mod tests { assert_eq!(blur_sigma(GeneratorKind::Position, §ion), 0.0); assert_eq!(blur_sigma(GeneratorKind::WorldSpaceNormals, §ion), 72.0); assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 0.0, ..section }, 2048), 0); - let radius = blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048) as f32; - assert!((radius * (radius + 1.0)).sqrt() - 4.5 < 0.6, "three boxes of radius {radius} spread like sigma 4.5"); + // Three boxes of radius 4 spread a texel with variance 4 × 5, the closest to sigma 4.5 squared + assert_eq!(blur_radius_at(GeneratorKind::AmbientOcclusion, &SectionParameters { blur: 1.0, ..section }, 2048), 4); } #[test] diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 27693163..0724f4e6 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -88,6 +88,12 @@ fn with_section(kind: GeneratorKind, change: impl FnOnce(&mut SectionParameters) generator } +/// `generator` with a uniform `value` plugged into its Position input +fn plugged(mut generator: Generator, value: f32) -> Generator { + generator.inputs.insert(BakedMap::Position, Source::Uniform([value; 3])); + generator +} + fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { let mut generator = Generator::new(GeneratorKind::Direction); let mut light = generator.light.unwrap(); @@ -159,7 +165,7 @@ fn world_space_normals_combine_the_axes_of_the_normal() { } #[test] -fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { +fn position_reads_the_mesh_bounds_unless_an_image_is_plugged_in() { let mut fixture = fixture(); let points = surface(&fixture); let texels: Vec<_> = points.iter().map(|point| point.0).collect(); @@ -168,7 +174,9 @@ fn position_reads_the_mesh_bounds_without_a_bake_and_the_baked_map_with_one() { assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "bounds"); fixture.baked = uniform_map(BakedMap::Position, 0.25); - let balanced = with_section(GeneratorKind::Position, |section| section.balance = 0.25); + assert_close(&mask(&mut fixture, Generator::new(GeneratorKind::Position), &texels), &expected, "a baked Position map is not read"); + + let balanced = plugged(with_section(GeneratorKind::Position, |section| section.balance = 0.25), 0.25); assert_close(&mask(&mut fixture, balanced, &texels), &vec![0.25f32.powf(0.2); texels.len()], "a power curve balance"); } @@ -183,10 +191,9 @@ fn occlusion_balance_is_linear_and_brightness_lerps() { let inverted = with_section(GeneratorKind::AmbientOcclusion, |section| section.invert = true); assert_close(&mask(&mut fixture, inverted, &texels), &vec![0.4; texels.len()], "section invert"); - fixture.baked = uniform_map(BakedMap::Position, 0.4); - let brighter = with_section(GeneratorKind::Position, |section| section.brightness = 0.5); + let brighter = plugged(with_section(GeneratorKind::Position, |section| section.brightness = 0.5), 0.4); assert_close(&mask(&mut fixture, brighter, &texels), &vec![0.7; texels.len()], "brightness 0.5 halves the way to white"); - let darker = with_section(GeneratorKind::Position, |section| section.brightness = -0.5); + let darker = plugged(with_section(GeneratorKind::Position, |section| section.brightness = -0.5), 0.4); assert_close(&mask(&mut fixture, darker, &texels), &vec![0.2; texels.len()], "brightness -0.5 halves the value"); } @@ -203,9 +210,9 @@ fn section_blur_spreads_occlusion_across_a_step() { let blurred = mask(&mut fixture, with_section(GeneratorKind::AmbientOcclusion, |section| section.blur = 16.0), &row); assert!(blurred.iter().all(|value| *value > 0.05 && *value < 0.95), "blurred across the step: {blurred:?}"); - let position = with_section(GeneratorKind::Position, |section| section.blur = 16.0); - fixture.baked = uniform_map(BakedMap::Position, 0.3); - assert_close(&mask(&mut fixture, position, &row), &vec![0.3; row.len()], "position has no section blur"); + let sharp_position = mask(&mut fixture, Generator::new(GeneratorKind::Position), &row); + let blurred_position = mask(&mut fixture, with_section(GeneratorKind::Position, |section| section.blur = 16.0), &row); + assert_close(&blurred_position, &sharp_position, "position has no section blur"); } #[test] diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index fedcca8a..663efd1f 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1082,6 +1082,18 @@ impl Generator { self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None + pub fn detail_in_use(&self) -> Option { + let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); + self.detail.clone().or_else(|| on_section.then(CurvatureDetail::default)) + } + + /// The mesh maps the generator reads: none for Position and Light on the earlier model, which read the mesh itself + pub fn inputs_in_use(&self) -> &'static [BakedMap] { + let reads_geometry = self.on_earlier_model() && matches!(self.kind, GeneratorKind::Position | GeneratorKind::Direction); + if reads_geometry { &[] } else { self.kind.inputs() } + } + /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2ed442d1..19a61f09 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -511,6 +511,11 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } + let reads_direction = matches!(kind, GeneratorKind::Position | GeneratorKind::Direction); + if params.get("direction").is_some() && !reads_direction { + return Err(bad(command, format!("{} has no `direction`: only Position and Light point one way", kind.label()))); + } + if earlier { if !new_keys.is_empty() { return Err(bad( @@ -1056,8 +1061,8 @@ fn set(session: &mut Session, params: &Value) -> Result { generator.micro = micro; } if let Some((map, source)) = input { - if !generator.kind.inputs().contains(&map) { - return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + if !generator.inputs_in_use().contains(&map) { + return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); } match source { diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 60676684..6a639aaf 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -89,6 +89,10 @@ fn keys_a_kind_lacks_or_both_models_at_once_are_refused() { assert!(execute(&mut session, "effect.set", &json!({"effect": position, "topBottomBlend": "overlay"})).is_err()); assert_eq!(generator(&session, position).section, SectionParameters::defaults(GeneratorKind::Position), "a refused edit changes nothing"); + let direction = json!([1.0, 0.0, 0.0]); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "direction": direction})).is_err(), "Curvature points no way"); + assert!(execute(&mut session, "effect.set", &json!({"effect": occlusion, "direction": direction})).is_err(), "nor does Ambient Occlusion"); + assert!(!section_key_applies(GeneratorKind::Position, "sectionBlur")); assert!(section_key_applies(GeneratorKind::WorldSpaceNormals, "rightLeftBlend")); } @@ -117,3 +121,17 @@ fn light_takes_its_controls_and_refuses_the_global_ones() { assert_eq!(moved.light.map(|light| light.vertical), Some(60.0)); assert_eq!(moved.global, Generator::new(GeneratorKind::Direction).global, "the light controls have no global adjustments"); } + +/// Position and Light read the mesh itself on the earlier model, so they take no Position input there +#[test] +fn an_input_the_generator_does_not_read_is_refused() { + let mut session = session(); + let earlier = add(&mut session, json!({"generator": "position", "level": 0.4})); + let plug = |effect: u64| json!({"effect": effect, "input": "position", "inputValue": 0.5}); + assert!(execute(&mut session, "effect.set", &plug(earlier)).is_err()); + assert!(generator(&session, earlier).inputs.is_empty()); + + let on_section = add(&mut session, json!({"generator": "position"})); + execute(&mut session, "effect.set", &plug(on_section)).unwrap(); + assert_eq!(generator(&session, on_section).inputs.len(), 1); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index effda2d1..7c6f7258 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -68,10 +68,10 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer }); }); }); - if !inputs_in_use(generator).is_empty() { + if !generator.inputs_in_use().is_empty() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - for map in inputs_in_use(generator) { - input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + for map in generator.inputs_in_use() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail_in_use().is_some()); } }); } @@ -108,12 +108,6 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr } } -/// The inputs `generator` reads: none for Position and Light on their earlier model, which read the mesh itself -fn inputs_in_use(generator: &Generator) -> &'static [BakedMap] { - let reads_geometry = generator.on_earlier_model() && matches!(generator.kind, GeneratorKind::Position | GeneratorKind::Direction); - if reads_geometry { &[] } else { generator.kind.inputs() } -} - /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -493,7 +487,7 @@ fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option Option { let tokens = Tokens::get(ui.ctx()); let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); @@ -502,7 +496,7 @@ fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { && let Some(pointer) = response.interact_pointer_pos() { let offset = pointer - rect.center(); - let turned = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); + let turned = (-offset.y).atan2(-offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { *degrees = turned; // Later frames of one drag share its undo step @@ -516,10 +510,11 @@ fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); let painter = ui.painter(); - let radius = DIAL_SIZE * 0.5 - 1.0; + // The rim's stroke stays inside the dial + let radius = (DIAL_SIZE - DIAL_NEEDLE_WIDTH) * 0.5; painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); let (sin, cos) = degrees.to_radians().sin_cos(); - let tip = rect.center() + egui::vec2(cos, -sin) * radius; + let tip = rect.center() + egui::vec2(-cos, -sin) * radius; painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); edit diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 6d49c460..513ca72b 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -171,12 +171,22 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); assert_eq!(count(&harness, "Blending mode"), 3); + for axis in ["Right to left", "Top to bottom", "Front to back"] { + assert_eq!(count(&harness, axis), 2, "{axis}: a section heading and its weight slider"); + } let (harness, _) = harness_with(false, json!({"generator": "direction"})); assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } +/// The blending mode dropdown in the Front to back section: the first dropdown below its heading, the topmost "Front to back" +fn front_to_back_dropdown<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let heading = harness.query_all_by_label("Front to back").map(|node| node.rect().top()).fold(f32::INFINITY, f32::min); + let below = harness.get_all_by_role(Role::ComboBox).filter(|node| node.rect().top() > heading); + below.min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + #[test] fn each_axis_has_its_own_blending_mode_dropdown() { let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); @@ -184,9 +194,9 @@ fn each_axis_has_its_own_blending_mode_dropdown() { harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() }; assert_eq!(added(&harness), 3); - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().scroll_to_me(); + front_to_back_dropdown(&harness).scroll_to_me(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).nth(2).unwrap().click(); + front_to_back_dropdown(&harness).click(); harness.run_steps(2); harness.get_by_label("Multiply").click(); harness.run_steps(3); @@ -221,7 +231,7 @@ fn the_light_dial_turns_towards_the_pointer() { harness.drop_at(left); harness.run_steps(3); let horizontal = generator(&harness, effect).light.unwrap().horizontal; - assert!((horizontal - 180.0).abs() < 1.0, "a click left of the centre points the needle left: {horizontal}"); + assert!(!(1.0..=359.0).contains(&horizontal), "0 is on the left, as in the reference: {horizontal}"); } #[test] From 38f2f66719ba5185858060a7222a0bb5a6e7dd36 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 10/54] Generators: the offset belongs to the earlier controls Like level, softness and noise, the offset keeps a generator on its earlier controls, and moving onto the wear, section or light controls drops it, so no unseen shift stays under controls without an Offset. --- crates/engine/tests/it/generator_sections.rs | 19 +++++++++++++++++++ crates/engine/tests/it/generator_wear.rs | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index 6a639aaf..ed9276f0 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -135,3 +135,22 @@ fn an_input_the_generator_does_not_read_is_refused() { execute(&mut session, "effect.set", &plug(on_section)).unwrap(); assert_eq!(generator(&session, on_section).inputs.len(), 1); } + +#[test] +fn the_offset_belongs_to_the_earlier_model() { + let mut session = session(); + for (kind, control) in [("position", json!({"sectionBalance": 0.3})), ("direction", json!({"highlightLevel": 0.5}))] { + let effect = add(&mut session, json!({"generator": kind, "offset": 0.4})); + assert_eq!(generator(&session, effect).offset, 0.4, "{kind}: the offset keeps it on the earlier model"); + + let mut edit = control.clone(); + edit["effect"] = json!(effect); + execute(&mut session, "effect.set", &edit).unwrap(); + assert_eq!(generator(&session, effect).offset, 0.0, "{kind}: moving onto the reference controls drops the unseen offset"); + + let mut both = control; + both["effect"] = json!(effect); + both["offset"] = json!(0.2); + assert!(execute(&mut session, "effect.set", &both).is_err(), "{kind}: offset and the reference controls at once are refused"); + } +} diff --git a/crates/engine/tests/it/generator_wear.rs b/crates/engine/tests/it/generator_wear.rs index c194dfe4..5d8bf639 100644 --- a/crates/engine/tests/it/generator_wear.rs +++ b/crates/engine/tests/it/generator_wear.rs @@ -91,3 +91,15 @@ fn mode_and_sizes_keep_edge_wear_on_the_earlier_model_where_they_apply() { execute(&mut session, "effect.set", &json!({"effect": effect, "blur": 0.5})).unwrap(); assert_eq!(generator(&session, effect).global.blur, 0.5, "the earlier model keeps its global blur"); } + +#[test] +fn a_wear_control_drops_the_earlier_models_offset() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "edgeWear", "offset": 0.4})); + assert_eq!(generator(&session, effect).wear, None, "the offset keeps it on the earlier model"); + assert_eq!(generator(&session, effect).offset, 0.4); + + execute(&mut session, "effect.set", &json!({"effect": effect, "wearLevel": 0.6})).unwrap(); + assert_eq!(generator(&session, effect).offset, 0.0, "on the wear controls the offset would shift the result unseen"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "offset": 0.2, "wearLevel": 0.5})).is_err(), "not both at once"); +} From 922c8e8a7adf644cf600ddec2e5c40107e51db37 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:57:56 +0000 Subject: [PATCH 11/54] Generators: Use Texture on Curvature, Ambient Occlusion, Position and World Space Normals A texture blends over the section-adjusted signal before the global controls: read in UV (scaled about the centre) or triplanar, turned gray by one of eight conversions, inverted, contrasted and brightened, then blended by one of ten modes at its opacity. Its image is the texture input of effect.set; an empty slot reads black. The panel shows Use texture at the end of Parameters, the texture's rows once it is on, and its slot first in Image inputs. --- crates/compose/src/below.rs | 2 +- crates/compose/src/eval.rs | 58 ++++- crates/compose/src/lib.rs | 1 + crates/compose/src/texture_layer.rs | 150 +++++++++++++ crates/compose/tests/cache_and_instances.rs | 38 ++++ crates/compose/tests/generator_texture.rs | 218 +++++++++++++++++++ crates/core/src/layer.rs | 26 ++- crates/core/src/layer/generator_grayscale.rs | 81 +++++++ crates/core/src/layer/texture_blend.rs | 80 +++++++ crates/core/src/layer/texture_layer.rs | 76 +++++++ crates/core/src/lib.rs | 4 +- crates/engine/src/inspect.rs | 3 + crates/engine/src/mask_cmds.rs | 119 ++++++++-- crates/engine/tests/it/generator_texture.rs | 106 +++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 180 ++++++++++++--- crates/ui-egui/tests/it/generator_panel.rs | 57 +++++ 17 files changed, 1134 insertions(+), 66 deletions(-) create mode 100644 crates/compose/src/texture_layer.rs create mode 100644 crates/compose/tests/generator_texture.rs create mode 100644 crates/core/src/layer/generator_grayscale.rs create mode 100644 crates/core/src/layer/texture_blend.rs create mode 100644 crates/core/src/layer/texture_layer.rs create mode 100644 crates/engine/tests/it/generator_texture.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index cdca3b83..dd440224 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -165,7 +165,7 @@ impl StackKey { match &effect.kind { EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), - EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.sources().flat_map(Source::images).for_each(&mut record_image_name), EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b0ae6b29..2b0500a7 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -40,6 +40,7 @@ use crate::sections; use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; +use crate::texture_layer; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -1657,7 +1658,7 @@ fn filter_region( _ => None, }; let components = match job { - Job::Mask(_) if generator.is_some() => 2, + Job::Mask(_) if generator.is_some() => GENERATOR_STAGE_COMPONENTS, Job::Mask(_) => 1, Job::Content(_) => 4, }; @@ -1727,7 +1728,8 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); - [texel.mask(mask_stack), ramp, 0.0, 0.0] + let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); + [texel.mask(mask_stack), ramp, texture, 0.0] } (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], @@ -1943,7 +1945,13 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +/// What a generator's texture reads with nothing in its slot +const EMPTY_TEXTURE_SLOT: Source = Source::Uniform([0.0; 3]); + +/// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray +const GENERATOR_STAGE_COMPONENTS: usize = 3; + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp, texture gray) per texel, sizes in texels per side fn generator_region( generator: &Generator, blend: BlendMode, @@ -1954,7 +1962,7 @@ fn generator_region( (uv_tile, texture_set): (u32, u32), ) -> Vec { let (columns, rows) = (width as usize, height as usize); - let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + let mut ramps: Vec = stack.par_chunks(GENERATOR_STAGE_COMPONENTS).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); // Coarser than the UV tile: averaged over cells, then the blur around them let cell = generator.resolution.cell(uv_tile, texture_set) as usize; @@ -1968,11 +1976,18 @@ fn generator_region( ramps.par_iter_mut().for_each(|signal| *signal = sections::adjusted(generator.kind, §ion, *signal)); } + // The texture blends over the adjusted signal, before the global blur + if let Some(texture) = generator.texture_in_use() { + ramps.par_iter_mut().zip(stack.par_chunks(GENERATOR_STAGE_COMPONENTS)).for_each(|(signal, texel)| { + *signal = texture_layer::blended_over(texture, *signal, texel.get(2).copied().unwrap_or(0.0)); + }); + } + blur_over_cover(&mut ramps, cover, (columns, rows), generator.applied_global().blur_radius_at(uv_tile).round() as usize); // Finished and blended over the stack below, like the generator effect itself stack - .par_chunks(2) + .par_chunks(GENERATOR_STAGE_COMPONENTS) .zip(ramps.par_iter()) .map(|(texel, ramp)| { let below = texel.first().copied().unwrap_or(0.0); @@ -3467,7 +3482,38 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let ramp = self.generator_ramp(generator, curvature_sizes); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); - finish_generator(generator, adjusted) + let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { + (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), + _ => adjusted, + }; + finish_generator(generator, textured) + } + + /// The gray of the generator's texture at this texel (None when it blends no texture) + fn generator_texture(&mut self, generator: &Generator) -> Option { + let texture = generator.texture_in_use()?; + let rgb = match texture.source.as_ref().unwrap_or(&EMPTY_TEXTURE_SLOT) { + Source::Image { name, .. } => { + let image = self.inp.images.get(name)?.clone(); + let read = |coordinates: Vec2| { + let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); + Vec3::new(red, green, blue) + }; + if texture.triplanar { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(texture, normal); + let coordinates = texture_layer::triplanar_coordinates(texture, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight).to_array() + } else { + read(texture_layer::uv_coordinates(texture, self.coords().uv)).to_array() + } + } + // A value or an anchor reads the same wherever it is projected + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + Some(texture_layer::texture_gray(texture, rgb)) } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a2369743..3c921ff9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -42,6 +42,7 @@ mod slope_texel; mod soft_box; pub mod solo; pub mod store; +mod texture_layer; pub mod thumb; pub mod tile_length; mod tile_pattern; diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs new file mode 100644 index 00000000..95c40fa3 --- /dev/null +++ b/crates/compose/src/texture_layer.rs @@ -0,0 +1,150 @@ +//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal + +use texturecraft_core::{TextureBlend, TextureLayer}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +/// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube +const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; + +/// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly +const MIN_NORMAL_COMPONENT: f32 = 1e-6; + +/// Where the texture is read in UV: scaled about the centre of the UV square +pub(crate) fn uv_coordinates(texture: &TextureLayer, uv: Vec2) -> Vec2 { + (uv - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5) +} + +/// Where the texture is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1), scaled about their centre +pub(crate) fn triplanar_coordinates(texture: &TextureLayer, position: Vec3) -> [Vec2; 3] { + let scaled = |u: f32, v: f32| (Vec2::new(u, v) - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5); + [scaled(-position.z, position.y), scaled(position.x, position.z), scaled(position.x, position.y)] +} + +/// How much each projection (facing X, Y and Z) counts for a surface facing `normal`, summing to 1 +pub(crate) fn triplanar_weights(texture: &TextureLayer, normal: Vec3) -> [f32; 3] { + let contrast = texture.triplanar_contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); + let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER); + let facing = normal.abs(); + let largest = facing.max_element().max(MIN_NORMAL_COMPONENT); + let weights = (facing / largest).powf(sharpness); + let total = weights.x + weights.y + weights.z; + if total > 0.0 { (weights / total).to_array() } else { [1.0 / 3.0; 3] } +} + +/// The texture's gray from its color: converted, inverted, contrasted, then brightened +pub(crate) fn texture_gray(texture: &TextureLayer, rgb: [f32; 3]) -> f32 { + let gray = texture.grayscale.gray(rgb).clamp(0.0, 1.0); + let gray = if texture.invert { 1.0 - gray } else { gray }; + + let contrast = texture.contrast.clamp(-1.0, 1.0); + let gray = if contrast > 0.0 { + let range = (1.0 - contrast).max(f32::EPSILON); + ((gray - 0.5) / range + 0.5).clamp(0.0, 1.0) + } else { + (gray - 0.5) * (1.0 + contrast) + 0.5 + }; + + let brightness = texture.brightness.clamp(-1.0, 1.0); + if brightness > 0.0 { gray + brightness * (1.0 - gray) } else { gray * (1.0 + brightness) } +} + +/// `gray` (the texture) blended over `signal` by the texture's blending mode and opacity +pub(crate) fn blended_over(texture: &TextureLayer, signal: f32, gray: f32) -> f32 { + let blend = match texture.blend { + TextureBlend::Normal => gray, + TextureBlend::Add => signal + gray, + TextureBlend::Subtract => signal - gray, + TextureBlend::Multiply => signal * gray, + TextureBlend::AddSub => signal + 2.0 * gray - 1.0, + TextureBlend::Max => signal.max(gray), + TextureBlend::Min => signal.min(gray), + TextureBlend::Overlay => { + if signal < 0.5 { + 2.0 * signal * gray + } else { + 1.0 - 2.0 * (1.0 - signal) * (1.0 - gray) + } + } + TextureBlend::Screen => 1.0 - (1.0 - signal) * (1.0 - gray), + TextureBlend::SoftLight => { + if gray < 0.5 { + 2.0 * signal * gray + signal * signal * (1.0 - 2.0 * gray) + } else { + 2.0 * signal * (1.0 - gray) + signal.max(0.0).sqrt() * (2.0 * gray - 1.0) + } + } + }; + let opacity = texture.opacity.clamp(0.0, 1.0); + (signal + (blend - signal) * opacity).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::GeneratorGrayscale; + + fn texture() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, ..TextureLayer::default() } + } + + #[test] + fn overlay_at_full_opacity_darkens_darks_and_lightens_lights() { + let texture = texture(); + assert!((blended_over(&texture, 0.25, 0.5) - 0.25).abs() < 1e-6, "mid gray leaves a dark signal unchanged"); + assert!(blended_over(&texture, 0.25, 0.2) < 0.25); + assert!(blended_over(&texture, 0.75, 0.8) > 0.75); + } + + #[test] + fn opacity_zero_leaves_the_signal() { + let texture = TextureLayer { opacity: 0.0, blend: TextureBlend::Normal, ..texture() }; + assert_eq!(blended_over(&texture, 0.3, 0.9), 0.3); + } + + #[test] + fn every_blend_stays_in_range() { + for blend in TextureBlend::ALL { + let texture = TextureLayer { blend, ..texture() }; + for signal in [0.0, 0.3, 0.5, 1.0] { + for gray in [0.0, 0.4, 1.0] { + let value = blended_over(&texture, signal, gray); + assert!((0.0..=1.0).contains(&value), "{blend:?} {signal} {gray} -> {value}"); + } + } + } + } + + #[test] + fn gray_is_converted_then_inverted_contrasted_and_brightened() { + let red = [1.0, 0.0, 0.0]; + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Red, ..texture() }, red), 1.0); + assert_eq!(texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Green, ..texture() }, red), 0.0); + assert!((texture_gray(&TextureLayer { grayscale: GeneratorGrayscale::Desaturation, ..texture() }, red) - 0.5).abs() < 1e-6); + let inverted = TextureLayer { grayscale: GeneratorGrayscale::Red, invert: true, ..texture() }; + assert_eq!(texture_gray(&inverted, red), 0.0); + let contrasted = TextureLayer { contrast: 0.5, ..texture() }; + assert!((texture_gray(&contrasted, [0.6; 3]) - 0.7).abs() < 1e-5, "contrast 0.5 doubles the distance from the middle"); + let flattened = TextureLayer { contrast: -1.0, ..texture() }; + assert!((texture_gray(&flattened, [0.9; 3]) - 0.5).abs() < 1e-6, "contrast −1 is flat gray"); + let brightened = TextureLayer { brightness: 0.5, ..texture() }; + assert!((texture_gray(&brightened, [0.4; 3]) - 0.7).abs() < 1e-6); + } + + #[test] + fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() { + let along_y = triplanar_weights(&texture(), Vec3::Y); + assert!((along_y[1] - 1.0).abs() < 1e-6); + let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize(); + let soft = triplanar_weights(&TextureLayer { triplanar_contrast: 0.001, ..texture() }, diagonal); + let hard = triplanar_weights(&TextureLayer { triplanar_contrast: 0.9, ..texture() }, diagonal); + assert!(hard[0] > soft[0] && hard[1] < soft[1]); + assert!((soft.iter().sum::() - 1.0).abs() < 1e-5); + } + + #[test] + fn scale_is_about_the_centre() { + let texture = TextureLayer { scale: 2.0, ..texture() }; + assert_eq!(uv_coordinates(&texture, Vec2::splat(0.5)), Vec2::splat(0.5)); + assert_eq!(uv_coordinates(&texture, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); + } +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 7a96a5f9..dac833d1 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -1270,3 +1270,41 @@ fn a_folder_thumbnail_reads_compare_inputs_from_its_backdrop() { assert!(thumbnail.rgba[center] > thumbnail.rgba[center + 2], "visible red child"); } + +#[test] +fn replacing_a_generator_texture_image_invalidates_the_cached_stack() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + use texturecraft_core::{TextureBlend, TextureLayer}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(texture), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); + let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask)); + let stack = &mut fixture.project.texture_sets[0].stack; + stack.retain(|id| *id != textured); + stack.insert(0, textured); + + let image_with_value = |value| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false)); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (stage, value) in [("dark", 0.1), ("light", 0.9)] { + images.insert("grunge".into(), image_with_value(value)); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: a new texture image drops the tiles cached below the hot layer"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs new file mode 100644 index 00000000..3800ccb6 --- /dev/null +++ b/crates/compose/tests/generator_texture.rs @@ -0,0 +1,218 @@ +//! A generator's texture (Use Texture) on a sphere: read in UV or triplanar, turned gray, blended over the signal before the global controls + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorGrayscale, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + SectionParameters, Source, TextureBlend, TextureLayer, TextureSet, +}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// How far a mask value may sit from the expected one +const TOLERANCE: f32 = 1e-3; + +/// The ambient occlusion every texel of the sphere reads +const OCCLUSION: f32 = 0.3; + +/// Width of the split image: its left half black, its right half white +const SPLIT_WIDTH: u32 = 64; + +/// How far from a split's edge (in UV) a texel must sit to read one side only +const SPLIT_MARGIN: f32 = 0.05; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// A unit sphere with a white fill layer, uniform occlusion and the images `flat` (one color) and `split` (black left, white right) +fn fixture(flat: [f32; 3]) -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![OCCLUSION; (RES * RES) as usize]))].into() }; + + let [red, green, blue] = flat; + let flat = ImageRes::new(4, 4, vec![[red, green, blue, 1.0]; 16], false); + let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }; + let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false); + let images = [("flat".to_string(), Arc::new(flat)), ("split".to_string(), Arc::new(split))].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// A covered texel with its UV, world position and normal +struct SurfacePoint { + texel: (u32, u32), + uv: [f32; 2], + position: Vec3, + normal: Vec3, +} + +/// Every covered texel +fn surface(fixture: &Fixture) -> Vec { + (0..RES * RES) + .filter_map(|index| { + let texel = (index % RES, index / RES); + let uv = [(texel.0 as f32 + 0.5) / RES as f32, (texel.1 as f32 + 0.5) / RES as f32]; + fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| SurfacePoint { texel, uv, position: surface.pos, normal: surface.nrm }) + }) + .collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// Ambient Occlusion on its section controls with `texture` reading image `image` +fn occlusion_with(image: &str, texture: TextureLayer) -> Generator { + Generator { texture: Some(TextureLayer { source: Some(Source::image(image)), ..texture }), ..Generator::new(GeneratorKind::AmbientOcclusion) } +} + +/// A texture turned on at full opacity, replacing the signal +fn replacing() -> TextureLayer { + TextureLayer { enabled: true, opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() } +} + +fn assert_all(actual: &[f32], expected: f32, what: &str) { + for (index, actual) in actual.iter().enumerate() { + assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); + } +} + +#[test] +fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { enabled: false, ..replacing() }), &texels), OCCLUSION, "turned off"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer { opacity: 0.0, ..replacing() }), &texels), OCCLUSION, "opacity 0"); + assert_all(&mask(&mut fixture, occlusion_with("flat", TextureLayer::default()), &texels), OCCLUSION, "the reference's defaults"); +} + +#[test] +fn an_empty_texture_slot_blends_black() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let empty = Generator { texture: Some(TextureLayer { opacity: 0.5, ..replacing() }), ..Generator::new(GeneratorKind::AmbientOcclusion) }; + assert_all(&mask(&mut fixture, empty, &texels), OCCLUSION * 0.5, "half way to black"); +} + +#[test] +fn a_texture_needs_the_section_controls() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let earlier = Generator { section: None, global: Default::default(), ..occlusion_with("flat", replacing()) }; + let without = Generator { texture: None, ..earlier.clone() }; + assert_eq!(mask(&mut fixture, earlier, &texels), mask(&mut fixture, without, &texels)); +} + +#[test] +fn the_texture_turns_gray_by_its_conversion() { + let mut fixture = fixture([1.0, 0.25, 0.0]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + for (grayscale, expected) in [ + (GeneratorGrayscale::Average, 1.25 / 3.0), + (GeneratorGrayscale::Red, 1.0), + (GeneratorGrayscale::Green, 0.25), + (GeneratorGrayscale::Desaturation, 0.5), + (GeneratorGrayscale::Luma, 0.299 + 0.587 * 0.25), + ] { + let generator = occlusion_with("flat", TextureLayer { grayscale, ..replacing() }); + assert_all(&mask(&mut fixture, generator, &texels), expected, &format!("{grayscale:?}")); + } +} + +#[test] +fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() { + let mut fixture = fixture([0.4; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let generator = occlusion_with("flat", TextureLayer { blend: TextureBlend::Overlay, opacity: 0.5, ..replacing() }); + let overlay = 2.0 * OCCLUSION * 0.4; + assert_all(&mask(&mut fixture, generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity"); +} + +#[test] +fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + + let mut section_inverted = occlusion_with("flat", replacing()); + section_inverted.section = Some(SectionParameters { invert: true, ..section_inverted.section.unwrap() }); + assert_all(&mask(&mut fixture, section_inverted, &texels), 0.6, "the texture replaces the inverted section"); + + let globally_inverted = Generator { invert: true, ..occlusion_with("flat", replacing()) }; + assert_all(&mask(&mut fixture, globally_inverted, &texels), 0.4, "the global invert flips the texture"); + + let mut blurred = occlusion_with("flat", replacing()); + blurred.section = Some(SectionParameters { blur: 2.0, ..blurred.section.unwrap() }); + assert_all(&mask(&mut fixture, blurred, &texels), 0.6, "with the section blur (computed over a region)"); +} + +#[test] +fn uv_scale_repeats_the_texture_about_the_centre() { + let mut fixture = fixture([0.0; 3]); + let points = surface(&fixture); + let side = |u: f32| (u.rem_euclid(1.0) >= 0.5) as u8 as f32; + for scale in [1.0, 2.0, 3.0] { + let read_at = |u: f32| (u - 0.5) * scale + 0.5; + let clear: Vec<_> = points + .iter() + .filter(|point| { + let u = read_at(point.uv[0]).rem_euclid(1.0); + [0.0, 0.5, 1.0].iter().all(|edge| (u - edge).abs() > SPLIT_MARGIN * scale) + }) + .collect(); + let texels: Vec<_> = clear.iter().map(|point| point.texel).collect(); + let values = mask(&mut fixture, occlusion_with("split", TextureLayer { scale, ..replacing() }), &texels); + for (point, value) in clear.iter().zip(values) { + let expected = side(read_at(point.uv[0])); + assert!((value - expected).abs() < TOLERANCE, "scale {scale} at u {}: {value}, expected {expected}", point.uv[0]); + } + } +} + +#[test] +fn triplanar_reads_the_top_from_the_plane_facing_up() { + let mut fixture = fixture([0.0; 3]); + let (low, high) = fixture.mesh.bounds(); + let across = |position: Vec3| (position.x - low.x) / (high.x - low.x); + let top: Vec<_> = surface(&fixture).into_iter().filter(|point| point.normal.y > 0.95 && (across(point.position) - 0.5).abs() > SPLIT_MARGIN).collect(); + assert!(!top.is_empty()); + + let texels: Vec<_> = top.iter().map(|point| point.texel).collect(); + let sharp = TextureLayer { triplanar: true, triplanar_contrast: 1.0, ..replacing() }; + let values = mask(&mut fixture, occlusion_with("split", sharp), &texels); + for (point, value) in top.iter().zip(values) { + let expected = if across(point.position) >= 0.5 { 1.0 } else { 0.0 }; + assert!((value - expected).abs() < TOLERANCE, "at x {}: {value}, expected {expected}", across(point.position)); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 663efd1f..a169516b 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -20,6 +20,7 @@ mod decal_flip; mod decal_symmetry; mod filtering; mod generator_global; +mod generator_grayscale; mod light_parameters; mod micro_detail; mod output_resolution; @@ -27,6 +28,8 @@ mod resolution_mode; mod sampling; mod scale_mode; mod section_parameters; +mod texture_blend; +mod texture_layer; mod tile_blending; mod tile_generator; mod tile_input_distribution; @@ -45,6 +48,7 @@ pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; +pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; @@ -52,6 +56,8 @@ pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; pub use scale_mode::ScaleMode; pub use section_parameters::SectionParameters; +pub use texture_blend::TextureBlend; +pub use texture_layer::TextureLayer; pub use tile_blending::TileBlending; pub use tile_generator::TileGenerator; pub use tile_input_distribution::TileInputDistribution; @@ -1062,6 +1068,9 @@ pub struct Generator { /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub light: Option, + /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub texture: Option, } impl Generator { @@ -1094,6 +1103,16 @@ impl Generator { if reads_geometry { &[] } else { self.kind.inputs() } } + /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity + pub fn texture_in_use(&self) -> Option<&TextureLayer> { + self.texture.as_ref().filter(|texture| texture.in_use() && self.section_controls().is_some()) + } + + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture + pub fn sources(&self) -> impl Iterator { + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())) + } + /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear @@ -1130,6 +1149,7 @@ impl Generator { wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), + texture: None, } } @@ -2103,7 +2123,7 @@ impl EffectKind { EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), EffectKind::Generator(generator) => { generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) - || generator.inputs.values().any(|source| source.reads_anchor(anchor)) + || generator.sources().any(|source| source.reads_anchor(anchor)) } _ => false, } @@ -2114,7 +2134,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let mut anchors: Vec<_> = sources @@ -2137,7 +2157,7 @@ impl EffectKind { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], EffectKind::Material(fill) => fill.sources.values().collect(), - EffectKind::Generator(generator) => generator.inputs.values().collect(), + EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; let id_map = match self { diff --git a/crates/core/src/layer/generator_grayscale.rs b/crates/core/src/layer/generator_grayscale.rs new file mode 100644 index 00000000..01ac149b --- /dev/null +++ b/crates/core/src/layer/generator_grayscale.rs @@ -0,0 +1,81 @@ +use serde::{Deserialize, Serialize}; + +/// How a color texture becomes one gray value +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum GeneratorGrayscale { + /// Halfway between the brightest and the darkest channel + Desaturation, + /// The channels weighted by how bright the eye sees them + Luma, + /// The mean of the three channels + #[default] + Average, + Max, + Min, + Red, + Green, + Blue, +} + +impl GeneratorGrayscale { + pub const ALL: [GeneratorGrayscale; 8] = [ + GeneratorGrayscale::Desaturation, + GeneratorGrayscale::Luma, + GeneratorGrayscale::Average, + GeneratorGrayscale::Max, + GeneratorGrayscale::Min, + GeneratorGrayscale::Red, + GeneratorGrayscale::Green, + GeneratorGrayscale::Blue, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "Desaturation", + GeneratorGrayscale::Luma => "Luma", + GeneratorGrayscale::Average => "Average", + GeneratorGrayscale::Max => "Max", + GeneratorGrayscale::Min => "Min", + GeneratorGrayscale::Red => "Red channel", + GeneratorGrayscale::Green => "Green channel", + GeneratorGrayscale::Blue => "Blue channel", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + GeneratorGrayscale::Desaturation => "desaturation", + GeneratorGrayscale::Luma => "luma", + GeneratorGrayscale::Average => "average", + GeneratorGrayscale::Max => "max", + GeneratorGrayscale::Min => "min", + GeneratorGrayscale::Red => "red", + GeneratorGrayscale::Green => "green", + GeneratorGrayscale::Blue => "blue", + } + } + + /// The conversion named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + GeneratorGrayscale::ALL.into_iter().find(|mode| mode.id().eq_ignore_ascii_case(name) || mode.label().eq_ignore_ascii_case(name)) + } + + /// The gray of `rgb` + pub fn gray(self, [red, green, blue]: [f32; 3]) -> f32 { + // ITU-R BT.601 weights, the reference's Luma + const LUMA: [f32; 3] = [0.299, 0.587, 0.114]; + match self { + GeneratorGrayscale::Desaturation => (red.max(green).max(blue) + red.min(green).min(blue)) * 0.5, + GeneratorGrayscale::Luma => red * LUMA[0] + green * LUMA[1] + blue * LUMA[2], + GeneratorGrayscale::Average => (red + green + blue) / 3.0, + GeneratorGrayscale::Max => red.max(green).max(blue), + GeneratorGrayscale::Min => red.min(green).min(blue), + GeneratorGrayscale::Red => red, + GeneratorGrayscale::Green => green, + GeneratorGrayscale::Blue => blue, + } + } +} diff --git a/crates/core/src/layer/texture_blend.rs b/crates/core/src/layer/texture_blend.rs new file mode 100644 index 00000000..73c3f3cc --- /dev/null +++ b/crates/core/src/layer/texture_blend.rs @@ -0,0 +1,80 @@ +use serde::{Deserialize, Serialize}; + +/// How a generator's texture combines with its signal +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TextureBlend { + /// The texture replaces the signal + Normal, + /// The texture adds to the signal + Add, + /// The texture is taken from the signal + Subtract, + /// The texture multiplies the signal + Multiply, + /// The texture adds above its middle gray and subtracts below it + AddSub, + /// The brighter of the texture and the signal + Max, + /// The darker of the texture and the signal + Min, + /// The texture darkens the signal's darks and lightens its lights + #[default] + Overlay, + /// The inverse of multiplying the inverses: always lighter + Screen, + /// A gentler overlay led by the texture + SoftLight, +} + +impl TextureBlend { + pub const ALL: [TextureBlend; 10] = [ + TextureBlend::Normal, + TextureBlend::Add, + TextureBlend::Subtract, + TextureBlend::Multiply, + TextureBlend::AddSub, + TextureBlend::Max, + TextureBlend::Min, + TextureBlend::Overlay, + TextureBlend::Screen, + TextureBlend::SoftLight, + ]; + + /// The name the panel shows + pub fn label(self) -> &'static str { + match self { + TextureBlend::Normal => "Normal", + TextureBlend::Add => "Linear Dodge (Add)", + TextureBlend::Subtract => "Subtract", + TextureBlend::Multiply => "Multiply", + TextureBlend::AddSub => "Add/Sub", + TextureBlend::Max => "Max (Lighten)", + TextureBlend::Min => "Min (Darken)", + TextureBlend::Overlay => "Overlay", + TextureBlend::Screen => "Screen", + TextureBlend::SoftLight => "Soft light", + } + } + + /// The name commands and saved projects use + pub fn id(self) -> &'static str { + match self { + TextureBlend::Normal => "normal", + TextureBlend::Add => "add", + TextureBlend::Subtract => "subtract", + TextureBlend::Multiply => "multiply", + TextureBlend::AddSub => "addSub", + TextureBlend::Max => "max", + TextureBlend::Min => "min", + TextureBlend::Overlay => "overlay", + TextureBlend::Screen => "screen", + TextureBlend::SoftLight => "softLight", + } + } + + /// The blend named by its id or its label, in any case + pub fn parse(name: &str) -> Option { + TextureBlend::ALL.into_iter().find(|blend| blend.id().eq_ignore_ascii_case(name) || blend.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/texture_layer.rs b/crates/core/src/layer/texture_layer.rs new file mode 100644 index 00000000..877e0f3d --- /dev/null +++ b/crates/core/src/layer/texture_layer.rs @@ -0,0 +1,76 @@ +use serde::{Deserialize, Serialize}; + +use super::Source; +use super::generator_grayscale::GeneratorGrayscale; +use super::texture_blend::TextureBlend; + +/// A texture a generator blends over its signal (the reference's Use Texture block): read as gray, adjusted, then blended before the global controls +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TextureLayer { + /// Use Texture: off keeps the settings but leaves the signal as it is + pub enabled: bool, + /// What the texture reads (None: an empty slot, uniform black) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, + /// How much of the blend shows (0..1) + pub opacity: f32, + pub invert: bool, + pub grayscale: GeneratorGrayscale, + pub blend: TextureBlend, + /// Repeats across the UV square, about its centre ([`TextureLayer::SCALE_RANGE`]) + pub scale: f32, + /// Narrows the texture around its middle (above 0) or flattens it towards gray (below 0) (−1..1) + pub contrast: f32, + /// Lifts the texture towards white (above 0) or black (below 0) (−1..1) + pub brightness: f32, + /// Projected from the world's three axes rather than laid out in UV + pub triplanar: bool, + /// How sharply the three projections meet ([`TextureLayer::TRIPLANAR_CONTRAST_RANGE`]) + pub triplanar_contrast: f32, +} + +impl Default for TextureLayer { + /// The reference app's defaults: off, and at opacity 0 even once turned on + fn default() -> Self { + TextureLayer { + enabled: false, + source: None, + opacity: 0.0, + invert: false, + grayscale: GeneratorGrayscale::default(), + blend: TextureBlend::default(), + scale: 1.0, + contrast: 0.0, + brightness: 0.0, + triplanar: false, + triplanar_contrast: 0.5, + } + } +} + +impl TextureLayer { + pub const SCALE_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + pub const TRIPLANAR_CONTRAST_RANGE: std::ops::RangeInclusive = 0.001..=1.0; + + /// Whether the texture changes the signal: turned on with some opacity (an empty slot blends black) + pub fn in_use(&self) -> bool { + self.enabled && self.opacity > 0.0 + } + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> TextureLayer { + let defaults = TextureLayer::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + TextureLayer { + opacity: within(self.opacity, defaults.opacity, 0.0..=1.0), + scale: within(self.scale, defaults.scale, TextureLayer::SCALE_RANGE), + contrast: within(self.contrast, defaults.contrast, -1.0..=1.0), + brightness: within(self.brightness, defaults.brightness, -1.0..=1.0), + triplanar_contrast: within(self.triplanar_contrast, defaults.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE), + ..self + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c5ff7ec3..b8d53dd9 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,9 +112,9 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, SectionParameters, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, + Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 09cdaecb..39918d33 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -153,6 +153,9 @@ fn generator_json(generator: &Generator) -> Value { if !generator.inputs.is_empty() { out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); } + if let Some(texture) = &generator.texture { + out["texture"] = json!(texture); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 19a61f09..8f67edf9 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::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, WearParameters, + GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, starting from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id or texture + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -485,10 +485,38 @@ const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"]; /// The Light generator's controls const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"]; -/// The section controls, the axis keys and the light controls `params` gives +/// The texture controls (Use Texture); the texture itself is the `texture` input +const TEXTURE_KEYS: [&str; 10] = [ + "useTexture", + "textureOpacity", + "textureInvert", + "textureGrayscale", + "textureBlend", + "textureScale", + "textureContrast", + "textureBrightness", + "textureTriplanar", + "textureTriplanarContrast", +]; + +/// The input name of a generator's texture, beside the mesh map ids +const TEXTURE_INPUT: &str = "texture"; + +/// The section controls, the axis keys, the texture controls and the light controls `params` gives (a texture input counts as `texture`) fn given_new_model_keys(params: &Value) -> Vec { let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}"))); - SECTION_KEYS.iter().chain(LIGHT_KEYS.iter()).map(|key| key.to_string()).chain(axis_keys).filter(|key| params.get(key).is_some()).collect() + let mut keys: Vec = SECTION_KEYS + .iter() + .chain(TEXTURE_KEYS.iter()) + .chain(LIGHT_KEYS.iter()) + .map(|key| key.to_string()) + .chain(axis_keys) + .filter(|key| params.get(key).is_some()) + .collect(); + if strp(params, "input") == Some(TEXTURE_INPUT) { + keys.push(TEXTURE_INPUT.to_string()); + } + keys } /// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model @@ -597,6 +625,44 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res } } generator.section = Some(section.clamped(kind)); + texture_from(command, params, generator) +} + +/// The texture controls in `params` (the generator is on its section controls already) +fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) { + return Ok(()); + } + let mut texture = generator.texture.clone().unwrap_or_default(); + if let Some(enabled) = boolp(params, "useTexture") { + texture.enabled = enabled; + } + for (key, value) in [ + ("textureOpacity", &mut texture.opacity), + ("textureScale", &mut texture.scale), + ("textureContrast", &mut texture.contrast), + ("textureBrightness", &mut texture.brightness), + ("textureTriplanarContrast", &mut texture.triplanar_contrast), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(invert) = boolp(params, "textureInvert") { + texture.invert = invert; + } + if let Some(triplanar) = boolp(params, "textureTriplanar") { + texture.triplanar = triplanar; + } + if let Some(value) = params.get("textureGrayscale") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureGrayscale` must be a string"))?; + texture.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale conversion `{name}`")))?; + } + if let Some(value) = params.get("textureBlend") { + let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?; + texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?; + } + generator.texture = Some(texture.clamped()); Ok(()) } @@ -604,7 +670,8 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix))); match key { - "sectionInvert" | "sectionContrast" => SectionParameters::defaults(kind).is_some(), + "sectionInvert" | "sectionContrast" | TEXTURE_INPUT => SectionParameters::defaults(kind).is_some(), + _ if TEXTURE_KEYS.contains(&key) => SectionParameters::defaults(kind).is_some(), "sectionBlur" => SectionParameters::has_blur(kind), "sectionBalance" => SectionParameters::has_balance(kind), "sectionBrightness" => SectionParameters::has_brightness(kind), @@ -736,12 +803,22 @@ fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value Ok(Some(Some(MicroDetail { anchor, amount }))) } -/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. -fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { +/// A generator input a command names: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum GeneratorInput { + Map(BakedMap), + Texture, +} + +/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture slot), for a generator on layer `owner` +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; - let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id or `texture`"))?; + let input = match name { + TEXTURE_INPUT => GeneratorInput::Texture, + _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), + }; let image = strp(params, "inputImage"); let value = f32p(params, "inputValue"); @@ -762,7 +839,7 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R (None, None, None, true) => None, _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), }; - Ok(Some((map, source))) + Ok(Some((input, source))) } fn add_generator(session: &mut Session, params: &Value) -> Result { @@ -1060,15 +1137,19 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(micro) = micro { generator.micro = micro; } - if let Some((map, source)) = input { - if !generator.inputs_in_use().contains(&map) { - return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + match input { + Some((GeneratorInput::Map(map), source)) => { + if !generator.inputs_in_use().contains(&map) { + return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; } - - match source { - Some(source) => generator.inputs.insert(map, source), - None => generator.inputs.remove(&map), - }; + // generator_from refused the texture on kinds without one and moved the generator onto its section controls + Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, + None => {} } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), diff --git a/crates/engine/tests/it/generator_texture.rs b/crates/engine/tests/it/generator_texture.rs new file mode 100644 index 00000000..9d640515 --- /dev/null +++ b/crates/engine/tests/it/generator_texture.rs @@ -0,0 +1,106 @@ +//! A generator's texture (Use Texture) through `effect.add.generator` and `effect.set`: its controls, its image as the `texture` input, and the kinds without one + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, GeneratorGrayscale, LayerId, Source, TextureBlend, TextureLayer}; +use texturecraft_engine::mask_cmds::section_key_applies; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("grunge.png", bytes).unwrap() +} + +#[test] +fn texture_controls_start_from_the_reference_defaults_and_clamp() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "curvature"})); + assert_eq!(generator(&session, effect).texture, None, "untouched until a texture control is given"); + + let edit = + json!({"effect": effect, "useTexture": true, "textureScale": 40.0, "textureContrast": -3.0, "textureBlend": "Soft light", "textureGrayscale": "red"}); + execute(&mut session, "effect.set", &edit).unwrap(); + let expected = TextureLayer { + enabled: true, + scale: *TextureLayer::SCALE_RANGE.end(), + contrast: -1.0, + blend: TextureBlend::SoftLight, + grayscale: GeneratorGrayscale::Red, + ..TextureLayer::default() + }; + assert_eq!(generator(&session, effect).texture, Some(expected)); + assert_eq!(TextureLayer::default().opacity, 0.0, "the reference starts the texture at opacity 0"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureBlend": "dissolve"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureGrayscale": "hue"})).is_err()); +} + +#[test] +fn the_texture_image_is_the_texture_input_and_stays_a_used_resource() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "ambientOcclusion"})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).unwrap(); + let plugged = generator(&session, effect); + assert_eq!(plugged.texture.as_ref().and_then(|texture| texture.source.clone()), Some(Source::image(name.clone()))); + assert!(plugged.inputs.is_empty(), "the texture is not a mesh map input"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the texture"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).texture.and_then(|texture| texture.source), None, "inputBaked empties the slot"); +} + +#[test] +fn a_texture_moves_an_earlier_generator_onto_its_section_controls() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "position", "level": 0.8})); + assert_eq!(generator(&session, effect).section, None); + + execute(&mut session, "effect.set", &json!({"effect": effect, "textureOpacity": 0.5})).unwrap(); + let moved = generator(&session, effect); + assert!(moved.section.is_some()); + assert_eq!(moved.texture.map(|texture| texture.opacity), Some(0.5)); + + let both = json!({"effect": effect, "useTexture": true, "level": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "a texture control and the earlier model at once"); +} + +#[test] +fn kinds_without_a_texture_refuse_its_controls_and_its_input() { + let mut session = session(); + let name = gray_image(&mut session); + for kind in ["dirt", "edgeWear", "fiberGlassEdgeWear", "direction", "thinAreas"] { + let effect = add(&mut session, json!({"generator": kind})); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "useTexture": true})).is_err(), "{kind} useTexture"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "input": "texture", "inputImage": name})).is_err(), "{kind} texture input"); + assert_eq!(generator(&session, effect).texture, None, "{kind}"); + } + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals"] { + let effect = add(&mut session, json!({"generator": kind})); + let added = generator(&session, effect); + assert!(section_key_applies(added.kind, "textureTriplanar"), "{kind}"); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 44effae5..140ea6ff 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -38,6 +38,7 @@ mod frame_selection; mod generator_inputs; mod generator_sections; mod generator_swap; +mod generator_texture; mod generator_wear; mod gradient_map; mod high_poly_missed; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 7c6f7258..3cadca28 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,8 +4,8 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, - SectionParameters, Source, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, + SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, }; use crate::TextureCraftApp; @@ -52,6 +52,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); + texture_parameters(app, ui, id, generator.texture.clone().unwrap_or_default()); } if let Some(defaults) = LightParameters::defaults(generator.kind) { light_parameters(app, ui, id, None, defaults); @@ -63,15 +64,19 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { - app.run("effect.set", defaults_of(id, generator.kind)); + app.run("effect.set", defaults_of(id, generator)); } }); }); }); - if !generator.inputs_in_use().is_empty() { + let texture = generator.texture.as_ref().filter(|texture| texture.enabled && SectionParameters::defaults(generator.kind).is_some()); + if !generator.inputs_in_use().is_empty() || texture.is_some() { section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + if let Some(texture) = texture { + input_slot(app, ui, (layer, id), InputSlot::Texture, texture.source.as_ref(), false); + } for map in generator.inputs_in_use() { - input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail_in_use().is_some()); + input_slot(app, ui, (layer, id), InputSlot::Map(*map), generator.inputs.get(map), generator.detail_in_use().is_some()); } }); } @@ -315,7 +320,8 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { } /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. -fn defaults_of(id: u64, kind: GeneratorKind) -> Value { +fn defaults_of(id: u64, generator: &Generator) -> Value { + let kind = generator.kind; let defaults = Generator::new(kind); let params = json!({ "effect": id, @@ -332,6 +338,10 @@ fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let own = match (&defaults.wear, &defaults.section, &defaults.light) { (Some(wear), _, _) => wear_params(kind, wear), (None, _, Some(light)) => light_params(light), + // The texture's controls only once it has them: its image stays in its slot + (None, Some(section), None) if generator.texture.is_some() => { + merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) + } (None, Some(section), None) => merged(section_params(kind, section), global), (None, None, None) => json!({ "level": defaults.level, @@ -433,6 +443,58 @@ fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { } /// The translated name of axis blending mode `blend` +/// Use Texture and, once it is on, the texture's controls and its opacity +fn texture_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, shown: TextureLayer) { + let mut edited = shown; + let mut edit = true_false(ui, tr("Use texture"), &mut edited.enabled).then_some(false); + if edited.enabled { + section(ui, "generator_texture", tr("Texture"), true, |ui| { + edit = edit.or(true_false(ui, tr("Invert"), &mut edited.invert).then_some(false)); + combo(ui, tr("Grayscale conversion"), tr(edited.grayscale.label()), |ui| { + for mode in GeneratorGrayscale::ALL { + if ui.selectable_label(mode == edited.grayscale, tr(mode.label())).clicked() { + edited.grayscale = mode; + edit = Some(false); + } + } + }); + combo(ui, tr("Blending mode"), tr(edited.blend.label()), |ui| { + for blend in TextureBlend::ALL { + if ui.selectable_label(blend == edited.blend, tr(blend.label())).clicked() { + edited.blend = blend; + edit = Some(false); + } + } + }); + edit = edit.or(slider_edit(ui, tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); + edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); + edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); + edit = edit.or(true_false(ui, tr("Triplanar"), &mut edited.triplanar).then_some(false)); + edit = edit.or(slider_edit(ui, tr("Triplanar contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); + }); + edit = edit.or(slider_edit(ui, tr("Texture opacity"), &mut edited.opacity, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); + } +} + +/// The texture controls as `effect.set` keys (its image is the `texture` input) +fn texture_params(texture: &TextureLayer) -> Value { + json!({ + "useTexture": texture.enabled, + "textureOpacity": texture.opacity, + "textureInvert": texture.invert, + "textureGrayscale": texture.grayscale.id(), + "textureBlend": texture.blend.id(), + "textureScale": texture.scale, + "textureContrast": texture.contrast, + "textureBrightness": texture.brightness, + "textureTriplanar": texture.triplanar, + "textureTriplanarContrast": texture.triplanar_contrast, + }) +} + fn axis_blend_label(blend: AxisBlend) -> &'static str { match blend { AxisBlend::Normal => tr("Normal"), @@ -552,26 +614,62 @@ fn curvature_mode_label(mode: CurvatureMode) -> &'static str { } } -/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. -fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { +/// What an image input slot of a generator replaces: a mesh map it reads, or its texture +#[derive(Clone, Copy)] +enum InputSlot { + Map(BakedMap), + Texture, +} + +impl InputSlot { + /// The input's name in `effect.set` + fn id(self) -> &'static str { + match self { + InputSlot::Map(map) => map.id(), + InputSlot::Texture => "texture", + } + } + + fn title(self) -> &'static str { + match self { + InputSlot::Map(map) => tr(baked_map_label(map)), + InputSlot::Texture => tr("Texture"), + } + } + + /// The value a slot set to a uniform value starts at + fn neutral(self) -> f32 { + match self { + InputSlot::Map(map) => map.neutral()[0], + InputSlot::Texture => 0.0, + } + } +} + +/// One image input: what it reads now, a menu to replace it with a value, an anchor point or an image, and a button to empty it +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), slot: InputSlot, source: Option<&Source>, detail_sizes: bool) { let tokens = Tokens::get(ui.ctx()); - let input = map.id(); - let current = match source { - None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), - Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), - Some(Source::Uniform(_)) => tr("Uniform value").to_string(), - Some(Source::Anchor { anchor, channel, .. }) => anchor_label(app, *anchor, *channel), - Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + let input = slot.id(); + let current = match (source, slot) { + (None, InputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + (None, InputSlot::Texture) | (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), + (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), + (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), + (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), + }; + let empty_hint = match slot { + InputSlot::Map(_) => tr("Read the mesh map again"), + InputSlot::Texture => tr("Empty the slot"), }; let group = ui.group(|ui| { ui.horizontal(|ui| { - input_tile(app, ui, map, source); + input_tile(app, ui, slot, source); ui.vertical(|ui| { - ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(slot.title()).strong()); ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + if source.is_some() && ui.button(ic::X).on_hover_text(empty_hint).clicked() { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } }); @@ -580,11 +678,14 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 ui.push_id(input, |ui| { combo(ui, tr("Source"), current.clone(), |ui| { let anchors = anchors_below(&app.session.doc.project, layer); - if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + if let InputSlot::Map(_) = slot + && ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() + { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } - if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + let uniform = matches!(source, Some(Source::Uniform(_))) || (source.is_none() && matches!(slot, InputSlot::Texture)); + if ui.selectable_label(uniform, tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); } for (anchor, label) in &anchors { if ui @@ -602,13 +703,18 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } }) }); - if let Some(Source::Uniform(value)) = source { - let mut value = value[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); - } + let uniform = match (source, slot) { + (Some(Source::Uniform(value)), _) => Some(value[0]), + (None, InputSlot::Texture) => Some(slot.neutral()), + _ => None, + }; + if let Some(mut value) = uniform + && let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) + { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); } - if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + let replaced_curvature = matches!(slot, InputSlot::Map(BakedMap::Curvature)) && source.is_some_and(|source| !matches!(source, Source::Uniform(_))); + if detail_sizes && replaced_curvature { ui.label( RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) .size(NOTE_FONT_SIZE) @@ -621,14 +727,15 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 } } -/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). -fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { +/// The picture beside an image input: its image, its value as gray, an icon for an anchor or a procedural, else its mesh map's color (black for an empty texture) +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, slot: InputSlot, source: Option<&Source>) { let tokens = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); let painter = ui.painter(); let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - match source { - Some(Source::Image { name, .. }) => match app.session.images.get(name) { + let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); + match (source, slot) { + (Some(Source::Image { name, .. }), _) => match app.session.images.get(name) { Some(image) => { let texture = app.thumbs.image(ui.ctx(), name, image); painter.image(texture.id(), rect, whole, egui::Color32::WHITE); @@ -637,15 +744,18 @@ fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Opt painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); } }, - Some(Source::Uniform(value)) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + (Some(Source::Uniform(value)), _) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(value[0])); } - Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); } - None => { + (None, InputSlot::Texture) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(slot.neutral())); + } + (None, InputSlot::Map(map)) => { let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 513ca72b..01bf845a 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -300,3 +300,60 @@ fn section_panel_snapshots() { harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); } } + +#[test] +fn use_texture_shows_the_texture_rows_and_its_slot() { + let (harness, _) = harness_with(false, json!({"generator": "position"})); + assert_eq!(count(&harness, "Use texture"), 1); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar contrast", "Texture"] { + assert_eq!(count(&harness, label), 0, "{label} waits for Use texture"); + } + + let (harness, _) = harness_with(false, json!({"generator": "position", "useTexture": true})); + for label in ["Grayscale conversion", "Texture opacity", "Triplanar", "Triplanar contrast", "Scale"] { + assert_eq!(count(&harness, label), 1, "{label}"); + } + assert_eq!(count(&harness, "Texture"), 2, "the Texture section and the Texture slot in Image inputs"); + assert_eq!(count(&harness, "Blending mode"), 4, "the texture's beside the three axes'"); + + let (harness, _) = harness_with(false, json!({"generator": "dirt"})); + assert_eq!(count(&harness, "Use texture"), 0, "wear generators have no texture"); +} + +#[test] +fn the_texture_slot_reads_a_uniform_value_until_it_is_given_one() { + let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion", "useTexture": true})); + let slot = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Uniform value")).count() + }; + assert_eq!(slot(&harness), 1, "an empty texture slot is a uniform value"); + assert_eq!(count(&harness, "Value"), 1, "with its value slider"); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + assert_eq!(count(&harness, "Mesh map"), 0, "the texture has no mesh map to go back to"); + // The slot's heading also reads "Uniform value": the menu entry is the button + harness.get_by_role_and_label(Role::Button, "Uniform value").click(); + harness.run_steps(3); + let texture = generator(&harness, effect).texture.unwrap(); + assert_eq!(texture.source, Some(Source::Uniform([0.0; 3]))); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn texture_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + for kind in ["position", "ambientOcclusion"] { + let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); + harness.get_by_label("Use texture").scroll_to_me(); + harness.run_steps(12); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("texture-panel-{kind}-{name}.png"))).unwrap(); + } + } +} From 31e834c10d272ddc2d14b23ae0e5979d9d667ef6 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:31:37 +0000 Subject: [PATCH 12/54] Wear generators: Use Custom Grunge reads an image instead of the kind's own grunge Metal Edge Wear, Fiber Glass Edge Wear and Dirt take the reference's Use Custom Grunge switch and its grunge image (effect.set input: grunge). Once on, the image's gray replaces the kind's built-in pattern, fitted to the reference app: repeated grunge-scale times across the UV square from half way across the image, or across the mesh's bounds when triplanar; mid gray adds nothing, a brighter image wears edges more and leaves less dirt; the seed leaves it in place. An empty slot reads black. The image moves an earlier-model generator onto its wear controls, is refused on kinds without them, counts as a used resource and stays across swaps between wear kinds. Use Texture and the custom grunge share one slot placement; a generator's texture is boxed so the generator effect stays small. --- crates/compose/src/eval.rs | 47 ++++-- crates/compose/src/texture_layer.rs | 46 ++++-- crates/compose/src/wear.rs | 47 +++++- crates/compose/tests/cache_and_instances.rs | 3 +- .../compose/tests/generator_custom_grunge.rs | 155 ++++++++++++++++++ crates/compose/tests/generator_texture.rs | 4 +- crates/core/src/layer.rs | 14 +- crates/core/src/layer/wear_parameters.rs | 5 + crates/engine/src/inspect.rs | 3 + crates/engine/src/mask_cmds.rs | 39 +++-- .../tests/it/generator_custom_grunge.rs | 104 ++++++++++++ crates/engine/tests/it/generator_texture.rs | 2 +- crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 2 +- 14 files changed, 407 insertions(+), 65 deletions(-) create mode 100644 crates/compose/tests/generator_custom_grunge.rs create mode 100644 crates/engine/tests/it/generator_custom_grunge.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2b0500a7..44875108 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1945,8 +1945,8 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } -/// What a generator's texture reads with nothing in its slot -const EMPTY_TEXTURE_SLOT: Source = Source::Uniform([0.0; 3]); +/// What a generator's texture or custom grunge reads with nothing in its slot +const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); /// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray const GENERATOR_STAGE_COMPONENTS: usize = 3; @@ -3452,7 +3452,13 @@ impl<'a, 'b> Texel<'a, 'b> { let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); - let grunge = wear::grunge(generator.kind, wear, generator.seed, &self.coords()); + let grunge = if wear.custom_grunge { + // An image not loaded yet reads mid gray, which leaves the wear as without grunge + let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); + wear::custom_grunge(generator.kind, gray) + } else { + wear::grunge(generator.kind, wear, generator.seed, &self.coords()) + }; wear::wear_value(generator.kind, wear, &WearInputs { curvature, blurred_curvature, occlusion, grunge }) } @@ -3492,28 +3498,35 @@ impl<'a, 'b> Texel<'a, 'b> { /// The gray of the generator's texture at this texel (None when it blends no texture) fn generator_texture(&mut self, generator: &Generator) -> Option { let texture = generator.texture_in_use()?; - let rgb = match texture.source.as_ref().unwrap_or(&EMPTY_TEXTURE_SLOT) { + let rgb = self.slot_color(generator, texture.source.as_ref(), &texture_layer::texture_placement(texture))?; + Some(texture_layer::texture_gray(texture, rgb)) + } + + /// The color of a generator's image slot holding `source` (None: empty, read as black) at this texel, read where `placement` puts it (None when its image isn't loaded) + fn slot_color(&mut self, generator: &Generator, source: Option<&Source>, placement: &texture_layer::SlotPlacement) -> Option<[f32; 3]> { + match source.unwrap_or(&EMPTY_IMAGE_SLOT) { Source::Image { name, .. } => { let image = self.inp.images.get(name)?.clone(); let read = |coordinates: Vec2| { let [red, green, blue, _] = image.sample(coordinates.x, coordinates.y); Vec3::new(red, green, blue) }; - if texture.triplanar { - let normal = self - .generator_input_color(generator, BakedMap::WorldNormal) - .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); - let weights = texture_layer::triplanar_weights(texture, normal); - let coordinates = texture_layer::triplanar_coordinates(texture, self.bounds_position()); - weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight).to_array() - } else { - read(texture_layer::uv_coordinates(texture, self.coords().uv)).to_array() - } + let color = match placement.triplanar_contrast { + Some(contrast) => { + let normal = self + .generator_input_color(generator, BakedMap::WorldNormal) + .map_or_else(|| self.coords().nrm, |encoded| Vec3::from(encoded) * 2.0 - 1.0); + let weights = texture_layer::triplanar_weights(contrast, normal); + let coordinates = texture_layer::triplanar_coordinates(placement, self.bounds_position()); + weights.iter().zip(coordinates).fold(Vec3::ZERO, |sum, (weight, at)| sum + read(at) * *weight) + } + None => read(texture_layer::uv_coordinates(placement, self.coords().uv)), + }; + Some(color.to_array()) } // A value or an anchor reads the same wherever it is projected - other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), - }; - Some(texture_layer::texture_gray(texture, rgb)) + other => Some(self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)), + } } /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index 95c40fa3..e9042d05 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -1,4 +1,4 @@ -//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal +//! A generator's texture (Use Texture): where it is read, how it turns gray and how it blends over the signal; its custom grunge is read the same way use texturecraft_core::{TextureBlend, TextureLayer}; use texturecraft_geom::glam::{Vec2, Vec3}; @@ -9,20 +9,33 @@ const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; /// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly const MIN_NORMAL_COMPONENT: f32 = 1e-6; -/// Where the texture is read in UV: scaled about the centre of the UV square -pub(crate) fn uv_coordinates(texture: &TextureLayer, uv: Vec2) -> Vec2 { - (uv - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5) +/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` +pub(crate) struct SlotPlacement { + pub scale: f32, + pub offset: f32, + /// How sharply the three projections meet, or None to read in UV + pub triplanar_contrast: Option, } -/// Where the texture is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1), scaled about their centre -pub(crate) fn triplanar_coordinates(texture: &TextureLayer, position: Vec3) -> [Vec2; 3] { - let scaled = |u: f32, v: f32| (Vec2::new(u, v) - Vec2::splat(0.5)) * texture.scale + Vec2::splat(0.5); - [scaled(-position.z, position.y), scaled(position.x, position.z), scaled(position.x, position.y)] +/// The texture is scaled about the centre of the UV square (or of the mesh's bounds) +pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { + SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } } -/// How much each projection (facing X, Y and Z) counts for a surface facing `normal`, summing to 1 -pub(crate) fn triplanar_weights(texture: &TextureLayer, normal: Vec3) -> [f32; 3] { - let contrast = texture.triplanar_contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); +/// Where a slot is read in UV +pub(crate) fn uv_coordinates(placement: &SlotPlacement, uv: Vec2) -> Vec2 { + uv * placement.scale + Vec2::splat(placement.offset) +} + +/// Where a slot is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1) +pub(crate) fn triplanar_coordinates(placement: &SlotPlacement, position: Vec3) -> [Vec2; 3] { + let placed = |u: f32, v: f32| Vec2::new(u, v) * placement.scale + Vec2::splat(placement.offset); + [placed(-position.z, position.y), placed(position.x, position.z), placed(position.x, position.y)] +} + +/// How much each projection (facing X, Y and Z) counts for a surface facing `normal` at triplanar `contrast`, summing to 1 +pub(crate) fn triplanar_weights(contrast: f32, normal: Vec3) -> [f32; 3] { + let contrast = contrast.clamp(*TextureLayer::TRIPLANAR_CONTRAST_RANGE.start(), *TextureLayer::TRIPLANAR_CONTRAST_RANGE.end()); let sharpness = (1.0 - contrast).max(f32::EPSILON).powf(-TRIPLANAR_SHARPNESS_POWER); let facing = normal.abs(); let largest = facing.max_element().max(MIN_NORMAL_COMPONENT); @@ -132,19 +145,18 @@ mod tests { #[test] fn triplanar_weights_follow_the_normal_and_sharpen_with_contrast() { - let along_y = triplanar_weights(&texture(), Vec3::Y); + let along_y = triplanar_weights(texture().triplanar_contrast, Vec3::Y); assert!((along_y[1] - 1.0).abs() < 1e-6); let diagonal = Vec3::new(1.0, 0.5, 0.0).normalize(); - let soft = triplanar_weights(&TextureLayer { triplanar_contrast: 0.001, ..texture() }, diagonal); - let hard = triplanar_weights(&TextureLayer { triplanar_contrast: 0.9, ..texture() }, diagonal); + let (soft, hard) = (triplanar_weights(0.001, diagonal), triplanar_weights(0.9, diagonal)); assert!(hard[0] > soft[0] && hard[1] < soft[1]); assert!((soft.iter().sum::() - 1.0).abs() < 1e-5); } #[test] fn scale_is_about_the_centre() { - let texture = TextureLayer { scale: 2.0, ..texture() }; - assert_eq!(uv_coordinates(&texture, Vec2::splat(0.5)), Vec2::splat(0.5)); - assert_eq!(uv_coordinates(&texture, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); + let placement = texture_placement(&TextureLayer { scale: 2.0, ..texture() }); + assert_eq!(uv_coordinates(&placement, Vec2::splat(0.5)), Vec2::splat(0.5)); + assert_eq!(uv_coordinates(&placement, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); } } diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index b766f3e1..864ae755 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -5,6 +5,7 @@ use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, W use crate::curvature_sizes::LEVEL_RADII; use crate::pattern::{Coords, procedural}; +use crate::texture_layer::SlotPlacement; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; @@ -29,11 +30,13 @@ struct GrungePattern { breakup: Option<(ProceduralKind, f32)>, mean: f32, spread: f32, + /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) + custom_gain: f32, } /// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt const EDGE_WEAR_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149 }; + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { kind: ProceduralKind::Weave, repeats_per_scale: 16.0, @@ -41,15 +44,22 @@ const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { breakup: Some((ProceduralKind::Grunge, 4.0)), mean: 0.539, spread: 0.198, + custom_gain: 1.9, }; const DIRT_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242 }; + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; /// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) const BREAKUP_DEPTH: f32 = 0.6; /// The triplanar seams' sharpness at triplanar contrast 0 and 1 const TRIPLANAR_SHARPNESS: std::ops::RangeInclusive = 1.0..=16.0; +/// The gray at which a custom grunge neither adds nor removes wear +const CUSTOM_GRUNGE_MID_GRAY: f32 = 0.5; + +/// Where the reference app reads a custom grunge at the UV square's origin: half way across the image (triplanar: at its origin) +const CUSTOM_GRUNGE_UV_OFFSET: f32 = 0.5; + /// The Gaussian sigma (texels at 2K) the kind's blurred curvature is read at pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { match kind { @@ -59,17 +69,24 @@ pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { } } -/// The wear's grunge at `coords`, normalised to mean 0 and spread 1 -pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { - let grunge = match kind { +fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { + match kind { GeneratorKind::Dirt => &DIRT_GRUNGE, GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, _ => &EDGE_WEAR_GRUNGE, - }; + } +} + +fn triplanar_sharpness(wear: &WearParameters) -> f32 { + TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast +} + +/// The wear's own grunge at `coords`, normalised to mean 0 and spread 1 +pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coords: &Coords) -> f32 { + let grunge = grunge_pattern(kind); let pattern = Procedural { scale: grunge.repeats_per_scale * wear.grunge_scale, seed, ..Procedural::new(grunge.kind) }; let projection = if wear.triplanar { - let sharpness = TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast; - Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] } + Projection::Triplanar { scale: 1.0, sharpness: triplanar_sharpness(wear), offset: [0.0; 3], uv: Default::default(), projector: Default::default() } } else { Projection::Uv { scale: [1.0, 1.0], rotation: grunge.rotation, offset: [0.0, 0.0] } }; @@ -81,6 +98,20 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor (value - grunge.mean) / grunge.spread } +/// Where a custom grunge image is read: repeated grunge-scale times across the UV square (or the mesh's bounds, triplanar) +pub(crate) fn custom_grunge_placement(wear: &WearParameters) -> SlotPlacement { + if wear.triplanar { + SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast) } + } else { + SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None } + } +} + +/// A custom grunge's `gray` as the normalised grunge the fitted signals read; the reference app's seed leaves it where it is +pub(crate) fn custom_grunge(kind: GeneratorKind, gray: f32) -> f32 { + grunge_pattern(kind).custom_gain * (gray - CUSTOM_GRUNGE_MID_GRAY) +} + /// The two blurred curvature levels around `sigma` and the weight of the wider one; level None is the map itself pub(crate) fn levels_around(sigma: f32) -> (Option, usize, f32) { let sigmas = LEVEL_SIGMAS; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index dac833d1..b3d1c309 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -1281,7 +1281,8 @@ fn replacing_a_generator_texture_image_invalidates_the_cached_stack() { let hot_layer = heavy_stack(&mut fixture); let texture = TextureLayer { enabled: true, source: Some(Source::image("grunge")), opacity: 1.0, blend: TextureBlend::Normal, ..TextureLayer::default() }; let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(texture), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); + mask.effects + .push(effect(&mut fixture, EffectKind::Generator(Generator { texture: Some(Box::new(texture)), ..Generator::new(GeneratorKind::AmbientOcclusion) }))); let textured = add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), Some(mask)); let stack = &mut fixture.project.texture_sets[0].stack; stack.retain(|id| *id != textured); diff --git a/crates/compose/tests/generator_custom_grunge.rs b/crates/compose/tests/generator_custom_grunge.rs new file mode 100644 index 00000000..ce652afc --- /dev/null +++ b/crates/compose/tests/generator_custom_grunge.rs @@ -0,0 +1,155 @@ +//! A wear generator's custom grunge on a sphere: read instead of the kind's own pattern, tiled by the grunge scale, the seed leaving it in place + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + WearParameters, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// Width of the split image: its left half black, its right half white +const SPLIT_WIDTH: u32 = 64; + +const WEAR_KINDS: [GeneratorKind; 3] = [GeneratorKind::EdgeWear, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::Dirt]; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// A unit sphere with a white fill layer, no occlusion anywhere, no curvature map, and the images `black`, `white` and `split` +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() }; + + let flat = |value: f32| Arc::new(ImageRes::new(4, 4, vec![[value, value, value, 1.0]; 16], false)); + let split_texel = |index: u32| if index % SPLIT_WIDTH < SPLIT_WIDTH / 2 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }; + let split = ImageRes::new(SPLIT_WIDTH, SPLIT_WIDTH, (0..SPLIT_WIDTH * SPLIT_WIDTH).map(split_texel).collect(), false); + let images = [("black".to_string(), flat(0.0)), ("white".to_string(), flat(1.0)), ("split".to_string(), Arc::new(split))].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// Every covered texel +fn covered(fixture: &Fixture) -> Vec<(u32, u32)> { + (0..RES * RES).filter(|index| fixture.gbuf.surface(&fixture.mesh, *index as usize).is_some()).map(|index| (index % RES, index / RES)).collect() +} + +/// The mask of `generator` alone over black at `texels` +fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// `kind` on its wear controls at full grunge amount, reading `image` (None: an empty slot) as its grunge once `custom` is on +fn wear(kind: GeneratorKind, image: Option<&str>, custom: bool, edit: impl Fn(&mut WearParameters)) -> Generator { + let mut wear = WearParameters { grunge_amount: 1.0, custom_grunge: custom, ..WearParameters::defaults(kind).unwrap() }; + edit(&mut wear); + Generator { wear: Some(wear), grunge: image.map(Source::image), ..Generator::new(kind) } +} + +fn mean(values: &[f32]) -> f32 { + values.iter().sum::() / values.len() as f32 +} + +/// The share of texels where `first` and `second` differ +fn differing(first: &[f32], second: &[f32]) -> f32 { + first.iter().zip(second).filter(|(a, b)| (*a - *b).abs() > 0.05).count() as f32 / first.len() as f32 +} + +#[test] +fn a_grunge_image_changes_nothing_until_use_custom_grunge_is_on() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + let own = mask(&mut fixture, wear(kind, None, false, |_| {}), &texels); + assert_eq!(mask(&mut fixture, wear(kind, Some("white"), false, |_| {}), &texels), own, "{kind:?}"); + assert!(differing(&mask(&mut fixture, wear(kind, Some("white"), true, |_| {}), &texels), &own) > 0.1, "{kind:?}: on, the image replaces the pattern"); + } +} + +#[test] +fn a_brighter_custom_grunge_wears_edges_more_and_dirties_less_in_uv_and_triplanar() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + for triplanar in [false, true] { + let read = |fixture: &mut Fixture, image| mean(&mask(fixture, wear(kind, Some(image), true, |wear| wear.triplanar = triplanar), &texels)); + let (white, black) = (read(&mut fixture, "white"), read(&mut fixture, "black")); + let (more, less) = if kind == GeneratorKind::Dirt { (black, white) } else { (white, black) }; + assert!(more > less + 0.3, "{kind:?} triplanar {triplanar}: white {white}, black {black}"); + } + } +} + +#[test] +fn an_empty_grunge_slot_reads_black() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + assert_eq!( + mask(&mut fixture, wear(kind, None, true, |_| {}), &texels), + mask(&mut fixture, wear(kind, Some("black"), true, |_| {}), &texels), + "{kind:?}" + ); + } +} + +#[test] +fn the_grunge_scale_repeats_a_custom_grunge_across_the_uv_square() { + let mut fixture = fixture(); + // Texel pairs half the UV square apart, both covered + let covered = covered(&fixture); + let pairs: Vec<((u32, u32), (u32, u32))> = + covered.iter().filter(|(x, _)| *x < RES / 2).map(|(x, y)| ((*x, *y), (x + RES / 2, *y))).filter(|(_, right)| covered.contains(right)).collect(); + let (left, right): (Vec<_>, Vec<_>) = pairs.into_iter().unzip(); + let halves = |fixture: &mut Fixture, scale: f32| { + let generator = wear(GeneratorKind::EdgeWear, Some("split"), true, |wear| wear.grunge_scale = scale); + (mask(fixture, generator.clone(), &left), mask(fixture, generator, &right)) + }; + + let (first, second) = halves(&mut fixture, 2.0); + assert!(differing(&first, &second) < 0.02, "twice across the square, half of it apart reads the same"); + let (first, second) = halves(&mut fixture, 1.0); + assert!(differing(&first, &second) > 0.5, "once across the square, half of it apart reads the other side of the image"); +} + +#[test] +fn the_seed_leaves_a_custom_grunge_in_place() { + let mut fixture = fixture(); + let texels = covered(&fixture); + for kind in WEAR_KINDS { + for triplanar in [false, true] { + let seeded = |seed| Generator { seed, ..wear(kind, Some("split"), true, |wear| wear.triplanar = triplanar) }; + assert_eq!(mask(&mut fixture, seeded(1), &texels), mask(&mut fixture, seeded(2), &texels), "{kind:?} triplanar {triplanar}"); + } + } +} diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index 3800ccb6..b9bd92ea 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -94,7 +94,7 @@ fn mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> V /// Ambient Occlusion on its section controls with `texture` reading image `image` fn occlusion_with(image: &str, texture: TextureLayer) -> Generator { - Generator { texture: Some(TextureLayer { source: Some(Source::image(image)), ..texture }), ..Generator::new(GeneratorKind::AmbientOcclusion) } + Generator { texture: Some(Box::new(TextureLayer { source: Some(Source::image(image)), ..texture })), ..Generator::new(GeneratorKind::AmbientOcclusion) } } /// A texture turned on at full opacity, replacing the signal @@ -122,7 +122,7 @@ fn a_texture_turned_off_or_at_opacity_zero_leaves_the_signal() { fn an_empty_texture_slot_blends_black() { let mut fixture = fixture([0.6; 3]); let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); - let empty = Generator { texture: Some(TextureLayer { opacity: 0.5, ..replacing() }), ..Generator::new(GeneratorKind::AmbientOcclusion) }; + let empty = Generator { texture: Some(Box::new(TextureLayer { opacity: 0.5, ..replacing() })), ..Generator::new(GeneratorKind::AmbientOcclusion) }; assert_all(&mask(&mut fixture, empty, &texels), OCCLUSION * 0.5, "half way to black"); } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index a169516b..0dbcc0d7 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1068,9 +1068,12 @@ pub struct Generator { /// The Light generator's controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub light: Option, - /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed) + /// The texture blended over the signal on the section controls (None: Use Texture never touched, as saved before it existed); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] - pub texture: Option, + pub texture: Option>, + /// The image a wear generator reads as its grunge once Use Custom Grunge is on (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grunge: Option, } impl Generator { @@ -1105,12 +1108,12 @@ impl Generator { /// The texture the generator blends over its signal: only on the section controls, turned on with some opacity pub fn texture_in_use(&self) -> Option<&TextureLayer> { - self.texture.as_ref().filter(|texture| texture.in_use() && self.section_controls().is_some()) + self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture and its custom grunge pub fn sources(&self) -> impl Iterator { - self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())) + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -1150,6 +1153,7 @@ impl Generator { section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), texture: None, + grunge: None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 956dbd1a..17975266 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -26,6 +26,9 @@ pub struct WearParameters { pub curvature_weight: f32, /// How much convex edges are kept clean (0..1; Dirt) pub edges_masking: f32, + /// The grunge read from the generator's custom grunge image instead of the kind's own pattern + #[serde(default)] + pub custom_grunge: bool, } impl WearParameters { @@ -45,6 +48,7 @@ impl WearParameters { ao_masking: 0.5, curvature_weight: 1.0, edges_masking: 0.5, + custom_grunge: false, }; match kind { GeneratorKind::EdgeWear | GeneratorKind::Dirt => Some(shared), @@ -76,6 +80,7 @@ impl WearParameters { ao_masking: unit(self.ao_masking, defaults.ao_masking), curvature_weight: unit(self.curvature_weight, defaults.curvature_weight), edges_masking: unit(self.edges_masking, defaults.edges_masking), + custom_grunge: self.custom_grunge, } } } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 39918d33..de36131e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -156,6 +156,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } + if let Some(grunge) = &generator.grunge { + out["grunge"] = source_json(grunge); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 8f67edf9..4369c512 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -53,7 +53,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking? (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id or texture + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture or grunge + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -395,7 +395,7 @@ const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale" const GLOBAL_KEYS: [&str; 3] = ["blur", "balance", "contrast"]; /// The wear controls `effect.add.generator` and `effect.set` take -const WEAR_KEYS: [&str; 10] = [ +const WEAR_KEYS: [&str; 11] = [ "wearLevel", "wearContrast", "grungeAmount", @@ -406,16 +406,21 @@ const WEAR_KEYS: [&str; 10] = [ "aoMasking", "curvatureWeight", "edgesMasking", + "useCustomGrunge", ]; -/// The wear controls in `params`: they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model +/// The input name of a wear generator's custom grunge image, beside the mesh map ids +const GRUNGE_INPUT: &str = "grunge"; + +/// The wear controls in `params` (a grunge input counts as one): they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let wear_given = given(&WEAR_KEYS) || strp(params, "input") == Some(GRUNGE_INPUT); let Some(defaults) = WearParameters::defaults(generator.kind) else { - return if given(&WEAR_KEYS) { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; + return if wear_given { Err(bad(command, "only Metal Edge Wear, Fiber Glass Edge Wear and Dirt have wear controls")) } else { Ok(()) }; }; - let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !given(&WEAR_KEYS) && generator.kind != GeneratorKind::FiberGlassEdgeWear); + let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !wear_given && generator.kind != GeneratorKind::FiberGlassEdgeWear); if given(&GLOBAL_KEYS) && !earlier_model { return Err(bad(command, format!("{} has no global blur, balance or contrast on its wear controls", generator.kind.label()))); } @@ -424,7 +429,7 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result } if given(&EARLIER_WEAR_KEYS) { - if given(&WEAR_KEYS) { + if wear_given { return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both")); } if generator.kind == GeneratorKind::FiberGlassEdgeWear { @@ -433,7 +438,7 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result generator.wear = None; return Ok(()); } - if !given(&WEAR_KEYS) { + if !wear_given { return Ok(()); } @@ -458,6 +463,9 @@ fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result if let Some(triplanar) = boolp(params, "triplanar") { wear.triplanar = triplanar; } + if let Some(custom_grunge) = boolp(params, "useCustomGrunge") { + wear.custom_grunge = custom_grunge; + } *wear = wear.clamped(generator.kind); Ok(()) } @@ -633,7 +641,7 @@ fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Res if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) { return Ok(()); } - let mut texture = generator.texture.clone().unwrap_or_default(); + let mut texture = generator.texture.as_deref().cloned().unwrap_or_default(); if let Some(enabled) = boolp(params, "useTexture") { texture.enabled = enabled; } @@ -662,7 +670,7 @@ fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Res let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?; texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?; } - generator.texture = Some(texture.clamped()); + generator.texture = Some(Box::new(texture.clamped())); Ok(()) } @@ -803,20 +811,22 @@ fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value Ok(Some(Some(MicroDetail { anchor, amount }))) } -/// A generator input a command names: a mesh map it reads, or its texture +/// A generator input a command names: a mesh map it reads, its texture or its custom grunge #[derive(Clone, Copy)] enum GeneratorInput { Map(BakedMap), Texture, + Grunge, } -/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture slot), for a generator on layer `owner` +/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id or `texture`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture` or `grunge`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, + GRUNGE_INPUT => GeneratorInput::Grunge, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -1149,6 +1159,8 @@ fn set(session: &mut Session, params: &Value) -> Result { } // generator_from refused the texture on kinds without one and moved the generator onto its section controls Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, + // generator_from refused the grunge on kinds without wear controls and moved the generator onto them + Some((GeneratorInput::Grunge, source)) => generator.grunge = source, None => {} } } @@ -1281,6 +1293,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { global: current.global, resolution: current.resolution, inputs, + grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), ..Generator::new(kind) } } diff --git a/crates/engine/tests/it/generator_custom_grunge.rs b/crates/engine/tests/it/generator_custom_grunge.rs new file mode 100644 index 00000000..4bb171b6 --- /dev/null +++ b/crates/engine/tests/it/generator_custom_grunge.rs @@ -0,0 +1,104 @@ +//! A wear generator's custom grunge through `effect.set`: Use Custom Grunge, its image as the `grunge` input, and the kinds without one + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, LayerId, Source}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("grunge.png", bytes).unwrap() +} + +#[test] +fn use_custom_grunge_is_a_wear_control_of_every_wear_kind() { + let mut session = session(); + for kind in ["edgeWear", "fiberGlassEdgeWear", "dirt"] { + let effect = add(&mut session, json!({"generator": kind})); + let wear = |session: &Session| generator(session, effect).wear.map(|wear| wear.custom_grunge); + assert_ne!(wear(&session), Some(true), "{kind}: off until turned on"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "useCustomGrunge": true})).unwrap(); + assert_eq!(wear(&session), Some(true), "{kind}"); + } +} + +#[test] +fn the_grunge_image_is_the_grunge_input_and_stays_a_used_resource() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "dirt", "wearLevel": 0.6})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + let plugged = generator(&session, effect); + assert_eq!(plugged.grunge, Some(Source::image(name.clone()))); + assert!(plugged.inputs.is_empty(), "the grunge is not a mesh map input"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the grunge"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).grunge, None, "inputBaked empties the slot"); +} + +#[test] +fn a_grunge_image_moves_an_earlier_wear_generator_onto_its_wear_controls() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "edgeWear", "level": 0.8})); + assert_eq!(generator(&session, effect).wear, None); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + assert!(generator(&session, effect).wear.is_some()); + + let both = json!({"effect": effect, "input": "grunge", "inputImage": name, "level": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "a grunge image and the earlier model at once"); + let both = json!({"effect": effect, "useCustomGrunge": true, "softness": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "Use Custom Grunge and the earlier model at once"); +} + +#[test] +fn kinds_without_wear_controls_refuse_a_custom_grunge() { + let mut session = session(); + let name = gray_image(&mut session); + for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction", "thinAreas"] { + let effect = add(&mut session, json!({"generator": kind})); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "useCustomGrunge": true})).is_err(), "{kind} useCustomGrunge"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).is_err(), "{kind} grunge input"); + assert_eq!(generator(&session, effect).grunge, None, "{kind}"); + } +} + +#[test] +fn swapping_between_wear_kinds_keeps_the_grunge_image() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "edgeWear"})); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "grunge", "inputImage": name})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "dirt"})).unwrap(); + assert_eq!(generator(&session, effect).grunge, Some(Source::image(name)), "Dirt reads a custom grunge too"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "curvature"})).unwrap(); + assert_eq!(generator(&session, effect).grunge, None, "Curvature has no grunge"); +} diff --git a/crates/engine/tests/it/generator_texture.rs b/crates/engine/tests/it/generator_texture.rs index 9d640515..b3dad7b7 100644 --- a/crates/engine/tests/it/generator_texture.rs +++ b/crates/engine/tests/it/generator_texture.rs @@ -48,7 +48,7 @@ fn texture_controls_start_from_the_reference_defaults_and_clamp() { grayscale: GeneratorGrayscale::Red, ..TextureLayer::default() }; - assert_eq!(generator(&session, effect).texture, Some(expected)); + assert_eq!(generator(&session, effect).texture, Some(Box::new(expected))); assert_eq!(TextureLayer::default().opacity, 0.0, "the reference starts the texture at opacity 0"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "textureBlend": "dissolve"})).is_err()); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 140ea6ff..de497d5a 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -35,6 +35,7 @@ mod filter_transform; mod filters; mod folder_contents; mod frame_selection; +mod generator_custom_grunge; mod generator_inputs; mod generator_sections; mod generator_swap; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 3cadca28..62b3d0bb 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -52,7 +52,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(generator.kind) { section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); - texture_parameters(app, ui, id, generator.texture.clone().unwrap_or_default()); + texture_parameters(app, ui, id, generator.texture.as_deref().cloned().unwrap_or_default()); } if let Some(defaults) = LightParameters::defaults(generator.kind) { light_parameters(app, ui, id, None, defaults); From 73900d425260ada3f91eabdf205b71236065afab Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:55:06 +0000 Subject: [PATCH 13/54] Generators: Micro Details add a height or normal image's curvature and occlusion Curvature, Ambient Occlusion and the three wear kinds take the reference's Micro Details: Use Micro Details (Curvature and Ambient Occlusion), Micro Height, Micro Normal, Curvature Type (Standard, Sobel, Smooth), Curvature Intensity, Height Details Intensity, AO Radius and AO Depth, with the images as the microHeight and microNormal inputs of effect.set (an image or a value; an empty slot reads black). Fitted to the reference app: the micro height becomes a normal, and that normal's divergence (Smooth: the height against blurred copies of itself) is added to the curvature input before the detail sizes blur it, with a small per-type lift; the micro normal adds its own divergence. Ambient Occlusion is multiplied by a horizon occlusion of the micro height over 16 directions. Both are built once per mesh map, image and settings and cached; derivatives and radii are per texel at 2K, so the look holds across resolutions. Off by default, so existing projects render as before; the controls move an earlier-model generator onto the reference's controls, are refused on kinds without them, and the images stay across swaps between kinds that have them. --- crates/compose/src/curvature_sizes.rs | 6 +- crates/compose/src/eval.rs | 277 ++++---- crates/compose/src/generator_maps.rs | 34 + crates/compose/src/lib.rs | 2 + crates/compose/src/micro_details.rs | 626 ++++++++++++++++++ .../compose/tests/generator_micro_details.rs | 211 ++++++ crates/core/src/block_scales.rs | 18 + crates/core/src/layer.rs | 90 ++- .../core/src/layer/anchored_micro_detail.rs | 18 + crates/core/src/layer/micro_curvature_type.rs | 30 + crates/core/src/layer/micro_detail.rs | 16 - crates/core/src/layer/micro_details.rs | 121 ++++ crates/core/src/lib.rs | 2 +- crates/engine/src/anchored_micro_edit.rs | 71 ++ crates/engine/src/inspect.rs | 6 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_cmds.rs | 74 +-- crates/engine/src/micro_params.rs | 91 +++ crates/engine/tests/it/content_effects.rs | 55 +- .../tests/it/generator_micro_details.rs | 133 ++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/dock.rs | 18 - crates/ui-egui/src/generator_panel.rs | 40 +- crates/ui-egui/tests/it/generator_panel.rs | 5 +- crates/ui-egui/tests/ui_snapshots.rs | 30 - 25 files changed, 1658 insertions(+), 319 deletions(-) create mode 100644 crates/compose/src/generator_maps.rs create mode 100644 crates/compose/src/micro_details.rs create mode 100644 crates/compose/tests/generator_micro_details.rs create mode 100644 crates/core/src/layer/anchored_micro_detail.rs create mode 100644 crates/core/src/layer/micro_curvature_type.rs delete mode 100644 crates/core/src/layer/micro_detail.rs create mode 100644 crates/core/src/layer/micro_details.rs create mode 100644 crates/engine/src/anchored_micro_edit.rs create mode 100644 crates/engine/src/micro_params.rs create mode 100644 crates/engine/tests/it/generator_micro_details.rs diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index f47d9fcb..4a95ff17 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -34,7 +34,11 @@ const CACHE_MAPS: usize = 16; impl CurvatureSizes { /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { - let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + CurvatureSizes::of_map(inp, inp.baked.maps.get(&BakedMap::Curvature)?, needed) + } + + /// The sizes of `curvature`, a map in the baked curvature map's layout (the baked map or one derived from it) + pub fn of_map(inp: &Inputs, curvature: &Arc>, needed: &[bool]) -> Option> { let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); if !needed.contains(&true) || width == 0 || height == 0 { return None; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 44875108..2bf1cf69 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -14,7 +14,7 @@ use rayon::prelude::*; use texturecraft_core::{ AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, MicroDetail, Mirror, NormalFormat, PreparedColorMatch, + HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; @@ -31,8 +31,10 @@ use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; +use crate::micro_details::AnchorHeights; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, placement, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; @@ -292,8 +294,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, - /// The curvature detail sizes a generator with detail reads. - curvature_sizes: Option>, + /// The detail sizes and micro details a generator reads + maps: GeneratorMaps, /// A filtered mask stage retained because an anchor above it records that stage. filtered_mask: Option<&'a Field>, /// The projector's depth map of a fill or material effect that culls by depth @@ -1694,7 +1696,7 @@ fn filter_region( let height_nodes = if heights { plan_in(inputs, &[id], &[Channel::Height], tile_x, tile_y, 0, Some(below), place, None) } else { Vec::new() }; let mut mask = None; let mut nodes = Vec::new(); - let mut generator_sizes = None; + let mut generator_maps = GeneratorMaps::default(); match job { Job::Mask(layer_mask) => { // The layer's own filtered content, for a compare of it (this mask's field is not built yet) @@ -1702,7 +1704,7 @@ fn filter_region( continue; }; - generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); + generator_maps = mask_stack.effects.get(index).map(|effect| effect.maps.clone()).unwrap_or_default(); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); @@ -1727,7 +1729,7 @@ fn filter_region( let value = match (&mask, nodes.first()) { (Some(mask_stack), _) => { - let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, &generator_maps)); let texture = generator.and_then(|(generator, _)| texel.generator_texture(generator)).unwrap_or(0.0); [texel.mask(mask_stack), ramp, texture, 0.0] } @@ -2298,6 +2300,7 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La draw_order(inp, list, 0, around.into(), &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); prepare_curvature_sizes(inp, &ids); + prepare_micro_anchors(inp); // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); @@ -2395,6 +2398,59 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { prepare_mask_curvature_sizes(inp, masks); } +/// Build the height of every anchor point a visible generator's Micro Height reads, over the whole texture set, before tiles composite in parallel +fn prepare_micro_anchors(inp: &EvaluationInputs) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + let tree = inp.project.render_tree(&set.stack); + let visible = tree.iter().filter_map(|id| inp.project.layers.get(id)).filter(|layer| layer.visible); + let mut readers: Vec<(LayerId, LayerId)> = Vec::new(); + for layer in visible { + let effects = layer_mask(inp.project, layer.id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); + for effect in effects.filter(|effect| effect.visible) { + if let EffectKind::Generator(generator) = &effect.kind + && let Some(micro) = generator.micro_in_use().filter(|micro| micro.height) + && let Some(Source::Anchor { anchor, .. }) = µ.height_source + && !readers.iter().any(|(_, read)| read == anchor) + { + readers.push((layer.id, *anchor)); + } + } + } + if readers.is_empty() { + return; + } + + for (reader, anchor) in readers { + let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; + crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); + } +} + +/// Anchor point `anchor`'s height over the whole texture set as layer `reader` reads it, in the working atlas's layout +fn anchor_heights(inp: &EvaluationInputs, reader: LayerId, anchor: LayerId) -> AnchorHeights { + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + let channels = evaluation_channels(inp, vec![Channel::Height]); + let fields = evaluation_fields(inp, &channels, &all_tiles(width, height)); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut data = vec![0.0f32; width_usize * height as usize]; + + // Each tile row writes its own atlas rows + data.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + let nodes = anchor_plan(inp, (reader, 0), &channels, tile_x, tile_y as u32, Some(&fields)); + for (x, y, offset) in tile_texels(inp.gbuf, tile_x, tile_y as u32) { + let mut texel = Texel::new(inp, x, y, offset, 0.0); + texel.anchors_below(&nodes, (reader, 0)); + if let Some(destination) = rows.get_mut((y as usize % tile_side) * width_usize + x as usize) { + *destination = texel.anchored(anchor, Channel::Height)[0]; + } + } + } + }); + AnchorHeights::new(data, (width, height), inp.block_scales.clone()) +} + /// The blurred curvature levels `generator` reads: its wear's smoothing, else its detail sizes (a replaced curvature input reads none) fn curvature_sizes_in_use(generator: &Generator) -> [bool; LEVEL_RADII.len()] { if generator.inputs.contains_key(&BakedMap::Curvature) { @@ -2418,6 +2474,11 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator( Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let curvature_sizes = match &effect.kind { - EffectKind::Generator(generator) => CurvatureSizes::of(inp, &curvature_sizes_in_use(generator)), - _ => None, + let maps = match &effect.kind { + EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)), + _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { EffectKind::Fill { projection, sampling, .. } | EffectKind::Material(Fill { projection, sampling, .. }) => { @@ -2492,7 +2553,7 @@ fn effect_plans<'a>( opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes, + maps, filtered_mask: None, depth, covers_all, @@ -3332,9 +3393,9 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The generator's ramp at this texel, before its global blur, balance, contrast and invert (on the section controls, before those too). - fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + fn generator_ramp(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { if let Some(wear) = wear_parameters(generator) { - return self.wear_ramp(generator, &wear, curvature_sizes); + return self.wear_ramp(generator, &wear, maps); } if let Some(light) = &generator.light { let normal = @@ -3343,32 +3404,29 @@ impl<'a, 'b> Texel<'a, 'b> { return sections::light_value(light, normal, position, generator.invert); } if let Some(section) = generator.section_controls() { - return self.section_signal(generator, §ion, curvature_sizes); + return self.section_signal(generator, §ion, maps); } let coords = self.coords(); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); + + // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(detail, sizes, curvature) } - (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => { - (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0 - } - (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.occlusion_input(generator, maps).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.occlusion_input(generator, maps).unwrap_or(1.0), (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals always computes with its section controls: this arm only keeps the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, }; - let signal = - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3389,33 +3447,16 @@ impl<'a, 'b> Texel<'a, 'b> { ramp * ramp * (3.0 - 2.0 * ramp) } - /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where - /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. - fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { - let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; - let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; - let response = height.clamp(-1.0, 1.0) * amount; - match kind { - GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::FiberGlassEdgeWear => response, - - // Dirt gathers in dents; dents are occluded - GeneratorKind::Dirt => -response, - GeneratorKind::AmbientOcclusion => response, - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => 0.0, - } - } - /// The signal a generator on its section controls adjusts at this texel: the axes of its map, its curvature or its occlusion - fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + fn section_signal(&mut self, generator: &Generator, section: &SectionParameters, maps: &GeneratorMaps) -> f32 { match generator.kind { GeneratorKind::Curvature => { let detail = generator.detail_in_use().unwrap_or_default(); - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; - let curvature = self.generator_input(generator, BakedMap::Curvature); - let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); - self.curvature_detail(&detail, sizes, curvature, micro) + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; + let curvature = self.curvature_input(generator, maps); + self.curvature_detail(&detail, sizes, curvature) } - GeneratorKind::AmbientOcclusion => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), GeneratorKind::Position => { let position = self.position_input(generator); sections::axes_signal(position, §ion.axes) @@ -3444,14 +3485,14 @@ impl<'a, 'b> Texel<'a, 'b> { } /// A wear generator's value at this texel from its curvature, occlusion and grunge, before its global adjustments and invert - fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let curvature = self.generator_input(generator, BakedMap::Curvature).map_or(0.0, |curvature| curvature - 0.5); + fn wear_ramp(&mut self, generator: &Generator, wear: &WearParameters, maps: &GeneratorMaps) -> f32 { + let curvature = self.curvature_input(generator, maps).map_or(0.0, |curvature| curvature - 0.5); // Blurred levels are copies of the mesh map, so a replaced curvature input is read at its own size only - let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let blurred_curvature = self.blurred_curvature(wear::blur_sigma(generator.kind, wear), sizes, curvature); - let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0); + let occlusion = self.occlusion_input(generator, maps).unwrap_or(1.0); let grunge = if wear.custom_grunge { // An image not loaded yet reads mid gray, which leaves the wear as without grunge let gray = self.slot_color(generator, generator.grunge.as_ref(), &wear::custom_grunge_placement(wear)).map_or(0.5, lum); @@ -3485,8 +3526,8 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let ramp = self.generator_ramp(generator, curvature_sizes); + fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { + let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), @@ -3529,6 +3570,22 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The generator's curvature input at this texel with what its micro details add + fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let curvature = self.generator_input(generator, BakedMap::Curvature)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_curvature.as_ref().and_then(|micro| micro.term.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(curvature + micro.unwrap_or(0.0)) + } + + /// The generator's occlusion input at this texel, darkened by its micro details + fn occlusion_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { + let occlusion = self.generator_input(generator, BakedMap::AmbientOcclusion)?; + let working_size = (self.res, self.inp.gbuf.height); + let micro = maps.micro_occlusion.as_ref().and_then(|micro| micro.at((self.x, self.y), working_size, &self.inp.block_scales)); + Some(occlusion * micro.unwrap_or(1.0)) + } + /// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked). fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option { match generator.inputs.get(&map) { @@ -3547,19 +3604,15 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { - let combine = |edges: f32, cavities: f32| { - let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); - let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); - match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), - } + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), }; - // Without baked curvature, only painted micro height supplies edges or cavities + // Without curvature to read the texel is flat: no edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; @@ -3649,7 +3702,7 @@ impl<'a, 'b> Texel<'a, 'b> { value += (blend1(effect.blend, value, fill) - value) * opacity * cover; } EffectKind::Generator(generator) => { - let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + let generated = self.generator(generator, &effect.maps); value += (blend1(effect.blend, value, generated) - value) * opacity; } EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, @@ -5159,7 +5212,8 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti mod tests { use super::*; use texturecraft_core::{ - ChannelBlend, CompareOp, Effect, Layer, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, TextureSet, + ChannelBlend, CompareOp, Effect, Layer, MicroDetails, OutputResolution, PbrValidate, Procedural, ProceduralKind, ResolutionMode, StylizedLighting, + TextureSet, }; use texturecraft_geom::primitives; @@ -6999,85 +7053,46 @@ soft {soft:?}" } #[test] - fn generator_micro_detail_follows_the_anchor_height() { + fn a_micro_height_read_from_an_anchor_follows_its_raised_region() { let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let disc = (0..64 * 64) + .map(|index| { + let (x, y) = ((index % 64) as f32 - 31.5, (index / 64) as f32 - 31.5); + if x * x + y * y < 100.0 { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] } + }) + .collect(); + let images: ImageStore = [("disc".to_string(), Arc::new(ImageRes::new(64, 64, disc, false)))].into(); let low = fixture.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + fill.sources.insert(Channel::Height, Source::image("disc")); fixture.project.insert_layer(0, Layer::new(low, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); - let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::Curvature) }; - let with = |fixture: &mut Fixture, generator: &Generator| { + let colors = |fixture: &mut Fixture, generator: &Generator| -> Vec { let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(generator.clone()))); fixture.project.layer_mut(top).unwrap().mask = Some(mask); - run(fixture, None).value(Channel::BaseColor, 5, 5)[0] + let composite = run_with_images(fixture, None, &images); + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() }; + let largest_change = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); - // No curvature map: flat mid gray, so the mask is 0.5 and the base color 0.75 - let flat = with(&mut fixture, &generator); - assert!((flat - 0.75).abs() < 0.02, "{flat}"); + // Curvature on its section controls, then on the earlier model a project saved before Micro Details keeps + let section = Generator::new(GeneratorKind::Curvature); + let earlier = Generator { section: None, level: 0.5, softness: 0.5, noise_amount: 0.0, ..section.clone() }; + for plain in [section, earlier] { + let off = colors(&mut fixture, &plain); + let read = Generator { micro: MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, 1.0).map(Box::new), ..plain.clone() }; - // Raised height reads as an edge - generator.micro = Some(MicroDetail { anchor, amount: 1.0 }); - assert!(with(&mut fixture, &generator) > flat + 0.2); + let raised = colors(&mut fixture, &read); + assert!(largest_change(&raised, &off) > 0.05, "the raised disc's rim reads as curvature"); - // Recessed height reads as a cavity; dirt gathers there - if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(low).unwrap().kind { - fill.sources.insert(Channel::Height, Source::Uniform([-0.5; 3])); - } - assert!(with(&mut fixture, &generator) < flat - 0.2); - let dirt = - Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, micro: Some(MicroDetail { anchor, amount: 1.0 }), ..Generator::new(GeneratorKind::Dirt) }; - let plain = Generator { micro: None, ..dirt.clone() }; - assert!(with(&mut fixture, &dirt) > with(&mut fixture, &plain) + 0.2); - - // A hostile amount does nothing - generator.micro = Some(MicroDetail { anchor, amount: f32::NAN }); - assert!((with(&mut fixture, &generator) - flat).abs() < 0.02); - } - - #[test] - fn curvature_modes_classify_raised_and_recessed_micro_height() { - let mut fixture = fixture(); - fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; - let lower = fixture.project.alloc_id(); - let mut fill = Fill::default(); - fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); - fixture.project.insert_layer(0, Layer::new(lower, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); - let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); - let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); - - for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { - for (height, mode, responds) in [ - (0.5, CurvatureMode::Edges, true), - (-0.5, CurvatureMode::Edges, false), - (0.5, CurvatureMode::Cavities, false), - (-0.5, CurvatureMode::Cavities, true), - (0.5, CurvatureMode::Both, true), - (-0.5, CurvatureMode::Both, true), - ] { - if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind { - fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); - } - let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; - let generator = Generator { - level: 0.5, - softness: 0.5, - noise_amount: 0.0, - detail: Some(detail), - micro: Some(MicroDetail { anchor, amount: 1.0 }), - ..Generator::new(kind) - }; - let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); - fixture.project.layer_mut(top).unwrap().mask = Some(mask); - - let value = run(&fixture, None).value(Channel::BaseColor, 5, 5)[0]; - let expected = if responds { 0.75 } else { 0.5 }; - assert!((value - expected).abs() < 0.02, "{kind:?} {mode:?} height {height}: {value}"); + let mut emptied = read.clone(); + if let Some(micro) = emptied.micro.as_mut() { + micro.height_source = None; } + assert_eq!(colors(&mut fixture, &emptied), off, "without an anchor the micro details change nothing"); } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs new file mode 100644 index 00000000..6bc18477 --- /dev/null +++ b/crates/compose/src/generator_maps.rs @@ -0,0 +1,34 @@ +//! The precomputed maps one generator reads: its curvature detail sizes and its micro details + +use std::sync::Arc; + +use texturecraft_core::{BakedMap, Generator, MicroDetails}; + +use crate::curvature_sizes::CurvatureSizes; +use crate::eval::Inputs; +use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; + +/// What a generator reads beyond its texel: built once per map and settings, shared by every tile +#[derive(Clone, Default)] +pub(crate) struct GeneratorMaps { + /// The curvature detail sizes it reads (of its micro curvature when it has some) + pub sizes: Option>, + /// The curvature its micro details add + pub micro_curvature: Option>, + /// What its micro details multiply its occlusion by + pub micro_occlusion: Option>, +} + +impl GeneratorMaps { + /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { + let micro = generator.micro_in_use(); + let micro_curvature = micro.filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); + let micro_occlusion = micro.filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); + let sizes = match µ_curvature { + Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), + None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion } + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 3c921ff9..b3f52141 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -25,9 +25,11 @@ mod fill_depth; mod fill_place; pub mod frame_placement; mod fur_lock; +mod generator_maps; mod held_fields; mod image_identity; mod mask_gray; +mod micro_details; pub mod mip_level; mod organic; pub mod pattern; diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details.rs new file mode 100644 index 00000000..d81fabf9 --- /dev/null +++ b/crates/compose/src/micro_details.rs @@ -0,0 +1,626 @@ +//! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings + +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, GeneratorKind, LayerId, MicroCurvatureType, MicroDetails, NormalFormat, Source}; + +use crate::below::StackKey; +use crate::eval::Inputs; +use crate::store::ImageRes; + +/// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted) +const HEIGHT_NORMAL_STRENGTH: f32 = 5.9; + +/// Blur sizes of the Smooth type, in texels at 2K: the height against each of these blurred copies +const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]; + +/// Below this sigma a blur is an explicit kernel; wider ones are three box passes +const BOX_BLUR_MIN_SIGMA: f32 = 2.0; + +/// Directions the occlusion looks along +const OCCLUSION_DIRECTIONS: usize = 16; + +/// Most steps the occlusion takes along each direction; longer radii step further each time +const OCCLUSION_STEPS: usize = 16; + +/// The occlusion radius in texels at 1K for AO Radius 1, and its exponent (fitted: radius 0.3 reaches about 6 texels, 1 about 48) +const OCCLUSION_RADIUS_TEXELS_1K: f32 = 47.675; +const OCCLUSION_RADIUS_POWER: f32 = 1.663; + +/// Shorter radii at 1K occlude nothing: the reference is unchanged at AO Radius 0.1 (about 1 texel) and occludes from 0.2 (about 3) +const MIN_OCCLUSION_RADIUS_TEXELS_1K: f32 = 2.0; + +/// How steep the micro height reads for occlusion per texel at 1K at AO Depth 1, and its exponent (fitted) +const OCCLUSION_DEPTH_SCALE_1K: f32 = 1473.8; +const OCCLUSION_DEPTH_POWER: f32 = 1.0654; + +/// How dark a fully occluding horizon makes the occlusion (fitted) +const OCCLUSION_STRENGTH: f32 = 0.3232; + +/// Cached micro maps; each entry is small next to the curvature sizes it feeds +const CACHE_ENTRIES: usize = 8; + +/// A map in a mesh map's layout: `size` texels, each UV tile one block +pub struct LayoutMap { + data: Vec, + size: (u32, u32), +} + +impl LayoutMap { + /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) + pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { + let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = scales.bake_uv(uv, working_size)?; + let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); + let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); + self.data.get((row * self.size.0 + column) as usize).copied() + } +} + +/// The curvature a generator's micro details add +pub struct MicroCurvature { + /// What they add to the curvature input + pub term: LayoutMap, + /// The baked curvature with the term added, which the detail sizes blur + pub curvature: Arc>, +} + +/// An anchor point's height over the whole texture set, in the working atlas's layout +pub struct AnchorHeights { + data: Vec, + working_size: (u32, u32), + scales: BlockScales, +} + +impl AnchorHeights { + pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { + AnchorHeights { data, working_size, scales } + } + + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) + fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { + let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; + let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; + + let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); + let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); + self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) + } +} + +/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key +struct AnchorEntry { + baked: Weak>, + texture_set: usize, + anchor: LayerId, + stack: StackKey, + heights: Arc, +} + +/// The anchor heights prepared last, one per mesh maps, texture set and anchor +static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); + +/// The mesh maps (by address) and texture sets whose anchor heights are being built: the build composites the stack, which prepares them again +static BUILDING_ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); + +/// A mesh map that tells one session's baked maps from another's (None without curvature or occlusion) +fn baked_identity(inp: &Inputs) -> Option>> { + [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inp.baked.maps.get(map)).map(Arc::downgrade) +} + +/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless `stack` is the stack they were built for +pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: StackKey, build: impl FnOnce() -> AnchorHeights) { + let Some(baked) = baked_identity(inp) else { return }; + let matches = |entry: &AnchorEntry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor; + { + let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|entry| entry.baked.strong_count() > 0); + if entries.iter().any(|entry| matches(entry) && entry.stack == stack) { + return; + } + } + + // Built outside the lock: the build composites the stack in parallel, and leaves the anchors it meets unprepared + let building = (baked.as_ptr() as usize, inp.ts); + { + let mut active = BUILDING_ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if active.contains(&building) { + return; + } + active.push(building); + } + let heights = Arc::new(build()); + BUILDING_ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).retain(|active| *active != building); + let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|entry| !matches(entry)); + entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); + let excess = entries.len().saturating_sub(CACHE_ENTRIES); + entries.drain(..excess); +} + +/// The heights prepared for anchor `anchor` (None before they are) +fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { + let baked = baked_identity(inp)?; + let entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.iter().find(|entry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor).map(|entry| entry.heights.clone()) +} + +/// What a micro details slot reads +#[derive(Clone)] +enum Slot { + Uniform([f32; 3]), + Image { + image: Arc, + flip_green: bool, + }, + /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map + Anchor { + heights: Arc, + origin: (u32, u32), + layout: (u32, u32), + }, +} + +impl Slot { + /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) + fn of(inp: &Inputs, source: Option<&Source>) -> Slot { + match source { + Some(Source::Uniform(value)) => Slot::Uniform(*value), + Some(Source::Image { name, normal_format }) => match inp.images.get(name) { + Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, + None => Slot::Uniform([0.0; 3]), + }, + Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { + Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, + None => Slot::Uniform([0.0; 3]), + }, + _ => Slot::Uniform([0.0; 3]), + } + } + + /// Whether every UV tile block reads the same (an image or a value repeats in each) + fn same_in_every_block(&self) -> bool { + !matches!(self, Slot::Anchor { .. }) + } + + /// The slot read in the block at `origin` of a `layout` sized mesh map + fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { + match self { + Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, + other => other.clone(), + } + } + + fn key(&self) -> SlotKey { + match self { + Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), + Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), + Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), + } + } + + /// The slot's color at `uv`, in the file's encoding + fn color(&self, uv: [f32; 2]) -> [f32; 3] { + match self { + Slot::Uniform(value) => *value, + Slot::Image { image, .. } => { + let [red, green, blue, _] = image.sample(uv[0], uv[1]); + [red, green, blue] + } + Slot::Anchor { .. } => [0.0; 3], + } + } + + /// The slot read as a height (its gray) over a `size` block + fn heights(&self, size: (u32, u32)) -> Vec { + match self { + Slot::Anchor { heights, origin, layout } => { + (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() + } + _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), + } + } + + /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention + fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { + let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); + block_uvs(size) + .map(|uv| { + let [red, green, _] = self.color(uv); + let y = green * 2.0 - 1.0; + (red * 2.0 - 1.0, if flip_green { -y } else { y }) + }) + .unzip() + } +} + +/// The UV of each texel's center in a `size` block, row by row +fn block_uvs((width, height): (u32, u32)) -> impl Iterator { + (0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32])) +} + +/// A slot as a cache key: an image by identity, a value by its bits +#[derive(Clone)] +enum SlotKey { + Uniform([u32; 3]), + Image(Weak, bool), + Anchor(Weak), +} + +impl PartialEq for SlotKey { + fn eq(&self, other: &SlotKey) -> bool { + match (self, other) { + (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, + (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, + (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), + _ => false, + } + } +} + +/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block +#[derive(Clone)] +struct Key { + map: Weak>, + height: Option, + normal: Option, + settings: Vec, + block: (u32, u32), +} + +impl PartialEq for Key { + fn eq(&self, other: &Key) -> bool { + self.map.strong_count() > 0 + && self.map.ptr_eq(&other.map) + && self.height == other.height + && self.normal == other.normal + && self.settings == other.settings + && self.block == other.block + } +} + +/// Built maps by what they were built from, most recently used last +struct Cache { + entries: Mutex)>>, +} + +impl Cache { + const fn new() -> Cache { + Cache { entries: Mutex::new(Vec::new()) } + } + + /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) + fn get_or_build(&self, key: Key, build: impl FnOnce() -> T) -> Arc { + let found = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.map.strong_count() > 0); + entries.iter().position(|(cached, _)| *cached == key).map(|index| { + let entry = entries.remove(index); + let built = entry.1.clone(); + entries.push(entry); + built + }) + }; + if let Some(built) = found { + return built; + } + + let built = Arc::new(build()); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, built.clone())); + let excess = entries.len().saturating_sub(CACHE_ENTRIES); + entries.drain(..excess); + built + } +} + +static CURVATURE_CACHE: Cache = Cache::new(); +static OCCLUSION_CACHE: Cache = Cache::new(); + +/// A baked map, its size and the size of one UV tile's block in it +type MapLayout = (Arc>, (u32, u32), (u32, u32)); + +/// The baked `map`'s layout (None when it isn't baked) +fn layout(inp: &Inputs, map: BakedMap) -> Option { + let data = inp.baked.maps.get(&map)?.clone(); + let size = (inp.baked.resolution, inp.baked.height(map)); + if size.0 == 0 || size.1 == 0 { + return None; + } + + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + Some((data, size, (block.0.max(1).min(size.0), block.1.max(1).min(size.1)))) +} + +/// `per_block` run on each UV tile block of a `size` map, its results placed into one map +fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per_block: impl Fn((u32, u32), (u32, u32)) -> Vec + Sync) -> Vec { + let blocks: Vec<(u32, u32)> = (0..size.1).step_by(block.1 as usize).flat_map(|y| (0..size.0).step_by(block.0 as usize).map(move |x| (x, y))).collect(); + + // Every block is a whole UV tile, so one computation serves them all unless the slots differ per block; a clipped last block differs too + let full = same_in_every_block.then(|| per_block((0, 0), block)); + let mut data = vec![0.0; (size.0 * size.1) as usize]; + for (left, top) in blocks { + let clipped = (block.0.min(size.0 - left), block.1.min(size.1 - top)); + let own = if clipped == block && full.is_some() { None } else { Some(per_block((left, top), clipped)) }; + let Some(values) = own.as_deref().or(full.as_deref()) else { continue }; + for row in 0..clipped.1 { + let source = (row * clipped.0) as usize; + let target = ((top + row) * size.0 + left) as usize; + if let (Some(target), Some(source)) = (data.get_mut(target..target + clipped.0 as usize), values.get(source..source + clipped.0 as usize)) { + target.copy_from_slice(source); + } + } + } + data +} + +impl MicroCurvature { + /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) + pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { + let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; + let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); + let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); + let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; + let key = Key { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; + + Some(CURVATURE_CACHE.get_or_build(key, || { + let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); + let term = by_blocks(size, block, same_in_every_block, |origin, block| { + let height = height.as_ref().map(|height| height.in_block(origin, size)); + let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); + curvature_term(micro, height.as_ref(), normal.as_ref(), block) + }); + let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); + MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } + })) + } +} + +/// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height) +pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails) -> Option> { + let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?; + let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?); + let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()]; + let key = Key { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; + + Some(OCCLUSION_CACHE.get_or_build(key, || { + let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block)); + LayoutMap { data, size } + })) +} + +/// The fitted constants of a curvature type: what it adds everywhere, and its gain on the height and on the normal +fn type_constants(curvature_type: MicroCurvatureType) -> (f32, f32, f32) { + match curvature_type { + MicroCurvatureType::Standard => (0.00876, 12.36, 9.49), + MicroCurvatureType::Sobel => (0.0, 5.72, 4.46), + MicroCurvatureType::Smooth => (-0.00332, 0.969, 34.2), + } +} + +/// The curvature the micro details add over one `size` UV tile block +fn curvature_term(micro: &MicroDetails, height: Option<&Slot>, normal: Option<&Slot>, size: (u32, u32)) -> Vec { + let (offset, height_gain, normal_gain) = type_constants(micro.curvature_type); + let texel_scale = size.0 as f32 / REFERENCE_TILE_TEXELS; + let mut term = vec![offset; (size.0 * size.1) as usize]; + + if let Some(height) = height { + let heights = height.heights(size); + let detail = match micro.curvature_type { + MicroCurvatureType::Smooth => smooth_detail(&heights, size, texel_scale).into_iter().map(|detail| detail * micro.height_intensity).collect(), + MicroCurvatureType::Standard | MicroCurvatureType::Sobel => { + // The height turned into a normal, then that normal's divergence + let strength = HEIGHT_NORMAL_STRENGTH * micro.height_intensity * texel_scale; + let (slope_x, slope_y) = sobel(&heights, size); + let tilted = |slope_x: f32, slope_y: f32| { + let (x, y) = (-strength * slope_x, -strength * slope_y); + let length = (x * x + y * y + 1.0).sqrt(); + (x / length, y / length) + }; + let (normal_x, normal_y): (Vec, Vec) = slope_x.par_iter().zip(slope_y.par_iter()).map(|(x, y)| tilted(*x, *y)).unzip(); + divergence(&normal_x, &normal_y, size, texel_scale) + } + }; + add_scaled(&mut term, &detail, micro.curvature_intensity * height_gain); + } + if let Some(normal) = normal { + let (normal_x, normal_y) = normal.normals(size); + add_scaled(&mut term, &divergence(&normal_x, &normal_y, size, texel_scale), micro.curvature_intensity * normal_gain); + } + term +} + +fn add_scaled(target: &mut [f32], values: &[f32], gain: f32) { + target.par_iter_mut().zip(values.par_iter()).for_each(|(target, value)| *target += value * gain); +} + +/// The Smooth type's detail: the height above its blurred copies, averaged over [`SMOOTH_SIGMAS`] +fn smooth_detail(heights: &[f32], size: (u32, u32), texel_scale: f32) -> Vec { + let mut detail = vec![0.0; heights.len()]; + for sigma in SMOOTH_SIGMAS { + let blurred = gaussian_wrapped(heights, size, sigma * texel_scale); + detail.par_iter_mut().zip(heights.par_iter().zip(blurred.par_iter())).for_each(|(detail, (height, blurred))| *detail += height - blurred); + } + let count = SMOOTH_SIGMAS.len() as f32; + detail.par_iter_mut().for_each(|detail| *detail /= count); + detail +} + +/// The divergence of the `x` and `y` fields, per texel at 2K +fn divergence(x: &[f32], y: &[f32], size: (u32, u32), texel_scale: f32) -> Vec { + let (dx, _) = sobel(x, size); + let (_, dy) = sobel(y, size); + dx.par_iter().zip(dy.par_iter()).map(|(dx, dy)| (dx + dy) * texel_scale).collect() +} + +/// The slope of `values` along X and Y per texel (3×3 Sobel), wrapping around the block like a tiling image +fn sobel(values: &[f32], (width, height): (u32, u32)) -> (Vec, Vec) { + let (width, height) = (i64::from(width.max(1)), i64::from(height.max(1))); + let at = |x: i64, y: i64| values.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0); + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = (texel % width, texel / width); + let column = |dx: i64| at(x + dx, y - 1) + 2.0 * at(x + dx, y) + at(x + dx, y + 1); + let row = |dy: i64| at(x - 1, y + dy) + 2.0 * at(x, y + dy) + at(x + 1, y + dy); + ((column(1) - column(-1)) / 8.0, (row(1) - row(-1)) / 8.0) + }) + .unzip() +} + +/// `values` blurred to `sigma` texels, wrapping around the block like a tiling image +fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> Vec { + let rows = blur_lines(values, width as usize, sigma); + let columns = blur_lines(&transposed(&rows, width as usize, height as usize), height as usize, sigma); + transposed(&columns, height as usize, width as usize) +} + +/// Each `length`-long line of `values` blurred to `sigma`, wrapping around +fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { + let length = length.max(1); + let mut out = vec![0.0; values.len()]; + out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| { + if sigma < BOX_BLUR_MIN_SIGMA { + kernel_blur(line, out, sigma); + } else { + // Three box passes of radius r spread a value with variance r(r + 1) + let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; + let mut current = line.to_vec(); + for _ in 0..3 { + box_blur(¤t, out, radius); + current.copy_from_slice(out); + } + } + }); + out +} + +/// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around +fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { + let reach = (3.0 * sigma).ceil().max(1.0) as i64; + let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); + let total: f32 = weights.iter().sum(); + let length = line.len().max(1) as i64; + for (index, value) in out.iter_mut().enumerate() { + let sum: f32 = (-reach..=reach) + .zip(&weights) + .map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight) + .sum(); + *value = sum / total; + } +} + +/// `line` averaged over `radius` texels each side into `out`, wrapping around +fn box_blur(line: &[f32], out: &mut [f32], radius: usize) { + let length = line.len().max(1) as i64; + let window = (2 * radius + 1) as f32; + let at = |index: i64| line.get(index.rem_euclid(length) as usize).copied().unwrap_or(0.0); + let mut sum: f32 = (-(radius as i64)..=radius as i64).map(at).sum(); + for (index, value) in out.iter_mut().enumerate() { + *value = sum / window; + let index = index as i64; + sum += at(index + radius as i64 + 1) - at(index - radius as i64); + } +} + +fn transposed(values: &[f32], width: usize, height: usize) -> Vec { + let height = height.max(1); + (0..width * height).into_par_iter().map(|texel| values.get((texel % height) * width + texel / height).copied().unwrap_or(0.0)).collect() +} + +/// What the occlusion is multiplied by over one `size` UV tile block: the horizon the micro height raises above its slope, looked for in [`OCCLUSION_DIRECTIONS`] +fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Vec { + let tile_scale = size.0 as f32 / (REFERENCE_TILE_TEXELS / 2.0); + let radius_1k = OCCLUSION_RADIUS_TEXELS_1K * micro.ao_radius.powf(OCCLUSION_RADIUS_POWER); + let radius = (radius_1k * tile_scale).round() as usize; + let count = (size.0 * size.1) as usize; + if radius_1k < MIN_OCCLUSION_RADIUS_TEXELS_1K || radius < 1 { + return vec![1.0; count]; + } + + let depth = OCCLUSION_DEPTH_SCALE_1K * micro.ao_depth.powf(OCCLUSION_DEPTH_POWER) * tile_scale; + let heights = height.heights(size); + let (width, rows) = (i64::from(size.0.max(1)), i64::from(size.1.max(1))); + let at = |x: i64, y: i64| heights.get((y.rem_euclid(rows) * width + x.rem_euclid(width)) as usize).copied().unwrap_or(0.0); + let directions: Vec<(f32, f32)> = (0..OCCLUSION_DIRECTIONS) + .map(|index| std::f32::consts::TAU * index as f32 / OCCLUSION_DIRECTIONS as f32) + .map(|angle| (angle.cos(), angle.sin())) + .collect(); + // Up to OCCLUSION_STEPS distances spread over the radius + let steps: Vec = if radius <= OCCLUSION_STEPS { + (1..=radius).map(|step| step as f32).collect() + } else { + (1..=OCCLUSION_STEPS).map(|step| 1.0 + (radius - 1) as f32 * (step - 1) as f32 / (OCCLUSION_STEPS - 1) as f32).collect() + }; + let sine = |slope: f32| slope / (1.0 + slope * slope).sqrt(); + + (0..width * rows) + .into_par_iter() + .map(|texel| { + let (x, y) = (texel % width, texel / width); + let here = at(x, y); + let gradient = ((at(x + 1, y) - at(x - 1, y)) / 2.0, (at(x, y + 1) - at(x, y - 1)) / 2.0); + let occluded: f32 = directions + .iter() + .map(|(dx, dy)| { + let horizon = steps + .iter() + .map(|distance| (at(x + (dx * distance).round() as i64, y + (dy * distance).round() as i64) - here) / distance) + .fold(f32::NEG_INFINITY, f32::max); + let tangent = gradient.0 * dx + gradient.1 * dy; + (sine(horizon * depth) - sine(tangent * depth)).max(0.0) + }) + .sum(); + 1.0 - OCCLUSION_STRENGTH * occluded / OCCLUSION_DIRECTIONS as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sobel_reads_a_ramp_as_its_slope() { + let size = (8, 8); + let ramp: Vec = (0..64).map(|texel| (texel % 8) as f32 * 0.1).collect(); + let (x, y) = sobel(&ramp, size); + assert!((x[3 * 8 + 3] - 0.1).abs() < 1e-5); + assert!(y[3 * 8 + 3].abs() < 1e-5); + } + + #[test] + fn wrapped_blurs_keep_the_mean() { + let size = (32, 16); + let values: Vec = (0..32 * 16).map(|texel| ((texel * 7919) % 13) as f32).collect(); + let mean = values.iter().sum::() / values.len() as f32; + for sigma in [0.5, 1.0, 4.0] { + let blurred = gaussian_wrapped(&values, size, sigma); + assert!((blurred.iter().sum::() / blurred.len() as f32 - mean).abs() < 1e-3, "sigma {sigma}"); + } + } + + #[test] + fn a_flat_height_adds_only_the_types_offset() { + let mut micro = MicroDetails::defaults(GeneratorKind::Curvature).unwrap(); + let flat = Slot::Uniform([0.4; 3]); + for curvature_type in MicroCurvatureType::ALL { + micro.curvature_type = curvature_type; + let term = curvature_term(µ, Some(&flat), Some(&Slot::Uniform([0.5, 0.5, 1.0])), (16, 16)); + assert!(term.iter().all(|value| (value - type_constants(curvature_type).0).abs() < 1e-6), "{curvature_type:?}"); + } + } + + #[test] + fn a_flat_height_occludes_nothing() { + let micro = MicroDetails::defaults(GeneratorKind::AmbientOcclusion).unwrap(); + let factor = occlusion_factor(µ, &Slot::Uniform([0.7; 3]), (64, 64)); + assert!(factor.iter().all(|value| (value - 1.0).abs() < 1e-6)); + } +} diff --git a/crates/compose/tests/generator_micro_details.rs b/crates/compose/tests/generator_micro_details.rs new file mode 100644 index 00000000..62254619 --- /dev/null +++ b/crates/compose/tests/generator_micro_details.rs @@ -0,0 +1,211 @@ +//! A generator's micro details on a flat plane: a height bump reads as an edge on Curvature and occludes its foot on Ambient Occlusion; off or flat, they change nothing + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, + MicroCurvatureType, MicroDetails, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// Size of the bump image, and the bump's spread in its texels +const BUMP_SIZE: u32 = 64; +const BUMP_SIGMA: f32 = 4.0; + +/// How steep the bump's normal image is drawn +const NORMAL_STRENGTH: f32 = 8.0; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, + images: ImageStore, +} + +/// The bump's height at texel (`x`, `y`) of the bump image: 1 at its center, 0 far away +fn bump_height(x: f32, y: f32) -> f32 { + let center = BUMP_SIZE as f32 / 2.0; + let distance_squared = (x - center).powi(2) + (y - center).powi(2); + (-distance_squared / (2.0 * BUMP_SIGMA * BUMP_SIGMA)).exp() +} + +/// A plane with a white fill layer, flat curvature and no occlusion, and the images `bump` (a height), `bump_normal` and `flat` +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let texels = (RES * RES) as usize; + let maps = [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; texels])), (BakedMap::Curvature, Arc::new(vec![0.5; texels]))]; + let baked = BakedMaps { resolution: RES, maps: maps.into() }; + + let texel_xy = |index: u32| ((index % BUMP_SIZE) as f32 + 0.5, (index / BUMP_SIZE) as f32 + 0.5); + let height = |index: u32| { + let (x, y) = texel_xy(index); + let height = bump_height(x, y); + [height, height, height, 1.0] + }; + let normal = |index: u32| { + let (x, y) = texel_xy(index); + let slope = ((bump_height(x + 0.5, y) - bump_height(x - 0.5, y)), (bump_height(x, y + 0.5) - bump_height(x, y - 0.5))); + let (normal_x, normal_y) = (-NORMAL_STRENGTH * slope.0, -NORMAL_STRENGTH * slope.1); + let length = (normal_x * normal_x + normal_y * normal_y + 1.0).sqrt(); + [normal_x / length * 0.5 + 0.5, normal_y / length * 0.5 + 0.5, 0.5 / length + 0.5, 1.0] + }; + let image = |texel: &dyn Fn(u32) -> [f32; 4]| Arc::new(ImageRes::new(BUMP_SIZE, BUMP_SIZE, (0..BUMP_SIZE * BUMP_SIZE).map(texel).collect(), false)); + let flat = Arc::new(ImageRes::new(4, 4, vec![[0.3, 0.3, 0.3, 1.0]; 16], false)); + let images = [("bump".to_string(), image(&height)), ("bump_normal".to_string(), image(&normal)), ("flat".to_string(), flat)].into(); + Fixture { project, mesh, gbuf, layer, baked, images } +} + +/// Every texel, row by row +fn texels() -> Vec<(u32, u32)> { + (0..RES * RES).map(|index| (index % RES, index / RES)).collect() +} + +/// The texel under the bump's center +fn bump_center() -> usize { + (RES / 2 * RES + RES / 2) as usize +} + +/// The mask of `generator` alone over black at every texel +fn mask(fixture: &mut Fixture, generator: Generator) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, &texels()).unwrap() +} + +/// `kind` with micro details reading `height` (and `normal` when given), edited by `edit` +fn with_micro(kind: GeneratorKind, height: Option<&str>, normal: Option<&str>, edit: impl Fn(&mut MicroDetails)) -> Generator { + let mut micro = MicroDetails { + enabled: true, + height: height.is_some(), + normal: normal.is_some(), + height_source: height.map(Source::image), + normal_source: normal.map(Source::image), + ..MicroDetails::defaults(kind).unwrap() + }; + edit(&mut micro); + let mut generator = Generator::new(kind); + if generator.wear.is_none() && kind != GeneratorKind::FiberGlassEdgeWear && generator.section.is_none() { + generator.wear = texturecraft_core::WearParameters::defaults(kind); + } + generator.micro = Some(Box::new(micro)); + generator +} + +/// Curvature in Raw mode, so a lift and a drop both show +fn raw_curvature(mut generator: Generator) -> Generator { + generator.detail = Some(CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() }); + generator +} + +fn strong(micro: &mut MicroDetails) { + (micro.curvature_intensity, micro.height_intensity) = (5.0, 10.0); +} + +fn mean(values: &[f32]) -> f32 { + values.iter().sum::() / values.len() as f32 +} + +#[test] +fn micro_details_switched_off_change_nothing() { + let mut fixture = fixture(); + for kind in [GeneratorKind::Curvature, GeneratorKind::AmbientOcclusion, GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] { + let plain = mask(&mut fixture, with_micro(kind, None, None, |_| {})); + // Curvature and Ambient Occlusion switch them off whole, the wear kinds by both their images + let switch = MicroDetails::has_switch(kind); + let off = |micro: &mut MicroDetails| (micro.enabled, micro.height, micro.normal) = (!switch, switch, switch); + + let switched_off = mask(&mut fixture, with_micro(kind, Some("bump"), Some("bump_normal"), off)); + assert_eq!(plain, switched_off, "{kind:?}"); + } +} + +#[test] +fn a_micro_height_bump_reads_as_an_edge_on_curvature() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, Some("bump"), None, strong)); + assert!(on[bump_center()] > off[bump_center()] + 0.01, "the bump's top is convex: {} vs {}", on[bump_center()], off[bump_center()]); + assert!((on[0] - off[0]).abs() < 1e-4, "far from the bump the surface stays flat"); +} + +#[test] +fn a_micro_normal_bump_reads_as_an_edge_on_curvature() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::Curvature)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::Curvature, None, Some("bump_normal"), strong)); + assert!(on[bump_center()] > off[bump_center()] + 0.01, "{} vs {}", on[bump_center()], off[bump_center()]); +} + +#[test] +fn standard_lifts_a_flat_micro_height_and_smooth_lowers_it() { + let mut fixture = fixture(); + let typed = |curvature_type| move |micro: &mut MicroDetails| micro.curvature_type = curvature_type; + let sobel = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Sobel))))); + let off = mean(&mask(&mut fixture, raw_curvature(Generator::new(GeneratorKind::Curvature)))); + + let standard = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Standard))))); + let smooth = mean(&mask(&mut fixture, raw_curvature(with_micro(GeneratorKind::Curvature, Some("flat"), None, typed(MicroCurvatureType::Smooth))))); + assert!((sobel - off).abs() < 1e-4, "Sobel adds nothing on a flat height"); + assert!(standard > off + 1e-3 && smooth < off - 1e-4, "standard {standard}, off {off}, smooth {smooth}"); +} + +#[test] +fn a_micro_height_bump_occludes_around_it_on_ambient_occlusion() { + let mut fixture = fixture(); + let deep = |micro: &mut MicroDetails| (micro.ao_radius, micro.ao_depth) = (1.0, 1.0); + let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion)); + let flat = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("flat"), None, deep)); + + let on = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, deep)); + assert_eq!(off, flat, "a flat micro height occludes nothing"); + assert!(on.iter().zip(&off).all(|(on, off)| on <= off), "micro occlusion only darkens"); + assert!(mean(&on) < mean(&off) - 1e-3, "{} vs {}", mean(&on), mean(&off)); +} + +#[test] +fn a_tiny_ao_radius_occludes_nothing() { + let mut fixture = fixture(); + let off = mask(&mut fixture, Generator::new(GeneratorKind::AmbientOcclusion)); + + let tiny = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 0.05)); + assert_eq!(off, tiny); +} + +#[test] +fn a_micro_height_bump_moves_the_wear_kinds_around_it() { + let mut fixture = fixture(); + for kind in [GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::FiberGlassEdgeWear] { + let off = mask(&mut fixture, with_micro(kind, None, None, |_| {})); + + let on = mask(&mut fixture, with_micro(kind, Some("bump"), None, |micro| micro.curvature_intensity = 1.0)); + let changed = on.iter().zip(&off).filter(|(on, off)| (*on - *off).abs() > 1e-3).count(); + assert!(changed > 0, "{kind:?}"); + } +} diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs index 65b2403e..ee5269f4 100644 --- a/crates/core/src/block_scales.rs +++ b/crates/core/src/block_scales.rs @@ -30,6 +30,24 @@ impl BlockScales { Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32]) } + /// Uniform bake atlas UV → working atlas UV, the inverse of [`BlockScales::bake_uv`] + pub fn working_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> { + if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + if self.scales.is_empty() { + return Some(uv); + } + + let block = self.block.max(1) as f32; + let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block]; + let origin = position.map(f32::floor); + let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32); + let local = [(position[0] - origin[0]) * scale, (position[1] - origin[1]) * scale]; + Some([(origin[0] + local[0]) * block / working_size.0 as f32, (origin[1] + local[1]) * block / working_size.1 as f32]) + } + /// The scale at atlas texel (x, y) pub fn at(&self, x: u32, y: u32) -> f32 { let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 0dbcc0d7..62629fc6 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,7 @@ use crate::{ ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum, }; +mod anchored_micro_detail; mod axis_blend; mod axis_layer; mod curvature_detail; @@ -22,7 +23,8 @@ mod filtering; mod generator_global; mod generator_grayscale; mod light_parameters; -mod micro_detail; +mod micro_curvature_type; +mod micro_details; mod output_resolution; mod resolution_mode; mod sampling; @@ -40,6 +42,7 @@ mod uv_transform; mod uv_wrap; mod wear_parameters; +use anchored_micro_detail::AnchoredMicroDetail; pub use axis_blend::AxisBlend; pub use axis_layer::AxisLayer; pub use curvature_detail::CurvatureDetail; @@ -50,7 +53,8 @@ pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; -pub use micro_detail::MicroDetail; +pub use micro_curvature_type::MicroCurvatureType; +pub use micro_details::MicroDetails; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; pub use sampling::Sampling; @@ -1028,6 +1032,7 @@ impl GeneratorKind { } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(remote = "Self")] pub struct Generator { pub kind: GeneratorKind, /// Where the mask starts (0..1, generator specific threshold). @@ -1056,9 +1061,6 @@ pub struct Generator { /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub inputs: BTreeMap, - /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub micro: Option, /// The wear kinds' controls (None: the level, softness and noise above, as saved before they existed) #[serde(default, skip_serializing_if = "Option::is_none")] pub wear: Option, @@ -1074,6 +1076,30 @@ pub struct Generator { /// The image a wear generator reads as its grunge once Use Custom Grunge is on (None: an empty slot) #[serde(default, skip_serializing_if = "Option::is_none")] pub grunge: Option, + /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub micro: Option>, +} + +impl Serialize for Generator { + fn serialize(&self, serializer: S) -> Result { + Generator::serialize(self, serializer) + } +} + +impl<'de> Deserialize<'de> for Generator { + fn deserialize>(deserializer: D) -> Result { + let mut saved = serde_json::Value::deserialize(deserializer)?; + + // Micro detail saved before Micro Details: an anchor point's height and its amount + let anchored = saved.get_mut("micro").filter(|micro| micro.get("anchor").is_some()).map(serde_json::Value::take); + let mut generator = Generator::deserialize(saved).map_err(serde::de::Error::custom)?; + if let Some(anchored) = anchored { + let AnchoredMicroDetail { anchor, amount } = serde_json::from_value(anchored).map_err(serde::de::Error::custom)?; + generator.micro = MicroDetails::of_anchor(generator.kind, anchor, amount).map(Box::new); + } + Ok(generator) + } } impl Generator { @@ -1111,9 +1137,15 @@ impl Generator { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture and its custom grunge + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge and its micro details pub fn sources(&self) -> impl Iterator { - self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()) + let micro = self.micro.iter().flat_map(|micro| micro.sources()); + self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) + } + + /// The micro details the generator computes with: switched on with an image to read (an anchor's micro detail saved on the earlier model reads too) + pub fn micro_in_use(&self) -> Option<&MicroDetails> { + self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -1148,12 +1180,12 @@ impl Generator { global: GeneratorGlobal::default(), resolution: OutputResolution::default(), inputs: BTreeMap::new(), - micro: None, wear: WearParameters::defaults(kind), section: SectionParameters::defaults(kind), light: LightParameters::defaults(kind), texture: None, grunge: None, + micro: None, } } @@ -2125,10 +2157,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.reads_anchor(anchor), EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), - EffectKind::Generator(generator) => { - generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) - || generator.sources().any(|source| source.reads_anchor(anchor)) - } + EffectKind::Generator(generator) => generator.sources().any(|source| source.reads_anchor(anchor)), _ => false, } } @@ -2141,19 +2170,13 @@ impl EffectKind { EffectKind::Generator(generator) => generator.sources().collect(), _ => Vec::new(), }; - let mut anchors: Vec<_> = sources + sources .into_iter() .filter_map(|source| match source { Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)), _ => None, }) - .collect(); - if let EffectKind::Generator(generator) = self - && let Some(micro) = generator.micro - { - anchors.push((micro.anchor, Channel::Height)); - } - anchors + .collect() } /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input, a colour selection's ID map) @@ -2641,10 +2664,10 @@ mod tests { let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind); assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8))))); - // A generator with micro detail reads its anchor too + // A generator whose Micro Height reads an anchor reads it too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); - generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + generator.micro = MicroDetails::of_anchor(GeneratorKind::Dirt, LayerId(9), 0.5).map(Box::new); assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8)))); @@ -2654,6 +2677,29 @@ mod tests { assert!(generator_layer.reads_anchor()); } + #[test] + fn micro_detail_saved_on_an_anchor_loads_as_micro_details_reading_its_height() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25}); + + let generator: Generator = serde_json::from_value(saved.clone()).unwrap(); + let micro = generator.micro.as_deref().unwrap(); + let defaults = MicroDetails::defaults(GeneratorKind::Curvature).unwrap(); + + assert!(micro.enabled && micro.height, "{micro:?}"); + assert_eq!(micro.height_source, Some(Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() })); + assert!(micro.height_intensity < defaults.height_intensity, "a weaker amount reads a gentler height"); + assert_eq!((micro.curvature_type, micro.ao_radius, micro.normal_source.clone()), (defaults.curvature_type, defaults.ao_radius, None)); + assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9)))); + + let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap(); + assert_eq!(reloaded, generator, "saved again as Micro Details"); + + saved["kind"] = serde_json::to_value(GeneratorKind::ThinAreas).unwrap(); + let without: Generator = serde_json::from_value(saved).unwrap(); + assert!(without.micro.is_none(), "a kind without micro details drops it"); + } + #[test] fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; diff --git a/crates/core/src/layer/anchored_micro_detail.rs b/crates/core/src/layer/anchored_micro_detail.rs new file mode 100644 index 00000000..0101ddfa --- /dev/null +++ b/crates/core/src/layer/anchored_micro_detail.rs @@ -0,0 +1,18 @@ +use serde::Deserialize; + +use super::LayerId; + +/// Micro detail as saved before Micro Details: the anchor point whose painted height it read, and how strongly +#[derive(Deserialize)] +pub(crate) struct AnchoredMicroDetail { + pub anchor: LayerId, + /// 0..1, 0.5 by default + #[serde(default = "AnchoredMicroDetail::default_amount")] + pub amount: f32, +} + +impl AnchoredMicroDetail { + fn default_amount() -> f32 { + 0.5 + } +} diff --git a/crates/core/src/layer/micro_curvature_type.rs b/crates/core/src/layer/micro_curvature_type.rs new file mode 100644 index 00000000..f0eba63c --- /dev/null +++ b/crates/core/src/layer/micro_curvature_type.rs @@ -0,0 +1,30 @@ +use serde::{Deserialize, Serialize}; + +/// How a generator's micro details turn the micro height into curvature +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum MicroCurvatureType { + /// The slope of the height, stronger than Sobel and lifting the whole surface slightly + Standard, + /// The slope of the height + #[default] + Sobel, + /// The height against blurred copies of itself, softer and wider + Smooth, +} + +impl MicroCurvatureType { + pub const ALL: [MicroCurvatureType; 3] = [MicroCurvatureType::Standard, MicroCurvatureType::Sobel, MicroCurvatureType::Smooth]; + + pub fn label(self) -> &'static str { + match self { + MicroCurvatureType::Standard => "Standard", + MicroCurvatureType::Sobel => "Sobel", + MicroCurvatureType::Smooth => "Smooth", + } + } + + /// The type named `name` (its label, any case) + pub fn parse(name: &str) -> Option { + MicroCurvatureType::ALL.into_iter().find(|kind| kind.label().eq_ignore_ascii_case(name)) + } +} diff --git a/crates/core/src/layer/micro_detail.rs b/crates/core/src/layer/micro_detail.rs deleted file mode 100644 index d7b13121..00000000 --- a/crates/core/src/layer/micro_detail.rs +++ /dev/null @@ -1,16 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::LayerId; - -/// Painted height read from an anchor point below a generator -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct MicroDetail { - /// The anchor point effect id - pub anchor: LayerId, - /// Strength of the height signal from 0 to 1 - pub amount: f32, -} - -impl MicroDetail { - pub const DEFAULT_AMOUNT: f32 = 0.5; -} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs new file mode 100644 index 00000000..3a090755 --- /dev/null +++ b/crates/core/src/layer/micro_details.rs @@ -0,0 +1,121 @@ +use serde::{Deserialize, Serialize}; + +use super::micro_curvature_type::MicroCurvatureType; +use super::{GeneratorKind, LayerId, Source}; +use crate::Channel; + +/// A generator's micro details: a height or normal image adding fine curvature or occlusion to its mesh maps +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MicroDetails { + /// Use Micro Details (Curvature and Ambient Occlusion; the wear kinds use them once Micro Height or Micro Normal is on) + pub enabled: bool, + /// Read the micro height image + pub height: bool, + /// Read the micro normal image + pub normal: bool, + pub curvature_type: MicroCurvatureType, + /// How strongly the micro details add to the curvature (0..5 on Curvature, 0..1 on the wear kinds) + pub curvature_intensity: f32, + /// How steep the micro height reads ([`MicroDetails::HEIGHT_INTENSITY_RANGE`]) + pub height_intensity: f32, + /// How far the micro height occludes (0..1) + pub ao_radius: f32, + /// How deep the micro height reads for occlusion (0..1) + pub ao_depth: f32, + /// The micro height image (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height_source: Option, + /// The micro normal image (None: an empty slot) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub normal_source: Option, +} + +impl MicroDetails { + pub const HEIGHT_INTENSITY_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + + /// Height Details Intensity per unit of an anchor's micro detail amount (0..1): the earlier default amount, 0.5, reads at the default intensity + pub const HEIGHT_INTENSITY_PER_AMOUNT: f32 = 2.0; + + /// The micro details reading anchor point `anchor`'s height as their Micro Height at `amount` (0..1) on a `kind` generator, None for kinds without them + pub fn of_anchor(kind: GeneratorKind, anchor: LayerId, amount: f32) -> Option { + let amount = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 }; + let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; + let micro = MicroDetails { + enabled: true, + height: true, + height_intensity: amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT, + height_source: Some(source), + ..MicroDetails::defaults(kind)? + }; + Some(micro.clamped(kind)) + } + + /// The reference app's defaults for `kind`, or None for kinds without micro details + pub fn defaults(kind: GeneratorKind) -> Option { + let shared = MicroDetails { + enabled: false, + height: true, + normal: true, + curvature_type: MicroCurvatureType::Sobel, + curvature_intensity: 1.0, + height_intensity: 1.0, + ao_radius: 0.3, + ao_depth: 0.05, + height_source: None, + normal_source: None, + }; + match kind { + GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion => Some(shared), + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => { + Some(MicroDetails { height: false, normal: false, curvature_intensity: 0.5, ..shared }) + } + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => None, + } + } + + /// Whether a generator of `kind` has the Use Micro Details switch (the wear kinds have only Micro Height and Micro Normal) + pub fn has_switch(kind: GeneratorKind) -> bool { + matches!(kind, GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion) + } + + /// Whether a generator of `kind` adds micro curvature + pub fn has_curvature(kind: GeneratorKind) -> bool { + MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::AmbientOcclusion + } + + /// Whether a generator of `kind` adds micro occlusion + pub fn has_occlusion(kind: GeneratorKind) -> bool { + MicroDetails::defaults(kind).is_some() && kind != GeneratorKind::Curvature + } + + /// The range of the curvature intensity on `kind` + pub fn curvature_intensity_range(kind: GeneratorKind) -> std::ops::RangeInclusive { + if kind == GeneratorKind::Curvature { 0.0..=5.0 } else { 0.0..=1.0 } + } + + /// Whether the micro details change a generator of `kind`: switched on with an image to read + pub fn in_use(&self, kind: GeneratorKind) -> bool { + (self.enabled || !MicroDetails::has_switch(kind)) && (self.height || self.normal) + } + + /// The images the micro details read: their height, then their normal + pub fn sources(&self) -> impl Iterator { + self.height_source.iter().chain(self.normal_source.as_ref()) + } + + /// Every value brought into its range, non-finite ones to the defaults of `kind` + pub fn clamped(self, kind: GeneratorKind) -> MicroDetails { + let Some(defaults) = MicroDetails::defaults(kind) else { return self }; + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + MicroDetails { + curvature_intensity: within(self.curvature_intensity, defaults.curvature_intensity, MicroDetails::curvature_intensity_range(kind)), + height_intensity: within(self.height_intensity, defaults.height_intensity, MicroDetails::HEIGHT_INTENSITY_RANGE), + ao_radius: within(self.ao_radius, defaults.ao_radius, 0.0..=1.0), + ao_depth: within(self.ao_depth, defaults.ao_depth, 0.0..=1.0), + ..self + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b8d53dd9..e68cdada 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -112,7 +112,7 @@ pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, + GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, diff --git a/crates/engine/src/anchored_micro_edit.rs b/crates/engine/src/anchored_micro_edit.rs new file mode 100644 index 00000000..75d2eb54 --- /dev/null +++ b/crates/engine/src/anchored_micro_edit.rs @@ -0,0 +1,71 @@ +//! `microAnchor` and `microAmount`: the earlier commands for a generator's micro detail, now its Micro Height read from an anchor point + +use serde_json::Value; +use texturecraft_core::{Channel, Generator, LayerId, MicroDetails, Source}; + +use crate::commands::bad; +use crate::mask_cmds::anchor_source; +use crate::{Result, Session}; + +/// What `microAnchor` and `microAmount` change on a generator's micro details +pub struct AnchoredMicroEdit { + /// The anchor point the Micro Height reads (`Some(None)`: `microAnchor: null` empties the slot) + anchor: Option>, + /// `microAmount`, 0..1, read as the Height Details Intensity + amount: Option, +} + +impl AnchoredMicroEdit { + /// The edit `params` ask of a generator on layer `reader` (None when they give neither key) + pub fn parse(session: &Session, command: &str, reader: LayerId, params: &Value) -> Result> { + let amount = match params.get("microAmount") { + Some(value) => { + let amount = value.as_f64().filter(|value| value.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?; + Some((amount as f32).clamp(0.0, 1.0)) + } + None => None, + }; + let anchor = match params.get("microAnchor") { + None => None, + Some(Value::Null) => Some(None), + Some(value) => { + let anchor = value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?; + + // The same rule as fills: an anchor below, in the same texture set + Some(Some(anchor_source(session, command, reader, LayerId(anchor), Channel::Height)?)) + } + }; + if anchor.is_none() && amount.is_none() { + return Ok(None); + } + + Ok(Some(AnchoredMicroEdit { anchor, amount })) + } + + /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there + pub fn apply(self, command: &str, generator: &mut Generator) -> Result<()> { + let kind = generator.kind; + let defaults = MicroDetails::defaults(kind); + match (self.anchor, &defaults) { + (Some(None), _) => { + if let Some(micro) = generator.micro.as_mut() { + micro.height_source = None; + } + } + (Some(Some(source)), Some(defaults)) => { + let micro = generator.micro.get_or_insert_with(|| Box::new(defaults.clone())); + (micro.enabled, micro.height, micro.height_source) = (true, true, Some(source)); + } + (Some(Some(_)), None) => return Err(bad(command, format!("{} has no micro details for `microAnchor`", kind.label()))), + (None, _) => {} + } + + if let Some(amount) = self.amount { + let reads_height = generator.micro.as_mut().filter(|micro| micro.height_source.is_some()); + let micro = reads_height.ok_or_else(|| bad(command, "give `microAnchor` before `microAmount`: the generator's Micro Height reads nothing"))?; + micro.height_intensity = amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; + **micro = micro.as_ref().clone().clamped(kind); + } + Ok(()) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index de36131e..c4ac692e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -159,13 +159,13 @@ fn generator_json(generator: &Generator) -> Value { if let Some(grunge) = &generator.grunge { out["grunge"] = source_json(grunge); } + if let Some(micro) = &generator.micro { + out["micro"] = json!(micro); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); } - if let Some(micro) = &generator.micro { - out["micro"] = json!({ "anchor": micro.anchor.0, "amount": micro.amount }); - } out } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..a9348fc1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod add_mask_cmds; +mod anchored_micro_edit; pub mod bake; pub mod bake_preview; pub mod brush_preset_cmds; @@ -50,6 +51,7 @@ pub mod materialx_cmds; pub mod meshmap_cmds; mod meshmap_file_name; pub mod meshmap_import_cmds; +pub mod micro_params; mod orb_camera; pub mod orb_preview; pub mod painting; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4369c512..3462216c 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,12 +3,14 @@ use serde_json::{Value, json}; use texturecraft_core::{ AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, + GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; +use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; +use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; use crate::session::StackTarget; use crate::{EngineError, Result, Session, cmd}; @@ -53,7 +55,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -98,7 +100,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture or grunge + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight or microNormal + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -691,6 +693,8 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; section_from(command, params, generator)?; + let earlier_keys: &[&str] = if WearParameters::defaults(generator.kind).is_some() { &EARLIER_WEAR_KEYS } else { &EARLIER_SECTION_KEYS }; + micro_from(command, params, generator, earlier_keys)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } @@ -780,53 +784,26 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result { push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal) } -/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer -/// `reader` (None: leave it as it is; `Some(None)`: remove it). -fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value, current: Option) -> Result>> { - let amount = match params.get("microAmount") { - Some(value) => { - Some(value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?.clamp(0.0, 1.0) as f32) - } - None => None, - }; - let anchor = match params.get("microAnchor") { - None => current.map(|m| m.anchor), - Some(Value::Null) => return Ok(Some(None)), - Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?)), - }; - let Some(anchor) = anchor else { - return match amount { - Some(_) => Err(bad(command, "give `microAnchor` before `microAmount`: the generator has no micro detail")), - None => Ok(None), - }; - }; - - if params.get("microAnchor").is_none() && amount.is_none() { - return Ok(None); - } - - // The same rule as fills: an anchor below, in the same texture set - anchor_source(session, command, reader, anchor, Channel::Height)?; - let amount = amount.or(current.map(|m| m.amount)).unwrap_or(MicroDetail::DEFAULT_AMOUNT); - Ok(Some(Some(MicroDetail { anchor, amount }))) -} - /// A generator input a command names: a mesh map it reads, its texture or its custom grunge #[derive(Clone, Copy)] enum GeneratorInput { Map(BakedMap), Texture, Grunge, + MicroHeight, + MicroNormal, } /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture` or `grunge`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight` or `microNormal`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, GRUNGE_INPUT => GeneratorInput::Grunge, + MICRO_HEIGHT_INPUT => GeneratorInput::MicroHeight, + MICRO_NORMAL_INPUT => GeneratorInput::MicroNormal, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -842,6 +819,9 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) } (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(_), false) if matches!(input, GeneratorInput::MicroNormal) => { + return Err(bad(CMD, "the micro normal reads an image or a value, not an anchor point")); + } (None, None, Some(anchor), false) => { let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) @@ -861,8 +841,8 @@ fn add_generator(session: &mut Session, params: &Value) -> Result { generator_from("effect.add.generator", params, &mut generator)?; let selected_layer = layer_param(session, "effect.add.generator", params)?; let reader = session.doc.project.mask_owner(selected_layer); - if let Some(micro) = micro_param(session, "effect.add.generator", reader, params, None)? { - generator.micro = micro; + if let Some(edit) = AnchoredMicroEdit::parse(session, "effect.add.generator", reader, params)? { + edit.apply("effect.add.generator", &mut generator)?; } let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); push_effect(session, params, EffectKind::Generator(generator), blend) @@ -1071,7 +1051,7 @@ fn set(session: &mut Session, params: &Value) -> Result { }; let micro = match session.doc.project.effect(effect) { - Some((owner, Effect { kind: EffectKind::Generator(generator), .. })) => micro_param(session, CMD, owner, params, generator.micro)?, + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => AnchoredMicroEdit::parse(session, CMD, owner, params)?, _ if params.get("microAnchor").is_some() || params.get("microAmount").is_some() => { return Err(bad(CMD, "`microAnchor` and `microAmount` edit generator effects only")); } @@ -1144,9 +1124,6 @@ fn set(session: &mut Session, params: &Value) -> Result { generator.inputs.retain(|map, _| kind.inputs().contains(map)); } generator_from(CMD, params, generator)?; - if let Some(micro) = micro { - generator.micro = micro; - } match input { Some((GeneratorInput::Map(map), source)) => { if !generator.inputs_in_use().contains(&map) { @@ -1161,8 +1138,22 @@ fn set(session: &mut Session, params: &Value) -> Result { Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source, // generator_from refused the grunge on kinds without wear controls and moved the generator onto them Some((GeneratorInput::Grunge, source)) => generator.grunge = source, + // generator_from refused micro details on kinds without them and created them + Some((GeneratorInput::MicroHeight, source)) => { + if let Some(micro) = generator.micro.as_mut() { + micro.height_source = source; + } + } + Some((GeneratorInput::MicroNormal, source)) => { + if let Some(micro) = generator.micro.as_mut() { + micro.normal_source = source; + } + } None => {} } + if let Some(edit) = micro { + edit.apply(CMD, generator)?; + } } _ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")), EffectKind::Levels(levels) => levels_from(CMD, params, levels)?, @@ -1294,6 +1285,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { resolution: current.resolution, inputs, grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), + micro: swapped_micro(current.micro.as_deref(), kind), ..Generator::new(kind) } } diff --git a/crates/engine/src/micro_params.rs b/crates/engine/src/micro_params.rs new file mode 100644 index 00000000..7e0ed083 --- /dev/null +++ b/crates/engine/src/micro_params.rs @@ -0,0 +1,91 @@ +//! The micro details controls `effect.add.generator` and `effect.set` take + +use serde_json::Value; +use texturecraft_core::{Generator, GeneratorKind, MicroCurvatureType, MicroDetails, SectionParameters, WearParameters}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, strp}; + +/// The micro details controls +pub const MICRO_KEYS: [&str; 8] = + ["useMicroDetails", "microHeight", "microNormal", "microCurvatureType", "microCurvatureIntensity", "microHeightIntensity", "microAoRadius", "microAoDepth"]; + +/// The input names of the micro height and micro normal images, beside the mesh map ids +pub const MICRO_HEIGHT_INPUT: &str = "microHeight"; +pub const MICRO_NORMAL_INPUT: &str = "microNormal"; + +/// Whether micro details control `key` changes a generator of `kind` +pub fn micro_key_applies(kind: GeneratorKind, key: &str) -> bool { + match key { + "useMicroDetails" => MicroDetails::has_switch(kind), + "microCurvatureType" | "microCurvatureIntensity" | "microHeightIntensity" => MicroDetails::has_curvature(kind), + "microAoRadius" | "microAoDepth" => MicroDetails::has_occlusion(kind), + _ => MicroDetails::defaults(kind).is_some(), + } +} + +/// The micro details controls in `params` (a micro height or normal input counts as one): they move a generator off its earlier model onto the reference's controls; `earlier_keys` are the keys that keep it there +pub fn micro_from(command: &str, params: &Value, generator: &mut Generator, earlier_keys: &[&str]) -> Result<()> { + let input_given = matches!(strp(params, "input"), Some(MICRO_HEIGHT_INPUT | MICRO_NORMAL_INPUT)); + let mut given = MICRO_KEYS.iter().filter(|key| params.get(**key).is_some()).peekable(); + if given.peek().is_none() && !input_given { + return Ok(()); + } + + let kind = generator.kind; + let Some(defaults) = MicroDetails::defaults(kind) else { + return Err(bad(command, format!("{} has no micro details: only Curvature, Ambient Occlusion and the wear kinds have them", kind.label()))); + }; + if let Some(unused) = given.find(|key| !micro_key_applies(kind, key)) { + return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); + } + if WearParameters::defaults(kind).is_some() && ["blur", "balance", "contrast"].iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, format!("{} has no global blur, balance or contrast beside its micro details", kind.label()))); + } + if earlier_keys.iter().any(|key| params.get(*key).is_some()) { + return Err(bad(command, "level, softness, noise and offset drive the earlier model: give them or the micro details, not both")); + } + + // Micro details exist on the reference's controls only + if generator.on_earlier_model() { + generator.offset = 0.0; + if let Some(wear) = WearParameters::defaults(kind) { + generator.wear = Some(wear); + } else { + let fresh = Generator::new(kind); + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale) = + (fresh.level, fresh.softness, fresh.noise_amount, fresh.noise_scale); + generator.section = SectionParameters::defaults(kind); + } + } + + let micro = generator.micro.get_or_insert_with(|| Box::new(defaults)); + for (key, value) in [("useMicroDetails", &mut micro.enabled), ("microHeight", &mut micro.height), ("microNormal", &mut micro.normal)] { + if let Some(given) = boolp(params, key) { + *value = given; + } + } + for (key, value) in [ + ("microCurvatureIntensity", &mut micro.curvature_intensity), + ("microHeightIntensity", &mut micro.height_intensity), + ("microAoRadius", &mut micro.ao_radius), + ("microAoDepth", &mut micro.ao_depth), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(value) = params.get("microCurvatureType") { + let name = value.as_str().ok_or_else(|| bad(command, "`microCurvatureType` must be a string"))?; + micro.curvature_type = MicroCurvatureType::parse(name).ok_or_else(|| bad(command, format!("unknown curvature type `{name}`")))?; + } + **micro = micro.as_ref().clone().clamped(kind); + Ok(()) +} + +/// `current`'s micro details carried onto a `kind` generator: its images stay, its controls start from `kind`'s defaults +pub fn swapped_micro(current: Option<&MicroDetails>, kind: GeneratorKind) -> Option> { + let current = current.filter(|micro| micro.sources().next().is_some())?; + let defaults = MicroDetails::defaults(kind)?; + Some(Box::new(MicroDetails { height_source: current.height_source.clone(), normal_source: current.normal_source.clone(), ..defaults })) +} diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index caba4447..f15a9ed8 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -150,35 +150,58 @@ fn anchor_points_in_masks_record_the_mask_for_layers_above() { assert!(close(center(&mut s, Channel::BaseColor), [expected; 3]), "{:?}", center(&mut s, Channel::BaseColor)); } +/// The composited base color over the whole texture set, row by row +fn base_colors(s: &mut Session) -> Vec<[f32; 3]> { + s.update(); + let composite = &s.caches[0].composite; + (0..composite.height).flat_map(|y| (0..composite.resolution).map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect() +} + +fn largest_change(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) +} + #[test] -fn generators_read_an_anchor_height_as_micro_detail() { - let mut s = session(); - let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); - let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); +fn generators_read_an_anchor_height_as_their_micro_height() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + + // A checker of raised height below, recorded by an anchor point + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); // The anchor must be below; `microAmount` needs an anchor; ids must be numbers assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAmount": 0.5})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": "x"})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": low})).is_err(), "not an anchor point"); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); - let generator = id(execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "noise": 0.0})).unwrap(), "effect"); - let plain = center(&mut s, Channel::BaseColor); + let generator = id(execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); + let plain = base_colors(&mut s); execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); - let raised = center(&mut s, Channel::BaseColor); - assert!(raised[0] > plain[0] + 0.1, "{plain:?} -> {raised:?}"); + let raised = base_colors(&mut s); + assert!(largest_change(&raised, &plain) > 0.05, "the checker's raised edges read as curvature"); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); - assert!(inspect.to_string().contains(&format!("\"micro\":{{\"amount\":1.0,\"anchor\":{anchor}}}")), "{inspect}"); + let inspected = inspect.to_string(); + assert!(inspected.contains("\"heightSource\"") && inspected.contains(&format!("\"anchor\":{anchor}")), "{inspect}"); - // The amount alone keeps the anchor; null removes the micro detail + // The amount alone keeps the anchor; null empties the Micro Height execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); - assert!(close(center(&mut s, Channel::BaseColor), plain)); + assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "no amount, no micro height"); execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); - assert!(s.doc.project.effect(LayerId(generator)).map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.is_none())).unwrap()); + let emptied = s + .doc + .project + .effect(LayerId(generator)) + .map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); + assert_eq!(emptied, Some(true)); + assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "without an anchor, as without micro details"); assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); - // A copied generator with micro detail needs the anchor below its new layer + // A copied generator reading an anchor needs the anchor below its new layer execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); diff --git a/crates/engine/tests/it/generator_micro_details.rs b/crates/engine/tests/it/generator_micro_details.rs new file mode 100644 index 00000000..33e13b87 --- /dev/null +++ b/crates/engine/tests/it/generator_micro_details.rs @@ -0,0 +1,133 @@ +//! A generator's micro details through `effect.add.generator` and `effect.set`: their controls per kind, their images as the `microHeight` and `microNormal` inputs, and the kinds without them + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Generator, LayerId, MicroCurvatureType, Source}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +/// A gray image resource, by the name it was imported under +fn gray_image(session: &mut Session) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("height.png", bytes).unwrap() +} + +#[test] +fn curvature_takes_its_micro_details_controls() { + let mut session = session(); + let params = json!({"generator": "curvature", "useMicroDetails": true, "microNormal": false, "microCurvatureType": "smooth", "microCurvatureIntensity": 4.0, "microHeightIntensity": 20.0}); + let effect = add(&mut session, params); + + let micro = generator(&session, effect).micro.unwrap(); + assert!(micro.enabled && micro.height && !micro.normal); + assert_eq!(micro.curvature_type, MicroCurvatureType::Smooth); + assert_eq!((micro.curvature_intensity, micro.height_intensity), (4.0, 10.0), "the height intensity stops at 10"); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"micro\""), "inspect shows the micro details"); +} + +#[test] +fn each_kind_refuses_the_micro_controls_it_lacks() { + let mut session = session(); + let refused = [ + ("curvature", "microAoRadius"), + ("ambientOcclusion", "microCurvatureType"), + ("ambientOcclusion", "microHeightIntensity"), + ("edgeWear", "useMicroDetails"), + ("dirt", "useMicroDetails"), + ("position", "microHeight"), + ("worldSpaceNormals", "microNormal"), + ("direction", "microAoDepth"), + ]; + for (kind, key) in refused { + let effect = add(&mut session, json!({"generator": kind})); + let value = if key == "microCurvatureType" { json!("sobel") } else { json!(true) }; + let value = if key.starts_with("microAo") || key.ends_with("Intensity") { json!(0.5) } else { value }; + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: value})).is_err(), "{kind} {key}"); + assert_eq!(generator(&session, effect).micro, None, "{kind} {key}"); + } +} + +#[test] +fn the_wear_kinds_cap_their_curvature_intensity_at_one() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "fiberGlassEdgeWear", "microHeight": true, "microCurvatureIntensity": 3.0})); + + assert_eq!(generator(&session, effect).micro.unwrap().curvature_intensity, 1.0); +} + +#[test] +fn the_micro_images_are_inputs_and_stay_used_resources() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "ambientOcclusion", "useMicroDetails": true})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputImage": name})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microNormal", "inputValue": 0.5})).unwrap(); + let micro = generator(&session, effect).micro.unwrap(); + assert_eq!(micro.height_source, Some(Source::image(name.clone()))); + assert_eq!(micro.normal_source, Some(Source::Uniform([0.5; 3]))); + assert!(generator(&session, effect).inputs.is_empty(), "micro images are not mesh map inputs"); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the micro height"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputBaked": true})).unwrap(); + assert_eq!(generator(&session, effect).micro.unwrap().height_source, None, "inputBaked empties the slot"); + let anchor = json!({"effect": effect, "input": "microNormal", "inputAnchor": effect}); + assert!(execute(&mut session, "effect.set", &anchor).is_err(), "the micro normal reads no anchor point"); +} + +#[test] +fn micro_details_move_an_earlier_generator_onto_the_reference_controls() { + let mut session = session(); + let name = gray_image(&mut session); + let wear = add(&mut session, json!({"generator": "edgeWear", "level": 0.8, "offset": 0.2})); + let curvature = add(&mut session, json!({"generator": "curvature", "level": 0.8})); + assert!(generator(&session, wear).on_earlier_model() && generator(&session, curvature).on_earlier_model()); + + execute(&mut session, "effect.set", &json!({"effect": wear, "input": "microHeight", "inputImage": name})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": curvature, "useMicroDetails": true})).unwrap(); + let moved = generator(&session, wear); + assert!(moved.wear.is_some() && moved.offset == 0.0, "Metal Edge Wear on its wear controls, without the earlier offset"); + assert!(generator(&session, curvature).section.is_some(), "Curvature on its section controls"); + + let both = json!({"effect": wear, "microHeight": true, "softness": 0.2}); + assert!(execute(&mut session, "effect.set", &both).is_err(), "micro details and the earlier model at once"); + let global = json!({"effect": wear, "microHeight": true, "blur": 0.2}); + assert!(execute(&mut session, "effect.set", &global).is_err(), "the wear kinds have no global blur"); +} + +#[test] +fn swapping_kinds_keeps_the_micro_images_where_the_kind_has_micro_details() { + let mut session = session(); + let name = gray_image(&mut session); + let effect = add(&mut session, json!({"generator": "curvature", "useMicroDetails": true, "microCurvatureIntensity": 4.0})); + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "microHeight", "inputImage": name})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "edgeWear"})).unwrap(); + let micro = generator(&session, effect).micro.unwrap(); + assert_eq!(micro.height_source, Some(Source::image(name))); + assert_eq!(micro.curvature_intensity, 0.5, "the controls start from Metal Edge Wear's defaults"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "position"})).unwrap(); + assert_eq!(generator(&session, effect).micro, None, "Position has no micro details"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index de497d5a..08d80a48 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -37,6 +37,7 @@ mod folder_contents; mod frame_selection; mod generator_custom_grunge; mod generator_inputs; +mod generator_micro_details; mod generator_sections; mod generator_swap; mod generator_texture; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index f965ca40..26170c32 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2834,24 +2834,6 @@ fn mask_anchor_enabled(app: &TextureCraftApp, anchor: LayerId) -> Option { mask.effects.iter().any(|effect| effect.id == anchor).then_some(mask.enabled) } -/// The anchor points of `anchors` as menu entries under their own heading (a note when there -/// are none); returns the one clicked. -pub(crate) fn anchor_entries(ui: &mut Ui, anchors: &[(LayerId, String)], current: Option) -> Option { - ui.separator(); - ui.label(caption(tr("Anchor points"))); - if anchors.is_empty() { - ui.label(RichText::new(tr("No anchor point below this layer")).color(Tokens::get(ui.ctx()).text_dim)); - } - - let mut picked = None; - for (anchor, label) in anchors { - if ui.selectable_label(current == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { - picked = Some(*anchor); - } - } - picked -} - pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); let label = trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 62b3d0bb..bfcf203a 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -4,15 +4,15 @@ use egui::{RichText, Ui}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LightParameters, MicroDetail, OutputResolution, ResolutionMode, - SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, + AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, LightParameters, OutputResolution, + ResolutionMode, SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, }; use crate::TextureCraftApp; -use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; use crate::i18n::{baked_map_label, tr, trf}; use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. @@ -58,9 +58,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer light_parameters(app, ui, id, None, defaults); } } - if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { - micro_detail_properties(app, ui, id, generator.micro, layer); - } ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.button(tr("Restore defaults")).clicked() { @@ -85,34 +82,6 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer } } -/// The painted height anchor and its influence on this generator -fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micro: Option, layer: LayerId) { - let tokens = Tokens::get(ui.ctx()); - ui.label(caption(tr("Micro detail"))) - .on_hover_text(tr("Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.")); - let anchors = effect_anchors_below(app, layer, LayerId(id)); - let current = match micro { - Some(detail) => anchors.iter().find(|(anchor, _)| *anchor == detail.anchor).map_or_else(|| tr("missing").to_string(), |(_, label)| label.clone()), - None => tr("None").to_string(), - }; - combo(ui, tr("Anchor point"), current, |ui| { - if ui.selectable_label(micro.is_none(), tr("None")).clicked() { - app.run("effect.set", json!({"effect": id, "microAnchor": null})); - } - if let Some(anchor) = anchor_entries(ui, &anchors, micro.map(|detail| detail.anchor)) { - app.run("effect.set", json!({"effect": id, "microAnchor": anchor.0})); - } - }); - if let Some(detail) = micro { - let mut amount = detail.amount; - if let Some(merge) = slider_edit(ui, tr("Amount"), &mut amount, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "microAmount": amount, "merge": merge})); - } - } else if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its height as micro detail.")).color(tokens.text_dim)); - } -} - /// What a generator kind makes, its category and its tags (read only). fn attributes(ui: &mut Ui, kind: GeneratorKind) { let tokens = Tokens::get(ui.ctx()); @@ -330,7 +299,6 @@ fn defaults_of(id: u64, generator: &Generator) -> Value { "resolution": format!("{:?}", defaults.resolution.mode), "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, - "microAnchor": null, }); // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 01bf845a..811582c8 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, MicroDetail, SectionParameters, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -73,9 +73,6 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { let (mut harness, effect) = harness(false); let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); - if let EffectKind::Generator(generator) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind { - generator.micro = Some(MicroDetail { anchor: LayerId(999), amount: 0.8 }); - } harness.run_steps(3); harness.get_by_label("Restore defaults").scroll_to_me(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..bea73433 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -724,36 +724,6 @@ fn nested_layers_snapshot() { } /// The mask anchor and generator micro controls in the integrated properties panel -#[test] -#[ignore] -fn mask_anchor_micro_detail_snapshot() { - use serde_json::{Value, json}; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); - execute(&mut session, "mask.add.black", &json!({"layer": lower})).unwrap(); - execute(&mut session, "effect.add.fill", &json!({"layer": lower, "value": 0.4})).unwrap(); - let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask", "name": "Wear"})).unwrap()["effect"].as_u64().unwrap(); - let upper = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); - let generator = execute(&mut session, "effect.add.generator", &json!({"layer": upper, "generator": "dirt", "microAnchor": anchor})).unwrap()["effect"] - .as_u64() - .unwrap(); - execute(&mut session, "layer.select", &json!({"layer": upper, "target": generator})).unwrap(); - - let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 1200.0)) - .with_pixels_per_point(1.0) - .wgpu() - .build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_label("Micro detail").scroll_to_me(); - save(&mut harness, &output_dir, "mask-anchor-micro-detail"); -} - #[test] #[ignore] fn path_tool_snapshots() { From 815bdb2e4703bcb2cfb2a3070142c5ef6dfb1d2d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:19:49 +0000 Subject: [PATCH 14/54] Generators: 3D Distance, white around a point fading over a radius A new kind with the reference's controls: Position X, Y and Z across the mesh's bounds (scaled evenly, the longest side spanning 0 to 1, as the reference's position map is), Radius, Offset, Contrast and Invert. The value falls from 1 at the point to 0 at the radius and is then slid through by a histogram scan (offset 0 all black, 1 all white; contrast 1 a hard edge); it matches the reference within 0.001 on every captured setting. It reads its Position input like Position does, has no earlier model or global controls (both refused), and swapping onto it drops the earlier offset. Commands only: the picker leaves it out until its panel is designed. --- crates/compose/src/eval.rs | 25 ++++- crates/compose/src/histogram_scan.rs | 35 +++++++ crates/compose/src/lib.rs | 2 + crates/compose/src/three_d_distance.rs | 13 +++ .../tests/generator_three_d_distance.rs | 96 +++++++++++++++++++ crates/core/src/layer.rs | 33 +++++-- crates/core/src/layer/distance_parameters.rs | 40 ++++++++ crates/core/src/layer/micro_details.rs | 6 +- crates/core/src/layer/section_parameters.rs | 7 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 48 ++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 7 +- .../tests/it/generator_three_d_distance.rs | 61 ++++++++++++ crates/engine/tests/it/main.rs | 1 + crates/ui-egui/src/generator_panel.rs | 1 + 17 files changed, 367 insertions(+), 14 deletions(-) create mode 100644 crates/compose/src/histogram_scan.rs create mode 100644 crates/compose/src/three_d_distance.rs create mode 100644 crates/compose/tests/generator_three_d_distance.rs create mode 100644 crates/core/src/layer/distance_parameters.rs create mode 100644 crates/engine/src/distance_params.rs create mode 100644 crates/engine/tests/it/generator_three_d_distance.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2bf1cf69..29db5ca0 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -43,6 +43,7 @@ use crate::shape_distance::distance_filter; use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::texture_layer; +use crate::three_d_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -3406,6 +3407,10 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } + if let Some(distance) = generator.distance_controls() { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(&distance, position); + } let coords = self.coords(); @@ -3424,8 +3429,9 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - // World Space Normals always computes with its section controls: this arm only keeps the match whole + // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, + (GeneratorKind::ThreeDDistance, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3466,7 +3472,12 @@ impl<'a, 'b> Texel<'a, 'b> { sections::axes_signal(normal, §ion.axes) } // Only the kinds with section controls reach here: this arm only keeps the match whole - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => 0.0, + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance => 0.0, } } @@ -3478,6 +3489,16 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 + fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { + if let Some(source) = generator.inputs.get(&BakedMap::Position) { + return Vec3::from(self.source(source, &Projection::default(), Sampling::default(), ChannelKind::NormalMap)); + } + let (low, high) = self.inp.bounds; + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + self.world().map_or(Vec3::splat(0.5), |position| (position - (low + high) * 0.5) / longest + Vec3::splat(0.5)) + } + /// This texel's world position across the mesh's bounds, 0..1 on each axis (0 where uncovered) fn bounds_position(&self) -> Vec3 { let (low, high) = self.inp.bounds; diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs new file mode 100644 index 00000000..ca9c851c --- /dev/null +++ b/crates/compose/src/histogram_scan.rs @@ -0,0 +1,35 @@ +//! The histogram scan several generators finish with: a ramp slid through the values and narrowed by a contrast + +/// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step +pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { + let width = 1.0 - contrast.clamp(0.0, 1.0); + // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white + let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; + if width <= f32::EPSILON { + return if value >= low { 1.0 } else { 0.0 }; + } + ((value - low) / width).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_ends_of_the_position_are_all_black_and_all_white() { + for value in [0.0, 0.3, 1.0] { + assert_eq!(histogram_scan(value, 0.0, 0.5), 0.0, "{value}"); + assert_eq!(histogram_scan(value, 1.0, 0.5), 1.0, "{value}"); + } + } + + #[test] + fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() { + assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6); + assert!((histogram_scan(0.5, 0.5, 0.0) - 0.5).abs() < 1e-6); + assert!((histogram_scan(0.7, 0.5, 0.5) - 0.9).abs() < 1e-6, "a ramp half wide from 0.25"); + assert!(histogram_scan(0.6, 0.5, 0.9) > histogram_scan(0.6, 0.5, 0.5)); + assert_eq!(histogram_scan(0.51, 0.5, 1.0), 1.0); + assert_eq!(histogram_scan(0.49, 0.5, 1.0), 0.0); + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index b3f52141..cf4ed85e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -27,6 +27,7 @@ pub mod frame_placement; mod fur_lock; mod generator_maps; mod held_fields; +mod histogram_scan; mod image_identity; mod mask_gray; mod micro_details; @@ -45,6 +46,7 @@ mod soft_box; pub mod solo; pub mod store; mod texture_layer; +mod three_d_distance; pub mod thumb; pub mod tile_length; mod tile_pattern; diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs new file mode 100644 index 00000000..f6f909c8 --- /dev/null +++ b/crates/compose/src/three_d_distance.rs @@ -0,0 +1,13 @@ +//! The 3D Distance generator: a gradient falling off with the distance from a point across the mesh's bounds + +use texturecraft_core::DistanceParameters; +use texturecraft_geom::glam::Vec3; + +use crate::histogram_scan::histogram_scan; + +/// The value at `position` (0..1 across the bounds, the longest side spanning 0..1): 1 at the point, 0 at the radius, then scanned by the offset and contrast +pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f32 { + let from_point = position.distance(Vec3::from(distance.point)); + let gradient = if distance.radius > 0.0 { (1.0 - from_point / distance.radius).clamp(0.0, 1.0) } else { 0.0 }; + histogram_scan(gradient, distance.offset, distance.contrast) +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs new file mode 100644 index 00000000..6b233479 --- /dev/null +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -0,0 +1,96 @@ +//! The 3D Distance generator on a sphere: white at its point, falling off over its radius, slid by its offset + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, + Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 32, 16); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; (RES * RES) as usize]))].into() }; + Fixture { project, mesh, gbuf, layer, baked } +} + +/// Every covered texel and its height on the sphere +fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { + (0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect() +} + +/// The mask of a 3D Distance generator with `distance` alone over black at `texels` +fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +#[test] +fn a_point_at_the_top_lights_the_top() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, DistanceParameters { point: [0.5, 1.0, 0.5], radius: 0.8, contrast: 0.0, ..DistanceParameters::default() }, &at); + let mean_where = |above: bool| { + let picked: Vec = texels.iter().zip(&values).filter(|((_, height), _)| (*height > 0.5) == above).map(|(_, value)| *value).collect(); + picked.iter().sum::() / picked.len() as f32 + }; + assert!(mean_where(true) > mean_where(false) + 0.3, "top {} bottom {}", mean_where(true), mean_where(false)); +} + +#[test] +fn the_offset_slides_the_mask_from_black_to_white() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let black = mask(&mut fixture, DistanceParameters { offset: 0.0, ..DistanceParameters::default() }, &at); + let white = mask(&mut fixture, DistanceParameters { offset: 1.0, ..DistanceParameters::default() }, &at); + assert!(black.iter().all(|value| *value == 0.0)); + assert!(white.iter().all(|value| *value == 1.0)); +} + +#[test] +fn a_larger_radius_reaches_further() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + let total = |values: Vec| values.iter().sum::(); + + let small = total(mask(&mut fixture, DistanceParameters { radius: 0.3, ..DistanceParameters::default() }, &at)); + let large = total(mask(&mut fixture, DistanceParameters { radius: 1.2, ..DistanceParameters::default() }, &at)); + assert!(large > small); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 62629fc6..67e57460 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -19,6 +19,7 @@ mod curvature_detail; mod curvature_mode; mod decal_flip; mod decal_symmetry; +mod distance_parameters; mod filtering; mod generator_global; mod generator_grayscale; @@ -49,6 +50,7 @@ pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; +pub use distance_parameters::DistanceParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; @@ -950,10 +952,12 @@ pub enum GeneratorKind { FiberGlassEdgeWear, /// The world space normal's axes combined into one gray WorldSpaceNormals, + /// White around a point across the mesh's bounds, fading with the distance from it + ThreeDDistance, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 9] = [ + pub const ALL: [GeneratorKind; 10] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -963,6 +967,7 @@ impl GeneratorKind { GeneratorKind::Direction, GeneratorKind::FiberGlassEdgeWear, GeneratorKind::WorldSpaceNormals, + GeneratorKind::ThreeDDistance, ]; pub fn label(self) -> &'static str { match self { @@ -975,6 +980,7 @@ impl GeneratorKind { GeneratorKind::Direction => "Light", GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", GeneratorKind::WorldSpaceNormals => "World Space Normals", + GeneratorKind::ThreeDDistance => "3D Distance", } } @@ -990,12 +996,13 @@ impl GeneratorKind { GeneratorKind::Direction => "Direction", GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", + GeneratorKind::ThreeDDistance => "ThreeDDistance", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; 3D Distance waits for its panel) pub fn in_picker(self) -> bool { - self != GeneratorKind::ThinAreas + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance) } /// Whether the kind's result depends on its seed @@ -1010,12 +1017,17 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position => &[BakedMap::Position], + GeneratorKind::Position | GeneratorKind::ThreeDDistance => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } } + /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise + pub fn has_no_earlier_model(self) -> bool { + matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance) + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); // The labels before the reference app's names, which agents may still send @@ -1079,6 +1091,9 @@ pub struct Generator { /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option>, + /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub distance: Option>, } impl Serialize for Generator { @@ -1112,7 +1127,7 @@ impl Generator { /// The global blur, balance and contrast the generator applies: none on the wear and light controls, which have no such controls pub fn applied_global(&self) -> GeneratorGlobal { - if self.wear.is_some() || self.light.is_some() || self.kind == GeneratorKind::FiberGlassEdgeWear { GeneratorGlobal::default() } else { self.global } + if self.wear.is_some() || self.light.is_some() || self.kind.has_no_earlier_model() { GeneratorGlobal::default() } else { self.global } } /// The section controls the generator computes with: its own, World Space Normals' defaults when it has none (it has no earlier model), else None @@ -1120,6 +1135,11 @@ impl Generator { self.section.or_else(|| SectionParameters::defaults(self.kind).filter(|_| self.kind == GeneratorKind::WorldSpaceNormals)) } + /// The 3D Distance controls the generator computes with: its own, else the defaults on a 3D Distance generator + pub fn distance_controls(&self) -> Option { + self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1150,7 +1170,7 @@ impl Generator { /// Whether the generator is on the level, softness and noise it had before the reference app's controls pub fn on_earlier_model(&self) -> bool { - self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && self.kind != GeneratorKind::FiberGlassEdgeWear + self.wear.is_none() && self.light.is_none() && self.section_controls().is_none() && !self.kind.has_no_earlier_model() } pub fn new(kind: GeneratorKind) -> Generator { @@ -1186,6 +1206,7 @@ impl Generator { texture: None, grunge: None, micro: None, + distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), } } diff --git a/crates/core/src/layer/distance_parameters.rs b/crates/core/src/layer/distance_parameters.rs new file mode 100644 index 00000000..a392b4a0 --- /dev/null +++ b/crates/core/src/layer/distance_parameters.rs @@ -0,0 +1,40 @@ +use serde::{Deserialize, Serialize}; + +/// The 3D Distance generator's controls: white around a point across the mesh's bounds, fading to black at the radius +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DistanceParameters { + /// The point, 0..1 across the mesh's bounds on each axis (Position X, Y and Z) + pub point: [f32; 3], + /// How far the gradient reaches, in units of the bounds' longest side ([`DistanceParameters::RADIUS_RANGE`]) + pub radius: f32, + /// Slides the gradient through: 0 all black, 1 all white + pub offset: f32, + /// Narrows the gradient (0..1; 1 a hard edge) + pub contrast: f32, +} + +impl DistanceParameters { + pub const RADIUS_RANGE: std::ops::RangeInclusive = 0.0..=1.5; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> DistanceParameters { + let defaults = DistanceParameters::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + DistanceParameters { + point: std::array::from_fn(|axis| within(self.point[axis], defaults.point[axis], 0.0..=1.0)), + radius: within(self.radius, defaults.radius, DistanceParameters::RADIUS_RANGE), + offset: within(self.offset, defaults.offset, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + } + } +} + +impl Default for DistanceParameters { + /// The reference app's defaults: the bounds' centre, radius 1 + fn default() -> DistanceParameters { + DistanceParameters { point: [0.5; 3], radius: 1.0, offset: 0.5, contrast: 0.5 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 3a090755..a0cbc4ff 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -70,7 +70,11 @@ impl MicroDetails { GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear => { Some(MicroDetails { height: false, normal: false, curvature_intensity: 0.5, ..shared }) } - GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals => None, + GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 583c4a99..322fd54c 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -35,7 +35,12 @@ impl SectionParameters { let defaults = SectionParameters { invert: false, blur: 0.0, balance: 0.5, contrast: 0.0, brightness: 0.0, axes: [axis(0.0), axis(1.0), axis(0.0)] }; match kind { GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::WorldSpaceNormals => Some(defaults), - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear => None, + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 17975266..b354a95f 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -58,7 +58,8 @@ impl WearParameters { | GeneratorKind::AmbientOcclusion | GeneratorKind::Position | GeneratorKind::Direction - | GeneratorKind::WorldSpaceNormals => None, + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index e68cdada..bd02feff 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs new file mode 100644 index 00000000..6e16cbda --- /dev/null +++ b/crates/engine/src/distance_params.rs @@ -0,0 +1,48 @@ +//! The 3D Distance controls `effect.add.generator` and `effect.set` take + +use serde_json::Value; +use texturecraft_core::{Generator, GeneratorKind}; + +use crate::Result; +use crate::commands::{bad, f32p}; + +/// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast +pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; + +/// The controls of the earlier model and the global adjustments, which 3D Distance doesn't have +const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; + +/// The 3D Distance controls in `params`, refused on other kinds; 3D Distance refuses the earlier model's controls +pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if generator.kind != GeneratorKind::ThreeDDistance { + return match first_given(params, &DISTANCE_KEYS) { + Some(key) => Err(bad(command, format!("{} has no `{key}`: only 3D Distance has it", generator.kind.label()))), + None => Ok(()), + }; + } + if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { + return Err(bad( + command, + format!("3D Distance has no `{key}`: its controls are distanceX, distanceY, distanceZ, distanceRadius, distanceOffset and distanceContrast"), + )); + } + + let mut distance = generator.distance_controls().unwrap_or_default(); + for (axis, key) in DISTANCE_KEYS.iter().take(3).enumerate() { + if let (Some(value), Some(coordinate)) = (f32p(params, key), distance.point.get_mut(axis)) { + *coordinate = value; + } + } + for (key, value) in [("distanceRadius", &mut distance.radius), ("distanceOffset", &mut distance.offset), ("distanceContrast", &mut distance.contrast)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.distance = Some(Box::new(distance.clamped())); + Ok(()) +} + +/// The first of `keys` that `params` gives +fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { + keys.iter().find(|key| params.get(**key).is_some()).copied() +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a9348fc1..041aca62 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ pub mod camera_cmds; pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; +pub mod distance_params; pub mod effect_blending_cmds; pub mod effect_clipboard; pub mod file_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 3462216c..fd9b3466 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -8,6 +8,7 @@ use texturecraft_core::{ use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::distance_params::distance_from; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; @@ -55,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -695,6 +696,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R section_from(command, params, generator)?; let earlier_keys: &[&str] = if WearParameters::defaults(generator.kind).is_some() { &EARLIER_WEAR_KEYS } else { &EARLIER_SECTION_KEYS }; micro_from(command, params, generator, earlier_keys)?; + distance_from(command, params, generator)?; if let Some(level) = f32p(params, "level") { generator.level = level.clamp(0.0, 1.0); } @@ -1278,7 +1280,8 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { noise_amount: current.noise_amount, noise_scale: current.noise_scale, seed: current.seed, - offset: current.offset, + // The offset belongs to the earlier model, which these kinds lack + offset: if kind.has_no_earlier_model() { 0.0 } else { current.offset }, direction: current.direction, invert: current.invert, global: current.global, diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs new file mode 100644 index 00000000..07f0bdb8 --- /dev/null +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -0,0 +1,61 @@ +//! The 3D Distance generator through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point + +use serde_json::{Value, json}; +use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + session +} + +fn add(session: &mut Session, params: Value) -> u64 { + execute(session, "effect.add.generator", ¶ms).unwrap()["effect"].as_u64().unwrap() +} + +fn generator(session: &Session, effect: u64) -> Generator { + match &session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + other => panic!("not a generator: {other:?}"), + } +} + +#[test] +fn three_d_distance_takes_its_controls_by_name_and_label() { + let mut session = session(); + for name in ["3dDistance", "3D Distance", "ThreeDDistance"] { + let effect = add(&mut session, json!({"generator": name, "distanceX": 0.2, "distanceRadius": 3.0, "distanceOffset": 0.7, "invert": true})); + + let made = generator(&session, effect); + assert_eq!(made.kind, GeneratorKind::ThreeDDistance, "{name}"); + let expected = DistanceParameters { point: [0.2, 0.5, 0.5], radius: 1.5, offset: 0.7, ..DistanceParameters::default() }; + assert_eq!(made.distance_controls(), Some(expected), "{name}: the radius stops at 1.5"); + assert!(made.invert && !made.on_earlier_model()); + } +} + +#[test] +fn three_d_distance_refuses_the_earlier_and_global_controls_and_others_refuse_its_own() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "3dDistance"})); + for key in ["level", "softness", "noise", "offset", "blur", "balance", "contrast"] { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, key: 0.3})).is_err(), "{key}"); + } + + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "distanceRadius": 0.5})).is_err()); + assert_eq!(generator(&session, curvature).distance, None); +} + +#[test] +fn swapping_onto_three_d_distance_drops_the_earlier_offset() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "curvature", "level": 0.5, "offset": 0.4})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "3dDistance"})).unwrap(); + let swapped = generator(&session, effect); + assert_eq!(swapped.offset, 0.0); + assert_eq!(swapped.distance_controls(), Some(DistanceParameters::default())); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 08d80a48..c67529cc 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -41,6 +41,7 @@ mod generator_micro_details; mod generator_sections; mod generator_swap; mod generator_texture; +mod generator_three_d_distance; mod generator_wear; mod gradient_map; mod high_poly_missed; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bfcf203a..22505eb3 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -95,6 +95,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::Position => (tr("A gradient across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + GeneratorKind::ThreeDDistance => (tr("A gradient around a point on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 0ab43ea76c8fb9b1c89f70531b0187250a33476c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:37:20 +0000 Subject: [PATCH 15/54] Generators: 3D Linear Gradient between a start and an end point A new kind with the reference's controls: 3D Position Start and End (0 to 1 across the mesh's bounds, scaled evenly like 3D Distance; bottom to top by default), Balance, Contrast and Invert. The value is how far along from the start to the end a texel lies, balanced and contrasted like the global controls; on the test gun it matches the reference within 0.001 on every captured setting, as 3D Distance does. It shares 3D Distance's command module; each refuses the other's controls, and both refuse the earlier model's and the global ones. Commands only: picking the points on the mesh and the panel come with its mock. --- crates/compose/src/eval.rs | 9 +++- crates/compose/src/three_d_distance.rs | 15 +++++- .../tests/generator_three_d_distance.rs | 29 +++++++++-- crates/core/src/layer.rs | 26 ++++++++-- .../src/layer/linear_gradient_parameters.rs | 36 +++++++++++++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 6 +-- crates/engine/src/distance_params.rs | 50 ++++++++++++++----- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 29 ++++++++++- crates/ui-egui/src/generator_panel.rs | 3 ++ 13 files changed, 177 insertions(+), 37 deletions(-) create mode 100644 crates/core/src/layer/linear_gradient_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 29db5ca0..39178fd9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3411,6 +3411,10 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(gradient) = generator.linear_gradient_controls() { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(&gradient, position); + } let coords = self.coords(); @@ -3431,7 +3435,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3477,7 +3481,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear - | GeneratorKind::ThreeDDistance => 0.0, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => 0.0, } } diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs index f6f909c8..d62524d4 100644 --- a/crates/compose/src/three_d_distance.rs +++ b/crates/compose/src/three_d_distance.rs @@ -1,6 +1,6 @@ -//! The 3D Distance generator: a gradient falling off with the distance from a point across the mesh's bounds +//! The 3D Distance and 3D Linear Gradient generators: gradients around a point and between two points across the mesh's bounds -use texturecraft_core::DistanceParameters; +use texturecraft_core::{DistanceParameters, GeneratorGlobal, LinearGradientParameters}; use texturecraft_geom::glam::Vec3; use crate::histogram_scan::histogram_scan; @@ -11,3 +11,14 @@ pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f let gradient = if distance.radius > 0.0 { (1.0 - from_point / distance.radius).clamp(0.0, 1.0) } else { 0.0 }; histogram_scan(gradient, distance.offset, distance.contrast) } + +/// Shortest start-to-end span the gradient divides by +const MIN_GRADIENT_LENGTH: f32 = 1e-6; + +/// The value at `position`: how far along from the start to the end it lies (0 at the start, 1 at the end), balanced and contrasted like a generator's global controls +pub(crate) fn linear_gradient_value(gradient: &LinearGradientParameters, position: Vec3) -> f32 { + let (start, end) = (Vec3::from(gradient.start), Vec3::from(gradient.end)); + let span = end - start; + let along = if span.length_squared() > MIN_GRADIENT_LENGTH { (position - start).dot(span) / span.length_squared() } else { 0.0 }; + GeneratorGlobal { balance: gradient.balance, contrast: gradient.contrast, ..GeneratorGlobal::default() }.apply(along.clamp(0.0, 1.0)) +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs index 6b233479..35d4aaad 100644 --- a/crates/compose/tests/generator_three_d_distance.rs +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -1,11 +1,11 @@ -//! The 3D Distance generator on a sphere: white at its point, falling off over its radius, slid by its offset +//! The 3D Distance and 3D Linear Gradient generators on a sphere: white at a point falling off over a radius, and a gradient between two points use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, - Source, TextureSet, + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LinearGradientParameters, Mask, + MaskBackground, Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -40,7 +40,11 @@ fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { /// The mask of a 3D Distance generator with `distance` alone over black at `texels` fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { - let generator = Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }; + generator_mask(fixture, Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) +} + +/// The mask of `generator` alone over black at `texels` +fn generator_mask(fixture: &mut Fixture, generator: Generator, texels: &[(u32, u32)]) -> Vec { let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); @@ -94,3 +98,20 @@ fn a_larger_radius_reaches_further() { let large = total(mask(&mut fixture, DistanceParameters { radius: 1.2, ..DistanceParameters::default() }, &at)); assert!(large > small); } + +#[test] +fn the_linear_gradient_runs_from_its_start_to_its_end() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + let gradient = + |gradient: LinearGradientParameters| Generator { linear_gradient: Some(Box::new(gradient)), ..Generator::new(GeneratorKind::ThreeDLinearGradient) }; + + let upwards = generator_mask(&mut fixture, gradient(LinearGradientParameters::default()), &at); + let downwards = + generator_mask(&mut fixture, gradient(LinearGradientParameters { start: [0.5, 1.0, 0.5], end: [0.5, 0.0, 0.5], ..Default::default() }), &at); + for (((_, height), up), down) in texels.iter().zip(&upwards).zip(&downwards) { + assert!((up - (height * 0.5 + 0.5)).abs() < 0.02, "bottom to top across the sphere's height: {up} at {height}"); + assert!((up + down - 1.0).abs() < 1e-4, "swapping the points reverses it"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 67e57460..bdbd77c4 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -24,6 +24,7 @@ mod filtering; mod generator_global; mod generator_grayscale; mod light_parameters; +mod linear_gradient_parameters; mod micro_curvature_type; mod micro_details; mod output_resolution; @@ -55,6 +56,7 @@ pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; pub use light_parameters::LightParameters; +pub use linear_gradient_parameters::LinearGradientParameters; pub use micro_curvature_type::MicroCurvatureType; pub use micro_details::MicroDetails; pub use output_resolution::OutputResolution; @@ -954,10 +956,12 @@ pub enum GeneratorKind { WorldSpaceNormals, /// White around a point across the mesh's bounds, fading with the distance from it ThreeDDistance, + /// A gradient from a start point to an end point across the mesh's bounds + ThreeDLinearGradient, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 10] = [ + pub const ALL: [GeneratorKind; 11] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -968,6 +972,7 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear, GeneratorKind::WorldSpaceNormals, GeneratorKind::ThreeDDistance, + GeneratorKind::ThreeDLinearGradient, ]; pub fn label(self) -> &'static str { match self { @@ -981,6 +986,7 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear => "Fiber Glass Edge Wear", GeneratorKind::WorldSpaceNormals => "World Space Normals", GeneratorKind::ThreeDDistance => "3D Distance", + GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", } } @@ -997,12 +1003,13 @@ impl GeneratorKind { GeneratorKind::FiberGlassEdgeWear => "FiberGlassEdgeWear", GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", GeneratorKind::ThreeDDistance => "ThreeDDistance", + GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; 3D Distance waits for its panel) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the 3D kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance) + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) } /// Whether the kind's result depends on its seed @@ -1017,7 +1024,7 @@ impl GeneratorKind { GeneratorKind::Curvature => &[BakedMap::Curvature], GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], GeneratorKind::ThinAreas => &[BakedMap::Thickness], - GeneratorKind::Position | GeneratorKind::ThreeDDistance => &[BakedMap::Position], + GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], } @@ -1025,7 +1032,7 @@ impl GeneratorKind { /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise pub fn has_no_earlier_model(self) -> bool { - matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance) + matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) } pub fn parse(s: &str) -> Option { @@ -1094,6 +1101,9 @@ pub struct Generator { /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub distance: Option>, + /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub linear_gradient: Option>, } impl Serialize for Generator { @@ -1140,6 +1150,11 @@ impl Generator { self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) } + /// The 3D Linear Gradient controls the generator computes with: its own, else the defaults on a 3D Linear Gradient generator + pub fn linear_gradient_controls(&self) -> Option { + self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1207,6 +1222,7 @@ impl Generator { grunge: None, micro: None, distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), + linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), } } diff --git a/crates/core/src/layer/linear_gradient_parameters.rs b/crates/core/src/layer/linear_gradient_parameters.rs new file mode 100644 index 00000000..2526da80 --- /dev/null +++ b/crates/core/src/layer/linear_gradient_parameters.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// The 3D Linear Gradient generator's controls: black at the start point, white at the end point, across the mesh's bounds +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LinearGradientParameters { + /// Where the gradient is black, 0..1 across the mesh's bounds on each axis + pub start: [f32; 3], + /// Where the gradient is white + pub end: [f32; 3], + /// Shifts the gradient darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gradient around its middle (0..1; 1 a hard step) + pub contrast: f32, +} + +impl LinearGradientParameters { + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> LinearGradientParameters { + let defaults = LinearGradientParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + LinearGradientParameters { + start: std::array::from_fn(|axis| unit(self.start[axis], defaults.start[axis])), + end: std::array::from_fn(|axis| unit(self.end[axis], defaults.end[axis])), + balance: unit(self.balance, defaults.balance), + contrast: unit(self.contrast, defaults.contrast), + } + } +} + +impl Default for LinearGradientParameters { + /// The reference app's defaults: bottom to top through the bounds' centre + fn default() -> LinearGradientParameters { + LinearGradientParameters { start: [0.5, 0.0, 0.5], end: [0.5, 1.0, 0.5], balance: 0.5, contrast: 0.0 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index a0cbc4ff..377e2d22 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -74,7 +74,8 @@ impl MicroDetails { | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 322fd54c..18837e45 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -40,7 +40,8 @@ impl SectionParameters { | GeneratorKind::ThinAreas | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index b354a95f..8937561c 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -59,7 +59,8 @@ impl WearParameters { | GeneratorKind::Position | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals - | GeneratorKind::ThreeDDistance => None, + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index bd02feff..0206af63 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,11 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, - GeneratorGlobal, GeneratorKind, GeneratorGrayscale, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, - OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, - Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, - hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 6e16cbda..2aa370ff 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,30 +1,36 @@ -//! The 3D Distance controls `effect.add.generator` and `effect.set` take +//! The 3D Distance and 3D Linear Gradient controls `effect.add.generator` and `effect.set` take use serde_json::Value; use texturecraft_core::{Generator, GeneratorKind}; use crate::Result; -use crate::commands::{bad, f32p}; +use crate::commands::{bad, color_param, f32p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; -/// The controls of the earlier model and the global adjustments, which 3D Distance doesn't have +/// The 3D Linear Gradient controls: its start and end points ([x, y, z] across the mesh's bounds), balance and contrast +pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gradientBalance", "gradientContrast"]; + +/// The controls of the earlier model and the global adjustments, which the 3D kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance controls in `params`, refused on other kinds; 3D Distance refuses the earlier model's controls +/// The 3D Distance and 3D Linear Gradient controls in `params`, each refused on other kinds; both kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { - if generator.kind != GeneratorKind::ThreeDDistance { - return match first_given(params, &DISTANCE_KEYS) { - Some(key) => Err(bad(command, format!("{} has no `{key}`: only 3D Distance has it", generator.kind.label()))), - None => Ok(()), - }; + let kind = generator.kind; + for (keys, owner) in [(&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient)] { + if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { + return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); + } + } + if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) { + return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { - return Err(bad( - command, - format!("3D Distance has no `{key}`: its controls are distanceX, distanceY, distanceZ, distanceRadius, distanceOffset and distanceContrast"), - )); + return Err(bad(command, format!("{} has no `{key}`: it has its own controls only", kind.label()))); + } + if kind == GeneratorKind::ThreeDLinearGradient { + return linear_gradient_from(command, params, generator); } let mut distance = generator.distance_controls().unwrap_or_default(); @@ -42,6 +48,24 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - Ok(()) } +/// The 3D Linear Gradient controls in `params` (the generator is one) +fn linear_gradient_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let mut gradient = generator.linear_gradient_controls().unwrap_or_default(); + if let Some(start) = color_param(command, params, "gradientStart")? { + gradient.start = start; + } + if let Some(end) = color_param(command, params, "gradientEnd")? { + gradient.end = end; + } + for (key, value) in [("gradientBalance", &mut gradient.balance), ("gradientContrast", &mut gradient.contrast)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.linear_gradient = Some(Box::new(gradient.clamped())); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index fd9b3466..78a407b7 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 07f0bdb8..8c5f0da5 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,7 @@ -//! The 3D Distance generator through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The 3D Distance and 3D Linear Gradient generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId}; +use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -59,3 +59,28 @@ fn swapping_onto_three_d_distance_drops_the_earlier_offset() { assert_eq!(swapped.offset, 0.0); assert_eq!(swapped.distance_controls(), Some(DistanceParameters::default())); } + +#[test] +fn three_d_linear_gradient_takes_its_points_balance_and_contrast() { + let mut session = session(); + let params = + json!({"generator": "3D Linear Gradient", "gradientStart": [0.0, 0.5, 0.5], "gradientEnd": [1.0, 0.5, 2.0], "gradientBalance": 0.25, "invert": true}); + let effect = add(&mut session, params); + + let made = generator(&session, effect); + assert_eq!(made.kind, GeneratorKind::ThreeDLinearGradient); + let expected = LinearGradientParameters { start: [0.0, 0.5, 0.5], end: [1.0, 0.5, 1.0], balance: 0.25, contrast: 0.0 }; + assert_eq!(made.linear_gradient_controls(), Some(expected), "points stay within the bounds"); + assert!(made.invert && !made.on_earlier_model()); +} + +#[test] +fn each_3d_kind_refuses_the_others_controls() { + let mut session = session(); + let gradient = add(&mut session, json!({"generator": "3dLinearGradient"})); + let distance = add(&mut session, json!({"generator": "3dDistance"})); + + assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "distanceRadius": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": distance, "gradientBalance": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "level": 0.5})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 22505eb3..fa9df7b1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -96,6 +96,9 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::Direction => (tr("Surfaces facing a light."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::WorldSpaceNormals => (tr("Surfaces facing along the world's axes."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), GeneratorKind::ThreeDDistance => (tr("A gradient around a point on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::ThreeDLinearGradient => { + (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) + } }; // Wrapped rows: a long line must not widen the panel past its edge From 9562b30c2b12fb338446ba4daf6f308331812270 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:05:17 +0000 Subject: [PATCH 16/54] Generators: UV Border Distance, white at the UV islands' borders fading inwards A new kind with the reference's controls: Distance (1 reaches about half a UV tile in), Smoothness, Balance, Contrast and Invert. Each covered texel's exact Euclidean distance to the nearest uncovered texel of its UV tile (the tile's edge counting as a border) sets a linear gradient; Smoothness blurs it with the empty space around the islands, softening the borders towards black; balance and contrast act like the global controls. The gradient is built once per UV layout and setting and cached. On the test gun it matches the reference within 0.002 to 0.011 mean error on every captured setting. Commands only; the picker leaves it out until its panel is designed. --- crates/compose/src/eval.rs | 11 +- crates/compose/src/generator_maps.rs | 6 +- crates/compose/src/lib.rs | 1 + crates/compose/src/uv_border_distance.rs | 217 ++++++++++++++++++ .../tests/generator_uv_border_distance.rs | 80 +++++++ crates/core/src/layer.rs | 28 ++- .../src/layer/border_distance_parameters.rs | 36 +++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 32 ++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 17 +- crates/ui-egui/src/generator_panel.rs | 1 + 15 files changed, 423 insertions(+), 19 deletions(-) create mode 100644 crates/compose/src/uv_border_distance.rs create mode 100644 crates/compose/tests/generator_uv_border_distance.rs create mode 100644 crates/core/src/layer/border_distance_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 39178fd9..ceeeb6a0 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -44,6 +44,7 @@ use crate::slope_texel::slope_texel; use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode}; use crate::texture_layer; use crate::three_d_distance; +use crate::uv_border_distance; use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample, warp_texel}; use crate::wear; use crate::wear_inputs::WearInputs; @@ -3411,6 +3412,11 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(border) = generator.border_distance_controls() { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); + return uv_border_distance::border_value(&border, gradient); + } if let Some(gradient) = generator.linear_gradient_controls() { let position = self.uniform_position_input(generator); return three_d_distance::linear_gradient_value(&gradient, position); @@ -3435,7 +3441,7 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance, _) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3482,7 +3488,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => 0.0, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 6bc18477..613e7e3a 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -7,6 +7,7 @@ use texturecraft_core::{BakedMap, Generator, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; +use crate::uv_border_distance::border_gradient; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -17,6 +18,8 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, + /// The UV Border Distance gradient at every working texel + pub border_gradient: Option>>, } impl GeneratorMaps { @@ -29,6 +32,7 @@ impl GeneratorMaps { Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion } + let border_gradient = generator.border_distance_controls().map(|border| border_gradient(inp, &border)); + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index cf4ed85e..24c3f9e5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -52,6 +52,7 @@ pub mod tile_length; mod tile_pattern; mod tile_random_stream; mod timber; +mod uv_border_distance; pub mod warp; mod warp_source_sample; mod warp_texel; diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs new file mode 100644 index 00000000..50033fcd --- /dev/null +++ b/crates/compose/src/uv_border_distance.rs @@ -0,0 +1,217 @@ +//! The UV Border Distance generator: how far each texel lies inside its UV island, as a gradient built once per UV layout and settings + +use std::sync::{Arc, Mutex}; + +use rayon::prelude::*; +use texturecraft_core::{BlockScales, BorderDistanceParameters, GeneratorGlobal}; + +use crate::eval::{Inputs, blur}; + +/// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) +const REACH_PER_DISTANCE: f32 = 0.4936; + +/// The blur at Smoothness 1, as a gaussian sigma in texels of a 2K UV tile (fitted) +const SMOOTHNESS_SIGMA_2K: f32 = 45.0; + +/// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// Cached gradients; one per layout and setting a stack shows at a time +const CACHE_ENTRIES: usize = 8; + +/// Texels between the samples a layout's fingerprint reads +const FINGERPRINT_STRIDE: usize = 997; + +/// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits +#[derive(Clone, PartialEq)] +struct Key { + size: (u32, u32), + fingerprint: u64, + block: (u32, u32), + scales: BlockScales, + settings: [u32; 2], +} + +static CACHE: Mutex>)>> = Mutex::new(Vec::new()); + +/// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) +pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { + let gbuf = inp.gbuf; + let size = (gbuf.width, gbuf.height); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); + let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); + let key = Key { size, fingerprint, block, scales: inp.block_scales.clone(), settings: [border.distance.to_bits(), border.smoothness.to_bits()] }; + + let cached = { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().find(|(cached, _)| *cached == key).map(|(_, gradient)| gradient.clone()) + }; + if let Some(gradient) = cached { + return gradient; + } + + // Built without the cache locked: the build runs parallel work + let gradient = Arc::new(build(inp, border, block)); + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(cached, _)| *cached != key); + cache.push((key, gradient.clone())); + let excess = cache.len().saturating_sub(CACHE_ENTRIES); + cache.drain(..excess); + gradient +} + +/// The value at a working texel: the gradient balanced, contrasted and inverted +pub(crate) fn border_value(border: &BorderDistanceParameters, gradient: f32) -> f32 { + GeneratorGlobal { balance: border.balance, contrast: border.contrast, ..GeneratorGlobal::default() }.apply(gradient) +} + +fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + + // Every covered texel's distance to the nearest uncovered one, within its UV tile + let distances = border_distances(gbuf, (width, height), block); + + let mut gradient: Vec = (0..width * height) + .into_par_iter() + .map(|texel| { + if !gbuf.covered(texel as usize) { + return 0.0; + } + let (x, y) = (texel % width, texel / width); + let tile_texels = block.0 as f32 * inp.block_scales.at(x, y); + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0); + let reach = border.distance * REACH_PER_DISTANCE * tile_texels; + if reach > 0.0 { (1.0 - to_border / reach).clamp(0.0, 1.0) } else { 0.0 } + }) + .collect(); + + // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black + let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * block.0 as f32 / REFERENCE_TILE_TEXELS; + let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize; + if radius > 0 { + blur_blocks(&mut gradient, (width, height), block, radius); + for (value, texel) in gradient.iter_mut().zip(0..) { + if !gbuf.covered(texel) { + *value = 0.0; + } + } + } + gradient +} + +/// Each texel's Euclidean distance in texels to the nearest uncovered texel of its UV tile block, the space past the block's edges counting as uncovered +fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { + let mut squared = vec![0.0f32; (width * height) as usize]; + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + + // A ring of uncovered texels around the block, then the exact transform along rows and columns + let (padded_columns, padded_rows) = (columns + 2, rows + 2); + let mut field: Vec = (0..padded_rows) + .flat_map(|row| (0..padded_columns).map(move |column| (column, row))) + .map(|(column, row)| { + let inside = (1..=columns).contains(&column) && (1..=rows).contains(&row); + if inside && gbuf.covered(index(column - 1, row - 1)) { f32::INFINITY } else { 0.0 } + }) + .collect(); + field.par_chunks_mut(padded_columns).for_each(squared_distance_line); + let mut transposed: Vec = (0..padded_columns * padded_rows) + .map(|texel| field.get((texel % padded_rows) * padded_columns + texel / padded_rows).copied().unwrap_or(0.0)) + .collect(); + transposed.par_chunks_mut(padded_rows).for_each(squared_distance_line); + + for row in 0..rows { + for column in 0..columns { + let value = transposed.get((column + 1) * padded_rows + row + 1).copied().unwrap_or(0.0); + if let Some(target) = squared.get_mut(index(column, row)) { + *target = value; + } + } + } + } + } + squared.into_iter().map(f32::sqrt).collect() +} + +/// The squared distance transform of one line in place (Felzenszwalb and Huttenlocher's lower envelope of parabolas); `line` holds 0 at sources and infinity elsewhere +fn squared_distance_line(line: &mut [f32]) { + let length = line.len(); + let input = line.to_vec(); + let finite: Vec = (0..length).filter(|index| input.get(*index).is_some_and(|value| value.is_finite())).collect(); + if finite.is_empty() { + return; + } + + // Parabola vertices and the boundaries between them + let value_at = |index: usize| input.get(index).copied().unwrap_or(f32::INFINITY); + let intersection = |a: usize, b: usize| ((value_at(b) + (b * b) as f32) - (value_at(a) + (a * a) as f32)) / (2.0 * (b as f32 - a as f32)); + let mut vertices: Vec = Vec::with_capacity(finite.len()); + let mut boundaries: Vec = Vec::with_capacity(finite.len() + 1); + for &index in &finite { + while let (Some(&last), Some(&start)) = (vertices.last(), boundaries.last()) { + if intersection(last, index) <= start { + vertices.pop(); + boundaries.pop(); + } else { + break; + } + } + let start = vertices.last().map_or(f32::NEG_INFINITY, |&last| intersection(last, index)); + vertices.push(index); + boundaries.push(start); + } + + let mut current = 0; + for (index, value) in line.iter_mut().enumerate() { + while boundaries.get(current + 1).is_some_and(|next| *next < index as f32) { + current += 1; + } + let vertex = vertices.get(current).copied().unwrap_or(index); + let offset = index as f32 - vertex as f32; + *value = offset * offset + value_at(vertex); + } +} + +/// `data` blurred one UV tile block at a time, reading black past each block's edges +fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius: usize) { + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + let mut values: Vec = (0..rows) + .flat_map(|row| (0..columns).map(move |column| (column, row))) + .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) + .collect(); + blur(&mut values, columns, rows, radius); + for (offset, value) in values.into_iter().enumerate() { + if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { + *target = value; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_line_reads_the_squared_distance_to_its_nearest_source() { + let mut line = [0.0, f32::INFINITY, f32::INFINITY, f32::INFINITY, f32::INFINITY, 0.0, f32::INFINITY]; + squared_distance_line(&mut line); + assert_eq!(line, [0.0, 1.0, 4.0, 4.0, 1.0, 0.0, 1.0]); + } + + #[test] + fn a_line_without_sources_stays_unreached() { + let mut line = [f32::INFINITY; 3]; + squared_distance_line(&mut line); + assert!(line.iter().all(|value| value.is_infinite())); + } +} diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs new file mode 100644 index 00000000..db5b5db6 --- /dev/null +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -0,0 +1,80 @@ +//! The UV Border Distance generator on a plane filling its UV tile: white at the tile's edge, fading inwards over its distance, softened by its smoothness + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, + TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// The middle row's values, left edge to centre +fn row(fixture: &mut Fixture, border: BorderDistanceParameters) -> Vec { + let generator = Generator { border_distance: Some(Box::new(border)), ..Generator::new(GeneratorKind::UvBorderDistance) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES / 2).map(|x| (x, RES / 2)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +#[test] +fn the_border_is_white_and_the_inside_fades_to_black() { + let mut fixture = fixture(); + let values = row(&mut fixture, BorderDistanceParameters { distance: 0.5, ..BorderDistanceParameters::default() }); + + assert!(values[0] > 0.9, "the edge, a texel in: {}", values[0]); + assert!(values.windows(2).all(|pair| pair[1] <= pair[0]), "falling inwards: {values:?}"); + assert!(*values.last().unwrap() < 0.05, "half a tile in is black at distance 0.5"); +} + +#[test] +fn a_larger_distance_reaches_further_in() { + let mut fixture = fixture(); + let near = row(&mut fixture, BorderDistanceParameters { distance: 0.1, ..BorderDistanceParameters::default() }); + let far = row(&mut fixture, BorderDistanceParameters { distance: 0.6, ..BorderDistanceParameters::default() }); + + assert!(far.iter().sum::() > near.iter().sum::() + 1.0); +} + +#[test] +fn smoothness_darkens_the_edge_with_the_space_around_the_island() { + let mut fixture = fixture(); + let sharp = row(&mut fixture, BorderDistanceParameters::default()); + let smooth = row(&mut fixture, BorderDistanceParameters { smoothness: 1.0, ..BorderDistanceParameters::default() }); + + assert!(smooth[0] < sharp[0] - 0.2, "{} vs {}", smooth[0], sharp[0]); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index bdbd77c4..f19b2ec3 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -15,6 +15,7 @@ use crate::{ mod anchored_micro_detail; mod axis_blend; mod axis_layer; +mod border_distance_parameters; mod curvature_detail; mod curvature_mode; mod decal_flip; @@ -47,6 +48,7 @@ mod wear_parameters; use anchored_micro_detail::AnchoredMicroDetail; pub use axis_blend::AxisBlend; pub use axis_layer::AxisLayer; +pub use border_distance_parameters::BorderDistanceParameters; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; @@ -958,10 +960,12 @@ pub enum GeneratorKind { ThreeDDistance, /// A gradient from a start point to an end point across the mesh's bounds ThreeDLinearGradient, + /// White at the UV islands' borders, fading towards their insides + UvBorderDistance, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 11] = [ + pub const ALL: [GeneratorKind; 12] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -973,6 +977,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals, GeneratorKind::ThreeDDistance, GeneratorKind::ThreeDLinearGradient, + GeneratorKind::UvBorderDistance, ]; pub fn label(self) -> &'static str { match self { @@ -987,6 +992,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => "World Space Normals", GeneratorKind::ThreeDDistance => "3D Distance", GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", + GeneratorKind::UvBorderDistance => "UV Border Distance", } } @@ -1004,12 +1010,13 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => "WorldSpaceNormals", GeneratorKind::ThreeDDistance => "ThreeDDistance", GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", + GeneratorKind::UvBorderDistance => "UvBorderDistance", } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the 3D kinds wait for their panels) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) + !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) } /// Whether the kind's result depends on its seed @@ -1027,12 +1034,16 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], + GeneratorKind::UvBorderDistance => &[], } } /// Whether the kind was added with the reference's controls only, so it never computes with level, softness and noise pub fn has_no_earlier_model(self) -> bool { - matches!(self, GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) + matches!( + self, + GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance + ) } pub fn parse(s: &str) -> Option { @@ -1104,6 +1115,9 @@ pub struct Generator { /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub linear_gradient: Option>, + /// The UV Border Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border_distance: Option>, } impl Serialize for Generator { @@ -1155,6 +1169,11 @@ impl Generator { self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) } + /// The UV Border Distance controls the generator computes with: its own, else the defaults on a UV Border Distance generator + pub fn border_distance_controls(&self) -> Option { + self.border_distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::UvBorderDistance).then(BorderDistanceParameters::default)) + } + /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None pub fn detail_in_use(&self) -> Option { let on_section = self.kind == GeneratorKind::Curvature && self.section_controls().is_some(); @@ -1223,6 +1242,7 @@ impl Generator { micro: None, distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), + border_distance: (kind == GeneratorKind::UvBorderDistance).then(Box::default), } } diff --git a/crates/core/src/layer/border_distance_parameters.rs b/crates/core/src/layer/border_distance_parameters.rs new file mode 100644 index 00000000..2d55c45b --- /dev/null +++ b/crates/core/src/layer/border_distance_parameters.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Border Distance generator's controls: white at the UV islands' borders, fading towards their insides +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BorderDistanceParameters { + /// How far in from the border the gradient reaches (0..1; 1 is half a UV tile) + pub distance: f32, + /// Softens the gradient, the empty space around the islands darkening their borders (0..1) + pub smoothness: f32, + /// Shifts the gradient darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gradient around its middle (0..1; 1 a hard step) + pub contrast: f32, +} + +impl BorderDistanceParameters { + /// Every value brought into 0..1, non-finite ones to the defaults + pub fn clamped(self) -> BorderDistanceParameters { + let defaults = BorderDistanceParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + BorderDistanceParameters { + distance: unit(self.distance, defaults.distance), + smoothness: unit(self.smoothness, defaults.smoothness), + balance: unit(self.balance, defaults.balance), + contrast: unit(self.contrast, defaults.contrast), + } + } +} + +impl Default for BorderDistanceParameters { + /// The reference app's defaults + fn default() -> BorderDistanceParameters { + BorderDistanceParameters { distance: 0.1, smoothness: 0.0, balance: 0.5, contrast: 0.0 } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 377e2d22..4fdfe6f5 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -75,7 +75,8 @@ impl MicroDetails { | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 18837e45..c0c64f41 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -41,7 +41,8 @@ impl SectionParameters { | GeneratorKind::Direction | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 8937561c..4f10a9c6 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -60,7 +60,8 @@ impl WearParameters { | GeneratorKind::Direction | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient => None, + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0206af63..fcbd7228 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 2aa370ff..5bab2b11 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,4 +1,4 @@ -//! The 3D Distance and 3D Linear Gradient controls `effect.add.generator` and `effect.set` take +//! The controls of 3D Distance, 3D Linear Gradient and UV Border Distance that `effect.add.generator` and `effect.set` take use serde_json::Value; use texturecraft_core::{Generator, GeneratorKind}; @@ -12,18 +12,25 @@ pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "di /// The 3D Linear Gradient controls: its start and end points ([x, y, z] across the mesh's bounds), balance and contrast pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gradientBalance", "gradientContrast"]; -/// The controls of the earlier model and the global adjustments, which the 3D kinds don't have +/// The UV Border Distance controls +pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness", "borderBalance", "borderContrast"]; + +/// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance and 3D Linear Gradient controls in `params`, each refused on other kinds; both kinds refuse the earlier model's and the global controls +/// The 3D Distance, 3D Linear Gradient and UV Border Distance controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; - for (keys, owner) in [(&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient)] { + for (keys, owner) in [ + (&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), + (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), + (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), + ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); } } - if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient) { + if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) { return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { @@ -32,6 +39,21 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::ThreeDLinearGradient { return linear_gradient_from(command, params, generator); } + if kind == GeneratorKind::UvBorderDistance { + let mut border = generator.border_distance_controls().unwrap_or_default(); + for (key, value) in [ + ("borderDistance", &mut border.distance), + ("borderSmoothness", &mut border.smoothness), + ("borderBalance", &mut border.balance), + ("borderContrast", &mut border.contrast), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.border_distance = Some(Box::new(border.clamped())); + return Ok(()); + } let mut distance = generator.distance_controls().unwrap_or_default(); for (axis, key) in DISTANCE_KEYS.iter().take(3).enumerate() { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 78a407b7..393e8a0b 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 8c5f0da5..a1508452 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,7 @@ -//! The 3D Distance and 3D Linear Gradient generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; +use texturecraft_engine::core::{BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -84,3 +84,16 @@ fn each_3d_kind_refuses_the_others_controls() { assert!(execute(&mut session, "effect.set", &json!({"effect": distance, "gradientBalance": 0.5})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": gradient, "level": 0.5})).is_err()); } + +#[test] +fn uv_border_distance_takes_its_controls_and_refuses_the_others() { + let mut session = session(); + let effect = add(&mut session, json!({"generator": "UV Border Distance", "borderDistance": 0.3, "borderSmoothness": 2.0, "borderContrast": 0.4})); + + let expected = BorderDistanceParameters { distance: 0.3, smoothness: 1.0, contrast: 0.4, ..BorderDistanceParameters::default() }; + assert_eq!(generator(&session, effect).border_distance_controls(), Some(expected)); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "distanceRadius": 0.5})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "softness": 0.5})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "borderDistance": 0.5})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index fa9df7b1..0139894f 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -99,6 +99,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::ThreeDLinearGradient => { (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) } + GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 13062a8efdb14153e5f7d50dc13ac6e1e5a61d22 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:27:14 +0000 Subject: [PATCH 17/54] Generators: Grayscale Conversion; the kinds with only their own controls share one field Grayscale Conversion is a new kind with the reference's controls: an image (effect.set input: image; an empty slot reads black) repeated Tile times across the UV square and turned by Rotation about its centre, made gray by one of the eight conversions Use Texture already has, then Balance, Contrast and Invert like the global controls. Safe Rotation turns in quarter turns only so the image keeps tiling; that rule is inferred, as the reference captures had no image plugged in. Its image counts as a used resource. 3D Distance, 3D Linear Gradient, UV Border Distance and Grayscale Conversion now keep their controls in one boxed KindControls field (one variant per kind) instead of a field each, so a generator effect stays small as kinds are added; their behaviour is unchanged. Commands only; the picker leaves the new kinds out until their panels are designed. --- crates/compose/src/eval.rs | 36 +++++-- .../tests/generator_grayscale_conversion.rs | 102 ++++++++++++++++++ .../tests/generator_three_d_distance.rs | 12 ++- .../tests/generator_uv_border_distance.rs | 6 +- crates/core/src/layer.rs | 82 ++++++++++---- .../layer/grayscale_conversion_parameters.rs | 59 ++++++++++ crates/core/src/layer/kind_controls.rs | 44 ++++++++ crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 47 ++++++-- crates/engine/src/mask_cmds.rs | 24 ++++- .../tests/it/generator_three_d_distance.rs | 27 ++++- crates/ui-egui/src/generator_panel.rs | 1 + 15 files changed, 397 insertions(+), 54 deletions(-) create mode 100644 crates/compose/tests/generator_grayscale_conversion.rs create mode 100644 crates/core/src/layer/grayscale_conversion_parameters.rs create mode 100644 crates/core/src/layer/kind_controls.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ceeeb6a0..2d725331 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,11 +12,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, - CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorKind, HeightMask, HeightToNormal, - HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, - PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, - TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -1952,6 +1948,9 @@ fn filter_region( /// What a generator's texture or custom grunge reads with nothing in its slot const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); +/// The step Safe Rotation turns a Grayscale Conversion image by, so it keeps tiling seamlessly +const QUARTER_TURN_DEGREES: f32 = 90.0; + /// Values per texel of a generator stage's region: the stack below, the generator's ramp and its texture's gray const GENERATOR_STAGE_COMPONENTS: usize = 3; @@ -3412,6 +3411,9 @@ impl<'a, 'b> Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::distance_value(&distance, position); } + if let Some(grayscale) = generator.grayscale_controls() { + return self.grayscale_conversion(&grayscale); + } if let Some(border) = generator.border_distance_controls() { let texel = (self.y * self.inp.gbuf.width + self.x) as usize; let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); @@ -3441,7 +3443,9 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance, _) => 0.0, + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion, _) => { + 0.0 + } }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3489,7 +3493,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => 0.0, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => 0.0, } } @@ -3501,6 +3506,23 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted + fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { + let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; + let (sin, cos) = degrees.to_radians().sin_cos(); + let centred = self.coords().uv - Vec2::splat(0.5); + let at = Vec2::new(centred.x * cos - centred.y * sin, centred.x * sin + centred.y * cos) * grayscale.tile + Vec2::splat(0.5); + let rgb = match grayscale.source.as_ref().unwrap_or(&EMPTY_IMAGE_SLOT) { + Source::Image { name, .. } => self.inp.images.get(name).map_or([0.0; 3], |image| { + let [red, green, blue, _] = image.sample(at.x, at.y); + [red, green, blue] + }), + other => self.source(other, &Projection::default(), Sampling::default(), ChannelKind::NormalMap), + }; + let gray = grayscale.grayscale.gray(rgb).clamp(0.0, 1.0); + GeneratorGlobal { balance: grayscale.balance, contrast: grayscale.contrast, ..GeneratorGlobal::default() }.apply(gray) + } + /// The image in `generator`'s Position input, else this texel's position across the mesh's bounds scaled evenly: the longest side spans 0..1, the others centred on 0.5 fn uniform_position_input(&mut self, generator: &Generator) -> Vec3 { if let Some(source) = generator.inputs.get(&BakedMap::Position) { diff --git a/crates/compose/tests/generator_grayscale_conversion.rs b/crates/compose/tests/generator_grayscale_conversion.rs new file mode 100644 index 00000000..ee3e79dd --- /dev/null +++ b/crates/compose/tests/generator_grayscale_conversion.rs @@ -0,0 +1,102 @@ +//! The Grayscale Conversion generator on a plane filling its UV tile: its image turned gray by the chosen type, tiled, turned and balanced + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes, ImageStore, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, KindControls, Layer, LayerId, LayerKind, + Mask, MaskBackground, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 64; + +/// Width of the image: its left half red, its right half blue +const IMAGE_WIDTH: u32 = 16; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + images: ImageStore, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let texel = |index: u32| if index % IMAGE_WIDTH < IMAGE_WIDTH / 2 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] }; + let image = ImageRes::new(IMAGE_WIDTH, IMAGE_WIDTH, (0..IMAGE_WIDTH * IMAGE_WIDTH).map(texel).collect(), false); + Fixture { project, mesh, gbuf, layer, images: [("split".to_string(), Arc::new(image))].into() } +} + +/// The values along a row a quarter of the way down, left to right +fn row(fixture: &mut Fixture, grayscale: GrayscaleConversionParameters) -> Vec { + let generator = Generator { + controls: Some(Box::new(KindControls::Grayscale(GrayscaleConversionParameters { source: Some(Source::image("split")), ..grayscale }))), + ..Generator::new(GeneratorKind::GrayscaleConversion) + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &fixture.images, + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 4)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +fn red_channel() -> GrayscaleConversionParameters { + GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Red, ..GrayscaleConversionParameters::default() } +} + +/// How many times the row changes between dark and light +fn edges(values: &[f32]) -> usize { + values.windows(2).filter(|pair| (pair[0] > 0.5) != (pair[1] > 0.5)).count() +} + +#[test] +fn the_type_picks_what_turns_white() { + let mut fixture = fixture(); + let red = row(&mut fixture, red_channel()); + let blue = row(&mut fixture, GrayscaleConversionParameters { grayscale: GeneratorGrayscale::Blue, ..GrayscaleConversionParameters::default() }); + + assert!(red[2] > 0.9 && red[RES as usize - 3] < 0.1, "red on the left: {red:?}"); + assert!(blue[2] < 0.1 && blue[RES as usize - 3] > 0.9, "blue on the right"); +} + +#[test] +fn tile_repeats_the_image_and_a_half_turn_mirrors_it() { + let mut fixture = fixture(); + let once = row(&mut fixture, red_channel()); + let four = row(&mut fixture, GrayscaleConversionParameters { tile: 4.0, ..red_channel() }); + let turned = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() }); + + assert!(edges(&four) > edges(&once) + 4, "{} vs {}", edges(&four), edges(&once)); + assert!(turned[2] < 0.1 && turned[RES as usize - 3] > 0.9, "the red half swaps sides"); +} + +#[test] +fn safe_rotation_turns_by_quarter_turns_only() { + let mut fixture = fixture(); + let snapped = row(&mut fixture, GrayscaleConversionParameters { rotation: 170.0, ..red_channel() }); + let half = row(&mut fixture, GrayscaleConversionParameters { rotation: 180.0, ..red_channel() }); + + assert_eq!(snapped, half); +} diff --git a/crates/compose/tests/generator_three_d_distance.rs b/crates/compose/tests/generator_three_d_distance.rs index 35d4aaad..db833c3b 100644 --- a/crates/compose/tests/generator_three_d_distance.rs +++ b/crates/compose/tests/generator_three_d_distance.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, LinearGradientParameters, Mask, - MaskBackground, Project, Source, TextureSet, + BakedMap, Channel, DistanceParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, + LinearGradientParameters, Mask, MaskBackground, Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -40,7 +40,7 @@ fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { /// The mask of a 3D Distance generator with `distance` alone over black at `texels` fn mask(fixture: &mut Fixture, distance: DistanceParameters, texels: &[(u32, u32)]) -> Vec { - generator_mask(fixture, Generator { distance: Some(Box::new(distance)), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) + generator_mask(fixture, Generator { controls: Some(Box::new(KindControls::Distance(distance))), ..Generator::new(GeneratorKind::ThreeDDistance) }, texels) } /// The mask of `generator` alone over black at `texels` @@ -104,8 +104,10 @@ fn the_linear_gradient_runs_from_its_start_to_its_end() { let mut fixture = fixture(); let texels = covered(&fixture); let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); - let gradient = - |gradient: LinearGradientParameters| Generator { linear_gradient: Some(Box::new(gradient)), ..Generator::new(GeneratorKind::ThreeDLinearGradient) }; + let gradient = |gradient: LinearGradientParameters| Generator { + controls: Some(Box::new(KindControls::LinearGradient(gradient))), + ..Generator::new(GeneratorKind::ThreeDLinearGradient) + }; let upwards = generator_mask(&mut fixture, gradient(LinearGradientParameters::default()), &at); let downwards = diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs index db5b5db6..4457fb8c 100644 --- a/crates/compose/tests/generator_uv_border_distance.rs +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -2,8 +2,8 @@ use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; use texturecraft_core::{ - BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, - TextureSet, + BorderDistanceParameters, Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + Project, Source, TextureSet, }; use texturecraft_geom::{Mesh, UvGBuffer, primitives}; @@ -30,7 +30,7 @@ fn fixture() -> Fixture { /// The middle row's values, left edge to centre fn row(fixture: &mut Fixture, border: BorderDistanceParameters) -> Vec { - let generator = Generator { border_distance: Some(Box::new(border)), ..Generator::new(GeneratorKind::UvBorderDistance) }; + let generator = Generator { controls: Some(Box::new(KindControls::BorderDistance(border))), ..Generator::new(GeneratorKind::UvBorderDistance) }; let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f19b2ec3..f5c23e39 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -24,6 +24,8 @@ mod distance_parameters; mod filtering; mod generator_global; mod generator_grayscale; +mod grayscale_conversion_parameters; +mod kind_controls; mod light_parameters; mod linear_gradient_parameters; mod micro_curvature_type; @@ -57,6 +59,8 @@ pub use distance_parameters::DistanceParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; +pub use grayscale_conversion_parameters::GrayscaleConversionParameters; +pub use kind_controls::KindControls; pub use light_parameters::LightParameters; pub use linear_gradient_parameters::LinearGradientParameters; pub use micro_curvature_type::MicroCurvatureType; @@ -962,10 +966,12 @@ pub enum GeneratorKind { ThreeDLinearGradient, /// White at the UV islands' borders, fading towards their insides UvBorderDistance, + /// An image turned gray, tiled and rotated across the UV square + GrayscaleConversion, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 12] = [ + pub const ALL: [GeneratorKind; 13] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -978,6 +984,7 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance, GeneratorKind::ThreeDLinearGradient, GeneratorKind::UvBorderDistance, + GeneratorKind::GrayscaleConversion, ]; pub fn label(self) -> &'static str { match self { @@ -993,6 +1000,7 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance => "3D Distance", GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", GeneratorKind::UvBorderDistance => "UV Border Distance", + GeneratorKind::GrayscaleConversion => "Grayscale Conversion", } } @@ -1011,12 +1019,20 @@ impl GeneratorKind { GeneratorKind::ThreeDDistance => "ThreeDDistance", GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", GeneratorKind::UvBorderDistance => "UvBorderDistance", + GeneratorKind::GrayscaleConversion => "GrayscaleConversion", } } /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) pub fn in_picker(self) -> bool { - !matches!(self, GeneratorKind::ThinAreas | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) + !matches!( + self, + GeneratorKind::ThinAreas + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + ) } /// Whether the kind's result depends on its seed @@ -1034,7 +1050,7 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], - GeneratorKind::UvBorderDistance => &[], + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion => &[], } } @@ -1042,7 +1058,11 @@ impl GeneratorKind { pub fn has_no_earlier_model(self) -> bool { matches!( self, - GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion ) } @@ -1109,15 +1129,9 @@ pub struct Generator { /// The micro details of Curvature, Ambient Occlusion and the wear kinds (None: never touched, their defaults: off); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] pub micro: Option>, - /// The 3D Distance generator's controls (None on every other kind); boxed, so a generator effect stays small + /// The controls of 3D Distance, 3D Linear Gradient, UV Border Distance or Grayscale Conversion (None on the other kinds); boxed, so a generator effect stays small #[serde(default, skip_serializing_if = "Option::is_none")] - pub distance: Option>, - /// The 3D Linear Gradient generator's controls (None on every other kind); boxed, so a generator effect stays small - #[serde(default, skip_serializing_if = "Option::is_none")] - pub linear_gradient: Option>, - /// The UV Border Distance generator's controls (None on every other kind); boxed, so a generator effect stays small - #[serde(default, skip_serializing_if = "Option::is_none")] - pub border_distance: Option>, + pub controls: Option>, } impl Serialize for Generator { @@ -1161,17 +1175,47 @@ impl Generator { /// The 3D Distance controls the generator computes with: its own, else the defaults on a 3D Distance generator pub fn distance_controls(&self) -> Option { - self.distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDDistance).then(DistanceParameters::default)) + match self.kind_controls() { + Some(KindControls::Distance(distance)) => Some(distance), + _ => None, + } } /// The 3D Linear Gradient controls the generator computes with: its own, else the defaults on a 3D Linear Gradient generator pub fn linear_gradient_controls(&self) -> Option { - self.linear_gradient.as_deref().copied().or_else(|| (self.kind == GeneratorKind::ThreeDLinearGradient).then(LinearGradientParameters::default)) + match self.kind_controls() { + Some(KindControls::LinearGradient(gradient)) => Some(gradient), + _ => None, + } } /// The UV Border Distance controls the generator computes with: its own, else the defaults on a UV Border Distance generator pub fn border_distance_controls(&self) -> Option { - self.border_distance.as_deref().copied().or_else(|| (self.kind == GeneratorKind::UvBorderDistance).then(BorderDistanceParameters::default)) + match self.kind_controls() { + Some(KindControls::BorderDistance(border)) => Some(border), + _ => None, + } + } + + /// The Grayscale Conversion controls the generator computes with: its own, else the defaults on a Grayscale Conversion generator + pub fn grayscale_controls(&self) -> Option { + match self.kind_controls() { + Some(KindControls::Grayscale(grayscale)) => Some(grayscale), + _ => None, + } + } + + /// The controls of a kind with only its own controls: its saved ones when they are that kind's, else its defaults + pub fn kind_controls(&self) -> Option { + self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().or_else(|| KindControls::defaults(self.kind)) + } + + /// The Grayscale Conversion controls as saved, without a copy + fn grayscale_controls_ref(&self) -> Option<&GrayscaleConversionParameters> { + match self.controls.as_deref() { + Some(KindControls::Grayscale(grayscale)) if self.kind == GeneratorKind::GrayscaleConversion => Some(grayscale), + _ => None, + } } /// The mode and detail sizes the generator reads its curvature with: its own, the defaults on Curvature's section controls, else None @@ -1191,9 +1235,9 @@ impl Generator { self.texture.as_deref().filter(|texture| texture.in_use() && self.section_controls().is_some()) } - /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge and its micro details + /// Everything the generator reads instead of its mesh maps: its inputs, then its texture, its custom grunge, its micro details and its Grayscale Conversion image pub fn sources(&self) -> impl Iterator { - let micro = self.micro.iter().flat_map(|micro| micro.sources()); + let micro = self.micro.iter().flat_map(|micro| micro.sources()).chain(self.grayscale_controls_ref().and_then(|grayscale| grayscale.source.as_ref())); self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } @@ -1240,9 +1284,7 @@ impl Generator { texture: None, grunge: None, micro: None, - distance: (kind == GeneratorKind::ThreeDDistance).then(Box::default), - linear_gradient: (kind == GeneratorKind::ThreeDLinearGradient).then(Box::default), - border_distance: (kind == GeneratorKind::UvBorderDistance).then(Box::default), + controls: KindControls::defaults(kind).map(Box::new), } } diff --git a/crates/core/src/layer/grayscale_conversion_parameters.rs b/crates/core/src/layer/grayscale_conversion_parameters.rs new file mode 100644 index 00000000..1745be39 --- /dev/null +++ b/crates/core/src/layer/grayscale_conversion_parameters.rs @@ -0,0 +1,59 @@ +use serde::{Deserialize, Serialize}; + +use super::Source; +use super::generator_grayscale::GeneratorGrayscale; + +/// The Grayscale Conversion generator's controls: an image turned gray, tiled and rotated across the UV square +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GrayscaleConversionParameters { + /// How the image's color becomes gray + pub grayscale: GeneratorGrayscale, + /// Shifts the gray darker (below 0.5) or brighter (above 0.5) + pub balance: f32, + /// Narrows the gray around its middle (0..1; 1 a hard step) + pub contrast: f32, + /// How many times the image repeats across the UV square ([`GrayscaleConversionParameters::TILE_RANGE`]) + pub tile: f32, + /// Degrees the image turns about the UV square's centre (0..360) + pub rotation: f32, + /// Turn in quarter turns only, so the image keeps tiling seamlessly + pub safe_rotation: bool, + /// The image (None: an empty slot, read black) + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source: Option, +} + +impl GrayscaleConversionParameters { + pub const TILE_RANGE: std::ops::RangeInclusive = 1.0..=16.0; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> GrayscaleConversionParameters { + let defaults = GrayscaleConversionParameters::default(); + let within = |value: f32, default: f32, range: std::ops::RangeInclusive| { + if value.is_finite() { value.clamp(*range.start(), *range.end()) } else { default } + }; + GrayscaleConversionParameters { + balance: within(self.balance, defaults.balance, 0.0..=1.0), + contrast: within(self.contrast, defaults.contrast, 0.0..=1.0), + tile: within(self.tile, defaults.tile, GrayscaleConversionParameters::TILE_RANGE).round(), + rotation: within(self.rotation, defaults.rotation, 0.0..=360.0), + ..self + } + } +} + +impl Default for GrayscaleConversionParameters { + /// The reference app's defaults + fn default() -> GrayscaleConversionParameters { + GrayscaleConversionParameters { + grayscale: GeneratorGrayscale::Desaturation, + balance: 0.5, + contrast: 0.0, + tile: 1.0, + rotation: 0.0, + safe_rotation: true, + source: None, + } + } +} diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs new file mode 100644 index 00000000..faf0000c --- /dev/null +++ b/crates/core/src/layer/kind_controls.rs @@ -0,0 +1,44 @@ +use serde::{Deserialize, Serialize}; + +use super::{BorderDistanceParameters, DistanceParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; + +/// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum KindControls { + Distance(DistanceParameters), + LinearGradient(LinearGradientParameters), + BorderDistance(BorderDistanceParameters), + Grayscale(GrayscaleConversionParameters), +} + +impl KindControls { + /// The reference app's defaults for `kind`, or None for kinds with an earlier model or section, wear or light controls + pub fn defaults(kind: GeneratorKind) -> Option { + match kind { + GeneratorKind::ThreeDDistance => Some(KindControls::Distance(DistanceParameters::default())), + GeneratorKind::ThreeDLinearGradient => Some(KindControls::LinearGradient(LinearGradientParameters::default())), + GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), + GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::ThinAreas + | GeneratorKind::Curvature + | GeneratorKind::AmbientOcclusion + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::WorldSpaceNormals => None, + } + } + + /// The kind these controls belong to + pub fn kind(&self) -> GeneratorKind { + match self { + KindControls::Distance(_) => GeneratorKind::ThreeDDistance, + KindControls::LinearGradient(_) => GeneratorKind::ThreeDLinearGradient, + KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, + KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, + } + } +} diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 4fdfe6f5..8040b874 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -76,7 +76,8 @@ impl MicroDetails { | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index c0c64f41..153640f8 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -42,7 +42,8 @@ impl SectionParameters { | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 4f10a9c6..6acde341 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -61,7 +61,8 @@ impl WearParameters { | GeneratorKind::WorldSpaceNormals | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance => None, + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index fcbd7228..33b70ff6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 5bab2b11..120d3d42 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ -//! The controls of 3D Distance, 3D Linear Gradient and UV Border Distance that `effect.add.generator` and `effect.set` take +//! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{Generator, GeneratorKind}; +use texturecraft_core::{Generator, GeneratorKind, GeneratorGrayscale, KindControls}; use crate::Result; -use crate::commands::{bad, color_param, f32p}; +use crate::commands::{bad, boolp, color_param, f32p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -15,22 +15,26 @@ pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gr /// The UV Border Distance controls pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness", "borderBalance", "borderContrast"]; +/// The Grayscale Conversion controls (its image is the `image` input) +pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "grayscaleContrast", "grayscaleTile", "grayscaleRotation", "grayscaleSafeRotation"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; -/// The 3D Distance, 3D Linear Gradient and UV Border Distance controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls +/// The controls of the kinds with only their own controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { let kind = generator.kind; for (keys, owner) in [ (&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance), (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), + (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); } } - if !matches!(kind, GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance) { + if !kind.has_no_earlier_model() || kind == GeneratorKind::FiberGlassEdgeWear { return Ok(()); } if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) { @@ -39,6 +43,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::ThreeDLinearGradient { return linear_gradient_from(command, params, generator); } + if kind == GeneratorKind::GrayscaleConversion { + return grayscale_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -51,7 +58,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - *value = given; } } - generator.border_distance = Some(Box::new(border.clamped())); + generator.controls = Some(Box::new(KindControls::BorderDistance(border.clamped()))); return Ok(()); } @@ -66,7 +73,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - *value = given; } } - generator.distance = Some(Box::new(distance.clamped())); + generator.controls = Some(Box::new(KindControls::Distance(distance.clamped()))); Ok(()) } @@ -84,7 +91,31 @@ fn linear_gradient_from(command: &str, params: &Value, generator: &mut Generator *value = given; } } - generator.linear_gradient = Some(Box::new(gradient.clamped())); + generator.controls = Some(Box::new(KindControls::LinearGradient(gradient.clamped()))); + Ok(()) +} + +/// The Grayscale Conversion controls in `params` (the generator is one) +fn grayscale_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let mut grayscale = generator.grayscale_controls().unwrap_or_default(); + if let Some(value) = params.get("grayscaleType") { + let name = value.as_str().ok_or_else(|| bad(command, "`grayscaleType` must be a string"))?; + grayscale.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale type `{name}`")))?; + } + for (key, value) in [ + ("grayscaleBalance", &mut grayscale.balance), + ("grayscaleContrast", &mut grayscale.contrast), + ("grayscaleTile", &mut grayscale.tile), + ("grayscaleRotation", &mut grayscale.rotation), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(safe) = boolp(params, "grayscaleSafeRotation") { + grayscale.safe_rotation = safe; + } + generator.controls = Some(Box::new(KindControls::Grayscale(grayscale.clamped()))); Ok(()) } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 393e8a0b..3cb7a868 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,9 @@ use serde_json::{Value, json}; use texturecraft_core::{ - AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, - GeneratorKind, GeneratorGrayscale, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, Sampling, SectionParameters, Source, TextureBlend, WearParameters, + AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, + Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project, + Sampling, SectionParameters, Source, TextureBlend, WearParameters, }; use crate::anchored_micro_edit::AnchoredMicroEdit; @@ -56,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -101,7 +102,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight or microNormal + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight, microNormal or image + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -510,6 +511,9 @@ const TEXTURE_KEYS: [&str; 10] = [ "textureTriplanarContrast", ]; +/// The input name of Grayscale Conversion's image, beside the mesh map ids +const GRAYSCALE_IMAGE_INPUT: &str = "image"; + /// The input name of a generator's texture, beside the mesh map ids const TEXTURE_INPUT: &str = "texture"; @@ -794,18 +798,20 @@ enum GeneratorInput { Grunge, MicroHeight, MicroNormal, + Image, } /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; let Some(name) = params.get("input") else { return Ok(None) }; - let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight` or `microNormal`"))?; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight`, `microNormal` or `image`"))?; let input = match name { TEXTURE_INPUT => GeneratorInput::Texture, GRUNGE_INPUT => GeneratorInput::Grunge, MICRO_HEIGHT_INPUT => GeneratorInput::MicroHeight, MICRO_NORMAL_INPUT => GeneratorInput::MicroNormal, + GRAYSCALE_IMAGE_INPUT => GeneratorInput::Image, _ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?), }; @@ -1146,6 +1152,14 @@ fn set(session: &mut Session, params: &Value) -> Result { micro.height_source = source; } } + Some((GeneratorInput::Image, source)) => { + if generator.kind != GeneratorKind::GrayscaleConversion { + return Err(bad(CMD, "only Grayscale Conversion reads an `image` input")); + } + let mut grayscale = generator.grayscale_controls().unwrap_or_default(); + grayscale.source = source; + generator.controls = Some(Box::new(KindControls::Grayscale(grayscale))); + } Some((GeneratorInput::MicroNormal, source)) => { if let Some(micro) = generator.micro.as_mut() { micro.normal_source = source; diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index a1508452..7e7ab4ef 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,7 +1,9 @@ //! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point use serde_json::{Value, json}; -use texturecraft_engine::core::{BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, LayerId, LinearGradientParameters}; +use texturecraft_engine::core::{ + BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LinearGradientParameters, Source, +}; use texturecraft_engine::{Session, execute}; fn session() -> Session { @@ -46,7 +48,7 @@ fn three_d_distance_refuses_the_earlier_and_global_controls_and_others_refuse_it let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "distanceRadius": 0.5})).is_err()); - assert_eq!(generator(&session, curvature).distance, None); + assert_eq!(generator(&session, curvature).controls, None); } #[test] @@ -97,3 +99,24 @@ fn uv_border_distance_takes_its_controls_and_refuses_the_others() { let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "borderDistance": 0.5})).is_err()); } + +#[test] +fn grayscale_conversion_takes_its_controls_and_its_image() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 50, 50, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("color.png", bytes).unwrap(); + let effect = add(&mut session, json!({"generator": "Grayscale Conversion", "grayscaleType": "red", "grayscaleTile": 3.4, "grayscaleSafeRotation": false})); + + execute(&mut session, "effect.set", &json!({"effect": effect, "input": "image", "inputImage": name})).unwrap(); + let grayscale = generator(&session, effect).grayscale_controls().unwrap(); + assert_eq!((grayscale.grayscale, grayscale.tile, grayscale.safe_rotation), (GeneratorGrayscale::Red, 3.0, false), "the tile is a whole count"); + assert_eq!(grayscale.source, Some(Source::image(name.clone()))); + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read"); + + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "input": "image", "inputImage": name})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "grayscaleTile": 2})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 0139894f..f7335dc8 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -100,6 +100,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { (tr("A gradient between two points on the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]) } GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), + GeneratorKind::GrayscaleConversion => (tr("An image turned gray."), [tr("mask"), tr("generator"), tr("grayscale"), tr("image")]), }; // Wrapped rows: a long line must not widen the panel past its edge From c2cad52627d920b66e016e0d33b655d30662934b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:49:36 +0000 Subject: [PATCH 18/54] Generators: review fixes for Micro Details and the new kinds Saved values are brought into range when read (a hand-edited project's infinite smoothness or huge AO radius no longer reaches the blurs and occlusion search), with tests. The UV Border Distance gradient is built once before tiles composite, not by every tile at once; its cache key adds the g-buffer's address and a denser coverage fingerprint, and its Smoothness blur follows each UV tile's own resolution. The micro and border caches keep at most 256 MB besides the newest entry. A generator's own controls are resolved once per plan instead of per texel; project.inspect shows them. Docs say which space the 3D kinds' points live in (the bounds scaled evenly, like the reference's position map) and that an empty micro slot reads a flat height. --- crates/compose/src/eval.rs | 51 ++++++++++++------- crates/compose/src/generator_maps.rs | 19 ++++--- crates/compose/src/micro_details.rs | 34 +++++++++++-- crates/compose/src/three_d_distance.rs | 6 +-- crates/compose/src/uv_border_distance.rs | 48 +++++++++++++---- .../compose/tests/generator_micro_details.rs | 10 ++++ .../tests/generator_uv_border_distance.rs | 10 ++++ crates/core/src/layer.rs | 7 +-- crates/core/src/layer/distance_parameters.rs | 2 +- crates/core/src/layer/kind_controls.rs | 10 ++++ .../src/layer/linear_gradient_parameters.rs | 4 +- crates/core/src/layer/micro_details.rs | 2 +- crates/engine/src/inspect.rs | 3 ++ 13 files changed, 158 insertions(+), 48 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 2d725331..746c03af 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,7 +12,12 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, + MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, + SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, + blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; @@ -2475,8 +2480,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } - if let Some(distance) = generator.distance_controls() { - let position = self.uniform_position_input(generator); - return three_d_distance::distance_value(&distance, position); - } - if let Some(grayscale) = generator.grayscale_controls() { - return self.grayscale_conversion(&grayscale); - } - if let Some(border) = generator.border_distance_controls() { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); - return uv_border_distance::border_value(&border, gradient); - } - if let Some(gradient) = generator.linear_gradient_controls() { - let position = self.uniform_position_input(generator); - return three_d_distance::linear_gradient_value(&gradient, position); + // The kinds with only their own controls: resolved once per plan, not per texel + let resolved; + let controls = match maps.controls.as_deref() { + Some(controls) => Some(controls), + None => { + resolved = generator.kind_controls(); + resolved.as_ref() + } + }; + match controls { + Some(KindControls::Distance(distance)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::distance_value(distance, position); + } + Some(KindControls::LinearGradient(gradient)) => { + let position = self.uniform_position_input(generator); + return three_d_distance::linear_gradient_value(gradient, position); + } + Some(KindControls::BorderDistance(border)) => { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); + return uv_border_distance::border_value(border, gradient); + } + Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + None => {} } let coords = self.coords(); diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 613e7e3a..a0498c0c 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use texturecraft_core::{BakedMap, Generator, MicroDetails}; +use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; use crate::eval::Inputs; @@ -20,19 +20,26 @@ pub(crate) struct GeneratorMaps { pub micro_occlusion: Option>, /// The UV Border Distance gradient at every working texel pub border_gradient: Option>>, + /// The controls of a kind with only its own controls, brought into range + pub controls: Option>, } impl GeneratorMaps { /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { - let micro = generator.micro_in_use(); - let micro_curvature = micro.filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); - let micro_occlusion = micro.filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); + let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); + let micro_curvature = + micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); + let micro_occlusion = micro.as_ref().filter(|_| MicroDetails::has_occlusion(generator.kind)).and_then(|micro| micro_occlusion(inp, micro)); let sizes = match µ_curvature { Some(micro) => CurvatureSizes::of_map(inp, µ.curvature, needed), None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; - let border_gradient = generator.border_distance_controls().map(|border| border_gradient(inp, &border)); - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient } + let controls = generator.kind_controls(); + let border_gradient = match &controls { + Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), + _ => None, + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details.rs index d81fabf9..35132998 100644 --- a/crates/compose/src/micro_details.rs +++ b/crates/compose/src/micro_details.rs @@ -41,8 +41,26 @@ const OCCLUSION_DEPTH_POWER: f32 = 1.0654; /// How dark a fully occluding horizon makes the occlusion (fitted) const OCCLUSION_STRENGTH: f32 = 0.3232; -/// Cached micro maps; each entry is small next to the curvature sizes it feeds +/// Most micro maps cached, and the bytes they may hold (the newest is kept whatever its size), like the curvature sizes they feed const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// What a cached map holds, to keep the cache within [`CACHE_BYTES`] +trait CachedBytes { + fn bytes(&self) -> usize; +} + +impl CachedBytes for LayoutMap { + fn bytes(&self) -> usize { + self.data.len().saturating_mul(size_of::()) + } +} + +impl CachedBytes for MicroCurvature { + fn bytes(&self) -> usize { + self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) + } +} /// A map in a mesh map's layout: `size` texels, each UV tile one block pub struct LayoutMap { @@ -288,7 +306,7 @@ struct Cache { entries: Mutex)>>, } -impl Cache { +impl Cache { const fn new() -> Cache { Cache { entries: Mutex::new(Vec::new()) } } @@ -313,7 +331,17 @@ impl Cache { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); entries.retain(|(cached, _)| *cached != key); entries.push((key, built.clone())); - let excess = entries.len().saturating_sub(CACHE_ENTRIES); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.bytes()); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); entries.drain(..excess); built } diff --git a/crates/compose/src/three_d_distance.rs b/crates/compose/src/three_d_distance.rs index d62524d4..02812e84 100644 --- a/crates/compose/src/three_d_distance.rs +++ b/crates/compose/src/three_d_distance.rs @@ -12,13 +12,13 @@ pub(crate) fn distance_value(distance: &DistanceParameters, position: Vec3) -> f histogram_scan(gradient, distance.offset, distance.contrast) } -/// Shortest start-to-end span the gradient divides by -const MIN_GRADIENT_LENGTH: f32 = 1e-6; +/// Smallest squared start-to-end span the gradient divides by +const MIN_GRADIENT_LENGTH_SQUARED: f32 = 1e-12; /// The value at `position`: how far along from the start to the end it lies (0 at the start, 1 at the end), balanced and contrasted like a generator's global controls pub(crate) fn linear_gradient_value(gradient: &LinearGradientParameters, position: Vec3) -> f32 { let (start, end) = (Vec3::from(gradient.start), Vec3::from(gradient.end)); let span = end - start; - let along = if span.length_squared() > MIN_GRADIENT_LENGTH { (position - start).dot(span) / span.length_squared() } else { 0.0 }; + let along = if span.length_squared() > MIN_GRADIENT_LENGTH_SQUARED { (position - start).dot(span) / span.length_squared() } else { 0.0 }; GeneratorGlobal { balance: gradient.balance, contrast: gradient.contrast, ..GeneratorGlobal::default() }.apply(along.clamp(0.0, 1.0)) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index 50033fcd..a18535a4 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -16,15 +16,18 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; /// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at const REFERENCE_TILE_TEXELS: f32 = 2048.0; -/// Cached gradients; one per layout and setting a stack shows at a time +/// Most gradients cached, and the bytes they may hold (the newest is kept whatever its size) const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; -/// Texels between the samples a layout's fingerprint reads -const FINGERPRINT_STRIDE: usize = 997; +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; /// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits #[derive(Clone, PartialEq)] struct Key { + /// The g-buffer's triangle data by address, beside its fingerprint + layout: usize, size: (u32, u32), fingerprint: u64, block: (u32, u32), @@ -42,7 +45,14 @@ pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) - let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); - let key = Key { size, fingerprint, block, scales: inp.block_scales.clone(), settings: [border.distance.to_bits(), border.smoothness.to_bits()] }; + let key = Key { + layout: gbuf.tri.as_ptr() as usize, + size, + fingerprint, + block, + scales: inp.block_scales.clone(), + settings: [border.distance.to_bits(), border.smoothness.to_bits()], + }; let cached = { let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -57,7 +67,17 @@ pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); cache.retain(|(cached, _)| *cached != key); cache.push((key, gradient.clone())); - let excess = cache.len().saturating_sub(CACHE_ENTRIES); + let mut bytes = 0usize; + let keep = cache + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = cache.len().saturating_sub(keep); cache.drain(..excess); gradient } @@ -89,10 +109,12 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> .collect(); // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black - let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * block.0 as f32 / REFERENCE_TILE_TEXELS; - let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize; - if radius > 0 { - blur_blocks(&mut gradient, (width, height), block, radius); + if border.smoothness > 0.0 { + let radius_at = |tile_texels: f32| { + let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS; + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize + }; + blur_blocks(&mut gradient, (width, height), block, |left, top| radius_at(block.0 as f32 * inp.block_scales.at(left, top))); for (value, texel) in gradient.iter_mut().zip(0..) { if !gbuf.covered(texel) { *value = 0.0; @@ -177,8 +199,8 @@ fn squared_distance_line(line: &mut [f32]) { } } -/// `data` blurred one UV tile block at a time, reading black past each block's edges -fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius: usize) { +/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges +fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { for top in (0..height).step_by(block.1 as usize) { for left in (0..width).step_by(block.0 as usize) { let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); @@ -187,6 +209,10 @@ fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), .flat_map(|row| (0..columns).map(move |column| (column, row))) .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) .collect(); + let radius = radius_at(left, top); + if radius == 0 { + continue; + } blur(&mut values, columns, rows, radius); for (offset, value) in values.into_iter().enumerate() { if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { diff --git a/crates/compose/tests/generator_micro_details.rs b/crates/compose/tests/generator_micro_details.rs index 62254619..2b8001a6 100644 --- a/crates/compose/tests/generator_micro_details.rs +++ b/crates/compose/tests/generator_micro_details.rs @@ -209,3 +209,13 @@ fn a_micro_height_bump_moves_the_wear_kinds_around_it() { assert!(changed > 0, "{kind:?}"); } } + +#[test] +fn saved_micro_values_out_of_range_render_as_their_nearest_valid_ones() { + let mut fixture = fixture(); + let hostile = + mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| (micro.ao_radius, micro.ao_depth) = (1e30, f32::NAN))); + let valid = mask(&mut fixture, with_micro(GeneratorKind::AmbientOcclusion, Some("bump"), None, |micro| micro.ao_radius = 1.0)); + + assert_eq!(hostile, valid); +} diff --git a/crates/compose/tests/generator_uv_border_distance.rs b/crates/compose/tests/generator_uv_border_distance.rs index 4457fb8c..ec14c22a 100644 --- a/crates/compose/tests/generator_uv_border_distance.rs +++ b/crates/compose/tests/generator_uv_border_distance.rs @@ -78,3 +78,13 @@ fn smoothness_darkens_the_edge_with_the_space_around_the_island() { assert!(smooth[0] < sharp[0] - 0.2, "{} vs {}", smooth[0], sharp[0]); } + +#[test] +fn saved_values_out_of_range_render_as_their_nearest_valid_ones() { + let mut fixture = fixture(); + let hostile = + row(&mut fixture, BorderDistanceParameters { distance: f32::NAN, smoothness: f32::INFINITY, contrast: 7.0, ..BorderDistanceParameters::default() }); + let valid = row(&mut fixture, BorderDistanceParameters { contrast: 1.0, ..BorderDistanceParameters::default() }); + + assert_eq!(hostile, valid, "non-finite values read their defaults, others their nearest valid value"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index f5c23e39..fd0a9c1a 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1205,9 +1205,10 @@ impl Generator { } } - /// The controls of a kind with only its own controls: its saved ones when they are that kind's, else its defaults + /// The controls of a kind with only its own controls: its saved ones (brought into range) when they are that kind's, else its defaults pub fn kind_controls(&self) -> Option { - self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().or_else(|| KindControls::defaults(self.kind)) + let saved = self.controls.as_deref().filter(|controls| controls.kind() == self.kind).cloned().map(KindControls::clamped); + saved.or_else(|| KindControls::defaults(self.kind)) } /// The Grayscale Conversion controls as saved, without a copy @@ -1241,7 +1242,7 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } - /// The micro details the generator computes with: switched on with an image to read (an anchor's micro detail saved on the earlier model reads too) + /// The micro details as saved, when the generator computes with them: with a slot switched on, also on the earlier model where an anchor's micro detail saved before Micro Details reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) } diff --git a/crates/core/src/layer/distance_parameters.rs b/crates/core/src/layer/distance_parameters.rs index a392b4a0..15a38371 100644 --- a/crates/core/src/layer/distance_parameters.rs +++ b/crates/core/src/layer/distance_parameters.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DistanceParameters { - /// The point, 0..1 across the mesh's bounds on each axis (Position X, Y and Z) + /// The point (Position X, Y and Z) in the mesh's bounds scaled evenly, as the reference's position map is: the longest side spans 0..1, the others are centred on 0.5 pub point: [f32; 3], /// How far the gradient reaches, in units of the bounds' longest side ([`DistanceParameters::RADIUS_RANGE`]) pub radius: f32, diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index faf0000c..abfd61b5 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -32,6 +32,16 @@ impl KindControls { } } + /// Every value brought into its range, non-finite ones to the defaults (saved files are not trusted) + pub fn clamped(self) -> KindControls { + match self { + KindControls::Distance(distance) => KindControls::Distance(distance.clamped()), + KindControls::LinearGradient(gradient) => KindControls::LinearGradient(gradient.clamped()), + KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), + KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), + } + } + /// The kind these controls belong to pub fn kind(&self) -> GeneratorKind { match self { diff --git a/crates/core/src/layer/linear_gradient_parameters.rs b/crates/core/src/layer/linear_gradient_parameters.rs index 2526da80..1c100065 100644 --- a/crates/core/src/layer/linear_gradient_parameters.rs +++ b/crates/core/src/layer/linear_gradient_parameters.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LinearGradientParameters { - /// Where the gradient is black, 0..1 across the mesh's bounds on each axis + /// Where the gradient is black, in the mesh's bounds scaled evenly like 3D Distance's point (the longest side spans 0..1, the others are centred on 0.5) pub start: [f32; 3], /// Where the gradient is white pub end: [f32; 3], @@ -29,7 +29,7 @@ impl LinearGradientParameters { } impl Default for LinearGradientParameters { - /// The reference app's defaults: bottom to top through the bounds' centre + /// The reference app's defaults: from y 0 to y 1 through the bounds' centre, which spans the mesh when its longest side is vertical fn default() -> LinearGradientParameters { LinearGradientParameters { start: [0.5, 0.0, 0.5], end: [0.5, 1.0, 0.5], balance: 0.5, contrast: 0.0 } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 8040b874..dc2c5f4b 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -101,7 +101,7 @@ impl MicroDetails { if kind == GeneratorKind::Curvature { 0.0..=5.0 } else { 0.0..=1.0 } } - /// Whether the micro details change a generator of `kind`: switched on with an image to read + /// Whether the micro details change a generator of `kind`: switched on with a slot to read (an empty slot reads a flat black height, which some curvature types still lift) pub fn in_use(&self, kind: GeneratorKind) -> bool { (self.enabled || !MicroDetails::has_switch(kind)) && (self.height || self.normal) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index c4ac692e..bc0efe3c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -162,6 +162,9 @@ fn generator_json(generator: &Generator) -> Value { if let Some(micro) = &generator.micro { out["micro"] = json!(micro); } + if let Some(controls) = &generator.controls { + out["controls"] = json!(controls); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); From f3c8103579e728d24a38c32320e8db43cc3ba743 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:10:31 +0000 Subject: [PATCH 19/54] Generators: Dripping Rust, rust grown from the occlusion and run down in drips A new kind with the reference's controls: Rust Spreading, Rust Contrast, Spreading Smoothness, Drips Intensity, Drips Smoothness, Drips Samples Amount, Position axis, Seed and Invert. Fitted to the reference: the rust rises with the occlusion, is blurred by the spreading smoothness, and each texel then takes the most rust found uphill along the chosen axis of the mesh's bounds over the samples, fading with distance (93 texels at 2K at intensity 1), blurred by the drips smoothness and scanned by spreading and contrast (spreading 0 and 1 are exactly black and white, as in the reference). The reference's grunge is not reproduced: the Dirt grunge breaks the rust up at the measured strength instead, so the look is close in level but not texel for texel (correlation 0.55 on the test gun, versus about 0.75 for the fitted model with its noise averaged out). The field is built once per layout, occlusion map and setting, with the UV Border Distance gradient's cache and blur now shared in one module. Commands only; no replaceable inputs yet (it reads the baked occlusion and the mesh's bounds whole). --- crates/compose/src/dripping_rust.rs | 162 ++++++++++++++++++ crates/compose/src/eval.rs | 43 ++++- crates/compose/src/generator_maps.rs | 9 +- crates/compose/src/lib.rs | 2 + crates/compose/src/uv_border_distance.rs | 94 +--------- crates/compose/src/working_field.rs | 127 ++++++++++++++ .../compose/tests/generator_dripping_rust.rs | 107 ++++++++++++ crates/core/src/layer.rs | 16 +- .../src/layer/dripping_rust_parameters.rs | 55 ++++++ crates/core/src/layer/kind_controls.rs | 6 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 42 ++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 20 ++- crates/ui-egui/src/generator_panel.rs | 3 + 18 files changed, 592 insertions(+), 107 deletions(-) create mode 100644 crates/compose/src/dripping_rust.rs create mode 100644 crates/compose/src/working_field.rs create mode 100644 crates/compose/tests/generator_dripping_rust.rs create mode 100644 crates/core/src/layer/dripping_rust_parameters.rs diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs new file mode 100644 index 00000000..ef3e308c --- /dev/null +++ b/crates/compose/src/dripping_rust.rs @@ -0,0 +1,162 @@ +//! The Dripping Rust generator: rust grown from the occlusion, broken up by grunge, then run down the mesh in drips; built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearParameters}; +use texturecraft_geom::glam::Vec3; + +use crate::eval::{Inputs, texel_coords}; +use crate::histogram_scan::histogram_scan; +use crate::wear; +use crate::working_field::{FieldCache, blur_blocks}; + +/// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) +const RUST_FLOOR: f32 = 0.315; +const RUST_GAIN: f32 = 3.19; +const RUST_OCCLUSION: f32 = 0.849; +const RUST_POWER: f32 = 2.38; + +/// How much grunge breaks the rust up: the spread of the reference's noise (measured); the pattern itself is inferred +const GRUNGE_SPREAD: f32 = 0.19; + +/// Blur sizes at Spreading Smoothness 1 and Drips Smoothness 1, as gaussian sigmas in texels of a 2K UV tile (fitted) +const SPREADING_SIGMA_2K: f32 = 47.0; +const DRIPS_SIGMA_2K: f32 = 11.5; + +/// How far a drip runs at Drips Intensity 1, in texels of a 2K UV tile, and how it fades along its length: `1 − DRIP_FADE · along^DRIP_FADE_POWER` (fitted) +const DRIP_LENGTH_2K: f32 = 90.86; +const DRIP_FADE: f32 = 0.898; +const DRIP_FADE_POWER: f32 = 0.671; + +/// The UV tile resolution the sizes above are measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// Coverage below which a blurred texel has nothing to average +const MIN_COVERAGE: f32 = 1e-3; + +static CACHE: FieldCache = FieldCache::new(); + +/// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) +pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) -> Arc> { + let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion); + let settings = vec![ + rust.spreading_smoothness.to_bits(), + rust.drips_intensity.to_bits(), + rust.drips_smoothness.to_bits(), + rust.drips_samples, + u32::from(rust.axis), + seed, + ]; + CACHE.get_or_build(inp, &occlusion.into_iter().collect::>(), settings, |block| build(inp, rust, seed, block)) +} + +/// The value at a working texel: the rust spread and contrasted +pub(crate) fn rust_value(rust: &DrippingRustParameters, field: f32) -> f32 { + histogram_scan(field, rust.spreading, rust.contrast) +} + +fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u32)) -> Vec { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let cover: Vec = (0..width * height).map(|texel| if gbuf.covered(texel as usize) { 1.0 } else { 0.0 }).collect(); + let tile_texels = |x: u32, y: u32| block.0 as f32 * inp.block_scales.at(x, y); + + // The rust from the occlusion, broken up by the Dirt generator's grunge + let grunge = WearParameters::defaults(GeneratorKind::Dirt); + let rust_at = |texel: u32| { + let (x, y) = (texel % width, texel / width); + let occlusion = inp.baked.sample_working(BakedMap::AmbientOcclusion, x, y, (width, height), &inp.block_scales).map_or(1.0, |value| value[0]); + let base = RUST_FLOOR + RUST_GAIN * (RUST_OCCLUSION - occlusion).max(0.0).powf(RUST_POWER); + let noise = grunge.map_or(0.0, |grunge| wear::grunge(GeneratorKind::Dirt, &grunge, seed, &texel_coords(inp, x, y))); + base + GRUNGE_SPREAD * noise + }; + let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); + + let sigma_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let mut field = drips(inp, rust, &field, (width, height), &tile_texels); + blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); + field +} + +/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) +fn box_radius(sigma: f32) -> usize { + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + +/// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in +fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { + let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); + let mut weights = cover.to_vec(); + blur_blocks(&mut sums, size, block, radius_at); + blur_blocks(&mut weights, size, block, radius_at); + values.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).zip(cover.par_iter()).for_each(|((value, (sum, weight)), covered)| { + if *covered > 0.0 && *weight > MIN_COVERAGE { + *value = sum / weight; + } + }); +} + +/// Each texel takes the most rust found uphill along the drip axis, fading with how far up it lies +fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, height): (u32, u32), tile_texels: &(impl Fn(u32, u32) -> f32 + Sync)) -> Vec { + let gbuf = inp.gbuf; + if rust.drips_samples == 0 || rust.drips_intensity <= 0.0 { + return field.to_vec(); + } + + // The drip axis across the mesh's bounds at every covered texel + let (low, high) = inp.bounds; + let extent = (high - low).max(Vec3::splat(f32::EPSILON)); + let axis = usize::from(rust.axis.min(2)); + let along_axis: Vec> = (0..width * height) + .into_par_iter() + .map(|texel| gbuf.surface(inp.mesh, texel as usize).map(|surface| ((surface.pos - low) / extent).to_array()[axis])) + .collect(); + let axis_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) { + return None; + } + along_axis.get((y * i64::from(width) + x) as usize).copied().flatten() + }; + let field_at = |x: i64, y: i64| -> Option { + if x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height) || !gbuf.covered((y * i64::from(width) + x) as usize) { + return None; + } + field.get((y * i64::from(width) + x) as usize).copied() + }; + // Central differences, one-sided at an island's border + let slope = |before: Option, here: f32, after: Option| match (before, after) { + (Some(before), Some(after)) => (after - before) * 0.5, + (None, Some(after)) => after - here, + (Some(before), None) => here - before, + (None, None) => 0.0, + }; + + let samples = rust.drips_samples; + (0..width * height) + .into_par_iter() + .map(|texel| { + let (x, y) = (i64::from(texel % width), i64::from(texel / width)); + let here = field.get(texel as usize).copied().unwrap_or(0.0); + let Some(axis_here) = axis_at(x, y) else { return here }; + let uphill = (slope(axis_at(x - 1, y), axis_here, axis_at(x + 1, y)), slope(axis_at(x, y - 1), axis_here, axis_at(x, y + 1))); + let length = (uphill.0 * uphill.0 + uphill.1 * uphill.1).sqrt(); + if length <= f32::EPSILON { + return here; + } + + let reach = rust.drips_intensity * DRIP_LENGTH_2K * tile_texels(texel % width, texel / width) / REFERENCE_TILE_TEXELS; + (1..=samples).fold(here, |most, step| { + let along = step as f32 / samples as f32; + let distance = reach * along; + let (sample_x, sample_y) = (x as f32 + distance * uphill.0 / length, y as f32 + distance * uphill.1 / length); + match field_at(sample_x.round() as i64, sample_y.round() as i64) { + Some(value) => most.max(value * (1.0 - DRIP_FADE * along.powf(DRIP_FADE_POWER))), + None => most, + } + }) + }) + .collect() +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 746c03af..52625777 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -26,6 +26,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::{CurvatureSizes, LEVEL_RADII}; +use crate::dripping_rust; use crate::effect_histogram::EffectHistogram; use crate::environment_sh::EnvironmentSh; use crate::fill_copies::FillCopies; @@ -1950,6 +1951,26 @@ fn filter_region( Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result, anchor_stages: Vec::new() }) } +/// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) +pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { + let g = inp.gbuf; + let mut c = match g.surface(inp.mesh, (y * g.width + x) as usize) { + Some(s) => { + let (center, radius) = mesh_frame(inp.bounds); + Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm } + } + None => Coords { uv: Vec2::new((x as f32 + 0.5) / g.width as f32, (y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + }; + + // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) + if let Ok(set) = inp.project.texture_set(inp.ts) + && let Some(grid) = set.tile_grid() + { + c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); + } + c +} + /// What a generator's texture or custom grunge reads with nothing in its slot const EMPTY_IMAGE_SLOT: Source = Source::Uniform([0.0; 3]); @@ -2481,7 +2502,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { return uv_border_distance::border_value(border, gradient); } Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), + Some(KindControls::DrippingRust(rust)) => { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + let field = maps.rust_field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0); + return dripping_rust::rust_value(rust, field); + } None => {} } @@ -3458,9 +3485,14 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, // World Space Normals and 3D Distance always compute with their own controls: these arms only keep the match whole (GeneratorKind::WorldSpaceNormals, _) => coords.nrm.y * 0.5 + 0.5, - (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion, _) => { - 0.0 - } + ( + GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust, + _, + ) => 0.0, }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); @@ -3509,7 +3541,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => 0.0, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index a0498c0c..acced92c 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use texturecraft_core::{BakedMap, Generator, KindControls, MicroDetails}; use crate::curvature_sizes::CurvatureSizes; +use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; @@ -20,6 +21,8 @@ pub(crate) struct GeneratorMaps { pub micro_occlusion: Option>, /// The UV Border Distance gradient at every working texel pub border_gradient: Option>>, + /// The Dripping Rust field at every working texel + pub rust_field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, } @@ -40,6 +43,10 @@ impl GeneratorMaps { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), _ => None, }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, controls: controls.map(Arc::new) } + let rust_field = match &controls { + Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), + _ => None, + }; + GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, rust_field, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 24c3f9e5..09ae63d8 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -14,6 +14,7 @@ mod curvature_size_level; pub mod curvature_sizes; pub mod display; mod distance_envelope; +mod dripping_rust; mod effect_histogram; pub mod environment_sh; pub mod environment_sky; @@ -59,6 +60,7 @@ mod warp_texel; mod wear; mod wear_inputs; mod wear_scan; +mod working_field; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index a18535a4..0fa3afd0 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -1,11 +1,12 @@ //! The UV Border Distance generator: how far each texel lies inside its UV island, as a gradient built once per UV layout and settings -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{BlockScales, BorderDistanceParameters, GeneratorGlobal}; +use texturecraft_core::{BorderDistanceParameters, GeneratorGlobal}; -use crate::eval::{Inputs, blur}; +use crate::eval::Inputs; +use crate::working_field::{FieldCache, blur_blocks}; /// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) const REACH_PER_DISTANCE: f32 = 0.4936; @@ -16,70 +17,11 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; /// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at const REFERENCE_TILE_TEXELS: f32 = 2048.0; -/// Most gradients cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; -const CACHE_BYTES: usize = 256 << 20; - -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; - -/// What a gradient was built from: the working layout (size, coverage fingerprint, UV tile block, tile scales) and the settings' bits -#[derive(Clone, PartialEq)] -struct Key { - /// The g-buffer's triangle data by address, beside its fingerprint - layout: usize, - size: (u32, u32), - fingerprint: u64, - block: (u32, u32), - scales: BlockScales, - settings: [u32; 2], -} - -static CACHE: Mutex>)>> = Mutex::new(Vec::new()); +static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { - let gbuf = inp.gbuf; - let size = (gbuf.width, gbuf.height); - let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); - let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); - let block = (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))); - let fingerprint = gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)); - let key = Key { - layout: gbuf.tri.as_ptr() as usize, - size, - fingerprint, - block, - scales: inp.block_scales.clone(), - settings: [border.distance.to_bits(), border.smoothness.to_bits()], - }; - - let cached = { - let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.iter().find(|(cached, _)| *cached == key).map(|(_, gradient)| gradient.clone()) - }; - if let Some(gradient) = cached { - return gradient; - } - - // Built without the cache locked: the build runs parallel work - let gradient = Arc::new(build(inp, border, block)); - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(cached, _)| *cached != key); - cache.push((key, gradient.clone())); - let mut bytes = 0usize; - let keep = cache - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = cache.len().saturating_sub(keep); - cache.drain(..excess); - gradient + CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) } /// The value at a working texel: the gradient balanced, contrasted and inverted @@ -199,30 +141,6 @@ fn squared_distance_line(line: &mut [f32]) { } } -/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges -fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { - for top in (0..height).step_by(block.1 as usize) { - for left in (0..width).step_by(block.0 as usize) { - let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); - let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; - let mut values: Vec = (0..rows) - .flat_map(|row| (0..columns).map(move |column| (column, row))) - .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) - .collect(); - let radius = radius_at(left, top); - if radius == 0 { - continue; - } - blur(&mut values, columns, rows, radius); - for (offset, value) in values.into_iter().enumerate() { - if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { - *target = value; - } - } - } - } -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs new file mode 100644 index 00000000..55c3763b --- /dev/null +++ b/crates/compose/src/working_field.rs @@ -0,0 +1,127 @@ +//! Whole-map fields some generators precompute at the working resolution (UV Border Distance, Dripping Rust), built once per layout, mesh map and settings + +use std::sync::{Arc, Mutex, Weak}; + +use texturecraft_core::BlockScales; + +use crate::eval::{Inputs, blur}; + +/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) +const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; + +/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh, the mesh maps it reads and its settings' bits +#[derive(Clone)] +struct Key { + layout: usize, + size: (u32, u32), + fingerprint: u64, + block: (u32, u32), + scales: BlockScales, + mesh: (usize, usize), + maps: Vec>>, + settings: Vec, +} + +impl PartialEq for Key { + fn eq(&self, other: &Key) -> bool { + let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + same_maps + && self.layout == other.layout + && self.size == other.size + && self.fingerprint == other.fingerprint + && self.block == other.block + && self.scales == other.scales + && self.mesh == other.mesh + && self.settings == other.settings + } +} + +/// Built fields by what they were built from, most recently used last +pub(crate) struct FieldCache { + entries: Mutex>)>>, +} + +impl FieldCache { + pub(crate) const fn new() -> FieldCache { + FieldCache { entries: Mutex::new(Vec::new()) } + } + + /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + let gbuf = inp.gbuf; + let block = working_block(inp); + let key = Key { + layout: gbuf.tri.as_ptr() as usize, + size: (gbuf.width, gbuf.height), + fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + block, + scales: inp.block_scales.clone(), + mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), + maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + settings, + }; + + let cached = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); + entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + }; + if let Some(field) = cached { + return field; + } + + let field = Arc::new(build(block)); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, field.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + field + } +} + +/// The size of one UV tile's block in `inp`'s working atlas +pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { + let size = (inp.gbuf.width, inp.gbuf.height); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or(size, |grid| (size.0 / grid.cols.max(1), size.1 / grid.rows.max(1))); + (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) +} + +/// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges +pub(crate) fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { + for top in (0..height).step_by(block.1 as usize) { + for left in (0..width).step_by(block.0 as usize) { + let (columns, rows) = (block.0.min(width - left) as usize, block.1.min(height - top) as usize); + let index = |column: usize, row: usize| (top as usize + row) * width as usize + left as usize + column; + let mut values: Vec = (0..rows) + .flat_map(|row| (0..columns).map(move |column| (column, row))) + .map(|(column, row)| data.get(index(column, row)).copied().unwrap_or(0.0)) + .collect(); + let radius = radius_at(left, top); + if radius == 0 { + continue; + } + blur(&mut values, columns, rows, radius); + for (offset, value) in values.into_iter().enumerate() { + if let Some(target) = data.get_mut(index(offset % columns, offset / columns)) { + *target = value; + } + } + } + } +} diff --git a/crates/compose/tests/generator_dripping_rust.rs b/crates/compose/tests/generator_dripping_rust.rs new file mode 100644 index 00000000..b94c323d --- /dev/null +++ b/crates/compose/tests/generator_dripping_rust.rs @@ -0,0 +1,107 @@ +//! The Dripping Rust generator on a sphere with an occluded band: rust grows in the occlusion, spreads from none to everywhere, and drips run down from it + +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + BakedMap, Channel, DrippingRustParameters, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, + MaskBackground, Project, Source, TextureSet, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 128; + +/// The occluded band's heights on the unit sphere, and its occlusion +const BAND: std::ops::Range = 0.2..0.5; +const BAND_OCCLUSION: f32 = 0.2; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, + baked: BakedMaps, +} + +/// A unit sphere with a white fill layer, occluded only in [`BAND`] +fn fixture() -> Fixture { + let mesh = primitives::sphere(1.0, 48, 24); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:sphere"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let occlusion: Vec = (0..RES * RES) + .map(|texel| gbuf.surface(&mesh, texel as usize).map_or(1.0, |surface| if BAND.contains(&surface.pos.y) { BAND_OCCLUSION } else { 1.0 })) + .collect(); + let baked = BakedMaps { resolution: RES, maps: [(BakedMap::AmbientOcclusion, Arc::new(occlusion))].into() }; + Fixture { project, mesh, gbuf, layer, baked } +} + +/// Every covered texel and its height +fn covered(fixture: &Fixture) -> Vec<((u32, u32), f32)> { + (0..RES * RES).filter_map(|index| fixture.gbuf.surface(&fixture.mesh, index as usize).map(|surface| ((index % RES, index / RES), surface.pos.y))).collect() +} + +fn mask(fixture: &mut Fixture, rust: DrippingRustParameters, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::DrippingRust(rust))), ..Generator::new(GeneratorKind::DrippingRust) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// The mean of `values` over the texels whose height lies in `heights` +fn mean_within(texels: &[((u32, u32), f32)], values: &[f32], heights: std::ops::Range) -> f32 { + let picked: Vec = texels.iter().zip(values).filter(|((_, height), _)| heights.contains(height)).map(|(_, value)| *value).collect(); + picked.iter().sum::() / picked.len().max(1) as f32 +} + +#[test] +fn spreading_runs_from_none_to_everywhere() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let none = mask(&mut fixture, DrippingRustParameters { spreading: 0.0, ..DrippingRustParameters::default() }, &at); + let all = mask(&mut fixture, DrippingRustParameters { spreading: 1.0, ..DrippingRustParameters::default() }, &at); + assert!(none.iter().all(|value| *value == 0.0)); + assert!(all.iter().all(|value| *value == 1.0)); +} + +#[test] +fn the_occluded_band_rusts_most() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..DrippingRustParameters::default() }, &at); + assert!(mean_within(&texels, &values, BAND) > mean_within(&texels, &values, -1.0..-0.2) + 0.3); +} + +#[test] +fn drips_only_add_rust_and_run_down_from_the_band() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + let rust = DrippingRustParameters { contrast: 0.0, drips_smoothness: 0.0, ..DrippingRustParameters::default() }; + + let dry = mask(&mut fixture, DrippingRustParameters { drips_intensity: 0.0, ..rust }, &at); + let dripping = mask(&mut fixture, DrippingRustParameters { drips_intensity: 1.0, ..rust }, &at); + assert!(dripping.iter().zip(&dry).all(|(wet, dry)| wet >= dry), "a drip takes the most rust above, never less than its own"); + let gain = |heights: std::ops::Range| mean_within(&texels, &dripping, heights.clone()) - mean_within(&texels, &dry, heights); + assert!(gain(0.05..0.2) > gain(0.5..0.65) + 0.05, "below the band {} above it {}", gain(0.05..0.2), gain(0.5..0.65)); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index fd0a9c1a..6844d9c0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -21,6 +21,7 @@ mod curvature_mode; mod decal_flip; mod decal_symmetry; mod distance_parameters; +mod dripping_rust_parameters; mod filtering; mod generator_global; mod generator_grayscale; @@ -56,6 +57,7 @@ pub use curvature_mode::CurvatureMode; pub use decal_flip::DecalFlip; pub use decal_symmetry::DecalSymmetry; pub use distance_parameters::DistanceParameters; +pub use dripping_rust_parameters::DrippingRustParameters; pub use filtering::Filtering; pub use generator_global::GeneratorGlobal; pub use generator_grayscale::GeneratorGrayscale; @@ -968,10 +970,12 @@ pub enum GeneratorKind { UvBorderDistance, /// An image turned gray, tiled and rotated across the UV square GrayscaleConversion, + /// Rust in the occluded areas, running down the mesh in drips + DrippingRust, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 13] = [ + pub const ALL: [GeneratorKind; 14] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -985,6 +989,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient, GeneratorKind::UvBorderDistance, GeneratorKind::GrayscaleConversion, + GeneratorKind::DrippingRust, ]; pub fn label(self) -> &'static str { match self { @@ -1001,6 +1006,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient => "3D Linear Gradient", GeneratorKind::UvBorderDistance => "UV Border Distance", GeneratorKind::GrayscaleConversion => "Grayscale Conversion", + GeneratorKind::DrippingRust => "Dripping Rust", } } @@ -1020,6 +1026,7 @@ impl GeneratorKind { GeneratorKind::ThreeDLinearGradient => "ThreeDLinearGradient", GeneratorKind::UvBorderDistance => "UvBorderDistance", GeneratorKind::GrayscaleConversion => "GrayscaleConversion", + GeneratorKind::DrippingRust => "DrippingRust", } } @@ -1032,12 +1039,13 @@ impl GeneratorKind { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust ) } /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear) + matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. @@ -1050,7 +1058,8 @@ impl GeneratorKind { GeneratorKind::Position | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient => &[BakedMap::Position], GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion => &[], + // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust => &[], } } @@ -1063,6 +1072,7 @@ impl GeneratorKind { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust ) } diff --git a/crates/core/src/layer/dripping_rust_parameters.rs b/crates/core/src/layer/dripping_rust_parameters.rs new file mode 100644 index 00000000..879044ed --- /dev/null +++ b/crates/core/src/layer/dripping_rust_parameters.rs @@ -0,0 +1,55 @@ +use serde::{Deserialize, Serialize}; + +/// The Dripping Rust generator's controls: rust in the occluded areas, running down in drips +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct DrippingRustParameters { + /// How far the rust spreads: 0 none, 1 everywhere + pub spreading: f32, + /// How hard the rust's edge is (0..1; 1 a hard step) + pub contrast: f32, + /// Softens the rust before it drips (0..1) + pub spreading_smoothness: f32, + /// How far the drips run (0..1) + pub drips_intensity: f32, + /// Softens the drips (0..1) + pub drips_smoothness: f32, + /// How many steps each drip is drawn with ([`DrippingRustParameters::MAX_SAMPLES`] at most) + pub drips_samples: u32, + /// The axis of the mesh's bounds the drips run down: 0 X, 1 Y, 2 Z + pub axis: u8, +} + +impl DrippingRustParameters { + pub const MAX_SAMPLES: u32 = 32; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> DrippingRustParameters { + let defaults = DrippingRustParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + DrippingRustParameters { + spreading: unit(self.spreading, defaults.spreading), + contrast: unit(self.contrast, defaults.contrast), + spreading_smoothness: unit(self.spreading_smoothness, defaults.spreading_smoothness), + drips_intensity: unit(self.drips_intensity, defaults.drips_intensity), + drips_smoothness: unit(self.drips_smoothness, defaults.drips_smoothness), + drips_samples: self.drips_samples.min(DrippingRustParameters::MAX_SAMPLES), + axis: self.axis.min(2), + } + } +} + +impl Default for DrippingRustParameters { + /// The reference app's defaults + fn default() -> DrippingRustParameters { + DrippingRustParameters { + spreading: 0.5, + contrast: 0.5, + spreading_smoothness: 0.0, + drips_intensity: 0.1, + drips_smoothness: 0.05, + drips_samples: 32, + axis: 1, + } + } +} diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index abfd61b5..83b820cd 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use super::{BorderDistanceParameters, DistanceParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; +use super::{BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -10,6 +10,7 @@ pub enum KindControls { LinearGradient(LinearGradientParameters), BorderDistance(BorderDistanceParameters), Grayscale(GrayscaleConversionParameters), + DrippingRust(DrippingRustParameters), } impl KindControls { @@ -20,6 +21,7 @@ impl KindControls { GeneratorKind::ThreeDLinearGradient => Some(KindControls::LinearGradient(LinearGradientParameters::default())), GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), + GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -39,6 +41,7 @@ impl KindControls { KindControls::LinearGradient(gradient) => KindControls::LinearGradient(gradient.clamped()), KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), + KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), } } @@ -49,6 +52,7 @@ impl KindControls { KindControls::LinearGradient(_) => GeneratorKind::ThreeDLinearGradient, KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, + KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index dc2c5f4b..63ed7115 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -77,7 +77,8 @@ impl MicroDetails { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 153640f8..375534b9 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -43,7 +43,8 @@ impl SectionParameters { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 6acde341..32d478c5 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -62,7 +62,8 @@ impl WearParameters { | GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion => None, + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 33b70ff6..09320d73 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 120d3d42..0c67f2a0 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{Generator, GeneratorKind, GeneratorGrayscale, KindControls}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls}; use crate::Result; -use crate::commands::{bad, boolp, color_param, f32p}; +use crate::commands::{bad, boolp, color_param, f32p, u64p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -18,6 +18,10 @@ pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness /// The Grayscale Conversion controls (its image is the `image` input) pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "grayscaleContrast", "grayscaleTile", "grayscaleRotation", "grayscaleSafeRotation"]; +/// The Dripping Rust controls (it also takes the seed and invert) +pub const DRIPPING_RUST_KEYS: [&str; 7] = + ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -29,6 +33,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient), (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), + (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -46,6 +51,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::GrayscaleConversion { return grayscale_from(command, params, generator); } + if kind == GeneratorKind::DrippingRust { + return dripping_rust_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -119,6 +127,36 @@ fn grayscale_from(command: &str, params: &Value, generator: &mut Generator) -> R Ok(()) } +/// The Dripping Rust controls in `params` (the generator is one) +fn dripping_rust_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::DrippingRust(mut rust)) = generator.kind_controls() else { return Ok(()) }; + for (key, value) in [ + ("rustSpreading", &mut rust.spreading), + ("rustContrast", &mut rust.contrast), + ("spreadingSmoothness", &mut rust.spreading_smoothness), + ("dripsIntensity", &mut rust.drips_intensity), + ("dripsSmoothness", &mut rust.drips_smoothness), + ] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + if let Some(samples) = u64p(params, "dripsSamples") { + rust.drips_samples = samples.min(u64::from(DrippingRustParameters::MAX_SAMPLES)) as u32; + } + if let Some(value) = params.get("dripsAxis") { + let name = value.as_str().ok_or_else(|| bad(command, "`dripsAxis` must be x, y or z"))?; + rust.axis = match name.to_ascii_lowercase().as_str() { + "x" => 0, + "y" => 1, + "z" => 2, + _ => return Err(bad(command, format!("unknown axis `{name}`: x, y or z"))), + }; + } + generator.controls = Some(Box::new(KindControls::DrippingRust(rust.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 3cb7a868..95811f45 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 7e7ab4ef..c9e63424 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -1,8 +1,8 @@ -//! The 3D Distance, 3D Linear Gradient and UV Border Distance generators through `effect.add.generator` and `effect.set`: its controls, the controls it lacks, and a gradient around its point +//! The generators with only their own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion, Dripping Rust) through `effect.add.generator` and `effect.set`: their controls and the controls they lack use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, EffectKind, Generator, GeneratorKind, GeneratorGrayscale, LayerId, LinearGradientParameters, Source, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, }; use texturecraft_engine::{Session, execute}; @@ -120,3 +120,19 @@ fn grayscale_conversion_takes_its_controls_and_its_image() { assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "input": "image", "inputImage": name})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "grayscaleTile": 2})).is_err()); } + +#[test] +fn dripping_rust_takes_its_controls_its_seed_and_its_axis() { + let mut session = session(); + let params = json!({"generator": "Dripping Rust", "rustSpreading": 0.7, "dripsIntensity": 0.4, "dripsSamples": 99, "dripsAxis": "X", "seed": 3}); + let effect = add(&mut session, params); + + let made = generator(&session, effect); + let expected = DrippingRustParameters { spreading: 0.7, drips_intensity: 0.4, drips_samples: 32, axis: 0, ..DrippingRustParameters::default() }; + assert_eq!(made.kind_controls(), Some(KindControls::DrippingRust(expected)), "samples stop at 32"); + assert_eq!(made.seed, 3); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "dripsAxis": "w"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "level": 0.2})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "rustSpreading": 0.2})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index f7335dc8..01eee8de 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -101,6 +101,9 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { } GeneratorKind::UvBorderDistance => (tr("A gradient in from the UV islands' borders."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), GeneratorKind::GrayscaleConversion => (tr("An image turned gray."), [tr("mask"), tr("generator"), tr("grayscale"), tr("image")]), + GeneratorKind::DrippingRust => { + (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } }; // Wrapped rows: a long line must not widen the panel past its edge From 59fd1bc705f5a373a61bbafcea2fc94aecaf5c98 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:14:23 +0000 Subject: [PATCH 20/54] Polygon fill: the triangle grouping moves to geom, for generators to share TrianglePartition and the UV edge key (with its corner grid) move from the engine into texturecraft-geom unchanged, beside the mesh they group, with a uv_islands constructor polygon fill now uses for its UV island mode. The compositor can then group texels by UV island for the UV island generators without depending on the engine. --- crates/engine/src/lib.rs | 1 - crates/engine/src/polygon_fill.rs | 23 ++------------ crates/engine/src/polygon_fill_drag.rs | 2 +- crates/engine/src/polygon_fill_mirror.rs | 2 +- crates/geom/src/lib.rs | 2 ++ .../src/triangle_partition.rs | 30 +++++++++++++++++-- 6 files changed, 34 insertions(+), 26 deletions(-) rename crates/{engine => geom}/src/triangle_partition.rs (78%) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 041aca62..336ba602 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -86,7 +86,6 @@ mod tile_transform_params; mod tool_availability; pub mod tool_cmds; pub mod tool_settings; -mod triangle_partition; mod uv_stroke_state; mod uv_symmetry; pub mod uv_tile_cmds; diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 3292c61b..4f65c090 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -5,18 +5,15 @@ use std::collections::{BTreeSet, HashSet}; use texturecraft_compose::MaskGray; use texturecraft_geom::glam::Vec2; -use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_geom::triangle_partition::CORNER_GRID_STEPS; +use texturecraft_geom::{Mesh, NO_TRI, TrianglePartition}; use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; use crate::fill_mode::FillMode; use crate::polygon_fill_drag::PolygonFillDrag; use crate::session::Session; -use crate::triangle_partition::TrianglePartition; use crate::{EngineError, Result}; -/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner -const CORNER_GRID_STEPS: f32 = 1e5; - impl Session { /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { @@ -178,7 +175,7 @@ impl Session { match self.tool.fill_mode { FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges), - FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges), + FillMode::UvIsland => TrianglePartition::uv_islands(&self.mesh, material), FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), } } @@ -298,12 +295,6 @@ fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { first..end.max(first) } -/// Texture coordinates of `triangle`'s corners -fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { - let [first, second, third] = mesh.tri(triangle)?; - Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) -} - /// The polygon diagonals of `triangle`: edges the importer added to split a polygon fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); @@ -318,14 +309,6 @@ fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { .collect() } -/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart -fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { - let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); - let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; - - [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() -} - /// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> { let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64)); diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs index 09c20905..39c64507 100644 --- a/crates/engine/src/polygon_fill_drag.rs +++ b/crates/engine/src/polygon_fill_drag.rs @@ -9,7 +9,7 @@ use texturecraft_paint::EyeDepth; use texturecraft_texel::TileImage; use crate::session::{Document, StackTarget}; -use crate::triangle_partition::TrianglePartition; +use texturecraft_geom::TrianglePartition; /// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends pub(crate) struct PolygonFillDrag { diff --git a/crates/engine/src/polygon_fill_mirror.rs b/crates/engine/src/polygon_fill_mirror.rs index 945d15bb..fd362ff2 100644 --- a/crates/engine/src/polygon_fill_mirror.rs +++ b/crates/engine/src/polygon_fill_mirror.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeSet, HashSet}; use texturecraft_geom::glam::Mat3; use crate::session::Session; -use crate::triangle_partition::TrianglePartition; +use texturecraft_geom::TrianglePartition; /// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal const MIRROR_TOLERANCE: f32 = 1e-3; diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 3ca0f8ed..eb71f854 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod camera; pub mod gbuffer; pub mod mesh; pub mod primitives; +pub mod triangle_partition; pub mod unwrap; pub use bvh::{Bvh, Hit}; @@ -18,6 +19,7 @@ pub use camera::{OrbitCamera, Ray}; pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; +pub use triangle_partition::TrianglePartition; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum GeomError { diff --git a/crates/engine/src/triangle_partition.rs b/crates/geom/src/triangle_partition.rs similarity index 78% rename from crates/engine/src/triangle_partition.rs rename to crates/geom/src/triangle_partition.rs index d6ad31cb..ab578c2c 100644 --- a/crates/engine/src/triangle_partition.rs +++ b/crates/geom/src/triangle_partition.rs @@ -1,9 +1,14 @@ -//! Triangles of one material grouped into the pieces polygon fill selects and fills. +//! Triangles of one material grouped into pieces joined across shared edges: the UV islands, polygons or connected meshes polygon fill selects and the UV island generators colour use std::collections::HashMap; use std::hash::Hash; -use texturecraft_geom::Mesh; +use glam::Vec2; + +use crate::Mesh; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +pub const CORNER_GRID_STEPS: f32 = 1e5; /// A material's triangles split into groups joined across shared edges pub struct TrianglePartition { @@ -58,15 +63,34 @@ impl TrianglePartition { self.group_of.get(&triangle).copied() } + /// `material`'s UV islands: triangles joined where they share an edge in UV space + pub fn uv_islands(mesh: &Mesh, material: usize) -> TrianglePartition { + TrianglePartition::new(mesh, material, uv_edges) + } + /// The group holding `triangle` (None for a triangle of another material) pub fn group(&self, triangle: u32) -> Option<&[u32]> { self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice) } } +/// Texture coordinates of `triangle`'s corners +fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) +} + +/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart +pub fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { + let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + #[cfg(test)] mod tests { - use texturecraft_geom::primitives; + use crate::primitives; use super::*; From 44a8af0943dce788dfd14e8fd2423667b1fc957a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:24:31 +0000 Subject: [PATCH 21/54] Generators: UV Random Color, one random value per UV island MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new kind with the reference's controls: Seed and Color Source Mode (Random, or Custom Gradient with its colors). Each UV island (triangles joined across shared UV edges, as polygon fill groups them) gets a seeded random color, or the gradient's color at a random point, and the mask reads the mean of its channels. The reference's random numbers are its own, so islands differ in value but not in kind: on the test gun every island is one flat value in both, with island means spread alike (0.52 ± 0.16 against the reference's 0.50 ± 0.15). As a mask it is gray; a colored fill would need generators in content stacks. Generator maps now hold one whole-map field for UV Border Distance, Dripping Rust and UV Random Color. Commands only. --- crates/compose/src/eval.rs | 28 ++--- crates/compose/src/generator_maps.rs | 15 ++- crates/compose/src/lib.rs | 1 + crates/compose/src/uv_islands.rs | 48 +++++++++ .../tests/generator_uv_random_color.rs | 102 ++++++++++++++++++ crates/core/src/layer.rs | 18 +++- crates/core/src/layer/kind_controls.rs | 9 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- .../src/layer/uv_random_color_parameters.rs | 29 +++++ crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 2 +- crates/engine/src/distance_params.rs | 30 +++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 14 ++- crates/ui-egui/src/generator_panel.rs | 1 + 16 files changed, 274 insertions(+), 34 deletions(-) create mode 100644 crates/compose/src/uv_islands.rs create mode 100644 crates/compose/tests/generator_uv_random_color.rs create mode 100644 crates/core/src/layer/uv_random_color_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52625777..b719fe21 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2502,7 +2502,8 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { let position = self.uniform_position_input(generator); return three_d_distance::linear_gradient_value(gradient, position); } - Some(KindControls::BorderDistance(border)) => { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let gradient = maps.border_gradient.as_ref().and_then(|gradient| gradient.get(texel)).copied().unwrap_or(0.0); - return uv_border_distance::border_value(border, gradient); - } + Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), - Some(KindControls::DrippingRust(rust)) => { - let texel = (self.y * self.inp.gbuf.width + self.x) as usize; - let field = maps.rust_field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0); - return dripping_rust::rust_value(rust, field); - } + Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), + Some(KindControls::UvRandomColor(_)) => return self.field_value(maps), None => {} } @@ -3490,7 +3484,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor, _, ) => 0.0, }; @@ -3542,7 +3537,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => 0.0, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => 0.0, } } @@ -3554,6 +3550,12 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// A generator's whole-map field at this texel (0 without one) + fn field_value(&self, maps: &GeneratorMaps) -> f32 { + let texel = (self.y * self.inp.gbuf.width + self.x) as usize; + maps.field.as_ref().and_then(|field| field.get(texel)).copied().unwrap_or(0.0) + } + /// The Grayscale Conversion generator at this texel: its image tiled and turned about the UV square's centre, made gray, balanced and contrasted fn grayscale_conversion(&mut self, grayscale: &GrayscaleConversionParameters) -> f32 { let degrees = if grayscale.safe_rotation { (grayscale.rotation / QUARTER_TURN_DEGREES).round() * QUARTER_TURN_DEGREES } else { grayscale.rotation }; diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index acced92c..6206889d 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -9,6 +9,7 @@ use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; +use crate::uv_islands::random_color_field; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -19,10 +20,8 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, - /// The UV Border Distance gradient at every working texel - pub border_gradient: Option>>, - /// The Dripping Rust field at every working texel - pub rust_field: Option>>, + /// The whole-map field of UV Border Distance, Dripping Rust or UV Random Color at every working texel + pub field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, } @@ -39,14 +38,12 @@ impl GeneratorMaps { None => inp.baked.maps.get(&BakedMap::Curvature).and_then(|curvature| CurvatureSizes::of_map(inp, curvature, needed)), }; let controls = generator.kind_controls(); - let border_gradient = match &controls { + let field = match &controls { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), - _ => None, - }; - let rust_field = match &controls { Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), + Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), _ => None, }; - GeneratorMaps { sizes, micro_curvature, micro_occlusion, border_gradient, rust_field, controls: controls.map(Arc::new) } + GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 09ae63d8..eb85e0ae 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -54,6 +54,7 @@ mod tile_pattern; mod tile_random_stream; mod timber; mod uv_border_distance; +mod uv_islands; pub mod warp; mod warp_source_sample; mod warp_texel; diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs new file mode 100644 index 00000000..400afeae --- /dev/null +++ b/crates/compose/src/uv_islands.rs @@ -0,0 +1,48 @@ +//! The UV island generators: a value per UV island at every working texel, built once per layout and settings + +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{UvRandomColorParameters, gradient}; +use texturecraft_geom::TrianglePartition; +use texturecraft_texel::noise::cell_hash; + +use crate::eval::Inputs; +use crate::working_field::FieldCache; + +static CACHE: FieldCache = FieldCache::new(); + +/// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) +pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { + let mut settings = vec![seed, u32::from(random.custom_gradient)]; + settings.extend(random.gradient.iter().flat_map(|color| color.map(f32::to_bits))); + CACHE.get_or_build(inp, &[], settings, |_| { + let island_values = island_values(inp, |island| random_gray(random, seed, island)); + let gbuf = inp.gbuf; + gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect() + }) +} + +/// The value `value_of` gives each UV island, by triangle +fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> std::collections::HashMap { + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + islands + .groups + .iter() + .enumerate() + .flat_map(|(island, triangles)| triangles.iter().map(move |triangle| (*triangle, island as u32))) + .map(|(triangle, island)| (triangle, value_of(island))) + .collect() +} + +/// An island's gray: the mean of a random color's channels, or of the gradient's color at a random point +fn random_gray(random: &UvRandomColorParameters, seed: u32, island: u32) -> f32 { + let island = island as i32; + let color = if random.custom_gradient { + gradient(&random.gradient, cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) + } else { + std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed)) + }; + color.iter().sum::() / 3.0 +} diff --git a/crates/compose/tests/generator_uv_random_color.rs b/crates/compose/tests/generator_uv_random_color.rs new file mode 100644 index 00000000..529bc354 --- /dev/null +++ b/crates/compose/tests/generator_uv_random_color.rs @@ -0,0 +1,102 @@ +//! The UV Random Color generator on a cube: one value per UV island, reshuffled by the seed, or picked along a gradient + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + UvRandomColorParameters, +}; +use texturecraft_geom::{Mesh, TrianglePartition, UvGBuffer, primitives}; + +const RES: u32 = 128; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::cube(1.0); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:cube"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// Every covered texel and its UV island +fn covered(fixture: &Fixture) -> Vec<((u32, u32), usize)> { + let islands = TrianglePartition::uv_islands(&fixture.mesh, 0); + (0..RES * RES) + .filter_map(|index| { + let triangle = *fixture.gbuf.tri.get(index as usize)?; + islands.index_of(triangle).map(|island| ((index % RES, index / RES), island)) + }) + .collect() +} + +fn mask(fixture: &mut Fixture, random: UvRandomColorParameters, seed: u32, texels: &[(u32, u32)]) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::UvRandomColor(random))), seed, ..Generator::new(GeneratorKind::UvRandomColor) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, fixture.layer, texels).unwrap() +} + +/// Each island's values, by island +fn by_island(texels: &[((u32, u32), usize)], values: &[f32]) -> std::collections::BTreeMap> { + let mut islands = std::collections::BTreeMap::>::new(); + for ((_, island), value) in texels.iter().zip(values) { + islands.entry(*island).or_default().push(*value); + } + islands +} + +#[test] +fn each_island_is_one_value_and_the_islands_differ() { + let mut fixture = fixture(); + let texels = covered(&fixture); + let at: Vec<(u32, u32)> = texels.iter().map(|(texel, _)| *texel).collect(); + + let islands = by_island(&texels, &mask(&mut fixture, UvRandomColorParameters::default(), 0, &at)); + assert!(islands.len() > 1, "the cube has several UV islands"); + assert!(islands.values().all(|values| values.iter().all(|value| (value - values[0]).abs() < 1e-6))); + let firsts: Vec = islands.values().map(|values| values[0]).collect(); + assert!(firsts.iter().any(|value| (value - firsts[0]).abs() > 0.01)); +} + +#[test] +fn the_seed_reshuffles_the_values() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let first = mask(&mut fixture, UvRandomColorParameters::default(), 0, &at); + let second = mask(&mut fixture, UvRandomColorParameters::default(), 2, &at); + assert_ne!(first, second); +} + +#[test] +fn a_one_color_gradient_colors_every_island_alike() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + + let values = mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]] }, 0, &at); + assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 6844d9c0..d74cfbf8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -44,6 +44,7 @@ mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_random_color_parameters; mod uv_transform; mod uv_wrap; mod wear_parameters; @@ -80,6 +81,7 @@ pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_random_color_parameters::UvRandomColorParameters; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; pub use wear_parameters::WearParameters; @@ -972,10 +974,12 @@ pub enum GeneratorKind { GrayscaleConversion, /// Rust in the occluded areas, running down the mesh in drips DrippingRust, + /// One random value per UV island + UvRandomColor, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 14] = [ + pub const ALL: [GeneratorKind; 15] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -990,6 +994,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance, GeneratorKind::GrayscaleConversion, GeneratorKind::DrippingRust, + GeneratorKind::UvRandomColor, ]; pub fn label(self) -> &'static str { match self { @@ -1007,6 +1012,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance => "UV Border Distance", GeneratorKind::GrayscaleConversion => "Grayscale Conversion", GeneratorKind::DrippingRust => "Dripping Rust", + GeneratorKind::UvRandomColor => "UV Random Color", } } @@ -1027,6 +1033,7 @@ impl GeneratorKind { GeneratorKind::UvBorderDistance => "UvBorderDistance", GeneratorKind::GrayscaleConversion => "GrayscaleConversion", GeneratorKind::DrippingRust => "DrippingRust", + GeneratorKind::UvRandomColor => "UvRandomColor", } } @@ -1040,12 +1047,16 @@ impl GeneratorKind { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor ) } /// Whether the kind's result depends on its seed pub fn includes_randomness(self) -> bool { - matches!(self, GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust) + matches!( + self, + GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + ) } /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. @@ -1059,7 +1070,7 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust => &[], + GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor => &[], } } @@ -1073,6 +1084,7 @@ impl GeneratorKind { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor ) } diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index 83b820cd..76292879 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -1,6 +1,9 @@ use serde::{Deserialize, Serialize}; -use super::{BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters}; +use super::{ + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters, + UvRandomColorParameters, +}; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -11,6 +14,7 @@ pub enum KindControls { BorderDistance(BorderDistanceParameters), Grayscale(GrayscaleConversionParameters), DrippingRust(DrippingRustParameters), + UvRandomColor(UvRandomColorParameters), } impl KindControls { @@ -22,6 +26,7 @@ impl KindControls { GeneratorKind::UvBorderDistance => Some(KindControls::BorderDistance(BorderDistanceParameters::default())), GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), + GeneratorKind::UvRandomColor => Some(KindControls::UvRandomColor(UvRandomColorParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -42,6 +47,7 @@ impl KindControls { KindControls::BorderDistance(border) => KindControls::BorderDistance(border.clamped()), KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), + KindControls::UvRandomColor(random) => KindControls::UvRandomColor(random.clamped()), } } @@ -53,6 +59,7 @@ impl KindControls { KindControls::BorderDistance(_) => GeneratorKind::UvBorderDistance, KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, + KindControls::UvRandomColor(_) => GeneratorKind::UvRandomColor, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 63ed7115..ed99f19c 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -78,7 +78,8 @@ impl MicroDetails { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 375534b9..8c1a6744 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -44,7 +44,8 @@ impl SectionParameters { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/layer/uv_random_color_parameters.rs b/crates/core/src/layer/uv_random_color_parameters.rs new file mode 100644 index 00000000..156a1be0 --- /dev/null +++ b/crates/core/src/layer/uv_random_color_parameters.rs @@ -0,0 +1,29 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Random Color generator's controls: one random value per UV island, picked at random or along a gradient +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UvRandomColorParameters { + /// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random + pub custom_gradient: bool, + /// The gradient's colors, evenly spaced (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) + pub gradient: Vec<[f32; 3]>, +} + +impl UvRandomColorParameters { + pub const MAX_GRADIENT_COLORS: usize = 16; + + /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one + pub fn clamped(self) -> UvRandomColorParameters { + let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; + let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect(); + UvRandomColorParameters { gradient: if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }, ..self } + } +} + +impl Default for UvRandomColorParameters { + /// Random colors; the gradient black to white + fn default() -> UvRandomColorParameters { + UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]] } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index 32d478c5..ab081fed 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -63,7 +63,8 @@ impl WearParameters { | GeneratorKind::ThreeDLinearGradient | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust => None, + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 09320d73..03c5f7ba 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,7 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvRandomColorParameters, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 0c67f2a0..1de81fae 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,10 +1,10 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvRandomColorParameters}; use crate::Result; -use crate::commands::{bad, boolp, color_param, f32p, u64p}; +use crate::commands::{bad, boolp, color_of, color_param, f32p, u64p}; /// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"]; @@ -22,6 +22,9 @@ pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "gra pub const DRIPPING_RUST_KEYS: [&str; 7] = ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; +/// The UV Random Color controls (it also takes the seed) +pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -34,6 +37,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance), (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), + (&UV_RANDOM_COLOR_KEYS[..], GeneratorKind::UvRandomColor), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -54,6 +58,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::DrippingRust { return dripping_rust_from(command, params, generator); } + if kind == GeneratorKind::UvRandomColor { + return uv_random_color_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -157,6 +164,25 @@ fn dripping_rust_from(command: &str, params: &Value, generator: &mut Generator) Ok(()) } +/// The UV Random Color controls in `params` (the generator is one) +fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::UvRandomColor(mut random)) = generator.kind_controls() else { return Ok(()) }; + if let Some(value) = params.get("colorSourceMode") { + random.custom_gradient = match value.as_str().map(str::to_ascii_lowercase).as_deref() { + Some("random") => false, + Some("customgradient" | "custom gradient" | "gradient") => true, + _ => return Err(bad(command, "`colorSourceMode` must be random or customGradient")), + }; + } + if let Some(value) = params.get("gradientColors") { + let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\""); + let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?; + random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::>()?; + } + generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 95811f45..9dc863d9 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index c9e63424..732c5a28 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -2,7 +2,7 @@ use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, UvRandomColorParameters, }; use texturecraft_engine::{Session, execute}; @@ -136,3 +136,15 @@ fn dripping_rust_takes_its_controls_its_seed_and_its_axis() { let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.set", &json!({"effect": curvature, "rustSpreading": 0.2})).is_err()); } + +#[test] +fn uv_random_color_takes_its_mode_and_gradient() { + let mut session = session(); + let params = json!({"generator": "UV Random Color", "colorSourceMode": "customGradient", "gradientColors": [[2.0, 0.5, 0.0], "#000000"]}); + let effect = add(&mut session, params); + + let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]] }; + assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvRandomColor(expected)), "colors stay within 0..1"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 01eee8de..51c9d7e9 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -104,6 +104,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::DrippingRust => { (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) } + GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From f3d5cbe40c5ad549f5af2ad7a92bac9c21486146 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:07:20 +0000 Subject: [PATCH 22/54] Generators: UV Checker, a checker and grid over each UV tile with the islands' borders A new kind with the reference's controls: Seed, Checker Color Mode (Uniform, or Random per UV island), Checker Color, Checker Grid Tile, Checker Grid Opacity, UV Borders Color and UV Borders Width. Fitted to the reference's color captures: four checker squares per grid tile, dark squares a shade of the light color; minor grid lines every quarter square and major ones on the square edges, each layer laid over the last at the grid opacity; texels within the border width (0.2 is 3 texels at 2K) of an island's edge take the border color; random mode gives each island its own light color; the mask reads the mean of the sRGB-encoded channels, as the reference does. On the test gun 99.9% of texels match the reference within 1/255, at the default and with the grid off (the rest lie on seams where two islands touch in UV, which coverage alone can't tell apart). Lines and borders test a texel's whole footprint, so they stay visible below 2K. Commands only. --- crates/compose/src/eval.rs | 14 +- crates/compose/src/generator_maps.rs | 5 +- crates/compose/src/uv_border_distance.rs | 2 +- crates/compose/src/uv_islands.rs | 127 +++++++++++++++++- crates/compose/tests/generator_uv_checker.rs | 76 +++++++++++ crates/core/src/layer.rs | 24 +++- crates/core/src/layer/kind_controls.rs | 6 +- crates/core/src/layer/micro_details.rs | 3 +- crates/core/src/layer/section_parameters.rs | 3 +- .../core/src/layer/uv_checker_parameters.rs | 51 +++++++ crates/core/src/layer/wear_parameters.rs | 3 +- crates/core/src/lib.rs | 8 +- crates/engine/src/distance_params.rs | 37 ++++- crates/engine/src/mask_cmds.rs | 2 +- .../tests/it/generator_three_d_distance.rs | 16 ++- crates/ui-egui/src/generator_panel.rs | 1 + 16 files changed, 354 insertions(+), 24 deletions(-) create mode 100644 crates/compose/tests/generator_uv_checker.rs create mode 100644 crates/core/src/layer/uv_checker_parameters.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b719fe21..06f95001 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2502,8 +2502,10 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator Texel<'a, 'b> { Some(KindControls::BorderDistance(border)) => return uv_border_distance::border_value(border, self.field_value(maps)), Some(KindControls::Grayscale(grayscale)) => return self.grayscale_conversion(grayscale), Some(KindControls::DrippingRust(rust)) => return dripping_rust::rust_value(rust, self.field_value(maps)), - Some(KindControls::UvRandomColor(_)) => return self.field_value(maps), + Some(KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) => return self.field_value(maps), None => {} } @@ -3485,7 +3487,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker, _, ) => 0.0, }; @@ -3538,7 +3541,8 @@ impl<'a, 'b> Texel<'a, 'b> { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => 0.0, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, } } diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 6206889d..151ae176 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -9,7 +9,7 @@ use crate::dripping_rust::rust_field; use crate::eval::Inputs; use crate::micro_details::{LayoutMap, MicroCurvature, micro_occlusion}; use crate::uv_border_distance::border_gradient; -use crate::uv_islands::random_color_field; +use crate::uv_islands::{checker_field, random_color_field}; /// What a generator reads beyond its texel: built once per map and settings, shared by every tile #[derive(Clone, Default)] @@ -20,7 +20,7 @@ pub(crate) struct GeneratorMaps { pub micro_curvature: Option>, /// What its micro details multiply its occlusion by pub micro_occlusion: Option>, - /// The whole-map field of UV Border Distance, Dripping Rust or UV Random Color at every working texel + /// The whole-map field of UV Border Distance, Dripping Rust, UV Random Color or UV Checker at every working texel pub field: Option>>, /// The controls of a kind with only its own controls, brought into range pub controls: Option>, @@ -42,6 +42,7 @@ impl GeneratorMaps { Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), + Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)), _ => None, }; GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index 0fa3afd0..c4d1af41 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -67,7 +67,7 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> } /// Each texel's Euclidean distance in texels to the nearest uncovered texel of its UV tile block, the space past the block's edges counting as uncovered -fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { +pub(crate) fn border_distances(gbuf: &texturecraft_geom::UvGBuffer, (width, height): (u32, u32), block: (u32, u32)) -> Vec { let mut squared = vec![0.0f32; (width * height) as usize]; for top in (0..height).step_by(block.1 as usize) { for left in (0..width).step_by(block.0 as usize) { diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 400afeae..25a23d10 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -1,13 +1,16 @@ -//! The UV island generators: a value per UV island at every working texel, built once per layout and settings +//! The UV island generators (UV Random Color, UV Checker) at every working texel, built once per layout and settings +use std::collections::HashMap; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{UvRandomColorParameters, gradient}; -use texturecraft_geom::TrianglePartition; +use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters, gradient}; +use texturecraft_geom::{NO_TRI, TrianglePartition}; +use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; -use crate::eval::Inputs; +use crate::eval::{Inputs, texel_coords}; +use crate::uv_border_distance::border_distances; use crate::working_field::FieldCache; static CACHE: FieldCache = FieldCache::new(); @@ -24,7 +27,7 @@ pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, } /// The value `value_of` gives each UV island, by triangle -fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> std::collections::HashMap { +fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap { let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); let islands = TrianglePartition::uv_islands(inp.mesh, material); islands @@ -46,3 +49,117 @@ fn random_gray(random: &UvRandomColorParameters, seed: u32, island: u32) -> f32 }; color.iter().sum::() / 3.0 } + +/// Checker squares across one grid tile, and grid lines across one square (fitted) +const SQUARES_PER_GRID_TILE: f32 = 4.0; +const MINOR_LINES_PER_SQUARE: f32 = 4.0; + +/// The dark squares are the light color times this, on its sRGB-encoded values (fitted) +const DARK_SQUARE_SHADE: f32 = 0.7128; + +/// What a full-opacity minor and major grid line multiply the color by (fitted) +const MINOR_LINE_SHADE: f32 = 0.8465; +const MAJOR_LINE_SHADE: f32 = 0.4230; + +/// Texels of a 2K UV tile a grid line lies within of its square's edge, and the border's width per unit of UV Borders Width (fitted: 0.2 is 3 texels) +const LINE_HALF_WIDTH_2K: f32 = 1.0; +const BORDER_TEXELS_PER_WIDTH_2K: f32 = 15.0; + +/// The UV tile resolution the sizes above are measured at +const REFERENCE_TILE_TEXELS: f32 = 2048.0; + +/// The saturation and value random island colors are picked within (measured) +const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; +const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; + +/// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands) +pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u32) -> Arc> { + let mut settings = vec![seed, u32::from(checker.random_colors), checker.grid_tile, checker.grid_opacity.to_bits(), checker.border_width.to_bits()]; + settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits())); + CACHE.get_or_build(inp, &[], settings, |block| { + let gbuf = inp.gbuf; + let (width, height) = (gbuf.width, gbuf.height); + let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() }; + let distances = border_distances(gbuf, (width, height), block); + let light = checker.checker_color.map(linear_to_srgb); + let border = checker.border_color.map(linear_to_srgb); + + (0..width * height) + .into_par_iter() + .map(|texel| { + let Some(triangle) = gbuf.tri.get(texel as usize).copied().filter(|triangle| *triangle != NO_TRI) else { return 0.0 }; + let (x, y) = (texel % width, texel / width); + let texels_2k = REFERENCE_TILE_TEXELS / (block.0 as f32 * inp.block_scales.at(x, y)); + // Measured from the texel's 2K sub-texel nearest the border, so a coarser texel still shows the border it holds + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - (texels_2k - 1.0).max(0.0); + let color = if checker.border_width > 0.0 && to_border <= checker.border_width * BORDER_TEXELS_PER_WIDTH_2K { + border + } else { + let uv = texel_coords(inp, x, y).uv; + let light = island_colors.get(&triangle).copied().unwrap_or(light); + let at = (uv.x.rem_euclid(1.0) * REFERENCE_TILE_TEXELS, uv.y.rem_euclid(1.0) * REFERENCE_TILE_TEXELS); + checker_color(checker, light, at, texels_2k) + }; + color.iter().sum::() / 3.0 + }) + .collect() + }) +} + +/// The checker's sRGB-encoded color at (`x`, `y`) in texels of a 2K UV tile (row 0 at the top) for a texel `texels_2k` of them wide, with `light` its light squares +fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f32), texels_2k: f32) -> [f32; 3] { + let square = REFERENCE_TILE_TEXELS / (SQUARES_PER_GRID_TILE * checker.grid_tile.max(1) as f32); + let is_light = ((x / square).floor() + (y / square).floor()).rem_euclid(2.0) >= 1.0; + let base = if is_light { light } else { light.map(|channel| channel * DARK_SQUARE_SHADE) }; + + // Line layers in the reference's order, each laid over the last at the grid's opacity + let minor = square / MINOR_LINES_PER_SQUARE; + // A texel is on a line when its footprint overlaps the line's band, so lines stay visible on coarser texels + let reach = LINE_HALF_WIDTH_2K + (texels_2k - 1.0).max(0.0) * 0.5; + let on_line = |position: f32, period: f32| (position - (position / period).round() * period).abs() < reach; + let layers = [ + (on_line(y, minor) && !on_line(y, square), MINOR_LINE_SHADE), + (on_line(x, minor) && !on_line(x, square), MINOR_LINE_SHADE), + (on_line(y, square), MAJOR_LINE_SHADE), + (on_line(x, square), MAJOR_LINE_SHADE), + ]; + let opacity = checker.grid_opacity.clamp(0.0, 1.0); + let shade = layers.iter().filter(|(on, _)| *on).fold(1.0, |shade, (_, line)| shade + (line - shade) * opacity); + base.map(|channel| channel * shade) +} + +/// A random light sRGB-encoded color per UV island, by triangle +fn island_colors(inp: &Inputs, seed: u32) -> HashMap { + let material = inp.project.texture_set(inp.ts).map_or(0, |set| set.material); + let islands = TrianglePartition::uv_islands(inp.mesh, material); + islands + .groups + .iter() + .enumerate() + .flat_map(|(island, triangles)| { + let island = island as i32; + let within = |range: &std::ops::RangeInclusive, random: f32| range.start() + (range.end() - range.start()) * random; + let color = hsv_to_rgb( + cell_hash(island, 0, 1, seed), + within(&RANDOM_SATURATION, cell_hash(island, 1, 1, seed)), + within(&RANDOM_VALUE, cell_hash(island, 2, 1, seed)), + ); + triangles.iter().map(move |triangle| (*triangle, color)) + }) + .collect() +} + +/// A color from its hue (in turns), saturation and value +fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [f32; 3] { + let sector = hue.rem_euclid(1.0) * 6.0; + let fraction = sector - sector.floor(); + let (low, falling, rising) = (value * (1.0 - saturation), value * (1.0 - saturation * fraction), value * (1.0 - saturation * (1.0 - fraction))); + match sector.floor() as u32 { + 0 => [value, rising, low], + 1 => [falling, value, low], + 2 => [low, value, rising], + 3 => [low, falling, value], + 4 => [rising, low, value], + _ => [value, low, falling], + } +} diff --git a/crates/compose/tests/generator_uv_checker.rs b/crates/compose/tests/generator_uv_checker.rs new file mode 100644 index 00000000..549abc29 --- /dev/null +++ b/crates/compose/tests/generator_uv_checker.rs @@ -0,0 +1,76 @@ +//! The UV Checker generator on a plane filling its UV tile: a checker with grid lines, its border along the tile's edge + +use texturecraft_compose::{BakedMaps, Inputs, PixelStore, mask_at}; +use texturecraft_core::{ + Channel, Effect, EffectKind, Fill, Generator, GeneratorKind, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Source, TextureSet, + UvCheckerParameters, +}; +use texturecraft_geom::{Mesh, UvGBuffer, primitives}; + +const RES: u32 = 256; + +struct Fixture { + project: Project, + mesh: Mesh, + gbuf: UvGBuffer, + layer: LayerId, +} + +fn fixture() -> Fixture { + let mesh = primitives::plane(2.0, 1); + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let id = project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let layer = project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + Fixture { project, mesh, gbuf, layer } +} + +/// The middle row, left to right +fn row(fixture: &mut Fixture, checker: UvCheckerParameters) -> Vec { + let generator = Generator { controls: Some(Box::new(KindControls::UvChecker(checker))), ..Generator::new(GeneratorKind::UvChecker) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(fixture.layer).unwrap().mask = Some(mask); + let baked = BakedMaps::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &PixelStore::default(), + baked: &baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &Default::default(), + bounds: fixture.mesh.bounds(), + }; + let texels: Vec<(u32, u32)> = (0..RES).map(|x| (x, RES / 2 + 3)).collect(); + mask_at(&inputs, fixture.layer, &texels).unwrap() +} + +/// The distinct values of `values`, to 0.01 +fn tones(values: &[f32]) -> std::collections::BTreeSet { + values.iter().map(|value| (value * 100.0).round() as u32).collect() +} + +#[test] +fn without_grid_lines_the_checker_has_two_tones_and_a_border() { + let mut fixture = fixture(); + let values = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, grid_tile: 1, ..UvCheckerParameters::default() }); + + assert_eq!(tones(&values[8..RES as usize - 8]).len(), 2, "two checker tones inside: {:?}", tones(&values)); + assert!((values[0] - 1.0 / 3.0).abs() < 0.01, "the red border reads a third: {}", values[0]); +} + +#[test] +fn grid_lines_only_darken() { + let mut fixture = fixture(); + let plain = row(&mut fixture, UvCheckerParameters { grid_opacity: 0.0, ..UvCheckerParameters::default() }); + let lined = row(&mut fixture, UvCheckerParameters::default()); + + assert!(lined.iter().zip(&plain).all(|(lined, plain)| lined <= plain)); + assert!(lined.iter().zip(&plain).any(|(lined, plain)| lined < plain)); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index d74cfbf8..ccbf8ed9 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -44,6 +44,7 @@ mod tile_input_distribution; mod tile_shape; mod tile_size_mode; mod tile_symmetry; +mod uv_checker_parameters; mod uv_random_color_parameters; mod uv_transform; mod uv_wrap; @@ -81,6 +82,7 @@ pub use tile_input_distribution::TileInputDistribution; pub use tile_shape::TileShape; pub use tile_size_mode::TileSizeMode; pub use tile_symmetry::TileSymmetry; +pub use uv_checker_parameters::UvCheckerParameters; pub use uv_random_color_parameters::UvRandomColorParameters; pub use uv_transform::UvTransform; pub use uv_wrap::UvWrap; @@ -976,10 +978,12 @@ pub enum GeneratorKind { DrippingRust, /// One random value per UV island UvRandomColor, + /// A checker and grid over each UV tile with the UV islands' borders drawn in, for checking a layout + UvChecker, } impl GeneratorKind { - pub const ALL: [GeneratorKind; 15] = [ + pub const ALL: [GeneratorKind; 16] = [ GeneratorKind::EdgeWear, GeneratorKind::Dirt, GeneratorKind::ThinAreas, @@ -995,6 +999,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion, GeneratorKind::DrippingRust, GeneratorKind::UvRandomColor, + GeneratorKind::UvChecker, ]; pub fn label(self) -> &'static str { match self { @@ -1013,6 +1018,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion => "Grayscale Conversion", GeneratorKind::DrippingRust => "Dripping Rust", GeneratorKind::UvRandomColor => "UV Random Color", + GeneratorKind::UvChecker => "UV Checker", } } @@ -1034,6 +1040,7 @@ impl GeneratorKind { GeneratorKind::GrayscaleConversion => "GrayscaleConversion", GeneratorKind::DrippingRust => "DrippingRust", GeneratorKind::UvRandomColor => "UvRandomColor", + GeneratorKind::UvChecker => "UvChecker", } } @@ -1048,6 +1055,7 @@ impl GeneratorKind { | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } @@ -1055,7 +1063,12 @@ impl GeneratorKind { pub fn includes_randomness(self) -> bool { matches!( self, - GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::FiberGlassEdgeWear | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + GeneratorKind::EdgeWear + | GeneratorKind::Dirt + | GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } @@ -1070,7 +1083,11 @@ impl GeneratorKind { GeneratorKind::WorldSpaceNormals => &[BakedMap::WorldNormal], GeneratorKind::Direction => &[BakedMap::WorldNormal, BakedMap::Position], // Dripping Rust reads the baked occlusion and the mesh's bounds whole, so no input replaces them yet - GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor => &[], + GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => &[], } } @@ -1085,6 +1102,7 @@ impl GeneratorKind { | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker ) } diff --git a/crates/core/src/layer/kind_controls.rs b/crates/core/src/layer/kind_controls.rs index 76292879..eab247d5 100644 --- a/crates/core/src/layer/kind_controls.rs +++ b/crates/core/src/layer/kind_controls.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; use super::{ BorderDistanceParameters, DistanceParameters, DrippingRustParameters, GeneratorKind, GrayscaleConversionParameters, LinearGradientParameters, - UvRandomColorParameters, + UvCheckerParameters, UvRandomColorParameters, }; /// The controls of a kind that has only the reference's own controls, no earlier model: one variant per kind @@ -15,6 +15,7 @@ pub enum KindControls { Grayscale(GrayscaleConversionParameters), DrippingRust(DrippingRustParameters), UvRandomColor(UvRandomColorParameters), + UvChecker(UvCheckerParameters), } impl KindControls { @@ -27,6 +28,7 @@ impl KindControls { GeneratorKind::GrayscaleConversion => Some(KindControls::Grayscale(GrayscaleConversionParameters::default())), GeneratorKind::DrippingRust => Some(KindControls::DrippingRust(DrippingRustParameters::default())), GeneratorKind::UvRandomColor => Some(KindControls::UvRandomColor(UvRandomColorParameters::default())), + GeneratorKind::UvChecker => Some(KindControls::UvChecker(UvCheckerParameters::default())), GeneratorKind::EdgeWear | GeneratorKind::Dirt | GeneratorKind::ThinAreas @@ -48,6 +50,7 @@ impl KindControls { KindControls::Grayscale(grayscale) => KindControls::Grayscale(grayscale.clamped()), KindControls::DrippingRust(rust) => KindControls::DrippingRust(rust.clamped()), KindControls::UvRandomColor(random) => KindControls::UvRandomColor(random.clamped()), + KindControls::UvChecker(checker) => KindControls::UvChecker(checker.clamped()), } } @@ -60,6 +63,7 @@ impl KindControls { KindControls::Grayscale(_) => GeneratorKind::GrayscaleConversion, KindControls::DrippingRust(_) => GeneratorKind::DrippingRust, KindControls::UvRandomColor(_) => GeneratorKind::UvRandomColor, + KindControls::UvChecker(_) => GeneratorKind::UvChecker, } } } diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index ed99f19c..186f3af4 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -79,7 +79,8 @@ impl MicroDetails { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/layer/section_parameters.rs b/crates/core/src/layer/section_parameters.rs index 8c1a6744..7ea25d60 100644 --- a/crates/core/src/layer/section_parameters.rs +++ b/crates/core/src/layer/section_parameters.rs @@ -45,7 +45,8 @@ impl SectionParameters { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/layer/uv_checker_parameters.rs b/crates/core/src/layer/uv_checker_parameters.rs new file mode 100644 index 00000000..2a15020b --- /dev/null +++ b/crates/core/src/layer/uv_checker_parameters.rs @@ -0,0 +1,51 @@ +use serde::{Deserialize, Serialize}; + +/// The UV Checker generator's controls: a checker with a grid laid over each UV tile, the UV islands' borders drawn in a color +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UvCheckerParameters { + /// A random light color per UV island instead of the checker color + pub random_colors: bool, + /// The checker's light squares (linear RGB); the dark ones are a shade of it + pub checker_color: [f32; 3], + /// Grid tiles across the UV tile, each four checker squares wide ([`UvCheckerParameters::GRID_TILE_RANGE`]) + pub grid_tile: u32, + /// How strongly the grid lines darken the checker (0..1) + pub grid_opacity: f32, + /// The color of the UV islands' borders (linear RGB) + pub border_color: [f32; 3], + /// How wide the borders are (0..1; 0.2 is 3 texels of a 2K UV tile) + pub border_width: f32, +} + +impl UvCheckerParameters { + pub const GRID_TILE_RANGE: std::ops::RangeInclusive = 1..=24; + + /// Every value brought into its range, non-finite ones to the defaults + pub fn clamped(self) -> UvCheckerParameters { + let defaults = UvCheckerParameters::default(); + let unit = |value: f32, default: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { default }; + UvCheckerParameters { + checker_color: std::array::from_fn(|channel| unit(self.checker_color[channel], defaults.checker_color[channel])), + grid_tile: self.grid_tile.clamp(*UvCheckerParameters::GRID_TILE_RANGE.start(), *UvCheckerParameters::GRID_TILE_RANGE.end()), + grid_opacity: unit(self.grid_opacity, defaults.grid_opacity), + border_color: std::array::from_fn(|channel| unit(self.border_color[channel], defaults.border_color[channel])), + border_width: unit(self.border_width, defaults.border_width), + ..self + } + } +} + +impl Default for UvCheckerParameters { + /// The reference app's defaults: a light cyan checker (#5BDDFF), red borders + fn default() -> UvCheckerParameters { + UvCheckerParameters { + random_colors: false, + checker_color: [0.104_616, 0.723_055, 1.0], + grid_tile: 16, + grid_opacity: 0.5, + border_color: [1.0, 0.0, 0.0], + border_width: 0.2, + } + } +} diff --git a/crates/core/src/layer/wear_parameters.rs b/crates/core/src/layer/wear_parameters.rs index ab081fed..1d7e1718 100644 --- a/crates/core/src/layer/wear_parameters.rs +++ b/crates/core/src/layer/wear_parameters.rs @@ -64,7 +64,8 @@ impl WearParameters { | GeneratorKind::UvBorderDistance | GeneratorKind::GrayscaleConversion | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor => None, + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => None, } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 03c5f7ba..0662670a 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -111,7 +111,13 @@ pub use height_to_normal::HeightToNormal; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ - AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvRandomColorParameters, UvTransform, UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, + AxisBlend, AxisLayer, BorderDistanceParameters, ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, + DistanceParameters, DrippingRustParameters, Effect, EffectKind, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorGrayscale, GeneratorKind, + GrayscaleConversionParameters, HeightMask, KindControls, Layer, LayerId, LayerKind, Levels, LightParameters, LinearGradientParameters, LinkParam, + LinkPreset, Mask, MaskBackground, MaterialLink, MicroCurvatureType, MicroDetails, OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, + Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES, Sampling, ScaleMode, SectionParameters, Source, TextureBlend, TextureLayer, + TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvCheckerParameters, UvRandomColorParameters, UvTransform, + UvWrap, WearParameters, gradient, hsl_adjust, per_unit, posterize, }; pub use lighting_output::LightingOutput; pub use mask_outline::MaskOutline; diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 1de81fae..7b620be0 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -1,7 +1,7 @@ //! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take use serde_json::Value; -use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvRandomColorParameters}; +use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvCheckerParameters, UvRandomColorParameters}; use crate::Result; use crate::commands::{bad, boolp, color_of, color_param, f32p, u64p}; @@ -25,6 +25,9 @@ pub const DRIPPING_RUST_KEYS: [&str; 7] = /// The UV Random Color controls (it also takes the seed) pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; +/// The UV Checker controls (it also takes the seed) +pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"]; + /// The controls of the earlier model and the global adjustments, which these kinds don't have const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"]; @@ -38,6 +41,7 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - (&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion), (&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust), (&UV_RANDOM_COLOR_KEYS[..], GeneratorKind::UvRandomColor), + (&UV_CHECKER_KEYS[..], GeneratorKind::UvChecker), ] { if let Some(key) = first_given(params, keys).filter(|_| kind != owner) { return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label()))); @@ -61,6 +65,9 @@ pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) - if kind == GeneratorKind::UvRandomColor { return uv_random_color_from(command, params, generator); } + if kind == GeneratorKind::UvChecker { + return uv_checker_from(command, params, generator); + } if kind == GeneratorKind::UvBorderDistance { let mut border = generator.border_distance_controls().unwrap_or_default(); for (key, value) in [ @@ -183,6 +190,34 @@ fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator Ok(()) } +/// The UV Checker controls in `params` (the generator is one) +fn uv_checker_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + let Some(KindControls::UvChecker(mut checker)) = generator.kind_controls() else { return Ok(()) }; + if let Some(value) = params.get("checkerColorMode") { + checker.random_colors = match value.as_str().map(str::to_ascii_lowercase).as_deref() { + Some("uniform") => false, + Some("random") => true, + _ => return Err(bad(command, "`checkerColorMode` must be uniform or random")), + }; + } + if let Some(color) = color_param(command, params, "checkerColor")? { + checker.checker_color = color; + } + if let Some(color) = color_param(command, params, "uvBordersColor")? { + checker.border_color = color; + } + if let Some(tile) = u64p(params, "checkerGridTile") { + checker.grid_tile = tile.min(u64::from(*UvCheckerParameters::GRID_TILE_RANGE.end())) as u32; + } + for (key, value) in [("checkerGridOpacity", &mut checker.grid_opacity), ("uvBordersWidth", &mut checker.border_width)] { + if let Some(given) = f32p(params, key) { + *value = given; + } + } + generator.controls = Some(Box::new(KindControls::UvChecker(checker.clamped()))); + Ok(()) +} + /// The first of `keys` that `params` gives fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> { keys.iter().find(|key| params.get(**key).is_some()).copied() diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9dc863d9..77341832 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 732c5a28..c4f7b3ed 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -2,7 +2,8 @@ use serde_json::{Value, json}; use texturecraft_engine::core::{ - BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, LinearGradientParameters, Source, UvRandomColorParameters, + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, EffectKind, Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, + LinearGradientParameters, Source, UvCheckerParameters, UvRandomColorParameters, }; use texturecraft_engine::{Session, execute}; @@ -148,3 +149,16 @@ fn uv_random_color_takes_its_mode_and_gradient() { assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); } + +#[test] +fn uv_checker_takes_its_controls() { + let mut session = session(); + let params = + json!({"generator": "UV Checker", "checkerColorMode": "random", "checkerGridTile": 40, "checkerGridOpacity": 0.25, "uvBordersColor": [0.0, 1.0, 0.0]}); + let effect = add(&mut session, params); + + let expected = + UvCheckerParameters { random_colors: true, grid_tile: 24, grid_opacity: 0.25, border_color: [0.0, 1.0, 0.0], ..UvCheckerParameters::default() }; + assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvChecker(expected)), "the grid tile stops at 24"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "checkerColorMode": "plaid"})).is_err()); +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 51c9d7e9..cee102fa 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -105,6 +105,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { (tr("Rust in occluded areas, running down in drips."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) } GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), + GeneratorKind::UvChecker => (tr("A checker over the UV layout."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; // Wrapped rows: a long line must not widen the panel past its edge From 90d1c3e7389f33e8b6f759510f8c53c972382046 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:32 +0000 Subject: [PATCH 23/54] Generators: every generator panel on the property sheet, as the approved mockups --- crates/engine/src/orb_preview.rs | 7 +- crates/ui-egui/src/dock.rs | 2 +- crates/ui-egui/src/fill_material_panel.rs | 4 +- crates/ui-egui/src/fill_symmetry_panel.rs | 4 +- crates/ui-egui/src/generator_input_card.rs | 129 +++ crates/ui-egui/src/generator_input_slot.rs | 63 ++ crates/ui-egui/src/generator_panel.rs | 831 +++--------------- crates/ui-egui/src/generator_params.rs | 182 ++++ crates/ui-egui/src/generator_section_rows.rs | 189 ++++ crates/ui-egui/src/generator_slot.rs | 28 +- crates/ui-egui/src/generator_wear_rows.rs | 158 ++++ crates/ui-egui/src/lib.rs | 6 +- crates/ui-egui/src/preview_request.rs | 4 + .../ui-egui/src/property_sheet/axis_rows.rs | 40 +- crates/ui-egui/src/property_sheet/group.rs | 17 + crates/ui-egui/src/property_sheet/mod.rs | 3 + .../src/property_sheet/size_columns.rs | 73 ++ .../property_sheet/size_columns_response.rs | 9 + crates/ui-egui/src/property_sheet/slider.rs | 39 +- .../src/property_sheet/stack_slider.rs | 3 + .../src/property_sheet/switch_control.rs | 2 +- crates/ui-egui/src/resource_slot.rs | 68 -- crates/ui-egui/src/shelf.rs | 2 +- crates/ui-egui/src/shelf_preview.rs | 19 +- crates/ui-egui/src/thumbs.rs | 5 + .../ui-egui/tests/it/curvature_generator.rs | 11 +- crates/ui-egui/tests/it/effect_sliders.rs | 54 +- crates/ui-egui/tests/it/generator_panel.rs | 242 ++--- 28 files changed, 1245 insertions(+), 949 deletions(-) create mode 100644 crates/ui-egui/src/generator_input_card.rs create mode 100644 crates/ui-egui/src/generator_input_slot.rs create mode 100644 crates/ui-egui/src/generator_params.rs create mode 100644 crates/ui-egui/src/generator_section_rows.rs create mode 100644 crates/ui-egui/src/generator_wear_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/size_columns.rs create mode 100644 crates/ui-egui/src/property_sheet/size_columns_response.rs delete mode 100644 crates/ui-egui/src/resource_slot.rs diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index a0b701a4..4d5d3c70 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -86,13 +86,18 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { + self.generator_of(Generator::new(kind), size) + } + + /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) + pub fn generator_of(&mut self, generator: Generator, size: usize) -> Option>> { if !valid_size(size) { return None; } // Each generator goes on the bare shape, not over the previous mask (self.session.doc, self.session.selected) = self.bare.clone(); - let effects = vec![(EffectKind::Generator(Generator::new(kind)), BlendMode::Normal)]; + let effects = vec![(EffectKind::Generator(generator), BlendMode::Normal)]; let mask = smart_masks::build_mask(&mut self.session.doc.project, MaskBackground::Black, effects); self.session.doc.project.layer_mut(self.layer).ok()?.mask = Some(mask); self.mask_pixels(size) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 26170c32..82b01579 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -3050,7 +3050,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe // Property sheets keep the panel's own edges; only the rows not yet laid out by one get the legacy margin match &effect.kind { - EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); diff --git a/crates/ui-egui/src/fill_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index 1d5b0f9a..b294da01 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -138,7 +138,7 @@ fn resolution_json(resolution: CookResolution) -> Value { } /// The size of the texture set being painted, `fallback` when none is -fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 { +pub(crate) fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 { app.session.doc.project.texture_set(app.session.ts()).map_or(fallback, |texture_set| texture_set.resolution) } @@ -484,7 +484,7 @@ fn procedural_rows( } /// The Resolution band's reading of a pattern's saved output resolution: a size of its own is Fixed, any other follows the texture set -fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution { +pub(crate) fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution { match resolution.mode { ResolutionMode::Custom => CookResolution::Fixed(resolution.output_size(texture_set, texture_set)), _ => CookResolution::Relative(resolution.factor), diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index 58579240..b306c05e 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -90,8 +90,8 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let (mut count_value, mut span_value) = (count as f32, symmetry.span); let mut sliders = [ - StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" }, - StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" }, + StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "", dial: false }, + StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°", dial: false }, ]; let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders); diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs new file mode 100644 index 00000000..2cc9c41f --- /dev/null +++ b/crates/ui-egui/src/generator_input_card.rs @@ -0,0 +1,129 @@ +//! A generator's image input as a slot: what it reads, a picker to replace it with a value, an anchor point or an image, and the way back + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{LayerId, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, mesh_map_color}; +use crate::fill_material_panel::{source_choice, source_tabs}; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::resource_picker; +use crate::source_choice::SourceChoice; +use crate::theme::Tokens; + +/// Glyph size on a slot picture standing for an anchor point +const GLYPH_SIZE: f32 = 12.0; + +/// The slot of input `slot` of generator effect `id` on `layer`, holding `source`: a card of its own, or a row of the card open now when `in_card` +pub(crate) fn input_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), slot: GeneratorInputSlot, source: Option<&Source>, in_card: bool) { + let tokens = Tokens::get(sheet.ui.ctx()); + let input = slot.id(); + let line = match (source, slot) { + (None, GeneratorInputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + (None, _) => tr("Empty").to_string(), + (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), + (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), + (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), + (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), + }; + + let image = match source { + Some(Source::Image { name, .. }) => app.session.images.get(name).map(|image| app.thumbs.image(sheet.ui.ctx(), name, image)), + _ => None, + }; + let baked = match slot { + GeneratorInputSlot::Map(map) => app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)), + _ => false, + }; + let picture = |painter: &Painter, rect: Rect| { + let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); + match (source, slot) { + (Some(Source::Image { .. }), _) => match &image { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, 0.0, tokens.button); + } + }, + (Some(Source::Uniform(value)), _) => { + painter.rect_filled(rect, 0.0, gray(value[0])); + } + (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { + painter.rect_filled(rect, 0.0, tokens.button); + let glyph = egui_phosphor::regular::ANCHOR; + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(GLYPH_SIZE), tokens.text_dim); + } + (None, GeneratorInputSlot::Map(map)) => { + painter.rect_filled(rect, 0.0, if baked { mesh_map_color(map) } else { tokens.button }); + } + (None, _) => { + painter.rect_filled(rect, 0.0, tokens.button); + } + } + }; + + // A mesh map input goes back to its map with ⟲; an image slot empties with × + let map_slot = matches!(slot, GeneratorInputSlot::Map(_)); + let response = match (in_card, map_slot) { + (true, _) => sheet.slot_in_card(&picture, slot.title(), &line, source.is_some()), + (false, true) => sheet.slot(&picture, slot.title(), &line, None, false, source.is_some()), + (false, false) => sheet.slot(&picture, slot.title(), &line, None, source.is_some(), false), + }; + if response.clear || response.reset { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if let Some(name) = image_drop(sheet.ui, &response.pick) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + + let popup = sheet.ui.make_persistent_id(("generator_input", id, input)); + if response.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = source.map(|source| source_choice(&app.session, source)); + let tabs = || { + let anchors = if slot.takes_anchor() { anchors_below(&app.session.doc.project, layer) } else { Vec::new() }; + let mut tabs = source_tabs(&app.session, &anchors, tokens.button, false); + + // A generator's inputs read images, values and anchor points, never a procedural + for tab in &mut tabs { + for group in &mut tab.groups { + group.items.retain(|item| !matches!(item.id, SourceChoice::Procedural(_))); + } + tab.groups.retain(|group| !group.items.is_empty()); + } + tabs.retain(|tab| !tab.groups.is_empty()); + tabs + }; + let picked = resource_picker::show(&response.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); + match picked.filter(|choice| Some(choice) != current.as_ref()) { + Some(SourceChoice::Uniform) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); + } + Some(SourceChoice::Image(name)) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + Some(SourceChoice::Anchor(anchor)) => { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + Some(SourceChoice::Import) => crate::menus::invoke(app, sheet.ui.ctx(), "resource.import"), + Some(SourceChoice::Procedural(_) | SourceChoice::Alpha(_)) | None => {} + } + + if let Some(Source::Uniform(value)) = source { + let mut gray = value[0]; + let edit = sheet.ramp(tr("Value"), &mut gray, 0.0..=1.0); + if edit.invert { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": 1.0 - gray})); + } else if let Some(merge) = edit.changed { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": gray, "merge": merge})); + } + } + if !in_card { + sheet.close_card(); + } +} diff --git a/crates/ui-egui/src/generator_input_slot.rs b/crates/ui-egui/src/generator_input_slot.rs new file mode 100644 index 00000000..0e145a6f --- /dev/null +++ b/crates/ui-egui/src/generator_input_slot.rs @@ -0,0 +1,63 @@ +//! What one image input of a generator replaces or holds + +use texturecraft_engine::core::{BakedMap, Generator, Source}; + +use crate::i18n::{baked_map_label, tr}; + +/// An image input of a generator: a mesh map it reads, or one of the images its switches add +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum GeneratorInputSlot { + Map(BakedMap), + Texture, + Grunge, + MicroHeight, + MicroNormal, +} + +impl GeneratorInputSlot { + /// The input's name in `effect.set` + pub(crate) fn id(self) -> &'static str { + match self { + GeneratorInputSlot::Map(map) => map.id(), + GeneratorInputSlot::Texture => "texture", + GeneratorInputSlot::Grunge => "grunge", + GeneratorInputSlot::MicroHeight => texturecraft_engine::micro_params::MICRO_HEIGHT_INPUT, + GeneratorInputSlot::MicroNormal => texturecraft_engine::micro_params::MICRO_NORMAL_INPUT, + } + } + + pub(crate) fn title(self) -> &'static str { + match self { + GeneratorInputSlot::Map(map) => tr(baked_map_label(map)), + GeneratorInputSlot::Texture => tr("Texture"), + GeneratorInputSlot::Grunge => tr("Custom Grunge"), + GeneratorInputSlot::MicroHeight => tr("Micro Height"), + GeneratorInputSlot::MicroNormal => tr("Micro Normal"), + } + } + + /// The value a slot set to a uniform value starts at + pub(crate) fn neutral(self) -> f32 { + match self { + GeneratorInputSlot::Map(map) => map.neutral()[0], + GeneratorInputSlot::MicroHeight | GeneratorInputSlot::MicroNormal => 0.5, + GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge => 0.0, + } + } + + /// Whether it may read an anchor point (the engine computes the micro normal from an image or a value only) + pub(crate) fn takes_anchor(self) -> bool { + self != GeneratorInputSlot::MicroNormal + } + + /// What it holds on `generator`: None reads the mesh map, or leaves an image slot empty + pub(crate) fn source(self, generator: &Generator) -> Option<&Source> { + match self { + GeneratorInputSlot::Map(map) => generator.inputs.get(&map), + GeneratorInputSlot::Texture => generator.texture.as_ref().and_then(|texture| texture.source.as_ref()), + GeneratorInputSlot::Grunge => generator.grunge.as_ref(), + GeneratorInputSlot::MicroHeight => generator.micro.as_ref().and_then(|micro| micro.height_source.as_ref()), + GeneratorInputSlot::MicroNormal => generator.micro.as_ref().and_then(|micro| micro.normal_source.as_ref()), + } + } +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index cee102fa..98d060ee 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,90 +1,143 @@ -//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. +//! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; -use serde_json::{Value, json}; -use texturecraft_engine::core::{ - AxisBlend, BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, LightParameters, OutputResolution, - ResolutionMode, SectionParameters, Source, TextureBlend, TextureLayer, WearParameters, -}; +use egui::{Painter, Rect, TextureHandle}; +use serde_json::json; +use texturecraft_engine::core::{CookResolution, Generator, GeneratorKind, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters}; use crate::TextureCraftApp; -use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; -use crate::i18n::{baked_map_label, tr, trf}; -use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; +use crate::fill_material_panel::{band_size, texture_set_size}; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{defaults_of, differs_from_defaults}; +use crate::generator_section_rows::{global_rows, ramp_rows, section_rows, texture_card}; +use crate::generator_wear_rows::{light_rows, micro_switch_card, wear_rows}; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; -use crate::widgets::{combo, section, slider_edit, slider_edit_with_suffix}; -/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. -const INPUT_TILE_SIZE: f32 = 32.0; -const INPUT_TILE_ROUNDING: f32 = 2.0; -const INPUT_TILE_ICON_SIZE: f32 = 16.0; +/// The width the preview's orb is rendered at, in pixels: sharp at twice the preview's size +const PREVIEW_ORB_PX: usize = 256; -/// Width of a False/True button, so the buttons line up under each other -const TOGGLE_WIDTH: f32 = 136.0; +/// The texture set size a project without one is shown against +const FALLBACK_TEXTURE_SET_SIZE: u32 = 2048; -/// Edge of a light angle's dial, the width of its needle and the radius of its hub -const DIAL_SIZE: f32 = 36.0; -const DIAL_NEEDLE_WIDTH: f32 = 2.0; -const DIAL_HUB_RADIUS: f32 = 2.0; +/// How soon a picture still rendering is looked for again +const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); -/// Closest to a dial's centre a pointer still turns it, so the angle is defined -const DIAL_DEAD_ZONE: f32 = 1.0; +/// The settings of generator effect `id` on `layer` +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, layer: LayerId, id: u64, generator: &Generator) { + PropertySheet::show(ui, ("generator_sheet", id), |sheet| { + sheet.section(tr("Generator"), false); + slot_card(app, sheet, id, generator); -/// The settings of generator effect `id`. -pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { - let tokens = Tokens::get(ui.ctx()); - crate::generator_slot::show(app, ui, id, generator); + let band = sheet.band(tr("Parameters"), true, Some(differs_from_defaults(generator)), None); + if band.reset { + app.run("effect.set", defaults_of(id, generator)); + } + if band.open { + parameters(app, sheet, (layer, id), generator); + } - section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); - section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); - section(ui, "generator_parameters", tr("Parameters"), true, |ui| { - if let Some(defaults) = WearParameters::defaults(generator.kind) { - // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them - wear_parameters(app, ui, id, generator, generator.wear.unwrap_or(defaults)); - } else if let Some(light) = generator.light { - light_parameters(app, ui, id, Some(generator.invert), light); - } else { - global_adjustments(app, ui, id, generator); - if generator.on_earlier_model() { - ramp_parameters(app, ui, id, generator); - } - // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them - if let Some(defaults) = SectionParameters::defaults(generator.kind) { - section_parameters(app, ui, id, generator, generator.section_controls().unwrap_or(defaults)); - texture_parameters(app, ui, id, generator.texture.as_deref().cloned().unwrap_or_default()); - } - if let Some(defaults) = LightParameters::defaults(generator.kind) { - light_parameters(app, ui, id, None, defaults); + let inputs = generator.inputs_in_use(); + if !inputs.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&inputs.len().to_string())).open { + for map in inputs { + let slot = GeneratorInputSlot::Map(*map); + input_card(app, sheet, (layer, id), slot, slot.source(generator), false); } } - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Restore defaults")).clicked() { - app.run("effect.set", defaults_of(id, generator)); - } - }); - }); + + let texture_set = texture_set_size(app, FALLBACK_TEXTURE_SET_SIZE); + if let Some(picked) = crate::resolution_band::resolution_band(sheet, band_size(generator.resolution, texture_set), texture_set) { + let size = match picked { + CookResolution::Relative(factor) => json!({"resolution": format!("{:?}", ResolutionMode::Auto), "resolutionFactor": factor}), + CookResolution::Fixed(size) => json!({"resolution": format!("{:?}", ResolutionMode::Custom), "customResolution": size, "resolutionFactor": 0}), + }; + app.run("effect.set", crate::generator_params::merged(json!({"effect": id}), size)); + } + + if sheet.band(tr("Attributes"), false, None, None).open { + attributes(sheet, generator.kind); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + sheet.caption(tr("Bake mesh maps (Ctrl+Shift+B) for curvature, AO and thickness based generators.")); + } }); - let texture = generator.texture.as_ref().filter(|texture| texture.enabled && SectionParameters::defaults(generator.kind).is_some()); - if !generator.inputs_in_use().is_empty() || texture.is_some() { - section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { - if let Some(texture) = texture { - input_slot(app, ui, (layer, id), InputSlot::Texture, texture.source.as_ref(), false); - } - for map in generator.inputs_in_use() { - input_slot(app, ui, (layer, id), InputSlot::Map(*map), generator.inputs.get(map), generator.detail_in_use().is_some()); - } - }); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps for curvature, AO and thickness based generators."))).color(tokens.warning)); +} + +/// The card naming the generator: its orb and name; a click opens the generator picker +fn slot_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator) { + let ctx = sheet.ui.ctx().clone(); + let thumbnail = app.thumbs.generator(&ctx, generator.kind); + let tokens = Tokens::get(&ctx); + let picture = |painter: &Painter, rect: Rect| orb(painter, rect, thumbnail.as_ref(), &tokens, &ctx); + let slot = sheet.slot(&picture, tr(generator.kind.label()), tr("Generator"), None, false, false); + sheet.close_card(); + crate::generator_slot::picker(app, &slot.pick, id, generator.kind); +} + +/// An orb picture in `rect`, a placeholder while it renders +fn orb(painter: &Painter, rect: Rect, texture: Option<&TextureHandle>, tokens: &Tokens, ctx: &egui::Context) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, 0.0, tokens.button); + ctx.request_repaint_after(PICTURE_POLL); + } } } -/// What a generator kind makes, its category and its tags (read only). -fn attributes(ui: &mut Ui, kind: GeneratorKind) { - let tokens = Tokens::get(ui.ctx()); +/// The Parameters band's rows: the kind's own controls, else the global block and the earlier model's ramp +fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let ctx = sheet.ui.ctx().clone(); + let tokens = Tokens::get(&ctx); + let kind = generator.kind; + + // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before + let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); + let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); + let preview = match (kind, generator.detail_in_use()) { + (GeneratorKind::Curvature, Some(detail)) => ShelfPreview::Curvature { mode: detail.mode, solo }, + _ => ShelfPreview::Generator(kind), + }; + let texture = app.thumbs.generator_picture(&ctx, preview, PREVIEW_ORB_PX); + + // A size shows the whole preview until its own render arrives + let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); + let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + + if let Some(defaults) = WearParameters::defaults(kind) { + // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them + wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); + return; + } + if let Some(light) = generator.light { + light_rows(app, sheet, id, Some(generator.invert), light, &picture); + return; + } + + global_rows(app, sheet, id, generator, &picture); + if generator.on_earlier_model() { + ramp_rows(app, sheet, id, generator); + } + + // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them + if let Some(defaults) = SectionParameters::defaults(kind) { + solo = None; + section_rows(app, sheet, id, generator, generator.section_controls().unwrap_or(defaults), &mut solo); + texture_card(app, sheet, (layer, id), generator.texture.as_deref().cloned().unwrap_or_default()); + micro_switch_card(app, sheet, (layer, id), generator); + sheet.ui.data_mut(|data| data.insert_temp(solo_id, solo)); + } + if let Some(defaults) = LightParameters::defaults(kind) { + light_rows(app, sheet, id, None, defaults, &picture); + } +} + +/// What a generator kind makes, its category and its tags (read only) +fn attributes(sheet: &mut PropertySheet<'_>, kind: GeneratorKind) { let (description, tags) = match kind { GeneratorKind::EdgeWear => (tr("Worn metal edges, scratched."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), GeneratorKind::FiberGlassEdgeWear => (tr("Worn fibreglass edges."), [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")]), @@ -107,637 +160,7 @@ fn attributes(ui: &mut Ui, kind: GeneratorKind) { GeneratorKind::UvRandomColor => (tr("A random value per UV island."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), GeneratorKind::UvChecker => (tr("A checker over the UV layout."), [tr("mask"), tr("generator"), tr("grayscale"), tr("uv")]), }; - - // Wrapped rows: a long line must not widen the panel past its edge - let tags = tags.join(", "); - for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { - ui.horizontal_top(|ui| { - ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); - ui.add(egui::Label::new(value).wrap()); - }); - } -} - -/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. -fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { - let tokens = Tokens::get(ui.ctx()); - combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { - for mode in ResolutionMode::ALL { - if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); - } - } - }) - .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); - if resolution.mode == ResolutionMode::Custom { - combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { - for size in OutputResolution::CUSTOM_SIZES { - if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { - app.run("effect.set", json!({"effect": id, "customResolution": size})); - } - } - }); - } - combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { - for factor in OutputResolution::FACTORS { - if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { - app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); - } - } - }) - .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); - - let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; - - let (smallest, largest) = texture_set - .uv_tiles - .iter() - .map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)) - .fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size))); - let (smallest, largest) = if largest == 0 { - let size = resolution.output_size(texture_set.resolution, texture_set.resolution); - (size, size) - } else { - (smallest, largest) - }; - let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") }; - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); - }) - .response - .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); -} - -/// Global invert, blur, balance and contrast: what every generator applies to its finished value. -fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let (mut invert, mut global) = (generator.invert, generator.global); - let invert_edit = true_false(ui, tr("Global invert"), &mut invert).then_some(false); - let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); - let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); - let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); - if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { - app.run( - "effect.set", - json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), - ); - } -} - -/// The wear controls of generator effect `id` in the reference app's order, showing `wear` -fn wear_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, wear: WearParameters) { - seed_row(app, ui, id, generator.seed); - let mut invert = generator.invert; - if true_false(ui, tr("Invert"), &mut invert) { - app.run("effect.set", json!({"effect": id, "invert": invert})); - } - - let dirt = generator.kind == GeneratorKind::Dirt; - let (level_label, contrast_label) = if dirt { (tr("Dirt level"), tr("Dirt contrast")) } else { (tr("Wear level"), tr("Wear contrast")) }; - let mut edited = wear; - let mut edit = slider_edit(ui, level_label, &mut edited.level, 0.0..=1.0, 2); - edit = edit.or(slider_edit(ui, contrast_label, &mut edited.contrast, 0.0..=1.0, 2)); - let triplanar_edit = true_false(ui, tr("Use triplanar"), &mut edited.triplanar).then_some(false); - edit = edit.or(triplanar_edit).or(slider_edit(ui, tr("Triplanar blending contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Grunge amount"), &mut edited.grunge_amount, 0.0..=1.0, 2)); - if generator.kind != GeneratorKind::FiberGlassEdgeWear { - edit = edit.or(slider_edit(ui, tr("Grunge scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); - } - if dirt { - edit = edit.or(slider_edit(ui, tr("Edges masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); - } else { - edit = edit.or(slider_edit(ui, tr("Edges smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Ambient occlusion masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Curvature weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); - } - - if let Some(merge) = edit { - let mut params = wear_params(generator.kind, &edited); - params["effect"] = json!(id); - params["merge"] = json!(merge); - app.run("effect.set", params); - } -} - -/// The `effect.set` params that set every wear control a generator of `kind` has to `wear` -fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { - let mut params = json!({ - "wearLevel": wear.level, - "wearContrast": wear.contrast, - "grungeAmount": wear.grunge_amount, - "grungeScale": wear.grunge_scale, - "triplanar": wear.triplanar, - "triplanarContrast": wear.triplanar_contrast, - "edgesSmoothness": wear.edges_smoothness, - "aoMasking": wear.ao_masking, - "curvatureWeight": wear.curvature_weight, - "edgesMasking": wear.edges_masking, - }); - if let Some(params) = params.as_object_mut() { - params.retain(|key, _| texturecraft_engine::mask_cmds::wear_key_applies(kind, key)); - } - params -} - -/// An on/off control as the reference app draws it: the name, then a full-width button reading False or True; returns whether it was clicked -fn true_false(ui: &mut Ui, label: &str, value: &mut bool) -> bool { - let mut clicked = false; - ui.horizontal(|ui| { - ui.label(label); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let text = if *value { tr("True") } else { tr("False") }; - if ui.add_sized([TOGGLE_WIDTH, ui.spacing().interact_size.y], egui::Button::new(text)).clicked() { - *value = !*value; - clicked = true; - } - }); - }); - clicked -} - -/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. -fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); - let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); - let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); - let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), - ); - } - seed_row(app, ui, id, generator.seed); -} - -/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. -fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { - let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); - let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); - ui.horizontal(|ui| { - ui.label(tr("Seed")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { - typing = !typing; - } - if typing { - let mut typed = seed; - let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); - if field.changed() { - // The later changes of one drag continue its first undo step - let merge = field.dragged() && !field.drag_started(); - app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); - } - } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { - app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); - } - }); - }); - ui.data_mut(|data| data.insert_temp(typing_id, typing)); -} - -/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. -fn defaults_of(id: u64, generator: &Generator) -> Value { - let kind = generator.kind; - let defaults = Generator::new(kind); - let params = json!({ - "effect": id, - "seed": defaults.seed, - "invert": defaults.invert, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - }); - - // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model - let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); - let own = match (&defaults.wear, &defaults.section, &defaults.light) { - (Some(wear), _, _) => wear_params(kind, wear), - (None, _, Some(light)) => light_params(light), - // The texture's controls only once it has them: its image stays in its slot - (None, Some(section), None) if generator.texture.is_some() => { - merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) - } - (None, Some(section), None) => merged(section_params(kind, section), global), - (None, None, None) => json!({ - "level": defaults.level, - "softness": defaults.softness, - "noise": defaults.noise_amount, - "noiseScale": defaults.noise_scale, - "offset": defaults.offset, - "direction": defaults.direction, - "blur": defaults.global.blur, - "balance": defaults.global.balance, - "contrast": defaults.global.contrast, - }), - }; - let mut params = merged(params, own); - if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { - params["mode"] = json!(format!("{:?}", detail.mode)); - params["sizes"] = json!(detail.weights); - } - params -} - -/// The keys of `extra` added to the object `params` -fn merged(mut params: Value, extra: Value) -> Value { - if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { - params.extend(extra); - } - params -} - -/// The section controls of generator effect `id` under the kind's own heading, showing `shown` -fn section_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, shown: SectionParameters) { - let kind = generator.kind; - let title = match kind { - GeneratorKind::Curvature => tr("Curvature"), - GeneratorKind::AmbientOcclusion => tr("Ambient occlusion"), - GeneratorKind::Position => tr("Position"), - _ => tr("World space normal"), - }; - section(ui, "generator_section", title, true, |ui| { - let mut edited = shown; - let mut edit = true_false(ui, tr("Invert"), &mut edited.invert).then_some(false); - if kind == GeneratorKind::Curvature { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if SectionParameters::has_blur(kind) { - edit = edit.or(slider_edit(ui, tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); - } - if SectionParameters::has_balance(kind) { - edit = edit.or(slider_edit(ui, tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); - } - edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); - if SectionParameters::has_brightness(kind) { - edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); - } - if SectionParameters::has_axes(kind) { - let titles = [tr("Right to left"), tr("Top to bottom"), tr("Front to back")]; - for (index, (axis, title)) in edited.axes.iter_mut().zip(titles).enumerate() { - // Each axis's dropdown needs its own id: the dropdown's id comes from its label - ui.push_id(("generator_axis", index), |ui| { - section(ui, "generator_axis", title, true, |ui| { - edit = edit.or(true_false(ui, tr("Invert"), &mut axis.invert).then_some(false)); - combo(ui, tr("Blending mode"), axis_blend_label(axis.blend), |ui| { - for blend in AxisBlend::ALL { - if ui.selectable_label(blend == axis.blend, axis_blend_label(blend)).clicked() { - axis.blend = blend; - edit = Some(false); - } - } - }); - }); - edit = edit.or(slider_edit(ui, title, &mut axis.weight, 0.0..=1.0, 2)); - }); - } - } - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); - } - }); -} - -/// The `effect.set` params that set every section control a generator of `kind` has to `section` -fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { - let mut params = json!({ - "sectionInvert": section.invert, - "sectionBlur": section.blur, - "sectionBalance": section.balance, - "sectionContrast": section.contrast, - "sectionBrightness": section.brightness, - }); - if let Some(params) = params.as_object_mut() { - for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { - params.insert(format!("{name}Invert"), json!(axis.invert)); - params.insert(format!("{name}Blend"), json!(axis.blend.id())); - params.insert(format!("{name}Weight"), json!(axis.weight)); - } - params.retain(|key, _| texturecraft_engine::mask_cmds::section_key_applies(kind, key)); - } - params -} - -/// The translated name of axis blending mode `blend` -/// Use Texture and, once it is on, the texture's controls and its opacity -fn texture_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, shown: TextureLayer) { - let mut edited = shown; - let mut edit = true_false(ui, tr("Use texture"), &mut edited.enabled).then_some(false); - if edited.enabled { - section(ui, "generator_texture", tr("Texture"), true, |ui| { - edit = edit.or(true_false(ui, tr("Invert"), &mut edited.invert).then_some(false)); - combo(ui, tr("Grayscale conversion"), tr(edited.grayscale.label()), |ui| { - for mode in GeneratorGrayscale::ALL { - if ui.selectable_label(mode == edited.grayscale, tr(mode.label())).clicked() { - edited.grayscale = mode; - edit = Some(false); - } - } - }); - combo(ui, tr("Blending mode"), tr(edited.blend.label()), |ui| { - for blend in TextureBlend::ALL { - if ui.selectable_label(blend == edited.blend, tr(blend.label())).clicked() { - edited.blend = blend; - edit = Some(false); - } - } - }); - edit = edit.or(slider_edit(ui, tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); - edit = edit.or(true_false(ui, tr("Triplanar"), &mut edited.triplanar).then_some(false)); - edit = edit.or(slider_edit(ui, tr("Triplanar contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); - }); - edit = edit.or(slider_edit(ui, tr("Texture opacity"), &mut edited.opacity, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); - } -} - -/// The texture controls as `effect.set` keys (its image is the `texture` input) -fn texture_params(texture: &TextureLayer) -> Value { - json!({ - "useTexture": texture.enabled, - "textureOpacity": texture.opacity, - "textureInvert": texture.invert, - "textureGrayscale": texture.grayscale.id(), - "textureBlend": texture.blend.id(), - "textureScale": texture.scale, - "textureContrast": texture.contrast, - "textureBrightness": texture.brightness, - "textureTriplanar": texture.triplanar, - "textureTriplanarContrast": texture.triplanar_contrast, - }) -} - -fn axis_blend_label(blend: AxisBlend) -> &'static str { - match blend { - AxisBlend::Normal => tr("Normal"), - AxisBlend::Add => tr("Linear Dodge (Add)"), - AxisBlend::Subtract => tr("Subtract"), - AxisBlend::Multiply => tr("Multiply"), - AxisBlend::AddSub => tr("Add/Sub"), - AxisBlend::Max => tr("Max (Lighten)"), - } -} - -/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) -fn light_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, invert: Option, shown: LightParameters) { - if let Some(mut invert) = invert - && true_false(ui, tr("Invert"), &mut invert) - { - app.run("effect.set", json!({"effect": id, "invert": invert})); - } - let mut edited = shown; - let mut edit = angle_row(ui, "generator_light_horizontal", tr("Horizontal angle"), &mut edited.horizontal); - edit = edit.or(angle_row(ui, "generator_light_vertical", tr("Vertical angle"), &mut edited.vertical)); - edit = edit.or(slider_edit(ui, tr("Highlight glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); - edit = edit.or(slider_edit(ui, tr("Highlight level"), &mut edited.highlight_level, 0.0..=1.0, 2)); - edit = edit.or(slider_edit(ui, tr("Light attenuation"), &mut edited.attenuation, 0.0..=1.0, 2)); - if let Some(merge) = edit { - app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); - } -} - -/// The `effect.set` params that set every light control to `light` -fn light_params(light: &LightParameters) -> Value { - json!({ - "lightHorizontal": light.horizontal, - "lightVertical": light.vertical, - "highlightGlossiness": light.glossiness, - "highlightLevel": light.highlight_level, - "lightAttenuation": light.attenuation, - }) -} - -/// A light angle in degrees: its name, then a dial beside an Angle slider; `Some(merge)` when either changes it -fn angle_row(ui: &mut Ui, id: &str, label: &str, degrees: &mut f32) -> Option { - ui.label(label); - ui.push_id(id, |ui| { - ui.horizontal(|ui| { - let dial = angle_dial(ui, label, degrees); - let slider = ui.vertical(|ui| slider_edit_with_suffix(ui, tr("Angle"), degrees, LightParameters::ANGLE_RANGE, 0, "°")).inner; - dial.or(slider) - }) - .inner - }) - .inner -} - -/// A round dial whose needle points at `degrees` (0 on the left, clockwise, as in the reference); dragging it turns it, `Some(merge)` like [`slider_edit`] -fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(egui::vec2(DIAL_SIZE, DIAL_SIZE), egui::Sense::click_and_drag()); - let mut edit = None; - if (response.dragged() || response.clicked()) - && let Some(pointer) = response.interact_pointer_pos() - { - let offset = pointer - rect.center(); - let turned = (-offset.y).atan2(-offset.x).to_degrees().rem_euclid(*LightParameters::ANGLE_RANGE.end()); - if offset.length() > DIAL_DEAD_ZONE && (turned - *degrees).abs() > f32::EPSILON { - *degrees = turned; - // Later frames of one drag share its undo step - edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); - } - } - if response.drag_stopped() || response.clicked() { - ui.data_mut(|data| data.remove_temp::(response.id)); - } - let shown = *degrees; - response.widget_info(|| egui::WidgetInfo::slider(true, f64::from(shown), label)); - - let painter = ui.painter(); - // The rim's stroke stays inside the dial - let radius = (DIAL_SIZE - DIAL_NEEDLE_WIDTH) * 0.5; - painter.circle(rect.center(), radius, tokens.field, egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.button_border)); - let (sin, cos) = degrees.to_radians().sin_cos(); - let tip = rect.center() + egui::vec2(-cos, -sin) * radius; - painter.line_segment([rect.center(), tip], egui::Stroke::new(DIAL_NEEDLE_WIDTH, tokens.accent)); - painter.circle_filled(rect.center(), DIAL_HUB_RADIUS, tokens.text); - edit -} - -/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). -fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let shown = detail.cloned().unwrap_or_default(); - combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { - for mode in CurvatureMode::ALL { - if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { - app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); - } - } - }); - - let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; - let mut weights = shown.weights; - let mut edit = None; - for (weight, name) in weights.iter_mut().zip(names) { - edit = edit.or(slider_edit(ui, name, weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } -} - -/// The translated name of curvature mode `mode`. -fn curvature_mode_label(mode: CurvatureMode) -> &'static str { - match mode { - CurvatureMode::Edges => tr("Edges"), - CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Dual"), - CurvatureMode::Raw => tr("Unprocessed"), - } -} - -/// What an image input slot of a generator replaces: a mesh map it reads, or its texture -#[derive(Clone, Copy)] -enum InputSlot { - Map(BakedMap), - Texture, -} - -impl InputSlot { - /// The input's name in `effect.set` - fn id(self) -> &'static str { - match self { - InputSlot::Map(map) => map.id(), - InputSlot::Texture => "texture", - } - } - - fn title(self) -> &'static str { - match self { - InputSlot::Map(map) => tr(baked_map_label(map)), - InputSlot::Texture => tr("Texture"), - } - } - - /// The value a slot set to a uniform value starts at - fn neutral(self) -> f32 { - match self { - InputSlot::Map(map) => map.neutral()[0], - InputSlot::Texture => 0.0, - } - } -} - -/// One image input: what it reads now, a menu to replace it with a value, an anchor point or an image, and a button to empty it -fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), slot: InputSlot, source: Option<&Source>, detail_sizes: bool) { - let tokens = Tokens::get(ui.ctx()); - let input = slot.id(); - let current = match (source, slot) { - (None, InputSlot::Map(map)) => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), - (None, InputSlot::Texture) | (Some(Source::Uniform(_)), _) => tr("Uniform value").to_string(), - (Some(Source::Image { name, .. }), _) => trf("Image: {name}", &[("name", name)]), - (Some(Source::Anchor { anchor, channel, .. }), _) => anchor_label(app, *anchor, *channel), - (Some(Source::Procedural { .. }), _) => tr("Procedural").to_string(), - }; - let empty_hint = match slot { - InputSlot::Map(_) => tr("Read the mesh map again"), - InputSlot::Texture => tr("Empty the slot"), - }; - let group = ui.group(|ui| { - ui.horizontal(|ui| { - input_tile(app, ui, slot, source); - ui.vertical(|ui| { - ui.label(RichText::new(slot.title()).strong()); - ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); - }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if source.is_some() && ui.button(ic::X).on_hover_text(empty_hint).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - }); - }); - // Each input's menu needs its own id: the dropdown's id comes from its label - ui.push_id(input, |ui| { - combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(&app.session.doc.project, layer); - if let InputSlot::Map(_) = slot - && ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); - } - let uniform = matches!(source, Some(Source::Uniform(_))) || (source.is_none() && matches!(slot, InputSlot::Texture)); - if ui.selectable_label(uniform, tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": slot.neutral()})); - } - for (anchor, label) in &anchors { - if ui - .selectable_label( - matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), - trf("Anchor: {name}", &[("name", label)]), - ) - .clicked() - { - app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); - } - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } - }) - }); - let uniform = match (source, slot) { - (Some(Source::Uniform(value)), _) => Some(value[0]), - (None, InputSlot::Texture) => Some(slot.neutral()), - _ => None, - }; - if let Some(mut value) = uniform - && let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) - { - app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); - } - let replaced_curvature = matches!(slot, InputSlot::Map(BakedMap::Curvature)) && source.is_some_and(|source| !matches!(source, Source::Uniform(_))); - if detail_sizes && replaced_curvature { - ui.label( - RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) - .size(NOTE_FONT_SIZE) - .color(tokens.text_dim), - ); - } - }); - if let Some(name) = image_drop(ui, &group.response) { - app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); - } -} - -/// The picture beside an image input: its image, its value as gray, an icon for an anchor or a procedural, else its mesh map's color (black for an empty texture) -fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, slot: InputSlot, source: Option<&Source>) { - let tokens = Tokens::get(ui.ctx()); - let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); - let painter = ui.painter(); - let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); - let gray = |value: f32| egui::Color32::from_gray((value.clamp(0.0, 1.0) * 255.0).round() as u8); - match (source, slot) { - (Some(Source::Image { name, .. }), _) => match app.session.images.get(name) { - Some(image) => { - let texture = app.thumbs.image(ui.ctx(), name, image); - painter.image(texture.id(), rect, whole, egui::Color32::WHITE); - } - None => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); - } - }, - (Some(Source::Uniform(value)), _) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(value[0])); - } - (Some(Source::Anchor { .. } | Source::Procedural { .. }), _) => { - let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; - painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); - painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); - } - (None, InputSlot::Texture) => { - painter.rect_filled(rect, INPUT_TILE_ROUNDING, gray(slot.neutral())); - } - (None, InputSlot::Map(map)) => { - let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); - painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); - } - } - painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); + sheet.attribute_text(tr("Description"), description); + sheet.attribute(tr("Category"), tr("Generators")); + sheet.attribute(tr("Tags"), &tags.join(", ")); } diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs new file mode 100644 index 00000000..96fc1980 --- /dev/null +++ b/crates/ui-egui/src/generator_params.rs @@ -0,0 +1,182 @@ +//! The `effect.set` keys of a generator's controls, as its panel sends them + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Generator, GeneratorKind, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; +use texturecraft_engine::mask_cmds::{section_key_applies, wear_key_applies}; +use texturecraft_engine::micro_params::micro_key_applies; + +/// The keys of `extra` added to the object `params` +pub(crate) fn merged(mut params: Value, extra: Value) -> Value { + if let (Some(params), Value::Object(extra)) = (params.as_object_mut(), extra) { + params.extend(extra); + } + params +} + +/// Every wear control a generator of `kind` has, set to `wear` +pub(crate) fn wear_params(kind: GeneratorKind, wear: &WearParameters) -> Value { + let mut params = json!({ + "wearLevel": wear.level, + "wearContrast": wear.contrast, + "grungeAmount": wear.grunge_amount, + "grungeScale": wear.grunge_scale, + "triplanar": wear.triplanar, + "triplanarContrast": wear.triplanar_contrast, + "edgesSmoothness": wear.edges_smoothness, + "aoMasking": wear.ao_masking, + "curvatureWeight": wear.curvature_weight, + "edgesMasking": wear.edges_masking, + "useCustomGrunge": wear.custom_grunge, + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| wear_key_applies(kind, key)); + } + params +} + +/// Every section control a generator of `kind` has, set to `section` +pub(crate) fn section_params(kind: GeneratorKind, section: &SectionParameters) -> Value { + let mut params = json!({ + "sectionInvert": section.invert, + "sectionBlur": section.blur, + "sectionBalance": section.balance, + "sectionContrast": section.contrast, + "sectionBrightness": section.brightness, + }); + if let Some(params) = params.as_object_mut() { + for (name, axis) in ["rightLeft", "topBottom", "frontBack"].into_iter().zip(§ion.axes) { + params.insert(format!("{name}Invert"), json!(axis.invert)); + params.insert(format!("{name}Blend"), json!(axis.blend.id())); + params.insert(format!("{name}Weight"), json!(axis.weight)); + } + params.retain(|key, _| section_key_applies(kind, key)); + } + params +} + +/// The texture's controls (its image is the `texture` input) +pub(crate) fn texture_params(texture: &TextureLayer) -> Value { + json!({ + "useTexture": texture.enabled, + "textureOpacity": texture.opacity, + "textureInvert": texture.invert, + "textureGrayscale": texture.grayscale.id(), + "textureBlend": texture.blend.id(), + "textureScale": texture.scale, + "textureContrast": texture.contrast, + "textureBrightness": texture.brightness, + "textureTriplanar": texture.triplanar, + "textureTriplanarContrast": texture.triplanar_contrast, + }) +} + +/// Every light control, set to `light` +pub(crate) fn light_params(light: &LightParameters) -> Value { + json!({ + "lightHorizontal": light.horizontal, + "lightVertical": light.vertical, + "highlightGlossiness": light.glossiness, + "highlightLevel": light.highlight_level, + "lightAttenuation": light.attenuation, + }) +} + +/// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) +pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { + let mut params = json!({ + "useMicroDetails": micro.enabled, + "microHeight": micro.height, + "microNormal": micro.normal, + "microCurvatureType": micro.curvature_type.label(), + "microCurvatureIntensity": micro.curvature_intensity, + "microHeightIntensity": micro.height_intensity, + "microAoRadius": micro.ao_radius, + "microAoDepth": micro.ao_depth, + }); + if let Some(params) = params.as_object_mut() { + params.retain(|key, _| micro_key_applies(kind, key)); + } + params +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind; its images stay in their slots +pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { + let kind = generator.kind; + let defaults = Generator::new(kind); + let params = json!({ + "effect": id, + "seed": defaults.seed, + "invert": defaults.invert, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + + // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model + let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); + let own = match (&defaults.wear, &defaults.section, &defaults.light) { + (Some(wear), _, _) => wear_params(kind, wear), + (None, _, Some(light)) => light_params(light), + // The texture's controls only once it has them: its image stays in its slot + (None, Some(section), None) if generator.texture.is_some() => { + merged(merged(section_params(kind, section), global), texture_params(&TextureLayer::default())) + } + (None, Some(section), None) => merged(section_params(kind, section), global), + (None, None, None) => json!({ + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "direction": defaults.direction, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + }), + }; + let mut params = merged(params, own); + if let (None, Some(detail)) = (&defaults.wear, defaults.detail) { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + + // Micro details only once it has them, as the texture's + if generator.micro.is_some() + && let Some(micro) = MicroDetails::defaults(kind) + { + params = merged(params, micro_params(kind, µ)); + } + params +} + +/// Whether Restore defaults would change generator `generator`: its controls differ from its kind's, images and resolution aside +pub(crate) fn differs_from_defaults(generator: &Generator) -> bool { + let mut restored = Generator::new(generator.kind); + restored.resolution = generator.resolution; + restored.inputs = generator.inputs.clone(); + restored.grunge = generator.grunge.clone(); + if let Some(texture) = &generator.texture { + restored.texture = Some(Box::new(TextureLayer { source: texture.source.clone(), ..TextureLayer::default() })); + } + if let Some(micro) = &generator.micro + && let Some(defaults) = MicroDetails::defaults(generator.kind) + { + restored.micro = Some(Box::new(MicroDetails { height_source: micro.height_source.clone(), normal_source: micro.normal_source.clone(), ..defaults })); + } + restored.controls = generator.controls.clone(); + + // Saved before the wear, section or light controls: the earlier model's own values count + if generator.wear.is_none() { + restored.wear = None; + } + if generator.section.is_none() { + restored.section = None; + } + if generator.light.is_none() { + restored.light = None; + } + if generator.detail.is_none() { + restored.detail = None; + } + restored != *generator +} diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs new file mode 100644 index 00000000..0e7533a8 --- /dev/null +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -0,0 +1,189 @@ +//! The Parameters rows of Curvature, Ambient Occlusion, Position and World Space Normals: the global block, the kind's own card, its axes, Use Texture; and the earlier model's ramp + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{ + AxisBlend, CurvatureDetail, CurvatureMode, Generator, GeneratorGrayscale, GeneratorKind, LayerId, SectionParameters, TextureBlend, TextureLayer, +}; + +use crate::TextureCraftApp; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{merged, section_params, texture_params}; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::AXIS_COLORS; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// Global Invert, then the preview beside Global Blur, Balance and Contrast: what every generator applies to its finished value +pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); + let mut stack = + [stacked(tr("Global Blur"), &mut global.blur), stacked(tr("Global Balance"), &mut global.balance), stacked(tr("Global Contrast"), &mut global.contrast)]; + let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + if let Some(merge) = invert_edit.or(stack_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// The kind's own card (Curvature's mode and sizes in it), then one card per axis, showing `shown`; `solo` keeps the Curvature size under the pointer for the preview +pub(crate) fn section_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, shown: SectionParameters, solo: &mut Option) { + let kind = generator.kind; + let title = match kind { + GeneratorKind::Curvature => tr("Curvature"), + GeneratorKind::AmbientOcclusion => tr("Ambient Occlusion"), + GeneratorKind::Position => tr("Position Gradient"), + _ => tr("World Space Normal"), + }; + let mut edited = shown; + let mut edit = None; + if sheet.card(title, Some(true)) { + edit = sheet.toggle(tr("Invert"), &mut edited.invert).then_some(false); + if kind == GeneratorKind::Curvature { + *solo = curvature_detail_rows(app, sheet, id, generator.detail.as_ref()); + } + if SectionParameters::has_blur(kind) { + edit = edit.or(sheet.slider(tr("Blur"), &mut edited.blur, SectionParameters::BLUR_RANGE, 2)); + } + if SectionParameters::has_balance(kind) { + edit = edit.or(sheet.slider(tr("Balance"), &mut edited.balance, 0.0..=1.0, 2)); + } + edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + if SectionParameters::has_brightness(kind) { + edit = edit.or(sheet.signed_slider(tr("Brightness"), &mut edited.brightness, SectionParameters::BRIGHTNESS_RANGE, 2)); + } + } + sheet.close_card(); + + if SectionParameters::has_axes(kind) { + let axes = [("X", tr("Right to Left")), ("Y", tr("Top To Bottom")), ("Z", tr("Front to Back"))]; + for ((axis, (letter, name)), tint) in edited.axes.iter_mut().zip(axes).zip(AXIS_COLORS) { + edit = edit.or(sheet.axis_card((letter, tint), name, &mut axis.weight, 0.0..=1.0, 2)); + edit = edit.or(sheet.toggle(tr("Invert"), &mut axis.invert).then_some(false)); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), axis.blend, &AxisBlend::ALL, |blend| axis_blend_label(blend).to_string(), None) { + axis.blend = picked; + edit = Some(false); + } + sheet.close_card(); + } + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), section_params(kind, &edited))); + } +} + +/// Curvature's Mode, each mode pictured, and its detail sizes as columns (`detail` None: saved before detail sizes); returns the size under the pointer +fn curvature_detail_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, detail: Option<&CurvatureDetail>) -> Option { + let shown = detail.cloned().unwrap_or_default(); + let ctx = sheet.ui.ctx().clone(); + let pictures: Vec<_> = CurvatureMode::ALL + .into_iter() + .map(|mode| (mode, app.thumbs.generator_picture(&ctx, crate::shelf_preview::ShelfPreview::Curvature { mode, solo: None }, MODE_PICTURE_PX))) + .collect(); + let draw = |painter: &Painter, rect: Rect, mode: CurvatureMode| { + if let Some((_, Some(texture))) = pictures.iter().find(|(shown, _)| *shown == mode) { + painter.image(texture.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } + }; + let name = |mode: CurvatureMode| curvature_mode_label(mode).to_string(); + if let (Some(mode), _) = sheet.dropdown(tr("Mode"), shown.mode, &CurvatureMode::ALL, name, Some(&draw)) { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + + let names = [tr("Sharp"), tr("Fine"), tr("Soft"), tr("Medium"), tr("Large"), tr("Big"), tr("Huge")]; + let mut weights = shown.weights; + let columns = sheet.size_columns(&names, &mut weights); + if let Some((_, merge)) = columns.edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + columns.hovered +} + +/// The width a Mode picture is rendered at, in pixels: sharp at twice the dropdown's picture +const MODE_PICTURE_PX: usize = 48; + +/// Use Texture's switch card: while on, the texture's slot and controls +pub(crate) fn texture_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), shown: TextureLayer) { + let mut edited = shown.clone(); + let mut edit = sheet.switch_card(tr("Use Texture"), &mut edited.enabled).then_some(false); + if edited.enabled { + input_card(app, sheet, (layer, id), GeneratorInputSlot::Texture, shown.source.as_ref(), true); + edit = edit.or(sheet.toggle(tr("Invert"), &mut edited.invert).then_some(false)); + let grayscale = |mode: GeneratorGrayscale| tr(mode.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Grayscale Conversion"), edited.grayscale, &GeneratorGrayscale::ALL, grayscale, None) { + edited.grayscale = picked; + edit = Some(false); + } + let blend = |blend: TextureBlend| tr(blend.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Blending Mode"), edited.blend, &TextureBlend::ALL, blend, None) { + edited.blend = picked; + edit = Some(false); + } + edit = edit.or(sheet.slider(tr("Scale"), &mut edited.scale, TextureLayer::SCALE_RANGE, 2)); + edit = edit.or(sheet.signed_slider(tr("Contrast"), &mut edited.contrast, -1.0..=1.0, 2)); + edit = edit.or(sheet.signed_slider(tr("Brightness"), &mut edited.brightness, -1.0..=1.0, 2)); + edit = edit.or(sheet.toggle(tr("Triplanar"), &mut edited.triplanar).then_some(false)); + if edited.triplanar { + edit = edit.or(sheet.slider(tr("Triplanar Contrast"), &mut edited.triplanar_contrast, TextureLayer::TRIPLANAR_CONTRAST_RANGE, 2)); + } + edit = edit.or(sheet.slider(tr("Texture Opacity"), &mut edited.opacity, 0.0..=1.0, 2)); + } + sheet.close_card(); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), texture_params(&edited))); + } +} + +/// The earlier model's ramp: where it starts, how soft it is, the noise breaking it up, its offset and its seed +pub(crate) fn ramp_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let mut edit = sheet.slider(tr("Level"), &mut level, 0.0..=1.0, 2); + edit = edit.or(sheet.slider(tr("Softness"), &mut softness, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Noise Amount"), &mut noise, 0.0..=Generator::MAX_NOISE_AMOUNT, 2)); + edit = edit.or(sheet.slider(tr("Noise Scale"), &mut noise_scale, EARLIER_NOISE_SCALE, 1)); + edit = edit.or(sheet.signed_slider(tr("Offset"), &mut offset, -1.0..=1.0, 2)); + if let Some(merge) = edit { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } +} + +/// What the earlier model's Noise Scale slider spans: the noise sizes it was tuned over +const EARLIER_NOISE_SCALE: std::ops::RangeInclusive = 0.1..=64.0; + +/// The translated name of axis blending mode `blend` +fn axis_blend_label(blend: AxisBlend) -> &'static str { + match blend { + AxisBlend::Normal => tr("Normal"), + AxisBlend::Add => tr("Linear Dodge (Add)"), + AxisBlend::Subtract => tr("Subtract"), + AxisBlend::Multiply => tr("Multiply"), + AxisBlend::AddSub => tr("Add/Sub"), + AxisBlend::Max => tr("Max (Lighten)"), + } +} + +/// The translated name of curvature mode `mode` +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Dual"), + CurvatureMode::Raw => tr("Unprocessed"), + } +} diff --git a/crates/ui-egui/src/generator_slot.rs b/crates/ui-egui/src/generator_slot.rs index 99c19557..4d396b4d 100644 --- a/crates/ui-egui/src/generator_slot.rs +++ b/crates/ui-egui/src/generator_slot.rs @@ -1,9 +1,8 @@ -//! The generator slot atop a generator's properties: its orb and name, opening a picker that swaps its kind +//! The generator picker a generator's slot card opens: picking a kind swaps the generator to it -use egui::{Sense, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::core::{Generator, GeneratorKind}; +use texturecraft_engine::core::GeneratorKind; use crate::TextureCraftApp; use crate::i18n::tr; @@ -11,27 +10,16 @@ use crate::picker_group::PickerGroup; use crate::picker_tab::PickerTab; use crate::resource_picker; use crate::resource_picker_item::ResourcePickerItem; -use crate::resource_slot::{ResourceSlot, SLOT_HEIGHT}; use crate::tile_picture::TilePicture; -/// The slot of generator effect `effect`: a pick runs `effect.set {generator}` -pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generator: &Generator) { - let ctx = ui.ctx().clone(); - let current = generator.kind; - let thumbnail = app.thumbs.generator(&ctx, current); - let name = tr(current.label()); - - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); - let popup = ui.make_persistent_id(("generator_picker", effect)); - if response.clicked() { +/// The picker of generator effect `effect` (a `current` generator) under its slot `pick`: a pick runs `effect.set {generator}` +pub(crate) fn picker(app: &mut TextureCraftApp, pick: &egui::Response, effect: u64, current: GeneratorKind) { + let ctx = pick.ctx.clone(); + let popup = pick.id.with(("generator_picker", effect)); + if pick.clicked() { resource_picker::toggle(&ctx, popup); } - let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); - let slot = ResourceSlot { highlighted, focused: response.has_focus(), thumbnail: thumbnail.as_ref(), caption: tr("Generator"), name }; - slot.paint(ui, rect); - let tabs = || { let mut items: Vec> = GeneratorKind::ALL .into_iter() @@ -43,7 +31,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, generato items.sort_by_cached_key(|item| item.label.to_lowercase()); vec![PickerTab { icon: ic::SPARKLE, name: tr("Generators"), groups: vec![PickerGroup { header: None, items }] }] }; - let picked = resource_picker::show(&response, popup, &mut app.thumbs, Some(¤t), true, tabs); + let picked = resource_picker::show(pick, popup, &mut app.thumbs, Some(¤t), true, tabs); if let Some(kind) = picked.filter(|kind| *kind != current) { app.run("effect.set", json!({"effect": effect, "generator": kind.id()})); } diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs new file mode 100644 index 00000000..09273f0b --- /dev/null +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -0,0 +1,158 @@ +//! The Parameters rows of the wear kinds and the Light generator, and the Micro Details rows they share with Curvature and Ambient Occlusion + +use egui::{Painter, Rect}; +use serde_json::json; +use texturecraft_engine::core::{Generator, GeneratorKind, LayerId, LightParameters, MicroCurvatureType, MicroDetails, WearParameters}; + +use crate::TextureCraftApp; +use crate::generator_input_card::input_card; +use crate::generator_input_slot::GeneratorInputSlot; +use crate::generator_params::{light_params, merged, micro_params, wear_params}; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, StackSlider}; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// The wear controls of generator effect `id` on `layer` in the reference's order, showing `wear`; `picture` draws the preview +pub(crate) fn wear_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + generator: &Generator, + wear: WearParameters, + picture: &dyn Fn(&Painter, Rect), +) { + let kind = generator.kind; + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } + let mut invert = generator.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let dirt = kind == GeneratorKind::Dirt; + let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; + let mut edited = wear; + let mut stack = [ + stacked(level_label, &mut edited.level), + stacked(contrast_label, &mut edited.contrast), + stacked(tr("Grunge Amount"), &mut edited.grunge_amount), + ]; + let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + if kind != GeneratorKind::FiberGlassEdgeWear { + edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); + } + if dirt { + edit = edit.or(sheet.slider(tr("Edges Masking"), &mut edited.edges_masking, 0.0..=1.0, 2)); + } else { + edit = edit.or(sheet.slider(tr("Edges Smoothness"), &mut edited.edges_smoothness, WearParameters::EDGES_SMOOTHNESS_RANGE, 2)); + edit = edit.or(sheet.slider(tr("Ambient Occlusion Masking"), &mut edited.ao_masking, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Curvature Weight"), &mut edited.curvature_weight, 0.0..=1.0, 2)); + } + + if sheet.switch_card(tr("Use Triplanar"), &mut edited.triplanar) { + edit = Some(false); + } + if edited.triplanar { + edit = edit.or(sheet.slider(tr("Triplanar Blending Contrast"), &mut edited.triplanar_contrast, 0.0..=1.0, 2)); + } + sheet.close_card(); + + if sheet.switch_card(tr("Use Custom Grunge"), &mut edited.custom_grunge) { + edit = Some(false); + } + if edited.custom_grunge { + input_card(app, sheet, (layer, id), GeneratorInputSlot::Grunge, generator.grunge.as_ref(), true); + } + sheet.close_card(); + + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), wear_params(kind, &edited))); + } + + if sheet.card(tr("Micro Details"), Some(false)) { + micro_rows(app, sheet, (layer, id), generator); + } + sheet.close_card(); +} + +/// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) +pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, invert: Option, shown: LightParameters, picture: &dyn Fn(&Painter, Rect)) { + if let Some(mut invert) = invert + && sheet.toggle(tr("Invert"), &mut invert) + { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + + let mut edited = shown; + let angle = |label, value| StackSlider { label, value, range: LightParameters::ANGLE_RANGE, typed: LightParameters::ANGLE_RANGE, decimals: 0, suffix: "°", dial: true }; + let mut stack = [ + angle(tr("Horizontal Angle"), &mut edited.horizontal), + angle(tr("Vertical Angle"), &mut edited.vertical), + stacked(tr("Light Attenuation"), &mut edited.attenuation), + ]; + let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); + edit = edit.or(sheet.slider(tr("Highlight Glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); + edit = edit.or(sheet.slider(tr("Highlight Level"), &mut edited.highlight_level, 0.0..=1.0, 2)); + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), light_params(&edited))); + } +} + +/// Curvature's and Ambient Occlusion's Use Micro Details: its switch card, holding the micro details rows while on +pub(crate) fn micro_switch_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let Some(defaults) = MicroDetails::defaults(generator.kind) else { return }; + + let mut on = generator.micro.as_ref().map_or(defaults.enabled, |micro| micro.enabled); + if sheet.switch_card(tr("Use Micro Details"), &mut on) { + app.run("effect.set", json!({"effect": id, "useMicroDetails": on})); + } + if on { + micro_rows(app, sheet, (layer, id), generator); + } + sheet.close_card(); +} + +/// The micro details rows of generator effect `id`, inside the card open now: each image's switch with its slot while on, then the kind's settings +fn micro_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), generator: &Generator) { + let kind = generator.kind; + let Some(defaults) = MicroDetails::defaults(kind) else { return }; + + let shown = generator.micro.as_deref().cloned().unwrap_or(defaults); + let mut edited = shown.clone(); + let mut edit = None; + if sheet.toggle(tr("Micro Height"), &mut edited.height) { + edit = Some(false); + } + if edited.height { + input_card(app, sheet, (layer, id), GeneratorInputSlot::MicroHeight, shown.height_source.as_ref(), true); + } + if sheet.toggle(tr("Micro Normal"), &mut edited.normal) { + edit = Some(false); + } + if edited.normal { + input_card(app, sheet, (layer, id), GeneratorInputSlot::MicroNormal, shown.normal_source.as_ref(), true); + } + if MicroDetails::has_curvature(kind) { + let name = |kind: MicroCurvatureType| tr(kind.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Curvature Type"), edited.curvature_type, &MicroCurvatureType::ALL, name, None) { + edited.curvature_type = picked; + edit = Some(false); + } + let range = MicroDetails::curvature_intensity_range(kind); + edit = edit.or(sheet.slider(tr("Curvature Intensity"), &mut edited.curvature_intensity, range, 2)); + edit = edit.or(sheet.slider(tr("Height Details Intensity"), &mut edited.height_intensity, MicroDetails::HEIGHT_INTENSITY_RANGE, 2)); + } + if MicroDetails::has_occlusion(kind) { + edit = edit.or(sheet.slider(tr("AO Radius"), &mut edited.ao_radius, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("AO Depth"), &mut edited.ao_depth, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), micro_params(kind, &edited))); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a8e83fce..d626d5c3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -44,8 +44,13 @@ mod filter_transform_rows; mod folder_properties; pub mod fonts; mod frame_gizmo; +mod generator_input_card; +mod generator_input_slot; mod generator_panel; +mod generator_params; +mod generator_section_rows; mod generator_slot; +mod generator_wear_rows; pub mod gpu; mod gray_slider; mod grid_tile; @@ -125,7 +130,6 @@ mod resolution_band; mod resource_panel; mod resource_picker; mod resource_picker_item; -mod resource_slot; mod round_gizmo; mod running_bake; pub mod saved_search; diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c925ea..f1d78d74 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -25,6 +25,10 @@ impl PreviewRequest { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), ShelfPreview::Generator(kind) => Some(mask_preview_image(self.size_px, &shape.get()?.generator(*kind, self.size_px)?)), + ShelfPreview::Curvature { mode, solo } => { + let generator = ShelfPreview::curvature_generator(*mode, *solo); + Some(mask_preview_image(self.size_px, &shape.get()?.generator_of(generator, self.size_px)?)) + } ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index 5a0f6a22..f16db1b3 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -5,7 +5,7 @@ use std::ops::RangeInclusive; use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; -use super::slider::KNOB_RADIUS; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -31,6 +31,15 @@ const STACK_CAPTION_LINE: f32 = 18.0; const STACK_PART_LINE: f32 = 22.0; const STACK_GAP: f32 = 6.0; +/// An axis card's air above its name row, the edge of its letter chip, the air from the chip to the name, and its full-width track's line +const AXIS_CARD_TOP: f32 = 4.0; +const AXIS_CHIP_SIZE: f32 = 18.0; +const AXIS_CHIP_TO_NAME: f32 = 8.0; +const AXIS_TRACK_LINE: f32 = 20.0; + +/// The letter on an axis chip: dark on every axis color, in every theme +const AXIS_CHIP_LETTER: Color32 = Color32::from_rgb(20, 20, 24); + /// The picture's top below the block's (the first caption's letters), how much shorter it is than the stack, and its air before the controls column const PICTURE_TOP: f32 = 4.0; const PICTURE_SHORTER: f32 = 10.0; @@ -97,6 +106,28 @@ impl PropertySheet<'_> { edit } + /// A card for one axis: its letter on a chip in `tint`, the bold name and the value, then a full-width slider filled in `tint`; the axis's other rows follow, then [`Self::close_card`] + pub(crate) fn axis_card(&mut self, (letter, tint): (&str, Color32), name: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.open_card(); + self.scope = self.named_id("axis_card", name); + self.space(AXIS_CARD_TOP); + let head = self.take(super::ROW_HEIGHT); + let center_y = head.center().y; + let chip = Rect::from_center_size(pos2(self.left + AXIS_CHIP_SIZE / 2.0, center_y), vec2(AXIS_CHIP_SIZE, AXIS_CHIP_SIZE)); + let painter = self.ui.painter(); + painter.rect_filled(chip, egui::CornerRadius::same(super::CONTROL_RADIUS), tint); + painter.text(chip.center(), Align2::CENTER_CENTER, letter, semibold(SMALL_TEXT_SIZE), AXIS_CHIP_LETTER); + painter.text(pos2(chip.right() + AXIS_CHIP_TO_NAME, center_y), Align2::LEFT_CENTER, name, semibold(TEXT_SIZE), self.tokens.text); + + let id = self.next_id(); + let typed = self.value_field(id, name, center_y, *value, &range, decimals, ""); + let track_y = self.take(AXIS_TRACK_LINE).center().y; + let track = Track { start: self.left + KNOB_RADIUS, end: self.right - KNOB_RADIUS, center_y: track_y, zero: None, ramp: false }; + let dragged = self.track_filled(id, name, &track, value, &range, tint); + self.drawn(track_y + KNOB_RADIUS); + Self::apply_typed(value, typed, dragged) + } + /// Draw a picture beside captioned sliders and report the edit on each slider. pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>; N]) -> [Option; N] { let count = sliders.len().max(1) as f32; @@ -117,7 +148,12 @@ impl PropertySheet<'_> { self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; let id = self.next_id(); - let track = Track { start: x0 + KNOB_RADIUS, end: self.track_end(), center_y, zero: None, ramp: false }; + let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; + let end = if slider.dial { dial_x - DIAL_RADIUS - DIAL_AIR } else { self.track_end() }; + let track = Track { start: x0 + KNOB_RADIUS, end, center_y, zero: None, ramp: false }; + if slider.dial { + self.paint_dial(pos2(dial_x, center_y), *slider.value); + } let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); *edit = Self::apply_typed(slider.value, typed, dragged); diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index 7a3085bf..d7d30e03 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -2,6 +2,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, Sense, Shape, Stroke, pos2, vec2} use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; +use super::switch_control::PILL_SIZE; use super::{BandResponse, GROUP_GAP, PropertySheet, ROW_HEIGHT, TEXT_SIZE, open_card::OpenCard}; use crate::theme::semibold; @@ -173,6 +174,22 @@ impl PropertySheet<'_> { open } + /// A card headed by its on/off switch: the bold name, the switch at the right edge; its settings follow while on, then [`Self::close_card`]. Returns whether the switch was clicked + pub(crate) fn switch_card(&mut self, title: &str, on: &mut bool) -> bool { + self.open_card(); + self.scope = self.named_id("card", title); + let rect = self.take(CARD_NAME_CENTER + ROW_HEIGHT / 2.0); + let center_y = rect.top() + CARD_NAME_CENTER; + let hit = Rect::from_x_y_ranges(self.left..=self.right, (center_y - CARD_HIT_HALF_HEIGHT)..=(center_y + CARD_HIT_HALF_HEIGHT)); + let clicked = self.toggle_hit(hit, title, on); + + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + self.pill(pos2(self.right - PILL_SIZE.x / 2.0, center_y), *on, true); + self.drawn(center_y + TITLE_HALF_LINE); + clicked + } + /// A sub-group inside the held card: its bold name on a hairline (no card in a card), a caret when it folds fn inner_caption(&mut self, title: &str, foldable: Option) -> bool { self.space(INNER_CAPTION_AIR); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..0a890707 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -37,6 +37,8 @@ mod section_tabs; #[path = "property_sheet.rs"] mod sheet; mod sheet_measure; +mod size_columns; +mod size_columns_response; mod slider; mod slot; mod slot_response; @@ -66,6 +68,7 @@ pub(crate) use section_tabs::{ full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, }; pub(crate) use sheet::PropertySheet; +pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs new file mode 100644 index 00000000..da810113 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -0,0 +1,73 @@ +//! A row of vertical sliders across the panel, one per size, each with its value above and its name below (Curvature's detail sizes) + +use egui::{Align2, CornerRadius, Rect, Sense, Stroke, WidgetInfo, pos2}; + +use super::slider::{KNOB_RADIUS, KNOB_STROKE}; +use super::{PropertySheet, SMALL_TEXT_SIZE, SizeColumnsResponse}; +use crate::theme::semibold; + +/// A column's value line above its track, the track's length, and its name line under it +const VALUE_LINE: f32 = 20.0; +const COLUMN_TRACK: f32 = 72.0; +const NAME_LINE: f32 = 22.0; + +/// How far a hovered column's face reaches past its value and name lines, and the air between neighbouring faces +const FACE_OVERHANG: f32 = 4.0; +const FACE_AIR: f32 = 2.0; + +/// Width of a column's track and fill +const COLUMN_TRACK_WIDTH: f32 = 2.0; + +impl PropertySheet<'_> { + /// One 0..1 vertical slider per name in `values`, side by side across the panel + pub(crate) fn size_columns(&mut self, names: &[&str], values: &mut [f32]) -> SizeColumnsResponse { + let block = self.take(VALUE_LINE + COLUMN_TRACK + NAME_LINE); + let pitch = (self.right - self.left) / names.len().max(1) as f32; + let (track_top, track_bottom) = (block.top() + VALUE_LINE, block.top() + VALUE_LINE + COLUMN_TRACK); + let tokens = self.tokens; + let mut response = SizeColumnsResponse::default(); + for (index, (name, value)) in names.iter().zip(values.iter_mut()).enumerate() { + let x = self.left + pitch * (index as f32 + 0.5); + let column = Rect::from_min_max(pos2(x - pitch / 2.0, block.top()), pos2(x + pitch / 2.0, block.bottom())); + let id = self.next_id(); + let hit = self.ui.interact(column, id, Sense::click_and_drag()); + hit.widget_info(|| WidgetInfo::slider(true, f64::from(*value), *name)); + + let mut moved = false; + if (hit.dragged() || hit.drag_stopped() || hit.clicked()) + && let Some(pointer) = hit.interact_pointer_pos() + { + let picked = (1.0 - (pointer.y - track_top) / COLUMN_TRACK).clamp(0.0, 1.0); + if picked != *value { + *value = picked; + moved = true; + } + } + if let Some(merge) = crate::widgets::press_edit(self.ui, id, moved) { + response.edit = Some((index, merge)); + } + let hovered = hit.hovered() || hit.dragged(); + if hovered { + response.hovered = Some(index); + } + + let painter = self.ui.painter(); + if hovered { + let face = Rect::from_min_max(pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG)); + painter.rect(face, CornerRadius::same(super::CONTROL_RADIUS), tokens.row_hover, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + } + painter.text(pos2(x, block.top() + VALUE_LINE / 2.0), Align2::CENTER_CENTER, format!("{value:.2}"), semibold(SMALL_TEXT_SIZE), tokens.text); + painter.line_segment([pos2(x, track_top), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.button_border)); + let knob_y = track_bottom - value.clamp(0.0, 1.0) * COLUMN_TRACK; + painter.line_segment([pos2(x, knob_y), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.accent)); + let outline = if hovered { tokens.accent } else { tokens.text }; + painter.circle(pos2(x, knob_y), KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, outline)); + let (font, color) = if hovered { (semibold(SMALL_TEXT_SIZE), tokens.text) } else { (egui::FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) }; + painter.text(pos2(x, track_bottom + NAME_LINE / 2.0), Align2::CENTER_CENTER, *name, font, color); + self.paint_control_focus(&hit); + } + + self.drawn(block.bottom()); + response + } +} diff --git a/crates/ui-egui/src/property_sheet/size_columns_response.rs b/crates/ui-egui/src/property_sheet/size_columns_response.rs new file mode 100644 index 00000000..2ea0031c --- /dev/null +++ b/crates/ui-egui/src/property_sheet/size_columns_response.rs @@ -0,0 +1,9 @@ +/// What a row of size columns did this frame +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SizeColumnsResponse { + /// The column edited and whether the edit continues the previous undo step + pub(crate) edit: Option<(usize, bool)>, + + /// The column under the pointer or being dragged + pub(crate) hovered: Option, +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 98ef953d..6cf51d26 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -13,7 +13,7 @@ use crate::theme::semibold; pub(super) const KNOB_RADIUS: f32 = 5.0; /// Width of a slider's knob outline -const KNOB_STROKE: f32 = 1.5; +pub(super) const KNOB_STROKE: f32 = 1.5; /// Width of a slider's track const TRACK_WIDTH: f32 = 2.0; @@ -22,13 +22,13 @@ const TRACK_WIDTH: f32 = 2.0; const ZERO_TICK_HALF: f32 = 4.0; /// Radius of an angle row's dial -const DIAL_RADIUS: f32 = 8.0; +pub(super) const DIAL_RADIUS: f32 = 8.0; /// The quarter turn back from the screen's 0 rad (pointing right) that points the dial's hand straight up at 0° const DIAL_ZERO_DEGREES: f32 = 90.0; /// Air between the dial and the value, and between the track's end and the dial -const DIAL_AIR: f32 = 6.0; +pub(super) const DIAL_AIR: f32 = 6.0; /// Air between a tinted slider's track end and its right-hand color name const TINT_WORD_AIR: f32 = 8.0; @@ -128,18 +128,23 @@ impl PropertySheet<'_> { let name = lead.text(); let dragged = self.track(id, name, &track, degrees, &range); - let tokens = self.tokens; - let painter = self.ui.painter(); - painter.circle_stroke(pos2(dial_x, center_y), DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); - let turn = (*degrees - DIAL_ZERO_DEGREES).to_radians(); - let hand = pos2(dial_x + DIAL_RADIUS * turn.cos(), center_y + DIAL_RADIUS * turn.sin()); - painter.line_segment([pos2(dial_x, center_y), hand], Stroke::new(TRACK_WIDTH, tokens.text)); + self.paint_dial(pos2(dial_x, center_y), *degrees); let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } + /// The small dial of an angle row centred on `center`, its hand at `degrees` + pub(super) fn paint_dial(&self, center: egui::Pos2, degrees: f32) { + let tokens = self.tokens; + let painter = self.ui.painter(); + painter.circle_stroke(center, DIAL_RADIUS, Stroke::new(KNOB_STROKE, tokens.button_border)); + let turn = (degrees - DIAL_ZERO_DEGREES).to_radians(); + let hand = pos2(center.x + DIAL_RADIUS * turn.cos(), center.y + DIAL_RADIUS * turn.sin()); + painter.line_segment([center, hand], Stroke::new(TRACK_WIDTH, tokens.text)); + } + /// A slider with a small dropdown chip before its value (Intensity's divider); returns the edit and the chip pub(crate) fn slider_with_chip( &mut self, @@ -187,6 +192,20 @@ impl PropertySheet<'_> { /// Paints a track with its knob and moves `value` while it is clicked or dragged pub(super) fn track(&mut self, id: Id, label: impl std::fmt::Display, track: &Track, value: &mut f32, range: &RangeInclusive) -> Option { + let fill = self.tokens.accent; + self.track_filled(id, label, track, value, range, fill) + } + + /// [`Self::track`] whose fill is `fill` (an axis card's in its axis color) + pub(super) fn track_filled( + &mut self, + id: Id, + label: impl std::fmt::Display, + track: &Track, + value: &mut f32, + range: &RangeInclusive, + fill: Color32, + ) -> Option { let (minimum, maximum) = (*range.start(), *range.end()); let span = (maximum - minimum).max(f32::EPSILON); let length = (track.end - track.start).max(1.0); @@ -218,7 +237,7 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); if !track.ramp { painter.line_segment([pos2(track.start, track.center_y), pos2(track.end, track.center_y)], Stroke::new(TRACK_WIDTH, tokens.button_border)); - painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, tokens.accent)); + painter.line_segment([pos2(zero_x.min(knob_x), track.center_y), pos2(zero_x.max(knob_x), track.center_y)], Stroke::new(TRACK_WIDTH, fill)); } if track.zero.is_some() { let tick = [pos2(zero_x, track.center_y - ZERO_TICK_HALF), pos2(zero_x, track.center_y + ZERO_TICK_HALF)]; diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs index b68c602d..9297e9b9 100644 --- a/crates/ui-egui/src/property_sheet/stack_slider.rs +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -17,4 +17,7 @@ pub(crate) struct StackSlider<'a> { /// A unit after the value ("°") pub(crate) suffix: &'a str, + + /// An angle: a small dial before its value, as an angle row has + pub(crate) dial: bool, } diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 7443f9f4..8f700a6d 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -234,7 +234,7 @@ impl PropertySheet<'_> { } /// A toggle's clickable area: a click flips `on`; returns whether it was clicked - fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { + pub(super) fn toggle_hit(&mut self, hit: Rect, label: &str, on: &mut bool) -> bool { let id = self.next_id(); let response = self.ui.interact(hit, id, Sense::click()); if response.clicked() { diff --git a/crates/ui-egui/src/resource_slot.rs b/crates/ui-egui/src/resource_slot.rs deleted file mode 100644 index e814dd27..00000000 --- a/crates/ui-egui/src/resource_slot.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! The box atop an effect's properties that names its resource and opens a picker: thumbnail, a caption over the name, a caret - -use egui::{Align2, FontId, Rect, Stroke, Ui, pos2, vec2}; -use egui_phosphor::regular as ic; - -use crate::theme::Tokens; -use crate::widgets::elided; - -/// The slot's height in points -pub(crate) const SLOT_HEIGHT: f32 = 52.0; -const SLOT_ROUNDING: f32 = 3.0; -const BORDER_WIDTH: f32 = 1.0; -const THUMBNAIL_SIZE: f32 = 40.0; -const THUMBNAIL_INSET: f32 = 6.0; -const CAPTION_FONT_SIZE: f32 = 11.0; -const NAME_FONT_SIZE: f32 = 13.0; -/// Gap between the caption's and the name's centers -const LINE_GAP: f32 = 15.0; -const CARET_INSET: f32 = 14.0; -const CARET_FONT_SIZE: f32 = 14.0; -/// Gap between the slot and its keyboard focus outline -const FOCUS_MARGIN: f32 = 2.0; - -/// What the slot shows and how: highlighted while hovered or its picker is open, outlined while focused -pub(crate) struct ResourceSlot<'a> { - pub highlighted: bool, - pub focused: bool, - pub thumbnail: Option<&'a egui::TextureHandle>, - pub caption: &'a str, - pub name: &'a str, -} - -impl ResourceSlot<'_> { - /// Paints the slot into `rect` - pub(crate) fn paint(&self, ui: &Ui, rect: Rect) { - let tk = Tokens::get(ui.ctx()); - let painter = ui.painter(); - let (fill, border) = if self.highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; - painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); - if self.focused { - painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); - } - - if let Some(texture) = self.thumbnail { - let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); - painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); - } - - // Long names are cut short rather than run under the thumbnail or the caret - let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; - let text_right = rect.right() - CARET_INSET * 2.0; - let text_center_x = (text_left + text_right) * 0.5; - let lines = [(self.caption, CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (self.name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; - for (text, size, color, offset) in lines { - let galley = elided(painter, text, size, color, text_right - text_left); - painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); - } - - let caret_color = if self.highlighted { tk.text } else { tk.text_dim }; - painter.text( - pos2(rect.right() - CARET_INSET, rect.center().y), - Align2::CENTER_CENTER, - ic::CARET_DOWN, - FontId::proportional(CARET_FONT_SIZE), - caret_color, - ); - } -} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index bc34317f..dc64aaae 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,7 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 20491e3a..744c3795 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; +use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -30,6 +30,8 @@ pub enum ShelfPreview { SmartMask(&'static str), /// A mask generator at its defaults, rendered like a smart mask on the worker's baked orb Generator(GeneratorKind), + /// A Curvature generator in `mode`, with only detail size `solo` (finest first) when given, rendered like [`ShelfPreview::Generator`] + Curvature { mode: CurvatureMode, solo: Option }, /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -47,6 +49,18 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// The Curvature generator [`ShelfPreview::Curvature`] renders + pub fn curvature_generator(mode: CurvatureMode, solo: Option) -> Generator { + let mut generator = Generator::new(GeneratorKind::Curvature); + let mut detail = generator.detail.take().unwrap_or_default(); + detail.mode = mode; + if let Some(solo) = solo { + detail.weights = std::array::from_fn(|size| if size == solo { 1.0 } else { 0.0 }); + } + generator.detail = Some(detail); + generator + } + /// Resolve a saved brush's image alpha while the project images are available pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { let settings = read_saved_brush(path); @@ -75,6 +89,7 @@ impl ShelfPreview { ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), + ShelfPreview::Curvature { mode, solo } => format!("curvature:{mode:?}:{solo:?}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -90,7 +105,7 @@ impl ShelfPreview { pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index e847359e..569443c6 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -300,6 +300,11 @@ impl Thumbs { self.worker_rendered(ctx, ShelfPreview::Generator(kind), SPHERE_PX, false) } + /// A generator orb (`preview` a [`ShelfPreview::Generator`] or [`ShelfPreview::Curvature`]) rendered `size_px` wide, kept like a thumbnail; None until the worker returns it + pub fn generator_picture(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + self.worker_rendered(ctx, preview, size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX), false) + } + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) diff --git a/crates/ui-egui/tests/it/curvature_generator.rs b/crates/ui-egui/tests/it/curvature_generator.rs index aae768dc..67ed3eca 100644 --- a/crates/ui-egui/tests/it/curvature_generator.rs +++ b/crates/ui-egui/tests/it/curvature_generator.rs @@ -37,9 +37,9 @@ fn mode_label(mode: CurvatureMode) -> &'static str { } fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) { - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(mode_label(current))).unwrap().click(); + harness.get_by_role_and_label(Role::ComboBox, mode_label(current)).click(); harness.run_steps(2); - harness.get_by_label(mode_label(next)).click(); + harness.get_by_role_and_label(Role::ListBoxOption, mode_label(next)).click(); harness.run_steps(4); } @@ -54,11 +54,10 @@ fn mode_and_detail_controls_apply_and_undo() { assert_eq!(detail(&harness).mode, CurvatureMode::Cavities); let previous = detail(&harness); let history = harness.state().session.history_labels().len(); - harness.get_by_label("Large").scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, "Large").scroll_to_me(); harness.run_steps(3); - let label = harness.get_by_label("Large").rect(); - let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0); - let end = start + egui::vec2(100.0, 0.0); + let column = harness.get_by_role_and_label(Role::Slider, "Large").rect(); + let (start, end) = (egui::pos2(column.center().x, column.bottom() - 30.0), egui::pos2(column.center().x, column.top() + 24.0)); harness.drag_at(start); harness.run_steps(2); harness.hover_at(end); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 30e53995..a191e641 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -38,10 +38,14 @@ fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { } } -/// The track under the slider labelled `label` (the row below the label). +/// The track of the slider labelled `label` fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let label_rect = harness.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) + harness.get_by_role_and_label(Role::Slider, label).rect() +} + +/// The point `share` of the way along `track` +fn along(track: egui::Rect, share: f32) -> egui::Pos2 { + egui::pos2(track.left() + track.width() * share, track.center().y) } #[test] @@ -49,12 +53,12 @@ fn dragging_a_slider_applies_it() { let (mut harness, effect) = selected_generator(); assert_eq!(balance(&harness, effect), 0.5); - let track_rect = track(&harness, "Global balance"); - harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + let track_rect = track(&harness, "Global Balance"); + harness.drag_at(along(track_rect, 0.98)); harness.run_steps(2); - harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.hover_at(along(track_rect, 0.08)); harness.run_steps(2); - harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.drop_at(along(track_rect, 0.08)); harness.run_steps(3); assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); @@ -71,19 +75,19 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { }; let steps = harness.state().session.history_labels().len(); let track_rect = track(&harness, "Level"); - let point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); - harness.drag_at(point_at(10.0)); + let point_at = |share: f32| along(track_rect, share); + harness.drag_at(point_at(0.05)); harness.run_steps(2); let mut last = 0.0; - for x in [60.0, 160.0] { - harness.hover_at(point_at(x)); + for share in [0.3, 0.8] { + harness.hover_at(point_at(share)); harness.run_steps(2); assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); last = level(&harness); } - harness.drop_at(point_at(160.0)); + harness.drop_at(point_at(0.8)); harness.run_steps(3); assert_eq!(level(&harness), last); @@ -93,8 +97,8 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { #[test] fn clicking_a_slider_track_applies_it() { let (mut harness, effect) = selected_generator(); - let track_rect = track(&harness, "Global balance"); - let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + let track_rect = track(&harness, "Global Balance"); + let at = along(track_rect, 0.08); harness.drag_at(at); harness.drop_at(at); harness.run_steps(3); @@ -104,20 +108,22 @@ fn clicking_a_slider_track_applies_it() { /// The number field in the row of the slider labelled `label` fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = harness.get_by_label(label).rect().center().y; + let row = track(harness, label).center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person. fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(harness, "Global balance").focus(); + harness.get_by_label("Global Balance value").click(); + harness.run_steps(2); + number_field(harness, "Global Balance").focus(); harness.run_steps(2); for key in keys { harness.key_press(*key); harness.run_steps(1); } for character in text.chars() { - number_field(harness, "Global balance").type_text(&character.to_string()); + number_field(harness, "Global Balance").type_text(&character.to_string()); harness.run_steps(1); } } @@ -140,12 +146,12 @@ fn a_value_typed_in_the_number_field_applies() { fn a_track_drag_drops_text_typed_in_the_number_field() { let (mut harness, effect) = selected_generator(); type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); - let track_rect = track(&harness, "Global balance"); - harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + let track_rect = track(&harness, "Global Balance"); + harness.drag_at(along(track_rect, 0.98)); harness.run_steps(2); - harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.hover_at(along(track_rect, 0.08)); harness.run_steps(2); - harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.drop_at(along(track_rect, 0.08)); harness.run_steps(2); let dragged = balance(&harness, effect); assert!(dragged < 0.25, "the drag applies: {dragged}"); @@ -175,8 +181,8 @@ fn leaving_the_number_field_unchanged_keeps_the_value() { type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); - assert!(number_field(&harness, "Global balance").is_focused()); + assert_eq!(number_field(&harness, "Global Balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global Balance").is_focused()); harness.key_press(egui::Key::Escape); harness.run_steps(3); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 811582c8..78fc0d9c 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -2,7 +2,7 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; @@ -42,13 +42,14 @@ fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generat } } -/// Drags the track under slider `label` to the right. +/// Drags slider `label` from near its left end to the right fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { - harness.get_by_label(label).scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, label).scroll_to_me(); harness.run_steps(3); - let rect = harness.get_by_label(label).rect(); - let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); - let end = start + egui::vec2(120.0, 0.0); + let rect = harness.get_by_role_and_label(Role::Slider, label).rect(); + let start = egui::pos2(rect.left() + 12.0, rect.center().y); + // Three quarters along: off a 0.5 default, which a drag ending mid-track would land back on + let end = egui::pos2(rect.left() + rect.width() * 0.75, rect.center().y); harness.drag_at(start); harness.run_steps(2); harness.hover_at(end); @@ -57,11 +58,31 @@ fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } +/// A press and release at `at` +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + harness.drag_at(at); + harness.run_steps(1); + harness.drop_at(at); + harness.run_steps(3); +} + +/// Clicks the one live control named `label` with `role` (the panel's Restore defaults and a slot's share a name) +fn click_live(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + let live = |harness: &Harness<'_, TextureCraftApp>| { + harness.get_all_by_role_and_label(role, label).find(|node| !node.accesskit_node().is_disabled()).expect("a live control").rect() + }; + let rect = live(harness); + harness.hover_at(rect.center()); + harness.run_steps(2); + let at = live(harness).center(); + click_at(harness, at); +} + #[test] fn global_blur_applies_as_one_undo_step() { let (mut harness, effect) = harness(false); let history = harness.state().session.history_labels().len(); - drag_slider(&mut harness, "Global blur"); + drag_slider(&mut harness, "Global Blur"); assert!(generator(&harness, effect).global.blur > 0.0); assert_eq!(harness.state().session.history_labels().len(), history + 1); harness.state_mut().session.undo().unwrap(); @@ -71,15 +92,12 @@ fn global_blur_applies_as_one_undo_step() { #[test] fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { let (mut harness, effect) = harness(false); + assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "at its defaults it does nothing"); let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); - harness.run_steps(3); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); } @@ -102,7 +120,7 @@ fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear", "level": 0.4})); assert_eq!(generator(&harness, effect).wear, None, "level keeps it on the earlier model"); - drag_slider(&mut harness, "Wear level"); + drag_slider(&mut harness, "Wear Level"); let wear = generator(&harness, effect).wear.expect("on the wear controls now"); let defaults = WearParameters::defaults(GeneratorKind::EdgeWear).unwrap(); @@ -113,29 +131,31 @@ fn a_wear_control_moves_an_earlier_wear_generator_onto_the_wear_controls() { #[test] fn restore_defaults_keeps_a_wear_generator_on_its_wear_controls() { let (mut harness, effect) = harness_with(false, json!({"generator": "dirt", "grungeAmount": 0.9, "seed": 3})); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Dirt)); } +/// The slot reading `value`: an image input's card +fn slot_reading<'a>(harness: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest::Node<'a> { + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(value)).expect("a slot reading it") +} + #[test] fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { let (mut harness, effect) = harness(false); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.get_by_role_and_label(Role::Button, "Image inputs").click(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + slot_reading(&harness, "Mesh map: Curvature").scroll_to_me(); + harness.run_steps(3); + slot_reading(&harness, "Mesh map: Curvature").click(); harness.run_steps(2); - harness.get_by_label("Uniform value").click(); + harness.get_by_role_and_label(Role::ListBoxOption, "Uniform value").click(); harness.run_steps(3); assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + assert!(slot_reading(&harness, "Uniform value").rect().is_positive()); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Mesh map").click(); - harness.run_steps(3); - assert!(generator(&harness, effect).inputs.is_empty()); + click_live(&mut harness, Role::Button, "Restore defaults"); + assert!(generator(&harness, effect).inputs.is_empty(), "the slot's reset reads the mesh map again"); } /// How many nodes carry `label` @@ -146,14 +166,14 @@ fn count(harness: &Harness<'_, TextureCraftApp>, label: &str) -> usize { #[test] fn each_kind_shows_its_section_rows_and_no_earlier_ones() { let rows = [ - ("curvature", &["Sharp", "Huge", "Brightness", "Global contrast"][..], &["Balance", "Blending mode", "Level"][..]), - ("ambientOcclusion", &["Blur", "Balance", "Global contrast"][..], &["Brightness", "Blending mode", "Level"][..]), - ("position", &["Balance", "Brightness", "Right to left", "Front to back"][..], &["Blur", "Level", "Sharp"][..]), - ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top to bottom"][..], &["Level", "Softness"][..]), + ("curvature", &["Sharp", "Huge", "Brightness", "Global Contrast"][..], &["Balance", "Blending Mode", "Level"][..]), + ("ambientOcclusion", &["Blur", "Balance", "Global Contrast"][..], &["Brightness", "Blending Mode", "Level"][..]), + ("position", &["Balance", "Brightness", "Right to Left", "Front to Back"][..], &["Blur", "Level", "Sharp"][..]), + ("worldSpaceNormals", &["Blur", "Balance", "Brightness", "Top To Bottom"][..], &["Level", "Softness"][..]), ( "direction", - &["Horizontal angle", "Vertical angle", "Highlight glossiness", "Highlight level", "Light attenuation"][..], - &["Global blur", "Level"][..], + &["Horizontal Angle", "Vertical Angle", "Highlight Glossiness", "Highlight Level", "Light Attenuation"][..], + &["Global Blur", "Level"][..], ), ]; for (kind, shown, hidden) in rows { @@ -167,35 +187,23 @@ fn each_kind_shows_its_section_rows_and_no_earlier_ones() { } let (harness, _) = harness_with(false, json!({"generator": "worldSpaceNormals"})); - assert_eq!(count(&harness, "Blending mode"), 3); - for axis in ["Right to left", "Top to bottom", "Front to back"] { - assert_eq!(count(&harness, axis), 2, "{axis}: a section heading and its weight slider"); - } - let (harness, _) = harness_with(false, json!({"generator": "direction"})); - assert_eq!(count(&harness, "Angle"), 2, "an Angle slider beside each dial"); + assert_eq!(harness.get_all_by_role_and_label(Role::ComboBox, "Linear Dodge (Add)").count(), 3, "a blending mode per axis"); let (harness, _) = harness_with(false, json!({"generator": "position", "level": 0.4})); assert!(count(&harness, "Level") > 0 && count(&harness, "Balance") > 0, "the earlier model keeps its level beside the section at its defaults"); } -/// The blending mode dropdown in the Front to back section: the first dropdown below its heading, the topmost "Front to back" -fn front_to_back_dropdown<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let heading = harness.query_all_by_label("Front to back").map(|node| node.rect().top()).fold(f32::INFINITY, f32::min); - let below = harness.get_all_by_role(Role::ComboBox).filter(|node| node.rect().top() > heading); - below.min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() -} - #[test] fn each_axis_has_its_own_blending_mode_dropdown() { let (mut harness, effect) = harness_with(false, json!({"generator": "worldSpaceNormals"})); - let added = |harness: &Harness<'_, TextureCraftApp>| { - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Linear Dodge (Add)")).count() + let lowest = |harness: &Harness<'_, TextureCraftApp>| { + let dropdowns = harness.get_all_by_role_and_label(Role::ComboBox, "Linear Dodge (Add)"); + dropdowns.max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().rect() }; - assert_eq!(added(&harness), 3); - front_to_back_dropdown(&harness).scroll_to_me(); + harness.get_by_role_and_label(Role::Slider, "Front to Back").scroll_to_me(); harness.run_steps(3); - front_to_back_dropdown(&harness).click(); - harness.run_steps(2); - harness.get_by_label("Multiply").click(); + let at = lowest(&harness).center(); + click_at(&mut harness, at); + harness.get_by_role_and_label(Role::ListBoxOption, "Multiply").click(); harness.run_steps(3); let axes = generator(&harness, effect).section.unwrap().axes; @@ -217,30 +225,57 @@ fn a_section_control_moves_an_earlier_generator_onto_the_section_controls() { } #[test] -fn the_light_dial_turns_towards_the_pointer() { - let (mut harness, effect) = harness_with(false, json!({"generator": "direction"})); - harness.get_by_role_and_label(Role::Slider, "Horizontal angle").scroll_to_me(); +fn a_curvature_size_column_sets_its_size_alone_in_one_step() { + let (mut harness, effect) = harness(false); + let before = generator(&harness, effect).detail.unwrap().weights; + let history = harness.state().session.history_labels().len(); + harness.get_by_role_and_label(Role::Slider, "Huge").scroll_to_me(); harness.run_steps(3); - let rect = harness.get_by_role_and_label(Role::Slider, "Horizontal angle").rect(); - let left = egui::pos2(rect.left() + 2.0, rect.center().y); - harness.drag_at(left); + let column = harness.get_by_role_and_label(Role::Slider, "Huge").rect(); + let (low, high) = (egui::pos2(column.center().x, column.bottom() - 30.0), egui::pos2(column.center().x, column.top() + 24.0)); + harness.drag_at(low); harness.run_steps(2); - harness.drop_at(left); + harness.hover_at(high); + harness.run_steps(2); + harness.drop_at(high); harness.run_steps(3); - let horizontal = generator(&harness, effect).light.unwrap().horizontal; - assert!(!(1.0..=359.0).contains(&horizontal), "0 is on the left, as in the reference: {horizontal}"); + + let after = generator(&harness, effect).detail.unwrap().weights; + let last = before.len() - 1; + assert!(after[last] > before[last], "dragged up, Huge rose: {} -> {}", before[last], after[last]); + assert_eq!(after[..last], before[..last], "the other sizes kept theirs"); + assert_eq!(harness.state().session.history_labels().len(), history + 1); } #[test] fn restore_defaults_puts_a_light_back_on_its_defaults() { let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); - harness.run_steps(3); + click_live(&mut harness, Role::Button, "Restore defaults"); assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Direction)); } +#[test] +fn micro_details_show_their_settings_once_switched_on() { + let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion"})); + assert_eq!(count(&harness, "AO Radius"), 0, "they wait for Use Micro Details"); + harness.get_by_role_and_label(Role::CheckBox, "Use Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Use Micro Details").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).micro.is_some_and(|micro| micro.enabled)); + for label in ["Micro Height", "Micro Normal", "AO Radius", "AO Depth"] { + assert!(count(&harness, label) > 0, "{label}"); + } + assert_eq!(count(&harness, "Curvature Type"), 0, "Ambient Occlusion's micro details have no curvature"); + + let (mut harness, _) = harness_with(false, json!({"generator": "dirt", "microHeight": true})); + harness.get_by_role_and_label(Role::Button, "Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + harness.run_steps(3); + assert!(slot_reading(&harness, "Empty").rect().is_positive(), "Micro Height on: its slot, empty"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -251,7 +286,7 @@ fn generator_panel_snapshots() { harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); for section in ["Attributes", "Resolution"] { - harness.get_by_label(section).click(); + harness.get_by_role_and_label(Role::Button, section).click(); harness.run_steps(3); } harness.run_steps(6); @@ -276,66 +311,65 @@ fn generator_panel_snapshots() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn wear_panel_snapshots() { +fn full_set_panel_snapshots() { let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); - for kind in ["edgeWear", "dirt", "fiberGlassEdgeWear"] { - let (mut harness, _) = harness_with(true, json!({"generator": kind})); - harness.run_steps(12); - harness.render().unwrap().save(directory.join(format!("wear-panel-{kind}.png"))).unwrap(); - } -} + let kinds = ["edgeWear", "fiberGlassEdgeWear", "dirt", "direction", "curvature", "ambientOcclusion", "position", "worldSpaceNormals"]; + for kind in kinds { + let (mut harness, _) = harness_with(true, json!({"generator": kind, "seed": 12})); + if kind == "dirt" { + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn section_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); - std::fs::create_dir_all(&directory).unwrap(); - for kind in ["curvature", "ambientOcclusion", "position", "worldSpaceNormals", "direction"] { - let (mut harness, _) = harness_with(true, json!({"generator": kind})); - harness.run_steps(12); - harness.render().unwrap().save(directory.join(format!("section-panel-{kind}.png"))).unwrap(); + // The orbs render on the preview worker + for _ in 0..40 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-{kind}-{name}.png"))).unwrap(); + } } } #[test] fn use_texture_shows_the_texture_rows_and_its_slot() { let (harness, _) = harness_with(false, json!({"generator": "position"})); - assert_eq!(count(&harness, "Use texture"), 1); - for label in ["Grayscale conversion", "Texture opacity", "Triplanar contrast", "Texture"] { - assert_eq!(count(&harness, label), 0, "{label} waits for Use texture"); + assert_eq!(harness.get_all_by_role_and_label(Role::CheckBox, "Use Texture").count(), 1); + let dropdowns = |harness: &Harness<'_, TextureCraftApp>| harness.get_all_by_role(Role::ComboBox).count(); + let closed = dropdowns(&harness); + for label in ["Texture Opacity", "Texture"] { + assert_eq!(count(&harness, label), 0, "{label} waits for Use Texture"); } let (harness, _) = harness_with(false, json!({"generator": "position", "useTexture": true})); - for label in ["Grayscale conversion", "Texture opacity", "Triplanar", "Triplanar contrast", "Scale"] { - assert_eq!(count(&harness, label), 1, "{label}"); + for label in ["Texture Opacity", "Triplanar", "Scale"] { + assert!(count(&harness, label) > 0, "{label}"); } - assert_eq!(count(&harness, "Texture"), 2, "the Texture section and the Texture slot in Image inputs"); - assert_eq!(count(&harness, "Blending mode"), 4, "the texture's beside the three axes'"); + assert_eq!(count(&harness, "Triplanar Contrast"), 0, "it waits for Triplanar"); + assert!(harness.get_by_role_and_label(Role::ComboBox, "Texture").rect().is_positive(), "the texture's slot in its card"); + assert_eq!(dropdowns(&harness), closed + 3, "the texture's slot, Grayscale Conversion and Blending Mode"); let (harness, _) = harness_with(false, json!({"generator": "dirt"})); - assert_eq!(count(&harness, "Use texture"), 0, "wear generators have no texture"); + assert_eq!(count(&harness, "Use Texture"), 0, "wear generators have no texture"); } #[test] -fn the_texture_slot_reads_a_uniform_value_until_it_is_given_one() { +fn the_texture_slot_takes_a_uniform_value_and_empties_again() { let (mut harness, effect) = harness_with(false, json!({"generator": "ambientOcclusion", "useTexture": true})); - let slot = |harness: &Harness<'_, TextureCraftApp>| { - harness.get_all_by_role(Role::ComboBox).filter(|node| node.value().as_deref() == Some("Uniform value")).count() - }; - assert_eq!(slot(&harness), 1, "an empty texture slot is a uniform value"); - assert_eq!(count(&harness, "Value"), 1, "with its value slider"); - - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + slot_reading(&harness, "Empty").scroll_to_me(); harness.run_steps(3); - harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + slot_reading(&harness, "Empty").click(); harness.run_steps(2); - assert_eq!(count(&harness, "Mesh map"), 0, "the texture has no mesh map to go back to"); - // The slot's heading also reads "Uniform value": the menu entry is the button - harness.get_by_role_and_label(Role::Button, "Uniform value").click(); + harness.get_by_role_and_label(Role::ListBoxOption, "Uniform value").click(); harness.run_steps(3); - let texture = generator(&harness, effect).texture.unwrap(); - assert_eq!(texture.source, Some(Source::Uniform([0.0; 3]))); + assert!(matches!(generator(&harness, effect).texture.unwrap().source, Some(Source::Uniform(_)))); + assert!(count(&harness, "Value") > 0, "with its value"); + + click_live(&mut harness, Role::Button, "Clear"); + assert_eq!(generator(&harness, effect).texture.unwrap().source, None); } #[test] @@ -345,7 +379,7 @@ fn texture_panel_snapshots() { std::fs::create_dir_all(&directory).unwrap(); for kind in ["position", "ambientOcclusion"] { let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); - harness.get_by_label("Use texture").scroll_to_me(); + harness.get_by_role_and_label(Role::CheckBox, "Use Texture").scroll_to_me(); harness.run_steps(12); for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; From b40f743878fc3b79474ba218e8fedde985b5abfc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:32 +0000 Subject: [PATCH 24/54] Generators: the seven new kinds in the picker with their panels, gradient stop places for UV Random Color and picking a point on the mesh --- crates/compose/src/uv_islands.rs | 8 +- .../tests/generator_uv_random_color.rs | 21 +- crates/core/src/layer.rs | 14 +- .../src/layer/uv_random_color_parameters.rs | 60 +++- crates/engine/src/commands.rs | 1 + crates/engine/src/distance_params.rs | 16 +- crates/engine/src/generator_pick.rs | 66 ++++ crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 4 +- crates/engine/src/orb_preview.rs | 13 +- .../tests/it/generator_three_d_distance.rs | 59 +++- crates/ui-egui/src/fill_symmetry_panel.rs | 10 +- crates/ui-egui/src/generator_input_card.rs | 9 +- crates/ui-egui/src/generator_input_slot.rs | 13 +- crates/ui-egui/src/generator_kind_rows.rs | 289 ++++++++++++++++++ crates/ui-egui/src/generator_panel.rs | 20 +- crates/ui-egui/src/generator_params.rs | 85 +++++- crates/ui-egui/src/generator_point_pick.rs | 30 ++ crates/ui-egui/src/generator_section_rows.rs | 16 +- crates/ui-egui/src/generator_wear_rows.rs | 26 +- crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/menus.rs | 7 + crates/ui-egui/src/properties_popup.rs | 1 + .../ui-egui/src/property_sheet/axis_rows.rs | 9 +- .../src/property_sheet/number_field.rs | 40 ++- .../src/property_sheet/size_columns.rs | 13 +- crates/ui-egui/src/shelf.rs | 3 +- crates/ui-egui/src/viewport.rs | 22 +- crates/ui-egui/tests/it/generator_panel.rs | 106 ++++++- 29 files changed, 904 insertions(+), 60 deletions(-) create mode 100644 crates/engine/src/generator_pick.rs create mode 100644 crates/ui-egui/src/generator_kind_rows.rs create mode 100644 crates/ui-egui/src/generator_point_pick.rs diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 25a23d10..124ece1b 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters, gradient}; +use texturecraft_core::{UvCheckerParameters, UvRandomColorParameters}; use texturecraft_geom::{NO_TRI, TrianglePartition}; use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; @@ -18,7 +18,9 @@ static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; - settings.extend(random.gradient.iter().flat_map(|color| color.map(f32::to_bits))); + settings.push(random.used_colors().len() as u32); + settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); + settings.extend(random.positions.iter().map(|position| position.to_bits())); CACHE.get_or_build(inp, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; @@ -43,7 +45,7 @@ fn island_values(inp: &Inputs, value_of: impl Fn(u32) -> f32) -> HashMap f32 { let island = island as i32; let color = if random.custom_gradient { - gradient(&random.gradient, cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) + random.at(cell_hash(island, 0, 0, seed)).unwrap_or([0.0; 3]) } else { std::array::from_fn(|channel| cell_hash(island, channel as i32 + 1, 0, seed)) }; diff --git a/crates/compose/tests/generator_uv_random_color.rs b/crates/compose/tests/generator_uv_random_color.rs index 529bc354..a546c627 100644 --- a/crates/compose/tests/generator_uv_random_color.rs +++ b/crates/compose/tests/generator_uv_random_color.rs @@ -97,6 +97,25 @@ fn a_one_color_gradient_colors_every_island_alike() { let mut fixture = fixture(); let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); - let values = mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]] }, 0, &at); + let values = + mask(&mut fixture, UvRandomColorParameters { custom_gradient: true, gradient: vec![[0.1, 0.2, 0.3]], ..UvRandomColorParameters::default() }, 0, &at); assert!(values.iter().all(|value| (value - 0.2).abs() < 1e-5), "the mean of its channels"); } + +#[test] +fn moving_a_gradient_stop_brightens_the_islands() { + let mut fixture = fixture(); + let at: Vec<(u32, u32)> = covered(&fixture).iter().map(|(texel, _)| *texel).collect(); + let black_to_white = |positions: Vec| UvRandomColorParameters { + custom_gradient: true, + gradient: vec![[0.0; 3], [1.0; 3]], + positions, + ..UvRandomColorParameters::default() + }; + + let even = mask(&mut fixture, black_to_white(Vec::new()), 0, &at); + let white_early = mask(&mut fixture, black_to_white(vec![0.0, 0.2]), 0, &at); + let mean = |values: &[f32]| values.iter().sum::() / values.len().max(1) as f32; + assert!(mean(&white_early) > mean(&even), "white reached sooner along the gradient: brighter islands"); + assert!(white_early.iter().zip(&even).all(|(early, even)| early >= even), "no island darker"); +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ccbf8ed9..bc82c7b7 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1044,19 +1044,9 @@ impl GeneratorKind { } } - /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks; the newest kinds wait for their panels) + /// Whether the generator picker offers this kind (Thin areas only loads from saved projects and smart masks) pub fn in_picker(self) -> bool { - !matches!( - self, - GeneratorKind::ThinAreas - | GeneratorKind::ThreeDDistance - | GeneratorKind::ThreeDLinearGradient - | GeneratorKind::UvBorderDistance - | GeneratorKind::GrayscaleConversion - | GeneratorKind::DrippingRust - | GeneratorKind::UvRandomColor - | GeneratorKind::UvChecker - ) + self != GeneratorKind::ThinAreas } /// Whether the kind's result depends on its seed diff --git a/crates/core/src/layer/uv_random_color_parameters.rs b/crates/core/src/layer/uv_random_color_parameters.rs index 156a1be0..07b73e13 100644 --- a/crates/core/src/layer/uv_random_color_parameters.rs +++ b/crates/core/src/layer/uv_random_color_parameters.rs @@ -6,24 +6,74 @@ use serde::{Deserialize, Serialize}; pub struct UvRandomColorParameters { /// Pick each island's color along [`UvRandomColorParameters::gradient`] instead of at random pub custom_gradient: bool, - /// The gradient's colors, evenly spaced (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) + /// The gradient's colors (linear RGB, [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] at most) pub gradient: Vec<[f32; 3]>, + /// Each color's place on the gradient (0..1); colors past the end are evenly spaced (projects saved before have none) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub positions: Vec, + /// How many of the colors the gradient uses (all of them where None): the rest are kept for when the count grows again + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quantity: Option, } impl UvRandomColorParameters { pub const MAX_GRADIENT_COLORS: usize = 16; - /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one + /// The fewest colors the gradient's count goes down to + pub const MIN_QUANTITY: u8 = 2; + + /// Every color brought into 0..1 (non-finite components black), at most [`UvRandomColorParameters::MAX_GRADIENT_COLORS`] of them, and at least one; places into 0..1, one per color at most pub fn clamped(self) -> UvRandomColorParameters { let unit = |value: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { 0.0 }; let gradient: Vec<[f32; 3]> = self.gradient.into_iter().take(UvRandomColorParameters::MAX_GRADIENT_COLORS).map(|color| color.map(unit)).collect(); - UvRandomColorParameters { gradient: if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }, ..self } + let gradient = if gradient.is_empty() { UvRandomColorParameters::default().gradient } else { gradient }; + let positions = self.positions.into_iter().take(gradient.len()).map(unit).collect(); + let quantity = self.quantity.map(|count| count.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8)); + UvRandomColorParameters { gradient, positions, quantity, ..self } + } + + /// The colors the gradient uses: the first [`UvRandomColorParameters::quantity`] of them (all of them where it has none) + pub fn used_colors(&self) -> &[[f32; 3]] { + let used = self.quantity.map_or(self.gradient.len(), usize::from).min(self.gradient.len()); + self.gradient.get(..used).unwrap_or(&self.gradient) + } + + /// Each used color's place on the gradient, evenly spaced where it has none + pub fn used_positions(&self) -> Vec { + let used = self.used_colors().len(); + let last = used.saturating_sub(1).max(1) as f32; + (0..used).map(|index| self.positions.get(index).copied().unwrap_or(index as f32 / last)).collect() + } + + /// The gradient's color at `t` (linear blend) + pub fn at(&self, t: f32) -> Option<[f32; 3]> { + let colors = self.used_colors(); + + // An evenly spaced gradient (projects saved before) takes the path it took then, so it renders bit for bit as before + if self.positions.is_empty() { super::gradient(colors, t) } else { crate::gradient_input::ramp(colors, &self.positions, true, t) } + } + + /// Use the first `wanted` colors: an evenly spaced gradient keeps its places from now on, and each added color starts at 1 as the gradient's color there + pub fn set_quantity(&mut self, wanted: u8) { + let wanted = wanted.clamp(UvRandomColorParameters::MIN_QUANTITY, UvRandomColorParameters::MAX_GRADIENT_COLORS as u8); + // The used colors without a place keep the even place the gradient gave them; hidden colors keep theirs + let even = self.used_positions(); + let placed = self.positions.len(); + self.positions.extend(even.into_iter().skip(placed)); + let fill = self.at(1.0).unwrap_or([1.0; 3]); + let wanted_len = usize::from(wanted); + if self.gradient.len() < wanted_len { + self.gradient.resize(wanted_len, fill); + } + if self.positions.len() < wanted_len { + self.positions.resize(wanted_len, 1.0); + } + self.quantity = Some(wanted); } } impl Default for UvRandomColorParameters { - /// Random colors; the gradient black to white fn default() -> UvRandomColorParameters { - UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]] } + UvRandomColorParameters { custom_gradient: false, gradient: vec![[0.0; 3], [1.0; 3]], positions: Vec::new(), quantity: None } } } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index e34e9327..49cead62 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -117,6 +117,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::generator_pick::specs()); v.extend(crate::mask_export::specs()); v.extend(crate::add_mask_cmds::specs()); v.extend(crate::color_selection_cmds::specs()); diff --git a/crates/engine/src/distance_params.rs b/crates/engine/src/distance_params.rs index 7b620be0..172a1cf2 100644 --- a/crates/engine/src/distance_params.rs +++ b/crates/engine/src/distance_params.rs @@ -23,7 +23,7 @@ pub const DRIPPING_RUST_KEYS: [&str; 7] = ["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"]; /// The UV Random Color controls (it also takes the seed) -pub const UV_RANDOM_COLOR_KEYS: [&str; 2] = ["colorSourceMode", "gradientColors"]; +pub const UV_RANDOM_COLOR_KEYS: [&str; 4] = ["colorSourceMode", "gradientColors", "gradientPositions", "gradientQuantity"]; /// The UV Checker controls (it also takes the seed) pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"]; @@ -185,6 +185,20 @@ fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\""); let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?; random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::>()?; + + // The colors given are the whole gradient: a count after them hides some again + random.quantity = None; + } + if let Some(value) = params.get("gradientPositions") { + let invalid = || bad(command, "`gradientPositions` must be numbers in 0..1, at most one per color"); + let places = value.as_array().filter(|places| places.len() <= random.gradient.len()).ok_or_else(invalid)?; + random.positions = places.iter().map(|place| place.as_f64().map(|place| place as f32).ok_or_else(invalid)).collect::>()?; + } + if params.get("gradientQuantity").is_some() { + let range = UvRandomColorParameters::MIN_QUANTITY..=UvRandomColorParameters::MAX_GRADIENT_COLORS as u8; + let wanted = u64p(params, "gradientQuantity").and_then(|count| u8::try_from(count).ok()).filter(|count| range.contains(count)); + let wanted = wanted.ok_or_else(|| bad(command, format!("`gradientQuantity` must be a whole number from {} to {}", range.start(), range.end())))?; + random.set_quantity(wanted); } generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped()))); Ok(()) diff --git a/crates/engine/src/generator_pick.rs b/crates/engine/src/generator_pick.rs new file mode 100644 index 00000000..b6195451 --- /dev/null +++ b/crates/engine/src/generator_pick.rs @@ -0,0 +1,66 @@ +//! `effect.generator.pickPoint`: a 3D Distance or 3D Linear Gradient point set from where the mesh is under a viewport point + +use serde_json::{Value, json}; +use texturecraft_core::{EffectKind, GeneratorKind, LayerId}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::commands::{CommandSpec, bad, f32p, has_layer, strp, u64p}; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +const CMD: &str = "effect.generator.pickPoint"; + +/// The least extent the mesh's bounds count with, so a flat mesh still places a point (the compositor's own floor) +const MIN_BOUNDS_EXTENT: f32 = 1e-6; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.generator.pickPoint", + "Pick generator point on mesh", + [], + None, + "{effect, point?: distance|start|end (default distance on 3dDistance, start on 3dLinearGradient), x?, y?: viewport pixels (default its centre), viewport?: [w, h]} sets a 3D Distance or 3D Linear Gradient point to the mesh under that pixel, across the mesh's bounds as the generator reads it; returns the point", + has_layer, + pick_point + )] +} + +fn pick_point(session: &mut Session, params: &Value) -> Result { + let effect = u64p(params, "effect").ok_or_else(|| bad(CMD, "`effect` is required"))?; + let kind = match session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.kind, + Some(_) => return Err(bad(CMD, format!("effect {effect} is not a generator"))), + None => return Err(bad(CMD, format!("no effect {effect}"))), + }; + let point = strp(params, "point").map(str::to_ascii_lowercase); + let key = match (kind, point.as_deref()) { + (GeneratorKind::ThreeDDistance, None | Some("distance")) => "distance", + (GeneratorKind::ThreeDLinearGradient, None | Some("start")) => "gradientStart", + (GeneratorKind::ThreeDLinearGradient, Some("end")) => "gradientEnd", + (GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, Some(other)) => { + return Err(bad(CMD, format!("{} has no point `{other}`", kind.label()))); + } + _ => return Err(bad(CMD, format!("{} has no point to pick: only 3D Distance and 3D Linear Gradient have one", kind.label()))), + }; + + let viewport = viewport_of(session, params); + let screen = match (f32p(params, "x"), f32p(params, "y")) { + (Some(x), Some(y)) => Vec2::new(x, y), + _ => viewport * 0.5, + }; + let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0)); + + let edit = match key { + "distance" => json!({"effect": effect, "distanceX": picked[0], "distanceY": picked[1], "distanceZ": picked[2]}), + _ => json!({"effect": effect, key: picked}), + }; + crate::mask_cmds::set(session, &edit)?; + Ok(json!({"effect": effect, "point": picked})) +} + +/// `position` across `bounds` as the 3D generators read the mesh: scaled evenly by the longest side, centred on 0.5 +pub fn across_bounds(position: Vec3, (low, high): (Vec3, Vec3)) -> Vec3 { + let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT); + (position - (low + high) * 0.5) / longest + Vec3::splat(0.5) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 336ba602..82d395ce 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; +pub mod generator_pick; pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 77341832..e7ef1e7a 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...] (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", + "{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...], gradientPositions?: [0..1 per color], gradientQuantity?: 2..16 (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}", has_layer, add_generator ), @@ -1016,7 +1016,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result { } /// Edit visibility, blending, name, effect parameters, or a filter's type -fn set(session: &mut Session, params: &Value) -> Result { +pub(crate) fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; let effect = effect_id(session, params, CMD)?; let blend = blend_param(CMD, params, "blend")?; diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 4d5d3c70..6d03ef36 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, LayerId, MaskBackground}; +use texturecraft_core::{ + BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, + ProceduralKind, Source, +}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; @@ -86,7 +89,13 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { - self.generator_of(Generator::new(kind), size) + let mut generator = Generator::new(kind); + + // Grayscale Conversion grays the image it is given: its picture grays clouds, as it starts with none + if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() { + grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + } + self.generator_of(generator, size) } /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index c4f7b3ed..735bef45 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -144,12 +144,46 @@ fn uv_random_color_takes_its_mode_and_gradient() { let params = json!({"generator": "UV Random Color", "colorSourceMode": "customGradient", "gradientColors": [[2.0, 0.5, 0.0], "#000000"]}); let effect = add(&mut session, params); - let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]] }; + let expected = UvRandomColorParameters { custom_gradient: true, gradient: vec![[1.0, 0.5, 0.0], [0.0; 3]], ..UvRandomColorParameters::default() }; assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvRandomColor(expected)), "colors stay within 0..1"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": []})).is_err()); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "colorSourceMode": "fancy"})).is_err()); } +#[test] +fn uv_random_color_gradient_takes_places_and_a_count() { + let mut session = session(); + let params = json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]}); + let effect = add(&mut session, params); + let random = |session: &Session| match generator(session, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random, + other => panic!("not UV Random Color controls: {other:?}"), + }; + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.25, 0.75]})).unwrap(); + assert_eq!(random(&session).at(0.5), Some([0.5; 3]), "halfway between the two places"); + assert_eq!(random(&session).at(0.1), Some([0.0; 3]), "before the first place: the first color"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors().len(), 3); + assert_eq!(random(&session).used_positions(), vec![0.25, 0.75, 1.0], "an added color starts at the end"); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientColors": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0]]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 2})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 3})).unwrap(); + assert_eq!(random(&session).used_colors()[2], [1.0, 0.0, 0.0], "a hidden color comes back as it was"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientQuantity": 17})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "gradientPositions": [0.0, 0.1, 0.2, 0.3]})).is_err()); +} + +#[test] +fn uv_random_color_saved_without_places_loads_evenly_spaced() { + let saved: UvRandomColorParameters = + serde_json::from_value(json!({"customGradient": true, "gradient": [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]]})).unwrap(); + assert_eq!(saved.used_positions(), vec![0.0, 0.5, 1.0]); + assert_eq!(saved.at(0.5), Some([1.0; 3])); +} + #[test] fn uv_checker_takes_its_controls() { let mut session = session(); @@ -162,3 +196,26 @@ fn uv_checker_takes_its_controls() { assert_eq!(generator(&session, effect).kind_controls(), Some(KindControls::UvChecker(expected)), "the grid tile stops at 24"); assert!(execute(&mut session, "effect.set", &json!({"effect": effect, "checkerColorMode": "plaid"})).is_err()); } + +#[test] +fn picking_on_the_mesh_sets_the_point() { + let mut session = session(); + let distance = add(&mut session, json!({"generator": "3dDistance", "distanceX": 0.0, "distanceY": 0.0, "distanceZ": 0.0})); + let picked = execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance})).unwrap(); + let point = generator(&session, distance).distance_controls().unwrap().point; + assert_eq!(json!(point), picked["point"], "the point is where the mesh is under the viewport's centre"); + assert_ne!(point, [0.0; 3]); + + let gradient = add(&mut session, json!({"generator": "3dLinearGradient"})); + let before = generator(&session, gradient).linear_gradient_controls().unwrap(); + execute(&mut session, "effect.generator.pickPoint", &json!({"effect": gradient, "point": "end"})).unwrap(); + let after = generator(&session, gradient).linear_gradient_controls().unwrap(); + assert_eq!(after.start, before.start, "picking the end leaves the start"); + assert_eq!(json!(after.end), picked["point"], "the same pixel gives the same point"); + + let missed = json!({"effect": distance, "x": 0.0, "y": 0.0, "viewport": [512, 512]}); + assert!(execute(&mut session, "effect.generator.pickPoint", &missed).is_err(), "a corner off the mesh picks nothing"); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "point": "end"})).is_err()); + let curvature = add(&mut session, json!({"generator": "curvature"})); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": curvature})).is_err()); +} diff --git a/crates/ui-egui/src/fill_symmetry_panel.rs b/crates/ui-egui/src/fill_symmetry_panel.rs index b306c05e..a2796f79 100644 --- a/crates/ui-egui/src/fill_symmetry_panel.rs +++ b/crates/ui-egui/src/fill_symmetry_panel.rs @@ -91,7 +91,15 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr let mut sliders = [ StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "", dial: false }, - StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°", dial: false }, + StackSlider { + label: tr("Angle span"), + value: &mut span_value, + range: FillSymmetry::SPANS, + typed: FillSymmetry::SPANS, + decimals: 0, + suffix: "°", + dial: false, + }, ]; let [count_edit, span_edit] = sheet.picture_sliders(&picture, &mut sliders); diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs index 2cc9c41f..b63012ce 100644 --- a/crates/ui-egui/src/generator_input_card.rs +++ b/crates/ui-egui/src/generator_input_card.rs @@ -18,7 +18,14 @@ use crate::theme::Tokens; const GLYPH_SIZE: f32 = 12.0; /// The slot of input `slot` of generator effect `id` on `layer`, holding `source`: a card of its own, or a row of the card open now when `in_card` -pub(crate) fn input_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, id): (LayerId, u64), slot: GeneratorInputSlot, source: Option<&Source>, in_card: bool) { +pub(crate) fn input_card( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + slot: GeneratorInputSlot, + source: Option<&Source>, + in_card: bool, +) { let tokens = Tokens::get(sheet.ui.ctx()); let input = slot.id(); let line = match (source, slot) { diff --git a/crates/ui-egui/src/generator_input_slot.rs b/crates/ui-egui/src/generator_input_slot.rs index 0e145a6f..4027cb4f 100644 --- a/crates/ui-egui/src/generator_input_slot.rs +++ b/crates/ui-egui/src/generator_input_slot.rs @@ -1,6 +1,6 @@ //! What one image input of a generator replaces or holds -use texturecraft_engine::core::{BakedMap, Generator, Source}; +use texturecraft_engine::core::{BakedMap, Generator, KindControls, Source}; use crate::i18n::{baked_map_label, tr}; @@ -12,6 +12,9 @@ pub(crate) enum GeneratorInputSlot { Grunge, MicroHeight, MicroNormal, + + /// Grayscale Conversion's image + Image, } impl GeneratorInputSlot { @@ -23,6 +26,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => "grunge", GeneratorInputSlot::MicroHeight => texturecraft_engine::micro_params::MICRO_HEIGHT_INPUT, GeneratorInputSlot::MicroNormal => texturecraft_engine::micro_params::MICRO_NORMAL_INPUT, + GeneratorInputSlot::Image => "image", } } @@ -33,6 +37,7 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => tr("Custom Grunge"), GeneratorInputSlot::MicroHeight => tr("Micro Height"), GeneratorInputSlot::MicroNormal => tr("Micro Normal"), + GeneratorInputSlot::Image => tr("Input Image"), } } @@ -41,7 +46,7 @@ impl GeneratorInputSlot { match self { GeneratorInputSlot::Map(map) => map.neutral()[0], GeneratorInputSlot::MicroHeight | GeneratorInputSlot::MicroNormal => 0.5, - GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge => 0.0, + GeneratorInputSlot::Texture | GeneratorInputSlot::Grunge | GeneratorInputSlot::Image => 0.0, } } @@ -58,6 +63,10 @@ impl GeneratorInputSlot { GeneratorInputSlot::Grunge => generator.grunge.as_ref(), GeneratorInputSlot::MicroHeight => generator.micro.as_ref().and_then(|micro| micro.height_source.as_ref()), GeneratorInputSlot::MicroNormal => generator.micro.as_ref().and_then(|micro| micro.normal_source.as_ref()), + GeneratorInputSlot::Image => match generator.controls.as_deref() { + Some(KindControls::Grayscale(grayscale)) => grayscale.source.as_ref(), + _ => None, + }, } } } diff --git a/crates/ui-egui/src/generator_kind_rows.rs b/crates/ui-egui/src/generator_kind_rows.rs new file mode 100644 index 00000000..8b3e8960 --- /dev/null +++ b/crates/ui-egui/src/generator_kind_rows.rs @@ -0,0 +1,289 @@ +//! The Parameters rows of the kinds with only their own controls: 3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion, Dripping Rust, UV Random Color and UV Checker + +use egui::{Painter, Rect}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + BorderDistanceParameters, DistanceParameters, DrippingRustParameters, Generator, GeneratorGrayscale, GrayscaleConversionParameters, KindControls, + LinearGradientParameters, UvCheckerParameters, UvRandomColorParameters, +}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::take_color_pick; +use crate::generator_params::{DRIPS_AXES, kind_params, merged}; +use crate::generator_point_pick::PointPick; +use crate::i18n::{tr, trf}; +use crate::property_sheet::{NumberField, PropertySheet, StackSlider}; +use crate::theme::AXIS_COLORS; + +/// A 0..1 setting in the stack beside the preview +fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } +} + +/// A whole-number setting in the stack beside the preview +fn stacked_whole<'a>(label: &'a str, value: &'a mut f32, range: std::ops::RangeInclusive) -> StackSlider<'a> { + StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } +} + +/// The first edit of a stack beside the preview +fn first_edit(edits: [Option; N]) -> Option { + edits.into_iter().flatten().next() +} + +/// The rows of generator effect `id`, whose own controls are `controls`; `picture` draws the preview +pub(crate) fn kind_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + controls: KindControls, + picture: &dyn Fn(&Painter, Rect), +) { + if generator.kind.includes_randomness() { + let mut seed = generator.seed; + if sheet.seed(tr("Seed"), &mut seed) { + app.run("effect.set", json!({"effect": id, "seed": seed})); + } + } + + // UV Random Color and UV Checker make colors: Invert is the reference's on the grayscale kinds only + if !matches!(controls, KindControls::UvRandomColor(_) | KindControls::UvChecker(_)) { + let mut invert = generator.invert; + if sheet.toggle(tr("Invert"), &mut invert) { + app.run("effect.set", json!({"effect": id, "invert": invert})); + } + } + + let edit = match controls { + KindControls::Distance(distance) => distance_rows(sheet, id, distance, picture), + KindControls::LinearGradient(gradient) => linear_gradient_rows(sheet, id, gradient, picture), + KindControls::BorderDistance(border) => border_rows(sheet, border, picture), + KindControls::Grayscale(grayscale) => grayscale_rows(sheet, grayscale, picture), + KindControls::DrippingRust(rust) => rust_rows(sheet, rust, picture), + KindControls::UvRandomColor(random) => random_color_rows(app, sheet, id, random), + KindControls::UvChecker(checker) => checker_rows(app, sheet, checker, picture), + }; + if let Some((merge, edited)) = edit { + app.run("effect.set", merged(json!({"effect": id, "merge": merge}), edited)); + } +} + +/// An edit: whether it continues the last undo step, and the controls to send +type KindEdit = Option<(bool, Value)>; + +/// The controls `controls` to send when `merge` says one was edited +fn sent(merge: Option, controls: KindControls) -> KindEdit { + merge.map(|merge| (merge, kind_params(&controls))) +} + +/// A point's X, Y and Z (across the mesh's evenly scaled bounds) with its pick-on-mesh button; returns its edit +fn point_row(sheet: &mut PropertySheet<'_>, label: &str, point: &mut [f32; 3], pick: PointPick) -> Option { + let mut fields: Vec = ["X", "Y", "Z"] + .into_iter() + .zip(AXIS_COLORS) + .zip(point.iter()) + .map(|((tag, color), value)| NumberField { tag, tag_color: Some(color), value: *value, speed: POINT_DRAG_SPEED, decimals: 2, suffix: "" }) + .collect(); + let ctx = sheet.ui.ctx().clone(); + let armed = crate::generator_point_pick::armed(&ctx) == Some(pick); + let (edited, clicked) = sheet.point_fields(label, &mut fields, armed); + if clicked { + crate::generator_point_pick::toggle(&ctx, pick); + } + let (index, merge) = edited?; + let (field, coordinate) = (fields.get(index)?, point.get_mut(index)?); + *coordinate = field.value.clamp(0.0, 1.0); + Some(merge) +} + +/// Change of a point's coordinate per pixel dragged +const POINT_DRAG_SPEED: f32 = 0.005; + +/// 3D Distance: Radius, Offset and Contrast beside the preview, then its point +fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let radius = StackSlider { + label: tr("Radius"), + value: &mut edited.radius, + range: DistanceParameters::RADIUS_RANGE, + typed: DistanceParameters::RADIUS_RANGE, + decimals: 2, + suffix: "", + dial: false, + }; + let mut stack = [radius, stacked(tr("Offset"), &mut edited.offset), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position"), &mut edited.point, PointPick { effect: id, point: "distance" })); + sent(edit, KindControls::Distance(edited)) +} + +/// 3D Linear Gradient: Balance and Contrast beside the preview, then its start and end +fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGradientParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [stacked(tr("Balance"), &mut edited.balance), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(point_row(sheet, tr("3D Position Start"), &mut edited.start, PointPick { effect: id, point: "start" })); + edit = edit.or(point_row(sheet, tr("3D Position End"), &mut edited.end, PointPick { effect: id, point: "end" })); + sent(edit, KindControls::LinearGradient(edited)) +} + +/// UV Border Distance: Distance, Smoothness and Balance beside the preview, then Contrast +fn border_rows(sheet: &mut PropertySheet<'_>, shown: BorderDistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = + [stacked(tr("Distance"), &mut edited.distance), stacked(tr("Smoothness"), &mut edited.smoothness), stacked(tr("Balance"), &mut edited.balance)]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); + sent(edit, KindControls::BorderDistance(edited)) +} + +/// Grayscale Conversion: its type, Balance, Contrast and Tile beside the preview, then Rotation and Safe Rotation (its image is in Image inputs) +fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + let name = |grayscale: GeneratorGrayscale| tr(grayscale.label()).to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Grayscale Type"), edited.grayscale, &GeneratorGrayscale::ALL, name, None) { + edited.grayscale = picked; + edit = Some(false); + } + let mut stack = [ + stacked(tr("Balance"), &mut edited.balance), + stacked(tr("Contrast"), &mut edited.contrast), + stacked_whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.tile = edited.tile.round(); + edit = edit.or(sheet.angle(tr("Rotation"), &mut edited.rotation, 0.0..=360.0)); + if sheet.toggle(tr("Safe Rotation"), &mut edited.safe_rotation) { + edit = Some(false); + } + sent(edit, KindControls::Grayscale(edited)) +} + +/// Dripping Rust: Rust Spreading, Rust Contrast and Spreading Smoothness beside the preview, then the drips and the axis they run along +fn rust_rows(sheet: &mut PropertySheet<'_>, shown: DrippingRustParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut stack = [ + stacked(tr("Rust Spreading"), &mut edited.spreading), + stacked(tr("Rust Contrast"), &mut edited.contrast), + stacked(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), + ]; + let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); + edit = edit.or(sheet.slider(tr("Drips Intensity"), &mut edited.drips_intensity, 0.0..=1.0, 2)); + edit = edit.or(sheet.slider(tr("Drips Smoothness"), &mut edited.drips_smoothness, 0.0..=1.0, 2)); + let mut samples = edited.drips_samples as f32; + if let Some(merge) = sheet.slider(tr("Drips Samples Amount"), &mut samples, 0.0..=DrippingRustParameters::MAX_SAMPLES as f32, 0) { + edited.drips_samples = samples.round() as u32; + edit = edit.or(Some(merge)); + } + let axes = [tr("X - Red Channel"), tr("Y - Green Channel"), tr("Z - Blue Channel")]; + let name = |axis: u8| axes.get(usize::from(axis)).copied().unwrap_or_default().to_string(); + if let (Some(picked), _) = sheet.dropdown(tr("Position Axis"), edited.axis, &[0, 1, 2], name, None) { + edited.axis = picked; + edit = Some(false); + } + debug_assert_eq!(DRIPS_AXES.len(), axes.len()); + sent(edit, KindControls::DrippingRust(edited)) +} + +/// UV Random Color: where its colors come from; a custom gradient shows the gradient editor (as the Gradient filter's) +fn random_color_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, shown: UvRandomColorParameters) -> KindEdit { + let mut edited = shown.clone(); + let mode = usize::from(edited.custom_gradient); + if let Some(picked) = sheet.switch(tr("Color Source Mode"), &[tr("Random"), tr("Custom Gradient")], mode) { + edited.custom_gradient = picked == 1; + return sent(Some(false), KindControls::UvRandomColor(edited)); + } + if !edited.custom_gradient { + return None; + } + + let used = shown.used_colors().to_vec(); + let mut places = shown.used_positions(); + if let Some(drag) = sheet.gradient_ramp(&used, &places, &|t| shown.at(t).unwrap_or([0.0; 3])) { + if let Some(place) = places.get_mut(drag.index) { + *place = drag.position; + } + return Some((drag.merge, gradient_places(&shown, &places))); + } + + let mut quantity = used.len() as f32; + let range = f32::from(UvRandomColorParameters::MIN_QUANTITY)..=UvRandomColorParameters::MAX_GRADIENT_COLORS as f32; + let slid = sheet.slider(tr("Color Quantity"), &mut quantity, range, 0).is_some(); + + // A press's first whole-number change starts its undo step: changes that round to the count it has apply nothing + let press = sheet.ui.make_persistent_id(("uv_random_color_quantity", id)); + let quantity = quantity.round(); + if let Some(merge) = crate::widgets::press_edit(sheet.ui, press, slid && quantity as usize != used.len()) { + return Some((merge, json!({"gradientQuantity": quantity}))); + } + + let mut edit = None; + for (index, color) in used.iter().enumerate() { + let label = trf("Color {number}", &[("number", &(index + 1))]); + let mut place = places.get(index).copied().unwrap_or(0.0); + let (pick, moved) = sheet.color_stop(&label, *color, &mut place, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + if let Some(slot) = edited.gradient.get_mut(index) { + *slot = picked; + } + edit = Some((pick.merge, gradient_colors(&edited))); + } + if let Some(merge) = moved { + if let Some(slot) = places.get_mut(index) { + *slot = place; + } + edit = Some((merge, gradient_places(&shown, &places))); + } + } + edit +} + +/// The colors of `random` to send: all of them, then its count again (the colors reset it) +fn gradient_colors(random: &UvRandomColorParameters) -> Value { + let mut params = json!({"gradientColors": random.gradient}); + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params +} + +/// The places to send: `used` (the used colors' places) and the hidden colors' own +fn gradient_places(random: &UvRandomColorParameters, used: &[f32]) -> Value { + let hidden = random.positions.iter().skip(used.len()).copied(); + json!({"gradientPositions": used.iter().copied().chain(hidden).collect::>()}) +} + +/// UV Checker: its color mode with the uniform color, Checker Grid Tile, Checker Grid Opacity and UV Borders Width beside the preview, then UV Borders Color +fn checker_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, shown: UvCheckerParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { + let mut edited = shown; + let mut edit = None; + if let Some(picked) = sheet.switch(tr("Checker Color Mode"), &[tr("Uniform"), tr("Random")], usize::from(edited.random_colors)) { + edited.random_colors = picked == 1; + edit = Some(false); + } + if !edited.random_colors { + let pick = sheet.color_bar_led(tr("Checker Color"), edited.checker_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.checker_color = picked; + edit = Some(pick.merge); + } + } + + let mut tile = edited.grid_tile as f32; + let tiles = *UvCheckerParameters::GRID_TILE_RANGE.start() as f32..=*UvCheckerParameters::GRID_TILE_RANGE.end() as f32; + let mut stack = [ + stacked_whole(tr("Checker Grid Tile"), &mut tile, tiles), + stacked(tr("Checker Grid Opacity"), &mut edited.grid_opacity), + stacked(tr("UV Borders Width"), &mut edited.border_width), + ]; + edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); + edited.grid_tile = tile.round() as u32; + + let pick = sheet.color_bar_led(tr("UV Borders Color"), edited.border_color, app.picking_color, &app.session.doc.project.swatches); + if let Some(picked) = take_color_pick(app, pick) { + edited.border_color = picked; + edit = Some(pick.merge); + } + sent(edit, KindControls::UvChecker(edited)) +} diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 98d060ee..4f6661da 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -2,7 +2,9 @@ use egui::{Painter, Rect, TextureHandle}; use serde_json::json; -use texturecraft_engine::core::{CookResolution, Generator, GeneratorKind, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters}; +use texturecraft_engine::core::{ + CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, +}; use crate::TextureCraftApp; use crate::fill_material_panel::{band_size, texture_set_size}; @@ -39,10 +41,14 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, parameters(app, sheet, (layer, id), generator); } - let inputs = generator.inputs_in_use(); - if !inputs.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&inputs.len().to_string())).open { - for map in inputs { - let slot = GeneratorInputSlot::Map(*map); + // The kinds with only their own controls show the images the reference lets them take: Grayscale Conversion's own + let slots: Vec = match generator.kind_controls() { + Some(KindControls::Grayscale(_)) => vec![GeneratorInputSlot::Image], + Some(_) => Vec::new(), + None => generator.inputs_in_use().iter().map(|map| GeneratorInputSlot::Map(*map)).collect(), + }; + if !slots.is_empty() && sheet.band(tr("Image inputs"), false, None, Some(&slots.len().to_string())).open { + for slot in slots { input_card(app, sheet, (layer, id), slot, slot.source(generator), false); } } @@ -108,6 +114,10 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + if let Some(controls) = generator.kind_controls() { + crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, &picture); + return; + } if let Some(defaults) = WearParameters::defaults(kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 96fc1980..00fd88d2 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -1,7 +1,7 @@ //! The `effect.set` keys of a generator's controls, as its panel sends them use serde_json::{Value, json}; -use texturecraft_engine::core::{Generator, GeneratorKind, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; +use texturecraft_engine::core::{Generator, GeneratorKind, KindControls, LightParameters, MicroDetails, SectionParameters, TextureLayer, WearParameters}; use texturecraft_engine::mask_cmds::{section_key_applies, wear_key_applies}; use texturecraft_engine::micro_params::micro_key_applies; @@ -81,6 +81,73 @@ pub(crate) fn light_params(light: &LightParameters) -> Value { }) } +/// Every control of a kind with only its own controls, set to `controls` (Grayscale Conversion's image is its `image` input, kept apart) +pub(crate) fn kind_params(controls: &KindControls) -> Value { + match controls { + KindControls::Distance(distance) => json!({ + "distanceX": distance.point[0], + "distanceY": distance.point[1], + "distanceZ": distance.point[2], + "distanceRadius": distance.radius, + "distanceOffset": distance.offset, + "distanceContrast": distance.contrast, + }), + KindControls::LinearGradient(gradient) => json!({ + "gradientStart": gradient.start, + "gradientEnd": gradient.end, + "gradientBalance": gradient.balance, + "gradientContrast": gradient.contrast, + }), + KindControls::BorderDistance(border) => json!({ + "borderDistance": border.distance, + "borderSmoothness": border.smoothness, + "borderBalance": border.balance, + "borderContrast": border.contrast, + }), + KindControls::Grayscale(grayscale) => json!({ + "grayscaleType": grayscale.grayscale.id(), + "grayscaleBalance": grayscale.balance, + "grayscaleContrast": grayscale.contrast, + "grayscaleTile": grayscale.tile, + "grayscaleRotation": grayscale.rotation, + "grayscaleSafeRotation": grayscale.safe_rotation, + }), + KindControls::DrippingRust(rust) => json!({ + "rustSpreading": rust.spreading, + "rustContrast": rust.contrast, + "spreadingSmoothness": rust.spreading_smoothness, + "dripsIntensity": rust.drips_intensity, + "dripsSmoothness": rust.drips_smoothness, + "dripsSamples": rust.drips_samples, + "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or("y"), + }), + KindControls::UvRandomColor(random) => { + let mut params = json!({ + "colorSourceMode": if random.custom_gradient { "customGradient" } else { "random" }, + "gradientColors": random.gradient, + "gradientPositions": random.positions, + }); + + // The colors reset the count to all of them: one kept hides the rest again + if let Some(quantity) = random.quantity { + params["gradientQuantity"] = json!(quantity); + } + params + } + KindControls::UvChecker(checker) => json!({ + "checkerColorMode": if checker.random_colors { "random" } else { "uniform" }, + "checkerColor": checker.checker_color, + "checkerGridTile": checker.grid_tile, + "checkerGridOpacity": checker.grid_opacity, + "uvBordersColor": checker.border_color, + "uvBordersWidth": checker.border_width, + }), + } +} + +/// Dripping Rust's `dripsAxis` names, by axis +pub(crate) const DRIPS_AXES: [&str; 3] = ["x", "y", "z"]; + /// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { let mut params = json!({ @@ -111,6 +178,9 @@ pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { "customResolution": defaults.resolution.custom, "resolutionFactor": defaults.resolution.factor, }); + if let Some(controls) = &defaults.controls { + return merged(params, kind_params(controls)); + } // A generator on the reference's controls restores those only: the earlier model's keys would move it back onto that model let global = json!({"blur": defaults.global.blur, "balance": defaults.global.balance, "contrast": defaults.global.contrast}); @@ -163,7 +233,18 @@ pub(crate) fn differs_from_defaults(generator: &Generator) -> bool { { restored.micro = Some(Box::new(MicroDetails { height_source: micro.height_source.clone(), normal_source: micro.normal_source.clone(), ..defaults })); } - restored.controls = generator.controls.clone(); + + // Grayscale Conversion's image stays in its slot + restored.controls = match (restored.controls.as_deref(), generator.controls.as_deref()) { + (_, None) => None, + (Some(KindControls::Grayscale(defaults)), Some(KindControls::Grayscale(saved))) => { + Some(Box::new(KindControls::Grayscale(texturecraft_engine::core::GrayscaleConversionParameters { + source: saved.source.clone(), + ..defaults.clone() + }))) + } + (defaults, _) => defaults.cloned().map(Box::new), + }; // Saved before the wear, section or light controls: the earlier model's own values count if generator.wear.is_none() { diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs new file mode 100644 index 00000000..72712c84 --- /dev/null +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -0,0 +1,30 @@ +//! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels + +/// Which point of which generator effect the next click in the 3D view sets +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PointPick { + pub(crate) effect: u64, + + /// `effect.generator.pickPoint`'s point: distance, start or end + pub(crate) point: &'static str, +} + +/// Where the armed pick is kept: a transient UI mode, like the depth of field's focus pick +fn pick_id() -> egui::Id { + egui::Id::unique("tc_generator_point_pick") +} + +/// The point the next click in the 3D view sets, if one is armed +pub(crate) fn armed(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::>(pick_id())).flatten() +} + +/// Arms `pick`, or disarms it when it is the one armed +pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { + let next = if armed(ctx) == Some(pick) { None } else { Some(pick) }; + set(ctx, next); +} + +pub(crate) fn set(ctx: &egui::Context, pick: Option) { + ctx.data_mut(|data| data.insert_temp(pick_id(), pick)); +} diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs index 0e7533a8..38377af0 100644 --- a/crates/ui-egui/src/generator_section_rows.rs +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -23,8 +23,11 @@ fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { let (mut invert, mut global) = (generator.invert, generator.global); let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); - let mut stack = - [stacked(tr("Global Blur"), &mut global.blur), stacked(tr("Global Balance"), &mut global.balance), stacked(tr("Global Contrast"), &mut global.contrast)]; + let mut stack = [ + stacked(tr("Global Blur"), &mut global.blur), + stacked(tr("Global Balance"), &mut global.balance), + stacked(tr("Global Contrast"), &mut global.contrast), + ]; let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if let Some(merge) = invert_edit.or(stack_edit) { app.run( @@ -35,7 +38,14 @@ pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<' } /// The kind's own card (Curvature's mode and sizes in it), then one card per axis, showing `shown`; `solo` keeps the Curvature size under the pointer for the preview -pub(crate) fn section_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, shown: SectionParameters, solo: &mut Option) { +pub(crate) fn section_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + generator: &Generator, + shown: SectionParameters, + solo: &mut Option, +) { let kind = generator.kind; let title = match kind { GeneratorKind::Curvature => tr("Curvature"), diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs index 09273f0b..c103ab72 100644 --- a/crates/ui-egui/src/generator_wear_rows.rs +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -38,11 +38,8 @@ pub(crate) fn wear_rows( let dirt = kind == GeneratorKind::Dirt; let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; let mut edited = wear; - let mut stack = [ - stacked(level_label, &mut edited.level), - stacked(contrast_label, &mut edited.contrast), - stacked(tr("Grunge Amount"), &mut edited.grunge_amount), - ]; + let mut stack = + [stacked(level_label, &mut edited.level), stacked(contrast_label, &mut edited.contrast), stacked(tr("Grunge Amount"), &mut edited.grunge_amount)]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if kind != GeneratorKind::FiberGlassEdgeWear { edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); @@ -82,7 +79,14 @@ pub(crate) fn wear_rows( } /// The Light generator's controls of effect `id`, showing `shown`; `invert` adds its Invert row (None on the earlier model, whose global invert it is) -pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, invert: Option, shown: LightParameters, picture: &dyn Fn(&Painter, Rect)) { +pub(crate) fn light_rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + id: u64, + invert: Option, + shown: LightParameters, + picture: &dyn Fn(&Painter, Rect), +) { if let Some(mut invert) = invert && sheet.toggle(tr("Invert"), &mut invert) { @@ -90,7 +94,15 @@ pub(crate) fn light_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_ } let mut edited = shown; - let angle = |label, value| StackSlider { label, value, range: LightParameters::ANGLE_RANGE, typed: LightParameters::ANGLE_RANGE, decimals: 0, suffix: "°", dial: true }; + let angle = |label, value| StackSlider { + label, + value, + range: LightParameters::ANGLE_RANGE, + typed: LightParameters::ANGLE_RANGE, + decimals: 0, + suffix: "°", + dial: true, + }; let mut stack = [ angle(tr("Horizontal Angle"), &mut edited.horizontal), angle(tr("Vertical Angle"), &mut edited.vertical), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d626d5c3..f13365a8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -46,8 +46,10 @@ pub mod fonts; mod frame_gizmo; mod generator_input_card; mod generator_input_slot; +mod generator_kind_rows; mod generator_panel; mod generator_params; +mod generator_point_pick; mod generator_section_rows; mod generator_slot; mod generator_wear_rows; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..3782cf3b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -473,6 +473,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Let the innermost popup consume Escape before cancelling the active tool let popup_open = egui::Popup::is_any_open(ctx); + let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); + let mut cancel_point_pick = false; let picker_open = crate::color_picker::open_window(ctx).is_some(); let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); @@ -528,6 +530,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::import_resources::keys_in(app, input, nothing_focused, popup_open); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; + } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + cancel_point_pick = true; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -543,6 +547,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { commands }); + if cancel_point_pick { + crate::generator_point_pick::set(ctx, None); + } for id in &commands_to_invoke { if matches!(id.as_str(), "layer.copy" | "layer.cut") diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index bde4267b..291d50d9 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -38,6 +38,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: && app.moving_on_model.is_none() && !gesture_key_held && !crate::viewport::focus_picking(ui.ctx()) + && crate::generator_point_pick::armed(ui.ctx()).is_none() && ui.input(|input| input.modifiers.is_none()); if !free || !response.clicked_by(PointerButton::Secondary) { diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index f16db1b3..c534afc3 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -107,7 +107,14 @@ impl PropertySheet<'_> { } /// A card for one axis: its letter on a chip in `tint`, the bold name and the value, then a full-width slider filled in `tint`; the axis's other rows follow, then [`Self::close_card`] - pub(crate) fn axis_card(&mut self, (letter, tint): (&str, Color32), name: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + pub(crate) fn axis_card( + &mut self, + (letter, tint): (&str, Color32), + name: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + ) -> Option { self.open_card(); self.scope = self.named_id("axis_card", name); self.space(AXIS_CARD_TOP); diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 2e352d98..2e321496 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -51,9 +51,25 @@ impl PropertySheet<'_> { pub(crate) fn number_fields(&mut self, label: &str, fields: &mut [NumberField], link: Option<&mut bool>, keep_link_slot: bool) -> Option<(usize, bool)> { let (control, center_y) = self.row(label); let slot = if link.is_some() || keep_link_slot { LINK_SLOT } else { 0.0 }; + let edited = self.fields_in(control, slot, label, fields); + if let Some(linked) = link { + self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); + } + edited + } + + /// A point in 3D: `label` on its own line, then its fields across the card and the pick-on-mesh button in the link slot, lit while `picking`; returns the edited index with whether it continues a drag, and whether the button was clicked + pub(crate) fn point_fields(&mut self, label: &str, fields: &mut [NumberField], picking: bool) -> (Option<(usize, bool)>, bool) { + let (control, center_y) = self.row_with(super::RowLead::Label { text: label, stack: true }); + let edited = self.fields_in(control, LINK_SLOT, label, fields); + let clicked = self.pick_button(pos2(self.right - LINK_SIZE / 2.0, center_y), label, picking); + (edited, clicked) + } + + /// `fields` side by side across `control`, leaving `slot` at its end + fn fields_in(&mut self, control: Rect, slot: f32, label: &str, fields: &mut [NumberField]) -> Option<(usize, bool)> { let count = fields.len().max(1) as f32; let width = (control.width() - slot - (count - 1.0) * FIELD_GAP) / count; - let mut edited = None; for (index, field) in fields.iter_mut().enumerate() { let left = control.left() + index as f32 * (width + FIELD_GAP); @@ -62,13 +78,27 @@ impl PropertySheet<'_> { edited = Some((index, edited.is_none_or(|(_, previous_merge)| previous_merge) && merge)); } } - - if let Some(linked) = link { - self.link_button(pos2(self.right - LINK_SIZE / 2.0, center_y), linked); - } edited } + /// The button that arms picking the point of row `label` on the mesh; returns whether it was clicked + fn pick_button(&mut self, center: egui::Pos2, label: &str, picking: bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pick_on_mesh", label); + let response = self.ui.interact(rect, id, Sense::click()); + let name = crate::i18n::trf("Pick {name} on the mesh", &[("name", &label)]); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, picking, &name)); + let response = self.tip(response, crate::i18n::tr("Pick on the mesh")); + + let tokens = self.tokens; + let (fill, border) = if picking { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::CROSSHAIR_SIMPLE, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + response.clicked() + } + /// The link that keeps two values together; returns whether it was clicked pub(super) fn link_button(&mut self, center: egui::Pos2, linked: &mut bool) -> bool { let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs index da810113..ec6dd9d7 100644 --- a/crates/ui-egui/src/property_sheet/size_columns.rs +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -53,8 +53,17 @@ impl PropertySheet<'_> { let painter = self.ui.painter(); if hovered { - let face = Rect::from_min_max(pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG)); - painter.rect(face, CornerRadius::same(super::CONTROL_RADIUS), tokens.row_hover, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + let face = Rect::from_min_max( + pos2(column.left() + FACE_AIR, block.top() - FACE_OVERHANG), + pos2(column.right() - FACE_AIR, block.bottom() + FACE_OVERHANG), + ); + painter.rect( + face, + CornerRadius::same(super::CONTROL_RADIUS), + tokens.row_hover, + Stroke::new(1.0, tokens.field_border), + egui::StrokeKind::Inside, + ); } painter.text(pos2(x, block.top() + VALUE_LINE / 2.0), Align2::CENTER_CENTER, format!("{value:.2}"), semibold(SMALL_TEXT_SIZE), tokens.text); painter.line_segment([pos2(x, track_top), pos2(x, track_bottom)], Stroke::new(COLUMN_TRACK_WIDTH, tokens.button_border)); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index dc64aaae..ba44649f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,7 +646,8 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); + let on_the_orb = + matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..473eaf29 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -864,9 +864,27 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // A 3D generator's armed point pick: a click sets the point there instead of painting + let point_pick = crate::generator_point_pick::armed(ui.ctx()); + if let Some(pick) = point_pick { + ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + let (at, viewport) = (local(pointer), app.session.viewport); + let params = json!({"effect": pick.effect, "point": pick.point, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); + + // A click off the mesh keeps it armed for the next + if app.run("effect.generator.pickPoint", params).is_some() { + crate::generator_point_pick::set(ui.ctx(), None); + } + } + } + // Depth of field focus pick: a click focuses there instead of painting - let focus_pick = focus_picking(ui.ctx()); - if focus_pick { + let focus_pick = focus_picking(ui.ctx()) || point_pick.is_some(); + if focus_picking(ui.ctx()) { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && response.clicked_by(PointerButton::Primary) diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 78fc0d9c..e191d8b0 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -4,7 +4,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; -use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, LayerId, SectionParameters, Source, WearParameters}; +use texturecraft_engine::core::{AxisBlend, BakedMap, EffectKind, Generator, GeneratorKind, KindControls, LayerId, SectionParameters, Source, WearParameters}; use texturecraft_engine::{ViewMode, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -388,3 +388,107 @@ fn texture_panel_snapshots() { } } } + +/// Whether control `label` with `role` shows on +fn is_on(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { + harness.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn a_point_pick_waits_for_the_view_until_escape() { + let (mut harness, _) = harness_with(false, json!({"generator": "3dLinearGradient"})); + let (start, end) = ("Pick 3D Position Start on the mesh", "Pick 3D Position End on the mesh"); + assert!(!is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end)); + + click_live(&mut harness, Role::Button, end); + assert!(is_on(&harness, Role::Button, end), "armed: the next click in the view sets the end"); + assert!(!is_on(&harness, Role::Button, start), "only the point picked waits"); + + click_live(&mut harness, Role::Button, start); + assert!(is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end), "arming the start hands the wait over"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, start), "Esc cancels the pick"); +} + +#[test] +fn a_gradient_color_place_moves_its_stop_in_one_step() { + let added = + json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[0.0, 0.0, 0.0], [0.8, 0.3, 0.1], [1.0, 1.0, 1.0]]}); + let (mut harness, effect) = harness_with(false, added); + let places = |harness: &Harness<'_, TextureCraftApp>| match generator(harness, effect).kind_controls() { + Some(KindControls::UvRandomColor(random)) => random.used_positions(), + other => panic!("not UV Random Color controls: {other:?}"), + }; + let before = places(&harness); + + // Color 2's own track, after its marker on the ramp + let rect = harness.get_all_by_role_and_label(Role::Slider, "Color 2").last().expect("Color 2's place").rect(); + let (from, to) = (egui::pos2(rect.left() + 4.0, rect.center().y), egui::pos2(rect.right() - 4.0, rect.center().y)); + harness.drag_at(from); + harness.run_steps(2); + harness.hover_at(to); + harness.run_steps(2); + harness.drop_at(to); + harness.run_steps(3); + + let after = places(&harness); + assert!(after[1] > before[1], "Color 2 moved right along the gradient"); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the other colors keep their places"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(places(&harness), before, "one undo step puts it back"); +} + +#[test] +fn the_color_rows_follow_the_color_mode() { + let (mut harness, _) = harness_with(false, json!({"generator": "uvChecker"})); + assert_eq!(count(&harness, "Checker Color"), 1, "uniform: its color shows"); + click_live(&mut harness, Role::RadioButton, "Random"); + assert_eq!(count(&harness, "Checker Color"), 0, "random colors: no color to pick"); + assert_eq!(count(&harness, "UV Borders Color"), 1, "the borders keep theirs"); + + let (mut harness, _) = harness_with(false, json!({"generator": "uvRandomColor"})); + assert_eq!(count(&harness, "Color 1"), 0, "random: no gradient"); + harness.get_by_role_and_label(Role::ComboBox, "Random").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::ListBoxOption, "Custom Gradient").click(); + harness.run_steps(3); + assert!(count(&harness, "Color 1") > 0 && count(&harness, "Color 2") > 0, "a custom gradient shows its colors"); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn new_kind_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let gradient = json!([[0.02, 0.02, 0.02], [0.6, 0.12, 0.03], [0.8, 0.8, 0.8]]); + let kinds = [ + ("3dDistance", json!({})), + ("3dLinearGradient", json!({})), + ("uvBorderDistance", json!({})), + ("grayscaleConversion", json!({})), + ("drippingRust", json!({})), + ("uvRandomColor", json!({"colorSourceMode": "customGradient", "gradientColors": gradient, "gradientPositions": [0.0, 0.45, 1.0]})), + ("uvChecker", json!({})), + ]; + for (kind, extra) in kinds { + let mut added = json!({"generator": kind}); + added.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let (mut harness, _) = harness_with(true, added); + if kind == "grayscaleConversion" { + harness.get_by_role_and_label(Role::Button, "Image inputs").click(); + } + + // The orbs render on the preview worker + for _ in 0..40 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-{kind}-{name}.png"))).unwrap(); + } + } +} From 494403237903360a338b9bae7c55ba2cf739b9c2 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:47:05 +0000 Subject: [PATCH 25/54] Property sheet: Escape cancels a typed value even where a shortcut takes the key; a press on the track drops the value typed in its row --- crates/ui-egui/src/property_sheet/number_field.rs | 2 +- crates/ui-egui/src/property_sheet/slider.rs | 7 ++++++- crates/ui-egui/src/property_sheet/slot.rs | 2 +- crates/ui-egui/src/property_sheet/value_text.rs | 15 +++++++++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 2e321496..36c484ad 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -154,7 +154,7 @@ impl PropertySheet<'_> { let untouched = self.end_typing(typing_id, &draft); let text = draft.text.trim(); - if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + if self.escape_pressed() { return None; } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 6cf51d26..8e43a01e 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -216,6 +216,11 @@ impl PropertySheet<'_> { let response = self.ui.interact(hit, id, Sense::click_and_drag()); response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + // A press on the track drops what was typed in its value: the track's value is the one wanted + if response.is_pointer_button_down_on() { + self.drop_typing(id.with((self.id, "typed"))); + } + let mut moved = false; if (response.dragged() || response.drag_stopped() || response.clicked()) && let Some(pointer) = response.interact_pointer_pos() @@ -336,7 +341,7 @@ impl PropertySheet<'_> { let untouched = self.end_typing(field_id, &draft); let typed_text = draft.text.trim(); - if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) { + if self.escape_pressed() { return None; } diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index b3b36a4c..90d2111b 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -248,7 +248,7 @@ impl PropertySheet<'_> { if let Ok(typed) = draft.text.trim().parse::() && !untouched && typed != *seed - && !self.ui.input(|input| input.key_pressed(egui::Key::Escape)) + && !self.escape_pressed() { *seed = typed; changed = true; diff --git a/crates/ui-egui/src/property_sheet/value_text.rs b/crates/ui-egui/src/property_sheet/value_text.rs index a569f284..fc83f749 100644 --- a/crates/ui-egui/src/property_sheet/value_text.rs +++ b/crates/ui-egui/src/property_sheet/value_text.rs @@ -45,6 +45,21 @@ impl super::PropertySheet<'_> { draft.original.trim() == draft.text.trim() } + /// Whether Escape was pressed this frame, even where a shortcut took it before the field lost its focus to it + pub(super) fn escape_pressed(&self) -> bool { + self.ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))) + } + + /// Drops the draft of field `field_id`, if it is being typed in, without applying it + pub(super) fn drop_typing(&self, field_id: Id) { + if self.typing_draft(field_id).is_some() { + self.ui.memory_mut(|memory| { + memory.caches.cache::().set(field_id, None); + memory.surrender_focus(field_id); + }); + } + } + /// Shows an edit in place of the displayed value, without shifting the sheet's rows pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, field_id: Id, draft: &mut ValueTextDraft) -> egui::Response { let font = semibold(super::TEXT_SIZE); From cb0a6f8a28174dd08674356749182a7fad16094a Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:09:33 +0000 Subject: [PATCH 26/54] Generators: names and comments to the review guidelines; the bake hint without a hardcoded shortcut --- crates/compose/src/eval.rs | 14 +++--- crates/core/src/layer.rs | 11 +++-- crates/engine/src/orb_preview.rs | 3 +- crates/engine/tests/it/content_effects.rs | 60 +++++++++++------------ crates/ui-egui/src/generator_panel.rs | 2 +- 5 files changed, 45 insertions(+), 45 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 06f95001..648a98fa 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1953,22 +1953,22 @@ fn filter_region( /// Where working texel (`x`, `y`) of `inp` is, for pattern evaluation (as [`Texel::coords`] sees it outside a fill copy) pub(crate) fn texel_coords(inp: &Inputs, x: u32, y: u32) -> Coords { - let g = inp.gbuf; - let mut c = match g.surface(inp.mesh, (y * g.width + x) as usize) { - Some(s) => { + let gbuf = inp.gbuf; + let mut coords = match gbuf.surface(inp.mesh, (y * gbuf.width + x) as usize) { + Some(surface) => { let (center, radius) = mesh_frame(inp.bounds); - Coords { uv: s.uv, pos: (s.pos - center) / radius, nrm: s.nrm } + Coords { uv: surface.uv, pos: (surface.pos - center) / radius, nrm: surface.nrm } } - None => Coords { uv: Vec2::new((x as f32 + 0.5) / g.width as f32, (y as f32 + 0.5) / g.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, + None => Coords { uv: Vec2::new((x as f32 + 0.5) / gbuf.width as f32, (y as f32 + 0.5) / gbuf.height as f32), pos: Vec3::ZERO, nrm: Vec3::Y }, }; // UV-tiled sets: projections see the mesh's own UVs (patterns repeat per tile) if let Ok(set) = inp.project.texture_set(inp.ts) && let Some(grid) = set.tile_grid() { - c.uv = Vec2::from(set.from_atlas(&grid, c.uv.to_array())); + coords.uv = Vec2::from(set.from_atlas(&grid, coords.uv.to_array())); } - c + coords } /// What a generator's texture or custom grunge reads with nothing in its slot diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index bc82c7b7..62db399d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1096,8 +1096,8 @@ impl GeneratorKind { ) } - pub fn parse(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); + pub fn parse(name: &str) -> Option { + let normalised = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); // The labels before the reference app's names, which agents may still send let earlier = |kind: GeneratorKind| match kind { GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), @@ -1105,9 +1105,10 @@ impl GeneratorKind { GeneratorKind::Direction => Some("Light / direction"), _ => None, }; - GeneratorKind::ALL - .into_iter() - .find(|k| norm(k.id()) == norm(s) || norm(k.label()) == norm(s) || earlier(*k).is_some_and(|label| norm(label) == norm(s))) + GeneratorKind::ALL.into_iter().find(|kind| { + let wanted = normalised(name); + normalised(kind.id()) == wanted || normalised(kind.label()) == wanted || earlier(*kind).is_some_and(|label| normalised(label) == wanted) + }) } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 6d03ef36..c392dc4c 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -86,8 +86,7 @@ impl OrbPreview { self.mask_pixels(size) } - /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, with None outside the shape - /// Returns None for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, None outside the shape (and for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]) pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { let mut generator = Generator::new(kind); diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index f15a9ed8..b8770541 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -163,52 +163,52 @@ fn largest_change(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { #[test] fn generators_read_an_anchor_height_as_their_micro_height() { - let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); // A checker of raised height below, recorded by an anchor point - let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); - execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); - execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); - let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); - let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); - execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); + let low = id(execute(&mut session, "layer.add.fill", &json!({"height": 1.0})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + let top = id(execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); // The anchor must be below; `microAmount` needs an anchor; ids must be numbers - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); - assert!(execute(&mut s, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAmount": 0.5})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAnchor": "x"})).is_err()); + assert!(execute(&mut session, "effect.add.generator", &json!({"layer": top, "microAnchor": low})).is_err(), "not an anchor point"); - let generator = id(execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); - let plain = base_colors(&mut s); - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); - let raised = base_colors(&mut s); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap(), "effect"); + let plain = base_colors(&mut session); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let raised = base_colors(&mut session); assert!(largest_change(&raised, &plain) > 0.05, "the checker's raised edges read as curvature"); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let inspect = execute(&mut session, "project.inspect", &Value::Null).unwrap(); let inspected = inspect.to_string(); assert!(inspected.contains("\"heightSource\"") && inspected.contains(&format!("\"anchor\":{anchor}")), "{inspect}"); // The amount alone keeps the anchor; null empties the Micro Height - execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); - assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "no amount, no micro height"); - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); - let emptied = s + execute(&mut session, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); + assert!(largest_change(&base_colors(&mut session), &plain) < 1e-3, "no amount, no micro height"); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); + let emptied = session .doc .project .effect(LayerId(generator)) - .map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); + .map(|(_, effect)| matches!(&effect.kind, EffectKind::Generator(made) if made.micro.as_ref().is_some_and(|micro| micro.height_source.is_none()))); assert_eq!(emptied, Some(true)); - assert!(largest_change(&base_colors(&mut s), &plain) < 1e-3, "without an anchor, as without micro details"); - assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); + assert!(largest_change(&base_colors(&mut session), &plain) < 1e-3, "without an anchor, as without micro details"); + assert!(execute(&mut session, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); // A copied generator reading an anchor needs the anchor below its new layer - execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); - execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); - execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); - execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); - assert!(execute(&mut s, "effect.paste", &json!({"target": "mask"})).is_err()); - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project, s.doc.project); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut session, "effect.paste", &json!({"target": "mask"})).is_err()); + let back = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, session.doc.project); } #[test] diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 4f6661da..bc7297cf 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -66,7 +66,7 @@ pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut egui::Ui, attributes(sheet, generator.kind); } if !app.session.doc.baked.contains_key(&app.session.ts()) { - sheet.caption(tr("Bake mesh maps (Ctrl+Shift+B) for curvature, AO and thickness based generators.")); + sheet.caption(tr("Bake mesh maps for curvature, AO and thickness based generators.")); } }); } From 1ed1f5ca5d13f60b4b4191a6c3a81406bc82e7d4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:31:47 +0000 Subject: [PATCH 27/54] Generators: review fixes (one type per file, a stale point pick drops, an image still loading blends black on both render paths, inspect reports the new controls) --- crates/compose/src/dripping_rust.rs | 17 +- crates/compose/src/eval.rs | 7 +- crates/compose/src/field_cache.rs | 66 ++++ crates/compose/src/field_cache_key.rs | 30 ++ crates/compose/src/grunge_pattern.rs | 37 +++ crates/compose/src/lib.rs | 4 + .../compose/src/micro_details/anchor_entry.rs | 15 + .../src/micro_details/anchor_heights.rs | 24 ++ crates/compose/src/micro_details/cache_key.rs | 24 ++ .../compose/src/micro_details/cached_bytes.rs | 4 + .../compose/src/micro_details/layout_map.rs | 26 ++ .../compose/src/micro_details/micro_cache.rs | 51 +++ .../src/micro_details/micro_curvature.rs | 47 +++ .../mod.rs} | 308 ++---------------- crates/compose/src/micro_details/slot.rs | 98 ++++++ crates/compose/src/micro_details/slot_key.rs | 23 ++ crates/compose/src/sections.rs | 4 + crates/compose/src/slot_placement.rs | 7 + crates/compose/src/texture_layer.rs | 10 +- crates/compose/src/uv_border_distance.rs | 11 +- crates/compose/src/uv_islands.rs | 15 +- crates/compose/src/wear.rs | 43 +-- crates/compose/src/working_field.rs | 98 +----- crates/compose/tests/generator_texture.rs | 12 + crates/core/src/layer.rs | 3 +- crates/engine/src/generator_input.rs | 12 + crates/engine/src/generator_pick.rs | 3 +- crates/engine/src/inspect.rs | 9 + crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 21 +- crates/ui-egui/src/generator_kind_rows.rs | 39 +-- crates/ui-egui/src/generator_params.rs | 5 +- crates/ui-egui/src/generator_point_pick.rs | 10 + crates/ui-egui/src/generator_section_rows.rs | 11 +- crates/ui-egui/src/generator_wear_rows.rs | 14 +- .../src/property_sheet/stack_slider.rs | 12 + crates/ui-egui/src/viewport.rs | 2 +- crates/ui-egui/src/widgets.rs | 31 +- crates/ui-egui/tests/it/effect_sliders.rs | 13 +- crates/ui-egui/tests/it/generator_panel.rs | 28 +- crates/ui-egui/tests/ui_snapshots.rs | 1 - 41 files changed, 659 insertions(+), 537 deletions(-) create mode 100644 crates/compose/src/field_cache.rs create mode 100644 crates/compose/src/field_cache_key.rs create mode 100644 crates/compose/src/grunge_pattern.rs create mode 100644 crates/compose/src/micro_details/anchor_entry.rs create mode 100644 crates/compose/src/micro_details/anchor_heights.rs create mode 100644 crates/compose/src/micro_details/cache_key.rs create mode 100644 crates/compose/src/micro_details/cached_bytes.rs create mode 100644 crates/compose/src/micro_details/layout_map.rs create mode 100644 crates/compose/src/micro_details/micro_cache.rs create mode 100644 crates/compose/src/micro_details/micro_curvature.rs rename crates/compose/src/{micro_details.rs => micro_details/mod.rs} (62%) create mode 100644 crates/compose/src/micro_details/slot.rs create mode 100644 crates/compose/src/micro_details/slot_key.rs create mode 100644 crates/compose/src/slot_placement.rs create mode 100644 crates/engine/src/generator_input.rs diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index ef3e308c..4b5f84d5 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -7,9 +7,10 @@ use texturecraft_core::{BakedMap, DrippingRustParameters, GeneratorKind, WearPar use texturecraft_geom::glam::Vec3; use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; use crate::histogram_scan::histogram_scan; use crate::wear; -use crate::working_field::{FieldCache, blur_blocks}; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; /// The rust before any grunge: `RUST_FLOOR + RUST_GAIN * max(RUST_OCCLUSION − occlusion, 0)^RUST_POWER` (fitted to the reference) const RUST_FLOOR: f32 = 0.315; @@ -29,9 +30,6 @@ const DRIP_LENGTH_2K: f32 = 90.86; const DRIP_FADE: f32 = 0.898; const DRIP_FADE_POWER: f32 = 0.671; -/// The UV tile resolution the sizes above are measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - /// Coverage below which a blurred texel has nothing to average const MIN_COVERAGE: f32 = 1e-3; @@ -73,19 +71,14 @@ fn build(inp: &Inputs, rust: &DrippingRustParameters, seed: u32, block: (u32, u3 }; let mut field: Vec = (0..width * height).into_par_iter().map(|texel| if gbuf.covered(texel as usize) { rust_at(texel) } else { 0.0 }).collect(); - let sigma_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); - blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); + let radius_at = |sigma_2k: f32, smoothness: f32| move |x: u32, y: u32| box_radius(smoothness * sigma_2k * tile_texels(x, y) / REFERENCE_TILE_TEXELS); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(SPREADING_SIGMA_2K, rust.spreading_smoothness)); let mut field = drips(inp, rust, &field, (width, height), &tile_texels); - blur_over_cover(&mut field, &cover, (width, height), block, sigma_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); + blur_over_cover(&mut field, &cover, (width, height), block, radius_at(DRIPS_SIGMA_2K, rust.drips_smoothness)); field.iter_mut().zip(&cover).for_each(|(value, covered)| *value = if *covered > 0.0 { value.clamp(0.0, 1.0) } else { 0.0 }); field } -/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) -fn box_radius(sigma: f32) -> usize { - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize -} - /// `values` blurred within each UV tile block by the radius `radius_at` gives, weighted by `cover` so the empty space around the islands doesn't bleed in fn blur_over_cover(values: &mut [f32], cover: &[f32], size: (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize + Copy) { let mut sums: Vec = values.iter().zip(cover).map(|(value, covered)| value * covered).collect(); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 648a98fa..a98e07a9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3638,9 +3638,10 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); - let textured = match (generator.texture_in_use(), self.generator_texture(generator)) { - (Some(texture), Some(gray)) => texture_layer::blended_over(texture, adjusted, gray), - _ => adjusted, + // An image still loading reads black, as it does where blur or resolution compute the generator over a region + let textured = match generator.texture_in_use() { + Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), + None => adjusted, }; finish_generator(generator, textured) } diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs new file mode 100644 index 00000000..910ce75c --- /dev/null +++ b/crates/compose/src/field_cache.rs @@ -0,0 +1,66 @@ +use std::sync::{Arc, Mutex}; + +use crate::eval::Inputs; +use crate::field_cache_key::FieldCacheKey; +use crate::working_field::working_block; + +/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) +const CACHE_ENTRIES: usize = 8; +const CACHE_BYTES: usize = 256 << 20; + +/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile +const FINGERPRINT_STRIDE: usize = 31; + +/// Built fields by what they were built from, most recently used last +pub(crate) struct FieldCache { + entries: Mutex>)>>, +} + +impl FieldCache { + pub(crate) const fn new() -> FieldCache { + FieldCache { entries: Mutex::new(Vec::new()) } + } + + /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + let gbuf = inp.gbuf; + let block = working_block(inp); + let key = FieldCacheKey { + layout: gbuf.tri.as_ptr() as usize, + size: (gbuf.width, gbuf.height), + fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + block, + scales: inp.block_scales.clone(), + mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len(), inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), + maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + settings, + }; + + let cached = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); + entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + }; + if let Some(field) = cached { + return field; + } + + let field = Arc::new(build(block)); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, field.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + field + } +} diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs new file mode 100644 index 00000000..fa84471e --- /dev/null +++ b/crates/compose/src/field_cache_key.rs @@ -0,0 +1,30 @@ +use std::sync::Weak; + +use texturecraft_core::BlockScales; + +/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits +#[derive(Clone)] +pub(crate) struct FieldCacheKey { + pub(crate) layout: usize, + pub(crate) size: (u32, u32), + pub(crate) fingerprint: u64, + pub(crate) block: (u32, u32), + pub(crate) scales: BlockScales, + pub(crate) mesh: (usize, usize, usize, usize), + pub(crate) maps: Vec>>, + pub(crate) settings: Vec, +} + +impl PartialEq for FieldCacheKey { + fn eq(&self, other: &FieldCacheKey) -> bool { + let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + same_maps + && self.layout == other.layout + && self.size == other.size + && self.fingerprint == other.fingerprint + && self.block == other.block + && self.scales == other.scales + && self.mesh == other.mesh + && self.settings == other.settings + } +} diff --git a/crates/compose/src/grunge_pattern.rs b/crates/compose/src/grunge_pattern.rs new file mode 100644 index 00000000..5005bb73 --- /dev/null +++ b/crates/compose/src/grunge_pattern.rs @@ -0,0 +1,37 @@ +use texturecraft_core::{GeneratorKind, ProceduralKind}; + +/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) +pub(crate) struct GrungePattern { + pub(crate) kind: ProceduralKind, + pub(crate) repeats_per_scale: f32, + pub(crate) rotation: f32, + /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change + pub(crate) breakup: Option<(ProceduralKind, f32)>, + pub(crate) mean: f32, + pub(crate) spread: f32, + /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) + pub(crate) custom_gain: f32, +} + +/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt +pub(crate) const EDGE_WEAR_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; +pub(crate) const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { + kind: ProceduralKind::Weave, + repeats_per_scale: 16.0, + rotation: 45.0, + breakup: Some((ProceduralKind::Grunge, 4.0)), + mean: 0.539, + spread: 0.198, + custom_gain: 1.9, +}; +pub(crate) const DIRT_GRUNGE: GrungePattern = + GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; + +pub(crate) fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { + match kind { + GeneratorKind::Dirt => &DIRT_GRUNGE, + GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, + _ => &EDGE_WEAR_GRUNGE, + } +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index eb85e0ae..e7d72fe8 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,6 +20,8 @@ pub mod environment_sh; pub mod environment_sky; pub mod eval; mod fabric; +mod field_cache; +mod field_cache_key; pub mod fill_copies; pub mod fill_copy; mod fill_depth; @@ -27,6 +29,7 @@ mod fill_place; pub mod frame_placement; mod fur_lock; mod generator_maps; +mod grunge_pattern; mod held_fields; mod histogram_scan; mod image_identity; @@ -43,6 +46,7 @@ pub mod projector_view; mod sections; mod shape_distance; mod slope_texel; +mod slot_placement; mod soft_box; pub mod solo; pub mod store; diff --git a/crates/compose/src/micro_details/anchor_entry.rs b/crates/compose/src/micro_details/anchor_entry.rs new file mode 100644 index 00000000..c530cb85 --- /dev/null +++ b/crates/compose/src/micro_details/anchor_entry.rs @@ -0,0 +1,15 @@ +use std::sync::{Arc, Weak}; + +use texturecraft_core::LayerId; + +use super::anchor_heights::AnchorHeights; +use crate::below::StackKey; + +/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key +pub(super) struct AnchorEntry { + pub(super) baked: Weak>, + pub(super) texture_set: usize, + pub(super) anchor: LayerId, + pub(super) stack: StackKey, + pub(super) heights: Arc, +} diff --git a/crates/compose/src/micro_details/anchor_heights.rs b/crates/compose/src/micro_details/anchor_heights.rs new file mode 100644 index 00000000..0a8b5c18 --- /dev/null +++ b/crates/compose/src/micro_details/anchor_heights.rs @@ -0,0 +1,24 @@ +use texturecraft_core::BlockScales; + +/// An anchor point's height over the whole texture set, in the working atlas's layout +pub struct AnchorHeights { + data: Vec, + working_size: (u32, u32), + scales: BlockScales, +} + +impl AnchorHeights { + pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { + AnchorHeights { data, working_size, scales } + } + + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) + pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { + let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; + let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; + + let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); + let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); + self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) + } +} diff --git a/crates/compose/src/micro_details/cache_key.rs b/crates/compose/src/micro_details/cache_key.rs new file mode 100644 index 00000000..ee0b6bc2 --- /dev/null +++ b/crates/compose/src/micro_details/cache_key.rs @@ -0,0 +1,24 @@ +use std::sync::Weak; + +use super::slot_key::SlotKey; + +/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block +#[derive(Clone)] +pub(super) struct CacheKey { + pub(super) map: Weak>, + pub(super) height: Option, + pub(super) normal: Option, + pub(super) settings: Vec, + pub(super) block: (u32, u32), +} + +impl PartialEq for CacheKey { + fn eq(&self, other: &CacheKey) -> bool { + self.map.strong_count() > 0 + && self.map.ptr_eq(&other.map) + && self.height == other.height + && self.normal == other.normal + && self.settings == other.settings + && self.block == other.block + } +} diff --git a/crates/compose/src/micro_details/cached_bytes.rs b/crates/compose/src/micro_details/cached_bytes.rs new file mode 100644 index 00000000..46847139 --- /dev/null +++ b/crates/compose/src/micro_details/cached_bytes.rs @@ -0,0 +1,4 @@ +/// What a cached map holds, to keep the cache within [`CACHE_BYTES`](super::CACHE_BYTES) +pub(super) trait CachedBytes { + fn bytes(&self) -> usize; +} diff --git a/crates/compose/src/micro_details/layout_map.rs b/crates/compose/src/micro_details/layout_map.rs new file mode 100644 index 00000000..477129b1 --- /dev/null +++ b/crates/compose/src/micro_details/layout_map.rs @@ -0,0 +1,26 @@ +use texturecraft_core::BlockScales; + +use super::cached_bytes::CachedBytes; + +/// A map in a mesh map's layout: `size` texels, each UV tile one block +pub struct LayoutMap { + pub(super) data: Vec, + pub(super) size: (u32, u32), +} + +impl LayoutMap { + /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) + pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { + let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; + let baked_uv = scales.bake_uv(uv, working_size)?; + let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); + let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); + self.data.get((row * self.size.0 + column) as usize).copied() + } +} + +impl CachedBytes for LayoutMap { + fn bytes(&self) -> usize { + self.data.len().saturating_mul(size_of::()) + } +} diff --git a/crates/compose/src/micro_details/micro_cache.rs b/crates/compose/src/micro_details/micro_cache.rs new file mode 100644 index 00000000..4aea74e7 --- /dev/null +++ b/crates/compose/src/micro_details/micro_cache.rs @@ -0,0 +1,51 @@ +use std::sync::{Arc, Mutex}; + +use super::cache_key::CacheKey; +use super::cached_bytes::CachedBytes; +use super::{CACHE_BYTES, CACHE_ENTRIES}; + +/// Built maps by what they were built from, most recently used last +pub(super) struct MicroCache { + entries: Mutex)>>, +} + +impl MicroCache { + pub(super) const fn new() -> MicroCache { + MicroCache { entries: Mutex::new(Vec::new()) } + } + + /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) + pub(super) fn get_or_build(&self, key: CacheKey, build: impl FnOnce() -> T) -> Arc { + let found = { + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(key, _)| key.map.strong_count() > 0); + entries.iter().position(|(cached, _)| *cached == key).map(|index| { + let entry = entries.remove(index); + let built = entry.1.clone(); + entries.push(entry); + built + }) + }; + if let Some(built) = found { + return built; + } + + let built = Arc::new(build()); + let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + entries.retain(|(cached, _)| *cached != key); + entries.push((key, built.clone())); + let mut bytes = 0usize; + let keep = entries + .iter() + .rev() + .take_while(|(_, built)| { + bytes = bytes.saturating_add(built.bytes()); + bytes <= CACHE_BYTES + }) + .count() + .clamp(1, CACHE_ENTRIES); + let excess = entries.len().saturating_sub(keep); + entries.drain(..excess); + built + } +} diff --git a/crates/compose/src/micro_details/micro_curvature.rs b/crates/compose/src/micro_details/micro_curvature.rs new file mode 100644 index 00000000..2ffd1bff --- /dev/null +++ b/crates/compose/src/micro_details/micro_curvature.rs @@ -0,0 +1,47 @@ +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, GeneratorKind, MicroDetails}; + +use super::cache_key::CacheKey; +use super::cached_bytes::CachedBytes; +use super::layout_map::LayoutMap; +use super::slot::Slot; +use super::{CURVATURE_CACHE, by_blocks, curvature_term, layout}; +use crate::eval::Inputs; + +/// The curvature a generator's micro details add +pub struct MicroCurvature { + /// What they add to the curvature input + pub term: LayoutMap, + /// The baked curvature with the term added, which the detail sizes blur + pub curvature: Arc>, +} + +impl MicroCurvature { + /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) + pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { + let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; + let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); + let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); + let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; + let key = CacheKey { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; + + Some(CURVATURE_CACHE.get_or_build(key, || { + let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); + let term = by_blocks(size, block, same_in_every_block, |origin, block| { + let height = height.as_ref().map(|height| height.in_block(origin, size)); + let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); + curvature_term(micro, height.as_ref(), normal.as_ref(), block) + }); + let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); + MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } + })) + } +} + +impl CachedBytes for MicroCurvature { + fn bytes(&self) -> usize { + self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) + } +} diff --git a/crates/compose/src/micro_details.rs b/crates/compose/src/micro_details/mod.rs similarity index 62% rename from crates/compose/src/micro_details.rs rename to crates/compose/src/micro_details/mod.rs index 35132998..cc4bf6e4 100644 --- a/crates/compose/src/micro_details.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -1,13 +1,29 @@ //! A generator's micro details: the curvature and occlusion its micro height (an image or an anchor point's height) and normal image add to its mesh maps, built once per map, image and settings +mod anchor_entry; +mod anchor_heights; +mod cache_key; +mod cached_bytes; +mod layout_map; +mod micro_cache; +mod micro_curvature; +mod slot; +mod slot_key; + use std::sync::{Arc, Mutex, Weak}; +use anchor_entry::AnchorEntry; +pub use anchor_heights::AnchorHeights; +use cache_key::CacheKey; +pub use layout_map::LayoutMap; +use micro_cache::MicroCache; +pub use micro_curvature::MicroCurvature; use rayon::prelude::*; -use texturecraft_core::{BakedMap, BlockScales, GeneratorKind, LayerId, MicroCurvatureType, MicroDetails, NormalFormat, Source}; +use slot::Slot; +use texturecraft_core::{BakedMap, LayerId, MicroCurvatureType, MicroDetails}; use crate::below::StackKey; -use crate::eval::Inputs; -use crate::store::ImageRes; +use crate::eval::{BLUR_BOX_PASSES, Inputs}; /// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size const REFERENCE_TILE_TEXELS: f32 = 2048.0; @@ -21,6 +37,9 @@ const SMOOTH_SIGMAS: [f32; 7] = [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]; /// Below this sigma a blur is an explicit kernel; wider ones are three box passes const BOX_BLUR_MIN_SIGMA: f32 = 2.0; +/// How many sigmas the sampled kernel reaches each side +const KERNEL_REACH_SIGMAS: f32 = 3.0; + /// Directions the occlusion looks along const OCCLUSION_DIRECTIONS: usize = 16; @@ -45,80 +64,6 @@ const OCCLUSION_STRENGTH: f32 = 0.3232; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// What a cached map holds, to keep the cache within [`CACHE_BYTES`] -trait CachedBytes { - fn bytes(&self) -> usize; -} - -impl CachedBytes for LayoutMap { - fn bytes(&self) -> usize { - self.data.len().saturating_mul(size_of::()) - } -} - -impl CachedBytes for MicroCurvature { - fn bytes(&self) -> usize { - self.term.bytes().saturating_add(self.curvature.len().saturating_mul(size_of::())) - } -} - -/// A map in a mesh map's layout: `size` texels, each UV tile one block -pub struct LayoutMap { - data: Vec, - size: (u32, u32), -} - -impl LayoutMap { - /// The value under working texel (`x`, `y`) of a `working_size` atlas laid out by `scales` (None outside the layout) - pub fn at(&self, (x, y): (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Option { - let uv = [(x as f32 + 0.5) / working_size.0.max(1) as f32, (y as f32 + 0.5) / working_size.1.max(1) as f32]; - let baked_uv = scales.bake_uv(uv, working_size)?; - let column = ((baked_uv[0] * self.size.0 as f32) as u32).min(self.size.0.saturating_sub(1)); - let row = ((baked_uv[1] * self.size.1 as f32) as u32).min(self.size.1.saturating_sub(1)); - self.data.get((row * self.size.0 + column) as usize).copied() - } -} - -/// The curvature a generator's micro details add -pub struct MicroCurvature { - /// What they add to the curvature input - pub term: LayoutMap, - /// The baked curvature with the term added, which the detail sizes blur - pub curvature: Arc>, -} - -/// An anchor point's height over the whole texture set, in the working atlas's layout -pub struct AnchorHeights { - data: Vec, - working_size: (u32, u32), - scales: BlockScales, -} - -impl AnchorHeights { - pub fn new(data: Vec, working_size: (u32, u32), scales: BlockScales) -> AnchorHeights { - AnchorHeights { data, working_size, scales } - } - - /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) - fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { - let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; - let Some(uv) = self.scales.working_uv(baked_uv, self.working_size) else { return 0.0 }; - - let column = ((uv[0] * self.working_size.0 as f32) as u32).min(self.working_size.0.saturating_sub(1)); - let row = ((uv[1] * self.working_size.1 as f32) as u32).min(self.working_size.1.saturating_sub(1)); - self.data.get((row * self.working_size.0 + column) as usize).copied().unwrap_or(0.0) - } -} - -/// The anchor heights built for a texture set's stack: the mesh maps they were built beside, the set, the anchor and the stack's key -struct AnchorEntry { - baked: Weak>, - texture_set: usize, - anchor: LayerId, - stack: StackKey, - heights: Arc, -} - /// The anchor heights prepared last, one per mesh maps, texture set and anchor static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); @@ -167,188 +112,13 @@ fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { entries.iter().find(|entry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor).map(|entry| entry.heights.clone()) } -/// What a micro details slot reads -#[derive(Clone)] -enum Slot { - Uniform([f32; 3]), - Image { - image: Arc, - flip_green: bool, - }, - /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map - Anchor { - heights: Arc, - origin: (u32, u32), - layout: (u32, u32), - }, -} - -impl Slot { - /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) - fn of(inp: &Inputs, source: Option<&Source>) -> Slot { - match source { - Some(Source::Uniform(value)) => Slot::Uniform(*value), - Some(Source::Image { name, normal_format }) => match inp.images.get(name) { - Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, - None => Slot::Uniform([0.0; 3]), - }, - Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { - Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, - None => Slot::Uniform([0.0; 3]), - }, - _ => Slot::Uniform([0.0; 3]), - } - } - - /// Whether every UV tile block reads the same (an image or a value repeats in each) - fn same_in_every_block(&self) -> bool { - !matches!(self, Slot::Anchor { .. }) - } - - /// The slot read in the block at `origin` of a `layout` sized mesh map - fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { - match self { - Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, - other => other.clone(), - } - } - - fn key(&self) -> SlotKey { - match self { - Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), - Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), - Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), - } - } - - /// The slot's color at `uv`, in the file's encoding - fn color(&self, uv: [f32; 2]) -> [f32; 3] { - match self { - Slot::Uniform(value) => *value, - Slot::Image { image, .. } => { - let [red, green, blue, _] = image.sample(uv[0], uv[1]); - [red, green, blue] - } - Slot::Anchor { .. } => [0.0; 3], - } - } - - /// The slot read as a height (its gray) over a `size` block - fn heights(&self, size: (u32, u32)) -> Vec { - match self { - Slot::Anchor { heights, origin, layout } => { - (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() - } - _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), - } - } - - /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention - fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { - let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); - block_uvs(size) - .map(|uv| { - let [red, green, _] = self.color(uv); - let y = green * 2.0 - 1.0; - (red * 2.0 - 1.0, if flip_green { -y } else { y }) - }) - .unzip() - } -} - /// The UV of each texel's center in a `size` block, row by row fn block_uvs((width, height): (u32, u32)) -> impl Iterator { (0..height).flat_map(move |y| (0..width).map(move |x| [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32])) } -/// A slot as a cache key: an image by identity, a value by its bits -#[derive(Clone)] -enum SlotKey { - Uniform([u32; 3]), - Image(Weak, bool), - Anchor(Weak), -} - -impl PartialEq for SlotKey { - fn eq(&self, other: &SlotKey) -> bool { - match (self, other) { - (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, - (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, - (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), - _ => false, - } - } -} - -/// What a micro map was built from: the mesh map giving its layout, its slots, its settings' bits and its UV tile block -#[derive(Clone)] -struct Key { - map: Weak>, - height: Option, - normal: Option, - settings: Vec, - block: (u32, u32), -} - -impl PartialEq for Key { - fn eq(&self, other: &Key) -> bool { - self.map.strong_count() > 0 - && self.map.ptr_eq(&other.map) - && self.height == other.height - && self.normal == other.normal - && self.settings == other.settings - && self.block == other.block - } -} - -/// Built maps by what they were built from, most recently used last -struct Cache { - entries: Mutex)>>, -} - -impl Cache { - const fn new() -> Cache { - Cache { entries: Mutex::new(Vec::new()) } - } - - /// The map built from `key`, built by `build` when missing (outside the lock: the build runs parallel work) - fn get_or_build(&self, key: Key, build: impl FnOnce() -> T) -> Arc { - let found = { - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.map.strong_count() > 0); - entries.iter().position(|(cached, _)| *cached == key).map(|index| { - let entry = entries.remove(index); - let built = entry.1.clone(); - entries.push(entry); - built - }) - }; - if let Some(built) = found { - return built; - } - - let built = Arc::new(build()); - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(cached, _)| *cached != key); - entries.push((key, built.clone())); - let mut bytes = 0usize; - let keep = entries - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.bytes()); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = entries.len().saturating_sub(keep); - entries.drain(..excess); - built - } -} - -static CURVATURE_CACHE: Cache = Cache::new(); -static OCCLUSION_CACHE: Cache = Cache::new(); +static CURVATURE_CACHE: MicroCache = MicroCache::new(); +static OCCLUSION_CACHE: MicroCache = MicroCache::new(); /// A baked map, its size and the size of one UV tile's block in it type MapLayout = (Arc>, (u32, u32), (u32, u32)); @@ -388,34 +158,12 @@ fn by_blocks(size: (u32, u32), block: (u32, u32), same_in_every_block: bool, per data } -impl MicroCurvature { - /// The curvature `micro` adds on a `kind` generator, in the baked curvature map's layout (None without a baked curvature map) - pub fn of(inp: &Inputs, kind: GeneratorKind, micro: &MicroDetails) -> Option> { - let (curvature, size, block) = layout(inp, BakedMap::Curvature)?; - let height = micro.height.then(|| Slot::of(inp, micro.height_source.as_ref())); - let normal = micro.normal.then(|| Slot::of(inp, micro.normal_source.as_ref())); - let settings = vec![micro.curvature_type as u32, micro.curvature_intensity.to_bits(), micro.height_intensity.to_bits(), kind as u32]; - let key = Key { map: Arc::downgrade(&curvature), height: height.as_ref().map(Slot::key), normal: normal.as_ref().map(Slot::key), settings, block }; - - Some(CURVATURE_CACHE.get_or_build(key, || { - let same_in_every_block = height.iter().chain(&normal).all(Slot::same_in_every_block); - let term = by_blocks(size, block, same_in_every_block, |origin, block| { - let height = height.as_ref().map(|height| height.in_block(origin, size)); - let normal = normal.as_ref().map(|normal| normal.in_block(origin, size)); - curvature_term(micro, height.as_ref(), normal.as_ref(), block) - }); - let adjusted = curvature.par_iter().zip(term.par_iter()).map(|(curvature, term)| curvature + term).collect(); - MicroCurvature { term: LayoutMap { data: term, size }, curvature: Arc::new(adjusted) } - })) - } -} - /// What the occlusion input is multiplied by: the micro height's occlusion in the baked AO map's layout (None without a baked AO map or a micro height) pub fn micro_occlusion(inp: &Inputs, micro: &MicroDetails) -> Option> { let (occlusion, size, block) = layout(inp, BakedMap::AmbientOcclusion)?; let height = Slot::of(inp, micro.height.then_some(micro.height_source.as_ref())?); let settings = vec![micro.ao_radius.to_bits(), micro.ao_depth.to_bits()]; - let key = Key { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; + let key = CacheKey { map: Arc::downgrade(&occlusion), height: Some(height.key()), normal: None, settings, block }; Some(OCCLUSION_CACHE.get_or_build(key, || { let data = by_blocks(size, block, height.same_in_every_block(), |origin, block| occlusion_factor(micro, &height.in_block(origin, size), block)); @@ -520,7 +268,7 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { // Three box passes of radius r spread a value with variance r(r + 1) let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; let mut current = line.to_vec(); - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_blur(¤t, out, radius); current.copy_from_slice(out); } @@ -531,7 +279,7 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { /// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { - let reach = (3.0 * sigma).ceil().max(1.0) as i64; + let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64; let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); let total: f32 = weights.iter().sum(); let length = line.len().max(1) as i64; @@ -612,6 +360,8 @@ fn occlusion_factor(micro: &MicroDetails, height: &Slot, size: (u32, u32)) -> Ve #[cfg(test)] mod tests { + use texturecraft_core::GeneratorKind; + use super::*; #[test] diff --git a/crates/compose/src/micro_details/slot.rs b/crates/compose/src/micro_details/slot.rs new file mode 100644 index 00000000..1c5f8c62 --- /dev/null +++ b/crates/compose/src/micro_details/slot.rs @@ -0,0 +1,98 @@ +use std::sync::Arc; + +use texturecraft_core::{NormalFormat, Source}; + +use super::anchor_heights::AnchorHeights; +use super::slot_key::SlotKey; +use super::{anchor_heights, block_uvs}; +use crate::eval::Inputs; +use crate::store::ImageRes; + +/// What a micro details slot reads +#[derive(Clone)] +pub(super) enum Slot { + Uniform([f32; 3]), + Image { + image: Arc, + flip_green: bool, + }, + /// An anchor point's height, different in each UV tile block: read from the block at `origin` of a `layout` sized mesh map + Anchor { + heights: Arc, + origin: (u32, u32), + layout: (u32, u32), + }, +} + +impl Slot { + /// The slot holding `source` (an empty slot, an image not loaded and an anchor not prepared yet read black; procedurals are not read) + pub(super) fn of(inp: &Inputs, source: Option<&Source>) -> Slot { + match source { + Some(Source::Uniform(value)) => Slot::Uniform(*value), + Some(Source::Image { name, normal_format }) => match inp.images.get(name) { + Some(image) => Slot::Image { image: image.clone(), flip_green: *normal_format == NormalFormat::DirectX }, + None => Slot::Uniform([0.0; 3]), + }, + Some(Source::Anchor { anchor, .. }) => match anchor_heights(inp, *anchor) { + Some(heights) => Slot::Anchor { heights, origin: (0, 0), layout: (0, 0) }, + None => Slot::Uniform([0.0; 3]), + }, + _ => Slot::Uniform([0.0; 3]), + } + } + + /// Whether every UV tile block reads the same (an image or a value repeats in each) + pub(super) fn same_in_every_block(&self) -> bool { + !matches!(self, Slot::Anchor { .. }) + } + + /// The slot read in the block at `origin` of a `layout` sized mesh map + pub(super) fn in_block(&self, origin: (u32, u32), layout: (u32, u32)) -> Slot { + match self { + Slot::Anchor { heights, .. } => Slot::Anchor { heights: heights.clone(), origin, layout }, + other => other.clone(), + } + } + + pub(super) fn key(&self) -> SlotKey { + match self { + Slot::Uniform(value) => SlotKey::Uniform(value.map(f32::to_bits)), + Slot::Image { image, flip_green } => SlotKey::Image(Arc::downgrade(image), *flip_green), + Slot::Anchor { heights, .. } => SlotKey::Anchor(Arc::downgrade(heights)), + } + } + + /// The slot's color at `uv`, in the file's encoding + pub(super) fn color(&self, uv: [f32; 2]) -> [f32; 3] { + match self { + Slot::Uniform(value) => *value, + Slot::Image { image, .. } => { + let [red, green, blue, _] = image.sample(uv[0], uv[1]); + [red, green, blue] + } + Slot::Anchor { .. } => [0.0; 3], + } + } + + /// The slot read as a height (its gray) over a `size` block + pub(super) fn heights(&self, size: (u32, u32)) -> Vec { + match self { + Slot::Anchor { heights, origin, layout } => { + (0..size.1).flat_map(|row| (0..size.0).map(move |column| (origin.0 + column, origin.1 + row))).map(|texel| heights.at(texel, *layout)).collect() + } + _ => block_uvs(size).map(|uv| self.color(uv).iter().sum::() / 3.0).collect(), + } + } + + /// The slot read as a normal over a `size` block: its X and Y, OpenGL convention + pub(super) fn normals(&self, size: (u32, u32)) -> (Vec, Vec) { + let flip_green = matches!(self, Slot::Image { flip_green: true, .. }); + block_uvs(size) + .map(|uv| { + let [red, green, _] = self.color(uv); + let y = green * 2.0 - 1.0; + (red * 2.0 - 1.0, if flip_green { -y } else { y }) + }) + .unzip() + } +} diff --git a/crates/compose/src/micro_details/slot_key.rs b/crates/compose/src/micro_details/slot_key.rs new file mode 100644 index 00000000..fdd853e3 --- /dev/null +++ b/crates/compose/src/micro_details/slot_key.rs @@ -0,0 +1,23 @@ +use std::sync::Weak; + +use super::anchor_heights::AnchorHeights; +use crate::store::ImageRes; + +/// A slot as a cache key: an image by identity, a value by its bits +#[derive(Clone)] +pub(super) enum SlotKey { + Uniform([u32; 3]), + Image(Weak, bool), + Anchor(Weak), +} + +impl PartialEq for SlotKey { + fn eq(&self, other: &SlotKey) -> bool { + match (self, other) { + (SlotKey::Uniform(a), SlotKey::Uniform(b)) => a == b, + (SlotKey::Image(a, a_flip), SlotKey::Image(b, b_flip)) => a.strong_count() > 0 && a.ptr_eq(b) && a_flip == b_flip, + (SlotKey::Anchor(a), SlotKey::Anchor(b)) => a.strong_count() > 0 && a.ptr_eq(b), + _ => false, + } + } +} diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index bee4012d..76e4d2a6 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -31,6 +31,7 @@ pub(crate) fn axes_signal(channels: [f32; 3], axes: &[AxisLayer; 3]) -> f32 { if axis.weight <= 0.0 { return base; } + let layer = if axis.invert { 1.0 - channels[index] } else { channels[index] }; (base + (blended(axis.blend, base, layer) - base) * axis.weight).clamp(0.0, 1.0) }) @@ -81,11 +82,14 @@ pub(crate) fn adjusted(kind: GeneratorKind, section: &SectionParameters, signal: value.powf(BALANCE_POWER_BASE.powf(2.0 * balance - 1.0)) }; } + value = contrasted(value, section.contrast.clamp(0.0, 1.0)); + if SectionParameters::has_brightness(kind) { let brightness = section.brightness.clamp(*SectionParameters::BRIGHTNESS_RANGE.start(), *SectionParameters::BRIGHTNESS_RANGE.end()); value = if brightness > 0.0 { value + brightness * (1.0 - value) } else { value * (1.0 + brightness) }; } + if section.invert { 1.0 - value } else { value } } diff --git a/crates/compose/src/slot_placement.rs b/crates/compose/src/slot_placement.rs new file mode 100644 index 00000000..69af657b --- /dev/null +++ b/crates/compose/src/slot_placement.rs @@ -0,0 +1,7 @@ +/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` +pub(crate) struct SlotPlacement { + pub scale: f32, + pub offset: f32, + /// How sharply the three projections meet, or None to read in UV + pub triplanar_contrast: Option, +} diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index e9042d05..02cf6769 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -3,20 +3,14 @@ use texturecraft_core::{TextureBlend, TextureLayer}; use texturecraft_geom::glam::{Vec2, Vec3}; +pub(crate) use crate::slot_placement::SlotPlacement; + /// Exponent of the triplanar weights per unit of `1 / (1 − triplanar contrast)`: contrast 0 weighs the axes by the normal itself, 0.5 by its cube const TRIPLANAR_SHARPNESS_POWER: f32 = 1.58; /// Smallest normal component still dividing the weights, so a zero normal weighs the axes evenly const MIN_NORMAL_COMPONENT: f32 = 1e-6; -/// Where a generator's image slot is read: `scale` times across the UV square (or the mesh's bounds, triplanar), plus `offset` -pub(crate) struct SlotPlacement { - pub scale: f32, - pub offset: f32, - /// How sharply the three projections meet, or None to read in UV - pub triplanar_contrast: Option, -} - /// The texture is scaled about the centre of the UV square (or of the mesh's bounds) pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index c4d1af41..b324e4ac 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -6,7 +6,8 @@ use rayon::prelude::*; use texturecraft_core::{BorderDistanceParameters, GeneratorGlobal}; use crate::eval::Inputs; -use crate::working_field::{FieldCache, blur_blocks}; +use crate::field_cache::FieldCache; +use crate::working_field::{REFERENCE_TILE_TEXELS, blur_blocks, box_radius}; /// How far in the gradient reaches at Distance 1, in UV units (fitted: about half a UV tile) const REACH_PER_DISTANCE: f32 = 0.4936; @@ -14,9 +15,6 @@ const REACH_PER_DISTANCE: f32 = 0.4936; /// The blur at Smoothness 1, as a gaussian sigma in texels of a 2K UV tile (fitted) const SMOOTHNESS_SIGMA_2K: f32 = 45.0; -/// The UV tile resolution [`SMOOTHNESS_SIGMA_2K`] is measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) @@ -52,10 +50,7 @@ fn build(inp: &Inputs, border: &BorderDistanceParameters, block: (u32, u32)) -> // Smoothness blurs the gradient with the empty space around the islands, so their borders soften towards black if border.smoothness > 0.0 { - let radius_at = |tile_texels: f32| { - let sigma = border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS; - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize - }; + let radius_at = |tile_texels: f32| box_radius(border.smoothness * SMOOTHNESS_SIGMA_2K * tile_texels / REFERENCE_TILE_TEXELS); blur_blocks(&mut gradient, (width, height), block, |left, top| radius_at(block.0 as f32 * inp.block_scales.at(left, top))); for (value, texel) in gradient.iter_mut().zip(0..) { if !gbuf.covered(texel) { diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 124ece1b..6ce27082 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -10,8 +10,9 @@ use texturecraft_texel::linear_to_srgb; use texturecraft_texel::noise::cell_hash; use crate::eval::{Inputs, texel_coords}; +use crate::field_cache::FieldCache; use crate::uv_border_distance::border_distances; -use crate::working_field::FieldCache; +use crate::working_field::REFERENCE_TILE_TEXELS; static CACHE: FieldCache = FieldCache::new(); @@ -67,9 +68,6 @@ const MAJOR_LINE_SHADE: f32 = 0.4230; const LINE_HALF_WIDTH_2K: f32 = 1.0; const BORDER_TEXELS_PER_WIDTH_2K: f32 = 15.0; -/// The UV tile resolution the sizes above are measured at -const REFERENCE_TILE_TEXELS: f32 = 2048.0; - /// The saturation and value random island colors are picked within (measured) const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; @@ -93,7 +91,7 @@ pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u let (x, y) = (texel % width, texel / width); let texels_2k = REFERENCE_TILE_TEXELS / (block.0 as f32 * inp.block_scales.at(x, y)); // Measured from the texel's 2K sub-texel nearest the border, so a coarser texel still shows the border it holds - let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - (texels_2k - 1.0).max(0.0); + let to_border = distances.get(texel as usize).copied().unwrap_or(0.0) * texels_2k - footprint_beyond_one(texels_2k); let color = if checker.border_width > 0.0 && to_border <= checker.border_width * BORDER_TEXELS_PER_WIDTH_2K { border } else { @@ -108,6 +106,11 @@ pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u }) } +/// How many 2K texels a working texel `texels_2k` of them wide covers beyond the one at its centre +fn footprint_beyond_one(texels_2k: f32) -> f32 { + (texels_2k - 1.0).max(0.0) +} + /// The checker's sRGB-encoded color at (`x`, `y`) in texels of a 2K UV tile (row 0 at the top) for a texel `texels_2k` of them wide, with `light` its light squares fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f32), texels_2k: f32) -> [f32; 3] { let square = REFERENCE_TILE_TEXELS / (SQUARES_PER_GRID_TILE * checker.grid_tile.max(1) as f32); @@ -117,7 +120,7 @@ fn checker_color(checker: &UvCheckerParameters, light: [f32; 3], (x, y): (f32, f // Line layers in the reference's order, each laid over the last at the grid's opacity let minor = square / MINOR_LINES_PER_SQUARE; // A texel is on a line when its footprint overlaps the line's band, so lines stay visible on coarser texels - let reach = LINE_HALF_WIDTH_2K + (texels_2k - 1.0).max(0.0) * 0.5; + let reach = LINE_HALF_WIDTH_2K + footprint_beyond_one(texels_2k) / 2.0; let on_line = |position: f32, period: f32| (position - (position / period).round() * period).abs() < reach; let layers = [ (on_line(y, minor) && !on_line(y, square), MINOR_LINE_SHADE), diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 864ae755..14903b8f 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -1,12 +1,11 @@ //! The wear generators' value at a texel (Metal Edge Wear, Fiber Glass Edge Wear, Dirt), fitted to the reference app's observed results -use texturecraft_core::{GeneratorKind, Procedural, ProceduralKind, Projection, WearParameters}; +use texturecraft_core::{GeneratorKind, Procedural, Projection, WearParameters}; use crate::curvature_sizes::LEVEL_RADII; - +use crate::grunge_pattern::grunge_pattern; use crate::pattern::{Coords, procedural}; -use crate::texture_layer::SlotPlacement; - +use crate::slot_placement::SlotPlacement; use crate::wear_inputs::WearInputs; use crate::wear_scan::{DIRT_SCAN, EDGE_WEAR_SCAN, FIBER_GLASS_SCAN}; @@ -21,33 +20,6 @@ const SMOOTHED_SHARE: f32 = 0.5; /// Dirt reads its edges and cavities slightly softened, sigma in texels at 2K const DIRT_CURVATURE_SIGMA: f32 = 1.49; -/// The pattern that breaks a wear kind up, its repeats across the UV square (or the mesh, triplanar) per unit of grunge scale, its rotation in degrees, and its mean and spread over the UV square (measured by `grunge_is_normalised`) -struct GrungePattern { - kind: ProceduralKind, - repeats_per_scale: f32, - rotation: f32, - /// A seeded pattern and its repeats per unit of grunge scale that varies the pattern's strength, for patterns the seed doesn't change - breakup: Option<(ProceduralKind, f32)>, - mean: f32, - spread: f32, - /// How strongly a custom grunge's gray away from mid gray counts, in units of the normalised grunge (Dirt reads a brighter custom grunge as cleaner) - custom_gain: f32, -} - -/// Fine scratches on metal edges, a woven fibre on fibreglass, blotchy grime for dirt -const EDGE_WEAR_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Scratches, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.037, spread: 0.149, custom_gain: 6.22 }; -const FIBER_GLASS_GRUNGE: GrungePattern = GrungePattern { - kind: ProceduralKind::Weave, - repeats_per_scale: 16.0, - rotation: 45.0, - breakup: Some((ProceduralKind::Grunge, 4.0)), - mean: 0.539, - spread: 0.198, - custom_gain: 1.9, -}; -const DIRT_GRUNGE: GrungePattern = - GrungePattern { kind: ProceduralKind::Grunge, repeats_per_scale: 4.0, rotation: 0.0, breakup: None, mean: 0.682, spread: 0.242, custom_gain: -5.56 }; /// How much a breakup pattern varies the grunge's strength (0 none, 1 down to nothing) const BREAKUP_DEPTH: f32 = 0.6; @@ -69,14 +41,6 @@ pub(crate) fn blur_sigma(kind: GeneratorKind, wear: &WearParameters) -> f32 { } } -fn grunge_pattern(kind: GeneratorKind) -> &'static GrungePattern { - match kind { - GeneratorKind::Dirt => &DIRT_GRUNGE, - GeneratorKind::FiberGlassEdgeWear => &FIBER_GLASS_GRUNGE, - _ => &EDGE_WEAR_GRUNGE, - } -} - fn triplanar_sharpness(wear: &WearParameters) -> f32 { TRIPLANAR_SHARPNESS.start() + (TRIPLANAR_SHARPNESS.end() - TRIPLANAR_SHARPNESS.start()) * wear.triplanar_contrast } @@ -195,6 +159,7 @@ mod tests { use texturecraft_geom::glam::{Vec2, Vec3}; use super::*; + use crate::grunge_pattern::{DIRT_GRUNGE, EDGE_WEAR_GRUNGE, FIBER_GLASS_GRUNGE}; fn inputs(curvature: f32, occlusion: f32) -> WearInputs { WearInputs { curvature, blurred_curvature: curvature, occlusion, grunge: 0.0 } diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs index 55c3763b..5c4e9c49 100644 --- a/crates/compose/src/working_field.rs +++ b/crates/compose/src/working_field.rs @@ -1,98 +1,9 @@ //! Whole-map fields some generators precompute at the working resolution (UV Border Distance, Dripping Rust), built once per layout, mesh map and settings -use std::sync::{Arc, Mutex, Weak}; - -use texturecraft_core::BlockScales; - use crate::eval::{Inputs, blur}; -/// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; -const CACHE_BYTES: usize = 256 << 20; - -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; - -/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh, the mesh maps it reads and its settings' bits -#[derive(Clone)] -struct Key { - layout: usize, - size: (u32, u32), - fingerprint: u64, - block: (u32, u32), - scales: BlockScales, - mesh: (usize, usize), - maps: Vec>>, - settings: Vec, -} - -impl PartialEq for Key { - fn eq(&self, other: &Key) -> bool { - let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); - same_maps - && self.layout == other.layout - && self.size == other.size - && self.fingerprint == other.fingerprint - && self.block == other.block - && self.scales == other.scales - && self.mesh == other.mesh - && self.settings == other.settings - } -} - -/// Built fields by what they were built from, most recently used last -pub(crate) struct FieldCache { - entries: Mutex>)>>, -} - -impl FieldCache { - pub(crate) const fn new() -> FieldCache { - FieldCache { entries: Mutex::new(Vec::new()) } - } - - /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work - pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { - let gbuf = inp.gbuf; - let block = working_block(inp); - let key = Key { - layout: gbuf.tri.as_ptr() as usize, - size: (gbuf.width, gbuf.height), - fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), - block, - scales: inp.block_scales.clone(), - mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), - maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), - settings, - }; - - let cached = { - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); - entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) - }; - if let Some(field) = cached { - return field; - } - - let field = Arc::new(build(block)); - let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(cached, _)| *cached != key); - entries.push((key, field.clone())); - let mut bytes = 0usize; - let keep = entries - .iter() - .rev() - .take_while(|(_, built)| { - bytes = bytes.saturating_add(built.len().saturating_mul(size_of::())); - bytes <= CACHE_BYTES - }) - .count() - .clamp(1, CACHE_ENTRIES); - let excess = entries.len().saturating_sub(keep); - entries.drain(..excess); - field - } -} +/// The resolution of a UV tile the generators' fitted sizes are measured at +pub(crate) const REFERENCE_TILE_TEXELS: f32 = 2048.0; /// The size of one UV tile's block in `inp`'s working atlas pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { @@ -102,6 +13,11 @@ pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) } +/// The box radius whose repeated passes approximate a Gaussian of `sigma` +pub(crate) fn box_radius(sigma: f32) -> usize { + (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize +} + /// `data` blurred one UV tile block at a time by the radius `radius_at` gives for the block's corner, reading black past each block's edges pub(crate) fn blur_blocks(data: &mut [f32], (width, height): (u32, u32), block: (u32, u32), radius_at: impl Fn(u32, u32) -> usize) { for top in (0..height).step_by(block.1 as usize) { diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index b9bd92ea..3dcc0d46 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -160,6 +160,18 @@ fn overlay_with_a_mid_gray_texture_doubles_a_dark_signal_times_the_gray() { assert_all(&mask(&mut fixture, generator, &texels), OCCLUSION + (overlay - OCCLUSION) * 0.5, "overlay at half opacity"); } +#[test] +fn an_image_not_loaded_blends_black_with_or_without_a_blur() { + let mut fixture = fixture([0.6; 3]); + let texels: Vec<_> = surface(&fixture).iter().map(|point| point.texel).collect(); + let loading = occlusion_with("not loaded yet", TextureLayer { opacity: 0.5, ..replacing() }); + assert_all(&mask(&mut fixture, loading.clone(), &texels), OCCLUSION * 0.5, "per texel"); + + let mut blurred = loading; + blurred.global.blur = 0.5; + assert_all(&mask(&mut fixture, blurred, &texels), OCCLUSION * 0.5, "over a region, as the blur computes it"); +} + #[test] fn the_texture_blends_after_the_section_controls_and_before_the_global_ones() { let mut fixture = fixture([0.6; 3]); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 62db399d..2e4371b5 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1098,6 +1098,8 @@ impl GeneratorKind { pub fn parse(name: &str) -> Option { let normalised = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); + let wanted = normalised(name); + // The labels before the reference app's names, which agents may still send let earlier = |kind: GeneratorKind| match kind { GeneratorKind::EdgeWear => Some("Mask Editor: Edge wear"), @@ -1106,7 +1108,6 @@ impl GeneratorKind { _ => None, }; GeneratorKind::ALL.into_iter().find(|kind| { - let wanted = normalised(name); normalised(kind.id()) == wanted || normalised(kind.label()) == wanted || earlier(*kind).is_some_and(|label| normalised(label) == wanted) }) } diff --git a/crates/engine/src/generator_input.rs b/crates/engine/src/generator_input.rs new file mode 100644 index 00000000..4a5c65e0 --- /dev/null +++ b/crates/engine/src/generator_input.rs @@ -0,0 +1,12 @@ +use texturecraft_core::BakedMap; + +/// A generator input a command names: a mesh map it reads, its texture or its custom grunge +#[derive(Clone, Copy)] +pub(crate) enum GeneratorInput { + Map(BakedMap), + Texture, + Grunge, + MicroHeight, + MicroNormal, + Image, +} diff --git a/crates/engine/src/generator_pick.rs b/crates/engine/src/generator_pick.rs index b6195451..b0e9ea0f 100644 --- a/crates/engine/src/generator_pick.rs +++ b/crates/engine/src/generator_pick.rs @@ -46,7 +46,8 @@ fn pick_point(session: &mut Session, params: &Value) -> Result { let viewport = viewport_of(session, params); let screen = match (f32p(params, "x"), f32p(params, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), - _ => viewport * 0.5, + (None, None) => viewport * 0.5, + _ => return Err(bad(CMD, "give both `x` and `y`, or neither for the viewport's centre")), }; let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0)); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index bc0efe3c..14863420 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -153,6 +153,15 @@ fn generator_json(generator: &Generator) -> Value { if !generator.inputs.is_empty() { out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::>().into(); } + if let Some(wear) = &generator.wear { + out["wear"] = json!(wear); + } + if let Some(section) = &generator.section { + out["section"] = json!(section); + } + if let Some(light) = &generator.light { + out["light"] = json!(light); + } if let Some(texture) = &generator.texture { out["texture"] = json!(texture); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 82d395ce..cb0519b8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod filter_about; pub mod filter_lib; pub mod folder_cmds; mod frame_target; +mod generator_input; pub mod generator_pick; pub mod id_mask_view; pub mod inspect; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e7ef1e7a..a746f431 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -10,6 +10,7 @@ use texturecraft_core::{ use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::distance_params::distance_from; +use crate::generator_input::GeneratorInput; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro}; @@ -391,7 +392,6 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend) } -/// Apply `params` to `generator`, using `command` in errors /// The parameters that drive the wear generators' earlier model const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale", "offset", "mode", "sizes"]; @@ -550,6 +550,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res None => Ok(()), }; } + if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) { return Err(bad(command, format!("{} has no `{unused}`", kind.label()))); } @@ -576,10 +577,12 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res generator.light = None; return Ok(()); } + let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty()); if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) { return Err(bad(command, "Light has no global blur, balance or contrast on its light controls")); } + if new_keys.is_empty() { return Ok(()); } @@ -594,6 +597,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res generator.global = defaults.global; } } + if let Some(defaults) = light_defaults { let light = generator.light.get_or_insert(defaults); for (key, value) in [ @@ -623,9 +627,11 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res *value = given; } } + if let Some(invert) = boolp(params, "sectionInvert") { section.invert = invert; } + for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) { if let Some(invert) = boolp(params, &format!("{name}Invert")) { axis.invert = invert; @@ -639,6 +645,7 @@ fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Res axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?; } } + generator.section = Some(section.clamped(kind)); texture_from(command, params, generator) } @@ -695,6 +702,7 @@ pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool { } } +/// Apply `params` to `generator`, using `command` in errors fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { wear_from(command, params, generator)?; section_from(command, params, generator)?; @@ -790,17 +798,6 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result { push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal) } -/// A generator input a command names: a mesh map it reads, its texture or its custom grunge -#[derive(Clone, Copy)] -enum GeneratorInput { - Map(BakedMap), - Texture, - Grunge, - MicroHeight, - MicroNormal, - Image, -} - /// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner` fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { const CMD: &str = "effect.set"; diff --git a/crates/ui-egui/src/generator_kind_rows.rs b/crates/ui-egui/src/generator_kind_rows.rs index 8b3e8960..e6df474c 100644 --- a/crates/ui-egui/src/generator_kind_rows.rs +++ b/crates/ui-egui/src/generator_kind_rows.rs @@ -15,16 +15,6 @@ use crate::i18n::{tr, trf}; use crate::property_sheet::{NumberField, PropertySheet, StackSlider}; use crate::theme::AXIS_COLORS; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - -/// A whole-number setting in the stack beside the preview -fn stacked_whole<'a>(label: &'a str, value: &'a mut f32, range: std::ops::RangeInclusive) -> StackSlider<'a> { - StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } -} - /// The first edit of a stack beside the preview fn first_edit(edits: [Option; N]) -> Option { edits.into_iter().flatten().next() @@ -111,7 +101,7 @@ fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParamete suffix: "", dial: false, }; - let mut stack = [radius, stacked(tr("Offset"), &mut edited.offset), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut stack = [radius, StackSlider::unit(tr("Offset"), &mut edited.offset), StackSlider::unit(tr("Contrast"), &mut edited.contrast)]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(point_row(sheet, tr("3D Position"), &mut edited.point, PointPick { effect: id, point: "distance" })); sent(edit, KindControls::Distance(edited)) @@ -120,7 +110,7 @@ fn distance_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: DistanceParamete /// 3D Linear Gradient: Balance and Contrast beside the preview, then its start and end fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGradientParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; - let mut stack = [stacked(tr("Balance"), &mut edited.balance), stacked(tr("Contrast"), &mut edited.contrast)]; + let mut stack = [StackSlider::unit(tr("Balance"), &mut edited.balance), StackSlider::unit(tr("Contrast"), &mut edited.contrast)]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(point_row(sheet, tr("3D Position Start"), &mut edited.start, PointPick { effect: id, point: "start" })); edit = edit.or(point_row(sheet, tr("3D Position End"), &mut edited.end, PointPick { effect: id, point: "end" })); @@ -130,8 +120,11 @@ fn linear_gradient_rows(sheet: &mut PropertySheet<'_>, id: u64, shown: LinearGra /// UV Border Distance: Distance, Smoothness and Balance beside the preview, then Contrast fn border_rows(sheet: &mut PropertySheet<'_>, shown: BorderDistanceParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; - let mut stack = - [stacked(tr("Distance"), &mut edited.distance), stacked(tr("Smoothness"), &mut edited.smoothness), stacked(tr("Balance"), &mut edited.balance)]; + let mut stack = [ + StackSlider::unit(tr("Distance"), &mut edited.distance), + StackSlider::unit(tr("Smoothness"), &mut edited.smoothness), + StackSlider::unit(tr("Balance"), &mut edited.balance), + ]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(sheet.slider(tr("Contrast"), &mut edited.contrast, 0.0..=1.0, 2)); sent(edit, KindControls::BorderDistance(edited)) @@ -147,9 +140,9 @@ fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParam edit = Some(false); } let mut stack = [ - stacked(tr("Balance"), &mut edited.balance), - stacked(tr("Contrast"), &mut edited.contrast), - stacked_whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), + StackSlider::unit(tr("Balance"), &mut edited.balance), + StackSlider::unit(tr("Contrast"), &mut edited.contrast), + StackSlider::whole(tr("Tile"), &mut edited.tile, GrayscaleConversionParameters::TILE_RANGE), ]; edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); edited.tile = edited.tile.round(); @@ -164,9 +157,9 @@ fn grayscale_rows(sheet: &mut PropertySheet<'_>, shown: GrayscaleConversionParam fn rust_rows(sheet: &mut PropertySheet<'_>, shown: DrippingRustParameters, picture: &dyn Fn(&Painter, Rect)) -> KindEdit { let mut edited = shown; let mut stack = [ - stacked(tr("Rust Spreading"), &mut edited.spreading), - stacked(tr("Rust Contrast"), &mut edited.contrast), - stacked(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), + StackSlider::unit(tr("Rust Spreading"), &mut edited.spreading), + StackSlider::unit(tr("Rust Contrast"), &mut edited.contrast), + StackSlider::unit(tr("Spreading Smoothness"), &mut edited.spreading_smoothness), ]; let mut edit = first_edit(sheet.picture_sliders(picture, &mut stack)); edit = edit.or(sheet.slider(tr("Drips Intensity"), &mut edited.drips_intensity, 0.0..=1.0, 2)); @@ -273,9 +266,9 @@ fn checker_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, shown: let mut tile = edited.grid_tile as f32; let tiles = *UvCheckerParameters::GRID_TILE_RANGE.start() as f32..=*UvCheckerParameters::GRID_TILE_RANGE.end() as f32; let mut stack = [ - stacked_whole(tr("Checker Grid Tile"), &mut tile, tiles), - stacked(tr("Checker Grid Opacity"), &mut edited.grid_opacity), - stacked(tr("UV Borders Width"), &mut edited.border_width), + StackSlider::whole(tr("Checker Grid Tile"), &mut tile, tiles), + StackSlider::unit(tr("Checker Grid Opacity"), &mut edited.grid_opacity), + StackSlider::unit(tr("UV Borders Width"), &mut edited.border_width), ]; edit = edit.or(first_edit(sheet.picture_sliders(picture, &mut stack))); edited.grid_tile = tile.round() as u32; diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 00fd88d2..879efecc 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -119,7 +119,7 @@ pub(crate) fn kind_params(controls: &KindControls) -> Value { "dripsIntensity": rust.drips_intensity, "dripsSmoothness": rust.drips_smoothness, "dripsSamples": rust.drips_samples, - "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or("y"), + "dripsAxis": DRIPS_AXES.get(usize::from(rust.axis)).copied().unwrap_or(DEFAULT_DRIPS_AXIS), }), KindControls::UvRandomColor(random) => { let mut params = json!({ @@ -148,6 +148,9 @@ pub(crate) fn kind_params(controls: &KindControls) -> Value { /// Dripping Rust's `dripsAxis` names, by axis pub(crate) const DRIPS_AXES: [&str; 3] = ["x", "y", "z"]; +/// The axis drips run along when a saved one is out of range: down Y, as new ones do +const DEFAULT_DRIPS_AXIS: &str = "y"; + /// Every micro details control a generator of `kind` has, set to `micro` (its images are the `microHeight` and `microNormal` inputs) pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { let mut params = json!({ diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 72712c84..4fd3d591 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -25,6 +25,16 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { set(ctx, next); } +/// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped +pub(crate) fn armed_on(ctx: &egui::Context, session: &texturecraft_engine::Session) -> Option { + let armed = armed(ctx)?; + if session.target == texturecraft_engine::StackTarget::Effect(texturecraft_engine::core::LayerId(armed.effect)) { + return Some(armed); + } + set(ctx, None); + None +} + pub(crate) fn set(ctx: &egui::Context, pick: Option) { ctx.data_mut(|data| data.insert_temp(pick_id(), pick)); } diff --git a/crates/ui-egui/src/generator_section_rows.rs b/crates/ui-egui/src/generator_section_rows.rs index 38377af0..40c58353 100644 --- a/crates/ui-egui/src/generator_section_rows.rs +++ b/crates/ui-egui/src/generator_section_rows.rs @@ -14,19 +14,14 @@ use crate::i18n::tr; use crate::property_sheet::{PropertySheet, StackSlider}; use crate::theme::AXIS_COLORS; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - /// Global Invert, then the preview beside Global Blur, Balance and Contrast: what every generator applies to its finished value pub(crate) fn global_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, generator: &Generator, picture: &dyn Fn(&Painter, Rect)) { let (mut invert, mut global) = (generator.invert, generator.global); let invert_edit = sheet.toggle(tr("Global Invert"), &mut invert).then_some(false); let mut stack = [ - stacked(tr("Global Blur"), &mut global.blur), - stacked(tr("Global Balance"), &mut global.balance), - stacked(tr("Global Contrast"), &mut global.contrast), + StackSlider::unit(tr("Global Blur"), &mut global.blur), + StackSlider::unit(tr("Global Balance"), &mut global.balance), + StackSlider::unit(tr("Global Contrast"), &mut global.contrast), ]; let stack_edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if let Some(merge) = invert_edit.or(stack_edit) { diff --git a/crates/ui-egui/src/generator_wear_rows.rs b/crates/ui-egui/src/generator_wear_rows.rs index c103ab72..3d7d15c6 100644 --- a/crates/ui-egui/src/generator_wear_rows.rs +++ b/crates/ui-egui/src/generator_wear_rows.rs @@ -11,11 +11,6 @@ use crate::generator_params::{light_params, merged, micro_params, wear_params}; use crate::i18n::tr; use crate::property_sheet::{PropertySheet, StackSlider}; -/// A 0..1 setting in the stack beside the preview -fn stacked<'a>(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { - StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } -} - /// The wear controls of generator effect `id` on `layer` in the reference's order, showing `wear`; `picture` draws the preview pub(crate) fn wear_rows( app: &mut TextureCraftApp, @@ -38,8 +33,11 @@ pub(crate) fn wear_rows( let dirt = kind == GeneratorKind::Dirt; let (level_label, contrast_label) = if dirt { (tr("Dirt Level"), tr("Dirt Contrast")) } else { (tr("Wear Level"), tr("Wear Contrast")) }; let mut edited = wear; - let mut stack = - [stacked(level_label, &mut edited.level), stacked(contrast_label, &mut edited.contrast), stacked(tr("Grunge Amount"), &mut edited.grunge_amount)]; + let mut stack = [ + StackSlider::unit(level_label, &mut edited.level), + StackSlider::unit(contrast_label, &mut edited.contrast), + StackSlider::unit(tr("Grunge Amount"), &mut edited.grunge_amount), + ]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); if kind != GeneratorKind::FiberGlassEdgeWear { edit = edit.or(sheet.slider(tr("Grunge Scale"), &mut edited.grunge_scale, WearParameters::GRUNGE_SCALE_RANGE, 0)); @@ -106,7 +104,7 @@ pub(crate) fn light_rows( let mut stack = [ angle(tr("Horizontal Angle"), &mut edited.horizontal), angle(tr("Vertical Angle"), &mut edited.vertical), - stacked(tr("Light Attenuation"), &mut edited.attenuation), + StackSlider::unit(tr("Light Attenuation"), &mut edited.attenuation), ]; let mut edit = sheet.picture_sliders(picture, &mut stack).into_iter().flatten().next(); edit = edit.or(sheet.slider(tr("Highlight Glossiness"), &mut edited.glossiness, LightParameters::GLOSSINESS_RANGE, 2)); diff --git a/crates/ui-egui/src/property_sheet/stack_slider.rs b/crates/ui-egui/src/property_sheet/stack_slider.rs index 9297e9b9..f14da76e 100644 --- a/crates/ui-egui/src/property_sheet/stack_slider.rs +++ b/crates/ui-egui/src/property_sheet/stack_slider.rs @@ -21,3 +21,15 @@ pub(crate) struct StackSlider<'a> { /// An angle: a small dial before its value, as an angle row has pub(crate) dial: bool, } + +impl<'a> StackSlider<'a> { + /// A 0..1 setting with two decimals + pub(crate) fn unit(label: &'a str, value: &'a mut f32) -> StackSlider<'a> { + StackSlider { label, value, range: 0.0..=1.0, typed: 0.0..=1.0, decimals: 2, suffix: "", dial: false } + } + + /// A whole-number setting across `range` + pub(crate) fn whole(label: &'a str, value: &'a mut f32, range: RangeInclusive) -> StackSlider<'a> { + StackSlider { label, value, range: range.clone(), typed: range, decimals: 0, suffix: "", dial: false } + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 473eaf29..92c07e7e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -865,7 +865,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // A 3D generator's armed point pick: a click sets the point there instead of painting - let point_pick = crate::generator_point_pick::armed(ui.ctx()); + let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session); if let Some(pick) = point_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 809fc048..126f7be5 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -19,7 +19,7 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { - slider_inner(ui, label, value, range, decimals, "").0 + slider_inner(ui, label, value, range, decimals).0 } /// For an editor `id` drawn every frame: `Some(merge)` when it `changed`, merge true for a press's later changes (one undo step per drag; typing never merges) @@ -57,12 +57,7 @@ pub(crate) fn press_edit(ui: &Ui, id: egui::Id, changed: bool) -> Option { /// true for the later changes of one drag, so the edit that applies them (with the command's /// `merge` param) continues the drag's first undo step. pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> Option { - slider_inner(ui, label, value, range, decimals, "").1 -} - -/// [`slider_edit`] showing `suffix` after the value (a unit such as °), which a typed value may leave out -pub fn slider_edit_with_suffix(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> Option { - slider_inner(ui, label, value, range, decimals, suffix).1 + slider_inner(ui, label, value, range, decimals).1 } /// Least width of a slider's value field, wide enough for a short number @@ -80,24 +75,12 @@ const SLIDER_KNOB_RADIUS: f32 = 4.5; /// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { - suffixed_value_header(ui, label, value, range, decimals, "") -} - -/// [`value_header`] showing `suffix` after the value, which a typed value may leave out -fn suffixed_value_header( - ui: &mut Ui, - label: &str, - value: &mut f32, - range: std::ops::RangeInclusive, - decimals: usize, - suffix: &str, -) -> (egui::Id, Option) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() - .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}{suffix}"), font.clone(), tokens.text).size().x) + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) .fold(SLIDER_VALUE_MIN_WIDTH, f32::max); let mut edit = None; let field = ui @@ -105,7 +88,7 @@ fn suffixed_value_header( ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{value:.decimals$}{suffix}"); + let shown = format!("{value:.decimals$}"); // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); @@ -128,7 +111,7 @@ fn suffixed_value_header( if response.lost_focus() && !escape && text != shown - && let Ok(parsed) = text.trim().strip_suffix(suffix).unwrap_or(text.trim()).trim_end().parse::() + && let Ok(parsed) = text.trim().parse::() && parsed.is_finite() && parsed.clamp(minimum, maximum) != *value { @@ -144,10 +127,10 @@ fn suffixed_value_header( (field, edit) } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize, suffix: &str) -> (Response, Option) { +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { let (minimum, maximum) = (*range.start(), *range.end()); let width = ui.available_width(); - let (field, mut edit) = suffixed_value_header(ui, label, value, range, decimals, suffix); + let (field, mut edit) = value_header(ui, label, value, range, decimals); let (rect, mut response) = ui.allocate_exact_size(vec2(width, SLIDER_TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a191e641..edce0259 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,4 +1,4 @@ -//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all) use egui::accesskit::Role; use egui_kittest::Harness; @@ -64,8 +64,7 @@ fn dragging_a_slider_applies_it() { assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } -/// A generator slider applies while it is dragged (the texture follows the pointer), and the -/// whole drag is one undo step. +/// A generator slider applies while it is dragged (the texture follows the pointer), and the whole drag is one undo step #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { let (mut harness, effect) = selected_generator(); @@ -112,7 +111,7 @@ fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> e harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person. +/// Click the balance's value to type in it and press `keys`, then type `text`, one key per frame like a person fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { harness.get_by_label("Global Balance value").click(); harness.run_steps(2); @@ -140,8 +139,7 @@ fn a_value_typed_in_the_number_field_applies() { assert_eq!(harness.state().session.history_labels().len(), steps + 1); } -/// Dragging the track while the number field has focus drops what was typed there: leaving the -/// field afterwards does not undo the drag. +/// Dragging the track while the value is being typed drops what was typed: leaving the field afterwards does not undo the drag #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { let (mut harness, effect) = selected_generator(); @@ -165,8 +163,7 @@ fn a_track_drag_drops_text_typed_in_the_number_field() { assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } -/// Leaving the number field without typing, or with Escape, keeps the value (not the rounded -/// text the field shows) and makes no undo step. +/// Leaving the value without typing, or with Escape, keeps it (not the rounded text shown) and makes no undo step #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { let (mut harness, effect) = selected_generator(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index e191d8b0..0c673fce 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -1,4 +1,4 @@ -//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator use egui::Role; use egui_kittest::Harness; @@ -10,7 +10,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::theme::Brightness; -/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { harness_with(render, json!({"generator": "curvature"})) } @@ -394,9 +394,22 @@ fn is_on(harness: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> boo harness.get_by_role_and_label(role, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } +#[test] +fn restore_defaults_puts_a_kind_with_its_own_controls_back() { + let added = json!({"generator": "uvRandomColor", "colorSourceMode": "customGradient", "gradientColors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]], "gradientPositions": [0.0, 0.3, 1.0], "seed": 4}); + let (mut harness, effect) = harness_with(false, added); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "gradientQuantity": 2})).unwrap(); + harness.run_steps(3); + + click_live(&mut harness, Role::Button, "Restore defaults"); + + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::UvRandomColor), "colors, places and count back to the kind's"); + assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "nothing left to restore"); +} + #[test] fn a_point_pick_waits_for_the_view_until_escape() { - let (mut harness, _) = harness_with(false, json!({"generator": "3dLinearGradient"})); + let (mut harness, effect) = harness_with(false, json!({"generator": "3dLinearGradient"})); let (start, end) = ("Pick 3D Position Start on the mesh", "Pick 3D Position End on the mesh"); assert!(!is_on(&harness, Role::Button, start) && !is_on(&harness, Role::Button, end)); @@ -410,6 +423,15 @@ fn a_point_pick_waits_for_the_view_until_escape() { harness.key_press(egui::Key::Escape); harness.run_steps(3); assert!(!is_on(&harness, Role::Button, start), "Esc cancels the pick"); + + // Selecting something else drops the pick: coming back finds it disarmed + click_live(&mut harness, Role::Button, end); + let layer = harness.state().session.doc.project.effect(effect).unwrap().0; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap(); + harness.run_steps(3); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); } #[test] diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index bea73433..dcc4fee8 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -723,7 +723,6 @@ fn nested_layers_snapshot() { save(&mut harness, &output_dir, "panel-layers-narrow-nested"); } -/// The mask anchor and generator micro controls in the integrated properties panel #[test] #[ignore] fn path_tool_snapshots() { From 9519f35873d6b0a8cb436d278fff027ed845f606 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:37:03 +0000 Subject: [PATCH 28/54] Generators: second review round (one box radius formula, named cache key fields, tests for inspect and a half-given pick pixel) --- crates/compose/src/eval.rs | 4 +++- crates/compose/src/field_cache.rs | 3 ++- crates/compose/src/field_cache_key.rs | 7 +++++-- crates/compose/src/micro_details/mod.rs | 4 +--- crates/compose/src/sections.rs | 4 +--- crates/compose/src/working_field.rs | 2 +- crates/engine/tests/it/generator_sections.rs | 13 +++++++++++++ .../engine/tests/it/generator_three_d_distance.rs | 1 + crates/ui-egui/src/generator_point_pick.rs | 11 +++++++---- crates/ui-egui/tests/it/generator_panel.rs | 3 +++ 10 files changed, 37 insertions(+), 15 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a98e07a9..a1a58358 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3634,15 +3634,17 @@ impl<'a, 'b> Texel<'a, 'b> { Some(((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32)) } - /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]) fn generator(&mut self, generator: &Generator, maps: &GeneratorMaps) -> f32 { let ramp = self.generator_ramp(generator, maps); let adjusted = generator.section_controls().map_or(ramp, |section| sections::adjusted(generator.kind, §ion, ramp)); + // An image still loading reads black, as it does where blur or resolution compute the generator over a region let textured = match generator.texture_in_use() { Some(texture) => texture_layer::blended_over(texture, adjusted, self.generator_texture(generator).unwrap_or(0.0)), None => adjusted, }; + finish_generator(generator, textured) } diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 910ce75c..1458cb3f 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -31,7 +31,8 @@ impl FieldCache { fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), block, scales: inp.block_scales.clone(), - mesh: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len(), inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), + positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), + uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), settings, }; diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index fa84471e..d29d80f5 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -10,7 +10,9 @@ pub(crate) struct FieldCacheKey { pub(crate) fingerprint: u64, pub(crate) block: (u32, u32), pub(crate) scales: BlockScales, - pub(crate) mesh: (usize, usize, usize, usize), + /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields + pub(crate) positions: (usize, usize), + pub(crate) uvs: (usize, usize), pub(crate) maps: Vec>>, pub(crate) settings: Vec, } @@ -24,7 +26,8 @@ impl PartialEq for FieldCacheKey { && self.fingerprint == other.fingerprint && self.block == other.block && self.scales == other.scales - && self.mesh == other.mesh + && self.positions == other.positions + && self.uvs == other.uvs && self.settings == other.settings } } diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index cc4bf6e4..ca5fa213 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -24,9 +24,7 @@ use texturecraft_core::{BakedMap, LayerId, MicroCurvatureType, MicroDetails}; use crate::below::StackKey; use crate::eval::{BLUR_BOX_PASSES, Inputs}; - -/// The resolution of a UV tile the reference's micro details were measured at: derivatives and radii are per texel at this size -const REFERENCE_TILE_TEXELS: f32 = 2048.0; +use crate::working_field::REFERENCE_TILE_TEXELS; /// How steeply the micro height tilts the normal it is turned into, per unit of Height Details Intensity (fitted) const HEIGHT_NORMAL_STRENGTH: f32 = 5.9; diff --git a/crates/compose/src/sections.rs b/crates/compose/src/sections.rs index 76e4d2a6..297a086a 100644 --- a/crates/compose/src/sections.rs +++ b/crates/compose/src/sections.rs @@ -66,9 +66,7 @@ pub(crate) fn generator_blur_sigma(generator: &Generator) -> f32 { /// The radius of the three box passes that blur like the section blur at `resolution` texels per side pub(crate) fn blur_radius_at(kind: GeneratorKind, section: &SectionParameters, resolution: u32) -> usize { let sigma = blur_sigma(kind, section) * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION; - - // Three boxes of radius r spread a texel with variance r (r + 1) - (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize + crate::working_field::box_radius(sigma) } /// `signal` after the section's balance, contrast, brightness and invert, as far as a generator of `kind` has them diff --git a/crates/compose/src/working_field.rs b/crates/compose/src/working_field.rs index 5c4e9c49..246e95b0 100644 --- a/crates/compose/src/working_field.rs +++ b/crates/compose/src/working_field.rs @@ -13,7 +13,7 @@ pub(crate) fn working_block(inp: &Inputs) -> (u32, u32) { (block.0.clamp(1, size.0.max(1)), block.1.clamp(1, size.1.max(1))) } -/// The box radius whose repeated passes approximate a Gaussian of `sigma` +/// The radius of three box passes that blur like a gaussian of `sigma`: three boxes of radius r spread a texel with variance r (r + 1) pub(crate) fn box_radius(sigma: f32) -> usize { (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) * 0.5).round() as usize } diff --git a/crates/engine/tests/it/generator_sections.rs b/crates/engine/tests/it/generator_sections.rs index ed9276f0..29311091 100644 --- a/crates/engine/tests/it/generator_sections.rs +++ b/crates/engine/tests/it/generator_sections.rs @@ -154,3 +154,16 @@ fn the_offset_belongs_to_the_earlier_model() { assert!(execute(&mut session, "effect.set", &both).is_err(), "{kind}: offset and the reference controls at once are refused"); } } + +#[test] +fn inspect_reports_the_reference_controls_set() { + let mut session = session(); + add(&mut session, json!({"generator": "position", "sectionContrast": 0.25})); + add(&mut session, json!({"generator": "direction", "lightHorizontal": 90.0})); + add(&mut session, json!({"generator": "dirt", "wearLevel": 0.125})); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for (key, value) in [("section", "\"contrast\":0.25"), ("light", "\"horizontal\":90.0"), ("wear", "\"level\":0.125")] { + assert!(inspected.contains(&format!("\"{key}\"")) && inspected.contains(value), "{key} with {value} in {inspected}"); + } +} diff --git a/crates/engine/tests/it/generator_three_d_distance.rs b/crates/engine/tests/it/generator_three_d_distance.rs index 735bef45..7866b622 100644 --- a/crates/engine/tests/it/generator_three_d_distance.rs +++ b/crates/engine/tests/it/generator_three_d_distance.rs @@ -215,6 +215,7 @@ fn picking_on_the_mesh_sets_the_point() { let missed = json!({"effect": distance, "x": 0.0, "y": 0.0, "viewport": [512, 512]}); assert!(execute(&mut session, "effect.generator.pickPoint", &missed).is_err(), "a corner off the mesh picks nothing"); + assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "x": 10.0})).is_err(), "a pixel needs both coordinates"); assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": distance, "point": "end"})).is_err()); let curvature = add(&mut session, json!({"generator": "curvature"})); assert!(execute(&mut session, "effect.generator.pickPoint", &json!({"effect": curvature})).is_err()); diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 4fd3d591..4b876e78 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -1,5 +1,8 @@ //! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, StackTarget}; + /// Which point of which generator effect the next click in the 3D view sets #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct PointPick { @@ -26,10 +29,10 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { } /// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped -pub(crate) fn armed_on(ctx: &egui::Context, session: &texturecraft_engine::Session) -> Option { - let armed = armed(ctx)?; - if session.target == texturecraft_engine::StackTarget::Effect(texturecraft_engine::core::LayerId(armed.effect)) { - return Some(armed); +pub(crate) fn armed_on(ctx: &egui::Context, session: &Session) -> Option { + let pick = armed(ctx)?; + if session.target == StackTarget::Effect(LayerId(pick.effect)) { + return Some(pick); } set(ctx, None); None diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 0c673fce..5d2e24b1 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -427,10 +427,13 @@ fn a_point_pick_waits_for_the_view_until_escape() { // Selecting something else drops the pick: coming back finds it disarmed click_live(&mut harness, Role::Button, end); let layer = harness.state().session.doc.project.effect(effect).unwrap().0; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap(); harness.run_steps(3); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); harness.run_steps(3); + assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); } From 0402ba32a5a9ba6b46fa0f2bc58f0fe79cb477ec Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:49:45 +0000 Subject: [PATCH 29/54] Generators: the panel's preview shows the generator as set, rendered one at a time while its settings change --- crates/engine/src/orb_preview.rs | 36 ++++++++++++++++++----- crates/ui-egui/src/generator_panel.rs | 16 ++++++---- crates/ui-egui/src/preview_request.rs | 3 ++ crates/ui-egui/src/preview_worker.rs | 15 +++++++++- crates/ui-egui/src/shelf.rs | 10 +++++-- crates/ui-egui/src/shelf_preview.rs | 34 +++++++++++++++++++++- crates/ui-egui/src/thumbs.rs | 42 +++++++++++++++++++++++++++ 7 files changed, 139 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index c392dc4c..e40366e1 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -2,8 +2,10 @@ //! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde_json::json; +use texturecraft_compose::ImageRes; use texturecraft_core::{ BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, ProceduralKind, Source, @@ -14,6 +16,7 @@ use texturecraft_texel::TILE; pub use crate::mask_preview_pixel::MaskPreviewPixel; pub use crate::material_preview_pixel::MaterialPreviewPixel; + use crate::orb_camera::OrbCamera; use crate::preview::Sample; use crate::session::Document; @@ -51,6 +54,16 @@ pub struct OrbPreview { cameras: Vec, } +/// `generator` with clouds in Grayscale Conversion's empty image slot: it grays the image it is given, and its picture would be black without one +fn with_sample_image(mut generator: Generator) -> Generator { + if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() + && grayscale.source.is_none() + { + grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + } + generator +} + impl OrbPreview { /// Bake the orb once (previews of any size reuse it) pub fn new() -> Result { @@ -88,13 +101,7 @@ impl OrbPreview { /// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, None outside the shape (and for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]) pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option>> { - let mut generator = Generator::new(kind); - - // Grayscale Conversion grays the image it is given: its picture grays clouds, as it starts with none - if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut() { - grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); - } - self.generator_of(generator, size) + self.generator_of(with_sample_image(Generator::new(kind)), size) } /// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone) @@ -111,6 +118,21 @@ impl OrbPreview { self.mask_pixels(size) } + /// [`Self::generator_of`] with `images` (the images the generator reads, by name) loaded for this render only + pub fn generator_reading(&mut self, generator: Generator, images: &[(String, Arc)], size: usize) -> Option>> { + let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); + let pixels = self.generator_of(with_sample_image(generator), size); + + // The orb's own images come back: the next preview reads only what it brings + for (name, previous) in replaced { + match previous { + Some(previous) => self.session.images.insert(name, previous), + None => self.session.images.remove(&name), + }; + } + pixels + } + /// Row-major `size²` pixels of the preview layer's current mask, with None outside the shape fn mask_pixels(&mut self, size: usize) -> Option>> { let camera = camera_for(&mut self.cameras, &self.session, size)?; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index bc7297cf..270ff5e1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -104,14 +104,18 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); - let preview = match (kind, generator.detail_in_use()) { - (GeneratorKind::Curvature, Some(detail)) => ShelfPreview::Curvature { mode: detail.mode, solo }, - _ => ShelfPreview::Generator(kind), + let solo_texture = match (kind, generator.detail_in_use(), solo) { + (GeneratorKind::Curvature, Some(detail), Some(size)) => { + app.thumbs.generator_picture(&ctx, ShelfPreview::Curvature { mode: detail.mode, solo: Some(size) }, PREVIEW_ORB_PX) + } + _ => None, }; - let texture = app.thumbs.generator_picture(&ctx, preview, PREVIEW_ORB_PX); - // A size shows the whole preview until its own render arrives - let texture = texture.or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); + // The preview shows the generator as set; a size shows the whole preview until its own render arrives, and the kind at its defaults shows until the first render + let set = ShelfPreview::generator_set(generator, &app.session.images); + let texture = solo_texture + .or_else(|| app.thumbs.generator_set_picture(&ctx, id, set, PREVIEW_ORB_PX)) + .or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); if let Some(controls) = generator.kind_controls() { diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index f1d78d74..2da02d5c 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -29,6 +29,9 @@ impl PreviewRequest { let generator = ShelfPreview::curvature_generator(*mode, *solo); Some(mask_preview_image(self.size_px, &shape.get()?.generator_of(generator, self.size_px)?)) } + ShelfPreview::GeneratorSet { generator, images } => { + Some(mask_preview_image(self.size_px, &shape.get()?.generator_reading(generator.as_ref().clone(), images, self.size_px)?)) + } ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index 57879c71..9bc7fb79 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -156,7 +156,7 @@ mod tests { use std::collections::HashMap; use std::time::{Duration, Instant}; - use texturecraft_engine::core::GeneratorKind; + use texturecraft_engine::core::{Generator, GeneratorKind}; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -187,6 +187,19 @@ mod tests { } } + #[test] + fn a_generator_as_set_renders_its_settings() { + let mut shape = OrbShape::default(); + let render = |shape: &mut OrbShape, generator: Generator| { + let preview = ShelfPreview::GeneratorSet { generator: Box::new(generator), images: Vec::new() }; + PreviewRequest { key: String::new(), preview, size_px: 16, hover: false }.render(shape).expect("an orb picture") + }; + + let plain = render(&mut shape, Generator::new(GeneratorKind::Dirt)); + let inverted = render(&mut shape, Generator { invert: true, ..Generator::new(GeneratorKind::Dirt) }); + assert_ne!(plain.pixels, inverted.pixels, "the picture follows the generator's settings"); + } + #[test] fn requests_are_answered_and_unknown_assets_get_none() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index ba44649f..2fa13ce5 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -646,8 +646,14 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; // High display scales must respect the orb camera's allocation limit - let on_the_orb = - matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_)); + let on_the_orb = matches!( + &preview, + ShelfPreview::SmartMask(_) + | ShelfPreview::Generator(_) + | ShelfPreview::Curvature { .. } + | ShelfPreview::GeneratorSet { .. } + | ShelfPreview::SmartMaterial(_) + ); let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 744c3795..30f0884d 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -32,6 +32,8 @@ pub enum ShelfPreview { Generator(GeneratorKind), /// A Curvature generator in `mode`, with only detail size `solo` (finest first) when given, rendered like [`ShelfPreview::Generator`] Curvature { mode: CurvatureMode, solo: Option }, + /// A generator as set, reading `images` (its image inputs by name), rendered like [`ShelfPreview::Generator`] + GeneratorSet { generator: Box, images: Vec<(String, Arc)> }, /// A library filter on a sample material on a sphere Filter(&'static str), /// A procedural pattern as a grayscale swatch @@ -61,6 +63,18 @@ impl ShelfPreview { generator } + /// `generator` as set, with the images it reads from `store` + pub fn generator_set(generator: &Generator, store: &ImageStore) -> ShelfPreview { + let images = generator + .sources() + .filter_map(|source| match source { + texturecraft_engine::core::Source::Image { name, .. } => store.get(name).map(|image| (name.clone(), image.clone())), + _ => None, + }) + .collect(); + ShelfPreview::GeneratorSet { generator: Box::new(generator.clone()), images } + } + /// Resolve a saved brush's image alpha while the project images are available pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self { let settings = read_saved_brush(path); @@ -90,6 +104,7 @@ impl ShelfPreview { ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Generator(kind) => format!("generator:{kind:?}"), ShelfPreview::Curvature { mode, solo } => format!("curvature:{mode:?}:{solo:?}"), + ShelfPreview::GeneratorSet { generator, images } => format!("generator-set:{:016x}", settings_hash(generator, images)), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), @@ -105,7 +120,11 @@ impl ShelfPreview { pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) | ShelfPreview::Generator(_) | ShelfPreview::Curvature { .. } | ShelfPreview::SmartMaterial(_) => None, + ShelfPreview::SmartMask(_) + | ShelfPreview::Generator(_) + | ShelfPreview::Curvature { .. } + | ShelfPreview::GeneratorSet { .. } + | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), @@ -228,3 +247,16 @@ mod tests { assert!(missing.image(64).is_none()); } } + +/// What a generator preview depends on: its settings and which images it reads +fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { + use std::hash::{Hash, Hasher}; + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); + for (name, image) in images { + name.hash(&mut hasher); + Arc::as_ptr(image).hash(&mut hasher); + } + hasher.finish() +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 569443c6..82755d8b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,6 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, + /// Per generator panel: the picture of its settings being rendered, and the last one finished (shown meanwhile) + set_pictures: HashMap, Option)>, } impl Thumbs { @@ -305,6 +307,29 @@ impl Thumbs { self.worker_rendered(ctx, preview, size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX), false) } + /// Generator `effect`'s picture as set (`preview` a [`ShelfPreview::GeneratorSet`]): one render at a time, the last finished one shown while the next renders, so a drag renders only as fast as the worker keeps up + pub fn generator_set_picture(&mut self, ctx: &egui::Context, effect: u64, preview: ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + let size_px = size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX); + let key = self.worker_key(&preview, size_px); + let (in_flight, last) = self.set_pictures.get(&effect).cloned().unwrap_or_default(); + + // The picture in flight landed: it is the latest shown + let last = match in_flight.as_ref().map(|key| self.rendered.get(key)) { + Some(Some(WorkerPreview::Ready(texture))) => Some(texture.clone()), + _ => last, + }; + let busy = in_flight.as_ref().is_some_and(|key| matches!(self.rendered.get(key), Some(WorkerPreview::Rendering))); + let shown = match self.ready(&key) { + Some(texture) => Some(texture), + None if busy => last.clone(), + None => self.big(ctx, preview, size_px).or_else(|| last.clone()), + }; + let in_flight = if busy { in_flight } else { Some(key) }; + self.set_pictures.insert(effect, (in_flight, shown.clone().or(last))); + shown + } + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) @@ -466,11 +491,28 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use texturecraft_engine::compose::BakedMaps; + use texturecraft_engine::core::Generator; use crate::orb_shape::OrbShape; static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn a_generator_picture_shows_the_last_one_while_the_next_renders() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() }; + let set = |invert| ShelfPreview::GeneratorSet { generator: Box::new(Generator { invert, ..Generator::new(GeneratorKind::Dirt) }), images: Vec::new() }; + let last = ctx.load_texture("last", ColorImage::filled([1, 1], Color32::RED), TextureOptions::LINEAR); + let rendering = thumbs.worker_key(&set(false), 8); + thumbs.rendered.insert(rendering.clone(), WorkerPreview::Rendering); + thumbs.set_pictures.insert(1, (Some(rendering), Some(last.clone()))); + + let shown = thumbs.generator_set_picture(&ctx, 1, set(true), 8); + + assert_eq!(shown.map(|texture| texture.id()), Some(last.id()), "the last picture stays up"); + assert!(!thumbs.rendered.contains_key(&thumbs.worker_key(&set(true), 8)), "the newer settings wait for the render in flight"); + } + #[test] fn saved_brush_refresh_discards_old_worker_result() { let ctx = egui::Context::default(); From 21b5180dc2199bf65a8234532b0e44f51a2bebda Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:14:07 +0000 Subject: [PATCH 30/54] Generators: Use Texture goes along when the kind changes between the four kinds that have it --- crates/engine/src/mask_cmds.rs | 1 + crates/engine/tests/it/generator_swap.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index a746f431..0d139bf4 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -1299,6 +1299,7 @@ fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator { resolution: current.resolution, inputs, grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()), + texture: current.texture.clone().filter(|_| SectionParameters::defaults(kind).is_some()), micro: swapped_micro(current.micro.as_deref(), kind), ..Generator::new(kind) } diff --git a/crates/engine/tests/it/generator_swap.rs b/crates/engine/tests/it/generator_swap.rs index a91790d0..24f88b5b 100644 --- a/crates/engine/tests/it/generator_swap.rs +++ b/crates/engine/tests/it/generator_swap.rs @@ -63,3 +63,23 @@ fn only_generator_effects_take_a_generator_kind() { assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "generator": "nope"})).is_err()); assert!(matches!(effect_kind(&session, filter), EffectKind::Filter(_)), "a refused swap changes nothing"); } + +#[test] +fn use_texture_goes_along_between_the_kinds_that_have_it() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let added = json!({"generator": "curvature", "useTexture": true, "textureOpacity": 0.75, "textureScale": 2.0}); + let effect = execute(&mut session, "effect.add.generator", &added).unwrap()["effect"].as_u64().unwrap(); + let texture = |session: &Session| match effect_kind(session, effect) { + EffectKind::Generator(generator) => generator.texture.map(|texture| (texture.enabled, texture.opacity, texture.scale)), + other => panic!("not a generator: {other:?}"), + }; + let before = texture(&session); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap(); + assert_eq!(texture(&session), before, "Ambient Occlusion has Use Texture too"); + + execute(&mut session, "effect.set", &json!({"effect": effect, "generator": "dirt"})).unwrap(); + assert_eq!(texture(&session), None, "Dirt has none"); +} From cc9b981112cb2d7d1439bebfab1eea7e3e5cd18c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:15:29 +0000 Subject: [PATCH 31/54] Shelf preview: the settings hash before the tests --- crates/ui-egui/src/shelf_preview.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 30f0884d..f6bad1cb 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -171,6 +171,19 @@ pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option { None } +/// What a generator preview depends on: its settings and which images it reads +fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { + use std::hash::{Hash, Hasher}; + + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); + for (name, image) in images { + name.hash(&mut hasher); + Arc::as_ptr(image).hash(&mut hasher); + } + hasher.finish() +} + #[cfg(test)] mod tests { use texturecraft_engine::filter_lib::FILTERS; @@ -247,16 +260,3 @@ mod tests { assert!(missing.image(64).is_none()); } } - -/// What a generator preview depends on: its settings and which images it reads -fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u64 { - use std::hash::{Hash, Hasher}; - - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - serde_json::to_string(generator).unwrap_or_default().hash(&mut hasher); - for (name, image) in images { - name.hash(&mut hasher); - Arc::as_ptr(image).hash(&mut hasher); - } - hasher.finish() -} From 3f72b65487c795467466d456363c7fd90f642c71 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:41:50 +0000 Subject: [PATCH 32/54] Bake mode pass 2: settings sync between texture sets, undoable high polys loaded on a worker, automatic cage, panels in the reference's layout --- crates/bake/src/cage.rs | 3 + crates/bake/src/cage/fitted_cage.rs | 169 +++++++ crates/bake/src/cage/high_poly_reach.rs | 2 +- crates/bake/src/cage/name_keys.rs | 38 ++ crates/bake/src/cage/ray_frame.rs | 22 +- crates/bake/src/cage/ray_start.rs | 12 + crates/bake/src/cage/vertex_reach.rs | 5 +- crates/bake/src/lib.rs | 6 +- crates/bake/src/map/bake_context.rs | 19 +- crates/bake/src/map/transfer.rs | 2 + crates/bake/src/test/cage_shell.rs | 6 + crates/bake/src/test/fitted_cage.rs | 150 ++++++ crates/bake/src/tests.rs | 3 + crates/core/src/bake.rs | 4 + crates/core/src/bake/bake_settings.rs | 17 +- crates/core/src/bake/bake_sync.rs | 40 ++ crates/core/src/bake/bake_sync_group.rs | 8 + crates/core/src/bake/cage_type.rs | 2 + crates/core/src/bake/common_bake_settings.rs | 4 +- crates/core/src/bake/mesh_map_settings.rs | 16 + crates/core/src/lib.rs | 10 +- crates/core/src/project.rs | 13 +- crates/core/tests/bake_settings.rs | 8 +- crates/engine/src/bake/bake_checks.rs | 2 +- crates/engine/src/bake/bake_mesh.rs | 2 + crates/engine/src/bake/bake_meshes.rs | 3 +- crates/engine/src/bake/high_poly_load.rs | 75 +++ crates/engine/src/bake/mesh_map_command.rs | 176 ++++--- crates/engine/src/bake/mod.rs | 4 + crates/engine/src/bake/model_patch.rs | 3 +- crates/engine/src/bake/sync_command.rs | 268 ++++++++++ crates/engine/src/file_cmds.rs | 41 +- crates/engine/src/lib.rs | 2 +- crates/engine/src/material_lib.rs | 22 +- crates/engine/src/session.rs | 19 +- crates/engine/src/smart_masks.rs | 3 + crates/engine/tests/it/bake.rs | 73 ++- crates/ui-egui/src/bake_job.rs | 4 + crates/ui-egui/src/bake_mode/bake_checks.rs | 2 +- crates/ui-egui/src/bake_mode/breadcrumb.rs | 96 +++- .../ui-egui/src/bake_mode/common_settings.rs | 412 +++++++-------- crates/ui-egui/src/bake_mode/controls.rs | 111 ++--- crates/ui-egui/src/bake_mode/glyph_look.rs | 9 + crates/ui-egui/src/bake_mode/map_settings.rs | 195 +++++--- .../ui-egui/src/bake_mode/map_thumbnails.rs | 69 +++ .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 317 ++++++++++-- crates/ui-egui/src/bake_mode/mod.rs | 37 +- crates/ui-egui/src/bake_mode/set_picker.rs | 290 +++++++++++ .../src/bake_mode/set_picker_purpose.rs | 10 + .../ui-egui/src/bake_mode/set_picker_row.rs | 7 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 2 +- .../ui-egui/src/bake_scene/cage_shell_key.rs | 33 +- crates/ui-egui/src/bake_scene/reach_link.rs | 18 +- crates/ui-egui/src/docking.rs | 4 +- crates/ui-egui/src/high_poly_job.rs | 79 +++ crates/ui-egui/src/lib.rs | 47 +- crates/ui-egui/src/property_sheet/choice.rs | 3 +- .../ui-egui/src/property_sheet/file_list.rs | 152 ++++++ .../src/property_sheet/file_list_add.rs | 6 + .../src/property_sheet/file_list_response.rs | 6 + crates/ui-egui/src/property_sheet/file_row.rs | 7 + .../src/property_sheet/fold_section.rs | 7 + crates/ui-egui/src/property_sheet/mod.rs | 11 + .../src/property_sheet/property_sheet.rs | 3 + crates/ui-egui/src/property_sheet/slider.rs | 6 +- .../src/property_sheet/stacked_rows.rs | 471 ++++++++++++++++++ crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/src/viewport.rs | 20 +- crates/ui-egui/src/web_files.rs | 19 +- crates/ui-egui/tests/bake_preview.rs | 20 + crates/ui-egui/tests/it/bake_job_mesh.rs | 2 +- crates/ui-egui/tests/it/bake_map_rows.rs | 70 +++ crates/ui-egui/tests/it/bake_mode.rs | 112 +++-- crates/ui-egui/tests/it/bake_presets.rs | 2 + crates/ui-egui/tests/it/bake_reset_menus.rs | 84 ++++ crates/ui-egui/tests/it/bake_sync.rs | 111 +++++ crates/ui-egui/tests/it/high_poly_loading.rs | 97 ++++ crates/ui-egui/tests/it/main.rs | 4 + crates/ui-egui/tests/it/skew_paint.rs | 14 +- crates/ui-egui/tests/ui_snapshots.rs | 2 +- docs/control-protocol.md | 15 +- 81 files changed, 3571 insertions(+), 669 deletions(-) create mode 100644 crates/bake/src/cage/fitted_cage.rs create mode 100644 crates/bake/src/cage/name_keys.rs create mode 100644 crates/bake/src/test/fitted_cage.rs create mode 100644 crates/core/src/bake/bake_sync.rs create mode 100644 crates/core/src/bake/bake_sync_group.rs create mode 100644 crates/engine/src/bake/high_poly_load.rs create mode 100644 crates/engine/src/bake/sync_command.rs create mode 100644 crates/ui-egui/src/bake_mode/glyph_look.rs create mode 100644 crates/ui-egui/src/bake_mode/map_thumbnails.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker_purpose.rs create mode 100644 crates/ui-egui/src/bake_mode/set_picker_row.rs create mode 100644 crates/ui-egui/src/high_poly_job.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list_add.rs create mode 100644 crates/ui-egui/src/property_sheet/file_list_response.rs create mode 100644 crates/ui-egui/src/property_sheet/file_row.rs create mode 100644 crates/ui-egui/src/property_sheet/fold_section.rs create mode 100644 crates/ui-egui/src/property_sheet/stacked_rows.rs create mode 100644 crates/ui-egui/tests/it/bake_map_rows.rs create mode 100644 crates/ui-egui/tests/it/bake_reset_menus.rs create mode 100644 crates/ui-egui/tests/it/bake_sync.rs create mode 100644 crates/ui-egui/tests/it/high_poly_loading.rs diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..088dae2f --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,169 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::collections::VecDeque; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals`: each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, ray_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + for (triangle, height) in heights_of_high_vertices(request, high, ray_normals, &keys).into_iter().flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// Per high-poly vertex, its nearest low-poly triangle and its height over it along the ray normal there +fn heights_of_high_vertices(request: &BakeRequest, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys) -> Vec> { + let low = request.mesh; + high.mesh + .positions + .par_iter() + .enumerate() + .map(|(vertex, &high_position)| { + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + Some((nearest.tri as usize, (high_position - low_position).dot(up))) + }) + .collect() +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Steps from the nearest fitted vertex; a vertex only takes distances from vertices one step nearer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::spread_to_neighbours; + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ use texturecraft_core::CageType; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { impl<'a> RayFrame<'a> { pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { let settings = request.settings; - let ray_normals = match settings.cage.average_normals && request.high.is_some() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, cage_paint: request.cage_paint, ray_epsilon: extent.ray_epsilon(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ impl VertexReach { /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { let origin = self.start.origin(self.low_position, frontal); - let (direction, front) = match self.start { - RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), - RayStart::Distance { up, scale } => (-up, frontal * scale), - }; + let (direction, front, rear) = self.start.span(frontal, rear); let along_ray = (self.high_position - origin).dot(direction); !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 1d99ab36..8b55546e 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -349,6 +349,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +363,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; - hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row @@ -379,6 +381,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +391,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // Share occlusion results when the bent-normal ray settings match let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..8dce2df9 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,6 +12,9 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, @@ -109,21 +112,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { let start = self.ray_frame.start(surface, barycentric); let origin = start.origin(surface.pos, self.frontal); - let (direction, front) = match start { - RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), - RayStart::Distance { up, scale } => (-up, self.frontal * scale), - }; + let (direction, front, rear) = start.span(self.frontal, self.rear); let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), }; - (Ray { origin, direction, max_distance: front + self.rear, key }, front) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: f32) -> Option { let (high, hit) = (self.high.as_ref()?, hit?); let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +246,7 @@ impl<'a> BakeContext<'a> { let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { let height = hit.front - hit.t; - if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..f0ce2600 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -60,6 +60,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3aa96e6b --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,150 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index eaa64cf2..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index 4b21a20d..a40f5ab0 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -7,6 +7,8 @@ mod bake_antialiasing; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_sync; +mod bake_sync_group; mod mesh_match_mode; mod skew_correction_method; pub use bake_paint_target::BakePaintTarget; @@ -45,6 +47,8 @@ pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_sync::BakeSync; +pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; pub use bent_normal_settings::BentNormalSettings; pub use cage_settings::CageSettings; diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs index 8d121419..87962b5c 100644 --- a/crates/core/src/bake/bake_settings.rs +++ b/crates/core/src/bake/bake_settings.rs @@ -1,4 +1,4 @@ -use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use super::{BakeSync, BakeSyncGroup, CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; use serde::{Deserialize, Serialize}; /// Persisted clean-room bake settings, grouped by the controls they belong to @@ -10,6 +10,8 @@ pub struct BakeSettings { pub cage: CageSettings, pub skew: SkewSettings, pub maps: MeshMapSettings, + /// What this texture set shares with the others + pub sync: BakeSync, } impl BakeSettings { @@ -17,4 +19,17 @@ impl BakeSettings { pub fn skew_applies(&self) -> bool { !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals } + + /// Take `group`'s settings from `source`, keeping whether this set is baked and which maps it bakes + pub fn copy_group(&mut self, source: &BakeSettings, group: BakeSyncGroup) { + match group { + BakeSyncGroup::Common => { + self.common = CommonBakeSettings { is_enabled: self.common.is_enabled, ..source.common }; + self.high_poly = source.high_poly.clone(); + self.cage = source.cage; + self.skew = source.skew; + } + BakeSyncGroup::Map(map) => self.maps.copy_parameters(map, &source.maps), + } + } } diff --git a/crates/core/src/bake/bake_sync.rs b/crates/core/src/bake/bake_sync.rs new file mode 100644 index 00000000..e53a4def --- /dev/null +++ b/crates/core/src/bake/bake_sync.rs @@ -0,0 +1,40 @@ +use super::{BakeSyncGroup, BakedMap}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Which of a texture set's bake settings it shares with every other texture set sharing them; all are shared at first, as in the reference +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeSync { + /// Shares Common Settings: output, high poly, cage and skew correction + pub common: bool, + /// The map types whose settings it shares + pub maps: BTreeSet, +} + +impl Default for BakeSync { + fn default() -> Self { + Self { common: true, maps: BakedMap::ALL.into_iter().collect() } + } +} + +impl BakeSync { + pub fn shares(&self, group: BakeSyncGroup) -> bool { + match group { + BakeSyncGroup::Common => self.common, + BakeSyncGroup::Map(map) => self.maps.contains(&map), + } + } + + pub fn set_shares(&mut self, group: BakeSyncGroup, shares: bool) { + match group { + BakeSyncGroup::Common => self.common = shares, + BakeSyncGroup::Map(map) if shares => { + self.maps.insert(map); + } + BakeSyncGroup::Map(map) => { + self.maps.remove(&map); + } + } + } +} diff --git a/crates/core/src/bake/bake_sync_group.rs b/crates/core/src/bake/bake_sync_group.rs new file mode 100644 index 00000000..c9007dbf --- /dev/null +++ b/crates/core/src/bake/bake_sync_group.rs @@ -0,0 +1,8 @@ +use super::BakedMap; + +/// A part of the bake settings texture sets can share: Common Settings, or one map type's settings +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum BakeSyncGroup { + Common, + Map(BakedMap), +} diff --git a/crates/core/src/bake/cage_type.rs b/crates/core/src/bake/cage_type.rs index 1985055f..a894235c 100644 --- a/crates/core/src/bake/cage_type.rs +++ b/crates/core/src/bake/cage_type.rs @@ -4,5 +4,7 @@ use serde::{Deserialize, Serialize}; pub enum CageType { #[default] DistanceBased, + /// Distances fitted to the high poly at every low-poly vertex + Automatic, CustomFile, } diff --git a/crates/core/src/bake/common_bake_settings.rs b/crates/core/src/bake/common_bake_settings.rs index 3f743fff..a39ef77f 100644 --- a/crates/core/src/bake/common_bake_settings.rs +++ b/crates/core/src/bake/common_bake_settings.rs @@ -21,8 +21,8 @@ impl Default for CommonBakeSettings { resolution: BakeResolution::R2048, resolution_height: None, antialiasing: BakeAntialiasing::None, - dilation: 1, - apply_diffusion: true, + dilation: 32, + apply_diffusion: false, } } } diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index c0a38673..281d5c98 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -68,6 +68,22 @@ impl MeshMapSettings { *enabled = is_enabled; } + /// Take `map`'s parameters from `source`, keeping whether it is checked + pub fn copy_parameters(&mut self, map: BakedMap, source: &MeshMapSettings) { + match map { + BakedMap::Normal => self.normal.parameters = source.normal.parameters, + BakedMap::WorldNormal => self.world_normal.parameters = source.world_normal.parameters, + BakedMap::Id => self.id.parameters = source.id.parameters, + BakedMap::AmbientOcclusion => self.ao.parameters = source.ao.parameters, + BakedMap::Curvature => self.curvature.parameters = source.curvature.parameters, + BakedMap::Position => self.position.parameters = source.position.parameters, + BakedMap::Thickness => self.thickness.parameters = source.thickness.parameters, + BakedMap::Height => self.height.parameters = source.height.parameters, + BakedMap::BentNormal => self.bent_normal.parameters = source.bent_normal.parameters, + BakedMap::Opacity => self.opacity.parameters = source.opacity.parameters, + } + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 88ee96d1..bd89a2a8 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,11 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, - BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, - HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, - NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, - SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, + BakeSyncGroup, BakedMap, BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, + HeightNormalization, HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, + MeshMatchMode, NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, + SelfOcclusion, SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, }; pub use bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..6bcf92e4 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -478,6 +478,17 @@ impl Project { self.texture_sets.get_mut(ts).ok_or(CoreError::NoTextureSet(ts)) } + /// The texture sets an edit of `group` on texture set `active` reaches: every set sharing `group` with it, or `active` alone + pub fn bake_synced_sets(&self, active: usize, group: BakeSyncGroup) -> Vec { + match self.texture_sets.get(active) { + Some(set) if set.bake.sync.shares(group) => { + self.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.sync.shares(group)).map(|(index, _)| index).collect() + } + Some(_) => vec![active], + None => Vec::new(), + } + } + pub fn layer(&self, id: LayerId) -> Result<&Layer> { self.layers.get(&id).ok_or(CoreError::NoLayer(id)) } diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 1616604f..80fda4b8 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -13,10 +13,11 @@ fn reference_defaults_cover_common_and_per_map_settings() { let mut thickness_rays = rays.clone(); thickness_rays["max_distance"] = json!(0.1); let mut expected = json!({ - "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true}, + "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 32, "apply_diffusion": false}, "high_poly": {"match_mode": "Always", "use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, "cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true}, "skew": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "sync": {"common": true, "maps": ["Normal", "WorldNormal", "Id", "AmbientOcclusion", "Curvature", "Position", "Thickness", "Height", "BentNormal", "Opacity"]}, "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { @@ -81,7 +82,7 @@ fn all_dropdowns_store_enum_choices() { assert_choices(&[bake::SkewCorrectionMethod::MeshNormalsBased, bake::SkewCorrectionMethod::FaceNormalsBased]); assert_choices(&bake::BakeResolution::ALL); assert_choices(&bake::BakeAntialiasing::ALL); - assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]); + assert_choices(&[bake::CageType::DistanceBased, bake::CageType::Automatic, bake::CageType::CustomFile]); assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]); assert_choices(&[ bake::IdColorSource::VertexColor, @@ -126,7 +127,8 @@ fn nested_settings_round_trip_per_texture_set() { settings.common.resolution = bake::BakeResolution::R16; settings.common.resolution_height = Some(bake::BakeResolution::R8192); settings.common.antialiasing = bake::BakeAntialiasing::Subsampling8x8; - settings.common.apply_diffusion = false; + settings.common.apply_diffusion = true; + settings.sync.set_shares(bake::BakeSyncGroup::Map(bake::BakedMap::Height), false); settings.high_poly.ignore_backface_suffix = "_two_sided".into(); settings.cage.kind = bake::CageType::CustomFile; settings.skew.edge_protection = true; diff --git a/crates/engine/src/bake/bake_checks.rs b/crates/engine/src/bake/bake_checks.rs index 3ea93729..f25ed63c 100644 --- a/crates/engine/src/bake/bake_checks.rs +++ b/crates/engine/src/bake/bake_checks.rs @@ -39,7 +39,7 @@ impl Session { pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { let set = self.doc.project.texture_set(texture_set)?; let settings = &set.bake.high_poly; - let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + let high = self.doc.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) } diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index 0d4d5ffe..bcdb2bcc 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -6,6 +6,8 @@ use texturecraft_geom::{BaseColor, Mesh}; #[derive(Clone, Debug)] pub struct BakeMesh { pub name: String, + /// The folder the file was read from, when it was picked from disk this session (projects don't keep it) + pub folder: Option, pub bytes: Arc>, pub mesh: Arc, pub base_color: Vec>>, diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index da0e4a97..b609e106 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -2,8 +2,7 @@ use super::{BakeMesh, MergedHigh}; use std::sync::{Arc, OnceLock}; use texturecraft_geom::{Bvh, Mesh}; -/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the -/// undo history. +/// The high-definition meshes and the cage; undo and redo restore them with the document #[derive(Clone, Debug, Default)] pub struct BakeMeshes { pub(crate) low_base_color: OnceLock>, diff --git a/crates/engine/src/bake/high_poly_load.rs b/crates/engine/src/bake/high_poly_load.rs new file mode 100644 index 00000000..7a69d30e --- /dev/null +++ b/crates/engine/src/bake/high_poly_load.rs @@ -0,0 +1,75 @@ +use std::sync::Arc; + +use texturecraft_formats::MeshFile; + +use super::mesh_map_command::{ADD_HIGH_POLY_LABEL, parse_mesh, unique_name}; +use super::{BakeMesh, BakeMeshes, MergedHigh}; +use crate::{Result, Session}; + +/// A high poly file parsed and merged with the meshes it joins, which a worker thread can prepare while the session stays in use +pub struct HighPolyLoad { + /// The name the file was picked by, before it was made unique in the list + file_name: String, + added: BakeMesh, + /// The list the mesh joined, with it at the end + high: Vec, + /// `high` as bakes see it + merged: Option, + /// Files the mesh refers to that could not be read, as messages for the log + warnings: Vec, +} + +impl HighPolyLoad { + /// Parse `file` and merge it with the high polys of `meshes` + pub fn prepare(meshes: &BakeMeshes, file: MeshFile) -> Result { + let mut added = parse_mesh(&file.name, file.bytes)?; + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&file.name, &taken); + + let mut joined = BakeMeshes { high: meshes.high.clone(), ..Default::default() }; + joined.high.push(added.clone()); + joined.rebuild(); + Ok(Self { file_name: file.name, added, high: joined.high, merged: joined.merged, warnings: file.warnings }) + } + + /// Read the mesh file at `path`, then [`HighPolyLoad::prepare`] it + #[cfg(not(target_arch = "wasm32"))] + pub fn read(meshes: &BakeMeshes, path: &str) -> Result { + Self::prepare(meshes, crate::file_cmds::read_mesh("bake.highPoly.add", path)?) + } + + /// Whether `current` is still the list this mesh was merged into + fn joins(&self, current: &[BakeMesh]) -> bool { + let joined = &self.high[..self.high.len() - 1]; + joined.len() == current.len() + && joined.iter().zip(current).all(|(joined, current)| joined.name == current.name && Arc::ptr_eq(&joined.mesh, ¤t.mesh)) + } +} + +impl Session { + /// Add a prepared high poly as one undo step; every texture set then bakes from the high polys. Returns its name + pub fn apply_high_poly_load(&mut self, load: HighPolyLoad) -> String { + let before = self.doc.clone(); + let meshes = &mut self.doc.bake_meshes; + let mut added = load.added.clone(); + if load.joins(&meshes.high) { + meshes.high = load.high; + meshes.merged = load.merged; + } else { + // The list changed while the file loaded, so the mesh joins the list as it is now + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&load.file_name, &taken); + meshes.high.push(added.clone()); + meshes.rebuild(); + } + + let textures = added.base_color.iter().flatten().filter(|color| !color.texels.is_empty()).count(); + self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", added.name, added.mesh.triangle_count())); + self.log.warnings("Baker", load.warnings); + for set in &mut self.doc.project.texture_sets { + set.bake.high_poly.use_low_as_high = false; + } + self.push_history(ADD_HIGH_POLY_LABEL, before); + added.name + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef27ea3..6bb70d19 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -9,19 +9,26 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; -use super::{BakeCageInputs, MergedHigh}; +use super::{BakeCageInputs, HighPolyLoad, MergedHigh}; use crate::{BakeMesh, BakeTask, StreamedBake}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, + SelfOcclusion, }; use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; +/// Undo step names of the bake mesh edits +pub(super) const ADD_HIGH_POLY_LABEL: &str = "Add high poly mesh"; +const REMOVE_HIGH_POLY_LABEL: &str = "Remove high poly mesh"; +const SET_CAGE_LABEL: &str = "Load cage mesh"; +const REMOVE_CAGE_LABEL: &str = "Remove cage mesh"; + pub(super) fn specs() -> Vec { vec![ cmd!( @@ -55,8 +62,11 @@ pub(super) fn specs() -> Vec { cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))), cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { - s.bake_meshes.cage = None; - s.modified = true; + if s.doc.bake_meshes.cage.is_some() { + let before = s.doc.clone(); + s.doc.bake_meshes.cage = None; + s.push_history(REMOVE_CAGE_LABEL, before); + } Ok(meshes_json(s)) }), ] @@ -86,8 +96,8 @@ fn chosen_tracer(installed: Option<&Arc>, enabled: bool) -> Option String { +/// A mesh file name made unique among `taken` (and safe as a project file entry) +pub(super) fn unique_name(file_name: &str, taken: &[&str]) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); @@ -99,10 +109,11 @@ fn unique_name(file_name: &str, taken: &[&str]) -> String { name } -fn parse_mesh(file_name: &str, bytes: Vec) -> Result { +pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); - Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) + let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) } impl Session { @@ -114,8 +125,9 @@ impl Session { let needs_low_color = set.bake.maps.opacity.is_enabled || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); - let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) { - self.bake_meshes + let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { + self.doc + .bake_meshes .low_base_color .get_or_init(|| match &self.mesh_source { Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes) @@ -179,7 +191,7 @@ impl Session { /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly fn bake_high(&self, texture_set: usize) -> Result> { let set = self.doc.project.texture_set(texture_set)?; - Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.doc.bake_meshes.merged.clone() }) } /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage @@ -189,7 +201,7 @@ impl Session { return Ok(None); } - let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + let cage = self.doc.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; Ok(Some(cage.mesh.clone())) } @@ -260,37 +272,38 @@ impl Session { Ok(tracer) } - /// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and - /// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name. + /// Add a high-definition mesh from file bytes as one undo step; every texture set then bakes from the high polys. Returns its name pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect(); - m.name = unique_name(file_name, &taken); - let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count(); - self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count())); - let name = m.name.clone(); - self.bake_meshes.high.push(m); - self.bake_meshes.rebuild(); - for set in &mut self.doc.project.texture_sets { - set.bake.high_poly.use_low_as_high = false; - } - self.modified = true; - Ok(name) + let file = texturecraft_formats::MeshFile { name: file_name.to_string(), bytes, warnings: Vec::new() }; + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?; + Ok(self.apply_high_poly_load(load)) } - /// Remove high-definition mesh `index`. + /// Remove high-definition mesh `index` as one undo step pub fn remove_high_poly(&mut self, index: usize) -> Result { - if index >= self.bake_meshes.high.len() { + if index >= self.doc.bake_meshes.high.len() { return Err(EngineError::Other(format!("no high poly mesh {index}"))); } - let removed = self.bake_meshes.high.remove(index); - self.bake_meshes.rebuild(); - self.modified = true; + + let before = self.doc.clone(); + let removed = self.doc.bake_meshes.high.remove(index); + self.doc.bake_meshes.rebuild(); + self.push_history(REMOVE_HIGH_POLY_LABEL, before); Ok(removed) } - /// Use a cage mesh (same triangles as the low poly) from file bytes. + /// Use a cage mesh (same triangles as the low poly) from file bytes as one undo step. Returns its name pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + let cage = self.cage_from_bytes(file_name, bytes)?; + let name = cage.name.clone(); + let before = self.doc.clone(); + self.doc.bake_meshes.cage = Some(cage); + self.push_history(SET_CAGE_LABEL, before); + Ok(name) + } + + /// Parse a cage mesh file, refusing one whose triangles are not the low poly's + fn cage_from_bytes(&self, file_name: &str, bytes: Vec) -> Result { let mut m = parse_mesh(file_name, bytes)?; if m.mesh.triangle_count() != self.mesh.triangle_count() { return Err(EngineError::Other(format!( @@ -301,33 +314,36 @@ impl Session { } m.name = unique_name(file_name, &[]); m.base_color.clear(); - let name = m.name.clone(); - self.bake_meshes.cage = Some(m); - self.modified = true; - Ok(name) + Ok(m) } - /// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could - /// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`. + /// Add mesh file `f` as a high poly or the cage, logging what it could not fold in; replies `{name, meshes}` like `bake.highPoly.add` / `bake.cage.set` pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result { - let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? }; - self.log.warnings("Baker", f.warnings); + let name = if cage { + let name = self.set_cage_bytes(&f.name, f.bytes)?; + self.log.warnings("Baker", f.warnings); + name + } else { + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, f)?; + self.apply_high_poly_load(load) + }; Ok(json!({ "name": name, "meshes": meshes_json(self) })) } - /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped. + /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped pub(crate) fn load_bake_meshes(&mut self, high: Vec, cage: Option) { for (name, bytes) in high { match parse_mesh(&name, bytes) { - Ok(m) => self.bake_meshes.high.push(m), + Ok(m) => self.doc.bake_meshes.high.push(m), Err(e) => self.log.warn("Baker", format!("skipped high poly mesh: {e}")), } } - self.bake_meshes.rebuild(); - if let Some((name, bytes)) = cage - && let Err(e) = self.set_cage_bytes(&name, bytes) - { - self.log.warn("Baker", format!("skipped cage mesh: {e}")); + self.doc.bake_meshes.rebuild(); + if let Some((name, bytes)) = cage { + match self.cage_from_bytes(&name, bytes) { + Ok(cage) => self.doc.bake_meshes.cage = Some(cage), + Err(e) => self.log.warn("Baker", format!("skipped cage mesh: {e}")), + } } } @@ -356,10 +372,10 @@ impl Session { .collect() } - /// The bake meshes for a project file: (high polys, cage). + /// The bake meshes for a project file: (high polys, cage) pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); - (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) + (self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry)) } } @@ -367,7 +383,7 @@ impl Session { pub fn meshes_json(s: &Session) -> Value { let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height })); - json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { + json!({ "highPoly": s.doc.bake_meshes.high.iter().map(one).collect::>(), "cage": s.doc.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 }; json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()}) }).collect::>() }) @@ -390,14 +406,17 @@ fn high_add(s: &mut Session, p: &Value) -> Result { fn high_remove(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { - s.bake_meshes.high.clear(); - s.bake_meshes.rebuild(); - s.modified = true; + if !s.doc.bake_meshes.high.is_empty() { + let before = s.doc.clone(); + s.doc.bake_meshes.high.clear(); + s.doc.bake_meshes.rebuild(); + s.push_history(REMOVE_HIGH_POLY_LABEL, before); + } return Ok(meshes_json(s)); } let index = match (u64p(p, "index"), strp(p, "name")) { (Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX), - (None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, + (None, Some(n)) => s.doc.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, (None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")), }; s.remove_high_poly(index)?; @@ -408,8 +427,8 @@ fn cage_set(s: &mut Session, p: &Value) -> Result { s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) } -/// Texture sets named by `ts` (default: the active one). -fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { +/// Texture sets named by `ts` (default: the active one) +pub(super) fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { let n = s.set_count(); let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}"))); match p.get("ts") { @@ -465,8 +484,9 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> if let Some(model) = params.get("model") { let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?; validate_model_settings(&replacement, command, boolp(params, "preset") == Some(true), None)?; - let is_enabled = settings.common.is_enabled; - *settings = replacement; + let (is_enabled, sync) = (settings.common.is_enabled, std::mem::take(&mut settings.sync)); + // Sync membership is not a setting: only `bake.sync` changes it + *settings = BakeSettings { sync, ..replacement }; if boolp(params, "preserveEnabled") == Some(true) { settings.common.is_enabled = is_enabled; } @@ -708,19 +728,37 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< } fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { - let next = updated_settings(session, params, command)?; - let sets = next.iter().map(|(index, _)| *index).collect(); - if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) { - session.edit("Bake Settings", |session| { - for (index, settings) in next { - session.doc.project.texture_set_mut(index)?.bake = settings; - } - Ok(()) - })?; - } + let targets = updated_settings(session, params, command)?; + let sets = targets.iter().map(|(index, _)| *index).collect(); + let next = with_sync_partners(&session.doc.project, targets, command)?; + + super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group +fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { + let mut next: BTreeMap = BTreeMap::new(); + for (target, settings) in &targets { + let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; + let Some(changed) = model_patch::changed_fields(&json!(before), &json!(settings)) else { continue }; + + let groups = std::iter::once(BakeSyncGroup::Common).chain(BakedMap::ALL.map(BakeSyncGroup::Map)); + for group in groups { + for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| partner != target) { + let Some(set) = project.texture_sets.get(partner) else { continue }; + let entry = next.entry(partner).or_insert_with(|| set.bake.clone()); + let mut model = json!(entry); + model_patch::apply_patch(&mut model, &changed, command)?; + let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + entry.copy_group(&patched, group); + } + } + } + next.extend(targets); + Ok(next.into_iter().collect()) +} + fn settings(session: &mut Session, params: &Value) -> Result { let sets = set_settings(session, params, "bake.settings")?; let result: Vec = sets diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ef9dc935..1be548db 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -5,6 +5,7 @@ mod bake_checks; mod bake_mesh; mod bake_meshes; mod bake_task; +mod high_poly_load; mod high_poly_missed; mod layout; mod merged_high; @@ -14,12 +15,14 @@ mod paint_command; mod preserve_tiles; mod streamed_bake; mod streamed_map; +mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; +pub use high_poly_load::HighPolyLoad; pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params}; @@ -36,5 +39,6 @@ pub(crate) fn specs() -> Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); commands.extend(tile_command::specs()); + commands.extend(sync_command::specs()); commands } diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs index 871d7dc8..6532f914 100644 --- a/crates/engine/src/bake/model_patch.rs +++ b/crates/engine/src/bake/model_patch.rs @@ -9,7 +9,8 @@ pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value { changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({})) } -fn changed_fields(before: &Value, after: &Value) -> Option { +/// The fields of `after` that differ from `before`, nested as a `bake.settings` patch; `None` when nothing changed +pub(super) fn changed_fields(before: &Value, after: &Value) -> Option { if before == after { return None; } diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs new file mode 100644 index 00000000..e244e507 --- /dev/null +++ b/crates/engine/src/bake/sync_command.rs @@ -0,0 +1,268 @@ +//! Sharing bake settings between texture sets: live sync groups, and one-off copies from the bake menus + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSettings, BakeSyncGroup, BakedMap}; + +use super::mesh_map_command::sets_param; +use crate::commands::{CommandSpec, always, bad, strp, u64p}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "bake.sync", + "Sync bake settings", + [], + None, + "{group: \"common\"|map id, ts: index|[indices]|\"all\"} → {group, ts}; exactly these texture sets share the group's settings from now on, and the ones added take the settings the group shares", + always, + sync + ), + cmd!( + "bake.copy", + "Copy bake settings", + [], + None, + "{what: \"settings\"|\"checked\"|\"check\", map?: id, from?: index (default: the active set), ts: index|[indices]|\"all\"} → {ts}; settings: every setting and which maps are checked, or with map that map's settings; checked: which maps are checked; check: check map. Settings also reach the sets sharing a group with a target, whose checkboxes stay their own", + always, + copy + ), + ] +} + +fn group_param(params: &Value, command: &str) -> Result { + match strp(params, "group") { + Some("common") => Ok(BakeSyncGroup::Common), + Some(id) => BakedMap::parse(id).map(BakeSyncGroup::Map).ok_or_else(|| bad(command, format!("unknown group {id}"))), + None => Err(bad(command, "`group` must be \"common\" or a mesh map id")), + } +} + +fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn sync(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.sync"; + let group = group_param(params, COMMAND)?; + let members = sets_param(session, COMMAND, params)?; + let sets = &session.doc.project.texture_sets; + + // Additions take the settings of a set that already shares them; with none left, of the active set when it joins, else of the first + let staying = members.iter().copied().find(|index| sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); + let active = session.ts(); + let source = staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()); + let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone()); + + let next: Vec<(usize, BakeSettings)> = sets + .iter() + .enumerate() + .map(|(index, set)| { + let mut settings = set.bake.clone(); + let joins = members.contains(&index); + if let Some(source) = source.as_ref().filter(|_| joins && !settings.sync.shares(group)) { + settings.copy_group(source, group); + } + settings.sync.set_shares(group, joins); + (index, settings) + }) + .collect(); + store(session, "Sync bake settings", next)?; + Ok(json!({ "group": group_id(group), "ts": members })) +} + +fn copy(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.copy"; + let map = strp(params, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(COMMAND, format!("unknown mesh map {id}")))).transpose()?; + let from = match u64p(params, "from") { + Some(index) => usize::try_from(index).map_err(|_| bad(COMMAND, "invalid `from`"))?, + None => session.ts(), + }; + let source = session.doc.project.texture_set(from)?.bake.clone(); + let targets = sets_param(session, COMMAND, params)?; + let maps: Vec = map.map_or_else(|| BakedMap::ALL.to_vec(), |map| vec![map]); + + let mut next: Vec = session.doc.project.texture_sets.iter().map(|set| set.bake.clone()).collect(); + let project = &session.doc.project; + // Every target together with the sets sharing `group` with it, so a sync group never drifts apart + let reached = |group: BakeSyncGroup| -> Vec { + let mut reached: Vec = targets.iter().flat_map(|target| project.bake_synced_sets(*target, group)).collect(); + reached.sort_unstable(); + reached.dedup(); + reached + }; + match strp(params, "what") { + Some("settings") => { + let groups = map.map_or_else( + || std::iter::once(BakeSyncGroup::Common).chain(maps.iter().map(|map| BakeSyncGroup::Map(*map))).collect(), + |map| vec![BakeSyncGroup::Map(map)], + ); + for group in groups { + for index in reached(group) { + if let Some(settings) = next.get_mut(index) { + settings.copy_group(&source, group); + } + } + } + if map.is_none() { + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| targets.contains(index)) { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, source.maps.is_enabled(map)); + } + } + } + } + Some(what @ ("checked" | "check")) => { + if what == "check" && map.is_none() { + return Err(bad(COMMAND, "`check` needs a `map`")); + } + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| targets.contains(index)) { + for map in &maps { + settings.maps.set_enabled(*map, what == "check" || source.maps.is_enabled(*map)); + } + } + } + _ => return Err(bad(COMMAND, "`what` must be settings, checked or check")), + } + + store(session, "Copy bake settings", next.into_iter().enumerate().collect())?; + Ok(json!({ "ts": targets })) +} + +/// Write each set's `next` bake settings as one undo step labelled `label`; nothing when none changed +pub(super) fn store(session: &mut Session, label: &str, next: Vec<(usize, BakeSettings)>) -> Result<()> { + let changed = + |session: &Session| next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)); + if !changed(session) { + return Ok(()); + } + + session.edit(label, |session| { + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + } + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{execute, sample_session}; + use texturecraft_core::BakeSettings; + + fn session() -> Session { + let session = sample_session(128, 32).unwrap(); + assert_eq!(session.set_count(), 2); + session + } + + fn bake(session: &Session, index: usize) -> &BakeSettings { + &session.doc.project.texture_sets[index].bake + } + + #[test] + fn projects_saved_before_sync_share_everything() { + let settings: BakeSettings = serde_json::from_value(json!({ "common": { "dilation": 4 } })).unwrap(); + assert!(settings.sync.common); + assert!(BakedMap::ALL.iter().all(|map| settings.sync.shares(BakeSyncGroup::Map(*map)))); + } + + #[test] + fn a_set_left_out_of_common_sync_keeps_its_own_common_settings() { + let mut session = session(); + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0, 1]); + + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Common), [1]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync is separate"); + + let reached = session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common); + execute(&mut session, "bake.settings", &json!({ "ts": reached, "patch": { "common": { "dilation": 7 } } })).unwrap(); + assert_eq!((bake(&session, 0).common.dilation, bake(&session, 1).common.dilation), (7, 32)); + } + + #[test] + fn a_set_joining_a_group_takes_its_settings_and_keeps_its_own_inclusion() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 3; + session.doc.project.texture_sets[1].bake.common.is_enabled = false; + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.common.dilation = 5; + + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": "all" })).unwrap(); + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": "all" })).unwrap(); + assert_eq!(bake(&session, 1).maps.ao.parameters, bake(&session, 0).maps.ao.parameters); + assert_eq!(bake(&session, 1).common.dilation, bake(&session, 0).common.dilation); + assert!(!bake(&session, 1).common.is_enabled, "whether the set bakes is its own"); + + session.undo().unwrap(); + assert_eq!(bake(&session, 1).common.dilation, 5, "one undo per sync"); + } + + #[test] + fn copies_check_maps_and_carry_settings_without_linking() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "height", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[0].bake.maps.height.parameters.scaling_divisor = 9.0; + + execute(&mut session, "bake.copy", &json!({ "what": "check", "map": "height", "ts": "all" })).unwrap(); + assert!(bake(&session, 0).maps.height.is_enabled && bake(&session, 1).maps.height.is_enabled); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "map": "height", "from": 0, "ts": [1] })).unwrap(); + assert_eq!(bake(&session, 1).maps.height.parameters.scaling_divisor, 9.0); + assert!(!bake(&session, 1).sync.shares(BakeSyncGroup::Map(BakedMap::Height)), "a copy does not link"); + + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + execute(&mut session, "bake.copy", &json!({ "what": "checked", "from": 0, "ts": [1] })).unwrap(); + assert_eq!(bake(&session, 1).maps.enabled().collect::>(), [BakedMap::Normal]); + } + + #[test] + fn a_copy_reaches_the_sets_sharing_the_group_with_its_target() { + let mut session = session(); + let third = session.doc.project.texture_sets[1].clone(); + session.doc.project.texture_sets.push(third); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0, 1] })).unwrap(); + session.doc.project.texture_sets[2].bake.maps.ao.parameters.rays.rays = 3; + let height_checked = !bake(&session, 0).maps.is_enabled(BakedMap::Height); + session.doc.project.texture_sets[2].bake.maps.set_enabled(BakedMap::Height, height_checked); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "from": 2, "ts": [0] })).unwrap(); + assert_eq!((bake(&session, 0).maps.ao.parameters.rays.rays, bake(&session, 1).maps.ao.parameters.rays.rays), (3, 3), "set 1 shares AO with set 0"); + assert!(!bake(&session, 2).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion))); + assert_eq!(bake(&session, 0).maps.is_enabled(BakedMap::Height), height_checked, "every setting includes which maps are checked"); + assert_ne!(bake(&session, 1).maps.is_enabled(BakedMap::Height), height_checked, "the set sharing a group keeps its own checkboxes"); + } + + #[test] + fn loading_a_preset_on_one_set_keeps_its_sync_groups_and_reaches_the_sets_sharing_them() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [1] })).unwrap(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = 9; + preset.maps.ao.parameters.rays.rays = 5; + preset.sync = Default::default(); + + let params = json!({ "ts": 0, "model": preset, "preserveEnabled": true, "preset": true }); + execute(&mut session, "bake.settings", ¶ms).unwrap(); + assert!(!bake(&session, 0).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion)), "a preset is settings, not membership"); + assert_eq!(bake(&session, 1).common.dilation, 9, "set 1 shares Common Settings with set 0"); + assert_ne!(bake(&session, 1).maps.ao.parameters.rays.rays, 5, "set 1 no longer shares AO with set 0"); + } + + #[test] + fn a_change_to_one_group_leaves_the_other_groups_of_the_sets_sharing_it_alone() { + let mut session = session(); + session.doc.project.texture_sets[1].bake.common.dilation = 3; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 6 } } } } } })).unwrap(); + assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6); + assert_eq!(bake(&session, 1).common.dilation, 3); + } +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 006bb979..59eaf446 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -209,8 +209,12 @@ impl Session { check_materials(&pf.project, &mesh)?; let source = pf.mesh.clone(); let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); - let mut s = - Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + + let mut s = Session::new( + Document { bake_meshes: Default::default(), bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, + mesh, + source, + )?; s.sync_images(); s.load_bake_meshes(pf.high_poly, pf.cage); @@ -608,10 +612,7 @@ impl Session { Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) } - /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: - /// texture sets map by material index. Nothing changes unless the new mesh fits the project. - /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies - /// like `file.reimportMesh`: `{preserved?}`. + /// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}` pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { @@ -625,27 +626,29 @@ impl Session { None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, }; + check_materials(&self.doc.project, &mesh)?; let mut doc = self.doc.clone(); if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; } + let mut next = Session::new(doc, mesh, source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); // The cage uses triangle indices and barycentrics, so it needs identical geometry - next.bake_meshes = self.bake_meshes.clone(); - next.bake_meshes.low_base_color = Default::default(); - if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { - next.bake_meshes.cage = None; + next.doc.bake_meshes.low_base_color = Default::default(); + if next.doc.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.doc.bake_meshes.cage = None; next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed"); } if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode"); } + next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -1486,19 +1489,21 @@ f 1/1 2/2 3/3 std::fs::create_dir_all(&dir).unwrap(); let a = dir.join("a.obj"); std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); - // Same triangle count, other vertices. + // Same triangle count, other vertices let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; - s.bake_meshes.cage = Some(cage); - let _ = s.bake_meshes.low_base_color.set(Err("old".into())); - // The same mesh again keeps the cage but not the cached colours. + let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.doc.bake_meshes.cage = Some(cage); + let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); + + // The same mesh again keeps the cage but not the cached colours crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_some()); - assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + assert!(s.doc.bake_meshes.cage.is_some()); + assert!(s.doc.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + assert!(s.doc.bake_meshes.cage.is_none(), "the cage was made for another mesh"); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..7ac866b0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -90,7 +90,7 @@ pub mod uv_tile_cmds; pub mod view_cmds; pub mod warp_cmds; -pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask, HighPolyLoad, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; pub use commands::{CommandSpec, check_enabled, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 678d7bb7..ac0b8636 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -70,7 +70,14 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() } + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + } } impl Session { @@ -129,12 +136,22 @@ impl Session { .first() .and_then(|t| t.stack.last().copied()) .ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?; + let resources: BTreeMap>> = project_file.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); - let source = Document { bake_paint: BTreeMap::new(), project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), resources }; + let source = Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project: project_file.project, + pixels: project_file.pixels, + baked: BTreeMap::new(), + resources, + }; + let id = self.edit("Add smart material", |s| { for (name, bytes) in &source.resources { s.doc.resources.entry(name.clone()).or_insert_with(|| Arc::clone(bytes)); } + let ts = s.ts(); let sel = s.selected_layer(); let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group()); @@ -144,6 +161,7 @@ impl Session { s.target = StackTarget::Content; Ok(id) })?; + self.sync_images(); Ok(id) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..cb69ffb3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -31,6 +31,8 @@ pub struct Document { pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>, /// Imported image resources by name: original file bytes. pub resources: BTreeMap>>, + /// High-definition meshes and cage for baking (saved inside the project) + pub bake_meshes: crate::BakeMeshes, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -426,8 +428,6 @@ pub struct Session { pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Vec)>, - /// High-definition meshes and cage for baking (saved inside the project). - pub bake_meshes: crate::BakeMeshes, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -525,7 +525,6 @@ impl Session { mesh, bvh: Arc::new(bvh), mesh_source, - bake_meshes: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), @@ -604,8 +603,7 @@ impl Session { Session::new_project_tiled(name, mesh, mesh_ref, mesh_source, resolution, None) } - /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` for every - /// set, `Some(false)` for none, `None` for the sets whose UVs leave tile 1001. + /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` every set, `Some(false)` none, `None` the sets whose UVs leave tile 1001 pub fn new_project_tiled( name: &str, mesh: Mesh, @@ -628,11 +626,20 @@ impl Session { ts.stack.push(id); project.texture_sets.push(ts); } + let mut s = Session::new( - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + }, mesh, mesh_source, )?; + s.log.append(log); Ok(s) } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 8c7a2791..13479df9 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -223,14 +223,17 @@ impl Session { .and_then(|root| pf.project.layers.get(&root)) .and_then(|l| l.mask.clone()) .ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?; + let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); let src = crate::session::Document { + bake_meshes: Default::default(), bake_paint: BTreeMap::new(), project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), }; + let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); self.edit(&format!("Apply smart mask {label}"), |s| { let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4c5314ad..09b9eca6 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -65,15 +65,15 @@ fn high_poly_meshes_drive_the_bake_and_round_trip() { // Save and reopen: meshes, cage and settings come back let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - let names = |session: &Session| session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); + let names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| (high.name.clone(), high.mesh.triangle_count())).collect::>(); assert_eq!(names(&reloaded), names(&session)); - assert_eq!(reloaded.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); + assert_eq!(reloaded.doc.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj")); assert_eq!(reloaded.doc.project.texture_sets[0].bake, session.doc.project.texture_sets[0].bake); execute(&mut session, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); - assert!(session.bake_meshes.high.is_empty()); + assert!(session.doc.bake_meshes.high.is_empty()); execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); - assert!(session.bake_meshes.cage.is_none()); + assert!(session.doc.bake_meshes.cage.is_none()); // Without high polys the bake falls back to the low poly execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); @@ -81,6 +81,63 @@ fn high_poly_meshes_drive_the_bake_and_round_trip() { let _ = std::fs::remove_dir_all(std::path::Path::new(&high).parent().unwrap()); } +#[test] +fn high_poly_and_cage_edits_are_undo_steps() { + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + let low = session.mesh.as_ref().clone(); + let high_names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect::>(); + let merged_triangles = |session: &Session| session.doc.bake_meshes.merged_high().map(|merged| merged.mesh.triangle_count()); + + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + assert_eq!(session.undo_label(), Some("Add high poly mesh")); + assert!(!session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high); + + session.undo().unwrap(); + assert!(high_names(&session).is_empty(), "undo takes the high poly out"); + assert_eq!(merged_triangles(&session), None, "bakes no longer see it"); + assert!(session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high, "the setting the add changed comes back"); + + session.redo().unwrap(); + assert_eq!(high_names(&session), ["part_high.obj"]); + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + execute(&mut session, "bake.highPoly.remove", &json!({ "index": 0 })).unwrap(); + session.undo().unwrap(); + assert_eq!(high_names(&session), ["part_high.obj"], "undo brings a removed high poly back"); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + session.undo().unwrap(); + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.undo().unwrap(); + assert!(session.doc.bake_meshes.cage.is_none(), "undo takes the cage out"); + session.redo().unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + session.undo().unwrap(); + assert_eq!(session.doc.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj"), "undo brings a removed cage back"); + + let steps = session.history_labels().len(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + assert_eq!(session.history_labels().len(), steps + 2, "removing nothing adds no step"); +} + +#[test] +fn opening_a_project_with_bake_meshes_adds_no_undo_step() { + let mut session = plane_session(); + let low = session.mesh.as_ref().clone(); + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reloaded.doc.bake_meshes.cage.is_some() && reloaded.doc.bake_meshes.merged_high().is_some()); + assert!(reloaded.history_labels().is_empty()); + assert!(!reloaded.modified, "a project just opened has nothing to save"); +} + #[test] fn malformed_high_poly_input_errors_cleanly() { let mut session = plane_session(); @@ -94,7 +151,7 @@ fn malformed_high_poly_input_errors_cleanly() { assert!(execute(&mut session, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); assert!(execute(&mut session, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); assert!(execute(&mut session, "bake.highPoly.remove", &Value::Null).is_err()); - assert!(session.bake_meshes.high.is_empty() && session.bake_meshes.cage.is_none()); + assert!(session.doc.bake_meshes.high.is_empty() && session.doc.bake_meshes.cage.is_none()); assert_eq!(session.doc.project, before, "failed imports preserve project settings"); } @@ -380,7 +437,7 @@ fn opacity_samples_a_textured_gltf_high_poly() { // The textures come back with the project let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color); } /// USDZ opacity uses the UsdPreviewSurface texture alpha @@ -441,7 +498,7 @@ fn opacity_samples_textures_next_to_a_high_poly() { // The project holds the folded file: the textures come back without the folder let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); - assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color, "{file}"); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color, "{file}"); } // A missing image is named in the log; the high poly still loads, untextured @@ -685,7 +742,7 @@ fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); - assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert_eq!(s.doc.bake_meshes.high.len(), 1, "the high poly stays"); assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); assert!(s.modified, "the project differs from the saved one"); assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 4b60f6f0..97dd4610 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -1,3 +1,5 @@ +use texturecraft_engine::core::BakedMap; + use crate::RunningBake; /// A background bake of one or more texture sets. @@ -7,4 +9,6 @@ pub struct BakeJob { pub total: usize, /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. pub mesh_id: u64, + /// The one map to bake (a row's quick bake) instead of the checked ones + pub only: Option, } diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs index 36b91298..4245a5a1 100644 --- a/crates/ui-egui/src/bake_mode/bake_checks.rs +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -50,7 +50,7 @@ pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc, Arc>)>(id)) && cached_key == key && cached_high.ptr_eq(&high) diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 14dc7fd5..2ece6800 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -1,35 +1,89 @@ -use egui::{RichText, Ui}; +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; use crate::i18n::{baked_map_label, tr}; +use crate::theme::{Tokens, semibold}; -/// The texture set and selected map above Mesh Map Settings, each behind a dropdown to switch it -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap) { +/// The breadcrumb's line and the air under its hairline +const LINE_HEIGHT: f32 = 32.0; +const AIR_BELOW: f32 = 10.0; + +/// A caret's click square, and the air between a caret and its name +const CARET_BOX: f32 = 18.0; +const CARET_TO_NAME: f32 = 4.0; + +/// Air between the set's name and the next caret +const NAME_TO_CARET: f32 = 8.0; + +/// Size of the carets and of the reset glyph +const CARET_SIZE: f32 = 12.0; +const RESET_SIZE: f32 = 14.0; +const RESET_BOX: f32 = 20.0; + +/// Size of the names +const NAME_SIZE: f32 = 12.0; + +/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; returns whether ⟲ was clicked +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, restorable: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); let active_set = app.session.ts(); let set_names: Vec = app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.name.clone()).collect(); + let (line, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_HEIGHT), Sense::hover()); + let center_y = line.center().y; + let painter = ui.painter().clone(); - ui.horizontal(|ui| { - ui.menu_button(icon::CARET_RIGHT, |ui| { - for (set_index, name) in set_names.iter().enumerate() { - if ui.selectable_label(set_index == active_set, name).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - ui.close(); - } - } - }); - ui.label(set_names.get(active_set).map_or("", String::as_str)); + let mut x = line.left(); + let set_caret = caret(ui, &painter, &tokens, x, center_y, "texture_set_caret", tr("Switch Texture Set")); + x += CARET_BOX + CARET_TO_NAME; + let set_name = set_names.get(active_set).map_or("", String::as_str); + let set_galley = painter.layout_no_wrap(set_name.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let set_width = set_galley.size().x; + painter.galley(pos2(x, center_y - set_galley.size().y / 2.0), set_galley, tokens.text); + x += set_width + NAME_TO_CARET; + let map_caret = caret(ui, &painter, &tokens, x, center_y, "map_caret", tr("Switch Mesh Map")); + x += CARET_BOX + CARET_TO_NAME; + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, tr(baked_map_label(selected)), semibold(NAME_SIZE), tokens.text_strong); - ui.menu_button(icon::CARET_RIGHT, |ui| { - for map in BakedMap::ALL { - if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { - app.ui.selected_baked_map = Some(map); - ui.close(); - } + egui::Popup::menu(&set_caret).show(|ui| { + for (set_index, name) in set_names.iter().enumerate() { + if ui.selectable_label(set_index == active_set, name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); } - }); - ui.label(RichText::new(tr(baked_map_label(selected))).strong()); + } }); + egui::Popup::menu(&map_caret).show(|ui| { + for map in BakedMap::ALL { + if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { + app.ui.selected_baked_map = Some(map); + } + } + }); + + let mut restore = false; + if restorable { + let rect = Rect::from_center_size(pos2(line.right() - RESET_BOX / 2.0, center_y), vec2(RESET_BOX, RESET_BOX)); + let response = ui.interact(rect, ui.scope_id().with("restore_defaults"), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, tr("Restore Defaults"))); + let response = response.on_hover_text(tr("Restore Defaults")); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_SIZE), color); + restore = response.clicked(); + } + + painter.line_segment([pos2(line.left(), line.bottom()), pos2(line.right(), line.bottom())], Stroke::new(1.0, tokens.separator)); + ui.add_space(AIR_BELOW); + restore +} + +/// A caret at `left` that opens a menu, answering as `label` +fn caret(ui: &mut Ui, painter: &egui::Painter, tokens: &Tokens, left: f32, center_y: f32, salt: &str, label: &str) -> egui::Response { + let rect = Rect::from_min_size(pos2(left, center_y - CARET_BOX / 2.0), vec2(CARET_BOX, CARET_BOX)); + let response = ui.interact(rect, ui.scope_id().with(salt), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, label)); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CARET_RIGHT, FontId::proportional(CARET_SIZE), color); + response } diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 1953d2d3..aca0ed1d 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -1,139 +1,161 @@ -use super::controls::{choice, hint, integer, number, section, text_input}; +use super::controls::{choice, integer, number, section, text_input}; use crate::TextureCraftApp; -use crate::i18n::tr; -use crate::theme::Tokens; -use crate::widgets::icon_button; -use egui::Ui; +use crate::i18n::{tr, trf}; +use crate::property_sheet::{FileListAdd, FileRow, PropertySheet}; use egui_phosphor::regular as icon; use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -/// How many rows the high poly list box is tall -const HIGH_POLY_LIST_ROWS: f32 = 5.0; +/// The high poly list is never shorter than this many rows, so it reads as a list while empty +const HIGH_POLY_LIST_MIN_ROWS: usize = 2; -/// Space between the panel's sections, in points -const SECTION_GAP: f32 = 8.0; +/// The Cage and Skew Correction ⟲ menus' items, in their order: reset the parameters, clear the paint strokes, both +const RESET_PARAMETERS: usize = 0; +const CLEAR_STROKES: usize = 1; +const RESET_AND_CLEAR: usize = 2; + +/// The cage list holds one file, so one row shows while it is empty +const CAGE_LIST_MIN_ROWS: usize = 1; + +/// Largest cage distance the sliders offer, and their decimals (relative to the bounding box, the reference's range) +const MAX_CAGE_DISTANCE: f32 = 0.05; +const CAGE_DISTANCE_DECIMALS: usize = 4; + +/// A paint brush's first value: half the frontal distance for the cage, full correction for skew +const CAGE_BRUSH_VALUE: f32 = 0.5; +const SKEW_BRUSH_VALUE: f32 = 1.0; + +/// The paint brush's radius range, in UV units +const BRUSH_RADIUS: std::ops::RangeInclusive = 0.002..=0.2; /// Widest dilation the slider offers, in texels (the bake settings command accepts the same) const MAX_DILATION_WIDTH: u32 = 128; -/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { +/// The Common Settings, Cage and Skew Correction sections, cage and skew greyed with the reason when they can't apply +pub(super) fn show(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, settings: &mut BakeSettings) -> Option { let mut reset = Map::new(); - ui.push_id("common", |ui| { - // Restore Defaults keeps whether the texture set is included in the bake - let is_enabled = settings.common.is_enabled; - if section(ui, tr("Common Parameters"), |ui| { - output_size(ui, &mut settings.common); - choice( - ui, - tr("Antialiasing"), - &mut settings.common.antialiasing, - &[ - (BakeAntialiasing::None, tr("None")), - (BakeAntialiasing::Subsampling2x2, tr("Subsampling 2x2")), - (BakeAntialiasing::Subsampling4x4, tr("Subsampling 4x4")), - (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), - ], - ); - integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); - ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); - }) { - settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; - let mut defaults = json!(settings.common); - if let Some(fields) = defaults.as_object_mut() { - fields.remove("is_enabled"); - } - reset.insert("common".into(), defaults); - } - }); + let has_high = !app.session.doc.bake_meshes.high.is_empty(); + let common_reset = section(sheet, tr("Common Settings"), &[], |sheet| { + sheet.sub_header(tr("Output Settings"), |sheet| { + output_size(sheet, &mut settings.common); + let antialiasing = BakeAntialiasing::ALL.map(|option| (option, antialiasing_label(option))); + choice(sheet, tr("Antialiasing"), &mut settings.common.antialiasing, &antialiasing); + integer(sheet, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); + sheet.check(tr("Apply Diffusion"), &mut settings.common.apply_diffusion); + }); + sheet.sub_header(tr("High-Poly Parameters"), |sheet| { + sheet.check(tr("Use Low Poly Mesh as High Poly Mesh"), &mut settings.high_poly.use_low_as_high); + high_poly_scene(app, sheet); - // Without a high poly the reference shows everything that needs one greyed, not hidden - let has_high = !app.session.bake_meshes.high.is_empty(); - ui.add_space(SECTION_GAP); - ui.push_id("high_poly", |ui| { - if section(ui, tr("High-Poly Parameters"), |ui| { - ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); - high_poly_scene(app, ui); - ui.add_enabled_ui(has_high, |ui| { - ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + // Without a high poly the reference shows everything that needs one greyed, not hidden + sheet.greyed(has_high, Some(tr("These settings apply once a high poly mesh is loaded.")), |sheet| { + sheet.check(tr("Ignore Backface"), &mut settings.high_poly.ignore_backface); choice( - ui, + sheet, tr("Match"), &mut settings.high_poly.match_mode, &[(MeshMatchMode::Always, tr("Always")), (MeshMatchMode::ByMeshName, tr("By Mesh Name"))], ); - text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); - text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); - text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); + text_input(sheet, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); + text_input(sheet, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); + text_input(sheet, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); }); - }) { - settings.high_poly = Default::default(); - reset.insert("high_poly".into(), json!(settings.high_poly)); + }); + }); + if common_reset.is_some() { + // Restoring keeps whether the texture set is included in the bake + settings.common = CommonBakeSettings { is_enabled: settings.common.is_enabled, ..CommonBakeSettings::default() }; + let mut defaults = json!(settings.common); + if let Some(fields) = defaults.as_object_mut() { + fields.remove("is_enabled"); + } + reset.insert("common".into(), defaults); + settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); + } + + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Cage Parameters"), tr("Clear All Cage Paint Strokes"), tr("Reset and Clear All")); + let cage_reset = section(sheet, tr("Cage"), &menu, |sheet| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + let reason = if has_high { + tr("The cage is not used while the low poly mesh is used as the high poly mesh.") + } else { + tr("The cage applies once a high poly mesh is loaded.") + }; + sheet.greyed(cage_applies, Some(reason), |sheet| { + choice( + sheet, + tr("Cage Type"), + &mut settings.cage.kind, + &[ + (CageType::DistanceBased, tr("Distance-Based")), + (CageType::Automatic, tr("Automatic (Experimental)")), + (CageType::CustomFile, tr("Custom File")), + ], + ); + if settings.cage.kind == CageType::DistanceBased { + paint_button(app, sheet, BakePaintTarget::Cage); + sheet.indented(|sheet| { + number(sheet, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + number(sheet, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + sheet.check(tr("Relative to Bounding Box"), &mut settings.cage.relative_to_bounding_box); + sheet.check(tr("Average Normals"), &mut settings.cage.average_normals); + }); + } + }); + + // A loaded cage stays listed and removable while the cage can't apply, so a saved one can still be dropped + if settings.cage.kind == CageType::CustomFile { + cage_file(app, sheet, cage_applies); } }); - - ui.add_space(SECTION_GAP); - ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), |ui| { - // The cage steers rays toward a separate high poly, so it has nothing to do without one - let cage_applies = has_high && !settings.high_poly.use_low_as_high; - if !has_high { - hint(ui, tr("The cage applies once a high poly mesh is loaded.")); - } else if !cage_applies { - hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); - } - ui.add_enabled_ui(cage_applies, |ui| { - choice( - ui, - tr("Cage Type"), - &mut settings.cage.kind, - &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], - ); - if settings.cage.kind == CageType::DistanceBased { - paint_brush(app, ui, BakePaintTarget::Cage); - number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); - number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); - ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); - ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); - } - }); - if settings.cage.kind == CageType::CustomFile { - cage_file(app, ui, cage_applies); - } - }) { + if let Some(item) = cage_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.cage = Default::default(); reset.insert("cage".into(), json!(settings.cage)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.cage.reset", json!({})); + } + } - // Shown greyed when it can't apply, as the reference does, with the reason on top + // Shown greyed when it can't apply, as the reference does, with the reason on hover let skew_applies = has_high && settings.skew_applies(); - ui.add_space(SECTION_GAP); - ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), |ui| { - if !skew_applies { - hint(ui, skew_unavailable_reason(settings, has_high)); - } - ui.add_enabled_ui(skew_applies, |ui| { - choice( - ui, - tr("Skew Correction Method"), - &mut settings.skew.method, - &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], - ); - paint_brush(app, ui, BakePaintTarget::Skew); - ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); - number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); - number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Skew Correction Parameters"), tr("Clear All Skew Paint Strokes"), tr("Reset and Clear All")); + let skew_reset = section(sheet, tr("Skew Correction"), &menu, |sheet| { + sheet.greyed(skew_applies, Some(skew_unavailable_reason(settings, has_high)), |sheet| { + paint_button(app, sheet, BakePaintTarget::Skew); + sheet.check(tr("Edge Protection"), &mut settings.skew.edge_protection); + sheet.greyed(settings.skew.edge_protection, None, |sheet| { + sheet.indented(|sheet| { + number(sheet, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(sheet, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }); }); - }) { + choice( + sheet, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + }); + }); + if let Some(item) = skew_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.skew = Default::default(); reset.insert("skew".into(), json!(settings.skew)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.skew.clear", json!({})); + } + } (!reset.is_empty()).then_some(Value::Object(reset)) } @@ -146,130 +168,122 @@ fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") } else if settings.cage.kind == CageType::CustomFile { tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else if settings.cage.kind == CageType::Automatic { + tr("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is.") } else { tr("Skew Correction needs Average Normals turned on in the cage settings.") } } -fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { - ui.label(tr("Output Size")); - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let dropdown_width = ((ui.available_width() - button_size - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); - let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { - egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { - for resolution in BakeResolution::ALL { - ui.selectable_value(value, resolution, resolution.pixels().to_string()); - } - }); - }; - - resolution(ui, "output_width", &mut settings.resolution); - let locked = settings.resolution_height.is_none(); - let mut height = settings.resolution_height.unwrap_or(settings.resolution); - ui.add_enabled_ui(!locked, |ui| resolution(ui, "output_height", &mut height)); - if !locked { - settings.resolution_height = Some(height); - } - - if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, button_size).clicked() { - settings.resolution_height = if locked { Some(settings.resolution) } else { None }; - } - }); +/// How the Antialiasing dropdown names `antialiasing` +pub(super) fn antialiasing_label(antialiasing: BakeAntialiasing) -> &'static str { + match antialiasing { + BakeAntialiasing::None => tr("None"), + BakeAntialiasing::Subsampling2x2 => tr("Subsampling 2x2"), + BakeAntialiasing::Subsampling4x4 => tr("Subsampling 4x4"), + BakeAntialiasing::Subsampling8x8 => tr("Subsampling 8x8"), + } } -/// The high poly meshes as a list box, with + to add some and − to remove the selected one -fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); - let selected_id = ui.make_persistent_id("high_poly_selected"); - let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); +/// The smallest output size offered, as in the reference; a project saved with a smaller one keeps it +const SMALLEST_OUTPUT_SIZE: u32 = 32; - ui.label(tr("High Poly Scene")); - let (mut add, mut remove) = (false, false); - ui.horizontal_top(|ui| { - let button_size = ui.spacing().interact_size.y; - let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); - let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; - egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { - ui.set_min_size(egui::vec2(list_width, list_height)); - ui.set_max_width(list_width); - egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { - for (index, name) in names.iter().enumerate() { - if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { - selected = Some(index); - } - } - }); - }); - ui.vertical(|ui| { - add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); - remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); - }); - }); +/// Width, the link, then the height it ties to the width, as in the reference +fn output_size(sheet: &mut PropertySheet<'_>, settings: &mut CommonBakeSettings) { + let sizes: Vec = BakeResolution::ALL.into_iter().filter(|resolution| resolution.pixels() >= SMALLEST_OUTPUT_SIZE).collect(); + let mut linked = settings.resolution_height.is_none(); + let height = settings.resolution_height.unwrap_or(settings.resolution); + let picked = sheet.dropdown_pair_above( + tr("Output Size"), + [settings.resolution, height], + &sizes, + |size| size.pixels().to_string(), + &mut linked, + tr("Lock Output Size"), + ); + match picked { + Some((0, size)) => settings.resolution = size, + Some((_, size)) => settings.resolution_height = Some(size), + None => {} + } + if linked { + settings.resolution_height = None; + } else if settings.resolution_height.is_none() { + settings.resolution_height = Some(settings.resolution); + } +} - if let (true, Some(index)) = (remove, selected) { +/// The high poly meshes, one row each with × to remove it, and + beside them to add some; files still loading show greyed +fn high_poly_scene(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let loading: Vec = app.high_poly_job.iter().flat_map(|job| job.file_names()).map(|name| trf("Loading {name}...", &[("name", &name)])).collect(); + let meshes = &app.session.doc.bake_meshes.high; + let rows: Vec> = meshes + .iter() + .map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }) + .chain(loading.iter().map(|name| FileRow { name, folder: None, loading: true })) + .collect(); + let answer = sheet.file_list( + tr("High Poly Scene"), + &rows, + HIGH_POLY_LIST_MIN_ROWS, + FileListAdd { glyph: icon::PLUS, label: tr("Add High-Poly Meshes"), enabled: true }, + tr("Remove"), + ); + if let Some(index) = answer.removed { app.run("bake.highPoly.remove", json!({ "index": index })); - selected = None; } - ui.data_mut(|data| { - if let Some(index) = selected { - data.insert_temp(selected_id, index); - } else { - data.remove_temp::(selected_id); - } - }); - if add { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), false); } } -/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped -fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { - ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); - let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); - ui.add_enabled_ui(apply, |ui| { - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); - } - }); - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { - app.run("bake.cage.clear", json!({})); - } - }); +/// The cage file's row, with the folder button that loads one while the cage `applies` +fn cage_file(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, applies: bool) { + let cage = app.session.doc.bake_meshes.cage.as_ref(); + let rows: Vec> = cage.iter().map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }).collect(); + let answer = sheet.file_list( + tr("Cage Scene"), + &rows, + CAGE_LIST_MIN_ROWS, + FileListAdd { glyph: icon::FOLDER_OPEN, label: tr("Load Cage"), enabled: applies }, + tr("Remove Cage"), + ); + if answer.removed.is_some() { + app.run("bake.cage.clear", json!({})); + } + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), true); + } } -fn paint_brush(app: &mut TextureCraftApp, ui: &mut Ui, target: BakePaintTarget) { - let (label, clear_label, clear_command) = match target { - BakePaintTarget::Cage => ("Paint Cage", "Reset Painted Cage", "bake.cage.reset"), - BakePaintTarget::Skew => ("Paint Skew Correction", "Remove Skew Correction", "bake.skew.clear"), +/// "Paint Cage" or "Paint Skew Correction", held down as "Stop Painting" while that brush is on, with the brush sliders under it +fn paint_button(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, target: BakePaintTarget) { + let label = match target { + BakePaintTarget::Cage => tr("Paint Cage"), + BakePaintTarget::Skew => tr("Paint Skew Correction"), }; let mut brush = app.ui.bake_paint_brush; let active = brush.on && brush.target == target; - if ui.add(egui::Button::new(tr(label)).selected(active)).clicked() { + let (glyph, text) = if active { (icon::PROHIBIT, tr("Stop Painting")) } else { (icon::PENCIL_SIMPLE, label) }; + if sheet.wide_button(glyph, text, active).clicked() { brush.on = !active; if brush.target != target { brush.value = match target { - BakePaintTarget::Cage => 0.5, - BakePaintTarget::Skew => 1.0, + BakePaintTarget::Cage => CAGE_BRUSH_VALUE, + BakePaintTarget::Skew => SKEW_BRUSH_VALUE, }; } brush.target = target; } if brush.on && brush.target == target { - number(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); - number(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); - number(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + sheet.indented(|sheet| { + number(sheet, tr("Radius"), &mut brush.radius, BRUSH_RADIUS, 3); + number(sheet, tr("Value"), &mut brush.value, 0.0..=1.0, 2); + number(sheet, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + }); if app.ui.layout == crate::state::ViewLayout::Only3D { app.ui.layout = crate::state::ViewLayout::Split; } } app.ui.bake_paint_brush = brush; - if app.session.doc.bake_paint.contains_key(&(app.session.ts(), target)) && ui.button(tr(clear_label)).clicked() { - app.run(clear_command, json!({})); - } } diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index f260bf7c..a8c78922 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -1,88 +1,55 @@ -use crate::i18n::tr; -use crate::theme::{Tokens, caption}; -use egui::collapsing_header::CollapsingState; -use egui::{RichText, Ui}; +//! The bake panels' settings on the property sheet: labels above full-width controls, as the reference's bake panels lay them out -/// A section's title bar with its chevron; clicking it opens or closes the section -fn section_header(ui: &mut Ui, title: &str, collapsing_state: &mut CollapsingState) { - let tokens = Tokens::get(ui.ctx()); - let header = egui::Frame::NONE.fill(tokens.row).corner_radius(tokens.cr()).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { - ui.set_min_width(ui.available_width()); - ui.horizontal(|ui| { - ui.set_min_height(ui.spacing().interact_size.y); - ui.add(egui::Label::new(caption(title).color(tokens.text_strong)).selectable(false)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 - }) - .inner - }) - .inner - }); +use crate::property_sheet::PropertySheet; - let response = ui.interact(header.response.rect, ui.make_persistent_id("section_header"), egui::Sense::click()); - if response.clicked() { - collapsing_state.toggle(ui); - } - - let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); - ui.put(header.inner, egui::Label::new(chevron).selectable(false)); -} - -/// A collapsible section with `contents` and Restore Defaults; returns whether that was clicked -pub(super) fn section(ui: &mut Ui, title: &str, contents: impl FnOnce(&mut Ui)) -> bool { - let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); - section_header(ui, title, &mut collapsing_state); - - collapsing_state - .show_body_unindented(ui, |ui| { - egui::Frame::NONE - .inner_margin(egui::Margin::same(8)) - .show(ui, |ui| { - contents(ui); - ui.add_space(6.0); - ui.button(tr("Restore Defaults")).clicked() - }) - .inner - }) - .is_some_and(|response| response.inner) -} - -pub(super) fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { - let caption = ui.label(label); - let selected = options.iter().find(|(option, _)| option == value).map_or("", |(_, label)| *label); - egui::ComboBox::from_id_salt(label) - .width(ui.available_width()) - .selected_text(selected) - .show_ui(ui, |ui| { - for (option, label) in options { - ui.selectable_value(value, *option, *label); +/// A folding section with `contents` under its caption; its reset glyph resets at once, or opens `reset_menu` when not empty. Returns the reset choice: `Some(0)` for a plain reset, else the chosen item of `reset_menu` (from 0) +pub(super) fn section(sheet: &mut PropertySheet<'_>, title: &str, reset_menu: &[&str], contents: impl FnOnce(&mut PropertySheet<'_>)) -> Option { + let section = sheet.fold_section(title, true); + let mut chosen = None; + if reset_menu.is_empty() { + chosen = section.reset.clicked().then_some(0); + } else { + // Hanging left from the glyph at the panel's right edge, so it stays inside the panel + egui::Popup::menu(§ion.reset).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + for (index, item) in reset_menu.iter().enumerate() { + if ui.button(*item).clicked() { + chosen = Some(index); + } } - }) - .response - .labelled_by(caption.id); + }); + } + if section.open { + contents(sheet); + } + chosen } -pub(super) fn number(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { - let response = crate::widgets::slider(ui, label, value, range.clone(), decimals); - if response.changed() && (response.dragged() || response.clicked()) { +/// A dropdown of `options`, each with its shown name +pub(super) fn choice(sheet: &mut PropertySheet<'_>, label: &str, value: &mut T, options: &[(T, &str)]) { + let values: Vec = options.iter().map(|(option, _)| *option).collect(); + let name = |option: T| options.iter().find(|(candidate, _)| *candidate == option).map_or("", |(_, name)| *name).to_owned(); + if let Some(picked) = sheet.dropdown_above(label, *value, &values, name) { + *value = picked; + } +} + +/// A slider whose dragged values keep `decimals` places +pub(super) fn number(sheet: &mut PropertySheet<'_>, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { + if sheet.slider_above(label, value, range.clone(), decimals).is_some() { let scale = 10_f32.powi(decimals as i32); *value = ((*value * scale).round() / scale).clamp(*range.start(), *range.end()); } } -pub(super) fn integer(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { +/// A slider of whole numbers +pub(super) fn integer(sheet: &mut PropertySheet<'_>, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { let mut number_value = *value as f32; - let response = crate::widgets::slider(ui, label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0); - if response.changed() { + if sheet.slider_above(label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0).is_some() { *value = (number_value.round() as u32).clamp(*range.start(), *range.end()); } } -pub(super) fn text_input(ui: &mut Ui, label: &str, value: &mut String) { - ui.label(label); - ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); -} - -pub(super) fn hint(ui: &mut Ui, text: &str) { - ui.label(RichText::new(text).color(Tokens::get(ui.ctx()).text_dim).size(11.0)); +/// A one-line text field +pub(super) fn text_input(sheet: &mut PropertySheet<'_>, label: &str, value: &mut String) { + sheet.text_field_above(label, value); } diff --git a/crates/ui-egui/src/bake_mode/glyph_look.rs b/crates/ui-egui/src/bake_mode/glyph_look.rs new file mode 100644 index 00000000..db9f8bc6 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/glyph_look.rs @@ -0,0 +1,9 @@ +/// How a baker row's glyph button shows its state +#[derive(Clone, Copy, PartialEq)] +pub(super) enum GlyphLook { + Plain, + /// Bright: what it stands for is on (the set shares these settings) + Lit, + /// Held down in a box: the view it toggles is showing + Pressed, +} diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 5168d341..7283d254 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,6 +1,6 @@ -use super::controls::{choice, hint, integer, number}; +use super::controls::{choice, integer, number}; use crate::i18n::tr; -use egui::Ui; +use crate::property_sheet::PropertySheet; use serde::Serialize; use serde_json::{Value, json}; use texturecraft_engine::core::{ @@ -9,89 +9,110 @@ use texturecraft_engine::core::{ RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, }; -/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so -pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option { +/// Most secondary rays a slider offers, as the reference's does (the bake settings command accepts the same) +const MAX_SECONDARY_RAYS: u32 = 256; + +/// Smallest distance, radius or divisor a slider offers: the bake settings command's lower limit +const SHORTEST_DISTANCE: f32 = 0.00001; + +/// Whether `map` has parameters (and so a Restore Defaults) +pub(super) fn has_parameters(map: BakedMap) -> bool { + !matches!(map, BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity) +} + +/// Draw `map`'s parameters; `restore` sets them back to the defaults. Maps without parameters say so +pub(super) fn show(sheet: &mut PropertySheet<'_>, map: BakedMap, settings: &mut MeshMapSettings, restore: bool) -> Option { match map { BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - hint(ui, tr("No Parameters")); + sheet.dim_line(tr("No Parameters")); None } - BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id), - BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion), - BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature), - BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position), - BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness), - BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height), - BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal), + BakedMap::Id => parameters(sheet, "id", &mut settings.id.parameters, restore, id), + BakedMap::AmbientOcclusion => parameters(sheet, "ao", &mut settings.ao.parameters, restore, ambient_occlusion), + BakedMap::Curvature => parameters(sheet, "curvature", &mut settings.curvature.parameters, restore, curvature), + BakedMap::Position => parameters(sheet, "position", &mut settings.position.parameters, restore, position), + BakedMap::Thickness => parameters(sheet, "thickness", &mut settings.thickness.parameters, restore, thickness), + BakedMap::Height => parameters(sheet, "height", &mut settings.height.parameters, restore, height), + BakedMap::BentNormal => parameters(sheet, "bent_normal", &mut settings.bent_normal.parameters, restore, bent_normal), } } -/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters -fn parameters(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option { - controls(ui, parameters); - ui.add_space(6.0); - - let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; - if restore.clicked() { +/// A map's controls; on `restore` only its parameters go back to the defaults +fn parameters( + sheet: &mut PropertySheet<'_>, + map_key: &str, + parameters: &mut T, + restore: bool, + controls: impl FnOnce(&mut PropertySheet<'_>, &mut T), +) -> Option { + controls(sheet, parameters); + if restore { *parameters = T::default(); return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } None } -fn id(ui: &mut Ui, settings: &mut IdSettings) { +/// Settings that belong to the one above: indented under it, greyed while it rules them out +fn dependent(sheet: &mut PropertySheet<'_>, applies: bool, body: impl FnOnce(&mut PropertySheet<'_>)) { + sheet.greyed(applies, None, |sheet| sheet.indented(body)); +} + +fn id(sheet: &mut PropertySheet<'_>, settings: &mut IdSettings) { choice( - ui, + sheet, tr("Color Source"), &mut settings.source, &[ (IdColorSource::VertexColor, tr("Vertex Color")), (IdColorSource::MaterialColor, tr("Material Color")), (IdColorSource::FileId, tr("File ID")), - (IdColorSource::MeshId, tr("Mesh ID")), + (IdColorSource::MeshId, tr("Mesh ID / Polygroup")), (IdColorSource::Submesh, tr("Submesh")), ], ); - if matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh) { + // Dependent controls show greyed and indented, never hidden, as in the reference + let generates_colors = matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh); + dependent(sheet, generates_colors, |sheet| { choice( - ui, + sheet, tr("Color Generator"), &mut settings.generator, &[(IdColorGenerator::Random, tr("Random")), (IdColorGenerator::HueShift, tr("Hue Shift")), (IdColorGenerator::Grayscale, tr("Grayscale"))], ); - } + }); } -fn rays(ui: &mut Ui, settings: &mut RaySettings) { - integer(ui, tr("Secondary Rays"), &mut settings.rays, 1..=256); - number(ui, tr("Min Occluder Distance"), &mut settings.min_distance, 0.00001..=1.0, 5); - number(ui, tr("Max Occluder Distance"), &mut settings.max_distance, 0.00001..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); - if ui.checkbox(&mut settings.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && settings.relative_to_bounding_box { +fn rays(sheet: &mut PropertySheet<'_>, settings: &mut RaySettings) { + integer(sheet, tr("Secondary Rays"), &mut settings.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Min Occluder Distance"), &mut settings.min_distance, SHORTEST_DISTANCE..=1.0, 5); + number(sheet, tr("Max Occluder Distance"), &mut settings.max_distance, SHORTEST_DISTANCE..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut settings.relative_to_bounding_box) && settings.relative_to_bounding_box { settings.max_distance = settings.max_distance.min(1.0); } - number(ui, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); - choice(ui, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); + number(sheet, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); + choice(sheet, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); } -fn backface(ui: &mut Ui, settings: &mut BackfaceMode) { +fn backface(sheet: &mut PropertySheet<'_>, settings: &mut BackfaceMode) { choice( - ui, + sheet, tr("Ignore Backface"), settings, &[(BackfaceMode::Never, tr("Never")), (BackfaceMode::Always, tr("Always")), (BackfaceMode::ByMeshName, tr("By Mesh Name"))], ); } -fn occlusion(ui: &mut Ui, label: &str, settings: &mut SelfOcclusion) { - choice(ui, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); +fn occlusion(sheet: &mut PropertySheet<'_>, label: &str, settings: &mut SelfOcclusion) { + choice(sheet, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); } -fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { - rays(ui, &mut settings.rays); - backface(ui, &mut settings.ignore_backface); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn ambient_occlusion(sheet: &mut PropertySheet<'_>, settings: &mut AmbientOcclusionSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Attenuation"), &mut settings.attenuation, &[ @@ -100,94 +121,104 @@ fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { (AmbientOcclusionAttenuation::Linear, tr("Linear")), ], ); - ui.checkbox(&mut settings.ground_plane.enabled, tr("Ground Plane")); - if settings.ground_plane.enabled { - number(ui, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2); - } + sheet.check(tr("Ground Plane"), &mut settings.ground_plane.enabled); + dependent(sheet, settings.ground_plane.enabled, |sheet| number(sheet, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2)); } -fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { +fn curvature(sheet: &mut PropertySheet<'_>, settings: &mut CurvatureSettings) { choice( - ui, + sheet, tr("Method"), &mut settings.method, - &[(CurvatureMethod::NormalMap, tr("Generate from Normal Map")), (CurvatureMethod::Mesh, tr("Generate from Mesh"))], + &[(CurvatureMethod::Mesh, tr("Generate from Mesh")), (CurvatureMethod::NormalMap, tr("Generate from Normal Map"))], ); match settings.method { CurvatureMethod::NormalMap => { - number(ui, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); - ui.checkbox(&mut settings.normal_map.enable_seams, tr("Enable Seams")); - if settings.normal_map.enable_seams { - number(ui, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2); - } + number(sheet, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); + sheet.check(tr("Enable Seams"), &mut settings.normal_map.enable_seams); + let seams = settings.normal_map.enable_seams; + dependent(sheet, seams, |sheet| number(sheet, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2)); } CurvatureMethod::Mesh => { let mesh = &mut settings.mesh; - integer(ui, tr("Secondary Rays"), &mut mesh.rays, 1..=256); - number(ui, tr("Sampling Radius"), &mut mesh.sampling_radius, 0.00001..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); - if ui.checkbox(&mut mesh.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && !mesh.relative_to_bounding_box { + integer(sheet, tr("Secondary Rays"), &mut mesh.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Sampling Radius"), &mut mesh.sampling_radius, SHORTEST_DISTANCE..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut mesh.relative_to_bounding_box) && !mesh.relative_to_bounding_box { mesh.sampling_radius = mesh.sampling_radius.min(1.0); } - occlusion(ui, tr("Self Intersection"), &mut mesh.self_intersection); - ui.checkbox(&mut mesh.auto_tonemapping, tr("Auto Tonemapping")); - if !mesh.auto_tonemapping { - number(ui, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); - number(ui, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); - } + occlusion(sheet, tr("Self Intersection"), &mut mesh.self_intersection); + sheet.check(tr("Auto Tonemapping (per UV Tile)"), &mut mesh.auto_tonemapping); + dependent(sheet, !mesh.auto_tonemapping, |sheet| { + number(sheet, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); + number(sheet, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); + }); } } } -fn position(ui: &mut Ui, settings: &mut PositionSettings) { - choice(ui, tr("Axis"), &mut settings.axis, &[(PositionAxis::All, tr("All")), (PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); +fn position(sheet: &mut PropertySheet<'_>, settings: &mut PositionSettings) { + // The reference splits the axis into a Mode and an Axis that applies only to One Axis + let mut one_axis = settings.axis != PositionAxis::All; + choice(sheet, tr("Mode"), &mut one_axis, &[(false, tr("All Axis")), (true, tr("One Axis"))]); + if one_axis && settings.axis == PositionAxis::All { + settings.axis = PositionAxis::X; + } else if !one_axis { + settings.axis = PositionAxis::All; + } + dependent(sheet, one_axis, |sheet| { + let mut axis = if one_axis { settings.axis } else { PositionAxis::X }; + choice(sheet, tr("Axis"), &mut axis, &[(PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); + if one_axis { + settings.axis = axis; + } + }); choice( - ui, + sheet, tr("Normalization Type"), &mut settings.normalization, &[(PositionMode::BoundingBox, tr("BBox")), (PositionMode::BoundingSphere, tr("BSphere")), (PositionMode::None, tr("None"))], ); choice( - ui, + sheet, tr("Normalization Scale"), &mut settings.scale, &[(PositionNormalizationScale::PerMaterial, tr("Per Material")), (PositionNormalizationScale::FullScene, tr("Full Scene"))], ); } -fn thickness(ui: &mut Ui, settings: &mut ThicknessSettings) { - rays(ui, &mut settings.rays); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn thickness(sheet: &mut PropertySheet<'_>, settings: &mut ThicknessSettings) { + rays(sheet, &mut settings.rays); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Normalization"), &mut settings.normalization, &[ (ThicknessNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), - (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (ThicknessNormalization::None, tr("None")), ], ); } -fn height(ui: &mut Ui, settings: &mut HeightSettings) { +fn height(sheet: &mut PropertySheet<'_>, settings: &mut HeightSettings) { choice( - ui, + sheet, tr("Normalization"), &mut settings.normalization, &[ (HeightNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), - (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh")), - (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh (per UV Tile)")), + (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (HeightNormalization::Manual, tr("Manual")), ], ); - if settings.normalization == HeightNormalization::Manual { - number(ui, tr("Scaling Divisor"), &mut settings.scaling_divisor, 0.00001..=100.0, 5); - } + let manual = settings.normalization == HeightNormalization::Manual; + dependent(sheet, manual, |sheet| number(sheet, tr("Scaling Divisor"), &mut settings.scaling_divisor, SHORTEST_DISTANCE..=100.0, 5)); } -fn bent_normal(ui: &mut Ui, settings: &mut BentNormalSettings) { - rays(ui, &mut settings.rays); - backface(ui, &mut settings.ignore_backface); - occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +fn bent_normal(sheet: &mut PropertySheet<'_>, settings: &mut BentNormalSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); } diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs new file mode 100644 index 00000000..433cbb98 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -0,0 +1,69 @@ +use std::collections::BTreeMap; +use std::sync::{Arc, Weak}; + +use egui::{ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::core::BakedMap; + +/// Side of a thumbnail's texture, in pixels (twice the row's square, for high-density screens) +const THUMBNAIL_PIXELS: u32 = 44; + +/// A thumbnail's texture, with the baked data and the working size it was drawn from +type Thumbnail = (Weak>, (u32, u32), TextureHandle); + +/// The Mesh Map Bakers rows' thumbnails of the baked maps, redrawn when a map is baked again +#[derive(Default)] +pub struct MapThumbnails { + textures: BTreeMap<(usize, BakedMap), Thumbnail>, +} + +impl MapThumbnails { + /// The thumbnail of `map` as texture set `texture_set` has it baked (a running bake's finished maps included), `None` before it is baked + pub fn texture(&mut self, context: &egui::Context, session: &Session, texture_set: usize, map: BakedMap) -> Option { + let key = (texture_set, map); + let baked = session.bake_preview_baked(texture_set).filter(|preview| preview.maps.contains_key(&map)).or_else(|| session.doc.baked.get(&texture_set)); + let (Some(data), Some(cache)) = (baked.and_then(|baked| baked.maps.get(&map)), session.caches.get(texture_set)) else { + self.textures.remove(&key); + return None; + }; + + if let Some((drawn_from, working_size, texture)) = self.textures.get(&key) + && drawn_from.ptr_eq(&Arc::downgrade(data)) + && *working_size == cache.size + { + return Some(texture.clone()); + } + + let rgba = texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, THUMBNAIL_PIXELS, cache.size, &cache.composite.block_scales); + let side = THUMBNAIL_PIXELS as usize; + let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); + let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); + self.textures.insert(key, (Arc::downgrade(data), cache.size, texture.clone())); + Some(texture) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_thumbnail_is_kept_until_its_map_is_baked_again() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let context = egui::Context::default(); + let mut thumbnails = MapThumbnails::default(); + let map = *session.doc.baked[&0].maps.keys().next().expect("the sample has a baked map"); + + let first = thumbnails.texture(&context, &session, 0, map).expect("a baked map has a thumbnail"); + assert_eq!(first.size(), [THUMBNAIL_PIXELS as usize; 2]); + assert_eq!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "the same bake reuses its texture"); + + let baked = session.doc.baked.get_mut(&0).unwrap(); + let rebaked = baked.maps[&map].as_ref().clone(); + baked.maps.insert(map, Arc::new(rebaked)); + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "a new bake is drawn again"); + + session.doc.baked.get_mut(&0).unwrap().maps.remove(&map); + assert!(thumbnails.texture(&context, &session, 0, map).is_none(), "a map not baked has none"); + } +} diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 059af550..4fbe3505 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,45 +1,112 @@ -use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui::{Align, CornerRadius, FontId, Layout, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use super::glyph_look::GlyphLook; +use super::set_picker::SetPicker; +use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{baked_map_label, tr, trf}; -use crate::theme::Tokens; +use crate::property_sheet::{CHECK_SIZE, paint_check}; +use crate::theme::{Tokens, semibold}; -/// Height of one baker row, in points -const ROW_HEIGHT: f32 = 24.0; -/// Inset of a row's checkbox and name from its left edge, in points +/// The presets menu's least width, and its name field's, room for a typical preset name +const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; +const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; + +/// How far past its box a row's check takes clicks, so it is easy to hit +const CHECK_HIT_AIR: f32 = 3.0; + +/// Height of the header's buttons, the air inside them beside their words, and between the glyph and the words +const HEADER_BUTTON_HEIGHT: f32 = 24.0; +const HEADER_BUTTON_PADDING: f32 = 10.0; +const HEADER_GLYPH_GAP: f32 = 6.0; +/// Air above the header and between its buttons +const HEADER_AIR: f32 = 6.0; +const HEADER_GAP: f32 = 6.0; +/// Height of one baker row, and of the Check All row +const ROW_HEIGHT: f32 = 28.0; +/// Inset of a row's check from its left edge const ROW_INSET: f32 = 6.0; +/// Side of a row's map thumbnail, and the air on its sides +const THUMBNAIL_SIZE: f32 = 22.0; +const THUMBNAIL_AIR: f32 = 9.0; +/// Side of a row's icon buttons and of the list menu button +const ROW_BUTTON_SIZE: f32 = 20.0; +/// Size of a row's glyphs +const ROW_GLYPH_SIZE: f32 = 14.0; +/// Size of the map names +const NAME_SIZE: f32 = 12.0; +/// Corner radius of a row's face and of a held-down glyph's box +const ROW_RADIUS: u8 = 4; +/// Opacity of a hovered row's face, against the selected row's full one +const HOVER_FACE_OPACITY: f32 = 0.5; +/// Air above and below the hairline under Check All +const RULE_AIR: f32 = 4.0; -/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { - if ui.button(format!("{} {}", icon::GEAR, tr("Common Settings"))).clicked() { - app.ui.dock.focus(Panel::CommonSettings); - } + let several_sets = app.session.doc.project.texture_sets.len() > 1; + ui.add_space(HEADER_AIR); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = HEADER_GAP; + if header_button(ui, icon::GEAR, tr("Common Settings")).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Common); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + if glyph_button(ui, slot, icon::LINK, tr("Synchronize Common Settings"), look).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Common)); + } + } + presets_menu(app, ui, settings); + }); + }); - presets_menu(app, ui, settings); + SetPicker::show(app, &ui.ctx().clone()); - ui.add_space(4.0); - check_all(ui, settings); - ui.separator(); + ui.add_space(RULE_AIR); + check_all_row(app, ui, settings); + ui.add_space(RULE_AIR); + let rule = ui.available_rect_before_wrap(); + ui.painter().hline(rule.x_range(), rule.top(), Stroke::new(1.0, Tokens::get(ui.ctx()).separator)); + ui.add_space(RULE_AIR); let selected = super::selected_map(app.ui.selected_baked_map, settings); + let check_drag_id = ui.scope_id().with("check_drag"); + let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } } + + // Kept through the frame of the release, so the click that ends a drag does not toggle its last checkbox back + let is_held = ui.input(|input| input.pointer.primary_down()); + ui.data_mut(|data| { + if let Some(value) = check_drag.filter(|_| is_held) { + data.insert_temp(check_drag_id, value); + } else { + data.remove_temp::(check_drag_id); + } + }); } /// The Presets menu: save the active set's settings under a name, load or delete a saved one, copy to all sets fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) { - ui.menu_button(format!("{} {}", icon::SLIDERS_HORIZONTAL, tr("Presets")), |ui| { - ui.set_min_width(220.0); + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + let button = glyph_button(ui, slot, icon::SLIDERS_HORIZONTAL, tr("Presets"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + ui.set_min_width(PRESETS_MENU_MIN_WIDTH); ui.horizontal(|ui| { - let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(130.0); + let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(PRESET_NAME_FIELD_WIDTH); let enter = ui.add(name_edit).lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); let can_save = !app.ui.bake_preset_name.trim().is_empty(); if (ui.add_enabled(can_save, egui::Button::new(tr("Save Preset"))).clicked() || (enter && can_save)) @@ -90,45 +157,209 @@ fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) }); } -/// Enable every map, or disable them all when every map is already enabled -fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { +/// Check All (mixed while only some maps are checked; a click checks them all, or unchecks them when all are) with the ≡ menu at the right +fn check_all_row(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let tokens = Tokens::get(ui.ctx()); let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); - let mut all_enabled = enabled_count == BakedMap::ALL.len(); - let some_enabled = enabled_count > 0 && !all_enabled; + let all_enabled = enabled_count == BakedMap::ALL.len(); + let state = match enabled_count { + 0 => Some(false), + _ if all_enabled => Some(true), + _ => None, + }; - if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let label = tr("Check All"); + let galley = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let hit = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(check.right() + THUMBNAIL_AIR + galley.size().x, rect.bottom())); + let response = ui.interact(hit, ui.scope_id().with("check_all"), Sense::click()); + response.widget_info(|| match state { + Some(on) => egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, label), + None => egui::WidgetInfo::labeled(egui::Role::CheckBox, true, label), + }); + paint_check(ui.painter(), &tokens, check, state, response.hovered()); + ui.painter().galley(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + if response.clicked() { for map in BakedMap::ALL { - settings.maps.set_enabled(map, all_enabled); + settings.maps.set_enabled(map, !all_enabled); } } + + let menu = Rect::from_center_size(pos2(rect.right() - ROW_BUTTON_SIZE / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + let mut menu_ui = ui.new_child(UiBuilder::new().max_rect(menu)); + list_menu(app, &mut menu_ui, settings); +} + +/// The ≡ menu beside Check All: check states, and copying them or every setting to other texture sets +fn list_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let button = glyph_button(ui, ui.max_rect(), icon::LIST, tr("Mesh Map Bakers Menu"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + if ui.button(tr("Check All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, true)); + } + if ui.button(tr("Uncheck All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, false)); + } + if ui.button(tr("Invert Checked Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, !settings.maps.is_enabled(map))); + } + copy_items(app, ui, "checked", None, [tr("Apply Checked to More Texture Sets..."), tr("Apply Checked to All Texture Sets")]); + ui.separator(); + copy_items(app, ui, "settings", None, [tr("Sync All Settings to More Texture Sets..."), tr("Sync All Settings to All Texture Sets")]); + }); +} + +/// A copy's two menu items: "...more Texture Sets..." opens the set picker, "...all Texture Sets" copies to every set +fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, what: &'static str, map: Option, [more, all]: [&str; 2]) { + // With one texture set there is nothing to copy to + let several_sets = app.session.doc.project.texture_sets.len() > 1; + if ui.add_enabled(several_sets, egui::Button::new(more)).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Copy { what, map }); + } + if ui.add_enabled(several_sets, egui::Button::new(all)).clicked() { + let from = app.session.ts(); + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": from, "ts": "all" })); + } } -/// One baker row; returns whether the row (not its checkbox) was clicked -fn row(ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool) -> bool { +/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses); returns whether the row itself was clicked +fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option) -> bool { + let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); - let painter = ui.painter(); + // The selected row is brighter and its name bold: no outline, no accent + let hovered = ui.rect_contains_pointer(rect); if is_selected { - painter.rect_filled(rect, tokens.cr(), tokens.row_selected); - painter.rect_stroke(rect, tokens.cr(), Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, tokens.cr(), tokens.row_hover); - } - painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); - - // Added after the row's own response, so the checkbox takes the clicks over it - let content_rect = rect.shrink2(vec2(ROW_INSET, 0.0)); - let mut content = ui.new_child(UiBuilder::new().max_rect(content_rect).layout(Layout::left_to_right(Align::Center))); - let mut is_enabled = settings.maps.is_enabled(map); - let checkbox = content.checkbox(&mut is_enabled, ""); - let text = if is_selected { RichText::new(name).strong() } else { RichText::new(name) }; - let label = content.add(egui::Label::new(text).selectable(false).truncate()); - if checkbox.labelled_by(label.id).changed() { - settings.maps.set_enabled(map, is_enabled); + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover); + } else if hovered { + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover.gamma_multiply(HOVER_FACE_OPACITY)); } + // Added after the row's own response, so the check and icons take the clicks over it + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); + checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); + let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag); + if let Some(value) = check_drag.filter(|_| is_dragged_over) { + settings.maps.set_enabled(map, value); + } else if checkbox.clicked() && check_drag.is_none() { + settings.maps.set_enabled(map, !settings.maps.is_enabled(map)); + } + paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered()); + + let texture = app.bake_map_thumbnails.texture(ui.ctx(), &app.session, app.session.ts(), map); + let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(ui, thumbnail_rect, texture.as_ref()); + + // Icons right to left, only on the hovered or selected row + let mut icons_left = rect.right(); + if is_selected || hovered { + let mut next_icon = || { + let slot = + Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + icons_left = slot.left() - ROW_INSET / 2.0; + slot + }; + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Map(map)); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + if glyph_button(ui, next_icon(), icon::LINK, &trf("Synchronize {map} Settings", &[("map", &name)]), look).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + } + } + let baking = app.bake_progress().is_some(); + let bolt = next_icon(); + let bolt_label = trf("Bake {map} Only", &[("map", &name)]); + if ui.add_enabled_ui(!baking, |ui| glyph_button(ui, bolt, icon::LIGHTNING, &bolt_label, GlyphLook::Plain)).inner.clicked() { + let active = app.session.ts(); + app.start_bake_of(vec![active], Some(map)); + } + let shown = app.session.view == ViewMode::MeshMap(map); + let look = if shown { GlyphLook::Pressed } else { GlyphLook::Plain }; + if glyph_button(ui, next_icon(), icon::EYE, &trf("Show {map} in the Viewport", &[("map", &name)]), look).clicked() { + let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; + app.run("viewport.view", json!({ "mode": mode })); + } + } + + let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; + let font = if is_selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let color = if is_selected { tokens.text_strong } else { tokens.text }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), font, color); + job.wrap = egui::text::TextWrapping::truncate_at_width((icons_left - name_left).max(0.0)); + let galley = ui.painter().layout_job(job); + // The full name on hover only when the row cuts it short + let response = if galley.elided { response.on_hover_text(name) } else { response }; + ui.painter().galley(pos2(name_left, rect.center().y - galley.size().y / 2.0), galley, color); + + response.context_menu(|ui| { + let labels = |more: &str, all: &str| [trf(more, &[("map", &name)]), trf(all, &[("map", &name)])]; + let [check_more, check_all] = labels("Check {map} for More Texture Sets...", "Check {map} for All Texture Sets"); + copy_items(app, ui, "check", Some(map), [&check_more, &check_all]); + ui.separator(); + let [apply_more, apply_all] = labels("Apply {map} Settings to More Texture Sets...", "Apply {map} Settings to All Texture Sets"); + copy_items(app, ui, "settings", Some(map), [&apply_more, &apply_all]); + ui.separator(); + if ui.add_enabled(several_sets, egui::Button::new(tr("Sync Settings..."))).clicked() { + SetPicker::open(app, ui.ctx(), SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + } + }); response.clicked() } + +/// Start a checkbox drag at a press on `checkbox`; returns whether a drag is in this row's checkbox column now (the whole row height counts) +fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option) -> bool { + if check_drag.is_none() && checkbox.is_pointer_button_down_on() { + *check_drag = Some(!is_enabled); + } + check_drag.is_some() && ui.rect_contains_pointer(Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range())) +} + +/// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal +fn thumbnail(ui: &Ui, rect: Rect, texture: Option<&egui::TextureHandle>) { + let tokens = Tokens::get(ui.ctx()); + let stroke = Stroke::new(1.0, tokens.text_dim); + match texture { + Some(texture) => { + egui::Image::new(texture).paint_at(ui, rect); + } + None => { + ui.painter().line_segment([rect.left_bottom(), rect.right_top()], stroke); + ui.painter().rect_stroke(rect, 0.0, stroke, egui::StrokeKind::Inside); + } + } +} + +/// A glyph in `rect` that answers clicks as `label`, its tooltip +fn glyph_button(ui: &mut Ui, rect: Rect, glyph: &str, label: &str, look: GlyphLook) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(label), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), look != GlyphLook::Plain, label)); + let response = response.on_hover_text(label); + if look == GlyphLook::Pressed { + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), tokens.separator, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + } + let color = if look == GlyphLook::Plain && !response.hovered() { tokens.text_dim } else { tokens.text_strong }; + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, glyph, FontId::proportional(ROW_GLYPH_SIZE), color); + response +} + +/// One of the header's bordered buttons, sized to its glyph and words +fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let icon = ui.painter().layout_no_wrap(glyph.to_owned(), FontId::proportional(ROW_GLYPH_SIZE), tokens.text); + let words = ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let width = 2.0 * HEADER_BUTTON_PADDING + icon.size().x + HEADER_GLYPH_GAP + words.size().x; + let (rect, response) = ui.allocate_exact_size(vec2(width, HEADER_BUTTON_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), fill, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + let x = rect.left() + HEADER_BUTTON_PADDING; + ui.painter().galley(pos2(x, rect.center().y - icon.size().y / 2.0), icon.clone(), tokens.text); + ui.painter().galley(pos2(x + icon.size().x + HEADER_GLYPH_GAP, rect.center().y - words.size().y / 2.0), words, tokens.text); + response +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 2ae7f095..a4bf439f 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -6,6 +6,7 @@ mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; +mod glyph_look; mod section_opening; pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; @@ -13,19 +14,31 @@ pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; +mod map_thumbnails; mod mesh_map_bakers; +pub use map_thumbnails::MapThumbnails; +mod set_picker; +mod set_picker_purpose; +mod set_picker_row; use egui::{Ui, vec2}; use egui_phosphor::regular as icon; use serde_json::{Value, json}; +use texturecraft_engine::Session; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, CageType}; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::property_sheet::PropertySheet; use crate::state::Mode; use crate::widgets::{icon_button, primary_button}; +/// Whether the high poly shows its matching error for `session`'s selected texture set: the automatic cage has no distances to fall short, as in the reference +pub(crate) fn matching_error_applies(session: &Session) -> bool { + session.doc.project.texture_sets.get(session.ts()).is_none_or(|set| set.bake.cage.kind != CageType::Automatic) +} + pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { for set_index in 0..app.session.set_count() { @@ -156,20 +169,30 @@ pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); - breadcrumb::show(app, ui, selected); - ui.separator(); - edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| { - ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner + let restore = ui.horizontal(|ui| { + ui.add_space(crate::property_sheet::SIDE_PADDING_POINTS); + ui.vertical(|ui| { + ui.set_width(ui.available_width() - crate::property_sheet::SIDE_PADDING_POINTS); + breadcrumb::show(app, ui, selected, map_settings::has_parameters(selected)) + }) + .inner + }); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected))); + edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { + PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.inner)) }); } /// The Common Settings panel: output, high poly, cage and skew settings pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Common)); + edit_settings(app, ui, "bake_common_settings", texture_sets, |app, ui, settings| { + PropertySheet::show(ui, "bake_common_sheet", |sheet| common_settings::show(app, sheet, settings)) + }); } /// The map whose settings show: the chosen one, else the first enabled map, else Normal -fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { +pub(super) fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) } diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs new file mode 100644 index 00000000..fc27b9e9 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -0,0 +1,290 @@ +//! The dialog that picks texture sets: which ones share settings, or which ones a copy goes to + +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; + +use super::common_settings::antialiasing_label; +use super::set_picker_purpose::SetPickerPurpose; +use super::set_picker_row::SetPickerRow; +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::theme::{Tokens, semibold}; + +/// Width of the dialog, in points +const DIALOG_WIDTH: f32 = 420.0; + +/// The title bar: its height, the gear's and the title's left edges, and the glyph and title sizes +const TITLE_BAR_HEIGHT: f32 = 30.0; +const TITLE_GEAR_CENTER: f32 = 19.0; +const TITLE_TEXT_LEFT: f32 = 34.0; +const TITLE_GLYPH_SIZE: f32 = 14.0; +const TITLE_TEXT_SIZE: f32 = 12.0; + +/// Air under the title bar and above the buttons, and around the dialog's edge +const BODY_AIR: f32 = 12.0; +const BUTTONS_AIR: f32 = 18.0; +const EDGE_AIR: f32 = 12.0; + +/// OK and Cancel: their size, the air between them, their corners +const BUTTON_SIZE: egui::Vec2 = vec2(88.0, 24.0); +const BUTTON_GAP: f32 = 8.0; +const DIALOG_RADIUS: u8 = 4; + +/// An open picker: what it is for, and per texture set whether it is ticked +#[derive(Clone, Debug)] +pub(super) struct SetPicker { + purpose: SetPickerPurpose, + chosen: Vec, +} + +impl SetPicker { + fn id() -> egui::Id { + egui::Id::unique("bake_set_picker") + } + + /// Open the picker for `purpose`; a sync picker starts with the sets sharing the group ticked, a copy picker with none + pub(super) fn open(app: &TextureCraftApp, ctx: &egui::Context, purpose: SetPickerPurpose) { + let chosen = app + .session + .doc + .project + .texture_sets + .iter() + .map(|set| match purpose { + SetPickerPurpose::Sync(group) => set.bake.sync.shares(group), + SetPickerPurpose::Copy { .. } => false, + }) + .collect(); + ctx.data_mut(|data| data.insert_temp(Self::id(), SetPicker { purpose, chosen })); + } + + /// The open picker, if any; OK runs its command + pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; + + let rows = picker.rows(app); + let active = app.session.ts(); + let tokens = Tokens::get(ctx); + let frame = egui::Frame::new() + .fill(tokens.panel) + .stroke(Stroke::new(1.0, tokens.button_border)) + .corner_radius(CornerRadius::same(DIALOG_RADIUS)) + .inner_margin(0); + let modal = egui::Modal::new(Self::id().with("modal")).frame(frame).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let closed = title_bar(ui, &tokens, &picker.title()); + ui.add_space(BODY_AIR); + PropertySheet::show(ui, "bake_set_picker_sheet", |sheet| picker.list(sheet, &rows)); + ui.add_space(BUTTONS_AIR); + let (ok, cancel) = buttons(ui, &tokens); + ui.add_space(EDGE_AIR); + (ok, cancel || closed) + }); + + let (ok, cancel) = modal.inner; + if ok { + picker.apply(app, active); + } + if ok || cancel || modal.should_close() { + ctx.data_mut(|data| data.remove::(Self::id())); + } else { + ctx.data_mut(|data| data.insert_temp(Self::id(), picker)); + } + } + + /// The listed sets + fn rows(&self, app: &TextureCraftApp) -> Vec { + let project = &app.session.doc.project; + let active = app.session.ts(); + let source = match self.purpose { + // New additions take on the settings already shared, or the active set's when none are + SetPickerPurpose::Sync(group) => project.texture_sets.iter().find(|set| set.bake.sync.shares(group)).or(project.texture_sets.get(active)), + SetPickerPurpose::Copy { .. } => None, + }; + project + .texture_sets + .iter() + .enumerate() + // A copy goes from the active set, so it isn't listed + .filter(|(index, _)| matches!(self.purpose, SetPickerPurpose::Sync(_)) || *index != active) + .map(|(index, set)| { + let note = match (self.purpose, source) { + (SetPickerPurpose::Sync(group), Some(source)) if !set.bake.sync.shares(group) => differing_values(&set.bake, &source.bake, group), + _ => None, + }; + SetPickerRow { index, name: set.name.clone(), note } + }) + .collect() + } + + fn title(&self) -> String { + match self.purpose { + SetPickerPurpose::Sync(group) => trf("{settings} Sync", &[("settings", &group_label(group))]), + SetPickerPurpose::Copy { what: "checked", .. } => tr("Apply Checked to More Texture Sets").to_owned(), + SetPickerPurpose::Copy { what: "check", map: Some(map) } => trf("Check {map} for More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { map: Some(map), .. } => trf("Apply {map} Settings to More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { .. } => tr("Sync All Settings to More Texture Sets").to_owned(), + } + } + + /// The master check and one check per listed set, indented under it + fn list(&mut self, sheet: &mut PropertySheet<'_>, rows: &[SetPickerRow]) { + let ticked = rows.iter().filter(|row| self.chosen.get(row.index).copied().unwrap_or(false)).count(); + let all_ticked = ticked == rows.len(); + let label = if all_ticked { tr("Deselect All") } else { tr("Select All") }; + let state = if ticked == 0 { Some(false) } else { all_ticked.then_some(true) }; + if sheet.check_mixed(label, state).clicked() { + for row in rows { + if let Some(chosen) = self.chosen.get_mut(row.index) { + *chosen = !all_ticked; + } + } + } + sheet.indented(|sheet| { + for row in rows { + let Some(chosen) = self.chosen.get_mut(row.index) else { continue }; + if sheet.check_noted(&row.name, Some(*chosen), row.note.as_deref()).clicked() { + *chosen = !*chosen; + } + } + }); + } + + fn apply(&self, app: &mut TextureCraftApp, active: usize) { + let ticked: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); + match self.purpose { + SetPickerPurpose::Sync(group) => { + app.run("bake.sync", json!({ "group": group_id(group), "ts": ticked })); + } + SetPickerPurpose::Copy { what, map } if !ticked.is_empty() => { + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": active, "ts": ticked })); + } + SetPickerPurpose::Copy { .. } => {} + } + } +} + +/// The group as the `bake.sync` command names it +pub(super) fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn group_label(group: BakeSyncGroup) -> String { + match group { + BakeSyncGroup::Common => tr("Common Settings").to_owned(), + BakeSyncGroup::Map(map) => trf("{map} Settings", &[("map", &tr(baked_map_label(map)))]), + } +} + +/// The title bar: gear, title, and × at the right; returns whether × was clicked +fn title_bar(ui: &mut Ui, tokens: &Tokens, title: &str) -> bool { + let (bar, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, TITLE_BAR_HEIGHT), Sense::hover()); + let top = CornerRadius { nw: DIALOG_RADIUS, ne: DIALOG_RADIUS, sw: 0, se: 0 }; + ui.painter().rect_filled(bar, top, tokens.chrome); + let center_y = bar.center().y; + ui.painter().text(pos2(bar.left() + TITLE_GEAR_CENTER, center_y), Align2::CENTER_CENTER, icon::GEAR, FontId::proportional(TITLE_GLYPH_SIZE), tokens.text); + let text = Rect::from_min_max(pos2(bar.left() + TITLE_TEXT_LEFT, bar.top()), pos2(bar.right() - TITLE_BAR_HEIGHT, bar.bottom())); + let label = egui::Label::new(RichText::new(title).font(semibold(TITLE_TEXT_SIZE)).color(tokens.text_strong)).truncate(); + ui.scope_builder(egui::UiBuilder::new().max_rect(text).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| ui.add(label)); + + let close = Rect::from_center_size(pos2(bar.right() - TITLE_BAR_HEIGHT / 2.0, center_y), vec2(TITLE_BAR_HEIGHT, TITLE_BAR_HEIGHT)); + let response = ui.interact(close, ui.scope_id().with("close"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Close"))); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(close.center(), Align2::CENTER_CENTER, icon::X, FontId::proportional(TITLE_TEXT_SIZE), color); + response.clicked() +} + +/// OK then Cancel at the right, both neutral; returns (OK, Cancel) clicked +fn buttons(ui: &mut Ui, tokens: &Tokens) -> (bool, bool) { + let (row, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, BUTTON_SIZE.y), Sense::hover()); + let cancel = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.top()), BUTTON_SIZE); + let ok = cancel.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); + (dialog_button(ui, tokens, ok, tr("OK")), dialog_button(ui, tokens, cancel, tr("Cancel"))) +} + +fn dialog_button(ui: &mut Ui, tokens: &Tokens, rect: Rect, text: &str) -> bool { + let response = ui.interact(rect, ui.scope_id().with(text), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(DIALOG_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(TITLE_TEXT_SIZE), tokens.text); + response.clicked() +} + +/// What `set` holds in `group` that differs from `source`, dim beside it: output size and antialiasing by value, the rest counted +fn differing_values(set: &BakeSettings, source: &BakeSettings, group: BakeSyncGroup) -> Option { + let mut taken = set.clone(); + taken.copy_group(source, group); + let mut patch = settings_patch(set, &taken); + let mut values = Vec::new(); + if let Some(common) = patch.get_mut("common").and_then(Value::as_object_mut) { + let resolution = common.remove("resolution").is_some(); + let height = common.remove("resolution_height").is_some(); + if resolution || height { + values.push(match set.common.output_size() { + (width, height) if width == height => width.to_string(), + (width, height) => format!("{width} × {height}"), + }); + } + if common.remove("antialiasing").is_some() { + values.push(tr(antialiasing_label(set.common.antialiasing)).to_owned()); + } + } + let rest = leaf_count(&patch); + match (values.is_empty(), rest) { + (true, 0) => None, + (true, 1) => Some(tr("1 differing setting").to_owned()), + (true, count) => Some(trf("{count} differing settings", &[("count", &count.to_string())])), + (false, 0) => Some(values.join(" · ")), + (false, count) => Some(trf("{values} · {count} more", &[("values", &values.join(" · ")), ("count", &count.to_string())])), + } +} + +/// How many plain values a settings patch changes +fn leaf_count(patch: &Value) -> usize { + match patch { + Value::Object(fields) => fields.values().map(leaf_count).sum(), + _ => 1, + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; + + use super::differing_values; + + #[test] + fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.resolution = BakeResolution::R1024; + set.common.antialiasing = BakeAntialiasing::Subsampling4x4; + set.common.dilation = 8; + set.high_poly.ignore_backface = !source.high_poly.ignore_backface; + + let note = differing_values(&set, &source, BakeSyncGroup::Common); + + assert_eq!(note.as_deref(), Some("1024 · Subsampling 4x4 · 2 more")); + } + + #[test] + fn a_set_matching_the_group_shows_nothing_and_other_groups_are_not_compared() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.is_enabled = false; + set.maps.ao.parameters.rays.rays = 16; + + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Common), None); + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Map(BakedMap::AmbientOcclusion)).as_deref(), Some("1 differing setting")); + } +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_purpose.rs b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs new file mode 100644 index 00000000..f2b21b50 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs @@ -0,0 +1,10 @@ +use texturecraft_engine::core::{BakeSyncGroup, BakedMap}; + +/// What a texture set picker does with the sets chosen in it +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SetPickerPurpose { + /// Exactly the chosen sets share the group's settings + Sync(BakeSyncGroup), + /// Copy from the active set to the chosen ones: `what` as the `bake.copy` command takes it, for one map or for all + Copy { what: &'static str, map: Option }, +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_row.rs b/crates/ui-egui/src/bake_mode/set_picker_row.rs new file mode 100644 index 00000000..e7f18f6c --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_row.rs @@ -0,0 +1,7 @@ +/// One texture set listed in the set picker +pub(super) struct SetPickerRow { + pub(super) index: usize, + pub(super) name: String, + /// For a set not yet sharing a sync group, the values it would give up + pub(super) note: Option, +} diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index 766a43c2..751aed00 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -52,7 +52,7 @@ impl BakeSceneLink { let Some(visualization) = visualization else { return }; if visualization.high_poly.shown { - let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let high = session.doc.bake_meshes.merged_high().map(|high| high.mesh.clone()); let handle = SharedHandle::of(high.as_ref()); if handle != self.high { self.high = handle; diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs index 44e17eca..126c7f06 100644 --- a/crates/ui-egui/src/bake_scene/cage_shell_key.rs +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -2,12 +2,12 @@ use std::collections::BTreeMap; use texturecraft_engine::Session; use texturecraft_engine::bake::BakePaintMap; -use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::core::{BakePaintTarget, CageType, HighPolySettings, SkewSettings}; use texturecraft_engine::geom::Mesh; use super::shared_handle::SharedHandle; -/// Everything a texture set's cage shell is built from except the distances, which only move its corners +/// Everything a texture set's cage shell and ray reach are built from except the distances, which only move its corners #[derive(Clone, Debug, PartialEq)] pub(super) struct CageShellKey { mesh_id: u64, @@ -19,7 +19,8 @@ pub(super) struct CageShellKey { cage_kind: CageType, relative_to_bounding_box: bool, average_normals: bool, - use_low_as_high: bool, + /// Whether the set has a cage at all, the name matching the automatic cage fits by and the backfaces the reach leaves out + high_poly: HighPolySettings, skew: SkewSettings, /// The painted skew and cage maps paint: [SharedHandle; 2], @@ -31,17 +32,37 @@ impl CageShellKey { let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); Some(CageShellKey { mesh_id: session.mesh_id, - high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), - cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + high: SharedHandle::of(session.doc.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.doc.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), material: set.material, uv_tiles: set.uv_tiles.clone(), tile_resolutions: set.tile_resolutions.clone(), cage_kind: set.bake.cage.kind, relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, average_normals: set.bake.cage.average_normals, - use_low_as_high: set.bake.high_poly.use_low_as_high, + high_poly: set.bake.high_poly.clone(), skew: set.bake.skew, paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], }) } } + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + use texturecraft_engine::geom::primitives; + + #[test] + fn the_key_changes_with_the_name_matching_the_automatic_cage_is_fitted_by() { + let mut session = Session::new_project("Cage", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + let before = CageShellKey::of(&session, 0); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let by_name = CageShellKey::of(&session, 0); + session.doc.project.texture_sets[0].bake.high_poly.high_suffix = "_hp".into(); + + assert_ne!(before, by_name); + assert_ne!(by_name, CageShellKey::of(&session, 0)); + } +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index f94ed3d5..3996a25b 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -2,7 +2,6 @@ use std::sync::mpsc::{Receiver, TryRecvError}; use texturecraft_engine::Session; use texturecraft_engine::bake::{HighPolyReach, high_poly_missed}; -use texturecraft_engine::core::HighPolySettings; use super::cage_shell_key::CageShellKey; use crate::gpu::SceneSync; @@ -13,8 +12,8 @@ type ShownDistances = (Vec<(f32, f32)>, Option); /// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show #[derive(Default)] pub(super) struct ReachLink { - /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for - keys: Vec>, + /// Each set's ray inputs, and the id of the high poly, the reach was started for + keys: Vec>, high_id: u64, job: Option>>>, reach: Vec>, @@ -56,14 +55,7 @@ impl ReachLink { } let set_count = session.doc.project.texture_sets.len(); - let keys: Vec> = session - .doc - .project - .texture_sets - .iter() - .enumerate() - .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) - .collect(); + let keys: Vec> = (0..set_count).map(|texture_set| CageShellKey::of(session, texture_set)).collect(); if keys != self.keys || high_id != self.high_id { // The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild @@ -87,7 +79,7 @@ impl ReachLink { return; } - let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + let Some(vertex_count) = session.doc.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count))); self.shown = Some(shown); @@ -164,7 +156,7 @@ mod tests { link.sync(&session, 2, None, &mut out); let (high_id, missed) = out.bake_high_missed.unwrap(); assert_eq!(high_id, 2); - assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]); + assert_eq!(missed, vec![0.0; session.doc.bake_meshes.merged_high().unwrap().mesh.positions.len()]); assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly"); } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 761928ec..c900230b 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -262,8 +262,8 @@ pub(crate) const TAB_HEIGHT: f32 = 30.0; /// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font const BAKERS_COLUMN_WIDTH: f32 = 232.0; -/// Width of the bake layout's common and mesh map settings column, in points -const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Width of the bake layout's common and mesh map settings column, in points: both tab names fit beside the × +const SETTINGS_COLUMN_WIDTH: f32 = 380.0; /// Height of the log under the bake layout's columns, in points const BAKING_LOG_HEIGHT: f32 = 160.0; /// Share of the first bake column the texture set list takes above the mesh map bakers diff --git a/crates/ui-egui/src/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs new file mode 100644 index 00000000..37ac21df --- /dev/null +++ b/crates/ui-egui/src/high_poly_job.rs @@ -0,0 +1,79 @@ +use std::collections::VecDeque; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use texturecraft_engine::{EngineError, HighPolyLoad, Result}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; + +/// How often the app looks for the worker's answer while a file loads +const POLL_INTERVAL: Duration = Duration::from_millis(30); + +/// High poly files loading on a worker thread, one after the other, so a large mesh does not freeze the app +pub struct HighPolyJob { + /// The file being loaded + pub current: String, + /// The worker's answer for `current` + answer: Receiver>, + /// The files still to load, in order + pub queue: VecDeque, + /// The project the files are for: they are dropped once another project is open + project: u64, +} + +impl HighPolyJob { + /// The names of the files being loaded and waiting, without their folders + pub fn file_names(&self) -> impl Iterator { + std::iter::once(&self.current).chain(&self.queue).map(|path| std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path)) + } +} + +impl TextureCraftApp { + /// Add the mesh files at `paths` as high polys, read and parsed on a worker thread + #[cfg(not(target_arch = "wasm32"))] + pub fn load_high_polys(&mut self, paths: impl IntoIterator) { + let mut paths: VecDeque = paths.into_iter().collect(); + match &mut self.high_poly_job { + Some(job) if job.project == self.session.project_id => job.queue.append(&mut paths), + _ => self.load_next_high_poly(paths), + } + } + + /// Start loading the first of `queue`, on top of the high polys the session has now + #[cfg(not(target_arch = "wasm32"))] + fn load_next_high_poly(&mut self, mut queue: VecDeque) { + self.high_poly_job = queue.pop_front().map(|current| { + let (meshes, path) = (self.session.doc.bake_meshes.clone(), current.clone()); + let answer = crate::spawn_worker("texturecraft-high-poly", move || HighPolyLoad::read(&meshes, &path)); + HighPolyJob { current, answer, queue, project: self.session.project_id } + }); + } + + /// Add a loaded high poly to the session and start on the next file; drop them all once another project is open + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { + let Some(job) = &self.high_poly_job else { return }; + if job.project != self.session.project_id { + self.high_poly_job = None; + self.toast(tr("The project changed while the high polys loaded, so they were not added"), true); + return; + } + + context.request_repaint_after(POLL_INTERVAL); + let loaded = match job.answer.try_recv() { + Ok(loaded) => loaded, + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => Err(EngineError::Other(tr("The mesh loading worker stopped").into())), + }; + let Some(job) = self.high_poly_job.take() else { return }; + + match loaded { + Ok(load) => { + self.session.apply_high_poly_load(load); + } + Err(error) => self.toast(trf("Couldn't import {name}: {error}", &[("name", &job.current), ("error", &error.to_string())]), true), + } + self.load_next_high_poly(job.queue); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47259f2b..a24b9d6d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -48,6 +48,7 @@ mod generator_panel; pub mod gpu; mod gray_slider; mod grid_tile; +mod high_poly_job; mod histogram_cache; pub mod i18n; pub mod id_color_pick; @@ -182,6 +183,7 @@ use texturecraft_engine::bake::Progress; pub use bake_job::BakeJob; pub use control::ControlRequest; +pub use high_poly_job::HighPolyJob; pub use running_bake::RunningBake; pub use state::UiState; @@ -264,12 +266,16 @@ pub struct TextureCraftApp { /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, + /// High poly files being loaded for the bake + pub high_poly_job: Option, pub link_cooks: Vec, #[cfg(not(target_arch = "wasm32"))] link_imports: Vec, pub thumbs: thumbs::Thumbs, /// The Layers panel's thumbnails and folded groups. pub layer_panel: layer_panel::LayerPanel, + /// The Mesh Map Bakers rows' thumbnails + pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -405,11 +411,13 @@ impl TextureCraftApp { bake_report: Default::default(), pbr_import: None, resize: None, + high_poly_job: None, link_cooks: Vec::new(), #[cfg(not(target_arch = "wasm32"))] link_imports: Vec::new(), thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), + bake_map_thumbnails: bake_mode::MapThumbnails::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -599,9 +607,13 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); } - /// Start baking texture sets in the background, one after another. Invalid set indices - /// show an error without starting a preview or queuing any work. + /// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything pub fn start_bake(&mut self, sets: Vec) { + self.start_bake_of(sets, None); + } + + /// Bake `sets`: only map `only` when given, else each set's checked maps + pub fn start_bake_of(&mut self, sets: Vec, only: Option) { if self.bake.is_some() || sets.is_empty() { return; } @@ -609,14 +621,19 @@ impl TextureCraftApp { // Restore the picker's view before the preview starts following baked maps id_color_pick::IdColorPick::end(self); - if let Err(error) = self.session.bake_preview_begin_for(&sets) { - self.toast(error.to_string(), true); - return; + match only { + Some(map) => self.session.bake_preview_begin(sets.iter().map(|set| (*set, vec![map])).collect()), + None => { + if let Err(error) = self.session.bake_preview_begin_for(&sets) { + self.toast(error.to_string(), true); + return; + } + } } let total = sets.len(); self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -713,8 +730,7 @@ impl TextureCraftApp { } } - /// Show at most one streamed map per frame, then apply the set as one undo step after - /// its map channel closes. Closing the preview alone does not stop the background bake. + /// Show at most one streamed map per frame, then apply the set as one undo step once its map channel closes; closing the preview alone does not stop the bake fn poll_bake(&mut self, ctx: &egui::Context) { // Leaving Bake mode puts the view mode back; the bake goes on if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { @@ -736,7 +752,7 @@ impl TextureCraftApp { return; } - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + ctx.request_repaint_after(BAKE_POLL_INTERVAL); if let Some(running) = &job.current { let set_index = running.set_index; @@ -787,9 +803,15 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); + let only = job.only; + self.session.bake_preview_set_current(set_index); match self.session.bake_task(set_index) { - Ok(task) => { + Ok(mut task) => { + if let Some(map) = only { + task.settings.maps.select([map]); + } + let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); @@ -1015,6 +1037,9 @@ struct CameraGlide { const GLIDE_SECONDS: f64 = 0.35; +/// How often a running bake is checked for finished maps: often enough that each shows within a few frames +const BAKE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50); + /// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) const FRAME_AVERAGE_KEEP: f32 = 0.9; /// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason @@ -1107,6 +1132,8 @@ impl eframe::App for TextureCraftApp { } self.poll_bake(ctx); self.poll_resize(ctx); + #[cfg(not(target_arch = "wasm32"))] + self.poll_high_poly_job(ctx); self.poll_link_cooks(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_link_imports(ctx); diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 5917a337..122857cb 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -159,7 +159,8 @@ impl PropertySheet<'_> { pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { let id = self.next_id(); let response = self.ui.interact(rect, id, Sense::click()); - response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, enabled, value)); let tokens = self.tokens; let painter = self.ui.painter(); painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs new file mode 100644 index 00000000..69a34386 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -0,0 +1,152 @@ +//! A list of loaded files under its label, one row per file, with its add button beside it + +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::FileListAdd; +use super::stacked_rows::{LABEL_LINE, STACK_ROW_AIR}; +use super::{CONTROL_RADIUS, FileListResponse, FileRow, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// One file's row, and the list's inner margin above and below its rows +const FILE_ROW_HEIGHT: f32 = 40.0; +const LIST_MARGIN: f32 = 2.0; + +/// The add button's square and the room it takes beside the list +const ADD_BUTTON_SIZE: f32 = 28.0; +const ADD_BUTTON_ROOM: f32 = 34.0; + +/// Where a row's cube sits, where its words start, and its × from the list's right edge +const CUBE_CENTER: f32 = 16.0; +const CUBE_SIZE: f32 = 14.0; +const NAME_LEFT: f32 = 32.0; +const REMOVE_INSET: f32 = 14.0; +const REMOVE_SIZE: f32 = 12.0; +const REMOVE_BOX: f32 = 18.0; + +/// The name's and the folder's centres from the row's top, when the row shows both +const NAME_CENTER: f32 = 13.0; +const FOLDER_CENTER: f32 = 28.0; + +/// The hairline between rows stops this far from the list's sides +const DIVIDER_INSET: f32 = 8.0; + +/// Size of the add button's glyph +const ADD_GLYPH_SIZE: f32 = 14.0; + +/// What stands for the folders left out of a shortened path +const ELLIPSIS: &str = "…"; + +impl PropertySheet<'_> { + /// `rows` in a box at least `min_rows` tall, with the `add` button beside it; each loaded file's × (`remove_label`) asks to remove it + pub(crate) fn file_list(&mut self, label: &str, rows: &[FileRow<'_>], min_rows: usize, add: FileListAdd<'_>, remove_label: &str) -> FileListResponse { + let line = self.take(LABEL_LINE); + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, line.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text); + + let height = rows.len().max(min_rows) as f32 * FILE_ROW_HEIGHT + 2.0 * LIST_MARGIN; + let area = self.take(height); + let list = Rect::from_min_max(pos2(self.left, area.top()), pos2(self.right - ADD_BUTTON_ROOM, area.bottom())); + let list_id = self.next_id(); + let list_response = self.ui.interact(list, list_id, Sense::hover()); + let enabled = self.ui.is_enabled(); + list_response.widget_info(|| WidgetInfo::labeled(egui::Role::List, enabled, label)); + self.ui.painter().rect(list, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + let mut answer = FileListResponse::default(); + for (index, row) in rows.iter().enumerate() { + let top = list.top() + LIST_MARGIN + index as f32 * FILE_ROW_HEIGHT; + let rect = Rect::from_min_max(pos2(list.left(), top), pos2(list.right(), top + FILE_ROW_HEIGHT)); + if index > 0 { + let divider = [pos2(list.left() + DIVIDER_INSET, top), pos2(list.right() - DIVIDER_INSET, top)]; + self.ui.painter().line_segment(divider, Stroke::new(1.0, tokens.separator)); + } + if self.file_row(rect, row, remove_label) { + answer.removed = Some(index); + } + } + + let add_rect = Rect::from_min_size(pos2(self.right - ADD_BUTTON_SIZE, area.top()), vec2(ADD_BUTTON_SIZE, ADD_BUTTON_SIZE)); + let add_id = self.next_id(); + let can_add = add.enabled && enabled; + let add_response = self.ui.interact(add_rect, add_id, if can_add { Sense::click() } else { Sense::hover() }); + add_response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, can_add, add.label)); + let add_response = self.tip(add_response, add.label); + let fill = if can_add && add_response.hovered() { tokens.row_hover } else { tokens.button }; + let glyph_color = if can_add { tokens.text } else { tokens.text_dim }; + let painter = self.ui.painter(); + painter.rect(add_rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + painter.text(add_rect.center(), Align2::CENTER_CENTER, add.glyph, FontId::proportional(ADD_GLYPH_SIZE), glyph_color); + self.paint_control_focus(&add_response); + answer.add = can_add && add_response.clicked(); + + self.drawn(area.bottom()); + self.space(2.0 * STACK_ROW_AIR); + answer + } + + /// One file's row in `rect`; returns whether its × was clicked + fn file_row(&mut self, rect: Rect, row: &FileRow<'_>, remove_label: &str) -> bool { + let tokens = self.tokens; + let words_right = rect.right() - REMOVE_INSET - REMOVE_BOX / 2.0; + let name_color = if row.loading { tokens.text_dim } else { tokens.text }; + let name_font = if row.loading { FontId::proportional(TEXT_SIZE) } else { semibold(TEXT_SIZE) }; + let name_y = if row.folder.is_some() { rect.top() + NAME_CENTER } else { rect.center().y }; + let painter = self.ui.painter().clone(); + painter.text(pos2(rect.left() + CUBE_CENTER, rect.center().y), Align2::CENTER_CENTER, ic::CUBE, FontId::proportional(CUBE_SIZE), tokens.text_dim); + let mut job = egui::text::LayoutJob::simple_singleline(row.name.to_owned(), name_font, name_color); + job.wrap = egui::text::TextWrapping::truncate_at_width((words_right - rect.left() - NAME_LEFT).max(0.0)); + let name = painter.layout_job(job); + painter.galley(pos2(rect.left() + NAME_LEFT, name_y - name.size().y / 2.0), name, name_color); + if let Some(folder) = row.folder { + let shown = shortened_folder(&painter, folder, words_right - rect.left() - NAME_LEFT); + painter.text( + pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER), + Align2::LEFT_CENTER, + shown, + FontId::proportional(SMALL_TEXT_SIZE), + tokens.text_dim, + ); + } + + let words = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(words_right, rect.bottom())); + let words_id = self.next_id(); + let words_response = self.ui.interact(words, words_id, Sense::hover()); + let enabled = self.ui.is_enabled() && !row.loading; + words_response.widget_info(|| WidgetInfo::labeled(egui::Role::ListItem, enabled, row.name)); + let full = match row.folder { + Some(folder) => format!("{}\n{folder}", row.name), + None => row.name.to_owned(), + }; + self.tip(words_response, &full); + if row.loading { + return false; + } + + let remove = Rect::from_center_size(pos2(rect.right() - REMOVE_INSET, rect.center().y), vec2(REMOVE_BOX, REMOVE_BOX)); + let id = self.next_id(); + let response = self.ui.interact(remove, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, self.ui.is_enabled(), remove_label)); + let response = self.tip(response, remove_label); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(remove.center(), Align2::CENTER_CENTER, ic::X, FontId::proportional(REMOVE_SIZE), color); + self.paint_control_focus(&response); + response.clicked() + } +} + +/// `folder` with folders after its first one left out, from the second on, until it fits in `room` +fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String { + let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), egui::Color32::WHITE).size().x <= room; + let mut parts: Vec<&str> = folder.split(['/', '\\']).collect(); + let mut shown = parts.join("/"); + while !fits(&shown) && parts.len() > 2 { + if parts[1] == ELLIPSIS { + parts.remove(2); + } else { + parts[1] = ELLIPSIS; + } + shown = parts.join("/"); + } + shown +} diff --git a/crates/ui-egui/src/property_sheet/file_list_add.rs b/crates/ui-egui/src/property_sheet/file_list_add.rs new file mode 100644 index 00000000..f790083e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_add.rs @@ -0,0 +1,6 @@ +/// A file list's add button: its glyph, its label (also its tooltip) and whether it can add now +pub(crate) struct FileListAdd<'a> { + pub(crate) glyph: &'a str, + pub(crate) label: &'a str, + pub(crate) enabled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/file_list_response.rs b/crates/ui-egui/src/property_sheet/file_list_response.rs new file mode 100644 index 00000000..e0b24c24 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_response.rs @@ -0,0 +1,6 @@ +/// What a file list answered: its add button clicked, or a file's × clicked +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct FileListResponse { + pub(crate) add: bool, + pub(crate) removed: Option, +} diff --git a/crates/ui-egui/src/property_sheet/file_row.rs b/crates/ui-egui/src/property_sheet/file_row.rs new file mode 100644 index 00000000..1d7bf0c0 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_row.rs @@ -0,0 +1,7 @@ +/// One file of a file list: its name, the folder it was read from when known, and whether it is still loading +#[derive(Clone, Copy)] +pub(crate) struct FileRow<'a> { + pub(crate) name: &'a str, + pub(crate) folder: Option<&'a str>, + pub(crate) loading: bool, +} diff --git a/crates/ui-egui/src/property_sheet/fold_section.rs b/crates/ui-egui/src/property_sheet/fold_section.rs new file mode 100644 index 00000000..7f8e1d3d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/fold_section.rs @@ -0,0 +1,7 @@ +use egui::Response; + +/// What a folding section's caption answered: whether its rows show, and its reset glyph +pub(crate) struct FoldSection { + pub(crate) open: bool, + pub(crate) reset: Response, +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 62c81046..852d4673 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -13,6 +13,11 @@ mod compare_row; mod compare_row_response; mod eye_toggle; mod factor_slider; +mod file_list; +mod file_list_add; +mod file_list_response; +mod file_row; +mod fold_section; mod gradient_rows; mod group; mod hold_pad; @@ -42,6 +47,7 @@ mod slot; mod slot_response; mod source_card; mod stack_slider; +mod stacked_rows; mod switch_control; mod tooltip; mod track; @@ -55,6 +61,10 @@ pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; pub(crate) use compare_row_response::CompareRowResponse; +pub(crate) use file_list_add::FileListAdd; +pub(crate) use file_list_response::FileListResponse; +pub(crate) use file_row::FileRow; +pub(crate) use fold_section::FoldSection; pub(crate) use id_color_row_response::IdColorRowResponse; pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; @@ -68,6 +78,7 @@ pub(crate) use section_tabs::{ pub(crate) use sheet::PropertySheet; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; +pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; /// Side padding: every row starts and ends this far inside the panel pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index 6d26f207..e1e5b1b6 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -27,6 +27,8 @@ pub(crate) struct PropertySheet<'u> { pub(super) sections: Vec<(String, f32)>, pub(super) info: Option<&'u str>, pub(super) held: bool, + /// Sub-headers so far in the current folding section: a later one takes air above it + pub(super) sub_headers: usize, } impl<'u> PropertySheet<'u> { @@ -53,6 +55,7 @@ impl<'u> PropertySheet<'u> { sections: Vec::new(), info: None, held: false, + sub_headers: 0, ui, }; let result = body(&mut sheet); diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 98ef953d..9770d2c5 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -195,7 +195,8 @@ impl PropertySheet<'_> { pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), ); let response = self.ui.interact(hit, id, Sense::click_and_drag()); - response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::slider(enabled, f64::from(*value), &label)); let mut moved = false; if (response.dragged() || response.drag_stopped() || response.clicked()) @@ -294,7 +295,8 @@ impl PropertySheet<'_> { let Some(mut draft) = editing else { self.skip_typing_edit(); let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); - response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, crate::i18n::trf("{label} value", &[("label", label)]))); self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); if response.hovered() { diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs new file mode 100644 index 00000000..88aad56b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -0,0 +1,471 @@ +//! Rows with their label above a full-width control, as the bake panels lay them out: folding sections, bold sub-headers, checks, and controls that grey out with a reason + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Sense, Stroke, StrokeKind, UiBuilder, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::number_field::shown_number; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use super::value_text::ValueText; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, FoldSection, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Height of a label's line above its control, and its text's centre in it +pub(super) const LABEL_LINE: f32 = 18.0; +const LABEL_CENTER: f32 = 9.0; + +/// Air under a control before the next setting; full-width buttons and lists take it above and twice below, so two filled boxes never touch +pub(super) const STACK_ROW_AIR: f32 = 6.0; + +/// A slider's track line under its label, and its centre in it +const TRACK_LINE: f32 = 16.0; +const TRACK_CENTER: f32 = 8.0; + +/// A check's line, its box and the air from the box to its label +const CHECK_LINE: f32 = 20.0; +pub(crate) const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; +const CHECK_TO_LABEL: f32 = 9.0; + +/// The tick's three points across a check's box, as fractions of its side (from the reference's tick) +const TICK_POINTS: [(f32, f32); 3] = [(0.25, 0.52), (0.43, 0.7), (0.75, 0.3)]; +const TICK_WIDTH: f32 = 1.7; + +/// Half the length of a mixed check's dash, and its thickness +const DASH_HALF: f32 = 3.0; +const DASH_WIDTH: f32 = 2.0; + +/// Air above a later section's hairline and from it to the caption +const FOLD_AIR_ABOVE: f32 = 8.0; +const FOLD_RULE_TO_CAPTION: f32 = 10.0; + +/// Air above the first section's caption +const FOLD_FIRST_AIR: f32 = 10.0; + +/// A section caption's line, the air under it, and where its chevron and caption sit +const FOLD_CAPTION_LINE: f32 = 20.0; +const FOLD_CAPTION_AIR: f32 = 10.0; +const FOLD_CHEVRON_CENTER: f32 = 5.0; +const FOLD_CAPTION_LEFT: f32 = 18.0; + +/// The reset glyph's size and its centre's distance from the right edge +const FOLD_RESET_SIZE: f32 = 14.0; +const FOLD_RESET_INSET: f32 = 6.0; +const FOLD_RESET_BOX: f32 = 20.0; + +/// Air above a later sub-header, its line, and the air under it +const SUB_HEADER_AIR: f32 = 6.0; +const SUB_HEADER_LINE: f32 = 18.0; +const SUB_HEADER_GAP: f32 = 4.0; + +/// How far a sub-header's rows, and settings that belong to the one above, sit in from the left +const STACK_INDENT: f32 = 12.0; + +/// Opacity of a greyed setting, on top of egui's disabled fade: 0.4 in all, the locked bake mock's 60 % blend toward the panel +const GREYED_EXTRA_OPACITY: f32 = 0.8; + +/// A full-width button's glyph size and the air between it and its words +const WIDE_BUTTON_ICON_SIZE: f32 = 13.0; +const WIDE_BUTTON_ICON_GAP: f32 = 8.0; + +/// Width of the link between two paired dropdowns, and the air on its sides +const PAIR_LINK_WIDTH: f32 = 26.0; +const PAIR_LINK_AIR: f32 = 4.0; + +/// Values with more places than this drop their trailing zeros +const SHORT_DECIMALS: usize = 2; + +/// Air before a field's text +const FIELD_TEXT_INSET: i8 = 8; + +impl PropertySheet<'_> { + /// A section that folds: chevron and CAPS caption left, its reset glyph right, a hairline above a later one; the click on the caption line folds it + pub(crate) fn fold_section(&mut self, title: &str, default_open: bool) -> FoldSection { + self.close_card(); + if self.empty { + self.space(FOLD_FIRST_AIR); + } else { + self.space(FOLD_AIR_ABOVE); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(FOLD_RULE_TO_CAPTION); + } + + let section = self.id.with(("fold_section", title)); + self.scope = section; + self.band_scope = section; + let line = self.take(FOLD_CAPTION_LINE); + let center_y = line.center().y; + let reset_rect = Rect::from_center_size(pos2(self.right - FOLD_RESET_INSET, center_y), vec2(FOLD_RESET_BOX, FOLD_RESET_BOX)); + let header = Rect::from_min_max(pos2(self.left, line.top()), pos2(reset_rect.left(), line.bottom())); + + let mut open = self.ui.data(|data| data.get_temp::(section)).unwrap_or(default_open); + let fold = self.ui.interact(header, section.with("fold"), Sense::click()); + if fold.clicked() { + open = !open; + self.ui.data_mut(|data| data.insert_temp(section, open)); + } + let enabled = self.ui.is_enabled(); + fold.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, open, title)); + + // Added after the caption's response, so the glyph takes the clicks over it + let reset = self.ui.interact(reset_rect, section.with("reset"), Sense::click()); + let reset_label = crate::i18n::trf("Reset {section}", &[("section", &title)]); + reset.widget_info(|| WidgetInfo::labeled(egui::Role::Button, enabled, &reset_label)); + let reset = self.tip(reset, &reset_label); + + let tokens = self.tokens; + let painter = self.ui.painter(); + let chevron = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(self.left + FOLD_CHEVRON_CENTER, center_y), Align2::CENTER_CENTER, chevron, FontId::proportional(ICON_SIZE), tokens.text); + painter.text(pos2(self.left + FOLD_CAPTION_LEFT, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text); + let reset_color = if reset.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(FOLD_RESET_SIZE), reset_color); + self.paint_control_focus(&fold); + self.paint_control_focus(&reset); + self.drawn(line.bottom()); + if open { + self.space(FOLD_CAPTION_AIR); + } + self.sub_headers = 0; + FoldSection { open, reset } + } + + /// A bold sub-header; its rows follow one [`STACK_INDENT`] in, inside `body` + pub(crate) fn sub_header(&mut self, title: &str, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + if self.sub_headers > 0 { + self.space(SUB_HEADER_AIR); + } + self.sub_headers += 1; + let line = self.take(SUB_HEADER_LINE); + let text = self.tokens.text_strong; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), text); + self.drawn(line.bottom()); + self.space(SUB_HEADER_GAP); + self.indented(body) + } + + /// `body`'s rows one [`STACK_INDENT`] in from the left + pub(crate) fn indented(&mut self, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let left = self.left; + self.left += STACK_INDENT; + let result = body(self); + self.left = left; + result + } + + /// `body`'s rows, greyed and inert unless `enabled`; hovering them shows `reason` (which also names them for assistive tech). Inside a greyed part they grey no further + pub(crate) fn greyed(&mut self, enabled: bool, reason: Option<&str>, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let already_greyed = !self.ui.is_enabled(); + let top = self.cursor_y(); + let builder = UiBuilder::new().max_rect(self.ui.available_rect_before_wrap()).layout(*self.ui.layout()); + let mut child = self.ui.new_child(builder); + if !enabled && !already_greyed { + child.disable(); + child.multiply_opacity(GREYED_EXTRA_OPACITY); + } + + let mut sheet = PropertySheet { + tokens: self.tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: std::mem::take(&mut self.named), + left: self.left, + right: self.right, + used: self.used, + seen: self.seen, + card: self.card.take(), + air_at: self.air_at, + drawn_bottom: self.drawn_bottom, + empty: self.empty, + sections: std::mem::take(&mut self.sections), + info: None, + held: self.held, + sub_headers: self.sub_headers, + ui: &mut child, + }; + let result = body(&mut sheet); + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = + (named, seen, card, air_at, drawn_bottom, empty, sections); + (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + + let bottom = child.min_rect().bottom().max(top); + let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); + self.ui.advance_cursor_after_rect(Rect::from_min_max(pos2(child.min_rect().left(), top), pos2(child.min_rect().right(), bottom))); + if let (false, false, Some(reason)) = (enabled, already_greyed, reason) { + let response = self.ui.interact(region, self.id.with(("greyed", top as i32)), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, reason)); + + // At the pointer: the region is tall, so a tip at its edge would land far from what was hovered + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(egui::PopupAnchor::Pointer); + tooltip.show(|ui| ui.label(reason)); + } + result + } + + /// A label on its own line above its control + fn label_line(&mut self, label: &str) -> Rect { + let line = self.take(LABEL_LINE); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + line + } + + /// A full-width control's box under its label, and the air after it + fn control_line(&mut self) -> Rect { + let line = self.take(CONTROL_HEIGHT); + self.drawn(line.bottom()); + let rect = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + self.space(STACK_ROW_AIR); + rect + } + + /// A dropdown under its label; returns the picked option + pub(crate) fn dropdown_above(&mut self, label: &str, current: T, options: &[T], name: impl Fn(T) -> String) -> Option { + self.label_line(label); + let button = self.control_line(); + let response = self.dropdown_button(button, &name(current), None::); + named_choice(self.ui, &response, label, &name(current)); + self.hanging_list(&response, current, options, &name, None::>).0 + } + + /// Two dropdowns under one label with a link between them; while `linked` the second follows the first and shows greyed. Returns which one picked what + pub(crate) fn dropdown_pair_above( + &mut self, + label: &str, + values: [T; 2], + options: &[T], + name: impl Fn(T) -> String, + linked: &mut bool, + link_label: &str, + ) -> Option<(usize, T)> { + self.label_line(label); + let line = self.control_line(); + let half = (line.width() - PAIR_LINK_WIDTH - 2.0 * PAIR_LINK_AIR) / 2.0; + let first = Rect::from_min_size(line.min, vec2(half, CONTROL_HEIGHT)); + let link = Rect::from_min_size(pos2(first.right() + PAIR_LINK_AIR, line.top()), vec2(PAIR_LINK_WIDTH, CONTROL_HEIGHT)); + let second = Rect::from_min_max(pos2(link.right() + PAIR_LINK_AIR, line.top()), line.max); + + let first_response = self.dropdown_button(first, &name(values[0]), None::); + named_choice(self.ui, &first_response, label, &name(values[0])); + let mut picked = self.hanging_list(&first_response, values[0], options, &name, None::>).0.map(|value| (0, value)); + + let link_id = self.next_id(); + let link_response = self.ui.interact(link, link_id, Sense::click()); + let enabled = self.ui.is_enabled(); + link_response.widget_info(|| WidgetInfo::selected(egui::Role::CheckBox, enabled, *linked, link_label)); + let link_response = self.tip(link_response, link_label); + if link_response.clicked() { + *linked = !*linked; + } + let tokens = self.tokens; + + // Held down: the hairline grey, neutral in every accent (tool_active takes the accent's tint) + let fill = if *linked { + tokens.separator + } else if link_response.hovered() { + tokens.row_hover + } else { + tokens.button + }; + let painter = self.ui.painter(); + painter.rect(link, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(link.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&link_response); + + let follows = *linked; + let second_value = if follows { values[0] } else { values[1] }; + let mut second_ui = self.ui.new_child(UiBuilder::new().max_rect(second)); + if follows { + second_ui.disable(); + } + let mut second_sheet = PropertySheet { + tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: Vec::new(), + left: second.left(), + right: second.right(), + used: self.used, + seen: self.seen, + card: None, + air_at: None, + drawn_bottom: self.drawn_bottom, + empty: false, + sections: Vec::new(), + info: None, + held: false, + sub_headers: 0, + ui: &mut second_ui, + }; + let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); + named_choice(second_sheet.ui, &second_response, label, &name(second_value)); + if let Some(value) = second_sheet.hanging_list(&second_response, second_value, options, &name, None::>).0 { + picked = Some((1, value)); + } + picked + } + + /// A slider under its label, its value at the label line's right end; `Some(merge)` when `value` changed, `merge` true for a drag's later steps + pub(crate) fn slider_above(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + let line = self.label_line(label); + let id = self.named_id("slider_above", label); + let shown = shown_number(*value, decimals); + + // Fine-grained values read as the reference's do, without trailing zeros ("0.01", "1"); short ones keep their places ("0.50") + let shown = if decimals > SHORT_DECIMALS && shown.contains('.') { shown.trim_end_matches('0').trim_end_matches('.').to_owned() } else { shown }; + let width = self.text_width(&shown, semibold(TEXT_SIZE)).max(super::VALUE_MIN_WIDTH); + let value_text = ValueText { label: &label, right: self.right, width, center_y: line.top() + LABEL_CENTER, shown: &shown, suffix: "" }; + let typed = self.value_text_field(id, value_text, *value, &range, decimals); + + let track_line = self.take(TRACK_LINE); + let center_y = track_line.top() + TRACK_CENTER; + let track = Track { start: self.left + KNOB_RADIUS, end: self.right - KNOB_RADIUS, center_y, zero: (*range.start() < 0.0).then_some(0.0), ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + self.drawn(center_y + KNOB_RADIUS); + self.space(STACK_ROW_AIR); + Self::apply_typed(value, typed, dragged) + } + + /// A check with its label after it; returns whether it was clicked (`on` already flipped) + pub(crate) fn check(&mut self, label: &str, on: &mut bool) -> bool { + let clicked = self.check_mixed(label, Some(*on)).clicked(); + if clicked { + *on = !*on; + } + clicked + } + + /// A check that may show mixed (`None`, a dash) for several states at once; the caller flips what it stands for on a click + pub(crate) fn check_mixed(&mut self, label: &str, state: Option) -> Response { + self.check_noted(label, state, None) + } + + /// `check_mixed` with a dim `note` at the row's right end, such as the values a set would give up + pub(crate) fn check_noted(&mut self, label: &str, state: Option, note: Option<&str>) -> Response { + let line = self.take(CHECK_LINE); + let center_y = line.center().y; + let text = self.ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), self.tokens.text); + let hit = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.left + CHECK_SIZE + CHECK_TO_LABEL + text.size().x, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| match state { + Some(on) => WidgetInfo::selected(egui::Role::CheckBox, enabled, on, label), + None => WidgetInfo::labeled(egui::Role::CheckBox, enabled, label), + }); + + let check = Rect::from_min_size(pos2(self.left, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + paint_check(self.ui.painter(), &self.tokens, check, state, response.hovered()); + self.ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, self.tokens.text); + if let Some(note) = note { + self.ui.painter().text(pos2(self.right, center_y), Align2::RIGHT_CENTER, note, FontId::proportional(SMALL_TEXT_SIZE), self.tokens.text_dim); + } + self.paint_control_focus(&response); + self.drawn(line.bottom()); + self.space(STACK_ROW_AIR); + response + } + + /// A one-line text field under its label; returns whether `text` changed + pub(crate) fn text_field_above(&mut self, label: &str, text: &mut String) -> bool { + self.label_line(label); + let line = self.take(CONTROL_HEIGHT); + let field = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.named_id("text_field_above", label); + let typing = self.ui.memory(|memory| memory.has_focus(id)); + let tokens = self.tokens; + let outline = Stroke::new(1.0, if typing { tokens.accent } else { tokens.field_border }); + self.ui.painter().rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, outline, StrokeKind::Inside); + let edit = egui::TextEdit::singleline(text) + .id(id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET, 0))) + .align(Align2::LEFT_CENTER); + let response = self.ui.put(field.shrink(1.0), edit); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::TextInput, enabled, label)); + self.drawn(field.bottom()); + self.space(STACK_ROW_AIR); + response.changed() + } + + /// A full-width button with air above and twice below; `pressed` shows it held down (a toggle that is on) + pub(crate) fn wide_button(&mut self, glyph: &str, text: &str, pressed: bool) -> Response { + self.space(STACK_ROW_AIR); + let line = self.take(CONTROL_HEIGHT); + let button = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(button, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, pressed, text)); + + let tokens = self.tokens; + // Held down: the hairline grey, as the paired dropdowns' link + let fill = match (pressed, response.hovered()) { + (true, _) => tokens.separator, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }; + let painter = self.ui.painter(); + painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let icon = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(WIDE_BUTTON_ICON_SIZE), tokens.text); + let words = painter.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); + let x = button.center().x - (icon.size().x + WIDE_BUTTON_ICON_GAP + words.size().x) / 2.0; + let center_y = button.center().y; + painter.galley(pos2(x, center_y - icon.size().y / 2.0), icon.clone(), tokens.text); + painter.galley(pos2(x + icon.size().x + WIDE_BUTTON_ICON_GAP, center_y - words.size().y / 2.0), words, tokens.text); + self.paint_control_focus(&response); + self.drawn(button.bottom()); + self.space(2.0 * STACK_ROW_AIR); + response + } + + /// A dim line of its own, such as a map's "No Parameters" + pub(crate) fn dim_line(&mut self, text: &str) { + let line = self.take(LABEL_LINE); + let dim = self.tokens.text_dim; + let id = self.next_id(); + let response = self.ui.interact(line, id, Sense::hover()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, text)); + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, text, FontId::proportional(TEXT_SIZE), dim); + self.drawn(line.bottom()); + } +} + +/// A check's box in `rect`: on = dim fill and a tick in the panel's colour, mixed (`None`) = a dash, off = the row colour with a field's border +pub(crate) fn paint_check(painter: &egui::Painter, tokens: &crate::theme::Tokens, rect: Rect, state: Option, hovered: bool) { + if state == Some(false) { + let border = if hovered { tokens.button_border } else { tokens.field_border }; + painter.rect(rect, CornerRadius::same(CHECK_RADIUS), tokens.row, Stroke::new(1.0, border), StrokeKind::Inside); + return; + } + + let fill = if hovered { tokens.text } else { tokens.text_dim }; + painter.rect_filled(rect, CornerRadius::same(CHECK_RADIUS), fill); + if state.is_none() { + let y = rect.center().y; + painter.line_segment([pos2(rect.center().x - DASH_HALF, y), pos2(rect.center().x + DASH_HALF, y)], Stroke::new(DASH_WIDTH, tokens.panel)); + return; + } + let points = TICK_POINTS.map(|(x, y)| pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height())); + painter.line(points.to_vec(), Stroke::new(TICK_WIDTH, tokens.panel)); +} + +/// Names a dropdown for assistive tech by its setting (`label`), its value the choice it shows +fn named_choice(ui: &egui::Ui, response: &Response, label: &str, value: &str) { + ui.ctx().accesskit_node_builder(response.id, |node| { + node.set_label(label); + node.set_value(value); + }); +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 26e6d85a..2b8530ec 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -253,7 +253,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3c5a3d7e..c101e8e2 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,7 +65,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on - && !app.session.bake_meshes.high.is_empty() + && !app.session.doc.bake_meshes.high.is_empty() && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { let settings = &texture_set.bake; match app.ui.bake_paint_brush.target { @@ -1117,7 +1117,9 @@ fn bake_visualization(app: &TextureCraftApp) -> Option, Pick)>) } } -/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog. The -/// meshes load on a later frame, when the dialog answers. +/// Bake mode: add high polys (they load on a worker) or load the cage with the native file dialog, once it answers #[cfg(not(target_arch = "wasm32"))] pub fn import_bake_mesh(app: &mut TextureCraftApp, _ctx: &egui::Context, cage: bool) { use crate::file_dialogs::{Bound, FileDialog}; let dialog = if cage { FileDialog::open() } else { FileDialog::open_many() }; app.ask_file(dialog.filter(tr("Meshes"), &MESH_EXTENSIONS), Bound::Project, move |app, paths| { - for p in paths { - let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; - app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); + let mut paths = paths.iter().map(|path| path.display().to_string()); + if !cage { + app.load_high_polys(paths); + } else if let Some(path) = paths.next() { + app.run("bake.cage.set", serde_json::json!({ "path": path })); } }); } @@ -507,8 +508,8 @@ mod tests { vec![("high.obj".into(), cage.clone(), Pick::HighPoly(old_project_id)), ("cage.obj".into(), cage, Pick::Cage(old_project_id))], ); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); assert!(!harness.state().session.modified); assert_eq!(harness.state().toasts.iter().filter(|toast| toast.error).count(), 2); @@ -521,8 +522,8 @@ mod tests { vec![("high.obj".into(), mesh.clone(), Pick::HighPoly(project_id)), ("cage.obj".into(), mesh, Pick::Cage(project_id))], ); - assert_eq!(harness.state().session.bake_meshes.high.len(), 1); - assert!(harness.state().session.bake_meshes.cage.is_some()); + assert_eq!(harness.state().session.doc.bake_meshes.high.len(), 1); + assert!(harness.state().session.doc.bake_meshes.cage.is_some()); } #[test] diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 1703abde..d0b0fcb7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -130,6 +130,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { queue: Vec::new(), total: 1, mesh_id, + only: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), @@ -184,3 +185,22 @@ fn an_invalid_set_does_not_start_a_partial_bake_or_change_the_view() { assert_eq!(app.session.history_labels().len(), history_steps); assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); } + +#[test] +fn a_rows_quick_bake_bakes_that_map_alone_and_keeps_the_others() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + let before = harness.state().session.doc.baked[&0].maps.clone(); + + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([]); + harness.state_mut().start_bake_of(vec![0], Some(MAPS[1])); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[1]), "the preview shows the one map"); + run_to_the_end(&mut harness); + + let after = &harness.state().session.doc.baked[&0].maps; + assert_eq!(after.keys().collect::>(), before.keys().collect::>(), "the other maps stay"); + for map in MAPS { + assert_eq!(!std::sync::Arc::ptr_eq(&after[&map], &before[&map]), map == MAPS[1], "{map:?}"); + } +} diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 60f6f03e..b634a9c5 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -22,7 +22,7 @@ fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, Textu std::mem::forget(maps_tx); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id, only: None }); (h, progress) } diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs new file mode 100644 index 00000000..ce17536c --- /dev/null +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -0,0 +1,70 @@ +//! The Mesh Map Bakers rows: a drag down the checkboxes gives each the state the first one took + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::BakedMap; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// The rows the drag crosses, from the press to the release +const DRAGGED: [(BakedMap, &str); 3] = [(BakedMap::Normal, "Normal"), (BakedMap::WorldNormal, "World Space Normal"), (BakedMap::Id, "ID")]; + +/// A bake-mode app with Mesh Map Bakers in front and every map checked +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select(BakedMap::ALL); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn checkbox_center(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::CheckBox, name).rect().center() +} + +fn enabled(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let maps = &harness.state().session.doc.project.texture_sets[0].bake.maps; + BakedMap::ALL.into_iter().filter(|map| maps.is_enabled(*map)).collect() +} + +#[test] +fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { + let mut harness = harness(); + let [from, through, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for position in [through, to] { + harness.hover_at(position); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "the three rows are unchecked, the release does not check the last one again"); +} + +#[test] +fn a_click_on_one_checkbox_still_toggles_only_that_row() { + let mut harness = harness(); + let (map, name) = DRAGGED[1]; + let at = checkbox_center(&harness, name); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|other| *other != map).collect(); + assert_eq!(enabled(&harness), expected); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index b2603842..2339512d 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -1,6 +1,6 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -45,9 +45,14 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } -fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let label_row = harness.get_by_label(label).rect().center().y; - harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap() +/// Type `text` as the value of the slider labelled `label`: a click on its value turns it into a field with the value selected +fn type_slider_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + harness.get_by_role_and_label(Role::Label, &format!("{label} value")).click(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text(text.into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); } #[test] @@ -99,7 +104,7 @@ fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { let mut expected = before.clone(); for texture_set in &mut expected.texture_sets { - texture_set.bake.common.apply_diffusion = false; + texture_set.bake.common.apply_diffusion = true; } assert_eq!(harness.state().session.doc.project, expected); @@ -129,14 +134,7 @@ fn secondary_rays_edit_from_another_set_updates_all_sets() { select_map(&mut harness, "Ambient Occlusion"); let history_steps = harness.state().session.history_labels().len(); - number_field(&harness, "Secondary Rays").focus(); - harness.run_steps(2); - harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - harness.run_steps(1); - number_field(&harness, "Secondary Rays").type_text("128"); - harness.run_steps(1); - harness.key_press(egui::Key::Enter); - harness.run_steps(3); + type_slider_value(&mut harness, "Secondary Rays", "128"); let session = &harness.state().session; assert_eq!(session.ts(), 1); @@ -333,12 +331,14 @@ fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); - harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click(); + harness.get_by_role_and_label(Role::Button, "Reset Common Settings").click(); harness.run_steps(3); let mut expected = before.clone(); expected.texture_sets[1].bake.common = Default::default(); expected.texture_sets[1].bake.common.is_enabled = false; + // The section holds the High-Poly Parameters too, so its reset covers them + expected.texture_sets[1].bake.high_poly = Default::default(); let session = &mut harness.state_mut().session; assert_eq!(session.doc.project, expected); session.undo().unwrap(); @@ -385,10 +385,10 @@ fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_heig assert!(harness.query_by_label("Normalization").is_none()); select_map(&mut harness, "Height"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "selecting is not enabling"); - assert!(harness.query_by_label("Scaling Divisor").is_none()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click(&mut harness, "Normalization"); click(&mut harness, "Manual"); - harness.get_by_label("Scaling Divisor"); + assert!(!harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); click_checkbox(&mut harness, "Height"); @@ -396,7 +396,7 @@ fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_heig click(&mut harness, "Restore Defaults"); assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "Restore Defaults keeps the map enabled"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); - assert!(harness.query_by_label("Scaling Divisor").is_none()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click_checkbox(&mut harness, "Height"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); } @@ -417,7 +417,8 @@ fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { assert!(harness.query_by_label("Attenuation").is_none()); assert_eq!(enabled_maps(&harness), before); - click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + harness.get_by_role_and_label(Role::Button, "Common Settings").click(); + harness.run_steps(3); assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); assert_eq!(enabled_maps(&harness), before); } @@ -437,9 +438,7 @@ fn the_breadcrumb_switches_the_shown_map() { harness.get_by_label("Sampling Radius"); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); - let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); - let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; - map_dropdown.click(); + harness.get_by_label("Switch Mesh Map").click(); harness.run_steps(3); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); @@ -452,19 +451,21 @@ fn the_breadcrumb_switches_the_shown_map() { } #[test] -fn curvature_controls_follow_the_method_and_notes_visibility_rules() { +fn curvature_controls_follow_the_method_and_grey_out_by_their_switches() { let mut harness = harness(Some(BakedMap::Curvature)); let curvature = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters; assert_eq!(curvature(&harness).method, CurvatureMethod::Mesh); assert!(harness.query_by_label("Details").is_none()); harness.get_by_label("Sampling Radius"); - assert!(harness.query_by_label("Value Bounds Min").is_none()); - assert!(harness.query_by_label("Value Bounds Max").is_none()); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(harness.get_by_label(bound).accesskit_node().is_disabled(), "{bound} is greyed while tonemapping is automatic"); + } - click(&mut harness, "Auto Tonemapping"); - harness.get_by_label("Value Bounds Min"); - harness.get_by_label("Value Bounds Max"); + click(&mut harness, "Auto Tonemapping (per UV Tile)"); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(!harness.get_by_label(bound).accesskit_node().is_disabled()); + } assert!(!curvature(&harness).mesh.auto_tonemapping); click(&mut harness, "Method"); @@ -473,9 +474,9 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { assert!(harness.query_by_label("Sampling Radius").is_none()); harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); + assert!(!harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); + assert!(harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); } #[test] @@ -490,13 +491,12 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { } harness.get_by_label("The cage applies once a high poly mesh is loaded."); harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); harness.run_steps(3); assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); - harness.get_by_label("Skew Correction"); + harness.get_by_role_and_label(Role::Button, "Reset Skew Correction"); harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; harness.run_steps(3); assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); @@ -505,12 +505,25 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { harness.run_steps(3); harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); - assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + assert!(harness.get(by().label_contains("Paint Cage")).accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); harness.run_steps(3); assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); + click(&mut harness, "Cage Type"); + click(&mut harness, "Automatic (Experimental)"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::Automatic); + for distance_based_only in ["Max Frontal Distance", "Average Normals"] { + assert!(harness.query_by_label(distance_based_only).is_none(), "the automatic cage has no {distance_based_only}"); + } + assert!(harness.query(by().label_contains("Paint Cage")).is_none(), "the automatic cage is not painted"); + assert!( + harness.get_by_role_and_label(Role::CheckBox, "Matching Error").accesskit_node().is_disabled(), + "greyed with the automatic cage, as in the reference" + ); + harness.get_by_label("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is."); + click(&mut harness, "Cage Type"); click(&mut harness, "Custom File"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); @@ -518,14 +531,20 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { assert!(harness.query_by_label("Max Frontal Distance").is_none()); assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); + harness.get_by_label("Load Cage"); +} - for button_size in [20.0, 28.0] { - harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); - harness.run_steps(3); - for label in ["Remove", "Load Cage"] { - assert_eq!(harness.get_by_label(label).rect().size(), egui::Vec2::splat(button_size)); - } +#[test] +fn output_sizes_run_from_32_to_8192_as_in_the_reference() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + for offered in ["32", "8192"] { + harness.get_by_label(offered); } + assert!(harness.query_by_label("16").is_none()); } #[test] @@ -535,7 +554,8 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { let session = &mut harness.state_mut().session; session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mesh = session.mesh.clone(); - session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + session.doc.bake_meshes.cage = + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); @@ -543,12 +563,15 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); click(&mut harness, "Remove Cage"); - assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); } #[test] fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { let mut harness = harness(None); + // Mesh Map Settings in front would show its map's preview instead of the material + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(2); assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material"); harness.get_by_value("Neutral Material").click(); harness.run_steps(3); @@ -582,14 +605,13 @@ fn the_high_poly_scene_is_a_list_with_add_and_remove() { harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); harness.get_by_label("Add High-Poly Meshes"); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + harness.get_by_label("Gunhigh.obj"); - harness.get_by_label("Gunhigh.obj").click(); - harness.run_steps(3); + // Each file's row has its own × harness.get_by_label("Remove").click(); harness.run_steps(3); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.query_by_label("Remove").is_none()); } #[test] diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 5adef4ea..2eeb3da2 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -56,6 +56,8 @@ fn a_saved_preset_loads_back_into_the_active_set_as_one_undo_step() { assert!(harness.state().ui.bake_preset_name.is_empty(), "the name field is cleared"); harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::None; + // The sets share Common Settings at first, and a set sharing them takes what the active set loads + harness.state_mut().run("bake.sync", json!({ "group": "common", "ts": [0] })); let steps = harness.state().session.history_labels().len(); open_menu(&mut harness); click(&mut harness, "Final"); diff --git a/crates/ui-egui/tests/it/bake_reset_menus.rs b/crates/ui-egui/tests/it/bake_reset_menus.rs new file mode 100644 index 00000000..4c5c579c --- /dev/null +++ b/crates/ui-egui/tests/it/bake_reset_menus.rs @@ -0,0 +1,84 @@ +//! The Cage and Skew Correction ⟲ menus: reset the parameters, clear the paint strokes, or both + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakePaintTarget, BakeSettings}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// Bake mode with a high poly, Common Settings in front, a painted stroke on `target` and its section's settings changed +fn harness(target: BakePaintTarget) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + + let command = match target { + BakePaintTarget::Cage => "bake.cage.paint", + BakePaintTarget::Skew => "bake.skew.paint", + }; + harness.state_mut().run(command, json!({ "points": [[0.5, 0.5]] })); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.max_frontal, settings.skew.edge_distance) = (CHANGED_CAGE_DISTANCE, CHANGED_EDGE_DISTANCE); + harness.run_steps(3); + harness +} + +/// Values other than the defaults (0.01 and 0.15), inside their sliders' ranges +const CHANGED_CAGE_DISTANCE: f32 = 0.03; +const CHANGED_EDGE_DISTANCE: f32 = 0.5; + +/// Open `section`'s ⟲ menu and pick `item` +fn pick(harness: &mut Harness<'static, TextureCraftApp>, section: &str, item: &str) { + // The Baking Visualization panel has its own Cage section in the 3D view, right of Common Settings + let label = format!("Reset {section}"); + let buttons = harness.get_all_by_role_and_label(Role::Button, &label); + buttons.min_by(|first, second| first.rect().left().total_cmp(&second.rect().left())).unwrap().click(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); +} + +/// Whether the first set still has its `target` strokes, and whether its section's parameters are the defaults +fn state(harness: &Harness<'static, TextureCraftApp>, target: BakePaintTarget) -> (bool, bool) { + let session = &harness.state().session; + let settings = &session.doc.project.texture_sets[0].bake; + let defaults = BakeSettings::default(); + let painted = session.doc.bake_paint.contains_key(&(0, target)); + let reset = match target { + BakePaintTarget::Cage => settings.cage == defaults.cage, + BakePaintTarget::Skew => settings.skew == defaults.skew, + }; + (painted, reset) +} + +#[test] +fn each_cage_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Cage Parameters", (true, true)), ("Clear All Cage Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Cage); + assert_eq!(state(&harness, BakePaintTarget::Cage), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Cage", item); + + assert_eq!(state(&harness, BakePaintTarget::Cage), expected, "{item}: (strokes kept, parameters reset)"); + } +} + +#[test] +fn each_skew_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Skew Correction Parameters", (true, true)), ("Clear All Skew Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Skew); + assert_eq!(state(&harness, BakePaintTarget::Skew), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Skew Correction", item); + + assert_eq!(state(&harness, BakePaintTarget::Skew), expected, "{item}: (strokes kept, parameters reset)"); + } +} diff --git a/crates/ui-egui/tests/it/bake_sync.rs b/crates/ui-egui/tests/it/bake_sync.rs new file mode 100644 index 00000000..43661323 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_sync.rs @@ -0,0 +1,111 @@ +//! Sharing bake settings between texture sets from the Mesh Map Bakers panel + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakeSyncGroup, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A bake-mode app on the two-set sample with Mesh Map Bakers in front +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake = Default::default(); + set.bake.common.resolution = BakeResolution::R64; + } + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +fn second_name(harness: &Harness<'_, TextureCraftApp>) -> String { + harness.state().session.doc.project.texture_sets[1].name.clone() +} + +#[test] +fn the_common_settings_sync_dialog_takes_a_set_out_of_the_group() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + harness.get_by_label("Common Settings Sync"); + harness.get_by_role_and_label(Role::CheckBox, "Deselect All"); + + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Select All"); + click(&mut harness, "OK"); + + let project = &harness.state().session.doc.project; + assert!(harness.query_by_label("Common Settings Sync").is_none()); + assert!(!project.texture_sets[1].bake.sync.common); + assert_eq!(project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync stays"); +} + +#[test] +fn cancel_leaves_the_group_as_it_was() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "Cancel"); + assert!(harness.state().session.doc.project.texture_sets[1].bake.sync.common); +} + +#[test] +fn common_settings_edits_reach_only_the_sets_sharing_them() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[1].bake.sync.common = false; + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Apply Diffusion").click(); + harness.run_steps(3); + + let sets = &harness.state().session.doc.project.texture_sets; + assert_ne!(sets[0].bake.common.apply_diffusion, sets[1].bake.common.apply_diffusion); +} + +#[test] +fn the_list_menu_applies_the_checked_maps_to_all_sets() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal, BakedMap::Height]); + harness.run_steps(3); + click(&mut harness, "Mesh Map Bakers Menu"); + click(&mut harness, "Apply Checked to All Texture Sets"); + let enabled: Vec = harness.state().session.doc.project.texture_sets[1].bake.maps.enabled().collect(); + assert_eq!(enabled, [BakedMap::Normal, BakedMap::Height]); +} + +#[test] +fn a_rows_menu_checks_the_map_for_sets_picked_in_the_dialog() { + let mut harness = harness(); + for set in &mut harness.state_mut().session.doc.project.texture_sets { + set.bake.maps.select([]); + } + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Height").click_secondary(); + harness.run_steps(3); + click(&mut harness, "Check Height for More Texture Sets..."); + harness.get_by_label("Check Height for More Texture Sets"); + + let first = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_role_and_label(Role::CheckBox, &first).is_none(), "the active set is the source, not a target"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "OK"); + + let sets = &harness.state().session.doc.project.texture_sets; + assert!(!sets[0].bake.maps.height.is_enabled && sets[1].bake.maps.height.is_enabled); +} diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs new file mode 100644 index 00000000..4808c98c --- /dev/null +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -0,0 +1,97 @@ +//! Bake mode: high poly files load on a worker thread, and the list names them while they do + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A triangle the importer accepts as a high poly +const TRIANGLE_OBJ: &str = "o Part_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; +/// Longest the test waits for the worker +const LOAD_TIMEOUT: Duration = Duration::from_secs(60); + +/// A bake-mode app with Common Settings in front +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness +} + +fn high_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect() +} + +fn run_until_loaded(harness: &mut Harness<'_, TextureCraftApp>) { + let started = Instant::now(); + while harness.state().high_poly_job.is_some() { + assert!(started.elapsed() < LOAD_TIMEOUT, "the high polys never finished loading"); + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } +} + +#[test] +fn picked_high_polys_load_in_the_background_and_each_is_an_undo_step() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-loading-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let paths: Vec = ["first.obj", "second.obj"].map(|name| folder.join(name).display().to_string()).into(); + for path in &paths { + std::fs::write(path, TRIANGLE_OBJ).unwrap(); + } + let missing = folder.join("missing.obj").display().to_string(); + + let mut harness = harness(); + let steps = harness.state().session.history_labels().len(); + harness.state_mut().load_high_polys([paths[0].clone(), missing, paths[1].clone()]); + assert!(high_names(&harness).is_empty(), "the call returns before a file is read"); + assert_eq!(harness.state().high_poly_job.as_ref().unwrap().file_names().collect::>(), ["first.obj", "missing.obj", "second.obj"]); + harness.run_steps(1); + harness.get_by_label("Loading second.obj..."); + + run_until_loaded(&mut harness); + harness.run_steps(2); + assert_eq!(high_names(&harness), ["first.obj", "second.obj"], "the unreadable file is skipped and the rest load in order"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("missing.obj")), "the unreadable file is reported"); + assert!(harness.query_by_label("Loading second.obj...").is_none()); + assert_eq!(harness.state().session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2); + + harness.state_mut().run("edit.undo", serde_json::Value::Null); + assert_eq!(high_names(&harness), ["first.obj"]); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn high_polys_still_loading_when_another_project_opens_are_not_added_to_it() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-moved-on-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + harness.state_mut().load_high_polys([path.clone(), path]); + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + run_until_loaded(&mut harness); + + assert!(high_names(&harness).is_empty()); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("not added"))); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let file = |name: &str| texturecraft_engine::formats::MeshFile { name: name.into(), bytes: TRIANGLE_OBJ.as_bytes().to_vec(), warnings: Vec::new() }; + let load = texturecraft_engine::HighPolyLoad::prepare(&session.doc.bake_meshes, file("part.obj")).unwrap(); + + session.add_high_poly_bytes("part.obj", TRIANGLE_OBJ.as_bytes().to_vec()).unwrap(); + assert_eq!(session.apply_high_poly_load(load), "2_part.obj", "the name is made unique against the list of now"); + assert_eq!(session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2, "both meshes bake"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 831a009a..a99ef8bf 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,8 +4,11 @@ mod alpha_parameters; mod anchor_point; mod bake_job_mesh; +mod bake_map_rows; mod bake_mode; mod bake_presets; +mod bake_reset_menus; +mod bake_sync; mod brush_drag; mod brush_section_reset; mod camera_views; @@ -40,6 +43,7 @@ mod folder_properties; mod frame_selection; mod generator_panel; mod help_menu_664; +mod high_poly_loading; mod history_panel; mod import_resources; mod inactive_set_hint; diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index dd3b5d02..0c76f5ad 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -2,7 +2,7 @@ //! brush controls are in Common Settings. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; @@ -26,7 +26,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { #[test] fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); - h.get_by_label("Skew Correction"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction"); assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); // Off: a drag in the view paints nothing @@ -37,9 +37,9 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke - h.get_by_label("Paint Skew Correction").scroll_to_me(); + h.get(by().label_contains("Paint Skew Correction")).scroll_to_me(); h.run_steps(3); - h.get_by_label("Paint Skew Correction").click(); + h.get(by().label_contains("Paint Skew Correction")).click(); h.run_steps(3); assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); @@ -53,10 +53,10 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let painted = map.values.iter().filter(|v| **v > 0.5).count(); assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); - // Removing it from the panel clears the map - h.get_by_label("Remove Skew Correction").scroll_to_me(); + // The section's reset menu clears the map + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction").click(); h.run_steps(3); - h.get_by_label("Remove Skew Correction").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Clear All Skew Paint Strokes").click(); h.run_steps(3); assert!(h.state().session.doc.bake_paint.is_empty()); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..3e2696f5 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -441,7 +441,7 @@ fn window_snapshots() { save(&mut harness, &output_dir, "bake-curvature-mesh"); select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); - harness.state_mut().session.bake_meshes.high.clear(); + harness.state_mut().session.doc.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; save(&mut harness, &output_dir, "painting-restored"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..11ce0f09 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -135,9 +135,18 @@ alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). The procedural, library and imported alphas alike and are returned by `tool.brush` with the other values. The alpha's rotation is the brush `angle`. -Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each -set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the -changed fields; Restore Defaults resets the whole parameter section across all sets. +Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that +group's settings: Common Settings, and each map's settings, are shared by any set of texture sets +(at first every set shares them). Each set keeps its own enabled mesh-map checkboxes and Include in +Bake flag. An edit reaches the sets sharing its group with only the fields it changed, so values +that differ elsewhere stay; Restore Defaults resets the whole parameter section across those sets. + +`bake.sync {group: "common" | , ts: [indices] | "all"}` makes exactly these sets share the +group from now on; sets joining take the settings the group shares. `bake.copy {what: "settings" | +"checked" | "check", map?, from?, ts}` copies once: every setting with which maps are checked (or +one map's settings), which maps are checked, or checks one map; settings also reach the sets sharing a group with a target, while +checkboxes stay per set. Each is one +undo step. `bake.settings` with `model` keeps each set's sync membership. `bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum From 623bd9008d1c8d8cebd50af4c586b6030f7b1a69 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:41:50 +0000 Subject: [PATCH 33/54] Bake mode pass 2: map preview on the model while a map's settings show --- crates/engine/src/bake_preview.rs | 2 +- .../src/bake_mode/bake_visualization_panel.rs | 60 +++- .../bake_mode/bake_visualization_toggles.rs | 14 + crates/ui-egui/src/bake_mode/live_preview.rs | 325 ++++++++++++++++++ .../src/bake_mode/live_preview_target.rs | 8 + .../ui-egui/src/bake_mode/map_preview_fold.rs | 69 ++++ crates/ui-egui/src/bake_mode/mod.rs | 25 +- crates/ui-egui/src/bake_mode/preview_input.rs | 19 + .../ui-egui/src/bake_mode/running_preview.rs | 18 + crates/ui-egui/src/lib.rs | 13 +- crates/ui-egui/tests/it/bake_live_preview.rs | 168 +++++++++ crates/ui-egui/tests/it/main.rs | 1 + 12 files changed, 709 insertions(+), 13 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/live_preview.rs create mode 100644 crates/ui-egui/src/bake_mode/live_preview_target.rs create mode 100644 crates/ui-egui/src/bake_mode/map_preview_fold.rs create mode 100644 crates/ui-egui/src/bake_mode/preview_input.rs create mode 100644 crates/ui-egui/src/bake_mode/running_preview.rs create mode 100644 crates/ui-egui/tests/it/bake_live_preview.rs diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 4898ae1a..6886535d 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Bake preview", [], None, - "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. In Bake mode the app's map preview also shows here while Mesh Map Settings is in front. With neither {active: false} (setting `show` is then an error)", always, preview )] diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs index 5c4d02cc..4907928f 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -1,9 +1,11 @@ use egui::collapsing_header::CollapsingState; use egui::{Rect, Ui, vec2}; use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_render::BakeOverlay; use super::BakeVisualizationToggles; +use super::map_preview_fold::MapPreviewFold; use super::section_opening::SectionOpening; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; @@ -25,6 +27,10 @@ const ROW_BUTTON_SIZE: f32 = 18.0; /// Width of an overlay's color swatch const SWATCH_WIDTH: f32 = 44.0; +/// The map preview's sizes and how the list names them +const PREVIEW_SIZES: [(BakeResolution, &str); 4] = + [(BakeResolution::R128, "128"), (BakeResolution::R256, "256"), (BakeResolution::R512, "512"), (BakeResolution::R1024, "1K")]; + /// The neutral material's quality steps: samples per pixel and their names const QUALITIES: [(u32, &str); 6] = [ (4, n_("Very Low (4 spp)")), @@ -37,6 +43,8 @@ const QUALITIES: [(u32, &str); 6] = [ /// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let matching_error_applies = super::matching_error_applies(&app.session); + let (shown, selected) = (app.live_preview.shown(), super::live_preview::map_settings_shown(app).map(|target| target.map)); let toggles = &mut app.ui.bake_visualization; let tokens = Tokens::get(ui.ctx()); egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( @@ -52,14 +60,14 @@ pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: collapsing_state.toggle(ui); } - collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles, matching_error_applies, shown, selected)); }); }, ); } -/// The panel's sections below its header -fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { +/// The panel's sections below its header; the Matching Error row greys unless `matching_error_applies` +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, matching_error_applies: bool, shown: Option, selected: Option) { ui.horizontal(|ui| { ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -72,7 +80,7 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { let meshes_editable = !toggles.hide_baking_meshes; if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); - overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + ui.add_enabled_ui(matching_error_applies, |ui| overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error)); }) { toggles.reset_high_poly(); } @@ -100,6 +108,42 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { }) { toggles.reset_project_mesh(); } + + map_preview_section(ui, toggles, shown, selected); +} + +/// The Map Preview section: whether the selected map shows on the model, and the size it bakes at; it opens by itself while a preview shows +fn map_preview_section(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, shown: Option, selected: Option) { + let fold_id = ui.make_persistent_id("map_preview_fold"); + let mut fold: MapPreviewFold = ui.ctx().data(|data| data.get_temp(fold_id)).unwrap_or_default(); + let section = section_id(ui, "map_preview"); + let mut state = CollapsingState::load_with_default_open(ui.ctx(), section, false); + if let Some(open) = fold.follow(shown, selected, !toggles.map_preview) { + state.set_open(open); + state.store(ui.ctx()); + } + let open_before = state.is_open(); + + let reset = collapsible(ui, "map_preview", tr("Map Preview"), SectionOpening::Closed, true, true, |ui| { + ui.checkbox(&mut toggles.map_preview, tr("Preview the Selected Map")); + ui.add_enabled_ui(toggles.map_preview, |ui| { + let size = &mut toggles.map_preview_size; + let selected = PREVIEW_SIZES.iter().find(|(option, _)| option == size).map_or("", |(_, name)| *name); + combo(ui, tr("Resolution"), selected, |ui| { + for (option, name) in PREVIEW_SIZES { + ui.selectable_value(size, option, name); + } + }); + }); + }); + let open_after = CollapsingState::load_with_default_open(ui.ctx(), section, false).is_open(); + if open_after != open_before { + fold.toggled(open_after); + } + ui.ctx().data_mut(|data| data.insert_temp(fold_id, fold)); + if reset { + toggles.reset_map_preview(); + } } /// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal @@ -126,8 +170,7 @@ fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { /// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); - let mut collapsing_state = - CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), section_id(ui, id), opening == SectionOpening::Open); let (header, reset) = ui .horizontal(|ui| { ui.set_min_height(EYE_BUTTON_SIZE); @@ -157,6 +200,11 @@ fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, rese reset.is_some_and(|reset| reset.clicked()) } +/// The id a section keeps its open state under +fn section_id(ui: &Ui, id: &str) -> egui::Id { + ui.make_persistent_id(("baking_visualization_section", id)) +} + /// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs index bb99e09b..d638da81 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use texturecraft_engine::core::BakeResolution; use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; /// Opacity of the cage's surface and wireframe until changed @@ -20,6 +21,10 @@ pub struct BakeVisualizationToggles { /// Show the project mesh with [`Self::neutral`] instead of its painted material pub neutral_shown: bool, pub neutral: NeutralMaterial, + /// Show the selected map on the model while Mesh Map Settings shows its settings + pub map_preview: bool, + /// The size the map preview bakes at once a change settles + pub map_preview_size: BakeResolution, } impl Default for BakeVisualizationToggles { @@ -37,6 +42,9 @@ impl Default for BakeVisualizationToggles { project_mesh: shown(parts.low_poly), neutral_shown: true, neutral: NeutralMaterial::default(), + // Web builds bake on the UI thread, so the preview there is opt-in + map_preview: !cfg!(target_arch = "wasm32"), + map_preview_size: BakeResolution::R256, } } } @@ -85,6 +93,12 @@ impl BakeVisualizationToggles { self.missing_seams = Self::default().missing_seams; } + /// Put the Map Preview section back to its defaults + pub fn reset_map_preview(&mut self) { + let defaults = Self::default(); + (self.map_preview, self.map_preview_size) = (defaults.map_preview, defaults.map_preview_size); + } + /// Put the Project Mesh section back to its defaults pub fn reset_project_mesh(&mut self) { let defaults = Self::default(); diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs new file mode 100644 index 00000000..4c358962 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -0,0 +1,325 @@ +//! The map preview: while Mesh Map Settings shows a map's settings, the 3D view shows that map on the model, re-baked small on a worker as the settings change + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::sync::mpsc::TryRecvError; + +use texturecraft_engine::StreamedMap; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeResolution, BakedMap}; + +use super::live_preview_target::LivePreviewTarget; +use super::preview_input::PreviewInput; +use super::running_preview::RunningPreview; +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::state::Mode; + +/// Sizes a dragged slider's previews step through, smallest first +const DRAG_SIZES: [BakeResolution; 5] = [BakeResolution::R64, BakeResolution::R128, BakeResolution::R256, BakeResolution::R512, BakeResolution::R1024]; + +/// A drag preview this quick bakes one size up next time +const DRAG_STEP_UP_SECONDS: f64 = 0.07; + +/// A drag preview this slow bakes one size down next time +const DRAG_STEP_DOWN_SECONDS: f64 = 0.14; + +/// How often the view looks for a finished preview: about one frame at 60 Hz, so it shows at once +const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); + +/// The map preview's state: what it shows, what its picture was made from (and the session revision and size it was last checked at), the bake running for it, the drag change waiting for it, whether a drag still needs the full-size bake, whether its last bake could not start, and each map's drag size on this machine +#[derive(Default)] +pub(crate) struct LivePreview { + shown: Option, + made_from: Option, + checked_at: Option<(u64, BakeResolution)>, + cannot_bake: bool, + running: Option, + drag_waiting: bool, + refine_on_release: bool, + drag_sizes: BTreeMap, +} + +impl LivePreview { + /// The map the preview shows now, if any + pub(crate) fn shown(&self) -> Option { + self.shown.map(|target| target.map) + } + + /// Stop the preview and give the 3D view back; a real bake calls this before it takes the view + pub(crate) fn release(&mut self, session: &mut texturecraft_engine::Session) { + self.cancel(); + self.refine_on_release = false; + self.made_from = None; + self.checked_at = None; + self.cannot_bake = false; + if self.shown.take().is_some() { + session.bake_preview_end(); + } + } + + fn cancel(&mut self) { + self.drag_waiting = false; + if let Some(running) = self.running.take() { + running.progress.cancel.store(true, Ordering::Relaxed); + } + } + + /// The size `map` bakes at while a slider drags: it starts small, follows how fast this machine bakes it, and never passes `chosen` + fn drag_size(&self, map: BakedMap, chosen: BakeResolution) -> BakeResolution { + let learned = self.drag_sizes.get(&map).copied().unwrap_or_else(|| first_drag_size(map)); + if learned.pixels() > chosen.pixels() { chosen } else { learned } + } + + /// A drag preview of `map` at `size` took `seconds`: step its drag size up or down one size, never past `chosen` + fn learn_drag_size(&mut self, map: BakedMap, size: BakeResolution, seconds: f64, chosen: BakeResolution) { + let Some(index) = DRAG_SIZES.iter().position(|step| *step == size) else { return }; + + let next = if seconds < DRAG_STEP_UP_SECONDS { + DRAG_SIZES.get(index + 1).copied().filter(|bigger| bigger.pixels() <= chosen.pixels()).unwrap_or(size) + } else if seconds > DRAG_STEP_DOWN_SECONDS { + index.checked_sub(1).and_then(|smaller| DRAG_SIZES.get(smaller).copied()).unwrap_or(size) + } else { + size + }; + self.drag_sizes.insert(map, next); + } +} + +/// The texture set and the map whose settings a Mesh Map Settings panel in front shows, in Bake mode +pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option { + let set = app.session.ts(); + let settings = &app.session.doc.project.texture_sets.get(set)?.bake; + let shows = app.ui.mode == Mode::Baking && app.ui.dock.is_visible(Panel::MeshMapSettings); + shows.then(|| LivePreviewTarget { set, map: super::selected_map(app.ui.selected_baked_map, settings) }) +} + +/// What the preview should show: the map whose settings show, while the preview is on and no real bake runs +fn wanted(app: &TextureCraftApp) -> Option { + map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none()) +} + +/// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves +pub(crate) fn slider_dragged(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(target) = app.live_preview.shown else { return }; + + app.live_preview.refine_on_release = true; + + // Web builds bake on the UI thread, so they wait for the release; a set that can't bake waits too + if cfg!(target_arch = "wasm32") || app.live_preview.cannot_bake { + return; + } + + if app.live_preview.running.as_ref().is_some_and(|running| running.dragging) { + app.live_preview.drag_waiting = true; + } else { + let size = app.live_preview.drag_size(target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, target, size, true); + } +} + +/// Once a frame: follow what the preview should show, bake again when its picture is out of date, and take a finished bake +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + // A new session (a project opened, the mesh replaced) has no preview layer: start over + if app.live_preview.shown.is_some() && !app.session.bake_preview_active() { + app.live_preview.release(&mut app.session); + } + + let wanted = wanted(app); + if wanted != app.live_preview.shown { + app.live_preview.release(&mut app.session); + if let Some(target) = wanted { + show(app, ctx, target); + } + } + + // After a drag, and whenever what the picture was made from changes (undo, a synced set, automation, the chosen size, the meshes) + if let Some(target) = app.live_preview.shown { + let released = app.live_preview.refine_on_release && ctx.dragged_id().is_none(); + let chosen = app.ui.bake_visualization.map_preview_size; + + // Only after an edit or a new size: comparing the inputs copies the settings + let check = (app.session.revision, chosen); + let unchecked = app.live_preview.checked_at != Some(check); + let out_of_date = unchecked && !app.live_preview.refine_on_release && app.live_preview.made_from != input(app, target, chosen); + if unchecked && !app.live_preview.refine_on_release { + app.live_preview.checked_at = Some(check); + } + if released || out_of_date { + app.live_preview.refine_on_release = false; + start(app, ctx, target, chosen, false); + } + } + + take_finished(app, ctx); +} + +/// Show a finished preview bake, learn the drag size from it, and start the drag change that waited for it; a failed one goes to the Log +fn take_finished(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(running) = &app.live_preview.running else { return }; + + ctx.request_repaint_after(POLL_INTERVAL); + let finished = match running.receiver.try_recv() { + Err(TryRecvError::Empty) => return, + Ok(finished) => finished, + Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other(tr("The map preview worker stopped").into())), + }; + let Some(running) = app.live_preview.running.take() else { return }; + + // A failure keeps the old picture and says why + let mut output = match finished { + Ok(output) => output, + Err(error) => { + let map = tr(baked_map_label(running.target.map)); + app.session.log.warn("Baker", trf("The {map} preview failed: {error}", &[("map", &map), ("error", &error.to_string())])); + app.live_preview.drag_waiting = false; + return; + } + }; + + if running.dragging { + let seconds = ctx.input(|input| input.time) - running.started; + app.live_preview.learn_drag_size(running.target.map, running.size, seconds, app.ui.bake_visualization.map_preview_size); + } + if let Some(data) = output.maps.remove(&running.target.map) { + let streamed = StreamedMap { map: running.target.map, index: 0, total: 1, resolution: output.resolution, height: output.height, data: Arc::new(data) }; + app.session.bake_preview_map(running.target.set, streamed); + } + + // The newest drag change waited for this picture + if std::mem::take(&mut app.live_preview.drag_waiting) && app.live_preview.refine_on_release { + let size = app.live_preview.drag_size(running.target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, running.target, size, true); + } +} + +/// Start showing `target`: the map's last real bake at once when there is one (it may predate the settings), then a preview bake at the chosen size +fn show(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget) { + app.session.bake_preview_begin(vec![(target.set, vec![target.map])]); + app.live_preview.shown = Some(target); + + let baked = app.session.baked(target.set).and_then(|baked| baked.maps.get(&target.map).map(|data| (baked.resolution, data.clone()))); + if let Some((resolution, data)) = baked { + let height = (data.len() / target.map.components()).checked_div(resolution as usize).unwrap_or(0) as u32; + app.session.bake_preview_map(target.set, StreamedMap { map: target.map, index: 0, total: 1, resolution, height, data }); + } + start(app, ctx, target, app.ui.bake_visualization.map_preview_size, false); +} + +/// What a preview of `target` at `size` would be made from now +fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) -> Option { + let set = app.session.doc.project.texture_sets.get(target.set)?; + let meshes = &app.session.doc.bake_meshes; + let painted = app.session.doc.bake_paint.iter().filter(|((index, _), _)| *index == target.set).map(|(_, map)| Arc::as_ptr(map) as usize).collect(); + + Some(PreviewInput { + settings: set.bake.clone(), + mesh_id: app.session.mesh_id, + uv_tiles: set.uv_tiles.clone(), + excluded_tiles: set.bake_excluded_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + high_polys: meshes.high.iter().map(|mesh| Arc::as_ptr(&mesh.mesh) as usize).collect(), + cage: meshes.cage.as_ref().map(|cage| Arc::as_ptr(&cage.mesh) as usize), + painted, + size, + }) +} + +/// Bake `target`'s map alone at `size` on the preview pool (`dragging`: for a slider still moving), cancelling the preview bake still running +fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) { + app.live_preview.cancel(); + app.live_preview.made_from = input(app, target, size); + let mut task = match app.session.bake_task(target.set) { + Ok(task) => task, + Err(error) => { + // Once, not on every change while it stays unbakeable + if !app.live_preview.cannot_bake { + let map = tr(baked_map_label(target.map)); + app.session.log.warn("Baker", trf("The {map} preview can't bake: {error}", &[("map", &map), ("error", &error.to_string())])); + } + app.live_preview.cannot_bake = true; + return; + } + }; + app.live_preview.cannot_bake = false; + + task.settings.maps.select([target.map]); + let own = task.settings.common.resolution; + let size = if own.pixels() < size.pixels() { own } else { size }; + task.settings.common.resolution = size; + task.settings.common.resolution_height = None; + + let progress = Arc::new(Progress::new()); + let worker_progress = progress.clone(); + + // Queued on the preview pool's own threads: starting a new thread per change can stall the UI while a bake allocates + let receiver = match preview_pool() { + Some(pool) => { + let (sender, receiver) = std::sync::mpsc::channel(); + pool.spawn(move || { + let _ = sender.send(task.run(&worker_progress)); + }); + receiver + } + None => crate::spawn_worker("texturecraft-map-preview", move || task.run(&worker_progress)), + }; + let started = ctx.input(|input| input.time); + app.live_preview.running = Some(RunningPreview { target, size, started, dragging, progress, receiver }); +} + +/// A dragged slider's first preview size before this machine's speed is known: 64 for the ray-traced bakers (well over 100 ms at 128 on a 4-core machine), else 128 +fn first_drag_size(map: BakedMap) -> BakeResolution { + match map { + BakedMap::AmbientOcclusion | BakedMap::Thickness | BakedMap::BentNormal | BakedMap::Curvature => BakeResolution::R64, + _ => BakeResolution::R128, + } +} + +/// The preview bakes' own thread pool, a thread short of the cores, so the UI's parallel work never waits behind a preview; None where no pool can start +#[cfg(not(target_arch = "wasm32"))] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |cores| cores.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|index| format!("texturecraft-map-preview-{index}")).build(); + if let Err(error) = &pool { + log::warn!("map previews share the global thread pool: {error}"); + } + pool.ok() + }) + .as_ref() +} + +/// Web builds have no threads: the preview bakes on the UI thread +#[cfg(target_arch = "wasm32")] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_drag_size_steps_up_while_fast_down_while_slow_and_never_past_the_chosen_size() { + let mut preview = LivePreview::default(); + let map = BakedMap::AmbientOcclusion; + let largest = BakeResolution::R1024; + let start = preview.drag_size(map, largest); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + let bigger = preview.drag_size(map, largest); + assert!(bigger.pixels() > start.pixels(), "a quick bake steps up"); + + preview.learn_drag_size(map, bigger, DRAG_STEP_DOWN_SECONDS * 2.0, largest); + assert_eq!(preview.drag_size(map, largest), start, "a slow bake steps back down"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, start); + assert_eq!(preview.drag_size(map, largest), start, "never steps past the chosen size"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + assert_eq!(preview.drag_size(map, start), start, "a smaller chosen size caps what was learned"); + } +} diff --git a/crates/ui-egui/src/bake_mode/live_preview_target.rs b/crates/ui-egui/src/bake_mode/live_preview_target.rs new file mode 100644 index 00000000..17e88085 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview_target.rs @@ -0,0 +1,8 @@ +use texturecraft_engine::core::BakedMap; + +/// One map of one texture set, as the map preview shows it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct LivePreviewTarget { + pub(crate) set: usize, + pub(crate) map: BakedMap, +} diff --git a/crates/ui-egui/src/bake_mode/map_preview_fold.rs b/crates/ui-egui/src/bake_mode/map_preview_fold.rs new file mode 100644 index 00000000..04fa8732 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_preview_fold.rs @@ -0,0 +1,69 @@ +use texturecraft_engine::core::BakedMap; + +/// The Map Preview section's fold: it opens while a preview shows and folds when the preview goes away; folded by hand on a map, it stays folded until another map is picked +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct MapPreviewFold { + /// The map the preview showed last frame + pub(super) shown: Option, + /// The map the user folded the section on while its preview showed + pub(super) folded_for: Option, +} + +impl MapPreviewFold { + /// Whether the section should open (Some(true)) or fold (Some(false)) this frame, or stay as it is; `selected` is the map whose settings show, `switched_off` whether the preview is turned off + pub(super) fn follow(&mut self, shown: Option, selected: Option, switched_off: bool) -> Option { + // Only another map ends it; no map at all (Common Settings in front) keeps it + if selected.is_some() && selected != self.folded_for { + self.folded_for = None; + } + if shown == self.shown { + return None; + } + + self.shown = shown; + match shown { + Some(map) => (self.folded_for != Some(map)).then_some(true), + // Turning the preview off from inside the section leaves it open until the user moves on + None => (!(switched_off && selected.is_some())).then_some(false), + } + } + + /// The user folded or opened the section by hand + pub(super) fn toggled(&mut self, open: bool) { + self.folded_for = if open { None } else { self.shown }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_section_opens_with_a_preview_and_folds_when_it_goes() { + let mut fold = MapPreviewFold::default(); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), Some(true)); + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "no change, no move"); + assert_eq!(fold.follow(None, None, false), Some(false)); + } + + #[test] + fn folded_by_hand_it_stays_folded_until_another_map_is_picked() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + fold.toggled(false); + fold.follow(None, None, false); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "same map: stays folded"); + assert_eq!(fold.follow(Some(BakedMap::Curvature), Some(BakedMap::Curvature), false), Some(true)); + } + + #[test] + fn switching_the_preview_off_leaves_the_section_open() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + assert_eq!(fold.follow(None, Some(BakedMap::AmbientOcclusion), true), None); + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index a4bf439f..4c3d0e61 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -7,6 +7,12 @@ mod bake_visualization_toggles; mod breadcrumb; mod common_settings; mod glyph_look; +mod live_preview; +mod live_preview_target; +mod map_preview_fold; +mod preview_input; +mod running_preview; +pub(crate) use live_preview::LivePreview; mod section_opening; pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; @@ -178,9 +184,19 @@ pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { .inner }); let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected))); - edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { + let changed = edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.inner)) }); + // Other changes reach the preview through its check of what its picture was made from + if changed && ui.ctx().dragged_id().is_some() { + let ctx = ui.ctx().clone(); + live_preview::slider_dragged(app, &ctx); + } +} + +/// Once a frame: the map preview follows the selected map and takes its finished bakes +pub(crate) fn poll_live_preview(app: &mut TextureCraftApp, ctx: &egui::Context) { + live_preview::poll(app, ctx); } /// The Common Settings panel: output, high poly, cage and skew settings @@ -203,14 +219,14 @@ fn edit_settings( scroll_id: &str, texture_sets: Value, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, -) { +) -> bool { let set_index = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; + let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return false }; let mut settings = before.clone(); let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; if settings == before && reset.is_none() { - return; + return false; } let mut patch = settings_patch(&before, &settings); @@ -218,6 +234,7 @@ fn edit_settings( fields.extend(reset); } app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + true } /// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material diff --git a/crates/ui-egui/src/bake_mode/preview_input.rs b/crates/ui-egui/src/bake_mode/preview_input.rs new file mode 100644 index 00000000..08b8a704 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/preview_input.rs @@ -0,0 +1,19 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_engine::core::{BakeResolution, BakeSettings}; + +/// What a map preview picture is made from, everything its bake reads: when any of it changes, the picture is out of date +#[derive(Clone, Debug, PartialEq)] +pub(super) struct PreviewInput { + pub(super) settings: BakeSettings, + pub(super) mesh_id: u64, + /// The set's UV tiles, the ones left out of the bake, and their resolutions + pub(super) uv_tiles: Vec, + pub(super) excluded_tiles: BTreeSet, + pub(super) tile_resolutions: BTreeMap, + /// The high polys', the cage's and the set's painted maps' shared buffers: a file loaded again under the same name is another buffer + pub(super) high_polys: Vec, + pub(super) cage: Option, + pub(super) painted: Vec, + pub(super) size: BakeResolution, +} diff --git a/crates/ui-egui/src/bake_mode/running_preview.rs b/crates/ui-egui/src/bake_mode/running_preview.rs new file mode 100644 index 00000000..38064540 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/running_preview.rs @@ -0,0 +1,18 @@ +use std::sync::Arc; +use std::sync::mpsc::Receiver; + +use texturecraft_engine::Result; +use texturecraft_engine::bake::{BakeOutput, Progress}; +use texturecraft_engine::core::BakeResolution; + +use super::live_preview_target::LivePreviewTarget; + +/// A map preview bake on its worker: its size, when it started (app time) and whether a dragged slider asked for it +pub(super) struct RunningPreview { + pub(super) target: LivePreviewTarget, + pub(super) size: BakeResolution, + pub(super) started: f64, + pub(super) dragging: bool, + pub(super) progress: Arc, + pub(super) receiver: Receiver>, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a24b9d6d..c1dcf34e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,6 +276,8 @@ pub struct TextureCraftApp { pub layer_panel: layer_panel::LayerPanel, /// The Mesh Map Bakers rows' thumbnails pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails, + /// The map preview: the selected map on the model while Mesh Map Settings shows it + pub(crate) live_preview: bake_mode::LivePreview, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -418,6 +420,7 @@ impl TextureCraftApp { thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), bake_map_thumbnails: bake_mode::MapThumbnails::default(), + live_preview: bake_mode::LivePreview::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -618,6 +621,9 @@ impl TextureCraftApp { return; } + // The bake takes the 3D view over from the map preview + self.live_preview.release(&mut self.session); + // Restore the picker's view before the preview starts following baked maps id_color_pick::IdColorPick::end(self); @@ -738,8 +744,10 @@ impl TextureCraftApp { } let Some(job) = self.bake.as_mut() else { - // A preview whose bake is gone must not keep the view - self.session.bake_preview_end(); + // A preview whose bake is gone must not keep the view; the map preview keeps its own + if self.live_preview.shown().is_none() { + self.session.bake_preview_end(); + } return; }; @@ -1131,6 +1139,7 @@ impl eframe::App for TextureCraftApp { } } self.poll_bake(ctx); + bake_mode::poll_live_preview(self, ctx); self.poll_resize(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_high_poly_job(ctx); diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs new file mode 100644 index 00000000..5944e3ce --- /dev/null +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -0,0 +1,168 @@ +//! The map preview: the selected map's settings show it on the model, small while a slider is dragged + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// How long a steady drag may take to bring its first new pictures, on a slow machine +const MOVING_DRAG_LIMIT: std::time::Duration = std::time::Duration::from_secs(20); + +/// Bake mode on the sample with Ambient Occlusion's settings in front +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake = Default::default(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R1024; + // No earlier bake to start the preview from: its first picture is a preview bake at the chosen size + session.doc.baked.clear(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R256; + harness.run_steps(4); + harness.get(egui_kittest::kittest::by().role(Role::Button).label("Ambient Occlusion")).click(); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); + harness.run_steps(3); + harness +} + +/// The size of the picture the preview shows for the first set, once it is `wanted` (the worker gets a few seconds) +fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { + for _ in 0..600 { + harness.run_steps(1); + let shown = + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)); + if shown.is_some_and(&wanted) { + return shown; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + None +} + +#[test] +fn the_selected_map_shows_on_the_model_and_common_settings_hide_it_at_once() { + let mut harness = harness(); + + let shown = wait_for_preview(&mut harness, |_| true); + assert!(shown.is_some(), "selecting a map's settings shows it"); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(1); + assert!(!harness.state().session.bake_preview_active(), "no lingering picture"); + assert_ne!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); +} + +#[test] +fn a_dragged_slider_previews_smaller_than_the_picture_it_settles_on() { + let mut harness = harness(); + let settled = wait_for_preview(&mut harness, |_| true).unwrap(); + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let (from, to) = (track.center(), track.left_center() + egui::vec2(track.width() * 0.1, 0.0)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + let dragged = wait_for_preview(&mut harness, |size| size < settled); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + let released = wait_for_preview(&mut harness, |size| size == settled); + + assert!(dragged.is_some(), "while dragging the preview bakes smaller"); + assert!(released.is_some(), "the release refines it to the chosen size"); +} + +#[test] +fn switching_the_preview_off_hides_it() { + let mut harness = harness(); + wait_for_preview(&mut harness, |_| true); + + harness.state_mut().ui.bake_visualization.map_preview = false; + harness.run_steps(1); + + assert!(!harness.state().session.bake_preview_active()); +} + +#[test] +fn pictures_keep_coming_while_the_slider_is_still_moving() { + let mut harness = harness(); + // Many rays: each preview bake takes several frames, as on a real mesh + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays = 256; + wait_for_preview(&mut harness, |_| true); + let track = harness.get_by_role_and_label(Role::Slider, "Spread Angle").rect(); + let from = track.left_center() + egui::vec2(track.width() * 0.05, 0.0); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + // Holding the last picture keeps a new one from reusing its address + let mut last = picture(&harness); + let mut pictures = 0; + let started = std::time::Instant::now(); + for step in 0.. { + if pictures > 2 || started.elapsed() > MOVING_DRAG_LIMIT { + break; + } + + // Every frame moves the slider, as a steady drag does + harness.hover_at(from + egui::vec2(track.width() * 0.002 * (step % 200) as f32, 0.0)); + harness.run_steps(1); + let now = picture(&harness); + if now.as_ref().map(std::sync::Arc::as_ptr) != last.as_ref().map(std::sync::Arc::as_ptr) { + pictures += 1; + last = now; + } + } + + assert!(pictures > 2, "new pictures arrive while the slider never stops"); +} + +#[test] +fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() { + let mut harness = harness(); + let first = wait_for_preview(&mut harness, |_| true).unwrap(); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R128; + let resized = wait_for_preview(&mut harness, |size| size < first); + assert!(resized.is_some(), "a smaller resolution bakes a smaller picture"); + + // A change that doesn't come from the panel: a script, an undo or a synced set + let before = picture(&harness); + harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); + let mut changed = false; + for _ in 0..600 { + harness.run_steps(1); + if picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) { + changed = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(changed, "the settings change brings a new picture"); + + // The same file loaded again: same name, new geometry + for (index, bytes) in [b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".as_slice(), b"v 0 0 0\nv 2 0 0\nv 0 2 0\nf 1 2 3\n".as_slice()].into_iter().enumerate() { + let session = &mut harness.state_mut().session; + if index > 0 { + session.remove_high_poly(0).unwrap(); + } + session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); + let before = picture(&harness); + let reloaded = (0..600).any(|_| { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) + }); + assert!(reloaded, "high poly load {index} brings a new picture"); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a99ef8bf..06e50b3c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,6 +4,7 @@ mod alpha_parameters; mod anchor_point; mod bake_job_mesh; +mod bake_live_preview; mod bake_map_rows; mod bake_mode; mod bake_presets; From b1c8bd67184668bf50fdfc795bce53a73ac59076 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:36:09 +0000 Subject: [PATCH 34/54] Generators: a click on the preview opens it enlarged in a tool window, following the settings --- crates/ui-egui/src/generator_panel.rs | 52 +++++++++++++--- .../ui-egui/src/generator_preview_window.rs | 61 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 3 + crates/ui-egui/src/thumbs.rs | 10 +-- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/it/generator_panel.rs | 39 ++++++++++++ 7 files changed, 153 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/src/generator_preview_window.rs diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 270ff5e1..dc4efa55 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,6 +1,6 @@ //! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{Painter, Rect, TextureHandle}; +use egui::{CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; use serde_json::json; use texturecraft_engine::core::{ CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, @@ -103,7 +103,7 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, // The Curvature size under the pointer shows alone in the preview: the columns are drawn after it, so it is kept from the frame before let solo_id = sheet.ui.make_persistent_id(("generator_solo", id)); - let mut solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); + let solo: Option = sheet.ui.data(|data| data.get_temp(solo_id)).flatten(); let solo_texture = match (kind, generator.detail_in_use(), solo) { (GeneratorKind::Curvature, Some(detail), Some(size)) => { app.thumbs.generator_picture(&ctx, ShelfPreview::Curvature { mode: detail.mode, solo: Some(size) }, PREVIEW_ORB_PX) @@ -116,37 +116,71 @@ fn parameters(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, (layer, let texture = solo_texture .or_else(|| app.thumbs.generator_set_picture(&ctx, id, set, PREVIEW_ORB_PX)) .or_else(|| app.thumbs.generator_picture(&ctx, ShelfPreview::Generator(kind), PREVIEW_ORB_PX)); - let picture = |painter: &Painter, rect: Rect| orb(painter, rect, texture.as_ref(), &tokens, &ctx); + let drawn_at = std::cell::Cell::new(None); + let picture = |painter: &Painter, rect: Rect| { + drawn_at.set(Some(rect)); + orb(painter, rect, texture.as_ref(), &tokens, &ctx); + }; + rows(app, sheet, (layer, id), generator, &picture, solo_id); + if let Some(rect) = drawn_at.get() { + enlarge_on_click(app, sheet, id, rect); + } +} + +/// The preview opens enlarged in its own window on a click: a grey outline shows it can while the pointer is on it, and that it is open +fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id: u64, rect: Rect) { + let response = sheet.ui.interact(rect, sheet.ui.make_persistent_id(("generator_preview_enlarge", id)), Sense::click()).on_hover_cursor(CursorIcon::ZoomIn); + let open = app.ui.windows.generator_preview == Some(id); + response.widget_info(|| WidgetInfo::selected(Role::Button, true, open, tr("Enlarge preview"))); + if response.hovered() || response.has_focus() || open { + let tokens = Tokens::get(sheet.ui.ctx()); + sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); + } + if response.clicked() { + crate::generator_preview_window::toggle(app, id); + } +} + +/// The kind's rows, `picture` drawing the preview; `solo_id` keeps the Curvature size under the pointer for the next frame's preview +fn rows( + app: &mut TextureCraftApp, + sheet: &mut PropertySheet<'_>, + (layer, id): (LayerId, u64), + generator: &Generator, + picture: &dyn Fn(&Painter, Rect), + solo_id: egui::Id, +) { + let kind = generator.kind; if let Some(controls) = generator.kind_controls() { - crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, &picture); + crate::generator_kind_rows::kind_rows(app, sheet, id, generator, controls, picture); return; } if let Some(defaults) = WearParameters::defaults(kind) { // A wear generator saved before its wear controls shows them at their defaults: editing one moves it onto them - wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), &picture); + wear_rows(app, sheet, (layer, id), generator, generator.wear.unwrap_or(defaults), picture); return; } if let Some(light) = generator.light { - light_rows(app, sheet, id, Some(generator.invert), light, &picture); + light_rows(app, sheet, id, Some(generator.invert), light, picture); return; } - global_rows(app, sheet, id, generator, &picture); + global_rows(app, sheet, id, generator, picture); if generator.on_earlier_model() { ramp_rows(app, sheet, id, generator); } // Saved before the section or light controls, a generator shows them at their defaults: editing one moves it onto them if let Some(defaults) = SectionParameters::defaults(kind) { - solo = None; + let mut solo = None; section_rows(app, sheet, id, generator, generator.section_controls().unwrap_or(defaults), &mut solo); texture_card(app, sheet, (layer, id), generator.texture.as_deref().cloned().unwrap_or_default()); micro_switch_card(app, sheet, (layer, id), generator); sheet.ui.data_mut(|data| data.insert_temp(solo_id, solo)); } if let Some(defaults) = LightParameters::defaults(kind) { - light_rows(app, sheet, id, None, defaults, &picture); + light_rows(app, sheet, id, None, defaults, picture); } } diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs new file mode 100644 index 00000000..e8a8d406 --- /dev/null +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -0,0 +1,61 @@ +//! A generator's preview enlarged in a tool window, following its settings while they change + +use egui::{Rect, Sense, pos2}; +use texturecraft_engine::core::{EffectKind, LayerId}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; + +/// The width the enlarged picture is rendered at, in pixels: the most a preview renders +const PICTURE_PX: usize = texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; + +/// The window's first width, in points +const DEFAULT_WIDTH: f32 = 420.0; + +/// The narrowest the picture shrinks to, in points +const MIN_SIDE: f32 = 160.0; + +/// How soon a picture still rendering is looked for again +const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); + +/// The open enlarged preview, if any: closed by its ×, and when its generator is gone +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(effect) = app.ui.windows.generator_preview else { return }; + let generator = match app.session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.clone(), + _ => { + app.ui.windows.generator_preview = None; + return; + } + }; + + let set = ShelfPreview::generator_set(&generator, &app.session.images); + let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); + let tokens = Tokens::get(ctx); + let mut open = true; + crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH).show(ctx, |ui| { + let side = ui.available_width().max(MIN_SIDE); + let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); + match &texture { + Some(texture) => { + ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + None => { + ui.painter().rect_filled(rect, 0.0, tokens.button); + ctx.request_repaint_after(PICTURE_POLL); + } + } + }); + if !open { + app.ui.windows.generator_preview = None; + } +} + +/// Opens generator effect `effect`'s enlarged preview, or closes it when it is the one open +pub(crate) fn toggle(app: &mut TextureCraftApp, effect: u64) { + let open = &mut app.ui.windows.generator_preview; + *open = if *open == Some(effect) { None } else { Some(effect) }; +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f13365a8..498f6f28 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -50,6 +50,7 @@ mod generator_kind_rows; mod generator_panel; mod generator_params; mod generator_point_pick; +mod generator_preview_window; mod generator_section_rows; mod generator_slot; mod generator_wear_rows; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index ae9d4980..b1a7483a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -121,6 +121,9 @@ pub struct Windows { /// Window ▸ Reset UI is waiting for its answer. #[serde(skip)] pub confirm_reset_ui: bool, + /// The generator effect whose preview is open enlarged in its own window + #[serde(skip)] + pub generator_preview: Option, } /// An action that replaces or ends the project, held while the project has unsaved changes. diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 82755d8b..38552ce4 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -64,8 +64,8 @@ pub struct Thumbs { big_shown: VecDeque, /// The frame that last took in the worker's results received_in_pass: u64, - /// Per generator panel: the picture of its settings being rendered, and the last one finished (shown meanwhile) - set_pictures: HashMap, Option)>, + /// Per generator effect and picture size: the picture of its settings being rendered, and the last one finished (shown meanwhile) + set_pictures: HashMap<(u64, usize), (Option, Option)>, } impl Thumbs { @@ -312,7 +312,7 @@ impl Thumbs { self.receive(ctx); let size_px = size_px.clamp(1, texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX); let key = self.worker_key(&preview, size_px); - let (in_flight, last) = self.set_pictures.get(&effect).cloned().unwrap_or_default(); + let (in_flight, last) = self.set_pictures.get(&(effect, size_px)).cloned().unwrap_or_default(); // The picture in flight landed: it is the latest shown let last = match in_flight.as_ref().map(|key| self.rendered.get(key)) { @@ -326,7 +326,7 @@ impl Thumbs { None => self.big(ctx, preview, size_px).or_else(|| last.clone()), }; let in_flight = if busy { in_flight } else { Some(key) }; - self.set_pictures.insert(effect, (in_flight, shown.clone().or(last))); + self.set_pictures.insert((effect, size_px), (in_flight, shown.clone().or(last))); shown } @@ -505,7 +505,7 @@ mod tests { let last = ctx.load_texture("last", ColorImage::filled([1, 1], Color32::RED), TextureOptions::LINEAR); let rendering = thumbs.worker_key(&set(false), 8); thumbs.rendered.insert(rendering.clone(), WorkerPreview::Rendering); - thumbs.set_pictures.insert(1, (Some(rendering), Some(last.clone()))); + thumbs.set_pictures.insert((1, 8), (Some(rendering), Some(last.clone()))); let shown = thumbs.generator_set_picture(&ctx, 1, set(true), 8); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index f9e8fa5c..240f43ed 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -33,6 +33,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { unsaved(app, ctx); reset_ui(app, ctx); crate::named_layouts::show(app, ctx); + crate::generator_preview_window::show(app, ctx); } /// Window ▸ Reset UI asks first: Escape closes the question, Enter answers Reset. diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 5d2e24b1..245bffcd 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -517,3 +517,42 @@ fn new_kind_panel_snapshots() { } } } + +#[test] +fn the_preview_opens_enlarged_in_its_own_window() { + let (mut harness, effect) = harness_with(false, json!({"generator": "edgeWear"})); + let enlarged = |harness: &Harness<'_, TextureCraftApp>| harness.query_by_role_and_label(Role::Image, "Preview").is_some(); + assert!(!enlarged(&harness)); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + assert!(enlarged(&harness), "a click on the preview opens it enlarged"); + assert!(is_on(&harness, Role::Button, "Enlarge preview"), "the preview shows it is open"); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + assert!(!enlarged(&harness), "a second click closes it"); + + click_live(&mut harness, Role::Button, "Enlarge preview"); + execute(&mut harness.state_mut().session, "effect.remove", &json!({"effect": effect.0})).unwrap(); + harness.run_steps(3); + assert!(!enlarged(&harness), "it closes with its generator"); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn enlarged_preview_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); + click_live(&mut harness, Role::Button, "Enlarge preview"); + + // The pictures render on the preview worker + for _ in 0..60 { + harness.run_steps(4); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-enlarged-preview-{name}.png"))).unwrap(); + } +} From 99c14baaed6b05d81b9724c6eb4dfa2b38be24ac Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:38:54 +0000 Subject: [PATCH 35/54] Map preview tests wait up to a minute for a bake, not a fixed number of frames --- crates/ui-egui/tests/it/bake_live_preview.rs | 52 ++++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 5944e3ce..848543c9 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -8,8 +8,11 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; -/// How long a steady drag may take to bring its first new pictures, on a slow machine -const MOVING_DRAG_LIMIT: std::time::Duration = std::time::Duration::from_secs(20); +/// How long a preview bake may take on a busy CI machine running every test at once +const PREVIEW_LIMIT: std::time::Duration = std::time::Duration::from_secs(60); + +/// How long the tests let the worker run between frames while they wait +const WAIT_STEP: std::time::Duration = std::time::Duration::from_millis(10); /// Bake mode on the sample with Ambient Occlusion's settings in front fn harness() -> Harness<'static, TextureCraftApp> { @@ -28,18 +31,27 @@ fn harness() -> Harness<'static, TextureCraftApp> { harness } -/// The size of the picture the preview shows for the first set, once it is `wanted` (the worker gets a few seconds) -fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { - for _ in 0..600 { +/// Run frames until `done` holds, letting the worker run between them; false when the preview limit passes first +fn run_until(harness: &mut Harness<'static, TextureCraftApp>, mut done: impl FnMut(&Harness<'static, TextureCraftApp>) -> bool) -> bool { + let started = std::time::Instant::now(); + while started.elapsed() < PREVIEW_LIMIT { harness.run_steps(1); - let shown = - harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)); - if shown.is_some_and(&wanted) { - return shown; + if done(harness) { + return true; } - std::thread::sleep(std::time::Duration::from_millis(10)); + std::thread::sleep(WAIT_STEP); } - None + false +} + +/// The size of the picture the preview shows for the first set +fn shown_size(harness: &Harness<'static, TextureCraftApp>) -> Option { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)) +} + +/// The size of the picture the preview shows for the first set, once it is `wanted` +fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { + run_until(harness, |harness| shown_size(harness).is_some_and(&wanted)).then(|| shown_size(harness)).flatten() } #[test] @@ -107,7 +119,7 @@ fn pictures_keep_coming_while_the_slider_is_still_moving() { let mut pictures = 0; let started = std::time::Instant::now(); for step in 0.. { - if pictures > 2 || started.elapsed() > MOVING_DRAG_LIMIT { + if pictures > 2 || started.elapsed() > PREVIEW_LIMIT { break; } @@ -139,15 +151,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() // A change that doesn't come from the panel: a script, an undo or a synced set let before = picture(&harness); harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); - let mut changed = false; - for _ in 0..600 { - harness.run_steps(1); - if picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) { - changed = true; - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } + let changed = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); assert!(changed, "the settings change brings a new picture"); // The same file loaded again: same name, new geometry @@ -158,11 +162,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() } session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); let before = picture(&harness); - let reloaded = (0..600).any(|_| { - harness.run_steps(1); - std::thread::sleep(std::time::Duration::from_millis(10)); - picture(&harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr) - }); + let reloaded = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); assert!(reloaded, "high poly load {index} brings a new picture"); } } From 577981a3d2537a5a7922fa64be26ca4feee6f5e5 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:44:17 +0000 Subject: [PATCH 36/54] Generators: the enlarged preview first opens beside the small one --- crates/ui-egui/src/generator_panel.rs | 3 ++- crates/ui-egui/src/generator_preview_window.rs | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index dc4efa55..b07914a4 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -138,7 +138,8 @@ fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); } if response.clicked() { - crate::generator_preview_window::toggle(app, id); + let ctx = sheet.ui.ctx().clone(); + crate::generator_preview_window::toggle(app, &ctx, id, rect); } } diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index e8a8d406..fbdc227b 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -17,6 +17,9 @@ const DEFAULT_WIDTH: f32 = 420.0; /// The narrowest the picture shrinks to, in points const MIN_SIDE: f32 = 160.0; +/// From the small preview's left edge to the window's right edge when it first opens, in points: clear of the properties panel +const BESIDE_GAP: f32 = 24.0; + /// How soon a picture still rendering is looked for again const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); @@ -35,7 +38,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); let tokens = Tokens::get(ctx); let mut open = true; - crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH).show(ctx, |ui| { + let beside = + ctx.data(|data| data.get_temp::(anchor_id())).map_or(ctx.content_rect().center(), |small| pos2(small.left() - BESIDE_GAP, small.center().y)); + let window = crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH); + window.default_pos(beside).pivot(egui::Align2::RIGHT_CENTER).show(ctx, |ui| { let side = ui.available_width().max(MIN_SIDE); let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); @@ -54,8 +60,14 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } } -/// Opens generator effect `effect`'s enlarged preview, or closes it when it is the one open -pub(crate) fn toggle(app: &mut TextureCraftApp, effect: u64) { +/// Opens generator effect `effect`'s enlarged preview beside its small one at `small`, or closes it when it is the one open +pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &egui::Context, effect: u64, small: Rect) { + ctx.data_mut(|data| data.insert_temp(anchor_id(), small)); let open = &mut app.ui.windows.generator_preview; *open = if *open == Some(effect) { None } else { Some(effect) }; } + +/// Where the small preview was when the window was asked for: it first opens beside it +fn anchor_id() -> egui::Id { + egui::Id::unique("generator_preview_anchor") +} From 582c6853b5984fa1ceb9ec3ea79ebab4503c1f5d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:57:26 +0000 Subject: [PATCH 37/54] Bake mode pass 2: review fixes - Automatic cage: coincident vertices of different mesh-name groups keep separate distances - A sync edit fails, changing no set, when a partner's merged settings would be invalid - A high poly read during a paint stroke is added once the stroke ends, so its cancel or undo keeps it - Quick bake and the map preview read the low poly's colours for the requested map even when it is unchecked - The set picker's differing-values note compares with the set bake.sync will take settings from - Map thumbnails redraw when the UV tiles' scales change - Checkbox drags start on the primary button only and reach rows crossed between two frames - A long texture set name or folder is cut to fit its row - Map preview tests require a new picture, not just a missing one --- crates/bake/src/cage/fitted_cage.rs | 30 +++++++++- crates/bake/src/test/fitted_cage.rs | 36 ++++++++++++ crates/core/src/project.rs | 6 ++ crates/engine/src/bake/mesh_map_command.rs | 58 ++++++++++++++++--- crates/engine/src/bake/sync_command.rs | 17 ++++-- crates/ui-egui/src/bake_mode/breadcrumb.rs | 10 +++- crates/ui-egui/src/bake_mode/live_preview.rs | 3 +- .../ui-egui/src/bake_mode/map_thumbnails.rs | 20 +++++-- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 50 ++++++++++++---- crates/ui-egui/src/bake_mode/set_picker.rs | 52 ++++++++++++----- crates/ui-egui/src/high_poly_job.rs | 7 ++- crates/ui-egui/src/lib.rs | 12 ++-- .../ui-egui/src/property_sheet/file_list.rs | 37 +++++++++--- crates/ui-egui/tests/it/bake_live_preview.rs | 9 ++- crates/ui-egui/tests/it/bake_map_rows.rs | 35 ++++++++++- crates/ui-egui/tests/it/bake_mode.rs | 11 ++++ crates/ui-egui/tests/it/high_poly_loading.rs | 29 ++++++++++ 17 files changed, 358 insertions(+), 64 deletions(-) diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs index 088dae2f..54bbde47 100644 --- a/crates/bake/src/cage/fitted_cage.rs +++ b/crates/bake/src/cage/fitted_cage.rs @@ -2,7 +2,7 @@ use super::name_keys::NameKeys; use crate::map::interpolate; use crate::{BakeRequest, HighPoly, MeshExtent}; use rayon::prelude::*; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use texturecraft_geom::Mesh; use texturecraft_geom::glam::Vec3; @@ -26,6 +26,7 @@ impl FittedCage { pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { let low = request.mesh; let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); let mut reach: Vec> = vec![None; welded_count]; @@ -71,6 +72,23 @@ impl FittedCage { } } +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups(welded_indices: &[u32], vertex_keys: &[u32]) -> Vec { + if vertex_keys.is_empty() { + return welded_indices.to_vec(); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + /// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { low.positions @@ -153,7 +171,15 @@ fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterat #[cfg(test)] mod tests { - use super::spread_to_neighbours; + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // Vertices 0 and 1 share a position, as do 2 and 3; 1 and 2 are in group 7, the others in group 5 + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]), [0, 0, 1], "without name matching nothing changes"); + } #[test] fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 3aa96e6b..903c5c99 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -148,3 +148,39 @@ fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); } + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 6bcf92e4..b8e66cd4 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -489,6 +489,12 @@ impl Project { } } + /// The set whose `group` settings the sets joining a sync of `members` take: one of them already sharing the group, else `active` when it is one of them, else the first + pub fn bake_sync_source(&self, group: BakeSyncGroup, members: &[usize], active: usize) -> Option { + let staying = members.iter().copied().find(|index| self.texture_sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); + staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()) + } + pub fn layer(&self, id: LayerId) -> Result<&Layer> { self.layers.get(&id).ok_or(CoreError::NoLayer(id)) } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 6bb70d19..3e544857 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -117,15 +117,30 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { + /// The bake of texture set `texture_set`'s checked maps pub fn bake_task(&self, texture_set: usize) -> Result { + self.bake_task_of(texture_set, None) + } + + /// The bake of texture set `texture_set`'s map `map` alone, checked or not + pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { + self.bake_task_of(texture_set, Some(map)) + } + + fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } - let needs_low_color = set.bake.maps.opacity.is_enabled - || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); - let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { + let mut settings = set.bake.clone(); + if let Some(map) = only { + settings.maps.select([map]); + } + // Read from the maps that bake, so a map baked alone while unchecked still gets the colours + let needs_low_color = settings.maps.opacity.is_enabled + || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); + let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { self.doc .bake_meshes .low_base_color @@ -158,7 +173,7 @@ impl Session { mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, - settings: set.bake.clone(), + settings, high, cage, skew, @@ -730,14 +745,19 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { let targets = updated_settings(session, params, command)?; let sets = targets.iter().map(|(index, _)| *index).collect(); - let next = with_sync_partners(&session.doc.project, targets, command)?; + let next = with_sync_partners(&session.doc.project, targets, command, boolp(params, "preset") == Some(true))?; super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } -/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group -fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's settings come out invalid (`from_preset`: preset limits apply) +fn with_sync_partners( + project: &texturecraft_core::Project, + targets: Vec<(usize, BakeSettings)>, + command: &str, + from_preset: bool, +) -> Result> { let mut next: BTreeMap = BTreeMap::new(); for (target, settings) in &targets { let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; @@ -755,6 +775,10 @@ fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, } } } + // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max + for (partner, settings) in &next { + validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; + } next.extend(targets); Ok(next.into_iter().collect()) } @@ -861,3 +885,23 @@ mod gpu_raytracing_tests { assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU"); } } + +#[cfg(test)] +mod bake_task_tests { + use std::sync::Arc; + + use texturecraft_core::BakedMap; + + #[test] + fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() { + let mut session = crate::sample_session(64, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + let colours = Arc::new(vec![None]); + let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); + + assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours"); + let task = session.bake_task_only(0, BakedMap::Opacity).unwrap(); + assert!(Arc::ptr_eq(&task.low_base_color, &colours), "Opacity reads them"); + assert!(task.settings.maps.opacity.is_enabled); + } +} diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs index e244e507..88018b6f 100644 --- a/crates/engine/src/bake/sync_command.rs +++ b/crates/engine/src/bake/sync_command.rs @@ -51,10 +51,7 @@ fn sync(session: &mut Session, params: &Value) -> Result { let members = sets_param(session, COMMAND, params)?; let sets = &session.doc.project.texture_sets; - // Additions take the settings of a set that already shares them; with none left, of the active set when it joins, else of the first - let staying = members.iter().copied().find(|index| sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); - let active = session.ts(); - let source = staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()); + let source = session.doc.project.bake_sync_source(group, &members, session.ts()); let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone()); let next: Vec<(usize, BakeSettings)> = sets @@ -265,4 +262,16 @@ mod tests { assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6); assert_eq!(bake(&session, 1).common.dilation, 3); } + + #[test] + fn an_edit_that_would_leave_a_synced_set_with_an_invalid_interval_changes_no_set() { + let mut session = session(); + session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.max_distance = 0.5; + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.max_distance = 0.05; + let before = session.doc.project.texture_sets.clone(); + + let patch = json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "min_distance": 0.1 } } } } } }); + assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum"); + assert_eq!(session.doc.project.texture_sets, before); + } } diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 2ece6800..ac3cda17 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -26,7 +26,7 @@ const RESET_BOX: f32 = 20.0; /// Size of the names const NAME_SIZE: f32 = 12.0; -/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; returns whether ⟲ was clicked +/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; a long set name is cut with "…"; returns whether ⟲ was clicked pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, restorable: bool) -> bool { let tokens = Tokens::get(ui.ctx()); let active_set = app.session.ts(); @@ -39,13 +39,17 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, r let set_caret = caret(ui, &painter, &tokens, x, center_y, "texture_set_caret", tr("Switch Texture Set")); x += CARET_BOX + CARET_TO_NAME; let set_name = set_names.get(active_set).map_or("", String::as_str); - let set_galley = painter.layout_no_wrap(set_name.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let map_name = tr(baked_map_label(selected)); + let map_width = painter.layout_no_wrap(map_name.to_owned(), semibold(NAME_SIZE), tokens.text_strong).size().x; + let reset_width = if restorable { RESET_BOX } else { 0.0 }; + let set_room = line.right() - reset_width - map_width - CARET_TO_NAME - CARET_BOX - NAME_TO_CARET - x; + let set_galley = crate::widgets::elided(&painter, set_name, NAME_SIZE, tokens.text, set_room); let set_width = set_galley.size().x; painter.galley(pos2(x, center_y - set_galley.size().y / 2.0), set_galley, tokens.text); x += set_width + NAME_TO_CARET; let map_caret = caret(ui, &painter, &tokens, x, center_y, "map_caret", tr("Switch Mesh Map")); x += CARET_BOX + CARET_TO_NAME; - painter.text(pos2(x, center_y), Align2::LEFT_CENTER, tr(baked_map_label(selected)), semibold(NAME_SIZE), tokens.text_strong); + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, map_name, semibold(NAME_SIZE), tokens.text_strong); egui::Popup::menu(&set_caret).show(|ui| { for (set_index, name) in set_names.iter().enumerate() { diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs index 4c358962..af8f4732 100644 --- a/crates/ui-egui/src/bake_mode/live_preview.rs +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -231,7 +231,7 @@ fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) { app.live_preview.cancel(); app.live_preview.made_from = input(app, target, size); - let mut task = match app.session.bake_task(target.set) { + let mut task = match app.session.bake_task_only(target.set, target.map) { Ok(task) => task, Err(error) => { // Once, not on every change while it stays unbakeable @@ -245,7 +245,6 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarg }; app.live_preview.cannot_bake = false; - task.settings.maps.select([target.map]); let own = task.settings.common.resolution; let size = if own.pixels() < size.pixels() { own } else { size }; task.settings.common.resolution = size; diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index 433cbb98..0cba2eeb 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -3,13 +3,13 @@ use std::sync::{Arc, Weak}; use egui::{ColorImage, TextureHandle, TextureOptions}; use texturecraft_engine::Session; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::core::{BakedMap, BlockScales}; /// Side of a thumbnail's texture, in pixels (twice the row's square, for high-density screens) const THUMBNAIL_PIXELS: u32 = 44; -/// A thumbnail's texture, with the baked data and the working size it was drawn from -type Thumbnail = (Weak>, (u32, u32), TextureHandle); +/// A thumbnail's texture, with the baked data, the working size and the UV tiles' scales it was drawn from +type Thumbnail = (Weak>, (u32, u32), BlockScales, TextureHandle); /// The Mesh Map Bakers rows' thumbnails of the baked maps, redrawn when a map is baked again #[derive(Default)] @@ -27,9 +27,10 @@ impl MapThumbnails { return None; }; - if let Some((drawn_from, working_size, texture)) = self.textures.get(&key) + if let Some((drawn_from, working_size, block_scales, texture)) = self.textures.get(&key) && drawn_from.ptr_eq(&Arc::downgrade(data)) && *working_size == cache.size + && *block_scales == cache.composite.block_scales { return Some(texture.clone()); } @@ -38,7 +39,7 @@ impl MapThumbnails { let side = THUMBNAIL_PIXELS as usize; let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); - self.textures.insert(key, (Arc::downgrade(data), cache.size, texture.clone())); + self.textures.insert(key, (Arc::downgrade(data), cache.size, cache.composite.block_scales.clone(), texture.clone())); Some(texture) } } @@ -63,6 +64,15 @@ mod tests { baked.maps.insert(map, Arc::new(rebaked)); assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "a new bake is drawn again"); + let mut tiled = + texturecraft_engine::Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + let tiled_set = &mut tiled.doc.project.texture_sets[0]; + let tile = *tiled_set.uv_tiles.iter().next().expect("the UDIM plane has UV tiles"); + tiled_set.tile_resolutions.insert(tile, 128); + let second = thumbnails.texture(&context, &session, 0, map).unwrap(); + session.caches[0].composite.block_scales = tiled_set.block_scales(); + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), second.id(), "a UV tile resolution edit draws it again"); + session.doc.baked.get_mut(&0).unwrap().maps.remove(&map); assert!(thumbnails.texture(&context, &session, 0, map).is_none(), "a map not baked has none"); } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 4fbe3505..72d3b1b9 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,4 +1,4 @@ -use egui::{Align, CornerRadius, FontId, Layout, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; +use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::ViewMode; @@ -17,6 +17,9 @@ use crate::theme::{Tokens, semibold}; const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; +/// Spacing of the points tested along a checkbox drag's path between two frames, well under a row's height +const CROSS_STEP: f32 = 4.0; + /// How far past its box a row's check takes clicks, so it is easy to hit const CHECK_HIT_AIR: f32 = 3.0; @@ -80,9 +83,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe let selected = super::selected_map(app.ui.selected_baked_map, settings); let check_drag_id = ui.scope_id().with("check_drag"); + let drag_from_id = ui.scope_id().with("check_drag_from"); let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); + let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag)).inner { + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } @@ -90,11 +95,16 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe // Kept through the frame of the release, so the click that ends a drag does not toggle its last checkbox back let is_held = ui.input(|input| input.pointer.primary_down()); + let pointer = ui.input(|input| input.pointer.latest_pos()); ui.data_mut(|data| { - if let Some(value) = check_drag.filter(|_| is_held) { + if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); + if let Some(pointer) = pointer { + data.insert_temp(drag_from_id, pointer); + } } else { data.remove_temp::(check_drag_id); + data.remove_temp::(drag_from_id); } }); } @@ -223,8 +233,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, what: &'static str, map: O } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses); returns whether the row itself was clicked -fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool, check_drag: &mut Option) -> bool { +/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +fn row( + app: &mut TextureCraftApp, + ui: &mut Ui, + map: BakedMap, + settings: &mut BakeSettings, + is_selected: bool, + check_drag: &mut Option, + drag_from: Option, +) -> bool { let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); @@ -243,7 +261,7 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); - let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag); + let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag, drag_from); if let Some(value) = check_drag.filter(|_| is_dragged_over) { settings.maps.set_enabled(map, value); } else if checkbox.clicked() && check_drag.is_none() { @@ -311,12 +329,24 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak response.clicked() } -/// Start a checkbox drag at a press on `checkbox`; returns whether a drag is in this row's checkbox column now (the whole row height counts) -fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option) -> bool { - if check_drag.is_none() && checkbox.is_pointer_button_down_on() { +/// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` +fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option, drag_from: Option) -> bool { + let is_primary = ui.input(|input| input.pointer.primary_down()); + if check_drag.is_none() && is_primary && checkbox.is_pointer_button_down_on() { *check_drag = Some(!is_enabled); } - check_drag.is_some() && ui.rect_contains_pointer(Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range())) + let Some(pointer) = ui.input(|input| input.pointer.latest_pos()).filter(|_| check_drag.is_some()) else { + return false; + }; + + let column = Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range()); + ui.rect_contains_pointer(column) || crosses(column, drag_from.unwrap_or(pointer), pointer) +} + +/// Whether the straight line from `from` to `to` passes through `rect`, so a row skipped between two frames still counts +fn crosses(rect: Rect, from: Pos2, to: Pos2) -> bool { + let steps = (from.distance(to) / CROSS_STEP).ceil().max(1.0) as u32; + (0..=steps).any(|step| rect.contains(from.lerp(to, step as f32 / steps as f32))) } /// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs index fc27b9e9..51ce9eef 100644 --- a/crates/ui-egui/src/bake_mode/set_picker.rs +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -4,7 +4,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKi use egui_phosphor::regular as icon; use serde_json::{Value, json}; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, Project}; use super::common_settings::antialiasing_label; use super::set_picker_purpose::SetPickerPurpose; @@ -66,7 +66,7 @@ impl SetPicker { pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; - let rows = picker.rows(app); + let rows = picker.rows(&app.session.doc.project, app.session.ts()); let active = app.session.ts(); let tokens = Tokens::get(ctx); let frame = egui::Frame::new() @@ -98,14 +98,8 @@ impl SetPicker { } /// The listed sets - fn rows(&self, app: &TextureCraftApp) -> Vec { - let project = &app.session.doc.project; - let active = app.session.ts(); - let source = match self.purpose { - // New additions take on the settings already shared, or the active set's when none are - SetPickerPurpose::Sync(group) => project.texture_sets.iter().find(|set| set.bake.sync.shares(group)).or(project.texture_sets.get(active)), - SetPickerPurpose::Copy { .. } => None, - }; + fn rows(&self, project: &Project, active: usize) -> Vec { + let chosen: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); project .texture_sets .iter() @@ -113,8 +107,19 @@ impl SetPicker { // A copy goes from the active set, so it isn't listed .filter(|(index, _)| matches!(self.purpose, SetPickerPurpose::Sync(_)) || *index != active) .map(|(index, set)| { - let note = match (self.purpose, source) { - (SetPickerPurpose::Sync(group), Some(source)) if !set.bake.sync.shares(group) => differing_values(&set.bake, &source.bake, group), + let note = match self.purpose { + // What the set would take on OK when ticked: the source `bake.sync` picks from the ticked sets with this one among them + SetPickerPurpose::Sync(group) if !set.bake.sync.shares(group) => { + let mut members = chosen.clone(); + if let Err(slot) = members.binary_search(&index) { + members.insert(slot, index); + } + project + .bake_sync_source(group, &members, active) + .filter(|source| *source != index) + .and_then(|source| project.texture_sets.get(source)) + .and_then(|source| differing_values(&set.bake, &source.bake, group)) + } _ => None, }; SetPickerRow { index, name: set.name.clone(), note } @@ -261,7 +266,7 @@ fn leaf_count(patch: &Value) -> usize { mod tests { use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; - use super::differing_values; + use super::{SetPicker, SetPickerPurpose, differing_values}; #[test] fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { @@ -287,4 +292,25 @@ mod tests { assert_eq!(differing_values(&set, &source, BakeSyncGroup::Common), None); assert_eq!(differing_values(&set, &source, BakeSyncGroup::Map(BakedMap::AmbientOcclusion)).as_deref(), Some("1 differing setting")); } + + #[test] + fn the_note_compares_with_the_set_the_sync_will_take_settings_from() { + let ao = BakeSyncGroup::Map(BakedMap::AmbientOcclusion); + let mut project = texturecraft_engine::sample_session(256, 64).unwrap().doc.project; + let third = project.texture_sets[1].clone(); + project.texture_sets.push(third); + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake = BakeSettings::default(); + set.bake.sync.set_shares(ao, index == 0); + } + project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + + // Set 0 leaves the group and sets 1 and 2 join with set 1 active: set 2 takes set 1's values, not set 0's + let picker = SetPicker { purpose: SetPickerPurpose::Sync(ao), chosen: vec![false, true, true] }; + let rows = picker.rows(&project, 1); + let note = |index: usize| rows.iter().find(|row| row.index == index).and_then(|row| row.note.clone()); + + assert_eq!(note(2).as_deref(), Some("1 differing setting")); + assert_eq!(note(1), None, "the source itself has nothing to take"); + } } diff --git a/crates/ui-egui/src/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs index 37ac21df..09716f9a 100644 --- a/crates/ui-egui/src/high_poly_job.rs +++ b/crates/ui-egui/src/high_poly_job.rs @@ -50,7 +50,7 @@ impl TextureCraftApp { }); } - /// Add a loaded high poly to the session and start on the next file; drop them all once another project is open + /// Add a loaded high poly to the session (once no paint stroke is running) and start on the next file; drop them all once another project is open #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { let Some(job) = &self.high_poly_job else { return }; @@ -61,6 +61,11 @@ impl TextureCraftApp { } context.request_repaint_after(POLL_INTERVAL); + // A stroke's cancel or undo restores the document from its start, which would drop a high poly added during it + if self.session.stroke_active() { + return; + } + let loaded = match job.answer.try_recv() { Ok(loaded) => loaded, Err(TryRecvError::Empty) => return, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1dcf34e..a0c23f0c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -814,12 +814,12 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); - match self.session.bake_task(set_index) { - Ok(mut task) => { - if let Some(map) = only { - task.settings.maps.select([map]); - } - + let task = match only { + Some(map) => self.session.bake_task_only(set_index, map), + None => self.session.bake_task(set_index), + }; + match task { + Ok(task) => { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs index 69a34386..8563df58 100644 --- a/crates/ui-egui/src/property_sheet/file_list.rs +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -99,14 +99,8 @@ impl PropertySheet<'_> { let name = painter.layout_job(job); painter.galley(pos2(rect.left() + NAME_LEFT, name_y - name.size().y / 2.0), name, name_color); if let Some(folder) = row.folder { - let shown = shortened_folder(&painter, folder, words_right - rect.left() - NAME_LEFT); - painter.text( - pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER), - Align2::LEFT_CENTER, - shown, - FontId::proportional(SMALL_TEXT_SIZE), - tokens.text_dim, - ); + let shown = folder_galley(&painter, folder, words_right - rect.left() - NAME_LEFT, tokens.text_dim); + painter.galley(pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER - shown.size().y / 2.0), shown, tokens.text_dim); } let words = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(words_right, rect.bottom())); @@ -135,6 +129,11 @@ impl PropertySheet<'_> { } } +/// `folder` shortened to fit `room`, cut with "…" when even its first and last folders are too wide +fn folder_galley(painter: &egui::Painter, folder: &str, room: f32, color: egui::Color32) -> std::sync::Arc { + crate::widgets::elided(painter, shortened_folder(painter, folder, room), SMALL_TEXT_SIZE, color, room) +} + /// `folder` with folders after its first one left out, from the second on, until it fits in `room` fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String { let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), egui::Color32::WHITE).size().x <= room; @@ -150,3 +149,25 @@ fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String } shown } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_folder_too_long_even_when_shortened_is_cut_to_its_room() { + let room = 120.0; + let folder = format!("C:\\{}", "W".repeat(80)); + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(folder_galley(ui.painter(), &folder, room, egui::Color32::WHITE)); + }); + + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert!(galley.size().x <= room); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 848543c9..89c6e301 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -151,7 +151,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() // A change that doesn't come from the panel: a script, an undo or a synced set let before = picture(&harness); harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); - let changed = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + let changed = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); assert!(changed, "the settings change brings a new picture"); // The same file loaded again: same name, new geometry @@ -162,7 +162,12 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() } session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); let before = picture(&harness); - let reloaded = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + let reloaded = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); assert!(reloaded, "high poly load {index} brings a new picture"); } } + +/// True when the preview holds a picture other than `before`, which the caller keeps alive so its address can't be reused +fn is_new(now: Option>>, before: Option<&std::sync::Arc>>) -> bool { + now.is_some_and(|now| before.is_none_or(|before| !std::sync::Arc::ptr_eq(&now, before))) +} diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs index ce17536c..8a03a411 100644 --- a/crates/ui-egui/tests/it/bake_map_rows.rs +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -1,4 +1,4 @@ -//! The Mesh Map Bakers rows: a drag down the checkboxes gives each the state the first one took +//! The Mesh Map Bakers rows: a primary drag down the checkboxes gives each the state the first one took use egui::{Event, Modifiers, PointerButton, Role}; use egui_kittest::Harness; @@ -52,6 +52,39 @@ fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { assert_eq!(enabled(&harness), expected, "the three rows are unchecked, the release does not check the last one again"); } +#[test] +fn a_drag_that_jumps_past_a_row_between_two_frames_still_unchecks_it() { + let mut harness = harness(); + let [from, _, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(to); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "World Space Normal, between Normal and ID, is unchecked too"); +} + +#[test] +fn holding_the_secondary_button_on_a_checkbox_leaves_it_alone() { + let mut harness = harness(); + let at = checkbox_center(&harness, DRAGGED[1].1); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(3); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + assert_eq!(enabled(&harness), BakedMap::ALL); +} + #[test] fn a_click_on_one_checkbox_still_toggles_only_that_row() { let mut harness = harness(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 2339512d..51a543ed 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -450,6 +450,17 @@ fn the_breadcrumb_switches_the_shown_map() { assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } +#[test] +fn a_long_texture_set_name_leaves_the_map_switcher_and_restore_defaults_in_the_breadcrumb() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().session.doc.project.texture_sets[0].name = "W".repeat(200); + harness.run_steps(3); + + let switcher = harness.get_by_label("Switch Mesh Map").rect(); + let restore = harness.get_by_role_and_label(Role::Button, "Restore Defaults").rect(); + assert!(switcher.right() <= restore.left(), "the map switcher stays left of Restore Defaults"); +} + #[test] fn curvature_controls_follow_the_method_and_grey_out_by_their_switches() { let mut harness = harness(Some(BakedMap::Curvature)); diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs index 4808c98c..c332cb95 100644 --- a/crates/ui-egui/tests/it/high_poly_loading.rs +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::state::Mode; const TRIANGLE_OBJ: &str = "o Part_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; /// Longest the test waits for the worker const LOAD_TIMEOUT: Duration = Duration::from_secs(60); +/// Frames (5 ms apart) a stroke stays open while a high poly loads +const STROKE_FRAMES: usize = 200; /// A bake-mode app with Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { @@ -95,3 +97,30 @@ fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { assert_eq!(session.apply_high_poly_load(load), "2_part.obj", "the name is made unique against the list of now"); assert_eq!(session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2, "both meshes bake"); } + +#[test] +fn a_high_poly_read_during_a_paint_stroke_is_added_after_it_and_survives_its_cancel() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-stroke-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + // Bake mode finishes strokes at once: the files go on loading after a switch back to painting + harness.state_mut().ui.mode = Mode::Painting; + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::json!({})).unwrap(); + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + harness.state_mut().load_high_polys([path]); + // Time for the worker to read one triangle + for _ in 0..STROKE_FRAMES { + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } + assert!(harness.state().session.stroke_active()); + assert!(high_names(&harness).is_empty(), "nothing is added while the stroke runs"); + + harness.state_mut().session.cancel_stroke(); + run_until_loaded(&mut harness); + assert_eq!(high_names(&harness), ["part.obj"]); + let _ = std::fs::remove_dir_all(folder); +} From d9f43048c56cb067a8faa9a17f760741c2191d47 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:02:05 +0000 Subject: [PATCH 38/54] Bake mode pass 2: review fixes, critic round 1 - Partner validation skips the edited sets and is set apart by blank lines - A drag whose pointer left the window starts a new line on its return - Tests for a legacy preset on synced sets and for each sync source rule --- crates/bake/src/test/fitted_cage.rs | 1 + crates/core/src/project.rs | 17 +++++++++++++++++ crates/engine/src/bake/mesh_map_command.rs | 5 ++++- crates/engine/src/bake/sync_command.rs | 13 +++++++++++++ crates/ui-egui/src/bake_mode/mesh_map_bakers.rs | 3 +++ crates/ui-egui/src/bake_mode/set_picker.rs | 2 +- 6 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 903c5c99..b6253f51 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -167,6 +167,7 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() low.append(&part("right_low", 1.0, 0.0, 4)); let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + // One material, so the cage shell covers both low parts for mesh in [&mut low, &mut high] { mesh.materials.truncate(1); for submesh in &mut mesh.submeshes { diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index b8e66cd4..db74dc2a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -804,6 +804,23 @@ mod tests { p } + #[test] + fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { + let group = BakeSyncGroup::Common; + let mut project = project(); + for name in ["Legs", "Arms"] { + project.texture_sets.push(TextureSet::new(name, 0, 512)); + } + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake.sync.set_shares(group, index == 2); + } + + assert_eq!(project.bake_sync_source(group, &[0, 1, 2], 0), Some(2), "a member already sharing the group"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 1), Some(1), "the active set when it joins"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 2), Some(0), "else the first member"); + assert_eq!(project.bake_sync_source(group, &[], 0), None); + } + fn paint(p: &mut Project, name: &str) -> Layer { Layer::new(p.alloc_id(), name, LayerKind::Paint, &Channel::DEFAULT_SET) } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 3e544857..b52268a4 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -137,6 +137,7 @@ impl Session { if let Some(map) = only { settings.maps.select([map]); } + // Read from the maps that bake, so a map baked alone while unchecked still gets the colours let needs_low_color = settings.maps.opacity.is_enabled || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); @@ -775,10 +776,12 @@ fn with_sync_partners( } } } + // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max - for (partner, settings) in &next { + for (partner, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; } + next.extend(targets); Ok(next.into_iter().collect()) } diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs index 88018b6f..cd6ceb0c 100644 --- a/crates/engine/src/bake/sync_command.rs +++ b/crates/engine/src/bake/sync_command.rs @@ -151,6 +151,9 @@ mod tests { use crate::{execute, sample_session}; use texturecraft_core::BakeSettings; + /// A dilation only presets may hold, above what an edit may set + const LEGACY_DILATION: u32 = 200; + fn session() -> Session { let session = sample_session(128, 32).unwrap(); assert_eq!(session.set_count(), 2); @@ -274,4 +277,14 @@ mod tests { assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum"); assert_eq!(session.doc.project.texture_sets, before); } + + #[test] + fn a_preset_with_a_legacy_value_loads_on_a_set_sharing_it() { + let mut session = session(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = LEGACY_DILATION; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "model": preset, "preset": true })).unwrap(); + assert_eq!(bake(&session, 1).common.dilation, LEGACY_DILATION, "set 1 shares Common Settings with set 0"); + } } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 72d3b1b9..b235b154 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -99,8 +99,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.data_mut(|data| { if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); + // A pointer back from outside the window starts a new line, so rows it never crossed stay as they were if let Some(pointer) = pointer { data.insert_temp(drag_from_id, pointer); + } else { + data.remove_temp::(drag_from_id); } } else { data.remove_temp::(check_drag_id); diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs index 51ce9eef..27fbcecf 100644 --- a/crates/ui-egui/src/bake_mode/set_picker.rs +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -66,8 +66,8 @@ impl SetPicker { pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; - let rows = picker.rows(&app.session.doc.project, app.session.ts()); let active = app.session.ts(); + let rows = picker.rows(&app.session.doc.project, active); let tokens = Tokens::get(ctx); let frame = egui::Frame::new() .fill(tokens.panel) From 3ec569def7e9d87d971b6b461383b78e52939e7d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:18:40 +0000 Subject: [PATCH 39/54] Generators: review fixes for the previews (an image read twice goes once and the orb gets its own back, pictures of a deleted generator dropped) --- crates/engine/src/orb_preview.rs | 6 +-- crates/ui-egui/src/generator_panel.rs | 9 +++- .../ui-egui/src/generator_preview_window.rs | 17 +++++--- crates/ui-egui/src/shelf_preview.rs | 43 ++++++++++++++++--- crates/ui-egui/src/thumbs.rs | 5 +++ crates/ui-egui/tests/it/generator_panel.rs | 11 +++-- 6 files changed, 69 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index e40366e1..eb096fe9 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -16,7 +16,6 @@ use texturecraft_texel::TILE; pub use crate::mask_preview_pixel::MaskPreviewPixel; pub use crate::material_preview_pixel::MaterialPreviewPixel; - use crate::orb_camera::OrbCamera; use crate::preview::Sample; use crate::session::Document; @@ -123,13 +122,14 @@ impl OrbPreview { let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); let pixels = self.generator_of(with_sample_image(generator), size); - // The orb's own images come back: the next preview reads only what it brings - for (name, previous) in replaced { + // The orb's own images come back, last replaced first so a name given twice ends as it began: the next preview reads only what it brings + for (name, previous) in replaced.into_iter().rev() { match previous { Some(previous) => self.session.images.insert(name, previous), None => self.session.images.remove(&name), }; } + pixels } diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index b07914a4..ba425222 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -1,6 +1,6 @@ //! A generator effect's properties, laid out like the reference app's: its slot, Parameters, Image inputs, Resolution, Attributes -use egui::{CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; +use egui::{CornerRadius, CursorIcon, Painter, Rect, Role, Sense, Stroke, StrokeKind, TextureHandle, WidgetInfo}; use serde_json::json; use texturecraft_engine::core::{ CookResolution, Generator, GeneratorKind, KindControls, LayerId, LightParameters, ResolutionMode, SectionParameters, WearParameters, @@ -18,6 +18,9 @@ use crate::property_sheet::PropertySheet; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +/// The outline on the preview while it can open enlarged under the pointer, or is open, in points +const ENLARGE_OUTLINE_WIDTH: f32 = 1.0; + /// The width the preview's orb is rendered at, in pixels: sharp at twice the preview's size const PREVIEW_ORB_PX: usize = 256; @@ -133,10 +136,12 @@ fn enlarge_on_click(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, id let response = sheet.ui.interact(rect, sheet.ui.make_persistent_id(("generator_preview_enlarge", id)), Sense::click()).on_hover_cursor(CursorIcon::ZoomIn); let open = app.ui.windows.generator_preview == Some(id); response.widget_info(|| WidgetInfo::selected(Role::Button, true, open, tr("Enlarge preview"))); + if response.hovered() || response.has_focus() || open { let tokens = Tokens::get(sheet.ui.ctx()); - sheet.ui.painter().rect_stroke(rect, 0.0, Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); + sheet.ui.painter().rect_stroke(rect, CornerRadius::ZERO, Stroke::new(ENLARGE_OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); } + if response.clicked() { let ctx = sheet.ui.ctx().clone(); crate::generator_preview_window::toggle(app, &ctx, id, rect); diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index fbdc227b..a67f4456 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -1,6 +1,6 @@ //! A generator's preview enlarged in a tool window, following its settings while they change -use egui::{Rect, Sense, pos2}; +use egui::{Align2, Color32, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; use texturecraft_engine::core::{EffectKind, LayerId}; use crate::TextureCraftApp; @@ -30,6 +30,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(EffectKind::Generator(generator)) => generator.clone(), _ => { app.ui.windows.generator_preview = None; + app.thumbs.forget_generator_pictures(effect); return; } }; @@ -37,24 +38,28 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let set = ShelfPreview::generator_set(&generator, &app.session.images); let texture = app.thumbs.generator_set_picture(ctx, effect, set, PICTURE_PX); let tokens = Tokens::get(ctx); + + // It first opens beside the small preview it was asked from, then stays where it is moved let mut open = true; let beside = ctx.data(|data| data.get_temp::(anchor_id())).map_or(ctx.content_rect().center(), |small| pos2(small.left() - BESIDE_GAP, small.center().y)); let window = crate::windows::window("generator_preview", tr(generator.kind.label()), &mut open).default_width(DEFAULT_WIDTH); - window.default_pos(beside).pivot(egui::Align2::RIGHT_CENTER).show(ctx, |ui| { + window.default_pos(beside).pivot(Align2::RIGHT_CENTER).show(ctx, |ui| { let side = ui.available_width().max(MIN_SIDE); - let (rect, response) = ui.allocate_exact_size(egui::vec2(side, side), Sense::hover()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Preview"))); + let (rect, response) = ui.allocate_exact_size(vec2(side, side), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, tr("Preview"))); + match &texture { Some(texture) => { - ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + ui.painter().image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } None => { - ui.painter().rect_filled(rect, 0.0, tokens.button); + ui.painter().rect_filled(rect, CornerRadius::ZERO, tokens.button); ctx.request_repaint_after(PICTURE_POLL); } } }); + if !open { app.ui.windows.generator_preview = None; } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index f6bad1cb..4ca10aef 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -65,13 +65,17 @@ impl ShelfPreview { /// `generator` as set, with the images it reads from `store` pub fn generator_set(generator: &Generator, store: &ImageStore) -> ShelfPreview { - let images = generator - .sources() - .filter_map(|source| match source { - texturecraft_engine::core::Source::Image { name, .. } => store.get(name).map(|image| (name.clone(), image.clone())), - _ => None, - }) - .collect(); + // An image read in two slots goes once + let mut images: Vec<(String, Arc)> = Vec::new(); + for source in generator.sources() { + if let texturecraft_engine::core::Source::Image { name, .. } = source + && let Some(image) = store.get(name) + && !images.iter().any(|(taken, _)| taken == name) + { + images.push((name.clone(), image.clone())); + } + } + ShelfPreview::GeneratorSet { generator: Box::new(generator.clone()), images } } @@ -193,6 +197,31 @@ mod tests { use super::*; + #[test] + fn a_generator_preview_is_keyed_by_its_settings_and_reads_an_image_once() { + let image = Arc::new(ImageRes::new(1, 1, vec![[0.5; 4]], false)); + let store: ImageStore = [("grunge.png".to_owned(), image)].into(); + let dirt = |grunge: Option<&str>, invert| Generator { + grunge: grunge.map(texturecraft_engine::core::Source::image), + micro: None, + invert, + ..Generator::new(GeneratorKind::Dirt) + }; + + let plain = ShelfPreview::generator_set(&dirt(None, false), &store); + assert_eq!(plain.key(), ShelfPreview::generator_set(&dirt(None, false), &store).key(), "the same settings share a picture"); + assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(None, true), &store).key(), "another setting is another picture"); + assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(Some("grunge.png"), false), &store).key(), "so is an image read"); + + let mut both = dirt(Some("grunge.png"), false); + both.texture = Some(Box::new(texturecraft_engine::core::TextureLayer { + source: Some(texturecraft_engine::core::Source::image("grunge.png")), + ..Default::default() + })); + let ShelfPreview::GeneratorSet { images, .. } = ShelfPreview::generator_set(&both, &store) else { panic!("a generator preview") }; + assert_eq!(images.len(), 1, "an image in two slots goes once"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn named_brush_files_render_their_saved_settings() { diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 38552ce4..08a7d5ae 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -330,6 +330,11 @@ impl Thumbs { shown } + /// Drops the pictures kept for generator effect `effect`, gone from the project + pub fn forget_generator_pictures(&mut self, effect: u64) { + self.set_pictures.retain(|(kept, _), _| *kept != effect); + } + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 245bffcd..f28b20a5 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -545,10 +545,13 @@ fn enlarged_preview_snapshots() { let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); click_live(&mut harness, Role::Button, "Enlarge preview"); - // The pictures render on the preview worker - for _ in 0..60 { - harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + // The pictures render on the preview worker: up to three seconds of frames + const WAITS: usize = 60; + const STEPS_PER_WAIT: usize = 4; + const WAIT: std::time::Duration = std::time::Duration::from_millis(50); + for _ in 0..WAITS { + harness.run_steps(STEPS_PER_WAIT); + std::thread::sleep(WAIT); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; From a7e15a489cc97d503a9a889e2ec47c5c1b2b3841 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:07 +0000 Subject: [PATCH 40/54] Generators: preview review round (pictures of any removed generator dropped, a test for the orb's restored images, imports) --- crates/engine/src/orb_preview.rs | 20 ++++++++++++++++++- .../ui-egui/src/generator_preview_window.rs | 15 +++++++++----- crates/ui-egui/src/shelf_preview.rs | 18 ++++++----------- crates/ui-egui/src/thumbs.rs | 17 +++++++++++++--- crates/ui-egui/tests/it/generator_panel.rs | 19 ++++++++++-------- 5 files changed, 60 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index eb096fe9..c63aa524 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -122,7 +122,7 @@ impl OrbPreview { let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect(); let pixels = self.generator_of(with_sample_image(generator), size); - // The orb's own images come back, last replaced first so a name given twice ends as it began: the next preview reads only what it brings + // Restore in reverse so a name given twice ends as it began for (name, previous) in replaced.into_iter().rev() { match previous { Some(previous) => self.session.images.insert(name, previous), @@ -267,6 +267,24 @@ mod tests { pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 } + #[test] + fn a_render_reading_an_image_twice_leaves_the_orbs_own_images() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let image = |value| Arc::new(ImageRes::new(1, 1, vec![[value; 4]], false)); + let own = image(0.1); + preview.session.images.insert("shared.png".into(), own.clone()); + + let brought = image(0.9); + let images = [("shared.png".into(), brought.clone()), ("shared.png".into(), brought.clone()), ("added.png".into(), brought)]; + preview.generator_reading(Generator::new(GeneratorKind::Dirt), &images, 0); + + assert!(preview.session.images.get("shared.png").is_some_and(|kept| Arc::ptr_eq(kept, &own)), "the orb's own image is back"); + assert!(!preview.session.images.contains_key("added.png"), "an image it lacked is gone again"); + } + #[test] fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); diff --git a/crates/ui-egui/src/generator_preview_window.rs b/crates/ui-egui/src/generator_preview_window.rs index a67f4456..48033859 100644 --- a/crates/ui-egui/src/generator_preview_window.rs +++ b/crates/ui-egui/src/generator_preview_window.rs @@ -1,6 +1,8 @@ //! A generator's preview enlarged in a tool window, following its settings while they change -use egui::{Align2, Color32, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; +use std::time::Duration; + +use egui::{Align2, Color32, Context, CornerRadius, Rect, Role, Sense, WidgetInfo, pos2, vec2}; use texturecraft_engine::core::{EffectKind, LayerId}; use crate::TextureCraftApp; @@ -21,16 +23,19 @@ const MIN_SIDE: f32 = 160.0; const BESIDE_GAP: f32 = 24.0; /// How soon a picture still rendering is looked for again -const PICTURE_POLL: std::time::Duration = std::time::Duration::from_millis(100); +const PICTURE_POLL: Duration = Duration::from_millis(100); /// The open enlarged preview, if any: closed by its ×, and when its generator is gone -pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &Context) { + // Pictures of generators gone from the project are dropped, whether or not their window is open + let project = &app.session.doc.project; + app.thumbs.keep_generator_pictures(|effect| project.effect(LayerId(effect)).is_some()); + let Some(effect) = app.ui.windows.generator_preview else { return }; let generator = match app.session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) { Some(EffectKind::Generator(generator)) => generator.clone(), _ => { app.ui.windows.generator_preview = None; - app.thumbs.forget_generator_pictures(effect); return; } }; @@ -66,7 +71,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } /// Opens generator effect `effect`'s enlarged preview beside its small one at `small`, or closes it when it is the one open -pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &egui::Context, effect: u64, small: Rect) { +pub(crate) fn toggle(app: &mut TextureCraftApp, ctx: &Context, effect: u64, small: Rect) { ctx.data_mut(|data| data.insert_temp(anchor_id(), small)); let open = &mut app.ui.windows.generator_preview; *open = if *open == Some(effect) { None } else { Some(effect) }; diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 4ca10aef..4c6026ca 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::compose::ImageStore; -use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind}; +use texturecraft_engine::core::{CurvatureMode, Generator, GeneratorKind, ProceduralKind, Source}; use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; @@ -68,7 +68,7 @@ impl ShelfPreview { // An image read in two slots goes once let mut images: Vec<(String, Arc)> = Vec::new(); for source in generator.sources() { - if let texturecraft_engine::core::Source::Image { name, .. } = source + if let Source::Image { name, .. } = source && let Some(image) = store.get(name) && !images.iter().any(|(taken, _)| taken == name) { @@ -195,18 +195,15 @@ mod tests { use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::PRESETS; + use texturecraft_engine::core::TextureLayer; + use super::*; #[test] fn a_generator_preview_is_keyed_by_its_settings_and_reads_an_image_once() { let image = Arc::new(ImageRes::new(1, 1, vec![[0.5; 4]], false)); let store: ImageStore = [("grunge.png".to_owned(), image)].into(); - let dirt = |grunge: Option<&str>, invert| Generator { - grunge: grunge.map(texturecraft_engine::core::Source::image), - micro: None, - invert, - ..Generator::new(GeneratorKind::Dirt) - }; + let dirt = |grunge: Option<&str>, invert| Generator { grunge: grunge.map(Source::image), micro: None, invert, ..Generator::new(GeneratorKind::Dirt) }; let plain = ShelfPreview::generator_set(&dirt(None, false), &store); assert_eq!(plain.key(), ShelfPreview::generator_set(&dirt(None, false), &store).key(), "the same settings share a picture"); @@ -214,10 +211,7 @@ mod tests { assert_ne!(plain.key(), ShelfPreview::generator_set(&dirt(Some("grunge.png"), false), &store).key(), "so is an image read"); let mut both = dirt(Some("grunge.png"), false); - both.texture = Some(Box::new(texturecraft_engine::core::TextureLayer { - source: Some(texturecraft_engine::core::Source::image("grunge.png")), - ..Default::default() - })); + both.texture = Some(Box::new(TextureLayer { source: Some(Source::image("grunge.png")), ..TextureLayer::default() })); let ShelfPreview::GeneratorSet { images, .. } = ShelfPreview::generator_set(&both, &store) else { panic!("a generator preview") }; assert_eq!(images.len(), 1, "an image in two slots goes once"); } diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 08a7d5ae..da1e1712 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -330,9 +330,9 @@ impl Thumbs { shown } - /// Drops the pictures kept for generator effect `effect`, gone from the project - pub fn forget_generator_pictures(&mut self, effect: u64) { - self.set_pictures.retain(|(kept, _), _| *kept != effect); + /// Keeps the generator pictures only of the effects `exists` still finds + pub fn keep_generator_pictures(&mut self, exists: impl Fn(u64) -> bool) { + self.set_pictures.retain(|(effect, _), _| exists(*effect)); } /// Sphere thumbnail of library filter `id` applied to a sample material @@ -502,6 +502,17 @@ mod tests { static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); + #[test] + fn the_pictures_of_a_removed_generator_go() { + let mut thumbs = Thumbs::default(); + thumbs.set_pictures.insert((1, 8), (None, None)); + thumbs.set_pictures.insert((2, 8), (None, None)); + + thumbs.keep_generator_pictures(|effect| effect == 2); + + assert!(!thumbs.set_pictures.contains_key(&(1, 8)) && thumbs.set_pictures.contains_key(&(2, 8))); + } + #[test] fn a_generator_picture_shows_the_last_one_while_the_next_renders() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index f28b20a5..931f469a 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -1,5 +1,8 @@ //! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator +use std::path::PathBuf; +use std::time::Duration; + use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -279,7 +282,7 @@ fn micro_details_show_their_settings_once_switched_on() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let (mut harness, effect) = harness(true); harness.run_steps(12); @@ -312,7 +315,7 @@ fn generator_panel_snapshots() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn full_set_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let kinds = ["edgeWear", "fiberGlassEdgeWear", "dirt", "direction", "curvature", "ambientOcclusion", "position", "worldSpaceNormals"]; for kind in kinds { @@ -324,7 +327,7 @@ fn full_set_panel_snapshots() { // The orbs render on the preview worker for _ in 0..40 { harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -375,7 +378,7 @@ fn the_texture_slot_takes_a_uniform_value_and_empties_again() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn texture_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); for kind in ["position", "ambientOcclusion"] { let (mut harness, _) = harness_with(true, json!({"generator": kind, "useTexture": true, "textureOpacity": 0.6, "textureBlend": "normal"})); @@ -485,7 +488,7 @@ fn the_color_rows_follow_the_color_mode() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn new_kind_panel_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let gradient = json!([[0.02, 0.02, 0.02], [0.6, 0.12, 0.03], [0.8, 0.8, 0.8]]); let kinds = [ @@ -508,7 +511,7 @@ fn new_kind_panel_snapshots() { // The orbs render on the preview worker for _ in 0..40 { harness.run_steps(4); - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(Duration::from_millis(50)); } for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { harness.state_mut().ui.prefs.brightness = brightness; @@ -540,7 +543,7 @@ fn the_preview_opens_enlarged_in_its_own_window() { #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn enlarged_preview_snapshots() { - let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let directory = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); std::fs::create_dir_all(&directory).unwrap(); let (mut harness, _) = harness_with(true, json!({"generator": "edgeWear", "seed": 12})); click_live(&mut harness, Role::Button, "Enlarge preview"); @@ -548,7 +551,7 @@ fn enlarged_preview_snapshots() { // The pictures render on the preview worker: up to three seconds of frames const WAITS: usize = 60; const STEPS_PER_WAIT: usize = 4; - const WAIT: std::time::Duration = std::time::Duration::from_millis(50); + const WAIT: Duration = Duration::from_millis(50); for _ in 0..WAITS { harness.run_steps(STEPS_PER_WAIT); std::thread::sleep(WAIT); From 2f5b8025302bc6edfd9f5435e8ee45381326bf33 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:21 +0000 Subject: [PATCH 41/54] Shelf preview: test imports in one group --- crates/ui-egui/src/shelf_preview.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index 4c6026ca..7fc3ac1c 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -190,13 +190,12 @@ fn settings_hash(generator: &Generator, images: &[(String, Arc)]) -> u #[cfg(test)] mod tests { + use texturecraft_engine::core::TextureLayer; use texturecraft_engine::filter_lib::FILTERS; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::PRESETS; - use texturecraft_engine::core::TextureLayer; - use super::*; #[test] From 1d7669c0384a11cb3c43d2ee9c38300c0bb39667 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:41 +0000 Subject: [PATCH 42/54] Bake mode pass 2: synced sets check only that their values agree The edited set's checks already bound every value it changes, so a legacy value it may keep (flat parameters, presets) also reaches the sets sharing it; a synced set is refused only when a copied value clashes with its own, such as a minimum above its maximum. Also fixes the new tests' sample resolution and a clippy lint --- crates/engine/src/bake/mesh_map_command.rs | 20 ++++++++----------- .../ui-egui/src/bake_mode/map_thumbnails.rs | 2 +- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index b52268a4..0edd341b 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -746,19 +746,14 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { let targets = updated_settings(session, params, command)?; let sets = targets.iter().map(|(index, _)| *index).collect(); - let next = with_sync_partners(&session.doc.project, targets, command, boolp(params, "preset") == Some(true))?; + let next = with_sync_partners(&session.doc.project, targets, command)?; super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } -/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's settings come out invalid (`from_preset`: preset limits apply) -fn with_sync_partners( - project: &texturecraft_core::Project, - targets: Vec<(usize, BakeSettings)>, - command: &str, - from_preset: bool, -) -> Result> { +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's values come out inconsistent +fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { let mut next: BTreeMap = BTreeMap::new(); for (target, settings) in &targets { let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; @@ -769,6 +764,7 @@ fn with_sync_partners( for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| partner != target) { let Some(set) = project.texture_sets.get(partner) else { continue }; let entry = next.entry(partner).or_insert_with(|| set.bake.clone()); + let mut model = json!(entry); model_patch::apply_patch(&mut model, &changed, command)?; let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; @@ -777,9 +773,9 @@ fn with_sync_partners( } } - // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max - for (partner, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { - validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; + // The target's checks already bound each value it changed, but beside a partner's other values one can clash: min above the partner's max + for (_, settings) in next.iter().filter(|(partner, _)| targets.iter().all(|(target, _)| target != *partner)) { + validate_model_settings(settings, command, false, Some(settings))?; } next.extend(targets); @@ -897,7 +893,7 @@ mod bake_task_tests { #[test] fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() { - let mut session = crate::sample_session(64, 64).unwrap(); + let mut session = crate::sample_session(128, 64).unwrap(); session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); let colours = Arc::new(vec![None]); let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index 0cba2eeb..191cf805 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -67,7 +67,7 @@ mod tests { let mut tiled = texturecraft_engine::Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); let tiled_set = &mut tiled.doc.project.texture_sets[0]; - let tile = *tiled_set.uv_tiles.iter().next().expect("the UDIM plane has UV tiles"); + let tile = *tiled_set.uv_tiles.first().expect("the UDIM plane has UV tiles"); tiled_set.tile_resolutions.insert(tile, 128); let second = thumbnails.texture(&context, &session, 0, map).unwrap(); session.caches[0].composite.block_scales = tiled_set.block_scales(); From e0c4fc49e9099bd39709c08ced2116d6a78e49f1 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:36:37 +0000 Subject: [PATCH 43/54] Map-alone bake test: clear the colours the sample read when it baked --- crates/engine/src/bake/mesh_map_command.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 0edd341b..8d95ce1e 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -896,7 +896,9 @@ mod bake_task_tests { let mut session = crate::sample_session(128, 64).unwrap(); session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); let colours = Arc::new(vec![None]); - let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); + // The sample bakes when made, which already read the colours + session.doc.bake_meshes.low_base_color = Default::default(); + assert!(session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())).is_ok()); assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours"); let task = session.bake_task_only(0, BakedMap::Opacity).unwrap(); From c4958764f1a508846087967a00663b855fe69e92 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:21:35 +0000 Subject: [PATCH 44/54] Automatic cage: fit along a vertex's own normal where welding cancelled it Parts welded back to back (or a double-sided sheet) sum to a zero averaged normal; the transfer ray there falls back to the surface normal, so the fit now measures along the vertex's own normal too instead of finding no direction and keeping only the padding --- crates/bake/src/cage/fitted_cage.rs | 23 +++++++-- crates/bake/src/test/fitted_cage.rs | 76 ++++++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs index 54bbde47..05d205f8 100644 --- a/crates/bake/src/cage/fitted_cage.rs +++ b/crates/bake/src/cage/fitted_cage.rs @@ -22,13 +22,15 @@ pub(crate) struct FittedCage { } impl FittedCage { - /// Fit the cage of `request`'s low poly around `high` along `ray_normals`: each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { let low = request.mesh; let keys = NameKeys::of(request, high); let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); let mut reach: Vec> = vec![None; welded_count]; let mut widen = |vertex: usize, height: f32| { if let Some(distances) = reach.get_mut(welded(vertex)) { @@ -37,12 +39,12 @@ impl FittedCage { } }; - for (vertex, height) in heights_at_low_vertices(low, high, ray_normals, &keys, extent.diagonal).into_iter().enumerate() { + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { if let Some(height) = height { widen(vertex, height); } } - for (triangle, height) in heights_of_high_vertices(request, high, ray_normals, &keys).into_iter().flatten() { + for (triangle, height) in heights_of_high_vertices(request, high, &fitting_normals, &keys).into_iter().flatten() { for corner in low.tri(triangle).into_iter().flatten() { widen(corner, height); } @@ -89,6 +91,21 @@ fn welded_within_groups(welded_indices: &[u32], vertex_keys: &[u32]) -> Vec .collect() } +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals(low: &Mesh, ray_normals: &[Vec3]) -> Vec { + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + /// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { low.positions diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index b6253f51..419b6fc4 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -1,6 +1,6 @@ use super::{covered_values, settings, transfer}; use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; -use texturecraft_core::{BakeSettings, BakedMap, CageType}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Bvh, Mesh, primitives}; @@ -36,6 +36,14 @@ fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(V shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() } +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + #[test] fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { let low = primitives::cube(1.0); @@ -142,7 +150,7 @@ fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { low.submeshes[0].name = "panel_low".into(); high.submeshes[0].name = "door_high".into(); let mut bake_settings = automatic(&[BakedMap::Normal]); - bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; let heights = cage_heights(&low, &high, &bake_settings); @@ -167,15 +175,11 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() low.append(&part("right_low", 1.0, 0.0, 4)); let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); - // One material, so the cage shell covers both low parts for mesh in [&mut low, &mut high] { - mesh.materials.truncate(1); - for submesh in &mut mesh.submeshes { - submesh.material = 0; - } + one_material(mesh); } let mut bake_settings = automatic(&[BakedMap::Normal]); - bake_settings.high_poly.match_mode = texturecraft_core::MeshMatchMode::ByMeshName; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; let heights = cage_heights(&low, &high, &bake_settings); @@ -185,3 +189,59 @@ fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); } } + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.chunks_exact_mut(3) { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} From d2a4b44a1d696316e789033d118a1c64cf1d4f4c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:33:19 +0000 Subject: [PATCH 45/54] Back-to-back cage test: chunk the indices with as_chunks_mut --- crates/bake/src/test/fitted_cage.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 419b6fc4..5c44dba6 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -203,7 +203,7 @@ fn parts_back_to_back_fit_their_cages_along_their_own_normals() { for normal in &mut mesh.normals { *normal = -*normal; } - for triangle in mesh.indices.chunks_exact_mut(3) { + for triangle in mesh.indices.as_chunks_mut::<3>().0 { triangle.swap(1, 2); } mesh From 333605327e437e29f8708d53efb696b58bfef677 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:57:21 +0000 Subject: [PATCH 46/54] Generators: a micro detail saved before Micro Details renders as saved while its generator stays on the earlier model MicroDetails.earlier marks a migrated {anchor, amount}: an earlier-model generator adds the anchor's height times the amount to its signal as #395 did; microAnchor/microAmount keep that reading on the earlier model, and any Micro Details control moves the generator onto the reference's controls and the anchor's curvature. --- crates/compose/src/eval.rs | 86 ++++++++++++++++++++--- crates/core/src/layer.rs | 32 ++++++++- crates/core/src/layer/micro_details.rs | 7 +- crates/engine/src/anchored_micro_edit.rs | 6 +- crates/engine/src/micro_params.rs | 1 + crates/engine/tests/it/content_effects.rs | 22 ++++++ 6 files changed, 140 insertions(+), 14 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a1a58358..a4c50ea2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -3463,6 +3463,7 @@ impl<'a, 'b> Texel<'a, 'b> { } let coords = self.coords(); + let earlier_micro = generator.earlier_micro().map_or(0.0, |(anchor, amount)| self.earlier_micro_detail(generator.kind, anchor, amount)); // Micro details saved on the earlier model add to its curvature and occlusion inputs too let signal = match (generator.kind, &generator.detail) { @@ -3470,7 +3471,7 @@ impl<'a, 'b> Texel<'a, 'b> { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let curvature = self.curvature_input(generator, maps); - self.curvature_detail(detail, sizes, curvature) + self.curvature_detail(detail, sizes, curvature, earlier_micro) } (GeneratorKind::EdgeWear, None) | (GeneratorKind::FiberGlassEdgeWear, _) => (self.curvature_input(generator, maps).unwrap_or(0.5) - 0.5) * 2.0, (GeneratorKind::Curvature, None) => self.curvature_input(generator, maps).unwrap_or(0.5), @@ -3492,6 +3493,11 @@ impl<'a, 'b> Texel<'a, 'b> { _, ) => 0.0, }; + let signal = if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { + signal + } else { + signal + earlier_micro + }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -3519,7 +3525,7 @@ impl<'a, 'b> Texel<'a, 'b> { let detail = generator.detail_in_use().unwrap_or_default(); let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { maps.sizes.as_deref() }; let curvature = self.curvature_input(generator, maps); - self.curvature_detail(&detail, sizes, curvature) + self.curvature_detail(&detail, sizes, curvature, 0.0) } GeneratorKind::AmbientOcclusion => self.occlusion_input(generator, maps).unwrap_or(1.0), GeneratorKind::Position => { @@ -3682,6 +3688,31 @@ impl<'a, 'b> Texel<'a, 'b> { } } + /// How a micro detail saved before Micro Details moves an earlier-model generator's signal at this texel: anchor point `anchor`'s height times `amount` (0 where the anchor is not evaluated yet), an edge where raised and a cavity where recessed + fn earlier_micro_detail(&self, kind: GeneratorKind, anchor: LayerId, amount: f32) -> f32 { + let response = self.anchor_value(anchor, Channel::Height, ChannelKind::Signed)[0].clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear | GeneratorKind::AmbientOcclusion => response, + + // Dirt gathers in dents + GeneratorKind::Dirt => -response, + + // Kinds the micro detail never moved, or without an earlier model + GeneratorKind::FiberGlassEdgeWear + | GeneratorKind::ThinAreas + | GeneratorKind::Position + | GeneratorKind::Direction + | GeneratorKind::WorldSpaceNormals + | GeneratorKind::ThreeDDistance + | GeneratorKind::ThreeDLinearGradient + | GeneratorKind::UvBorderDistance + | GeneratorKind::GrayscaleConversion + | GeneratorKind::DrippingRust + | GeneratorKind::UvRandomColor + | GeneratorKind::UvChecker => 0.0, + } + } + /// The generator's curvature input at this texel with what its micro details add fn curvature_input(&mut self, generator: &Generator, maps: &GeneratorMaps) -> Option { let curvature = self.generator_input(generator, BakedMap::Curvature)?; @@ -3715,16 +3746,20 @@ impl<'a, 'b> Texel<'a, 'b> { } } - /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { - let combine = |edges: f32, cavities: f32| match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given and an earlier micro detail's term (see [`Texel::earlier_micro_detail`]) as an edge where positive and a cavity where negative + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, earlier_micro: f32) -> f32 { + let combine = |edges: f32, cavities: f32| { + let edges = 1.0 - (1.0 - edges) * (1.0 - earlier_micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + earlier_micro.min(0.0)); + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } }; - // Without curvature to read the texel is flat: no edges or cavities + // Without curvature to read only an earlier micro detail supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let Some((baked_x, baked_y)) = self.baked_curvature_texel() else { return combine(0.0, 0.0) }; @@ -7208,6 +7243,37 @@ soft {soft:?}" } } + #[test] + fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { + const SAVED_AMOUNT: f32 = 0.25; + const FLAT_CURVATURE: f32 = 0.4; + let colors = |height: f32, curvature: f32, micro: bool| -> Vec { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![curvature; 64 * 64]))].into() }; + let low = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); + fixture.project.insert_layer(0, Layer::new(low, "Flat", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut fixture, low, EffectKind::Anchor); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let earlier = Generator { section: None, detail: None, level: 0.5, softness: 0.5, noise_amount: 0.0, ..Generator::new(GeneratorKind::Curvature) }; + let micro = MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, SAVED_AMOUNT).filter(|_| micro).map(Box::new); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(Generator { micro, ..earlier }))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + let composite = run(&fixture, None); + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + }; + + // The saved micro detail added the anchor's height times its amount to the curvature signal, even where the height is flat + for height in [0.0, 0.3, 0.6, 1.0] { + let saved = colors(0.0, FLAT_CURVATURE + height * SAVED_AMOUNT, false); + let loaded = colors(height, FLAT_CURVATURE, true); + let largest_change = saved.iter().zip(&loaded).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(largest_change < 1e-3, "height {height}: {largest_change}"); + } + } + #[test] fn fills_inside_folders_take_the_folders_scale_and_rotation_on_top_of_their_own() { // Nested folders (x2 turned 30, then x1.5 turned -10) around a procedural fill with a procedural mask fill diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 2e4371b5..ef7a535c 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -1274,9 +1274,18 @@ impl Generator { self.inputs.values().chain(self.texture.as_ref().and_then(|texture| texture.source.as_ref())).chain(self.grunge.as_ref()).chain(micro) } - /// The micro details as saved, when the generator computes with them: with a slot switched on, also on the earlier model where an anchor's micro detail saved before Micro Details reads (bring them into range before use: saved files are not trusted) + /// The micro details as saved, when the generator computes with them: with a slot switched on, except a micro detail saved before Micro Details on a generator still on the earlier model, which [`Generator::earlier_micro`] reads (bring them into range before use: saved files are not trusted) pub fn micro_in_use(&self) -> Option<&MicroDetails> { - self.micro.as_deref().filter(|micro| micro.in_use(self.kind)) + self.micro.as_deref().filter(|micro| micro.in_use(self.kind) && !(micro.earlier && self.on_earlier_model())) + } + + /// The anchor point and amount (0..1) of a micro detail saved before Micro Details, while the generator is still on the earlier model: its signal adds that anchor's height times the amount, as it did when saved + pub fn earlier_micro(&self) -> Option<(LayerId, f32)> { + let micro = self.micro.as_deref().filter(|micro| micro.earlier && micro.in_use(self.kind) && micro.height && self.on_earlier_model())?; + let Some(Source::Anchor { anchor, .. }) = µ.height_source else { return None }; + + let amount = micro.height_intensity / MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; + Some((*anchor, if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 })) } /// Whether the generator is on the level, softness and noise it had before the reference app's controls @@ -2832,6 +2841,25 @@ mod tests { assert!(without.micro.is_none(), "a kind without micro details drops it"); } + #[test] + fn a_micro_detail_saved_on_an_anchor_keeps_its_earlier_reading_until_the_generator_leaves_the_earlier_model() { + // Saved before the reference's controls too: on the earlier model + let earlier = Generator { section: None, ..Generator::new(GeneratorKind::Curvature) }; + let mut saved = serde_json::to_value(earlier).unwrap(); + saved["micro"] = serde_json::json!({"anchor": 9, "amount": 0.25}); + let generator: Generator = serde_json::from_value(saved).unwrap(); + + assert_eq!(generator.earlier_micro(), Some((LayerId(9), 0.25))); + assert!(generator.micro_in_use().is_none(), "the earlier reading replaces the Micro Height's curvature"); + + let reloaded: Generator = serde_json::from_value(serde_json::to_value(&generator).unwrap()).unwrap(); + assert_eq!(reloaded.earlier_micro(), Some((LayerId(9), 0.25)), "saving again keeps the earlier reading"); + + let on_sections = Generator { section: SectionParameters::defaults(GeneratorKind::Curvature), ..generator }; + assert_eq!(on_sections.earlier_micro(), None); + assert!(on_sections.micro_in_use().is_some(), "on the reference's controls the anchor reads as a Micro Height"); + } + #[test] fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; diff --git a/crates/core/src/layer/micro_details.rs b/crates/core/src/layer/micro_details.rs index 186f3af4..462cfa0d 100644 --- a/crates/core/src/layer/micro_details.rs +++ b/crates/core/src/layer/micro_details.rs @@ -29,6 +29,9 @@ pub struct MicroDetails { /// The micro normal image (None: an empty slot) #[serde(default, skip_serializing_if = "Option::is_none")] pub normal_source: Option, + /// Saved as the micro detail before Micro Details (an anchor's height times an amount): a generator still on the earlier model adds it that way, see [`super::Generator::earlier_micro`] + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub earlier: bool, } impl MicroDetails { @@ -37,7 +40,7 @@ impl MicroDetails { /// Height Details Intensity per unit of an anchor's micro detail amount (0..1): the earlier default amount, 0.5, reads at the default intensity pub const HEIGHT_INTENSITY_PER_AMOUNT: f32 = 2.0; - /// The micro details reading anchor point `anchor`'s height as their Micro Height at `amount` (0..1) on a `kind` generator, None for kinds without them + /// The micro detail saved before Micro Details, anchor point `anchor`'s height at `amount` (0..1), as Micro Details on a `kind` generator (None for kinds without them): the anchor is the Micro Height, `amount` its intensity pub fn of_anchor(kind: GeneratorKind, anchor: LayerId, amount: f32) -> Option { let amount = if amount.is_finite() { amount.clamp(0.0, 1.0) } else { 0.0 }; let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; @@ -46,6 +49,7 @@ impl MicroDetails { height: true, height_intensity: amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT, height_source: Some(source), + earlier: true, ..MicroDetails::defaults(kind)? }; Some(micro.clamped(kind)) @@ -64,6 +68,7 @@ impl MicroDetails { ao_depth: 0.05, height_source: None, normal_source: None, + earlier: false, }; match kind { GeneratorKind::Curvature | GeneratorKind::AmbientOcclusion => Some(shared), diff --git a/crates/engine/src/anchored_micro_edit.rs b/crates/engine/src/anchored_micro_edit.rs index 75d2eb54..f509a525 100644 --- a/crates/engine/src/anchored_micro_edit.rs +++ b/crates/engine/src/anchored_micro_edit.rs @@ -42,9 +42,10 @@ impl AnchoredMicroEdit { Ok(Some(AnchoredMicroEdit { anchor, amount })) } - /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there + /// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there; a generator on the earlier model reads it as these keys did before Micro Details pub fn apply(self, command: &str, generator: &mut Generator) -> Result<()> { let kind = generator.kind; + let earlier = generator.on_earlier_model(); let defaults = MicroDetails::defaults(kind); match (self.anchor, &defaults) { (Some(None), _) => { @@ -66,6 +67,9 @@ impl AnchoredMicroEdit { micro.height_intensity = amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT; **micro = micro.as_ref().clone().clamped(kind); } + if let Some(micro) = generator.micro.as_mut() { + micro.earlier = earlier; + } Ok(()) } } diff --git a/crates/engine/src/micro_params.rs b/crates/engine/src/micro_params.rs index 7e0ed083..bd62a209 100644 --- a/crates/engine/src/micro_params.rs +++ b/crates/engine/src/micro_params.rs @@ -60,6 +60,7 @@ pub fn micro_from(command: &str, params: &Value, generator: &mut Generator, earl } let micro = generator.micro.get_or_insert_with(|| Box::new(defaults)); + micro.earlier = false; for (key, value) in [("useMicroDetails", &mut micro.enabled), ("microHeight", &mut micro.height), ("microNormal", &mut micro.normal)] { if let Some(given) = boolp(params, key) { *value = given; diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index b8770541..278bfc04 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -211,6 +211,28 @@ fn generators_read_an_anchor_height_as_their_micro_height() { assert_eq!(back.doc.project, session.doc.project); } +#[test] +fn the_earlier_micro_keys_keep_an_earlier_model_generator_on_the_earlier_micro_detail() { + let mut session = session(); + let low = id(execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + let top = id(execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); + let earlier_micro = |session: &Session, generator: u64| match session.doc.project.effect(LayerId(generator)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => generator.earlier_micro(), + _ => None, + }; + + // `level` keeps the generator on the earlier model, where these keys read the anchor's height as before Micro Details + let generator = id(execute(&mut session, "effect.add.generator", &json!({"layer": top, "generator": "curvature", "level": 0.5})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 0.25})).unwrap(); + assert_eq!(earlier_micro(&session, generator), Some((LayerId(anchor), 0.25))); + + // A Micro Details control moves it onto the reference's controls and the anchor's curvature + execute(&mut session, "effect.set", &json!({"effect": generator, "microHeightIntensity": 1.0})).unwrap(); + assert_eq!(earlier_micro(&session, generator), None); +} + #[test] fn anchor_effects_added_through_instance_validate_against_source() { let mut session = session(); From eaf3ad1c2a630726654404144587475421df7084 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:07:40 +0000 Subject: [PATCH 47/54] Generators: every anchor height a render reads stays prepared, built lowest anchor first at the working size Anchor heights are kept while the texture set reads them (no 8-entry cap that dropped a ninth anchor to black), built in the anchors' draw order as their topmost reader reads them (an anchor's height can hold readers of lower anchors; layer ids no longer decide), rebuilt when the working atlas size changes, and prepared before the generator maps that read them. --- crates/compose/src/eval.rs | 135 +++++++++++++++++- .../src/micro_details/anchor_heights.rs | 5 + crates/compose/src/micro_details/mod.rs | 20 ++- 3 files changed, 149 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a4c50ea2..653e9f80 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2326,8 +2326,8 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], (list, around): (&[La let mut order = Vec::new(); draw_order(inp, list, 0, around.into(), &mut order); let ids: Vec = order.iter().map(|(id, _)| *id).collect(); - prepare_curvature_sizes(inp, &ids); prepare_micro_anchors(inp); + prepare_curvature_sizes(inp, &ids); // Walk backwards to find the region each Compare needs below its position in the stack let mut below_margin = (0u32, false); @@ -2428,25 +2428,34 @@ fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { /// Build the height of every anchor point a visible generator's Micro Height reads, over the whole texture set, before tiles composite in parallel fn prepare_micro_anchors(inp: &EvaluationInputs) { let Ok(set) = inp.project.texture_set(inp.ts) else { return }; - let tree = inp.project.render_tree(&set.stack); - let visible = tree.iter().filter_map(|id| inp.project.layers.get(id)).filter(|layer| layer.visible); + let mut order = Vec::new(); + draw_order(inp, &set.stack, 0, ContentsOffset::NONE.into(), &mut order); + + // Each anchor is built as its topmost reader reads it: a reader the anchor was moved above reads the same heights let mut readers: Vec<(LayerId, LayerId)> = Vec::new(); - for layer in visible { + for layer in order.iter().filter_map(|(id, _)| inp.project.layers.get(id)).filter(|layer| layer.visible) { let effects = layer_mask(inp.project, layer.id).filter(|mask| mask.enabled).into_iter().flat_map(|mask| &mask.effects); for effect in effects.filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind && let Some(micro) = generator.micro_in_use().filter(|micro| micro.height) && let Some(Source::Anchor { anchor, .. }) = µ.height_source - && !readers.iter().any(|(_, read)| read == anchor) { + readers.retain(|(_, read)| read != anchor); readers.push((layer.id, *anchor)); } } } + crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); if readers.is_empty() { return; } + // Lowest anchor first: an anchor's height holds the generators below it, which may read lower anchors + let drawn_at = |anchor: LayerId| { + let owner = inp.project.effect(anchor).map(|(owner, _)| owner); + order.iter().position(|(id, _)| Some(*id) == owner).unwrap_or(usize::MAX) + }; + readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); @@ -7243,6 +7252,122 @@ soft {soft:?}" } } + /// A 64 × 64 disc of raised height in an image named "disc", and a fixture with a flat baked curvature for micro details to read beside + fn micro_height_fixture() -> (Fixture, ImageStore) { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let disc = (0..64 * 64) + .map(|index| { + let (x, y) = ((index % 64) as f32 - 31.5, (index / 64) as f32 - 31.5); + if x * x + y * y < 100.0 { [1.0; 4] } else { [0.0, 0.0, 0.0, 1.0] } + }) + .collect(); + (fixture, [("disc".to_string(), Arc::new(ImageRes::new(64, 64, disc, false)))].into()) + } + + /// A Curvature generator whose Micro Height reads anchor point `anchor` + fn reading_micro_height(anchor: LayerId) -> Generator { + Generator { micro: MicroDetails::of_anchor(GeneratorKind::Curvature, anchor, 1.0).map(Box::new), ..Generator::new(GeneratorKind::Curvature) } + } + + /// A height fill of `source`, with an anchor point after it: the layer's id and the anchor's + fn anchored_height(fixture: &mut Fixture, id: LayerId, source: Source) -> (LayerId, LayerId) { + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, source); + let layer = fixture.project.insert_layer(0, Layer::new(id, "Height", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + (layer, content_fx(fixture, layer, EffectKind::Anchor)) + } + + fn base_color_reds(composite: &Composite) -> Vec { + (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + } + + #[test] + fn every_anchor_height_a_render_reads_stays_prepared_however_many_it_reads() { + const OTHER_READERS: usize = 8; + let colors = |others_read: bool| { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (low, first) = anchored_height(&mut fixture, id, Source::image("disc")); + let others: Vec = (0..OTHER_READERS).map(|_| content_fx(&mut fixture, low, EffectKind::Anchor)).collect(); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(first)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + + // Readers of eight more anchors on a layer of height only, drawn above + let id = fixture.project.alloc_id(); + let readers = + fixture.project.insert_layer(0, Layer::new(id, "Readers", LayerKind::Fill(Fill::default()), &[Channel::Height]), None, false).unwrap(); + let mut mask = Mask::new(MaskBackground::Black); + for (index, anchor) in others.iter().enumerate().filter(|_| others_read) { + mask.effects.push(Effect::new(LayerId(901 + index as u64), EffectKind::Generator(reading_micro_height(*anchor)))); + } + fixture.project.layer_mut(readers).unwrap().mask = Some(mask); + base_color_reds(&run_with_images(&fixture, None, &images)) + }; + + assert_eq!(colors(true), colors(false), "a ninth anchor read keeps the first one's height"); + } + + #[test] + fn an_anchor_height_holding_a_reader_of_a_lower_anchor_is_built_after_it_whatever_the_layer_ids() { + let colors = |top_id_first: bool| { + let (mut fixture, images) = micro_height_fixture(); + let early = fixture.project.alloc_id(); + let late = fixture.project.alloc_id(); + let (top_id, middle_id) = if top_id_first { (early, late) } else { (late, early) }; + let id = fixture.project.alloc_id(); + let (_, lower) = anchored_height(&mut fixture, id, Source::image("disc")); + + // The upper anchor records the middle layer's mask: a reader of the lower anchor + let middle = + fixture.project.insert_layer(0, Layer::new(middle_id, "Middle", LayerKind::Fill(Fill::default()), &[Channel::Height]), None, false).unwrap(); + let upper = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(lower)))); + mask.effects.push(Effect::new(upper, EffectKind::Anchor)); + fixture.project.layer_mut(middle).unwrap().mask = Some(mask); + + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([1.0; 3])); + let top = fixture.project.insert_layer(0, Layer::new(top_id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(901), EffectKind::Generator(reading_micro_height(upper)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + base_color_reds(&run_with_images(&fixture, None, &images)) + }; + + let (by_draw_order, against_it) = (colors(false), colors(true)); + let largest_change = by_draw_order.iter().zip(&against_it).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(largest_change < 1e-4, "{largest_change}"); + } + + #[test] + fn anchor_heights_are_built_again_at_another_working_size() { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (_, anchor) = anchored_height(&mut fixture, id, Source::image("disc")); + let stack = || { + StackKey::new(&fixture.project, &fixture.pixels, &fixture.baked, &images, 0, &fixture.project.texture_sets[0].stack) + .expect("the plane's stack has a key") + }; + let builds = std::cell::Cell::new(0); + let build = |size: (u32, u32)| { + builds.set(builds.get() + 1); + AnchorHeights::new(vec![0.0; (size.0 * size.1) as usize], size, fixture.project.texture_sets[0].block_scales()) + }; + let half = UvGBuffer::new(&fixture.mesh, 0, 32, 32); + let inputs_at = |gbuf| Inputs { gbuf, ..inputs(&fixture, &images, None) }; + + crate::micro_details::prepare_anchor_heights(&inputs_at(&fixture.gbuf), anchor, stack(), || build((64, 64))); + crate::micro_details::prepare_anchor_heights(&inputs_at(&fixture.gbuf), anchor, stack(), || build((64, 64))); + assert_eq!(builds.get(), 1, "the same stack and size reuse them"); + + crate::micro_details::prepare_anchor_heights(&inputs_at(&half), anchor, stack(), || build((32, 32))); + assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); + } + #[test] fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { const SAVED_AMOUNT: f32 = 0.25; diff --git a/crates/compose/src/micro_details/anchor_heights.rs b/crates/compose/src/micro_details/anchor_heights.rs index 0a8b5c18..5fe6f76e 100644 --- a/crates/compose/src/micro_details/anchor_heights.rs +++ b/crates/compose/src/micro_details/anchor_heights.rs @@ -12,6 +12,11 @@ impl AnchorHeights { AnchorHeights { data, working_size, scales } } + /// The working atlas's size the heights were built at + pub(super) fn working_size(&self) -> (u32, u32) { + self.working_size + } + /// The height under texel (`x`, `y`) of a `layout` sized mesh map (0 outside the working atlas) pub(super) fn at(&self, (x, y): (u32, u32), layout: (u32, u32)) -> f32 { let baked_uv = [(x as f32 + 0.5) / layout.0.max(1) as f32, (y as f32 + 0.5) / layout.1.max(1) as f32]; diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index ca5fa213..b6173ebd 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -73,14 +73,24 @@ fn baked_identity(inp: &Inputs) -> Option>> { [BakedMap::Curvature, BakedMap::AmbientOcclusion].iter().find_map(|map| inp.baked.maps.get(map)).map(Arc::downgrade) } -/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless `stack` is the stack they were built for +/// Drop the anchor heights of `inp`'s texture set that its generators no longer read (`anchors` are the ones they read) and those of mesh maps gone: every height a render reads stays until it stops reading it +pub(crate) fn keep_anchor_heights(inp: &Inputs, anchors: &[LayerId]) { + let baked = baked_identity(inp); + let stale = |entry: &AnchorEntry| { + let this_set = baked.as_ref().is_some_and(|baked| entry.baked.ptr_eq(baked)) && entry.texture_set == inp.ts; + entry.baked.strong_count() == 0 || (this_set && !anchors.contains(&entry.anchor)) + }; + ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).retain(|entry| !stale(entry)); +} + +/// Keep anchor `anchor`'s heights for the micro details reading it, building them with `build` unless they were built for `stack` at this working size pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: StackKey, build: impl FnOnce() -> AnchorHeights) { let Some(baked) = baked_identity(inp) else { return }; let matches = |entry: &AnchorEntry| entry.baked.ptr_eq(&baked) && entry.texture_set == inp.ts && entry.anchor == anchor; + let working_size = (inp.gbuf.width, inp.gbuf.height); { - let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|entry| entry.baked.strong_count() > 0); - if entries.iter().any(|entry| matches(entry) && entry.stack == stack) { + let entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if entries.iter().any(|entry| matches(entry) && entry.stack == stack && entry.heights.working_size() == working_size) { return; } } @@ -99,8 +109,6 @@ pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: Stack let mut entries = ANCHOR_HEIGHTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); entries.retain(|entry| !matches(entry)); entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); - let excess = entries.len().saturating_sub(CACHE_ENTRIES); - entries.drain(..excess); } /// The heights prepared for anchor `anchor` (None before they are) From 44b1bc0273bf68a6d10e070bf77cfa1a80ed8d2d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:12:15 +0000 Subject: [PATCH 48/54] Generators: whole-map fields keyed by a coverage hash taken once per evaluation and by each mesh map's bake size The field cache read every 31st texel's triangle on each lookup (once per tile plan) and could miss an edit between samples; the evaluation now hashes every texel once, on first use. A mesh map's bake size joins its key (one allocation read as another layout), and a hit moves to the most recently used end. --- crates/compose/src/dripping_rust.rs | 5 +- crates/compose/src/eval.rs | 79 +++++++++++++++++++- crates/compose/src/eval/evaluation_inputs.rs | 7 ++ crates/compose/src/field_cache.rs | 44 +++++++++-- crates/compose/src/field_cache_key.rs | 13 ++-- crates/compose/src/generator_maps.rs | 12 +-- crates/compose/src/uv_border_distance.rs | 4 +- crates/compose/src/uv_islands.rs | 8 +- 8 files changed, 140 insertions(+), 32 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index 4b5f84d5..c098fe29 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -36,8 +36,7 @@ const MIN_COVERAGE: f32 = 1e-3; static CACHE: FieldCache = FieldCache::new(); /// The rust before its spreading and contrast at every working texel of `inp` (0 outside the islands) -pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) -> Arc> { - let occlusion = inp.baked.maps.get(&BakedMap::AmbientOcclusion); +pub(crate) fn rust_field(inp: &Inputs, coverage: u64, rust: &DrippingRustParameters, seed: u32) -> Arc> { let settings = vec![ rust.spreading_smoothness.to_bits(), rust.drips_intensity.to_bits(), @@ -46,7 +45,7 @@ pub(crate) fn rust_field(inp: &Inputs, rust: &DrippingRustParameters, seed: u32) u32::from(rust.axis), seed, ]; - CACHE.get_or_build(inp, &occlusion.into_iter().collect::>(), settings, |block| build(inp, rust, seed, block)) + CACHE.get_or_build(inp, coverage, &[BakedMap::AmbientOcclusion], settings, |block| build(inp, rust, seed, block)) } /// The value at a working texel: the rust spread and contrasted diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 653e9f80..582f5bbf 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2419,7 +2419,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool { } /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. -fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { +fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); prepare_mask_curvature_sizes(inp, masks); @@ -2506,7 +2506,7 @@ fn wear_parameters(generator: &Generator) -> Option { } /// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. -fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { +fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(generator) = &effect.kind { @@ -2516,7 +2516,7 @@ fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator( None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; let maps = match &effect.kind { - EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator)), + EffectKind::Generator(generator) => GeneratorMaps::of(inp, generator, &curvature_sizes_in_use(generator), || inp.coverage_identity()), _ => GeneratorMaps::default(), }; let (depth, covers_all, projection) = match &effect.kind { @@ -7368,6 +7368,77 @@ soft {soft:?}" assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); } + /// Builds a field cache made: the counter goes up with each build + fn counted_build(builds: &std::cell::Cell) -> impl FnOnce((u32, u32)) -> Vec + '_ { + move |_| { + builds.set(builds.get() + 1); + vec![0.0; 4] + } + } + + #[test] + fn a_whole_map_field_is_built_again_when_its_mesh_map_is_read_at_another_bake_size() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let occlusion = Arc::new(vec![0.5; 16]); + let images = ImageStore::default(); + for resolution in [4, 4, 8] { + fixture.baked = BakedMaps { resolution, maps: [(BakedMap::AmbientOcclusion, occlusion.clone())].into() }; + let inputs = inputs(&fixture, &images, None); + cache.get_or_build( + &inputs, + crate::field_cache::coverage_identity(&fixture.gbuf), + &[BakedMap::AmbientOcclusion], + Vec::new(), + counted_build(&builds), + ); + } + + assert_eq!(builds.get(), 2, "4 × 4 reuses its field; the same map read as 8 × 2 builds another"); + } + + #[test] + fn a_whole_map_field_is_built_again_after_any_texel_of_its_coverage_changes() { + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let mut fixture = fixture(); + let images = ImageStore::default(); + let build_on = |fixture: &Fixture| { + let inputs = inputs(fixture, &images, None); + cache.get_or_build(&inputs, crate::field_cache::coverage_identity(&fixture.gbuf), &[], Vec::new(), counted_build(&builds)); + }; + build_on(&fixture); + build_on(&fixture); + + // The second texel, in place: the same allocation, one triangle different + fixture.gbuf.tri[1] = if fixture.gbuf.tri[1] == NO_TRI { 0 } else { NO_TRI }; + build_on(&fixture); + + assert_eq!(builds.get(), 2); + } + + #[test] + fn a_whole_map_field_read_again_outlives_fields_built_before_it() { + const FIELDS_KEPT: u32 = 8; + let cache = crate::field_cache::FieldCache::new(); + let builds = std::cell::Cell::new(0); + let fixture = fixture(); + let images = ImageStore::default(); + let inputs = inputs(&fixture, &images, None); + let coverage = crate::field_cache::coverage_identity(&fixture.gbuf); + let field = |settings: u32| { + cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds)); + }; + (0..FIELDS_KEPT).for_each(field); + field(0); + field(FIELDS_KEPT); + let built = builds.get(); + field(0); + + assert_eq!(builds.get(), built, "the field read again stays when a newer one pushes the oldest out"); + } + #[test] fn a_micro_detail_saved_before_micro_details_renders_as_saved_on_the_earlier_model() { const SAVED_AMOUNT: f32 = 0.25; diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index 2f9027fe..dbb8f392 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -22,6 +22,7 @@ pub(super) struct EvaluationInputs<'a> { instance_draws: OnceLock>, depth_maps: Mutex>, gradients: Mutex>>, + coverage: OnceLock, } impl<'a> EvaluationInputs<'a> { @@ -33,9 +34,15 @@ impl<'a> EvaluationInputs<'a> { instance_draws: OnceLock::new(), depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), + coverage: OnceLock::new(), } } + /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) + pub(super) fn coverage_identity(&self) -> u64 { + *self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf)) + } + pub(super) fn environment(&self) -> EnvironmentSh { if let Some(environment) = self.environment.get() { return *environment; diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 1458cb3f..51581173 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -1,5 +1,9 @@ use std::sync::{Arc, Mutex}; +use rayon::prelude::*; +use texturecraft_core::BakedMap; +use texturecraft_geom::UvGBuffer; + use crate::eval::Inputs; use crate::field_cache_key::FieldCacheKey; use crate::working_field::working_block; @@ -8,8 +12,19 @@ use crate::working_field::working_block; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// Texels between the samples a layout's fingerprint reads: dense enough to tell UV edits apart, sparse enough to read once per tile -const FINGERPRINT_STRIDE: usize = 31; +/// Texels hashed together before their hashes are combined, so the coverage hashes in parallel +const COVERAGE_CHUNK_TEXELS: usize = 1 << 16; + +/// The 64-bit FNV prime, spreading each step of the coverage hash over every bit +const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; + +/// The identity of `gbuf`'s coverage: its size and the triangle under every texel, hashed (read once per evaluation, as it reads every texel) +pub(crate) fn coverage_identity(gbuf: &UvGBuffer) -> u64 { + let chunk_hash = + |chunk: &[u32]| chunk.iter().fold(chunk.len() as u64, |hash, triangle| (hash.rotate_left(5) ^ u64::from(*triangle)).wrapping_mul(FNV_PRIME)); + let chunks: Vec = gbuf.tri.par_chunks(COVERAGE_CHUNK_TEXELS).map(chunk_hash).collect(); + chunks.iter().fold((u64::from(gbuf.width) << 32) | u64::from(gbuf.height), |hash, chunk| (hash.rotate_left(7) ^ chunk).wrapping_mul(FNV_PRIME)) +} /// Built fields by what they were built from, most recently used last pub(crate) struct FieldCache { @@ -21,26 +36,39 @@ impl FieldCache { FieldCache { entries: Mutex::new(Vec::new()) } } - /// The field of `inp`'s working layout reading `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work - pub(crate) fn get_or_build(&self, inp: &Inputs, maps: &[&Arc>], settings: Vec, build: impl FnOnce((u32, u32)) -> Vec) -> Arc> { + /// The field of `inp`'s working layout (its coverage: [`coverage_identity`]) reading the baked `maps` with `settings`, built by `build` (given the UV tile block) when missing, outside the lock: the build runs parallel work + pub(crate) fn get_or_build( + &self, + inp: &Inputs, + coverage: u64, + maps: &[BakedMap], + settings: Vec, + build: impl FnOnce((u32, u32)) -> Vec, + ) -> Arc> { let gbuf = inp.gbuf; let block = working_block(inp); + let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map))))); let key = FieldCacheKey { layout: gbuf.tri.as_ptr() as usize, size: (gbuf.width, gbuf.height), - fingerprint: gbuf.tri.iter().step_by(FINGERPRINT_STRIDE).fold(gbuf.tri.len() as u64, |hash, tri| hash.rotate_left(5) ^ u64::from(*tri)), + coverage, block, scales: inp.block_scales.clone(), positions: (inp.mesh.positions.as_ptr() as usize, inp.mesh.positions.len()), uvs: (inp.mesh.uvs.as_ptr() as usize, inp.mesh.uvs.len()), - maps: maps.iter().map(|map| Arc::downgrade(map)).collect(), + maps: read.collect(), settings, }; + // A hit moves to the most recently used end let cached = { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|map| map.strong_count() > 0)); - entries.iter().find(|(cached, _)| *cached == key).map(|(_, field)| field.clone()) + entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.strong_count() > 0)); + let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index)); + hit.map(|(cached, field)| { + entries.push((cached, field.clone())); + field + }) }; if let Some(field) = cached { return field; diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index d29d80f5..1010ac97 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -2,28 +2,31 @@ use std::sync::Weak; use texturecraft_core::BlockScales; -/// What a field was built from: the working layout (the g-buffer's address, size, coverage fingerprint, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits +/// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits #[derive(Clone)] pub(crate) struct FieldCacheKey { pub(crate) layout: usize, pub(crate) size: (u32, u32), - pub(crate) fingerprint: u64, + /// Every texel's triangle, hashed: [`crate::field_cache::coverage_identity`] + pub(crate) coverage: u64, pub(crate) block: (u32, u32), pub(crate) scales: BlockScales, /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields pub(crate) positions: (usize, usize), pub(crate) uvs: (usize, usize), - pub(crate) maps: Vec>>, + /// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels + pub(crate) maps: Vec<(Weak>, (u32, u32))>, pub(crate) settings: Vec, } impl PartialEq for FieldCacheKey { fn eq(&self, other: &FieldCacheKey) -> bool { - let same_maps = self.maps.len() == other.maps.len() && self.maps.iter().zip(&other.maps).all(|(a, b)| a.strong_count() > 0 && a.ptr_eq(b)); + let same_maps = self.maps.len() == other.maps.len() + && self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size); same_maps && self.layout == other.layout && self.size == other.size - && self.fingerprint == other.fingerprint + && self.coverage == other.coverage && self.block == other.block && self.scales == other.scales && self.positions == other.positions diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 151ae176..503a32c9 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -27,8 +27,8 @@ pub(crate) struct GeneratorMaps { } impl GeneratorMaps { - /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size) - pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool]) -> GeneratorMaps { + /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> u64) -> GeneratorMaps { let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); let micro_curvature = micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); @@ -39,10 +39,10 @@ impl GeneratorMaps { }; let controls = generator.kind_controls(); let field = match &controls { - Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, border)), - Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, rust, generator.seed)), - Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, random, generator.seed)), - Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, checker, generator.seed)), + Some(KindControls::BorderDistance(border)) => Some(border_gradient(inp, coverage(), border)), + Some(KindControls::DrippingRust(rust)) => Some(rust_field(inp, coverage(), rust, generator.seed)), + Some(KindControls::UvRandomColor(random)) => Some(random_color_field(inp, coverage(), random, generator.seed)), + Some(KindControls::UvChecker(checker)) => Some(checker_field(inp, coverage(), checker, generator.seed)), _ => None, }; GeneratorMaps { sizes, micro_curvature, micro_occlusion, field, controls: controls.map(Arc::new) } diff --git a/crates/compose/src/uv_border_distance.rs b/crates/compose/src/uv_border_distance.rs index b324e4ac..9cced087 100644 --- a/crates/compose/src/uv_border_distance.rs +++ b/crates/compose/src/uv_border_distance.rs @@ -18,8 +18,8 @@ const SMOOTHNESS_SIGMA_2K: f32 = 45.0; static CACHE: FieldCache = FieldCache::new(); /// The gradient before balance, contrast and invert for every working texel of `inp` (0 outside the islands) -pub(crate) fn border_gradient(inp: &Inputs, border: &BorderDistanceParameters) -> Arc> { - CACHE.get_or_build(inp, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) +pub(crate) fn border_gradient(inp: &Inputs, coverage: u64, border: &BorderDistanceParameters) -> Arc> { + CACHE.get_or_build(inp, coverage, &[], vec![border.distance.to_bits(), border.smoothness.to_bits()], |block| build(inp, border, block)) } /// The value at a working texel: the gradient balanced, contrasted and inverted diff --git a/crates/compose/src/uv_islands.rs b/crates/compose/src/uv_islands.rs index 6ce27082..d5233984 100644 --- a/crates/compose/src/uv_islands.rs +++ b/crates/compose/src/uv_islands.rs @@ -17,12 +17,12 @@ use crate::working_field::REFERENCE_TILE_TEXELS; static CACHE: FieldCache = FieldCache::new(); /// UV Random Color at every working texel of `inp`: one value per UV island (0 outside the islands) -pub(crate) fn random_color_field(inp: &Inputs, random: &UvRandomColorParameters, seed: u32) -> Arc> { +pub(crate) fn random_color_field(inp: &Inputs, coverage: u64, random: &UvRandomColorParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(random.custom_gradient)]; settings.push(random.used_colors().len() as u32); settings.extend(random.used_colors().iter().flat_map(|color| color.map(f32::to_bits))); settings.extend(random.positions.iter().map(|position| position.to_bits())); - CACHE.get_or_build(inp, &[], settings, |_| { + CACHE.get_or_build(inp, coverage, &[], settings, |_| { let island_values = island_values(inp, |island| random_gray(random, seed, island)); let gbuf = inp.gbuf; gbuf.tri.par_iter().map(|triangle| island_values.get(triangle).copied().unwrap_or(0.0)).collect() @@ -73,10 +73,10 @@ const RANDOM_SATURATION: std::ops::RangeInclusive = 0.06..=0.57; const RANDOM_VALUE: std::ops::RangeInclusive = 0.42..=0.80; /// UV Checker at every working texel of `inp`: the gray of its color, the mean of the sRGB-encoded channels as the reference reads it (0 outside the islands) -pub(crate) fn checker_field(inp: &Inputs, checker: &UvCheckerParameters, seed: u32) -> Arc> { +pub(crate) fn checker_field(inp: &Inputs, coverage: u64, checker: &UvCheckerParameters, seed: u32) -> Arc> { let mut settings = vec![seed, u32::from(checker.random_colors), checker.grid_tile, checker.grid_opacity.to_bits(), checker.border_width.to_bits()]; settings.extend(checker.checker_color.iter().chain(&checker.border_color).map(|value| value.to_bits())); - CACHE.get_or_build(inp, &[], settings, |block| { + CACHE.get_or_build(inp, coverage, &[], settings, |block| { let gbuf = inp.gbuf; let (width, height) = (gbuf.width, gbuf.height); let island_colors = if checker.random_colors { island_colors(inp, seed) } else { HashMap::new() }; From 30dcceb3ef7328ba1d99b657770e5802e04b4a1c Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:16:06 +0000 Subject: [PATCH 49/54] Generators: mask comparisons in tests reject missing texels; the micro blur's kernel is sampled once per pass bake_resolution checks the mask's length again (the zip let a short or empty mask pass), as do the texture and section test helpers. --- crates/compose/src/micro_details/mod.rs | 25 ++++++++++++++-------- crates/compose/tests/generator_sections.rs | 1 + crates/compose/tests/generator_texture.rs | 1 + crates/engine/tests/it/bake_resolution.rs | 1 + 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index b6173ebd..4ee72fd3 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -267,10 +267,12 @@ fn gaussian_wrapped(values: &[f32], (width, height): (u32, u32), sigma: f32) -> fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { let length = length.max(1); let mut out = vec![0.0; values.len()]; - out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| { - if sigma < BOX_BLUR_MIN_SIGMA { - kernel_blur(line, out, sigma); - } else { + + // Every line reads the same sampled kernel + let kernel = (sigma < BOX_BLUR_MIN_SIGMA).then(|| gaussian_kernel(sigma)); + out.par_chunks_mut(length).zip(values.par_chunks(length)).for_each(|(out, line)| match &kernel { + Some(kernel) => kernel_blur(line, out, kernel), + None => { // Three box passes of radius r spread a value with variance r(r + 1) let radius = (((1.0 + 4.0 * sigma * sigma).sqrt() - 1.0) / 2.0).round().max(1.0) as usize; let mut current = line.to_vec(); @@ -283,18 +285,23 @@ fn blur_lines(values: &[f32], length: usize, sigma: f32) -> Vec { out } -/// `line` blurred into `out` by a sampled gaussian of `sigma`, wrapping around -fn kernel_blur(line: &[f32], out: &mut [f32], sigma: f32) { +/// A gaussian of `sigma` sampled at whole texels each side of its centre, its weights summing to 1 +fn gaussian_kernel(sigma: f32) -> Vec { let reach = (KERNEL_REACH_SIGMAS * sigma).ceil().max(1.0) as i64; let weights: Vec = (-reach..=reach).map(|offset| (-(offset * offset) as f32 / (2.0 * sigma * sigma)).exp()).collect(); let total: f32 = weights.iter().sum(); + weights.into_iter().map(|weight| weight / total).collect() +} + +/// `line` blurred into `out` by `kernel` (centred, as [`gaussian_kernel`] samples it), wrapping around +fn kernel_blur(line: &[f32], out: &mut [f32], kernel: &[f32]) { + let reach = (kernel.len() / 2) as i64; let length = line.len().max(1) as i64; for (index, value) in out.iter_mut().enumerate() { - let sum: f32 = (-reach..=reach) - .zip(&weights) + *value = (-reach..=reach) + .zip(kernel) .map(|(offset, weight)| line.get((index as i64 + offset).rem_euclid(length) as usize).copied().unwrap_or(0.0) * weight) .sum(); - *value = sum / total; } } diff --git a/crates/compose/tests/generator_sections.rs b/crates/compose/tests/generator_sections.rs index 0724f4e6..799674d6 100644 --- a/crates/compose/tests/generator_sections.rs +++ b/crates/compose/tests/generator_sections.rs @@ -103,6 +103,7 @@ fn with_light(change: impl FnOnce(&mut LightParameters)) -> Generator { } fn assert_close(actual: &[f32], expected: &[f32], what: &str) { + assert_eq!(actual.len(), expected.len(), "{what}: texels read"); for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); } diff --git a/crates/compose/tests/generator_texture.rs b/crates/compose/tests/generator_texture.rs index 3dcc0d46..d1cc4ccf 100644 --- a/crates/compose/tests/generator_texture.rs +++ b/crates/compose/tests/generator_texture.rs @@ -103,6 +103,7 @@ fn replacing() -> TextureLayer { } fn assert_all(actual: &[f32], expected: f32, what: &str) { + assert!(!actual.is_empty(), "{what}: no texels read"); for (index, actual) in actual.iter().enumerate() { assert!((actual - expected).abs() < TOLERANCE, "{what}: texel {index} is {actual}, expected {expected}"); } diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index b2c88885..f690d2ae 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -128,6 +128,7 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); let expected = [240.0 / 255.0, 20.0 / 255.0]; + assert_eq!(mask.len(), expected.len(), "one value per requested texel"); assert!( mask.iter().zip(expected).all(|(value, expected)| (value - expected).abs() < 0.001), "generators sample the whole bake through the working layout: {mask:?}" From ff298779c2488163e5044fdbbc30f9b655d419fc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:16:06 +0000 Subject: [PATCH 50/54] Generators panel: Restore defaults keeps the Resolution band, the input card offers anchors below the owner, a swapped kind drops its point pick, size columns step with the arrow keys - Restore defaults resets the Parameters only, as its band says (it was disabled when only the resolution differed, yet reset it otherwise) - an inherited generator's slots list the anchors below both the owner and the instance, as the Properties picker does (others were refused) - a pick armed on a generator swapped to a kind without that point is dropped - a focused size column takes the arrow keys, each press one step - the picker snapshot hovers the tile by its ListBoxOption role --- crates/ui-egui/src/generator_input_card.rs | 4 +- crates/ui-egui/src/generator_params.rs | 11 +-- crates/ui-egui/src/generator_point_pick.rs | 17 ++++- .../src/property_sheet/size_columns.rs | 20 +++++ crates/ui-egui/tests/it/generator_panel.rs | 75 ++++++++++++++++++- crates/ui-egui/tests/it/generator_picker.rs | 4 +- 6 files changed, 114 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/generator_input_card.rs b/crates/ui-egui/src/generator_input_card.rs index b63012ce..0f25860c 100644 --- a/crates/ui-egui/src/generator_input_card.rs +++ b/crates/ui-egui/src/generator_input_card.rs @@ -5,7 +5,7 @@ use serde_json::json; use texturecraft_engine::core::{LayerId, Source}; use crate::TextureCraftApp; -use crate::dock::{anchor_label, anchors_below, image_drop, mesh_map_color}; +use crate::dock::{anchor_label, image_drop, mesh_map_color, project_effect_anchors_below}; use crate::fill_material_panel::{source_choice, source_tabs}; use crate::generator_input_slot::GeneratorInputSlot; use crate::i18n::{baked_map_label, tr, trf}; @@ -93,7 +93,7 @@ pub(crate) fn input_card( } let current = source.map(|source| source_choice(&app.session, source)); let tabs = || { - let anchors = if slot.takes_anchor() { anchors_below(&app.session.doc.project, layer) } else { Vec::new() }; + let anchors = if slot.takes_anchor() { project_effect_anchors_below(&app.session.doc.project, layer, LayerId(id)) } else { Vec::new() }; let mut tabs = source_tabs(&app.session, &anchors, tokens.button, false); // A generator's inputs read images, values and anchor points, never a procedural diff --git a/crates/ui-egui/src/generator_params.rs b/crates/ui-egui/src/generator_params.rs index 879efecc..f056d8ba 100644 --- a/crates/ui-egui/src/generator_params.rs +++ b/crates/ui-egui/src/generator_params.rs @@ -169,18 +169,11 @@ pub(crate) fn micro_params(kind: GeneratorKind, micro: &MicroDetails) -> Value { params } -/// The `effect.set` params that put generator effect `id` back to the defaults of its kind; its images stay in their slots +/// The `effect.set` params that put generator effect `id`'s parameters back to the defaults of its kind; its images stay in their slots and its resolution, in a band of its own, stays as set pub(crate) fn defaults_of(id: u64, generator: &Generator) -> Value { let kind = generator.kind; let defaults = Generator::new(kind); - let params = json!({ - "effect": id, - "seed": defaults.seed, - "invert": defaults.invert, - "resolution": format!("{:?}", defaults.resolution.mode), - "customResolution": defaults.resolution.custom, - "resolutionFactor": defaults.resolution.factor, - }); + let params = json!({"effect": id, "seed": defaults.seed, "invert": defaults.invert}); if let Some(controls) = &defaults.controls { return merged(params, kind_params(controls)); } diff --git a/crates/ui-egui/src/generator_point_pick.rs b/crates/ui-egui/src/generator_point_pick.rs index 4b876e78..293f4e7b 100644 --- a/crates/ui-egui/src/generator_point_pick.rs +++ b/crates/ui-egui/src/generator_point_pick.rs @@ -1,6 +1,6 @@ //! Picking a 3D generator's point on the mesh: its crosshair button arms it, the next click in the 3D view sets the point, Esc or the button again cancels -use texturecraft_engine::core::LayerId; +use texturecraft_engine::core::{EffectKind, GeneratorKind, LayerId}; use texturecraft_engine::{Session, StackTarget}; /// Which point of which generator effect the next click in the 3D view sets @@ -12,6 +12,13 @@ pub(crate) struct PointPick { pub(crate) point: &'static str, } +impl PointPick { + /// Whether a `kind` generator has the point this pick sets + fn belongs_to(&self, kind: GeneratorKind) -> bool { + matches!((kind, self.point), (GeneratorKind::ThreeDDistance, "distance") | (GeneratorKind::ThreeDLinearGradient, "start" | "end")) + } +} + /// Where the armed pick is kept: a transient UI mode, like the depth of field's focus pick fn pick_id() -> egui::Id { egui::Id::unique("tc_generator_point_pick") @@ -28,10 +35,14 @@ pub(crate) fn toggle(ctx: &egui::Context, pick: PointPick) { set(ctx, next); } -/// The armed pick while its effect is still the selected one; a pick whose effect was deselected or deleted is dropped +/// The armed pick while its effect is still the selected one and still has its point; a pick whose effect was deselected, deleted or swapped to a kind without that point is dropped pub(crate) fn armed_on(ctx: &egui::Context, session: &Session) -> Option { let pick = armed(ctx)?; - if session.target == StackTarget::Effect(LayerId(pick.effect)) { + let has_point = match session.doc.project.effect(LayerId(pick.effect)).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Generator(generator)) => pick.belongs_to(generator.kind), + _ => false, + }; + if has_point && session.target == StackTarget::Effect(LayerId(pick.effect)) { return Some(pick); } set(ctx, None); diff --git a/crates/ui-egui/src/property_sheet/size_columns.rs b/crates/ui-egui/src/property_sheet/size_columns.rs index ec6dd9d7..2d0fbeb5 100644 --- a/crates/ui-egui/src/property_sheet/size_columns.rs +++ b/crates/ui-egui/src/property_sheet/size_columns.rs @@ -18,6 +18,9 @@ const FACE_AIR: f32 = 2.0; /// Width of a column's track and fill const COLUMN_TRACK_WIDTH: f32 = 2.0; +/// How far one arrow key press moves a focused column: a twentieth of its track +const KEY_STEP: f32 = 0.05; + impl PropertySheet<'_> { /// One 0..1 vertical slider per name in `values`, side by side across the panel pub(crate) fn size_columns(&mut self, names: &[&str], values: &mut [f32]) -> SizeColumnsResponse { @@ -43,6 +46,23 @@ impl PropertySheet<'_> { moved = true; } } + + // A focused column keeps the arrow keys: up and right raise it, down and left lower it, each press its own step + if hit.has_focus() { + self.ui.memory_mut(|memory| { + memory.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = self.ui.input(|input| { + let raised = input.num_presses(egui::Key::ArrowUp) + input.num_presses(egui::Key::ArrowRight); + let lowered = input.num_presses(egui::Key::ArrowDown) + input.num_presses(egui::Key::ArrowLeft); + raised as f32 - lowered as f32 + }); + let stepped = (*value + presses * KEY_STEP).clamp(0.0, 1.0); + if stepped != *value { + *value = stepped; + moved = true; + } + } if let Some(merge) = crate::widgets::press_edit(self.ui, id, moved) { response.edit = Some((index, merge)); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 931f469a..3b5c8c2d 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -102,7 +102,10 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { click_live(&mut harness, Role::Button, "Restore defaults"); - assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); + // Resolution has its own band: restoring the parameters leaves it as set + let restored = generator(&harness, effect); + assert_eq!(restored.resolution.factor, -2); + assert_eq!(Generator { resolution: Generator::new(GeneratorKind::Curvature).resolution, ..restored }, Generator::new(GeneratorKind::Curvature)); } #[test] @@ -250,6 +253,29 @@ fn a_curvature_size_column_sets_its_size_alone_in_one_step() { assert_eq!(harness.state().session.history_labels().len(), history + 1); } +#[test] +fn a_focused_curvature_size_column_steps_with_the_arrow_keys() { + let (mut harness, effect) = harness(false); + let last = generator(&harness, effect).detail.unwrap().weights.len() - 1; + harness.get_by_role_and_label(Role::Slider, "Huge").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Slider, "Huge").focus(); + harness.run_steps(2); + let before = generator(&harness, effect).detail.unwrap().weights; + let history = harness.state().session.history_labels().len(); + + harness.key_press(egui::Key::ArrowDown); + harness.run_steps(3); + let lowered = generator(&harness, effect).detail.unwrap().weights; + harness.key_press(egui::Key::ArrowUp); + harness.run_steps(3); + + assert!(lowered[last] < before[last], "down lowered Huge: {} -> {}", before[last], lowered[last]); + assert_eq!(lowered[..last], before[..last], "the other sizes kept theirs"); + assert!((generator(&harness, effect).detail.unwrap().weights[last] - before[last]).abs() < 1e-6, "up raised it back"); + assert_eq!(harness.state().session.history_labels().len(), history + 2, "each press is a step"); +} + #[test] fn restore_defaults_puts_a_light_back_on_its_defaults() { let (mut harness, effect) = harness_with(false, json!({"generator": "direction", "lightHorizontal": 10.0, "highlightLevel": 0.7, "invert": true})); @@ -279,6 +305,45 @@ fn micro_details_show_their_settings_once_switched_on() { assert!(slot_reading(&harness, "Empty").rect().is_positive(), "Micro Height on: its slot, empty"); } +/// An instance showing its source's generator offers its Micro Height only the anchor points below both: one between the source and the instance is refused by the source's mask +#[test] +fn an_inherited_generators_micro_height_lists_only_anchors_below_its_owner() { + const BELOW: &str = "Height below"; + const BETWEEN: &str = "Height between"; + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + let low = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "content", "name": BELOW})).unwrap(); + let source = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let added = execute(&mut session, "effect.add.generator", &json!({"layer": source, "generator": "dirt", "microHeight": true})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + let between = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": between, "target": "content", "name": BETWEEN})).unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap(); + session.target = texturecraft_engine::StackTarget::Effect(effect); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + + harness.get_by_role_and_label(Role::Button, "Micro Details").scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Micro Details").click(); + harness.run_steps(3); + slot_reading(&harness, "Empty").scroll_to_me(); + harness.run_steps(3); + slot_reading(&harness, "Empty").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Tab, "Anchor points").click(); + harness.run_steps(3); + + let offered: Vec<_> = harness.get_all_by_role(Role::ListBoxOption).filter_map(|row| row.accesskit_node().label()).collect(); + assert!(offered.iter().any(|label| label.contains(BELOW)), "the anchor below the source is offered: {offered:?}"); + assert!(!offered.iter().any(|label| label.contains(BETWEEN)), "the anchor above the source is excluded: {offered:?}"); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn generator_panel_snapshots() { @@ -438,6 +503,14 @@ fn a_point_pick_waits_for_the_view_until_escape() { harness.run_steps(3); assert!(!is_on(&harness, Role::Button, end), "a pick left behind is dropped"); + + // A kind without the point drops it too: swapped back, it waits no more + click_live(&mut harness, Role::Button, end); + for kind in ["position", "3dLinearGradient"] { + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "generator": kind})).unwrap(); + harness.run_steps(3); + } + assert!(!is_on(&harness, Role::Button, end), "a pick on a swapped kind is dropped"); } #[test] diff --git a/crates/ui-egui/tests/it/generator_picker.rs b/crates/ui-egui/tests/it/generator_picker.rs index b300a7e2..d99f1006 100644 --- a/crates/ui-egui/tests/it/generator_picker.rs +++ b/crates/ui-egui/tests/it/generator_picker.rs @@ -95,8 +95,8 @@ fn generator_picker_snapshots() { harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap(); } - // The picker's tile is the button named Dirt - harness.get_by_role_and_label(Role::Button, "Dirt").hover(); + // The picker's tile is the list option named Dirt + harness.get_by_role_and_label(Role::ListBoxOption, "Dirt").hover(); for _ in 0..10 { harness.run_steps(5); std::thread::sleep(std::time::Duration::from_millis(300)); From e7fa9730f2b075c4dd124cd77affe44e8b7cda7d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:26:15 +0000 Subject: [PATCH 51/54] Generators: drips take no rust from lower on the axis, histogram ends hold at a hard step, Use Texture's X projection scales about the centre - a drip ray past a ridge no longer carries rust up from texels lower on the drip axis (the fitted captures move closer with the check) - position 0 stays all black and 1 all white at contrast 1, as the scan's ends are documented (3D Distance at offset 0, Dripping Rust spread 0) - Use Texture's triplanar X projection mirrors U about the bounds' centre like the scale it uses; custom grunge keeps its fitted placement (identical at whole scales, which every capture used) --- crates/compose/src/dripping_rust.rs | 55 +++++++++++++++++++++++++++- crates/compose/src/histogram_scan.rs | 14 +++++++ crates/compose/src/slot_placement.rs | 2 + crates/compose/src/texture_layer.rs | 18 ++++++++- crates/compose/src/wear.rs | 4 +- 5 files changed, 88 insertions(+), 5 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index c098fe29..43e42858 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -144,7 +144,11 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei let along = step as f32 / samples as f32; let distance = reach * along; let (sample_x, sample_y) = (x as f32 + distance * uphill.0 / length, y as f32 + distance * uphill.1 / length); - match field_at(sample_x.round() as i64, sample_y.round() as i64) { + let (sample_x, sample_y) = (sample_x.round() as i64, sample_y.round() as i64); + + // Rust drips down: a tap the ray reaches past a ridge, lower on the axis, gives none + let above = axis_at(sample_x, sample_y).is_some_and(|axis| axis >= axis_here); + match field_at(sample_x, sample_y).filter(|_| above) { Some(value) => most.max(value * (1.0 - DRIP_FADE * along.powf(DRIP_FADE_POWER))), None => most, } @@ -152,3 +156,52 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei }) .collect() } + +#[cfg(test)] +mod tests { + use texturecraft_core::{Project, TextureSet}; + use texturecraft_geom::{UvGBuffer, primitives}; + + use super::*; + use crate::{BakedMaps, PixelStore}; + + const RES: u32 = 256; + + #[test] + fn a_drip_takes_no_rust_from_past_a_ridge_lower_on_the_axis() { + // A strip rising gently to a ridge at its middle, then falling steeply + let mut mesh = primitives::plane(2.0, 64); + for position in &mut mesh.positions { + position.y = if position.z <= 0.0 { 1.0 + position.z } else { 1.0 - 8.0 * position.z }; + } + let gbuf = UvGBuffer::new(&mesh, 0, RES, RES); + let mut project = Project::new("t", "strip"); + project.texture_sets.push(TextureSet::new("A", 0, RES)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), Default::default()); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + // Rust only on the steep side, all lower than the gentle side's texel just below the ridge + let rusted = |surface: &texturecraft_geom::Surface| surface.pos.z > 0.01; + let field: Vec = (0..RES * RES).map(|texel| gbuf.surface(&mesh, texel as usize).filter(rusted).map_or(0.0, |_| 1.0)).collect(); + let rust = DrippingRustParameters { drips_intensity: 1.0, drips_samples: DrippingRustParameters::MAX_SAMPLES, axis: 1, ..Default::default() }; + let dripped = drips(&inputs, &rust, &field, (RES, RES), &|_, _| RES as f32); + + let below_ridge = (0..RES * RES) + .find(|texel| { + gbuf.surface(&mesh, *texel as usize).is_some_and(|surface| (surface.pos.z + 0.04).abs() < 1.0 / RES as f32 && surface.pos.x.abs() < 0.1) + }) + .expect("a texel just below the ridge"); + assert_eq!(dripped[below_ridge as usize], 0.0); + } +} diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs index ca9c851c..8c474d7e 100644 --- a/crates/compose/src/histogram_scan.rs +++ b/crates/compose/src/histogram_scan.rs @@ -2,6 +2,14 @@ /// `value` scanned at `position` (0 all black, 1 all white) over a ramp `1 − contrast` wide; contrast 1 is a hard step pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { + // The ends hold at a hard step too, where the ramp has no width to reach them + if position <= 0.0 { + return 0.0; + } + if position >= 1.0 { + return 1.0; + } + let width = 1.0 - contrast.clamp(0.0, 1.0); // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; @@ -23,6 +31,12 @@ mod tests { } } + #[test] + fn the_ends_of_the_position_hold_at_a_hard_step() { + assert_eq!(histogram_scan(1.0, 0.0, 1.0), 0.0, "position 0 is all black, even for white"); + assert_eq!(histogram_scan(0.0, 1.0, 1.0), 1.0, "position 1 is all white, even for black"); + } + #[test] fn the_middle_position_keeps_mid_gray_and_contrast_narrows_around_it() { assert!((histogram_scan(0.5, 0.5, 0.5) - 0.5).abs() < 1e-6); diff --git a/crates/compose/src/slot_placement.rs b/crates/compose/src/slot_placement.rs index 69af657b..d5c18cde 100644 --- a/crates/compose/src/slot_placement.rs +++ b/crates/compose/src/slot_placement.rs @@ -4,4 +4,6 @@ pub(crate) struct SlotPlacement { pub offset: f32, /// How sharply the three projections meet, or None to read in UV pub triplanar_contrast: Option, + /// The X projection's mirrored U turns about the bounds' centre, which a centred scale keeps fixed (Use Texture); else about 0, as custom grunge was fitted + pub mirrored_about_centre: bool, } diff --git a/crates/compose/src/texture_layer.rs b/crates/compose/src/texture_layer.rs index 02cf6769..4d121f42 100644 --- a/crates/compose/src/texture_layer.rs +++ b/crates/compose/src/texture_layer.rs @@ -13,7 +13,12 @@ const MIN_NORMAL_COMPONENT: f32 = 1e-6; /// The texture is scaled about the centre of the UV square (or of the mesh's bounds) pub(crate) fn texture_placement(texture: &TextureLayer) -> SlotPlacement { - SlotPlacement { scale: texture.scale, offset: 0.5 * (1.0 - texture.scale), triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast) } + SlotPlacement { + scale: texture.scale, + offset: 0.5 * (1.0 - texture.scale), + triplanar_contrast: texture.triplanar.then_some(texture.triplanar_contrast), + mirrored_about_centre: true, + } } /// Where a slot is read in UV @@ -24,7 +29,8 @@ pub(crate) fn uv_coordinates(placement: &SlotPlacement, uv: Vec2) -> Vec2 { /// Where a slot is read on each of the three projections (facing X, Y and Z) for `position` across the mesh's bounds (0..1) pub(crate) fn triplanar_coordinates(placement: &SlotPlacement, position: Vec3) -> [Vec2; 3] { let placed = |u: f32, v: f32| Vec2::new(u, v) * placement.scale + Vec2::splat(placement.offset); - [placed(-position.z, position.y), placed(position.x, position.z), placed(position.x, position.y)] + let mirrored_z = if placement.mirrored_about_centre { 1.0 - position.z } else { -position.z }; + [placed(mirrored_z, position.y), placed(position.x, position.z), placed(position.x, position.y)] } /// How much each projection (facing X, Y and Z) counts for a surface facing `normal` at triplanar `contrast`, summing to 1 @@ -153,4 +159,12 @@ mod tests { assert_eq!(uv_coordinates(&placement, Vec2::splat(0.5)), Vec2::splat(0.5)); assert_eq!(uv_coordinates(&placement, Vec2::new(0.75, 0.25)), Vec2::new(1.0, 0.0)); } + + #[test] + fn every_triplanar_projection_is_scaled_about_the_centre_of_the_bounds() { + let placement = texture_placement(&TextureLayer { scale: 1.5, triplanar: true, ..texture() }); + for (axis, at) in triplanar_coordinates(&placement, Vec3::splat(0.5)).into_iter().enumerate() { + assert!((at - Vec2::splat(0.5)).abs().max_element() < 1e-6, "projection {axis} reads {at} at the centre"); + } + } } diff --git a/crates/compose/src/wear.rs b/crates/compose/src/wear.rs index 14903b8f..3eb2d7d9 100644 --- a/crates/compose/src/wear.rs +++ b/crates/compose/src/wear.rs @@ -65,9 +65,9 @@ pub(crate) fn grunge(kind: GeneratorKind, wear: &WearParameters, seed: u32, coor /// Where a custom grunge image is read: repeated grunge-scale times across the UV square (or the mesh's bounds, triplanar) pub(crate) fn custom_grunge_placement(wear: &WearParameters) -> SlotPlacement { if wear.triplanar { - SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast) } + SlotPlacement { scale: wear.grunge_scale, offset: 0.0, triplanar_contrast: Some(wear.triplanar_contrast), mirrored_about_centre: false } } else { - SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None } + SlotPlacement { scale: wear.grunge_scale, offset: CUSTOM_GRUNGE_UV_OFFSET, triplanar_contrast: None, mirrored_about_centre: false } } } From 0d1f687b9abb13b294e02242eed8eda3729b0a70 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:35:22 +0000 Subject: [PATCH 52/54] Generators: a histogram's cut stack reads the anchor heights the whole stack prepared A histogram evaluates the stack cut below an effect: it rebuilt every anchor height under the cut's stack key, replacing the viewport's, so the next render built them again. A cut now builds only heights that are missing and leaves the set's prepared ones as they are. Review tidying: blank lines, histogram scan comment, the field cache test reads the cache's size. --- crates/compose/src/dripping_rust.rs | 1 + crates/compose/src/eval.rs | 49 ++++++++++++++++---- crates/compose/src/eval/evaluation_inputs.rs | 13 ++++++ crates/compose/src/field_cache.rs | 2 +- crates/compose/src/generator_maps.rs | 2 +- crates/compose/src/histogram_scan.rs | 5 +- crates/compose/src/micro_details/mod.rs | 5 ++ 7 files changed, 64 insertions(+), 13 deletions(-) diff --git a/crates/compose/src/dripping_rust.rs b/crates/compose/src/dripping_rust.rs index 43e42858..859088c9 100644 --- a/crates/compose/src/dripping_rust.rs +++ b/crates/compose/src/dripping_rust.rs @@ -118,6 +118,7 @@ fn drips(inp: &Inputs, rust: &DrippingRustParameters, field: &[f32], (width, hei } field.get((y * i64::from(width) + x) as usize).copied() }; + // Central differences, one-sided at an island's border let slope = |before: Option, here: f32, after: Option| match (before, after) { (Some(before), Some(after)) => (after - before) * 0.5, diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 582f5bbf..e621c528 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2445,7 +2445,9 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { } } } - crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); + if inp.whole_stack() { + crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); + } if readers.is_empty() { return; } @@ -2457,6 +2459,10 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { }; readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { + // A stack cut below an effect (a histogram's) reads the heights the whole stack prepared, building only those missing + if !inp.whole_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { + continue; + } let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; crate::micro_details::prepare_anchor_heights(inp, anchor, stack, || anchor_heights(inp, reader, anchor)); } @@ -3446,6 +3452,7 @@ impl<'a, 'b> Texel<'a, 'b> { if let Some(section) = generator.section_controls() { return self.section_signal(generator, §ion, maps); } + // The kinds with only their own controls: resolved once per plan, not per texel let resolved; let controls = match maps.controls.as_deref() { @@ -5111,7 +5118,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let (cut, in_mask) = cut_below(inp.project, owner, effect)?; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); let channels = evaluation_channels(&cut_inp, cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default()); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); @@ -5235,7 +5242,7 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); let mut channels = evaluation_channels(&cut_inp, set.channel_list()); if !channels.contains(&channel) { channels.push(channel); @@ -7343,6 +7350,31 @@ soft {soft:?}" assert!(largest_change < 1e-4, "{largest_change}"); } + #[test] + fn a_histogram_below_a_reader_leaves_the_anchor_heights_it_reads() { + let (mut fixture, images) = micro_height_fixture(); + let id = fixture.project.alloc_id(); + let (low, anchor) = anchored_height(&mut fixture, id, Source::image("disc")); + let levels = content_fx(&mut fixture, low, EffectKind::Levels(Default::default())); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(reading_micro_height(anchor)))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + run_with_images(&fixture, None, &images); + + // The histogram evaluates the stack cut below the levels + effect_histogram(&inputs(&fixture, &images, None), levels, Channel::Height, 16); + + let stack = StackKey::new(&fixture.project, &fixture.pixels, &fixture.baked, &images, 0, &fixture.project.texture_sets[0].stack) + .expect("the plane's stack has a key"); + let builds = std::cell::Cell::new(0); + crate::micro_details::prepare_anchor_heights(&inputs(&fixture, &images, None), anchor, stack, || { + builds.set(builds.get() + 1); + AnchorHeights::new(vec![0.0; 64 * 64], (64, 64), fixture.project.texture_sets[0].block_scales()) + }); + assert_eq!(builds.get(), 0, "the render's heights are still prepared"); + } + #[test] fn anchor_heights_are_built_again_at_another_working_size() { let (mut fixture, images) = micro_height_fixture(); @@ -7368,7 +7400,7 @@ soft {soft:?}" assert_eq!(builds.get(), 2, "a smaller working atlas builds them again"); } - /// Builds a field cache made: the counter goes up with each build + /// A field build that counts each call in `builds` fn counted_build(builds: &std::cell::Cell) -> impl FnOnce((u32, u32)) -> Vec + '_ { move |_| { builds.set(builds.get() + 1); @@ -7420,7 +7452,7 @@ soft {soft:?}" #[test] fn a_whole_map_field_read_again_outlives_fields_built_before_it() { - const FIELDS_KEPT: u32 = 8; + let fields_kept = crate::field_cache::CACHE_ENTRIES as u32; let cache = crate::field_cache::FieldCache::new(); let builds = std::cell::Cell::new(0); let fixture = fixture(); @@ -7430,9 +7462,9 @@ soft {soft:?}" let field = |settings: u32| { cache.get_or_build(&inputs, coverage, &[], vec![settings], counted_build(&builds)); }; - (0..FIELDS_KEPT).for_each(field); + (0..fields_kept).for_each(field); field(0); - field(FIELDS_KEPT); + field(fields_kept); let built = builds.get(); field(0); @@ -7457,8 +7489,7 @@ soft {soft:?}" let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(Generator { micro, ..earlier }))); fixture.project.layer_mut(top).unwrap().mask = Some(mask); - let composite = run(&fixture, None); - (0..64 * 64).map(|index| composite.value(Channel::BaseColor, index % 64, index / 64)[0]).collect() + base_color_reds(&run(&fixture, None)) }; // The saved micro detail added the anchor's height times its amount to the curvature signal, even where the height is flat diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index dbb8f392..ae870daa 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -23,6 +23,8 @@ pub(super) struct EvaluationInputs<'a> { depth_maps: Mutex>, gradients: Mutex>>, coverage: OnceLock, + /// The project is the session's stack as drawn, not one cut below an effect (a histogram's) + whole_stack: bool, } impl<'a> EvaluationInputs<'a> { @@ -35,9 +37,20 @@ impl<'a> EvaluationInputs<'a> { depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), coverage: OnceLock::new(), + whole_stack: true, } } + /// These inputs evaluating a project cut below an effect: it reads the anchor heights the whole stack prepared + pub(super) fn below_a_cut(self) -> Self { + Self { whole_stack: false, ..self } + } + + /// Whether the project evaluated is the session's whole stack + pub(super) fn whole_stack(&self) -> bool { + self.whole_stack + } + /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) pub(super) fn coverage_identity(&self) -> u64 { *self.coverage.get_or_init(|| crate::field_cache::coverage_identity(self.inputs.gbuf)) diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 51581173..e03fcc94 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -9,7 +9,7 @@ use crate::field_cache_key::FieldCacheKey; use crate::working_field::working_block; /// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) -const CACHE_ENTRIES: usize = 8; +pub(crate) const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; /// Texels hashed together before their hashes are combined, so the coverage hashes in parallel diff --git a/crates/compose/src/generator_maps.rs b/crates/compose/src/generator_maps.rs index 503a32c9..cd9b6e4a 100644 --- a/crates/compose/src/generator_maps.rs +++ b/crates/compose/src/generator_maps.rs @@ -28,7 +28,7 @@ pub(crate) struct GeneratorMaps { impl GeneratorMaps { /// The maps `generator` reads, with the detail sizes `needed` marks (one flag per blurred size); `coverage` gives the working layout's coverage identity for whole-map fields - pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl Fn() -> u64) -> GeneratorMaps { + pub fn of(inp: &Inputs, generator: &Generator, needed: &[bool], coverage: impl FnOnce() -> u64) -> GeneratorMaps { let micro = generator.micro_in_use().map(|micro| micro.clone().clamped(generator.kind)); let micro_curvature = micro.as_ref().filter(|_| MicroDetails::has_curvature(generator.kind)).and_then(|micro| MicroCurvature::of(inp, generator.kind, micro)); diff --git a/crates/compose/src/histogram_scan.rs b/crates/compose/src/histogram_scan.rs index 8c474d7e..9e1bbbf7 100644 --- a/crates/compose/src/histogram_scan.rs +++ b/crates/compose/src/histogram_scan.rs @@ -11,8 +11,9 @@ pub(crate) fn histogram_scan(value: f32, position: f32, contrast: f32) -> f32 { } let width = 1.0 - contrast.clamp(0.0, 1.0); - // The ramp's low end runs from 1 at position 0 to −width at position 1, so the ends are wholly black or white - let low = (1.0 - position.clamp(0.0, 1.0)) * (1.0 + width) - width; + + // The ramp's low end runs from 1 towards position 0 to −width towards position 1 + let low = (1.0 - position) * (1.0 + width) - width; if width <= f32::EPSILON { return if value >= low { 1.0 } else { 0.0 }; } diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index 4ee72fd3..4120d0ed 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -111,6 +111,11 @@ pub(crate) fn prepare_anchor_heights(inp: &Inputs, anchor: LayerId, stack: Stack entries.push(AnchorEntry { baked, texture_set: inp.ts, anchor, stack, heights }); } +/// Whether heights are prepared for anchor `anchor`, for any stack +pub(crate) fn has_anchor_heights(inp: &Inputs, anchor: LayerId) -> bool { + anchor_heights(inp, anchor).is_some() +} + /// The heights prepared for anchor `anchor` (None before they are) fn anchor_heights(inp: &Inputs, anchor: LayerId) -> Option> { let baked = baked_identity(inp)?; From 5f33d84f1e0a2aaa817bf1614cff6c9f5f7169e9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:40:42 +0000 Subject: [PATCH 53/54] Generators: only the session's own composite drops anchor heights it no longer reads Thumbnails, solo layers and histograms evaluate cut-down stacks without every reader: they now build only missing heights and drop none, so a thumbnail refresh no longer throws away the viewport's. Doc full stops on the touched preparation functions. --- crates/compose/src/eval.rs | 16 ++++++++-------- crates/compose/src/eval/evaluation_inputs.rs | 18 +++++++++--------- crates/compose/src/micro_details/mod.rs | 2 +- crates/ui-egui/tests/it/generator_panel.rs | 5 +++-- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e621c528..944ac73c 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2418,7 +2418,7 @@ fn compares_this_layer(kind: &EffectKind) -> bool { matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) } -/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel fn prepare_curvature_sizes(inp: &EvaluationInputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); @@ -2445,7 +2445,8 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { } } } - if inp.whole_stack() { + // Only the session's own stack knows every reader: a cut-down one (a histogram's, a thumbnail's) builds what is missing and drops nothing + if inp.is_session_stack() { crate::micro_details::keep_anchor_heights(inp, &readers.iter().map(|(_, anchor)| *anchor).collect::>()); } if readers.is_empty() { @@ -2459,8 +2460,7 @@ fn prepare_micro_anchors(inp: &EvaluationInputs) { }; readers.sort_by_key(|(_, anchor)| drawn_at(*anchor)); for (reader, anchor) in readers { - // A stack cut below an effect (a histogram's) reads the heights the whole stack prepared, building only those missing - if !inp.whole_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { + if !inp.is_session_stack() && crate::micro_details::has_anchor_heights(inp, anchor) { continue; } let Some(stack) = StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack) else { return }; @@ -2511,7 +2511,7 @@ fn wear_parameters(generator: &Generator) -> Option { generator.wear.or_else(|| WearParameters::defaults(generator.kind).filter(|_| generator.kind == GeneratorKind::FiberGlassEdgeWear)) } -/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel fn prepare_mask_curvature_sizes<'a>(inp: &EvaluationInputs, masks: impl Iterator) { let mut needed = [false; LEVEL_RADII.len()]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { @@ -4407,7 +4407,7 @@ pub fn composite_tiles_with_projectors( cache.bind_mesh(mesh); } - let inputs = EvaluationInputs::new(inputs, projectors); + let inputs = EvaluationInputs::new(inputs, projectors).of_the_session_stack(); composite_evaluation_tiles(&inputs, out, tiles, below); } @@ -5118,7 +5118,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u let (cut, in_mask) = cut_below(inp.project, owner, effect)?; let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let channels = evaluation_channels(&cut_inp, cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default()); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); @@ -5242,7 +5242,7 @@ pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option< let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors).below_a_cut(); + let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); let mut channels = evaluation_channels(&cut_inp, set.channel_list()); if !channels.contains(&channel) { channels.push(channel); diff --git a/crates/compose/src/eval/evaluation_inputs.rs b/crates/compose/src/eval/evaluation_inputs.rs index ae870daa..257ee055 100644 --- a/crates/compose/src/eval/evaluation_inputs.rs +++ b/crates/compose/src/eval/evaluation_inputs.rs @@ -23,8 +23,8 @@ pub(super) struct EvaluationInputs<'a> { depth_maps: Mutex>, gradients: Mutex>>, coverage: OnceLock, - /// The project is the session's stack as drawn, not one cut below an effect (a histogram's) - whole_stack: bool, + /// The project is the session's own stack as the viewport composites it, not one cut down (a histogram's, a thumbnail's, a solo layer's) + session_stack: bool, } impl<'a> EvaluationInputs<'a> { @@ -37,18 +37,18 @@ impl<'a> EvaluationInputs<'a> { depth_maps: Mutex::new(Vec::new()), gradients: Mutex::default(), coverage: OnceLock::new(), - whole_stack: true, + session_stack: false, } } - /// These inputs evaluating a project cut below an effect: it reads the anchor heights the whole stack prepared - pub(super) fn below_a_cut(self) -> Self { - Self { whole_stack: false, ..self } + /// These inputs evaluating the session's own stack: they keep the anchor heights the stack reads and drop the rest + pub(super) fn of_the_session_stack(self) -> Self { + Self { session_stack: true, ..self } } - /// Whether the project evaluated is the session's whole stack - pub(super) fn whole_stack(&self) -> bool { - self.whole_stack + /// Whether the project evaluated is the session's own stack (see [`EvaluationInputs::of_the_session_stack`]) + pub(super) fn is_session_stack(&self) -> bool { + self.session_stack } /// The working layout's coverage identity, hashed on first use only: the whole-map generator fields' cache reads it ([`crate::field_cache::coverage_identity`]) diff --git a/crates/compose/src/micro_details/mod.rs b/crates/compose/src/micro_details/mod.rs index 4120d0ed..74c098b7 100644 --- a/crates/compose/src/micro_details/mod.rs +++ b/crates/compose/src/micro_details/mod.rs @@ -62,7 +62,7 @@ const OCCLUSION_STRENGTH: f32 = 0.3232; const CACHE_ENTRIES: usize = 8; const CACHE_BYTES: usize = 256 << 20; -/// The anchor heights prepared last, one per mesh maps, texture set and anchor +/// The anchor heights prepared last, one per mesh maps, texture set and anchor: a working-size atlas each, kept while the session's stack reads it and its mesh maps live static ANCHOR_HEIGHTS: Mutex> = Mutex::new(Vec::new()); /// The mesh maps (by address) and texture sets whose anchor heights are being built: the build composites the stack, which prepares them again diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs index 3b5c8c2d..38eaf6d5 100644 --- a/crates/ui-egui/tests/it/generator_panel.rs +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -94,9 +94,10 @@ fn global_blur_applies_as_one_undo_step() { #[test] fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + const SET_FACTOR: i8 = -2; let (mut harness, effect) = harness(false); assert!(harness.get_by_role_and_label(Role::Button, "Restore defaults").accesskit_node().is_disabled(), "at its defaults it does nothing"); - let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": SET_FACTOR, "seed": 99}); execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); harness.run_steps(3); @@ -104,7 +105,7 @@ fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { // Resolution has its own band: restoring the parameters leaves it as set let restored = generator(&harness, effect); - assert_eq!(restored.resolution.factor, -2); + assert_eq!(restored.resolution.factor, SET_FACTOR); assert_eq!(Generator { resolution: Generator::new(GeneratorKind::Curvature).resolution, ..restored }, Generator::new(GeneratorKind::Curvature)); } From eda6f834deb991127489fb4aec1d55d49c77a7a4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:42:35 +0000 Subject: [PATCH 54/54] Generators: a whole-map field's sampled mesh map is a type of its own (clippy type_complexity) --- crates/compose/src/field_cache.rs | 7 +++++-- crates/compose/src/field_cache_key.rs | 25 ++++--------------------- crates/compose/src/lib.rs | 1 + crates/compose/src/sampled_map.rs | 14 ++++++++++++++ 4 files changed, 24 insertions(+), 23 deletions(-) create mode 100644 crates/compose/src/sampled_map.rs diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index e03fcc94..42ad9ebc 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -6,6 +6,7 @@ use texturecraft_geom::UvGBuffer; use crate::eval::Inputs; use crate::field_cache_key::FieldCacheKey; +use crate::sampled_map::SampledMap; use crate::working_field::working_block; /// Most fields cached, and the bytes they may hold (the newest is kept whatever its size) @@ -47,7 +48,9 @@ impl FieldCache { ) -> Arc> { let gbuf = inp.gbuf; let block = working_block(inp); - let read = maps.iter().filter_map(|map| inp.baked.maps.get(map).map(|data| (Arc::downgrade(data), (inp.baked.resolution, inp.baked.height(*map))))); + let read = maps.iter().filter_map(|map| { + inp.baked.maps.get(map).map(|data| SampledMap { data: Arc::downgrade(data), baked_size: (inp.baked.resolution, inp.baked.height(*map)) }) + }); let key = FieldCacheKey { layout: gbuf.tri.as_ptr() as usize, size: (gbuf.width, gbuf.height), @@ -63,7 +66,7 @@ impl FieldCache { // A hit moves to the most recently used end let cached = { let mut entries = self.entries.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - entries.retain(|(key, _)| key.maps.iter().all(|(map, _)| map.strong_count() > 0)); + entries.retain(|(key, _)| key.maps.iter().all(|map| map.data.strong_count() > 0)); let hit = entries.iter().position(|(cached, _)| *cached == key).map(|index| entries.remove(index)); hit.map(|(cached, field)| { entries.push((cached, field.clone())); diff --git a/crates/compose/src/field_cache_key.rs b/crates/compose/src/field_cache_key.rs index 1010ac97..2f44ab4f 100644 --- a/crates/compose/src/field_cache_key.rs +++ b/crates/compose/src/field_cache_key.rs @@ -1,9 +1,9 @@ -use std::sync::Weak; - use texturecraft_core::BlockScales; +use crate::sampled_map::SampledMap; + /// What a field was built from: the working layout (the g-buffer's address, size, coverage, UV tile block and tile scales), the mesh's positions and UVs, the mesh maps it reads and its settings' bits -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub(crate) struct FieldCacheKey { pub(crate) layout: usize, pub(crate) size: (u32, u32), @@ -14,23 +14,6 @@ pub(crate) struct FieldCacheKey { /// The mesh's positions and UVs, each by address and length: a UV edit changes island fields pub(crate) positions: (usize, usize), pub(crate) uvs: (usize, usize), - /// The mesh maps it samples, each with the size it was baked at: one allocation read as another layout reads other texels - pub(crate) maps: Vec<(Weak>, (u32, u32))>, + pub(crate) maps: Vec, pub(crate) settings: Vec, } - -impl PartialEq for FieldCacheKey { - fn eq(&self, other: &FieldCacheKey) -> bool { - let same_maps = self.maps.len() == other.maps.len() - && self.maps.iter().zip(&other.maps).all(|((a, a_size), (b, b_size))| a.strong_count() > 0 && a.ptr_eq(b) && a_size == b_size); - same_maps - && self.layout == other.layout - && self.size == other.size - && self.coverage == other.coverage - && self.block == other.block - && self.scales == other.scales - && self.positions == other.positions - && self.uvs == other.uvs - && self.settings == other.settings - } -} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e7d72fe8..724cf4ad 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -43,6 +43,7 @@ pub mod projector_cover; pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; +mod sampled_map; mod sections; mod shape_distance; mod slope_texel; diff --git a/crates/compose/src/sampled_map.rs b/crates/compose/src/sampled_map.rs new file mode 100644 index 00000000..1583f3f6 --- /dev/null +++ b/crates/compose/src/sampled_map.rs @@ -0,0 +1,14 @@ +use std::sync::Weak; + +/// A mesh map a whole-map field samples: its allocation and the size it was baked at (one allocation read as another layout reads other texels) +#[derive(Clone)] +pub(crate) struct SampledMap { + pub(crate) data: Weak>, + pub(crate) baked_size: (u32, u32), +} + +impl PartialEq for SampledMap { + fn eq(&self, other: &SampledMap) -> bool { + self.data.strong_count() > 0 && self.data.ptr_eq(&other.data) && self.baked_size == other.baked_size + } +}