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] 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