From 37edd3c44b6158617890f026807ead6014e1b087 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:43:05 +0000 Subject: [PATCH 1/9] Tile Generator pattern and pattern resolution A Tile Generator pattern kind lays shapes out in a grid of tiles: 15 shapes and image inputs, tile counts, row or column offset, middle size, interstice, size modes, scale, free and quarter-turn rotation, mirroring, per-tile random scale, position, rotation and luminance, masks, Add/Max/Add sub blending, background, opacity and a position/contrast window. Its settings are a TileGenerator on Procedural (saved only for that kind). Every pattern gets an output resolution like generators: below the UV tile's resolution it is read from an image of that size, bilinearly. Patterns saved before keep their form and render unchanged. --- crates/compose/src/eval.rs | 10 +- crates/compose/src/lib.rs | 2 + crates/compose/src/pattern.rs | 52 +- crates/compose/src/tile_pattern.rs | 447 ++++++++++++++++++ crates/compose/src/tile_random_stream.rs | 52 ++ crates/core/src/layer.rs | 88 +++- crates/core/src/layer/tile_blending.rs | 23 + crates/core/src/layer/tile_generator.rs | 265 +++++++++++ .../core/src/layer/tile_input_distribution.rs | 22 + crates/core/src/layer/tile_shape.rs | 67 +++ crates/core/src/layer/tile_size_mode.rs | 32 ++ crates/core/src/layer/tile_symmetry.rs | 22 + crates/core/src/lib.rs | 3 +- crates/engine/src/material_lib.rs | 6 +- crates/engine/src/materials.rs | 2 +- crates/engine/src/smart_masks.rs | 2 +- 16 files changed, 1071 insertions(+), 24 deletions(-) create mode 100644 crates/compose/src/tile_pattern.rs create mode 100644 crates/compose/src/tile_random_stream.rs create mode 100644 crates/core/src/layer/tile_blending.rs create mode 100644 crates/core/src/layer/tile_generator.rs create mode 100644 crates/core/src/layer/tile_input_distribution.rs create mode 100644 crates/core/src/layer/tile_shape.rs create mode 100644 crates/core/src/layer/tile_size_mode.rs create mode 100644 crates/core/src/layer/tile_symmetry.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 7bea1c3d..c8423295 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -21,7 +21,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; +use crate::pattern::{Coords, decal_uv, image_samples, pattern_pixels, procedural_sized, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; const NCH: usize = Channel::ALL.len(); @@ -1423,7 +1423,13 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { let (coords, projection, _) = self.projected(projection); - let amount = procedural(pattern, projection, &coords); + let pixels = if pattern.resolution.can_reduce() { + let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(self.inp.tile_res(), |set| set.resolution); + pattern_pixels(pattern, self.inp.tile_res(), texture_set) + } else { + None + }; + let amount = procedural_sized(pattern, projection, &coords, pixels); mix3(*low, *high, amount) } Source::Image { name, normal_format } => { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a181a337..f80e441c 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -18,6 +18,8 @@ mod image_identity; pub mod pattern; pub mod store; pub mod thumb; +mod tile_pattern; +mod tile_random_stream; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 44c33692..44da3236 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -143,6 +143,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { let (g1, _, _) = noise::cellular((p * 2.7 + Vec3::splat(13.0)).to_array(), seed ^ 0x6B); smoothstep(0.08, 0.16, f1).min(smoothstep(0.06, 0.12, g1)) } + ProceduralKind::TileGenerator => crate::tile_pattern::value(&crate::tile_pattern::DEFAULT, p.truncate(), seed), ProceduralKind::Chips => { let (f1, _, _) = noise::cellular((p * 2.0).to_array(), seed ^ 0x45); let n = noise::fbm(a, 5, seed, noise::perlin) + (f1 - 0.5) * 0.25; @@ -200,16 +201,23 @@ fn shape(pr: &Procedural, v: f32) -> f32 { if pr.invert { 1.0 - v } else { v } } -/// Evaluate a procedural through a projection. +/// Evaluate a procedural through a projection, at full resolution pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { + procedural_sized(pattern, projection, coords, None) +} + +/// Evaluate a procedural through a projection, drawn as an image of `pixels` texels per side over one repeat of the projection (read back bilinearly) when its resolution asks for one: see [`pattern_pixels`]. `None` evaluates it exactly +pub fn procedural_sized(pattern: &Procedural, projection: &Projection, coords: &Coords, pixels: Option) -> f32 { let pattern_scale = pattern.scale.max(1e-4); + let cells = pixels.map(|pixels| pixels as f32 / pattern_scale); + let sample = |point: Vec3| plane_value(pattern, point, cells); let value = match projection { Projection::Uv { scale, rotation, offset } => { let (sn, cs) = rotation.to_radians().sin_cos(); let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); // Evaluate two-dimensional patterns on a slice of the volume - raw(pattern.kind, (uv * pattern_scale).extend(0.0), pattern.seed) + sample((uv * pattern_scale).extend(0.0)) } Projection::Triplanar { scale, sharpness, offset } => { let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); @@ -217,7 +225,7 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords // Shape scales the blend by the contrast let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))]; - planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| raw(pattern.kind, q, pattern.seed) * w).sum() + planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum() } Projection::Planar { scale, axis, offset } => { let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); @@ -226,13 +234,13 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords 1 => Vec3::new(p.x, p.z, 0.0), _ => Vec3::new(p.x, p.y, 0.0), }; - raw(pattern.kind, q, pattern.seed) + sample(q) } Projection::Spherical { scale } => { let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - raw(pattern.kind, Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale, pattern.seed) + sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale) } Projection::Cylindrical { scale, axis } => { let p = coords.pos; @@ -242,15 +250,45 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords _ => (p.x, p.y, p.z), }; let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - raw(pattern.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale, pattern.seed) + sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale) } // The decal already supplied coordinates in its local frame - Projection::Decal(_) => raw(pattern.kind, (coords.uv * pattern_scale).extend(0.0), pattern.seed), + Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)), }; shape(pattern, value) } +/// The texels per side `pattern`'s resolution draws it at for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`, when that is coarser than the UV tile (a finer image changes nothing: patterns are evaluated per texel) +pub fn pattern_pixels(pattern: &Procedural, uv_tile: u32, texture_set: u32) -> Option { + if !pattern.resolution.can_reduce() { + return None; + } + + let size = pattern.resolution.output_size(uv_tile, texture_set); + (size < uv_tile).then_some(size) +} + +/// The pattern at `point` of its plane, read from an image of `cells` texels per unit (bilinear) when given +fn plane_value(pr: &Procedural, point: Vec3, cells: Option) -> f32 { + let Some(cells) = cells.filter(|cells| cells.is_finite() && *cells > 0.0) else { return pattern_value(pr, point) }; + let grid = point.truncate() * cells - 0.5; + let base = grid.floor(); + let fraction = grid - base; + let at = |dx: f32, dy: f32| pattern_value(pr, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z)); + let top = at(0.0, 0.0) + (at(1.0, 0.0) - at(0.0, 0.0)) * fraction.x; + let bottom = at(0.0, 1.0) + (at(1.0, 1.0) - at(0.0, 1.0)) * fraction.x; + top + (bottom - top) * fraction.y +} + +/// The pattern at `point` of its plane, exactly +fn pattern_value(pr: &Procedural, point: Vec3) -> f32 { + match (&pr.tile, pr.kind) { + (Some(tile), ProceduralKind::TileGenerator) => crate::tile_pattern::value(tile, point.truncate(), pr.seed), + _ => raw(pr.kind, point, pr.seed), + } +} + /// Texture coordinates (and blend weights) at which an image is sampled for a projection /// (unused slots weigh 0; no allocation per texel). pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs new file mode 100644 index 00000000..490a0d37 --- /dev/null +++ b/crates/compose/src/tile_pattern.rs @@ -0,0 +1,447 @@ +//! The Tile Generator pattern: shapes in a grid of tiles over one repeating unit, x right and y down as a texture's rows + +use std::sync::LazyLock; + +use texturecraft_core::{TileBlending, TileGenerator, TileShape, TileSizeMode, TileSymmetry}; +use texturecraft_geom::glam::Vec2; + +use crate::tile_random_stream::TileRandomStream; + +/// The settings a Tile Generator pattern saved without its own reads +pub(crate) static DEFAULT: LazyLock = LazyLock::new(TileGenerator::default); + +/// The output size the pixel size mode measures shapes against +const PIXEL_REFERENCE: f32 = 2048.0; +/// Position random moves a tile up to this many cells times its amount, either way +const POSITION_RANDOM_CELLS: f32 = 1.0; +/// Capsule shape: the radius of its round ends +const CAPSULE_RADIUS: f32 = 0.2225; +/// Half bell shape: the width of its squashed half at a specific of 0 +const HALF_BELL_WIDTH: f32 = 1.24; +/// Gaussian shape: the falloff exponent, 2^(−k·r²) +const GAUSSIAN_FALLOFF: f32 = 16.0; +/// Crescent shape: scales its ring r²(1 − r²)² to a peak of 1 +const CRESCENT_GAIN: f32 = 6.75; +/// Waves shape: cycles across the tile at a specific of 0, and the cycles a specific of 1 adds +const WAVES_BASE_CYCLES: f32 = 1.5; +const WAVES_SPECIFIC_CYCLES: f32 = 6.0; +/// Narrower than this, a size or a bevel is none +const EPSILON: f32 = 1e-6; +/// Tiles a texel looks at, at most, along each axis (bounds the work of huge or far-moved shapes) +const MAX_REACH: i32 = 16; + +fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn bell(r: f32) -> f32 { + (1.0 - r * r).clamp(0.0, 1.0).powi(4) +} + +/// The shape's value at (u, v) of its square (−1..1 both ways; 0 outside it). `specific` changes some shapes +fn shape(kind: TileShape, u: f32, v: f32, specific: f32) -> f32 { + if u.abs() > 1.0 || v.abs() > 1.0 { + return 0.0; + } + let r = u.hypot(v); + match kind { + TileShape::Square => 1.0, + TileShape::Disc => f32::from(u8::from(r <= 1.0)), + TileShape::Paraboloid => (1.0 - r * r).clamp(0.0, 1.0), + TileShape::Bell => bell(r), + TileShape::Gaussian => (-GAUSSIAN_FALLOFF * r * r).exp2(), + TileShape::Thorn => (1.0 - r).clamp(0.0, 1.0).powi(4), + TileShape::Pyramid => (1.0 - u.abs().max(v.abs())).clamp(0.0, 1.0), + TileShape::Cone => (1.0 - r).clamp(0.0, 1.0), + TileShape::Brick if specific <= EPSILON => 1.0, + TileShape::Brick => smoothstep((1.0 - u.abs()) / specific) * smoothstep((1.0 - v.abs()) / specific), + TileShape::Gradation => (u + 1.0) * 0.5 * (1.0 - specific), + TileShape::Waves => { + let cycles = WAVES_BASE_CYCLES + WAVES_SPECIFIC_CYCLES * specific; + (1.0 - r * r).clamp(0.0, 1.0) * (0.5 + 0.5 * (std::f32::consts::TAU * cycles * u).cos()) + } + TileShape::HalfBell => { + let width = HALF_BELL_WIDTH * (1.0 - specific); + let cut = match (u > 0.0, width > EPSILON) { + (false, _) => 1.0, + (true, true) => bell(u / width), + (true, false) => 0.0, + }; + bell(r) * cut + } + TileShape::RidgedBell => bell(r) * (1.0 - u.abs()).powi(2), + TileShape::Crescent if specific >= 1.0 => 0.0, + TileShape::Crescent => { + let shifted = (u + 1.0) / (1.0 - specific) - 1.0; + let ring = (1.0 - r * r).clamp(0.0, 1.0); + CRESCENT_GAIN * r * r * ring * ring * smoothstep((1.0 - shifted) * 0.5) + } + TileShape::Capsule => { + let half_length = specific * (1.0 - CAPSULE_RADIUS); + let distance = (u.abs() - half_length).max(0.0).hypot(v); + (1.0 - (distance / CAPSULE_RADIUS).powi(2)).clamp(0.0, 1.0) + } + // The image shape reads the pattern's input images, which the plane alone cannot: nothing until they are given + TileShape::Image => 0.0, + } +} + +/// `point` turned clockwise on screen by `turns` undone (y runs down) +fn unrotate(point: Vec2, turns: f32) -> Vec2 { + if turns == 0.0 { + return point; + } + let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos(); + Vec2::new(cos * point.x + sin * point.y, -sin * point.x + cos * point.y) +} + +/// The pattern section: tile-local (u, v) through the shape's tiling, angle, scale, size and 45° turn, then the shape +fn pattern(tile: &TileGenerator, local: Vec2) -> f32 { + if local.x.abs() > 1.0 || local.y.abs() > 1.0 { + return 0.0; + } + let mut local = local; + if tile.shape_tiling > 1 { + // The shape repeats tiling × tiling times, but one copy shows: the one at index ceil(tiling / 2) − 1 from the top left + let count = tile.shape_tiling as f32; + let shown = (tile.shape_tiling.div_ceil(2) - 1) as f32; + let cell = (local + 1.0) * 0.5 * count; + if cell.x.floor() != shown || cell.y.floor() != shown { + return 0.0; + } + local = (cell - shown) * 2.0 - 1.0; + } + local = unrotate(local, tile.shape_angle / 360.0); + let size = Vec2::from(tile.shape_size) * tile.shape_scale; + if size.x <= EPSILON || size.y <= EPSILON { + return 0.0; + } + local /= size; + if tile.shape_diagonal { + local = unrotate(local, 0.125) * std::f32::consts::SQRT_2; + } + let samples = Vec2::new(tile.shape_resolution[0] as f32, tile.shape_resolution[1] as f32); + sampled_shape(tile, local, samples) +} + +/// The shape read from an image of `samples` texels over its square, bilinearly, as the shape is drawn at its own resolution +fn sampled_shape(tile: &TileGenerator, local: Vec2, samples: Vec2) -> f32 { + let grid = (local + 1.0) * 0.5 * samples - 0.5; + let base = grid.floor(); + let fraction = grid - base; + let at = |dx: f32, dy: f32| { + let texel = (base + Vec2::new(dx, dy) + 0.5) / samples * 2.0 - 1.0; + shape(tile.shape, texel.x, texel.y, tile.specific) + }; + let top = at(0.0, 0.0) + (at(1.0, 0.0) - at(0.0, 0.0)) * fraction.x; + let bottom = at(0.0, 1.0) + (at(1.0, 1.0) - at(0.0, 1.0)) * fraction.x; + top + (bottom - top) * fraction.y +} + +/// The start and width, in cells, of cell `index` along an axis whose middle size is `middle` (cells pair up) +fn cell_span(index: i32, middle: f32) -> (f32, f32) { + let pair = index.div_euclid(2) as f32 * 2.0; + if index.rem_euclid(2) == 0 { (pair, 2.0 * middle) } else { (pair + 2.0 * middle, 2.0 * (1.0 - middle)) } +} + +/// `delta` wrapped into −span/2..span/2 (the pattern repeats every `span`) +fn wrap(delta: f32, span: f32) -> f32 { + delta - (delta / span).round() * span +} + +/// What one tile gives a texel (its shape times its luminance), or None when it is hidden or does not reach it +fn tile_value(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), (columns, rows): (i32, i32), point: Vec2) -> Option { + let total = columns * rows; + let number = column * rows + row; + let index = (if tile.reverse_order { total - 1 - number } else { number }) as u32; + if hidden(tile, seed, (column, row), index) { + return None; + } + + let (start_x, width) = cell_span(column, tile.middle_size[0]); + let (start_y, height) = cell_span(row, tile.middle_size[1]); + let mut center = Vec2::new(start_x + width * 0.5, start_y + height * 0.5); + if tile.vertical_offset { + center.y += line_shift(tile, column); + } else { + center.x += line_shift(tile, row); + } + center.x += (TileRandomStream::PositionX.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[0]; + center.y += (TileRandomStream::PositionY.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[1]; + let counts = Vec2::new(columns as f32, rows as f32); + let center = center / counts + Vec2::from(tile.global_offset); + + let scale_factor = 1.0 - tile.scale_random * TileRandomStream::Scale.draw(tile.scale_random_seed, index); + let size = tile_size(tile, seed, index, Vec2::new(width, height) / counts) * tile.scale * scale_factor; + if size.x <= EPSILON || size.y <= EPSILON { + return None; + } + + let delta = Vec2::new(wrap(point.x - center.x, 1.0), wrap(point.y - center.y, 1.0)); + let turns = (tile.rotation + tile.rotation_random * TileRandomStream::Rotation.draw(seed, index) * 360.0) / 360.0; + let mut local = unrotate(delta, turns) * 2.0 / size; + for _ in 0..quarter_turns(tile, seed, (column, row), index) { + local = Vec2::new(local.y, -local.x); + } + let mirrors = tile.symmetry_random * 0.5; + if tile.symmetry != TileSymmetry::Vertical && TileRandomStream::MirrorX.draw(seed, index) < mirrors { + local.x = -local.x; + } + if tile.symmetry != TileSymmetry::Horizontal && TileRandomStream::MirrorY.draw(seed, index) < mirrors { + local.y = -local.y; + } + + let value = pattern(tile, local); + if value <= 0.0 { + return None; + } + let mut luminance = 1.0 - tile.luminance_random * TileRandomStream::Luminance.draw(seed, index); + if tile.luminance_by_number { + luminance *= (number + 1) as f32 / total as f32; + } + if tile.luminance_by_scale { + luminance *= scale_factor; + } + Some(value * luminance) +} + +/// Whether the masks hide tile (column, row), whose randoms are at `index` +fn hidden(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> bool { + let masked = (tile.checker_mask && (column + row).rem_euclid(2) == 1) + || (tile.horizontal_mask && row.rem_euclid(2) == 1) + || (tile.vertical_mask && column.rem_euclid(2) == 0) + || (tile.random_mask > 0.0 && TileRandomStream::Mask.draw(seed, index) < tile.random_mask); + masked != tile.invert_mask +} + +/// The tile's width and height on the plane before its scale, for a cell `cell` wide and high +fn tile_size(tile: &TileGenerator, seed: u32, index: u32, cell: Vec2) -> Vec2 { + match tile.size_mode { + TileSizeMode::NormalInterstice => { + let gap_x = tile.interstice[0] * (1.0 - tile.interstice_random[0] * TileRandomStream::IntersticeX.draw(seed, index)); + let gap_y = tile.interstice[1] * (1.0 - tile.interstice_random[1] * TileRandomStream::IntersticeY.draw(seed, index)); + cell * Vec2::new(1.0 - gap_x, 1.0 - gap_y) + } + TileSizeMode::NormalSize => cell * Vec2::from(tile.size), + TileSizeMode::KeepRatio => Vec2::splat(cell.x.min(cell.y)), + TileSizeMode::Absolute | TileSizeMode::Pixel => { + let size = if tile.size_mode == TileSizeMode::Absolute { Vec2::from(tile.size_absolute) } else { Vec2::from(tile.size_pixel) / PIXEL_REFERENCE }; + let random_x = 1.0 - tile.size_random[0] * TileRandomStream::SizeX.draw(seed, index); + let random_y = 1.0 - tile.size_random[1] * TileRandomStream::SizeY.draw(seed, index); + size * Vec2::new(random_x, random_y) + } + } +} + +/// The quarter turns clockwise of tile (column, row): the set ones, the quincunx pinwheel and the random ones +fn quarter_turns(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> u32 { + let mut turns = u32::from(tile.quarter_turns); + if tile.quincunx_flip { + turns += match (column.rem_euclid(2), row.rem_euclid(2)) { + (0, 0) => 0, + (1, 0) => 3, + (0, _) => 1, + _ => 2, + }; + } + if tile.quarter_turn_random > 0.0 && TileRandomStream::QuarterTurnApplies.draw(seed, index) < tile.quarter_turn_random { + turns += (TileRandomStream::QuarterTurn.draw(seed, index) * 4.0) as u32; + } + turns % 4 +} + +/// How far, in cells along each axis, a tile's center can be from a texel its shape reaches: half its largest size turned, plus its random move and the shift of its center by the middle size +fn reach(tile: &TileGenerator, counts: Vec2) -> Vec2 { + let widest = Vec2::new(tile.middle_size[0].max(1.0 - tile.middle_size[0]), tile.middle_size[1].max(1.0 - tile.middle_size[1])) * 2.0; + let largest = match tile.size_mode { + TileSizeMode::NormalInterstice | TileSizeMode::KeepRatio => widest / counts, + TileSizeMode::NormalSize => widest / counts * Vec2::from(tile.size), + TileSizeMode::Absolute => Vec2::from(tile.size_absolute), + TileSizeMode::Pixel => Vec2::from(tile.size_pixel) / PIXEL_REFERENCE, + } * tile.scale; + let radius = largest.length() * 0.5 * counts; + let moved = Vec2::from(tile.position_random) * POSITION_RANDOM_CELLS; + let middle = Vec2::new((tile.middle_size[0] - 0.5).abs(), (tile.middle_size[1] - 0.5).abs()); + radius + moved + middle +} + +/// The cells along an axis of `count` whose centers can be within `reach` of `position` (in cells): each once, at most `count` +fn near(position: f32, reach: f32, count: i32) -> impl Iterator { + let first = (position - reach - 0.5).floor() as i32; + let last = (position + reach - 0.5).ceil() as i32; + let span = last - first + 1; + let kept = span.clamp(1, count.min(MAX_REACH * 2 + 1)); + // A capped span keeps the cells nearest the texel + let first = first + (span - kept) / 2; + (first..first + kept).map(move |index| index.rem_euclid(count)) +} + +/// The shift along its line of line `line` (a row, or a column with a vertical offset), in cells +fn line_shift(tile: &TileGenerator, line: i32) -> f32 { + tile.offset * line as f32 + tile.offset_random * TileRandomStream::Offset.draw(tile.offset_random_seed, line as u32) +} + +/// The pattern's value at `point` of its plane (one unit = the whole grid, repeating) +pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32) -> f32 { + let tile = tile.clamped_without_images(); + let (columns, rows) = (tile.amount[0] as i32, tile.amount[1] as i32); + let counts = Vec2::new(columns as f32, rows as f32); + let point = Vec2::new(point.x.rem_euclid(1.0), point.y.rem_euclid(1.0)); + let cell = (point - Vec2::from(tile.global_offset)) * counts; + let reach = reach(&tile, counts); + + let mut sum = 0.0f32; + let mut colored = 0.0f32; + let mut add = |value: f32| match tile.blending { + TileBlending::Max => { + sum = sum.max(value); + colored = colored.max(value * tile.color); + } + TileBlending::Add => { + sum += value; + colored += value * tile.color; + } + TileBlending::AddSub => { + sum += value; + colored += value * (2.0 * tile.color - 1.0); + } + }; + + // Lines (rows, or columns with a vertical offset) shift their tiles along them, so the tiles near the texel are found per line + if tile.vertical_offset { + for column in near(cell.x, reach.x, columns) { + for row in near(cell.y - line_shift(&tile, column), reach.y, rows) { + if let Some(value) = tile_value(&tile, seed, (column, row), (columns, rows), point) { + add(value); + } + } + } + } else { + for row in near(cell.y, reach.y, rows) { + for column in near(cell.x - line_shift(&tile, row), reach.x, columns) { + if let Some(value) = tile_value(&tile, seed, (column, row), (columns, rows), point) { + add(value); + } + } + } + } + finish(&tile, sum, colored) +} + +/// The combined tiles over the background, through the pattern's opacity and its position/contrast window +fn finish(tile: &TileGenerator, sum: f32, colored: f32) -> f32 { + let alpha = sum.clamp(0.0, 1.0) * tile.opacity; + let color = colored.clamp(0.0, 1.0) * tile.opacity; + let value = (tile.background * (1.0 - alpha) + color).clamp(0.0, 1.0); + window(value, tile.position, tile.contrast) +} + +/// The position/contrast window: position picks the input range stretched to 0..1 (0.5 keeps it), contrast narrows it around its middle +fn window(value: f32, position: f32, contrast: f32) -> f32 { + let low = (1.0 - 2.0 * position).clamp(0.0, 1.0); + let high = (2.0 - 2.0 * position).clamp(0.0, 1.0); + let middle = (low + high) * 0.5; + let half = (high - low) * 0.5 * (1.0 - contrast); + if half <= EPSILON { + return f32::from(u8::from(value >= middle)); + } + ((value - (middle - half)) / (2.0 * half)).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(tile: &TileGenerator, x: f32, y: f32) -> f32 { + value(tile, Vec2::new(x, y), 1) + } + + /// Bell shapes peak only at their tile's center, so the brightest texel of a cell shows where its tile is + fn bells(amount: [u32; 2]) -> TileGenerator { + TileGenerator { shape: TileShape::Bell, amount, ..TileGenerator::default() } + } + + #[test] + fn tile_centers_follow_the_amounts() { + let tile = bells([4, 2]); + // Cell (i, j) of a 4 × 2 grid is centered at ((i + 0.5) / 4, (j + 0.5) / 2) + for (x, y) in [(0.125, 0.25), (0.375, 0.75), (0.875, 0.25)] { + assert!(at(&tile, x, y) > 0.99, "a tile center at ({x}, {y})"); + } + assert!(at(&tile, 0.25, 0.25) < 0.01, "the bells meet at zero between cells"); + } + + #[test] + fn the_offset_shifts_each_row_along_by_its_share_of_a_cell() { + let tile = TileGenerator { offset: 0.5, ..bells([4, 4]) }; + // Row 0 stays; row 1 (y 0.375) moves half a cell (0.125) to the right + assert!(at(&tile, 0.125, 0.125) > 0.99); + assert!(at(&tile, 0.25, 0.375) > 0.99, "row 1's first tile is centered at x 0.25"); + assert!(at(&tile, 0.125, 0.375) < 0.5); + + let columns = TileGenerator { vertical_offset: true, ..tile }; + assert!(at(&columns, 0.375, 0.25) > 0.99, "a vertical offset moves column 1 down instead"); + } + + #[test] + fn a_free_rotation_turns_the_shape_clockwise() { + // The half bell's bright side is to the left (−x); turned a quarter clockwise it is at the top + let tile = TileGenerator { shape: TileShape::HalfBell, specific: 1.0, amount: [1, 1], ..TileGenerator::default() }; + assert!(at(&tile, 0.3, 0.5) > at(&tile, 0.7, 0.5)); + let turned = TileGenerator { rotation: 90.0, ..tile }; + assert!(at(&turned, 0.5, 0.3) > at(&turned, 0.5, 0.7), "the bright side moved from the left to the top"); + } + + #[test] + fn masks_hide_their_rows_columns_and_checkers() { + let checker = TileGenerator { checker_mask: true, ..bells([2, 2]) }; + assert!(at(&checker, 0.25, 0.25) > 0.99 && at(&checker, 0.75, 0.25) < 0.01, "odd (i + j) is hidden"); + let rows = TileGenerator { horizontal_mask: true, ..bells([2, 2]) }; + assert!(at(&rows, 0.25, 0.25) > 0.99 && at(&rows, 0.25, 0.75) < 0.01, "the horizontal mask hides odd rows"); + let columns = TileGenerator { vertical_mask: true, ..bells([2, 2]) }; + assert!(at(&columns, 0.25, 0.25) < 0.01 && at(&columns, 0.75, 0.25) > 0.99, "the vertical mask hides even columns"); + let inverted = TileGenerator { invert_mask: true, ..columns }; + assert!(at(&inverted, 0.25, 0.25) > 0.99, "invert mask shows what the masks hid"); + } + + #[test] + fn the_position_window_stretches_a_range_and_contrast_makes_a_step() { + assert_eq!(window(0.3, 0.5, 0.0), 0.3, "the middle position leaves the value"); + assert_eq!(window(0.75, 0.25, 0.0), 0.5, "position 0.25 stretches 0.5..1 to 0..1"); + assert_eq!(window(0.49, 0.5, 1.0), 0.0); + assert_eq!(window(0.51, 0.5, 1.0), 1.0, "full contrast cuts at the middle of the range"); + } + + #[test] + fn every_shape_stays_in_range_and_outside_its_square_is_empty() { + for shape_kind in TileShape::ALL { + for specific in [0.0, 0.5, 1.0] { + for step in 0..41 { + let u = step as f32 / 20.0 - 1.0; + let value = shape(shape_kind, u, u * 0.7, specific); + assert!((0.0..=1.0 + 1e-5).contains(&value), "{shape_kind:?} at {u}: {value}"); + } + assert_eq!(shape(shape_kind, 1.2, 0.0, specific), 0.0); + } + } + } + + #[test] + fn hostile_settings_neither_crash_nor_leave_the_range() { + let hostile = TileGenerator { + amount: [0, u32::MAX], + scale: f32::INFINITY, + size_mode: TileSizeMode::Pixel, + size_pixel: [f32::NAN, 1e30], + position_random: [1.0, 1.0], + offset: f32::NAN, + middle_size: [0.0, 1.0], + ..TileGenerator::default() + }; + for step in 0..20 { + let value = at(&hostile, step as f32 * 0.37, -(step as f32) * 1.3); + assert!((0.0..=1.0).contains(&value)); + } + } +} diff --git a/crates/compose/src/tile_random_stream.rs b/crates/compose/src/tile_random_stream.rs new file mode 100644 index 00000000..9a79d49a --- /dev/null +++ b/crates/compose/src/tile_random_stream.rs @@ -0,0 +1,52 @@ +//! The random streams of a Tile Generator + +/// The random streams of a Tile Generator, so the randoms of one tile are independent of each other +#[derive(Clone, Copy)] +pub(crate) enum TileRandomStream { + Luminance = 0, + Scale, + Offset, + PositionX, + PositionY, + Rotation, + QuarterTurn, + QuarterTurnApplies, + MirrorX, + MirrorY, + Mask, + SizeX, + SizeY, + IntersticeX, + IntersticeY, +} + +/// Odd multipliers spreading the seed, the stream and the index over the hash, and its start (the golden ratio's and xxHash32's primes) +const SEED_MIX: u32 = 0x9E37_79B1; +const STREAM_MIX: u32 = 0x85EB_CA77; +const INDEX_MIX: u32 = 0xC2B2_AE3D; +const HASH_START: u32 = 0x27D4_EB2F; +/// The finalizer's multipliers ("lowbias32", an integer hash whose output bits all depend on every input bit) and its rounds +const FINALIZER_MIX_A: u32 = 0x7FEB_352D; +const FINALIZER_MIX_B: u32 = 0x846C_A68B; +const FINALIZER_ROUNDS: usize = 3; +/// The bits a draw keeps: an f32's precision, so every value is exact and below 1 +const DRAW_BITS: u32 = 24; + +impl TileRandomStream { + /// A uniform value in 0..1 per (seed, stream, index): an integer hash, so a tile's randoms do not depend on evaluation order + pub(crate) fn draw(self, seed: u32, index: u32) -> f32 { + let mut hash = seed + .wrapping_mul(SEED_MIX) + .wrapping_add((self as u32).wrapping_mul(STREAM_MIX)) + .wrapping_add(index.wrapping_mul(INDEX_MIX)) + .wrapping_add(HASH_START); + for _ in 0..FINALIZER_ROUNDS { + hash ^= hash >> 16; + hash = hash.wrapping_mul(FINALIZER_MIX_A); + hash ^= hash >> 15; + hash = hash.wrapping_mul(FINALIZER_MIX_B); + hash ^= hash >> 16; + } + (hash >> (u32::BITS - DRAW_BITS)) as f32 / (1u32 << DRAW_BITS) as f32 + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 4eede134..374c912d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -12,6 +12,12 @@ mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod tile_blending; +mod tile_generator; +mod tile_input_distribution; +mod tile_shape; +mod tile_size_mode; +mod tile_symmetry; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; @@ -19,6 +25,12 @@ pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use tile_blending::TileBlending; +pub use tile_generator::TileGenerator; +pub use tile_input_distribution::TileInputDistribution; +pub use tile_shape::TileShape; +pub use tile_size_mode::TileSizeMode; +pub use tile_symmetry::TileSymmetry; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -262,10 +274,12 @@ pub enum ProceduralKind { Pores, /// Sharp-edged paint chips. Chips, + /// Shapes laid out in a grid of tiles, with the settings in [`Procedural::tile`] + TileGenerator, } impl ProceduralKind { - pub const ALL: [ProceduralKind; 23] = [ + pub const ALL: [ProceduralKind; 24] = [ ProceduralKind::Clouds, ProceduralKind::Perlin, ProceduralKind::Noise, @@ -289,6 +303,7 @@ impl ProceduralKind { ProceduralKind::Smudges, ProceduralKind::Pores, ProceduralKind::Chips, + ProceduralKind::TileGenerator, ]; pub fn label(self) -> &'static str { match self { @@ -315,6 +330,7 @@ impl ProceduralKind { ProceduralKind::Smudges => "Fingerprints", ProceduralKind::Pores => "Pores", ProceduralKind::Chips => "Paint chips", + ProceduralKind::TileGenerator => "Tile Generator", } } pub fn parse(s: &str) -> Option { @@ -335,11 +351,33 @@ pub struct Procedural { /// Shifts the pattern brighter (+) or darker (−). pub balance: f32, pub invert: bool, + /// The Tile Generator's settings; `None` for other kinds (and reads as the defaults); loaded in range, as drawing trusts them + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "tile_in_range")] + pub tile: Option>, + /// The resolution the pattern is computed at before it is sampled onto the texture set + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, +} + +/// Saved Tile Generator settings brought into range (a saved project is hostile input) +fn tile_in_range<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result>, D::Error> { + let saved: Option> = Deserialize::deserialize(deserializer)?; + Ok(saved.map(|tile| Box::new(tile.clamped()))) } impl Procedural { + /// The scales a command accepts (repeats per projection unit) + pub const MIN_SCALE: f32 = 0.001; + pub const MAX_SCALE: f32 = 1000.0; + /// The strongest contrast a command accepts, and the furthest balance either way + pub const MAX_CONTRAST: f32 = 20.0; + pub const MAX_BALANCE: f32 = 1.0; + pub fn new(kind: ProceduralKind) -> Procedural { - Procedural { kind, scale: 4.0, seed: 1, contrast: 1.0, balance: 0.0, invert: false } + let tile = (kind == ProceduralKind::TileGenerator).then(Box::default); + // The Tile Generator lays its whole grid over one projection unit, as its tile counts set its frequency + let scale = if tile.is_some() { 1.0 } else { 4.0 }; + Procedural { kind, scale, seed: 1, contrast: 1.0, balance: 0.0, invert: false, tile, resolution: OutputResolution::default() } } } @@ -372,6 +410,15 @@ impl Source { Source::Image { name: name.into(), normal_format: crate::NormalFormat::OpenGl } } + /// The image resources this source reads: its image, or the images of a Tile Generator pattern + pub fn images(&self) -> Vec<&str> { + match self { + Source::Image { name, .. } => vec![name.as_str()], + Source::Procedural { pattern, .. } => pattern.tile.iter().flat_map(|tile| tile.images()).collect(), + Source::Uniform(_) | Source::Anchor { .. } => Vec::new(), + } + } + /// The anchor point this source reads, if any. pub fn anchor(&self) -> Option { match self { @@ -1126,7 +1173,7 @@ impl EffectKind { anchors } - /// The image resources this effect's sources read (a fill, material or generator input). + /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input) pub fn images_read(&self) -> impl Iterator { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], @@ -1134,10 +1181,7 @@ impl EffectKind { EffectKind::Generator(generator) => generator.inputs.values().collect(), _ => Vec::new(), }; - sources.into_iter().filter_map(|source| match source { - Source::Image { name, .. } => Some(name.as_str()), - _ => None, - }) + sources.into_iter().flat_map(Source::images) } } @@ -1206,6 +1250,36 @@ mod tests { } } + #[test] + fn patterns_saved_before_tile_settings_keep_their_form() { + let saved = serde_json::json!({"kind": "Clouds", "scale": 4.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false}); + let loaded: Procedural = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(loaded, Procedural::new(ProceduralKind::Clouds)); + assert_eq!(serde_json::to_value(&loaded).unwrap(), saved, "a pattern at its defaults saves as before"); + + let tile = serde_json::to_value(Procedural::new(ProceduralKind::TileGenerator)).unwrap(); + assert!( + tile.get("tile").is_some() && tile.get("resolution").is_none(), + "only the Tile Generator carries tile settings, and a default resolution is not saved" + ); + } + + #[test] + fn tile_settings_saved_with_missing_or_hostile_values_load_in_range() { + let tile = serde_json::json!({"amount": [0, 4000], "specific": 7.0, "quarter_turns": 6, "inputs": ["a", "b", "c", "d", "e", "f", "g"]}); + let saved = serde_json::json!({"kind": "TileGenerator", "scale": 1.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false, "tile": tile}); + let loaded: Procedural = serde_json::from_value(saved).unwrap(); + let tile = loaded.tile.unwrap(); + assert_eq!(tile.amount, [1, 64]); + assert_eq!(tile.specific, 1.0); + assert_eq!(tile.quarter_turns, 2); + assert_eq!(tile.inputs.len(), TileGenerator::MAX_INPUTS); + assert_eq!(tile.middle_size, TileGenerator::default().middle_size, "a missing setting reads its default"); + + let not_finite = TileGenerator { scale: f32::NAN, rotation: f32::INFINITY, ..TileGenerator::default() }.clamped(); + assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0)); + } + #[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/tile_blending.rs b/crates/core/src/layer/tile_blending.rs new file mode 100644 index 00000000..9f42f021 --- /dev/null +++ b/crates/core/src/layer/tile_blending.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; + +/// How a Tile Generator combines shapes that overlap +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileBlending { + #[default] + Add, + Max, + /// Adds bright shapes and subtracts dark ones + AddSub, +} + +impl TileBlending { + pub const ALL: [TileBlending; 3] = [TileBlending::Add, TileBlending::Max, TileBlending::AddSub]; + + pub fn label(self) -> &'static str { + match self { + TileBlending::Add => "Add", + TileBlending::Max => "Max", + TileBlending::AddSub => "Add sub", + } + } +} diff --git a/crates/core/src/layer/tile_generator.rs b/crates/core/src/layer/tile_generator.rs new file mode 100644 index 00000000..6836fcd9 --- /dev/null +++ b/crates/core/src/layer/tile_generator.rs @@ -0,0 +1,265 @@ +use serde::{Deserialize, Serialize}; + +use super::tile_blending::TileBlending; +use super::tile_input_distribution::TileInputDistribution; +use super::tile_shape::TileShape; +use super::tile_size_mode::TileSizeMode; +use super::tile_symmetry::TileSymmetry; + +/// The settings of a Tile Generator pattern: shapes laid out in a grid of tiles, in the reference app's sections (pattern, size, position, rotation, color); pairs are `[horizontal, vertical]`; angles are in degrees; the seeds of the random settings are separate from the pattern's seed, as in the reference app +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TileGenerator { + /// The level the output is cut at (0.5 leaves it unchanged) + pub position: f32, + /// How sharply the output is cut at [`TileGenerator::position`] (0 unchanged, 1 a hard step) + pub contrast: f32, + /// Tiles across and down + pub amount: [u32; 2], + /// The reference app's Non Square Expansion, kept with the settings: its outputs match with it on and off, so drawing ignores it + pub non_square_expansion: bool, + + pub shape: TileShape, + /// Texels per side the shape is drawn at before it is laid out + pub shape_resolution: [u32; 2], + /// Changes the shape in its own way (roundness, falloff, ripple count…) + pub specific: f32, + pub shape_angle: f32, + pub shape_scale: f32, + pub shape_size: [f32; 2], + /// Repeats of the shape inside each tile + pub shape_tiling: u32, + /// Turns the shape 45 degrees + pub shape_diagonal: bool, + /// As [`TileGenerator::non_square_expansion`], for the shape itself + pub shape_non_square_expansion: bool, + /// Input images, read when [`TileGenerator::shape`] is [`TileShape::Image`] + pub inputs: Vec, + pub input_distribution: TileInputDistribution, + /// Quarter turns of every shape (0 to 3) + pub quarter_turns: u8, + /// The share of shapes turned by a random number of quarter turns + pub quarter_turn_random: f32, + /// Turns every other shape a quarter turn + pub quincunx_flip: bool, + /// The share of shapes mirrored + pub symmetry_random: f32, + pub symmetry: TileSymmetry, + + pub size_mode: TileSizeMode, + /// Where the boundary between alternating columns (rows) falls; 0.5 makes them equal + pub middle_size: [f32; 2], + /// The gap between shapes, in [`TileSizeMode::NormalInterstice`] + pub interstice: [f32; 2], + pub interstice_random: [f32; 2], + /// The shape's size as a share of its cell, in [`TileSizeMode::NormalSize`] + pub size: [f32; 2], + /// The shape's size as a share of the pattern, in [`TileSizeMode::Absolute`] + pub size_absolute: [f32; 2], + /// The shape's size in pixels, in [`TileSizeMode::Pixel`] + pub size_pixel: [f32; 2], + /// How much each shape's size shrinks at random, in [`TileSizeMode::Absolute`] and [`TileSizeMode::Pixel`] + pub size_random: [f32; 2], + pub scale: f32, + pub scale_random: f32, + pub scale_random_seed: u32, + + /// Shift of each row (column) from the one before, as a share of a tile + pub offset: f32, + pub offset_random: f32, + pub offset_random_seed: u32, + /// Shifts columns instead of rows + pub vertical_offset: bool, + pub position_random: [f32; 2], + pub global_offset: [f32; 2], + + pub rotation: f32, + pub rotation_random: f32, + + /// The shapes' brightness + pub color: f32, + pub luminance_random: f32, + /// Brightness rises tile after tile + pub luminance_by_number: bool, + /// Bigger shapes are brighter + pub luminance_by_scale: bool, + /// Hides every other tile + pub checker_mask: bool, + /// Hides the odd rows + pub horizontal_mask: bool, + /// Hides the even columns + pub vertical_mask: bool, + /// The share of tiles hidden at random + pub random_mask: f32, + /// Shows the hidden tiles instead + pub invert_mask: bool, + pub blending: TileBlending, + pub background: f32, + /// An image under the shapes instead of [`TileGenerator::background`] + pub background_image: Option, + pub opacity: f32, + /// Gives tile n the randoms of the last tile but n (the reference app's Reverse Rendering Order: its blendings don't depend on order) + pub reverse_order: bool, +} + +impl TileGenerator { + /// Tiles per side: the reference app's slider range + pub const AMOUNT: std::ops::RangeInclusive = 1..=64; + /// Shape resolutions offered (the reference app's 256 to 4096) + pub const SHAPE_RESOLUTIONS: [u32; 5] = [256, 512, 1024, 2048, 4096]; + pub const SHAPE_TILING: std::ops::RangeInclusive = 1..=16; + pub const MAX_SCALE: f32 = 2.0; + pub const MAX_RANDOM_SEED: u32 = 1000; + /// The largest shape in the pixel size mode: the largest shape resolution + pub const MAX_SIZE_PIXELS: f32 = 4096.0; + /// Input images a pattern reads + pub const MAX_INPUTS: usize = 6; + + pub fn is_default(&self) -> bool { + *self == TileGenerator::default() + } + + /// The settings inside their ranges, with non-finite numbers at their defaults (saved projects and commands are hostile input) + pub fn clamped(&self) -> TileGenerator { + TileGenerator { + inputs: self.inputs.iter().take(TileGenerator::MAX_INPUTS).cloned().collect(), + background_image: self.background_image.clone(), + ..self.clamped_numbers() + } + } + + /// [`TileGenerator::clamped`] without the input images + fn clamped_numbers(&self) -> TileGenerator { + let default = TileGenerator::default(); + let unit = |value: f32, fallback: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { fallback }; + let unit_pair = |pair: [f32; 2], fallback: [f32; 2]| [unit(pair[0], fallback[0]), unit(pair[1], fallback[1])]; + let angle = |value: f32| if value.is_finite() { value.rem_euclid(360.0) } else { 0.0 }; + let amount = |count: u32| count.clamp(*TileGenerator::AMOUNT.start(), *TileGenerator::AMOUNT.end()); + let resolution = |size: u32| { + let largest = TileGenerator::SHAPE_RESOLUTIONS[TileGenerator::SHAPE_RESOLUTIONS.len() - 1]; + size.clamp(TileGenerator::SHAPE_RESOLUTIONS[0], largest).next_power_of_two().min(largest) + }; + TileGenerator { + position: unit(self.position, default.position), + contrast: unit(self.contrast, default.contrast), + amount: self.amount.map(amount), + shape_resolution: self.shape_resolution.map(resolution), + specific: unit(self.specific, default.specific), + shape_angle: angle(self.shape_angle), + shape_scale: unit(self.shape_scale, default.shape_scale), + shape_size: unit_pair(self.shape_size, default.shape_size), + shape_tiling: self.shape_tiling.clamp(*TileGenerator::SHAPE_TILING.start(), *TileGenerator::SHAPE_TILING.end()), + inputs: Vec::new(), + quarter_turns: self.quarter_turns % 4, + quarter_turn_random: unit(self.quarter_turn_random, 0.0), + symmetry_random: unit(self.symmetry_random, 0.0), + middle_size: unit_pair(self.middle_size, default.middle_size), + interstice: unit_pair(self.interstice, default.interstice), + interstice_random: unit_pair(self.interstice_random, default.interstice_random), + size: unit_pair(self.size, default.size), + size_absolute: unit_pair(self.size_absolute, default.size_absolute), + size_pixel: self + .size_pixel + .map(|pixels| if pixels.is_finite() { pixels.clamp(0.0, TileGenerator::MAX_SIZE_PIXELS) } else { default.size_pixel[0] }), + size_random: unit_pair(self.size_random, default.size_random), + scale: if self.scale.is_finite() { self.scale.clamp(0.0, TileGenerator::MAX_SCALE) } else { default.scale }, + scale_random: unit(self.scale_random, 0.0), + scale_random_seed: self.scale_random_seed.min(TileGenerator::MAX_RANDOM_SEED), + offset: unit(self.offset, 0.0), + offset_random: unit(self.offset_random, 0.0), + offset_random_seed: self.offset_random_seed.min(TileGenerator::MAX_RANDOM_SEED), + position_random: unit_pair(self.position_random, default.position_random), + global_offset: unit_pair(self.global_offset, default.global_offset), + rotation: angle(self.rotation), + rotation_random: unit(self.rotation_random, 0.0), + color: unit(self.color, default.color), + luminance_random: unit(self.luminance_random, 0.0), + random_mask: unit(self.random_mask, 0.0), + background: unit(self.background, default.background), + opacity: unit(self.opacity, default.opacity), + background_image: None, + non_square_expansion: self.non_square_expansion, + shape: self.shape, + shape_diagonal: self.shape_diagonal, + shape_non_square_expansion: self.shape_non_square_expansion, + input_distribution: self.input_distribution, + quincunx_flip: self.quincunx_flip, + symmetry: self.symmetry, + size_mode: self.size_mode, + vertical_offset: self.vertical_offset, + luminance_by_number: self.luminance_by_number, + luminance_by_scale: self.luminance_by_scale, + checker_mask: self.checker_mask, + horizontal_mask: self.horizontal_mask, + vertical_mask: self.vertical_mask, + invert_mask: self.invert_mask, + blending: self.blending, + reverse_order: self.reverse_order, + } + } + + /// Every image the pattern reads + pub fn images(&self) -> impl Iterator { + self.inputs.iter().chain(&self.background_image).map(String::as_str) + } +} + +impl Default for TileGenerator { + fn default() -> Self { + TileGenerator { + position: 0.5, + contrast: 0.0, + amount: [10, 10], + non_square_expansion: true, + shape: TileShape::default(), + shape_resolution: [256, 256], + specific: 0.5, + shape_angle: 0.0, + shape_scale: 1.0, + shape_size: [1.0, 1.0], + shape_tiling: 1, + shape_diagonal: false, + shape_non_square_expansion: true, + inputs: Vec::new(), + input_distribution: TileInputDistribution::default(), + quarter_turns: 0, + quarter_turn_random: 0.0, + quincunx_flip: false, + symmetry_random: 0.0, + symmetry: TileSymmetry::default(), + size_mode: TileSizeMode::default(), + middle_size: [0.5, 0.5], + interstice: [0.0, 0.0], + interstice_random: [0.0, 0.0], + size: [1.0, 1.0], + size_absolute: [0.1, 0.1], + size_pixel: [1.0, 1.0], + size_random: [0.0, 0.0], + scale: 1.0, + scale_random: 0.0, + scale_random_seed: 0, + offset: 0.0, + offset_random: 0.0, + offset_random_seed: 0, + vertical_offset: false, + position_random: [0.0, 0.0], + global_offset: [0.0, 0.0], + rotation: 0.0, + rotation_random: 0.0, + color: 1.0, + luminance_random: 0.0, + luminance_by_number: false, + luminance_by_scale: false, + checker_mask: false, + horizontal_mask: false, + vertical_mask: false, + random_mask: 0.0, + invert_mask: false, + blending: TileBlending::default(), + background: 0.0, + background_image: None, + opacity: 1.0, + reverse_order: false, + } + } +} diff --git a/crates/core/src/layer/tile_input_distribution.rs b/crates/core/src/layer/tile_input_distribution.rs new file mode 100644 index 00000000..3830c87e --- /dev/null +++ b/crates/core/src/layer/tile_input_distribution.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// Which of a Tile Generator's input images each tile draws +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileInputDistribution { + /// A random input per tile + #[default] + Random, + /// The inputs in turn, tile after tile + ByNumber, +} + +impl TileInputDistribution { + pub const ALL: [TileInputDistribution; 2] = [TileInputDistribution::Random, TileInputDistribution::ByNumber]; + + pub fn label(self) -> &'static str { + match self { + TileInputDistribution::Random => "Random", + TileInputDistribution::ByNumber => "By pattern number", + } + } +} diff --git a/crates/core/src/layer/tile_shape.rs b/crates/core/src/layer/tile_shape.rs new file mode 100644 index 00000000..8ab1ba2c --- /dev/null +++ b/crates/core/src/layer/tile_shape.rs @@ -0,0 +1,67 @@ +use serde::{Deserialize, Serialize}; + +/// The shape a Tile Generator draws in each tile +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileShape { + /// One of the pattern's input images + Image, + Square, + Disc, + Paraboloid, + Bell, + Gaussian, + Thorn, + Pyramid, + #[default] + Brick, + Gradation, + Waves, + HalfBell, + RidgedBell, + Crescent, + Capsule, + Cone, +} + +impl TileShape { + /// In the reference app's menu order + pub const ALL: [TileShape; 16] = [ + TileShape::Image, + TileShape::Square, + TileShape::Disc, + TileShape::Paraboloid, + TileShape::Bell, + TileShape::Gaussian, + TileShape::Thorn, + TileShape::Pyramid, + TileShape::Brick, + TileShape::Gradation, + TileShape::Waves, + TileShape::HalfBell, + TileShape::RidgedBell, + TileShape::Crescent, + TileShape::Capsule, + TileShape::Cone, + ]; + + pub fn label(self) -> &'static str { + match self { + TileShape::Image => "Custom image input", + TileShape::Square => "Square", + TileShape::Disc => "Disc", + TileShape::Paraboloid => "Paraboloid", + TileShape::Bell => "Bell", + TileShape::Gaussian => "Gaussian", + TileShape::Thorn => "Thorn", + TileShape::Pyramid => "Pyramid", + TileShape::Brick => "Brick", + TileShape::Gradation => "Gradation", + TileShape::Waves => "Waves", + TileShape::HalfBell => "Half bell", + TileShape::RidgedBell => "Ridged bell", + TileShape::Crescent => "Crescent", + TileShape::Capsule => "Capsule", + TileShape::Cone => "Cone", + } + } +} diff --git a/crates/core/src/layer/tile_size_mode.rs b/crates/core/src/layer/tile_size_mode.rs new file mode 100644 index 00000000..efb56069 --- /dev/null +++ b/crates/core/src/layer/tile_size_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// How a Tile Generator sizes its shapes +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileSizeMode { + /// Each shape fills its tile minus the interstice (the gap between shapes) + #[default] + NormalInterstice, + /// Each shape takes a size relative to its tile, whatever the gap + NormalSize, + /// Each shape is the largest square its tile holds; the size settings are not read + KeepRatio, + /// A size relative to the whole pattern, whatever the tile count + Absolute, + /// A size in pixels of a 2048 pixel output, whatever the output's resolution + Pixel, +} + +impl TileSizeMode { + pub const ALL: [TileSizeMode; 5] = + [TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio, TileSizeMode::Absolute, TileSizeMode::Pixel]; + + pub fn label(self) -> &'static str { + match self { + TileSizeMode::NormalInterstice => "Normal - interstice", + TileSizeMode::NormalSize => "Normal - size", + TileSizeMode::KeepRatio => "Keep ratio", + TileSizeMode::Absolute => "Absolute", + TileSizeMode::Pixel => "Pixel", + } + } +} diff --git a/crates/core/src/layer/tile_symmetry.rs b/crates/core/src/layer/tile_symmetry.rs new file mode 100644 index 00000000..c9f92902 --- /dev/null +++ b/crates/core/src/layer/tile_symmetry.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// The mirrors a Tile Generator's random symmetry picks from +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileSymmetry { + #[default] + Both, + Horizontal, + Vertical, +} + +impl TileSymmetry { + pub const ALL: [TileSymmetry; 3] = [TileSymmetry::Both, TileSymmetry::Horizontal, TileSymmetry::Vertical]; + + pub fn label(self) -> &'static str { + match self { + TileSymmetry::Both => "Horizontal + vertical", + TileSymmetry::Horizontal => "Horizontal", + TileSymmetry::Vertical => "Vertical", + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c43c9a68..2a4982d0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -26,7 +26,8 @@ pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural, - ProceduralKind, Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, + ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, gradient, + hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 8c5c819f..acbf7283 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -44,11 +44,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, let Some(layer) = project.layers.get(&id) else { return }; if let LayerKind::Fill(fill) = &layer.kind { - for source in fill.sources.values() { - if let Source::Image { name, .. } = source { - out.push(name.clone()); - } - } + out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); out.extend(fill.link.as_ref().map(|link| link.package.clone())); } for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 1d4e717a..9adf4d9c 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -167,7 +167,7 @@ fn rgb(c: [f32; 3]) -> Source { } fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source { - Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high } + Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low, high } } /// A scalar pattern between `lo` and `hi`. diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index dd0111f3..f96fe1c4 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -75,7 +75,7 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, /// A triplanar grayscale pattern fill. pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind { EffectKind::Fill { - source: Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low: [0.0; 3], high: [1.0; 3] }, + source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, } } From cf622778578b864fa9be109ea3c45efc634ebd70 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:43:05 +0000 Subject: [PATCH 2/9] Pattern settings in fill commands layer.fill.set, effect.add.fill and effect.set take `tile` (Tile Generator settings in camelCase, menu choices by label or id, brought into range), `tileDefaults` and a pattern's `resolution`, `customResolution` and `resolutionFactor`; settings alone edit the current pattern, and picking the kind a channel already has keeps them. effect.set picks a mask fill's pattern with `procedural` and a uniform value with `uniform`. project.inspect reports both. --- crates/engine/src/inspect.rs | 22 ++- crates/engine/src/layer_cmds.rs | 165 +++++++++++--------- crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 63 +++++--- crates/engine/src/material_lib.rs | 2 +- crates/engine/src/materials.rs | 1 + crates/engine/src/procedural_params.rs | 141 +++++++++++++++++ crates/engine/src/smart_masks.rs | 2 +- crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/tile_generator.rs | 187 +++++++++++++++++++++++ 10 files changed, 485 insertions(+), 100 deletions(-) create mode 100644 crates/engine/src/procedural_params.rs create mode 100644 crates/engine/tests/it/tile_generator.rs diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3a2e348c..0425e1dc 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -7,12 +7,22 @@ use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, Laye use crate::Session; use crate::session::StackTarget; -fn source_json(s: &Source) -> Value { - match s { - Source::Uniform(v) => json!({ "uniform": v }), - Source::Procedural { pattern, low, high } => json!({ - "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high - }), +fn source_json(source: &Source) -> Value { + match source { + Source::Uniform(value) => json!({ "uniform": value }), + Source::Procedural { pattern, low, high } => { + let mut out = json!({ + "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high + }); + if !pattern.resolution.is_default() { + out["resolution"] = + json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor }); + } + if let Some(tile) = &pattern.tile { + out["tile"] = crate::procedural_params::tile_report(tile); + } + out + } Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }), Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }), Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }), diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 5d5fc104..5a6074fd 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -2,7 +2,9 @@ //! per-channel blending and fill sources. use serde_json::{Value, json}; -use texturecraft_core::{BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Projection, Source}; +use texturecraft_core::{ + BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Projection, Source, +}; use crate::commands::{ CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p, @@ -27,7 +29,7 @@ pub fn specs() -> Vec { "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -309,89 +311,61 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { } } -fn fill_set(s: &mut Session, p: &Value) -> Result { - let target = fill_target(s, p, "layer.fill.set")?; - let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?; - // `solo`: this channel on, every other one off. - let solo = boolp(p, "solo") == Some(true); - let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; - let normal_format = normal_format_param("layer.fill.set", p)?; - let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]); - let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]); - let color = color_param("layer.fill.set", p, "color")?; - let value = color_param("layer.fill.set", p, "value")?; - let source = if let Some(kind) = strp(p, "procedural") { - let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; - let mut pr = Procedural::new(kind); - if let Some(v) = f32p(p, "scale") { - pr.scale = v.clamp(0.001, 1000.0); - } - if let Some(v) = u64p(p, "seed") { - pr.seed = v as u32; - } - if let Some(v) = f32p(p, "contrast") { - pr.contrast = v.clamp(0.0, 20.0); - } - if let Some(v) = f32p(p, "balance") { - pr.balance = v.clamp(-1.0, 1.0); - } - pr.invert = boolp(p, "invert").unwrap_or(false); - Some(Source::Procedural { pattern: pr, low, high }) - } else if let Some(c) = color.or(value) { - Some(Source::Uniform(c)) - } else if let Some(name) = strp(p, "image") { - Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) - } else if let Some(a) = u64p(p, "anchor") { - let reader = match target { - FillTarget::Layer(id) => Some(id), - FillTarget::Effect(e) => s.doc.project.effect(e).map(|(owner, _)| owner), - }; - let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?; - let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch); - Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?) - } else if enabled.is_some() || normal_format.is_some() { - None - } else { - return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `normalFormat`, `enabled` or `solo`")); - }; - if normal_format.is_some() && source.as_ref().is_some_and(|src| !matches!(src, Source::Image { .. })) { - return Err(bad("layer.fill.set", "`normalFormat` goes with `image` or alone")); +fn fill_set(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "layer.fill.set"; + let target = fill_target(session, params, CMD)?; + let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?; + // `solo`: this channel on, every other one off + let solo = boolp(params, "solo") == Some(true); + let enabled = if solo { Some(true) } else { boolp(params, "enabled") }; + let normal_format = normal_format_param(CMD, params)?; + let source = fill_source_from(session, params, (target, channel), normal_format)?; + if source.is_none() && enabled.is_none() && normal_format.is_none() { + return Err(bad( + CMD, + "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `normalFormat`, `enabled` or `solo`", + )); } - // A format-only edit leaves the channel on or off. + + if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) { + return Err(bad(CMD, "`normalFormat` goes with `image` or alone")); + } + + // A format-only edit leaves the channel on or off let touches_channel = source.is_some() || enabled.is_some(); - s.edit("Set fill", |s| { - let f = fill_mut(s, target)?; - // `normalFormat` alone: the convention of the channel's image. - if let (None, Some(nf)) = (&source, normal_format) { - match f.sources.get_mut(&ch) { - Some(Source::Image { normal_format, .. }) => *normal_format = nf, - _ => return Err(bad("layer.fill.set", "`normalFormat` needs an image on the channel")), + session.edit("Set fill", |session| { + let fill = fill_mut(session, target)?; + // `normalFormat` alone: the convention of the channel's image + if let (None, Some(format)) = (&source, normal_format) { + match fill.sources.get_mut(&channel) { + Some(Source::Image { normal_format, .. }) => *normal_format = format, + _ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")), } } match target { - // A fill effect's channel is on while it has a source. + // A fill effect's channel is on while it has a source FillTarget::Effect(_) if enabled == Some(false) => { - f.sources.remove(&ch); + fill.sources.remove(&channel); } FillTarget::Effect(_) => { - let src = source.unwrap_or_else(|| f.source(ch)); - f.sources.insert(ch, src); + let source = source.unwrap_or_else(|| fill.source(channel)); + fill.sources.insert(channel, source); if solo { - f.sources.retain(|c, _| *c == ch); + fill.sources.retain(|kept, _| *kept == channel); } } FillTarget::Layer(id) => { - if let Some(src) = source { - f.sources.insert(ch, src); + if let Some(source) = source { + fill.sources.insert(channel, source); } - let l = s.doc.project.layer_mut(id)?; + let layer = session.doc.project.layer_mut(id)?; if enabled == Some(false) { - l.channels.remove(&ch); + layer.channels.remove(&channel); } else if touches_channel { - l.channels.entry(ch).or_default(); + layer.channels.entry(channel).or_default(); } if solo { - l.channels.retain(|c, _| *c == ch); + layer.channels.retain(|kept, _| *kept == channel); } } } @@ -400,6 +374,61 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format +fn fill_source_from( + session: &mut Session, + params: &Value, + (target, channel): (FillTarget, Channel), + normal_format: Option, +) -> Result> { + const CMD: &str = "layer.fill.set"; + let current = fill_mut(session, target).map(|fill| fill.source(channel)).ok(); + let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]); + let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]); + let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?); + if let Some(name) = strp(params, "procedural") { + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; + let mut pattern = Procedural::new(kind); + crate::procedural_params::pattern_basics_from(params, &mut pattern); + // A pattern of the kind the channel already has keeps its resolution and Tile Generator settings + if let Some(Source::Procedural { pattern: current, .. }) = current + && current.kind == kind + { + pattern.resolution = current.resolution; + pattern.tile = current.tile; + } + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + return Ok(Some(Source::Procedural { pattern, low, high })); + } + + if let Some(color) = uniform { + return Ok(Some(Source::Uniform(color))); + } + if let Some(name) = strp(params, "image") { + return Ok(Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })); + } + if let Some(anchor) = u64p(params, "anchor") { + let reader = match target { + FillTarget::Layer(id) => Some(id), + FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), + }; + let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?; + let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel); + return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?)); + } + if !crate::procedural_params::has_pattern_settings(params) { + return Ok(None); + } + + // Pattern settings alone edit the channel's current pattern + let Some(Source::Procedural { mut pattern, low, high }) = current else { + return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings")); + }; + + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + Ok(Some(Source::Procedural { pattern, low, high })) +} + /// The projection `p` asks for. Fields it does not give keep their values from `current` when /// that is of the same kind (or `p` names no kind), and the kind's defaults otherwise. pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>) -> Result { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 34b6bf3a..470c10ea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -47,6 +47,7 @@ mod polygon_fill_drag; mod preserve; pub mod preset_cmds; pub mod preview; +mod procedural_params; pub mod project_cmds; pub mod quick_mask; pub mod resource_cmds; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index fe79c845..63af43e3 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, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, - MaskBackground, MicroDetail, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, + MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Add fill", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed? | anchor?: anchor effect id, anchorChannel?: channel (height); content: color?, roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", + "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color?, roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", has_layer, add_fill ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, 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), 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?, image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, 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), 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), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -294,9 +294,6 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result fn add_fill(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.add.fill"; - const MIN_PATTERN_SCALE: f32 = 0.001; - const MAX_PATTERN_SCALE: f32 = 1000.0; - let projection = projection_from(params, CMD, None)?; let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal); let layer = layer_param(session, CMD, params)?; @@ -327,13 +324,8 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { Some(name) => { let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; let mut pattern = Procedural::new(kind); - if let Some(scale) = f32p(params, "scale") { - pattern.scale = scale.clamp(MIN_PATTERN_SCALE, MAX_PATTERN_SCALE); - } - if let Some(seed) = u64p(params, "seed") { - pattern.seed = seed as u32; - } - + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] } } None => Source::Uniform([f32p(params, "value").unwrap_or(1.0).clamp(0.0, 1.0); 3]), @@ -377,17 +369,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(contrast) = f32p(params, "contrast") { generator.global.contrast = contrast.clamp(0.0, 1.0); } - if let Some(value) = params.get("resolution") { - let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; - generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; - } - if let Some(custom) = u64p(params, "customResolution") { - generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; - } - if let Some(factor) = params.get("resolutionFactor") { - let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; - generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; - } + crate::procedural_params::resolution_from(command, params, &mut generator.resolution)?; // A mode or sizes also give a curvature generator saved before detail sizes its detail let mode = params @@ -691,6 +673,10 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = anchor; } else if let Some(image) = image { *source = image; + } else if let Some(pattern) = fill_pattern(CMD, params, source)? { + *source = pattern; + } else if let Some(value) = f32p(params, "uniform") { + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. } | Source::Image { .. }) { @@ -715,6 +701,35 @@ fn set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// The pattern a mask fill reads after `params`: `procedural` picks one (a pattern of the kind it already reads keeps its settings), pattern settings alone edit the current one +fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result> { + let (current, range) = match current { + Source::Procedural { pattern, low, high } => (Some(pattern), (*low, *high)), + _ => (None, ([0.0; 3], [1.0; 3])), + }; + let mut pattern = match strp(params, "procedural") { + Some(name) => { + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(command, format!("unknown procedural `{name}`")))?; + current.filter(|pattern| pattern.kind == kind).cloned().unwrap_or_else(|| Procedural::new(kind)) + } + None => { + let has_settings = crate::procedural_params::has_pattern_settings(params); + let edits_pattern = has_settings || ["scale", "seed", "contrast", "balance", "invert"].iter().any(|key| params.get(key).is_some()); + match current { + Some(pattern) if edits_pattern => pattern.clone(), + None if has_settings => { + return Err(bad(command, "the mask fill reads no pattern: give `procedural` with its settings")); + } + _ => return Ok(None), + } + } + }; + + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(command, params, &mut pattern)?; + Ok(Some(Source::Procedural { pattern, low: range.0, high: range.1 })) +} + /// The library id of the filter effect `effect` is, if it is one fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { match &s.doc.project.effect(effect)?.1.kind { diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index acbf7283..ab31de4c 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -36,7 +36,7 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and mask or content effects). +/// Image resources a layer subtree uses (fill sources and their patterns, mask fills and generator inputs) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 9adf4d9c..af18b74c 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -166,6 +166,7 @@ fn rgb(c: [f32; 3]) -> Source { Source::Uniform(c) } +/// A pattern between colors `low` and `high` (short: the material catalog calls it on almost every line) fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source { Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low, high } } diff --git a/crates/engine/src/procedural_params.rs b/crates/engine/src/procedural_params.rs new file mode 100644 index 00000000..ebd7f304 --- /dev/null +++ b/crates/engine/src/procedural_params.rs @@ -0,0 +1,141 @@ +//! Pattern settings in commands: the resolution a pattern is computed at and the Tile Generator's settings + +use serde_json::{Map, Value}; +use texturecraft_core::{ + OutputResolution, Procedural, ProceduralKind, ResolutionMode, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, +}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, u64p}; + +/// The pattern's `scale`, `seed`, `contrast`, `balance` and `invert` in `params`, applied to `pattern` in range +pub(crate) fn pattern_basics_from(params: &Value, pattern: &mut Procedural) { + if let Some(scale) = f32p(params, "scale") { + pattern.scale = scale.clamp(Procedural::MIN_SCALE, Procedural::MAX_SCALE); + } + if let Some(seed) = u64p(params, "seed") { + pattern.seed = u32::try_from(seed).unwrap_or(u32::MAX); + } + if let Some(contrast) = f32p(params, "contrast") { + pattern.contrast = contrast.clamp(0.0, Procedural::MAX_CONTRAST); + } + if let Some(balance) = f32p(params, "balance") { + pattern.balance = balance.clamp(-Procedural::MAX_BALANCE, Procedural::MAX_BALANCE); + } + if let Some(invert) = boolp(params, "invert") { + pattern.invert = invert; + } +} + +/// Whether `params` holds any pattern setting [`pattern_settings_from`] reads +pub(crate) fn has_pattern_settings(params: &Value) -> bool { + ["resolution", "customResolution", "resolutionFactor", "tile", "tileDefaults"].iter().any(|key| params.get(key).is_some()) +} + +/// Apply the resolution and Tile Generator settings in `params` to `pattern`, using `command` in errors +pub(crate) fn pattern_settings_from(command: &str, params: &Value, pattern: &mut Procedural) -> Result<()> { + resolution_from(command, params, &mut pattern.resolution)?; + let resets = boolp(params, "tileDefaults") == Some(true); + let edits = params.get("tile"); + if (resets || edits.is_some()) && pattern.kind != ProceduralKind::TileGenerator { + return Err(bad(command, "`tile` and `tileDefaults` go with the Tile Generator pattern")); + } + + if resets { + pattern.tile = Some(Box::default()); + } + if let Some(edits) = edits { + let current = pattern.tile.get_or_insert_with(Box::default); + **current = tile_from(command, edits, current)?; + } + Ok(()) +} + +/// The `resolution`, `customResolution` and `resolutionFactor` params applied to `resolution` +pub(crate) fn resolution_from(command: &str, params: &Value, resolution: &mut OutputResolution) -> Result<()> { + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } + Ok(()) +} + +/// `current` with the camelCase settings in `edits` applied (menu choices by label or id), in range +fn tile_from(command: &str, edits: &Value, current: &TileGenerator) -> Result { + let edits = edits.as_object().ok_or_else(|| bad(command, "`tile` must be an object"))?; + let mut merged = serde_json::to_value(current).map_err(|error| bad(command, error.to_string()))?; + let fields = merged.as_object_mut().ok_or_else(|| bad(command, "the Tile Generator settings are not an object"))?; + for (key, value) in edits { + let field = snake_case(key); + if !fields.contains_key(&field) { + return Err(bad(command, format!("unknown Tile Generator setting `{key}`"))); + } + + fields.insert(field.clone(), choice_id(command, &field, value)?); + } + let tile: TileGenerator = serde_json::from_value(merged).map_err(|error| bad(command, format!("bad Tile Generator setting: {error}")))?; + Ok(tile.clamped()) +} + +/// A menu setting's value as its saved id (`"Half bell"` → `"HalfBell"`); other values unchanged +fn choice_id(command: &str, field: &str, value: &Value) -> Result { + let Some(text) = value.as_str() else { return Ok(value.clone()) }; + let id = match field { + "shape" => find(&TileShape::ALL, TileShape::label, text), + "size_mode" => find(&TileSizeMode::ALL, TileSizeMode::label, text), + "input_distribution" => find(&TileInputDistribution::ALL, TileInputDistribution::label, text), + "symmetry" => find(&TileSymmetry::ALL, TileSymmetry::label, text), + "blending" => find(&TileBlending::ALL, TileBlending::label, text), + _ => return Ok(value.clone()), + }; + id.map(Value::String).ok_or_else(|| bad(command, format!("unknown {} `{text}`", camel_case(field)))) +} + +/// The id of the choice in `all` whose label or id is `text` (any case, spaces optional) +fn find(all: &[T], label: fn(T) -> &'static str, text: &str) -> Option { + let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-', '+'], ""); + let wanted = normalize(text); + all.iter().find(|choice| normalize(label(**choice)) == wanted || normalize(&format!("{choice:?}")) == wanted).map(|choice| format!("{choice:?}")) +} + +/// The Tile Generator settings as `project.inspect` reports them: camelCase keys, as the commands take them +pub(crate) fn tile_report(tile: &TileGenerator) -> Value { + let Ok(Value::Object(fields)) = serde_json::to_value(tile) else { return Value::Null }; + Value::Object(fields.into_iter().map(|(key, value)| (camel_case(&key), value)).collect::>()) +} + +fn snake_case(key: &str) -> String { + let mut snake = String::with_capacity(key.len()); + for character in key.chars() { + if character.is_ascii_uppercase() { + snake.push('_'); + snake.push(character.to_ascii_lowercase()); + } else { + snake.push(character); + } + } + snake +} + +fn camel_case(field: &str) -> String { + let mut camel = String::with_capacity(field.len()); + let mut upper = false; + for character in field.chars() { + if character == '_' { + upper = true; + } else if upper { + camel.push(character.to_ascii_uppercase()); + upper = false; + } else { + camel.push(character); + } + } + camel +} diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index f96fe1c4..8fb1c482 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -72,7 +72,7 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } -/// A triplanar grayscale pattern fill. +/// A triplanar grayscale pattern fill pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind { EffectKind::Fill { source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3] }, diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 7c61e03b..019d6971 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -27,6 +27,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod thumbs; +mod tile_generator; mod tool_availability; mod tools; mod udim; diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs new file mode 100644 index 00000000..5394162a --- /dev/null +++ b/crates/engine/tests/it/tile_generator.rs @@ -0,0 +1,187 @@ +//! The Tile Generator pattern and pattern resolutions through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind, Procedural, ProceduralKind, ResolutionMode, Source, TileGenerator, TileShape}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +/// A fill layer whose base color reads the Tile Generator, and its id +fn tile_fill(session: &mut Session) -> u64 { + let layer = execute(session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator"})).unwrap(); + layer +} + +fn base_color_pattern(session: &Session, layer: u64) -> Procedural { + let LayerKind::Fill(fill) = &session.doc.project.layer(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") }; + let Source::Procedural { pattern, .. } = fill.source(Channel::BaseColor) else { panic!("the base color is not a pattern") }; + pattern +} + +fn tile(pattern: &Procedural) -> TileGenerator { + pattern.tile.as_deref().cloned().unwrap() +} + +/// A mask fill effect reading a uniform value, on a fresh fill layer's black mask +fn mask_fill(session: &mut Session) -> u64 { + execute(session, "layer.add.fill", &Value::Null).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + execute(session, "effect.add.fill", &json!({"value": 1.0})).unwrap()["effect"].as_u64().unwrap() +} + +fn mask_pattern(session: &Session, effect: u64) -> Procedural { + let Some((_, effect)) = session.doc.project.effect(LayerId(effect)) else { panic!("no effect {effect}") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, .. } = &effect.kind else { panic!("the mask fill reads no pattern") }; + pattern.clone() +} + +#[test] +fn a_new_tile_generator_starts_from_the_reference_defaults() { + let mut session = session(); + let layer = tile_fill(&mut session); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(pattern.kind, ProceduralKind::TileGenerator); + assert_eq!(tile(&pattern), TileGenerator::default()); + assert_eq!(pattern.scale, 1.0, "the tile counts set its frequency: the grid covers one repeat of the projection"); +} + +#[test] +fn tile_settings_alone_edit_the_channels_pattern() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [4, 2], "shape": "Half bell", "offset": 0.5}})).unwrap(); + + let tile = tile(&base_color_pattern(&session, layer)); + assert_eq!(tile.amount, [4, 2]); + assert_eq!(tile.shape, TileShape::HalfBell, "a menu choice is taken by its label"); + assert_eq!(tile.offset, 0.5); + assert_eq!(tile.specific, TileGenerator::default().specific, "settings not named keep their value"); +} + +#[test] +fn picking_the_tile_generator_again_keeps_its_settings() { + let mut session = session(); + let layer = tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "resolution": "custom", "customResolution": 128})) + .unwrap(); + + // The panel's scale and seed edits send the pattern again with its kind + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator", "seed": 9})).unwrap(); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(pattern.seed, 9); + assert_eq!(tile(&pattern).amount, [3, 3]); + assert_eq!((pattern.resolution.mode, pattern.resolution.custom), (ResolutionMode::Custom, 128)); +} + +#[test] +fn hostile_tile_settings_are_brought_into_range() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "tile": {"amount": [0, 999], "specific": -5.0, "shapeTiling": 400, "rotation": 450.0, "shapeResolution": [3, 100000]}}), + ) + .unwrap(); + + let tile = tile(&base_color_pattern(&session, layer)); + assert_eq!(tile.amount, [1, 64]); + assert_eq!(tile.specific, 0.0); + assert_eq!(tile.shape_tiling, 16); + assert_eq!(tile.rotation, 90.0, "angles wrap around the turn"); + assert_eq!(tile.shape_resolution, [256, 4096]); +} + +#[test] +fn unknown_or_misplaced_tile_settings_are_errors() { + let mut session = session(); + tile_fill(&mut session); + + let unknown = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"colour": 0.5}})); + assert!(unknown.unwrap_err().to_string().contains("colour"), "the unknown setting is named"); + let bad_shape = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Hexagon"}})); + assert!(bad_shape.is_err()); + + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "procedural": "Clouds"})).unwrap(); + let on_clouds = execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "tile": {"offset": 0.5}})); + assert!(on_clouds.is_err(), "tile settings go with the Tile Generator only"); + let no_pattern = execute(&mut session, "layer.fill.set", &json!({"channel": "metallic", "tile": {"offset": 0.5}})); + assert!(no_pattern.is_err(), "a uniform channel has no pattern to edit"); +} + +#[test] +fn a_mask_fill_picks_and_edits_a_pattern_with_effect_set() { + let mut session = session(); + let effect = mask_fill(&mut session); + + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "tile": {"checkerMask": true}, "seed": 4})).unwrap(); + + let pattern = mask_pattern(&session, effect); + assert!(tile(&pattern).checker_mask); + assert_eq!(pattern.seed, 4); + + execute(&mut session, "effect.set", &json!({"effect": effect, "tileDefaults": true})).unwrap(); + assert_eq!(tile(&mask_pattern(&session, effect)), TileGenerator::default(), "Restore defaults puts every tile setting back"); + + // A value takes the mask fill back from the pattern only through a uniform source pick, so a stray value is ignored as before + execute(&mut session, "effect.set", &json!({"effect": effect, "value": 0.3})).unwrap(); + assert_eq!(mask_pattern(&session, effect).kind, ProceduralKind::TileGenerator); +} + +#[test] +fn a_mask_fill_added_with_tile_settings_keeps_them() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + + let added = execute(&mut session, "effect.add.fill", &json!({"procedural": "Tile Generator", "tile": {"amount": [6, 6]}, "resolutionFactor": -2})).unwrap(); + + let pattern = mask_pattern(&session, added["effect"].as_u64().unwrap()); + assert_eq!(tile(&pattern).amount, [6, 6]); + assert_eq!(pattern.resolution.factor, -2); +} + +#[test] +fn inspect_reports_the_tile_settings_and_a_patterns_resolution() { + let mut session = session(); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [5, 7]}, "resolution": "textureSet"})).unwrap(); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"amount\":[5,7]"), "the settings are reported: {inspected}"); + assert!(inspected.contains("\"randomMask\""), "under the camelCase names the commands take"); + assert!(inspected.contains("\"mode\":\"TextureSet\""), "the pattern's resolution is reported"); +} + +/// Imports a small gray PNG as resource `name` and returns its resource name +fn import_gray(session: &mut Session, name: &str) -> 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(name, bytes).unwrap() +} + +#[test] +fn removing_unused_resources_keeps_the_images_a_tile_generator_reads() { + let mut session = session(); + let input = import_gray(&mut session, "vent.png"); + let background = import_gray(&mut session, "plate.png"); + let unused = import_gray(&mut session, "unused.png"); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "backgroundImage": background}})) + .unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&input), "the pattern input is still read"); + assert!(session.doc.resources.contains_key(&background), "the background image is still read"); + assert!(!session.doc.resources.contains_key(&unused)); +} From 429e7cac651ac57baa64c5e1207ac20c2de3fdb8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:43:05 +0000 Subject: [PATCH 3/9] Pattern panel and fill source picker A fill channel's or a mask fill's source is a slot that opens the resource picker, with Resources (patterns, images, a uniform value) and Anchor points tabs; anchors show a picture of the stack they record. The picked pattern shows its Attributes, Resolution, Parameters and Image inputs; the Tile Generator's parameters follow the reference app's sections, with an angle dial and black-to-white gray rows. The picker's group headers read as section titles. --- crates/engine/src/thumbs.rs | 22 +- crates/ui-egui/src/angle_dial.rs | 52 +++ crates/ui-egui/src/dock.rs | 220 ++++------- crates/ui-egui/src/fill_source_slot.rs | 208 ++++++++++ crates/ui-egui/src/fill_source_target.rs | 12 + crates/ui-egui/src/filter_slot.rs | 18 +- crates/ui-egui/src/generator_panel.rs | 31 +- crates/ui-egui/src/gray_slider.rs | 54 +++ crates/ui-egui/src/i18n.rs | 9 +- crates/ui-egui/src/layer_panel.rs | 52 ++- crates/ui-egui/src/lib.rs | 14 + crates/ui-egui/src/pattern_panel.rs | 374 ++++++++++++++++++ crates/ui-egui/src/pattern_target.rs | 11 + crates/ui-egui/src/preview_image.rs | 17 +- crates/ui-egui/src/resource_panel.rs | 33 ++ crates/ui-egui/src/resource_picker.rs | 240 +++++++++-- crates/ui-egui/src/resource_picker_anchor.rs | 14 + crates/ui-egui/src/resource_picker_choice.rs | 9 + crates/ui-egui/src/resource_picker_tab.rs | 8 + crates/ui-egui/src/resource_picker_tile.rs | 14 + crates/ui-egui/src/tile_edits.rs | 85 ++++ crates/ui-egui/tests/it/fill_channel_image.rs | 30 +- crates/ui-egui/tests/it/main.rs | 1 + .../ui-egui/tests/it/tile_generator_panel.rs | 208 ++++++++++ 24 files changed, 1504 insertions(+), 232 deletions(-) create mode 100644 crates/ui-egui/src/angle_dial.rs create mode 100644 crates/ui-egui/src/fill_source_slot.rs create mode 100644 crates/ui-egui/src/fill_source_target.rs create mode 100644 crates/ui-egui/src/gray_slider.rs create mode 100644 crates/ui-egui/src/pattern_panel.rs create mode 100644 crates/ui-egui/src/pattern_target.rs create mode 100644 crates/ui-egui/src/resource_panel.rs create mode 100644 crates/ui-egui/src/resource_picker_anchor.rs create mode 100644 crates/ui-egui/src/resource_picker_choice.rs create mode 100644 crates/ui-egui/src/resource_picker_tab.rs create mode 100644 crates/ui-egui/src/resource_picker_tile.rs create mode 100644 crates/ui-egui/src/tile_edits.rs create mode 100644 crates/ui-egui/tests/it/tile_generator_panel.rs diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index 6cd6e2a2..811a742f 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -293,7 +293,14 @@ impl ThumbService { self.tick = self.tick.wrapping_add(1); let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); let checked = self.checked(session); - if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) { + + // A target the document no longer has would render for nothing, again each frame + if !fresh + && checked + && !self.in_flight.contains(&(self.generation, target)) + && !self.queue.contains(&target) + && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(target)) + { self.queue.push_back(target); } @@ -475,6 +482,19 @@ mod tests { eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); } + #[test] + fn a_target_the_document_lacks_is_not_rendered() { + let session = test_session().unwrap(); + let removed_anchor = ThumbTarget::Stage { effect: texturecraft_core::LayerId(u64::MAX), channel: Channel::Height }; + let (mut service, jobs, _results) = held_worker(); + service.begin_frame(&session, 0.0); + + assert!(service.get(&session, removed_anchor).image.is_none()); + + assert!(!service.poll(&session), "nothing is rendered, so no frame is asked for"); + assert!(jobs.try_recv().is_err()); + } + #[test] fn collecting_the_last_result_requests_a_frame_to_display_it() { let session = test_session().unwrap(); diff --git a/crates/ui-egui/src/angle_dial.rs b/crates/ui-egui/src/angle_dial.rs new file mode 100644 index 00000000..a2129841 --- /dev/null +++ b/crates/ui-egui/src/angle_dial.rs @@ -0,0 +1,52 @@ +//! An angle as a dial beside a slider, as the reference app shows angles: drag the dial to point it, or set the slider + +use egui::{Sense, Stroke, Ui, vec2}; + +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::slider_edit; + +const DIAL_SIZE: f32 = 36.0; +const DIAL_RIM_WIDTH: f32 = 1.5; +const POINTER_WIDTH: f32 = 2.0; +const HUB_RADIUS: f32 = 2.0; +/// Gap between the dial and its slider +const DIAL_GAP: f32 = 8.0; +const FULL_TURN: f32 = 360.0; + +/// `label` over a dial and an "Angle" slider for `degrees` (0 at the right, counterclockwise): `Some(merge)` on every frame that changes it, as [`slider_edit`] +pub(crate) fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { + ui.label(label); + ui.horizontal(|ui| { + let dial_edit = dial(ui, degrees); + ui.add_space(DIAL_GAP); + let slider = ui.vertical(|ui| slider_edit(ui, tr("Angle"), degrees, 0.0..=FULL_TURN, 0)).inner; + dial_edit.or(slider) + }) + .inner +} + +/// The dial: a disc whose pointer follows a drag around its center +fn dial(ui: &mut Ui, degrees: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(DIAL_SIZE, DIAL_SIZE), Sense::click_and_drag()); + let center = rect.center(); + let mut edit = None; + if let Some(pointer) = response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) { + let offset = pointer - center; + if offset.length() > HUB_RADIUS { + // Screen y grows downwards, angles grow counterclockwise + *degrees = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(FULL_TURN); + edit = Some(response.dragged() && !response.drag_started()); + } + } + + let radius = DIAL_SIZE * 0.5 - DIAL_RIM_WIDTH; + let painter = ui.painter(); + let rim = if response.hovered() || response.dragged() { tokens.button_border } else { tokens.field_border }; + painter.circle(center, radius, tokens.field, Stroke::new(DIAL_RIM_WIDTH, rim)); + let (sin, cos) = degrees.to_radians().sin_cos(); + painter.line_segment([center, center + vec2(cos, -sin) * (radius - DIAL_RIM_WIDTH)], Stroke::new(POINTER_WIDTH, tokens.accent)); + painter.circle_filled(center, HUB_RADIUS, tokens.text); + edit +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b168194d..63877e2e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, - Source, + BakedMap, BlendMode, Channel, ChannelKind, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -210,7 +209,6 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); } }); - app.layer_panel.end(ui.ctx(), &app.session); } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -2274,13 +2272,13 @@ fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option Value { - let mut v = base.clone(); - if let (Some(o), Value::Object(e)) = (v.as_object_mut(), extra) { - o.extend(e); +/// `base` with the fields of `extra` added +pub(crate) fn with(base: &Value, extra: Value) -> Value { + let mut params = base.clone(); + if let (Some(fields), Value::Object(extra)) = (params.as_object_mut(), extra) { + fields.extend(extra); } - v + params } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). @@ -2323,7 +2321,7 @@ pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect } /// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). -fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { +pub(crate) fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { let project = &app.session.doc.project; project .effect(anchor) @@ -2537,123 +2535,76 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI ); } -/// The source of one fill channel: uniform, procedural, image or anchor. -fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, c: Channel, anchors: &[(LayerId, String)], salt: &str) { - let tk = Tokens::get(ui.ctx()); - use texturecraft_engine::core::ChannelKind; - { - let set = |extra: Value| with(base, with(&json!({"channel": c.id()}), extra)); - let group = ui.group(|ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(c.label())).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { - if ui.button(tr("Uniform value")).clicked() { - app.run("layer.fill.set", set(json!({"value": c.default_value()}))); - ui.close(); - } - ui.separator(); - for k in ProceduralKind::ALL { - if ui.button(tr(k.label())).clicked() { - let (lo, hi) = match c { - Channel::BaseColor => ([0.15, 0.15, 0.15], [0.85, 0.85, 0.85]), - Channel::Height => ([-0.05; 3], [0.05; 3]), - _ => ([0.2; 3], [0.8; 3]), - }; - app.run("layer.fill.set", set(json!({"procedural": k.label(), "low": lo, "high": hi}))); - ui.close(); - } - } - ui.separator(); - if let Some(name) = image_menu(app, ui) { - app.run("layer.fill.set", set(json!({"image": name}))); - } - if let Some(a) = anchor_entries(ui, anchors, fill.source(c).anchor()) { - app.run("layer.fill.set", set(json!({"anchor": a.0}))); - ui.close(); - } - }) - .response - .on_hover_text(tr("Channel source: uniform value, procedural, image or anchor")); - }); - }); - match fill.source(c) { - Source::Uniform(mut v) => { - if c.kind() == ChannelKind::Color { - if color_swatch(ui, &format!("fill_{salt}_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.run("layer.fill.set", set(json!({"color": v}))); - } - } else { - let range = if c.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut v[0], range, 2) { - app.run("layer.fill.set", set(json!({"value": v[0], "merge": merge}))); - } - } - } - Source::Procedural { pattern, low, high } => { - ui.label( - RichText::new(trf( - "{pattern} (scale {scale}, seed {seed})", - &[("pattern", &tr(pattern.kind.label())), ("scale", &format!("{:.1}", pattern.scale)), ("seed", &pattern.seed)], - )) - .color(tk.text_dim), - ); - let mut s = pattern.scale; - let mut con = pattern.contrast; - let r1 = slider_edit(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); - let r2 = slider_edit(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); - let mut seed = pattern.seed as f32; - let r3 = slider_edit(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); - if let Some(merge) = r1.or(r2).or(r3) { - app.run( - "layer.fill.set", - set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high, "merge": merge})), - ); - } - if c.kind() == ChannelKind::Color { - let (mut lo, mut hi) = (low, high); - let mut changed = false; - ui.horizontal(|ui| { - ui.label(tr("Low")); - changed |= color_swatch(ui, &format!("lo_{salt}_{}", c.id()), &mut lo, 60.0); - ui.label(tr("High")); - changed |= color_swatch(ui, &format!("hi_{salt}_{}", c.id()), &mut hi, 60.0); - }); - if changed { - app.run( - "layer.fill.set", - set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": pattern.seed, "low": lo, "high": hi})), - ); - } - } - } - Source::Image { name, normal_format } => { - ui.label(trf("Image: {name}", &[("name", &name)])); - if c.kind() == ChannelKind::NormalMap { - let mut directx = normal_format == texturecraft_engine::core::NormalFormat::DirectX; - if ui - .checkbox(&mut directx, tr("DirectX normal map")) - .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")) - .changed() - { - app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); - } - } - } - Source::Anchor { anchor, channel } => { - ui.label(RichText::new(anchor_label(app, anchor, channel)).color(tk.text_dim)); +/// Space a fill channel's color swatch leaves at the group's right edge, and the width of a pattern's low and high swatches +const CHANNEL_SWATCH_MARGIN: f32 = 4.0; +const PATTERN_RANGE_SWATCH_WIDTH: f32 = 60.0; + +/// The source of one fill channel: its slot, then what the source needs (a value, a pattern's settings, an image's format) +fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, channel: Channel, anchors: &[(LayerId, String)], salt: &str) { + let tokens = Tokens::get(ui.ctx()); + let set = |extra: Value| with(base, with(&json!({"channel": channel.id()}), extra)); + let source = fill.source(channel); + let group = ui.group(|ui| { + let slot = crate::fill_source_target::FillSourceTarget::Channel { base: base.clone(), channel }; + crate::fill_source_slot::show(app, ui, &slot, &source, (anchors, tr(channel.label()))); + match source { + Source::Uniform(mut value) if channel.kind() == ChannelKind::Color => { + if color_swatch(ui, &format!("fill_{salt}_{}", channel.id()), &mut value, ui.available_width() - CHANNEL_SWATCH_MARGIN) { + app.run("layer.fill.set", set(json!({"color": value}))); } } - }); - - // A shelf image dropped on the channel becomes its source - if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { - app.run("layer.fill.set", set(json!({"image": name}))); + Source::Uniform(mut value) => { + let range = if channel.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value[0], range, 2) { + app.run("layer.fill.set", set(json!({"value": value[0], "merge": merge}))); + } + } + Source::Procedural { pattern, low, high } => { + let target = crate::pattern_target::PatternTarget { + command: "layer.fill.set", + base: with(base, json!({"channel": channel.id(), "low": low, "high": high})), + salt: format!("{salt}_{}", channel.id()), + }; + crate::pattern_panel::pattern_properties(app, ui, &target, &pattern); + if channel.kind() == ChannelKind::Color { + let (mut low, mut high) = (low, high); + let mut changed = false; + ui.horizontal(|ui| { + ui.label(tr("Low")); + changed |= color_swatch(ui, &format!("lo_{salt}_{}", channel.id()), &mut low, PATTERN_RANGE_SWATCH_WIDTH); + ui.label(tr("High")); + changed |= color_swatch(ui, &format!("hi_{salt}_{}", channel.id()), &mut high, PATTERN_RANGE_SWATCH_WIDTH); + }); + if changed { + crate::pattern_panel::send(app, &target, &pattern, json!({"low": low, "high": high})); + } + } + } + Source::Image { name, normal_format } => { + ui.label(trf("Image: {name}", &[("name", &name)])); + if channel.kind() == ChannelKind::NormalMap { + let mut directx = normal_format == texturecraft_engine::core::NormalFormat::DirectX; + let toggle = ui + .checkbox(&mut directx, tr("DirectX normal map")) + .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")); + if toggle.changed() { + app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); + } + } + } + Source::Anchor { anchor, channel: anchored } => { + ui.label(RichText::new(anchor_label(app, anchor, anchored)).color(tokens.text_dim)); + } } + }); + + // A shelf image dropped on the channel becomes its source + if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { + app.run("layer.fill.set", set(json!({"image": name}))); } } -/// The properties of effect `effect_id` of `layer`: each kind's own settings. +/// The properties of effect `effect_id` of `layer`: each kind's own settings fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { let tokens = Tokens::get(ui.ctx()); let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; @@ -2666,26 +2617,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Fill { source, projection } => { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); - let current = match source { - Source::Anchor { anchor, channel } => anchor_label(app, *anchor, *channel), - Source::Uniform(_) => tr("Uniform value").to_string(), - Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), - Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), - }; - let source_response = combo(ui, tr("Source"), current, |ui| { - if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "value": 1.0})); - } - if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { - app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "image": name})); - } - }); + let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; + let slot = ui.scope(|ui| crate::fill_source_slot::show(app, ui, &target, source, (&anchors, tr("Grayscale")))).response; - // The source selector accepts image drops from the Assets panel - if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { + // The slot accepts image drops from the Assets panel + if let Some(name) = image_drop(ui, &slot.interact(Sense::hover())) { app.run("effect.set", json!({"effect": id, "image": name})); } @@ -2696,6 +2632,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } + Source::Procedural { pattern, .. } => { + let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; + crate::pattern_panel::pattern_properties(app, ui, &target, pattern); + } Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { let note = if mask_anchor_enabled(app, *anchor) == Some(false) { tr("Off") } else { tr("A mask anchor reads as its mask's gray.") }; ui.label(RichText::new(note).color(tokens.text_dim)); diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs new file mode 100644 index 00000000..ba8ff6dc --- /dev/null +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -0,0 +1,208 @@ +//! The source slot of a fill: a mask fill's grayscale or one channel of a fill. It shows what the fill reads and opens the source picker: the patterns, the project's images and a uniform value, or the anchor points below the layer + +use std::sync::{Arc, LazyLock}; + +use egui::{Sense, Ui, vec2}; +use serde_json::json; +use texturecraft_engine::compose::{ImageRes, ThumbTarget}; +use texturecraft_engine::core::{Channel, LayerId, ProceduralKind, Source}; + +use crate::TextureCraftApp; +use crate::dock::with; +use crate::fill_source_target::FillSourceTarget; +use crate::filter_slot::{SLOT_HEIGHT, paint}; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_anchor::ResourcePickerAnchor; +use crate::resource_picker_choice::ResourcePickerChoice; +use crate::resource_picker_tile::ResourcePickerTile; +use crate::shelf_preview::ShelfPreview; + +/// The key of the uniform value tile, and the prefixes of the pattern and image tiles' keys +const UNIFORM_KEY: &str = "uniform"; +const PATTERN_PREFIX: &str = "pattern:"; +const IMAGE_PREFIX: &str = "image:"; +/// The gray the uniform value tile shows +const UNIFORM_TILE_GRAY: f32 = 0.8; +/// The swatch's name among the image previews, prefixed like the stencil previews so it is not taken for a project image +const UNIFORM_SWATCH_NAME: &str = "swatch:uniform"; +/// One swatch for every frame, so its preview stays cached +static UNIFORM_SWATCH: LazyLock> = + LazyLock::new(|| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], srgb: false })); + +/// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) { + let ctx = ui.ctx().clone(); + let channel = match fill { + FillSourceTarget::Mask { .. } => source_channel(source), + FillSourceTarget::Channel { channel, .. } => *channel, + }; + let (name, picture) = shown(app, &ctx, source); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + // Read as a dropdown named for what it fills, its value the source + response.widget_info(|| egui::WidgetInfo { current_text_value: Some(name.clone()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, caption) }); + let popup = ui.make_persistent_id(("fill_source_picker", fill_key(fill))); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + let highlighted = response.hovered() || resource_picker::is_open(&ctx, popup); + paint(ui, rect, (highlighted, response.has_focus()), picture, (caption, &name)); + if !resource_picker::is_open(&ctx, popup) { + return; + } + + let images = matches!(fill, FillSourceTarget::Channel { .. }); + let tiles = tiles(app, &ctx, images); + let anchors: Vec = anchors + .iter() + .map(|(anchor, name)| ResourcePickerAnchor { + anchor: *anchor, + name: name.clone(), + layer: layer_name(app, *anchor), + channel: read_label(app, *anchor, channel), + picture: app.layer_panel.texture_outside(&ctx, &app.session, ThumbTarget::Stage { effect: *anchor, channel }), + }) + .collect(); + let current = current_key(source); + let picked = resource_picker::show_sources(&response, popup, &mut app.thumbs, (current.as_deref(), source.anchor()), tiles, anchors); + match picked { + Some(ResourcePickerChoice::Resource(key)) if Some(&key) != current.as_ref() => pick_resource(app, fill, &key), + Some(ResourcePickerChoice::Anchor(anchor)) if source.anchor() != Some(anchor) => pick_anchor(app, fill, anchor, channel), + _ => {} + } +} + +/// The name and picture of what `source` reads +fn shown(app: &mut TextureCraftApp, ctx: &egui::Context, source: &Source) -> (String, Option) { + match source { + Source::Uniform(_) => (tr("Uniform value").to_string(), None), + Source::Procedural { pattern, .. } => (tr(pattern.kind.label()).to_string(), app.thumbs.procedural(ctx, pattern.kind).map(|texture| texture.id())), + Source::Image { name, .. } => { + let picture = app.session.images.get(name).cloned().map(|image| app.thumbs.image(ctx, name, &image).id()); + (name.clone(), picture) + } + Source::Anchor { anchor, channel } => { + let name = format!("{} · {}", layer_name(app, *anchor), tr(read_label(app, *anchor, *channel))); + (name, app.layer_panel.texture_outside(ctx, &app.session, ThumbTarget::Stage { effect: *anchor, channel: *channel })) + } + } +} + +/// What a fill reads at anchor point `anchor`: its mask's gray when it sits in a mask, else `channel` +fn read_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> &'static str { + if crate::dock::anchor_in_mask(app, anchor) { "Mask" } else { channel.label() } +} + +/// The name of the layer anchor point `anchor` sits on +fn layer_name(app: &TextureCraftApp, anchor: LayerId) -> String { + let project = &app.session.doc.project; + let layer = project.effect(anchor).and_then(|(owner, _)| project.layers.get(&owner)); + layer.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()) +} + +/// The channel a mask fill's anchor is read in (height until one is picked) +fn source_channel(source: &Source) -> Channel { + match source { + Source::Anchor { channel, .. } => *channel, + _ => Channel::Height, + } +} + +/// Keeps the pickers of two slots shown at once apart +fn fill_key(fill: &FillSourceTarget) -> String { + match fill { + FillSourceTarget::Mask { effect } => format!("mask_{effect}"), + FillSourceTarget::Channel { base, channel } => format!("{base}_{}", channel.id()), + } +} + +/// The key of the tile `source` is, outlined in the picker +fn current_key(source: &Source) -> Option { + match source { + Source::Uniform(_) => Some(UNIFORM_KEY.to_string()), + Source::Procedural { pattern, .. } => Some(format!("{PATTERN_PREFIX}{}", pattern.kind.label())), + Source::Image { name, .. } => Some(format!("{IMAGE_PREFIX}{name}")), + Source::Anchor { .. } => None, + } +} + +/// The Resources tab: the patterns, the project's images (`images`) and a uniform value +fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context, images: bool) -> Vec> { + let mut tiles: Vec> = ProceduralKind::ALL + .into_iter() + .map(|kind| ResourcePickerTile { + key: format!("{PATTERN_PREFIX}{}", kind.label()), + label: tr(kind.label()).to_string(), + group: tr("Patterns"), + thumbnail: app.thumbs.procedural(ctx, kind), + preview: Box::new(move || ShelfPreview::Procedural(kind)), + }) + .collect(); + if images { + let mut names: Vec<(String, Arc)> = app.session.images.iter().map(|(name, image)| (name.clone(), image.clone())).collect(); + names.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, image) in names { + let thumbnail = Some(app.thumbs.image(ctx, &name, &image)); + let preview_name = name.clone(); + tiles.push(ResourcePickerTile { + key: format!("{IMAGE_PREFIX}{name}"), + label: name, + group: tr("Images"), + thumbnail, + preview: Box::new(move || ShelfPreview::Image(preview_name.clone(), image.clone())), + }); + } + } + tiles.push(ResourcePickerTile { + key: UNIFORM_KEY.to_string(), + label: tr("Uniform value").to_string(), + group: tr("Uniform"), + thumbnail: Some(app.thumbs.image(ctx, UNIFORM_SWATCH_NAME, &UNIFORM_SWATCH)), + preview: Box::new(|| ShelfPreview::Image(UNIFORM_SWATCH_NAME.to_string(), UNIFORM_SWATCH.clone())), + }); + tiles +} + +/// Sets the fill to the resource whose tile key is `key` +fn pick_resource(app: &mut TextureCraftApp, fill: &FillSourceTarget, key: &str) { + let pattern = key.strip_prefix(PATTERN_PREFIX).and_then(ProceduralKind::parse); + match (fill, pattern) { + (FillSourceTarget::Mask { effect }, Some(kind)) => { + app.run("effect.set", json!({"effect": effect, "procedural": kind.label()})); + } + (FillSourceTarget::Mask { effect }, None) => { + app.run("effect.set", json!({"effect": effect, "uniform": 1.0})); + } + (FillSourceTarget::Channel { base, channel }, Some(kind)) => { + let (low, high) = pattern_range(*channel); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "procedural": kind.label(), "low": low, "high": high}))); + } + (FillSourceTarget::Channel { base, channel }, None) => match key.strip_prefix(IMAGE_PREFIX) { + Some(name) => { + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "image": name}))); + } + None => { + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "value": channel.default_value()}))); + } + }, + } +} + +/// Sets the fill to read anchor point `anchor` in `channel` +fn pick_anchor(app: &mut TextureCraftApp, fill: &FillSourceTarget, anchor: LayerId, channel: Channel) { + let (command, params) = match fill { + FillSourceTarget::Mask { effect } => ("effect.set", json!({"effect": effect, "anchor": anchor.0, "anchorChannel": channel.id()})), + FillSourceTarget::Channel { base, channel } => ("layer.fill.set", with(base, json!({"channel": channel.id(), "anchor": anchor.0}))), + }; + app.run(command, params); +} + +/// The values a new pattern maps to in `channel`: grays for the base color, a small relief for height, most of the range otherwise +fn pattern_range(channel: Channel) -> ([f32; 3], [f32; 3]) { + match channel { + Channel::BaseColor => ([0.15; 3], [0.85; 3]), + Channel::Height => ([-0.05; 3], [0.05; 3]), + _ => ([0.2; 3], [0.8; 3]), + } +} diff --git a/crates/ui-egui/src/fill_source_target.rs b/crates/ui-egui/src/fill_source_target.rs new file mode 100644 index 00000000..78b5fe63 --- /dev/null +++ b/crates/ui-egui/src/fill_source_target.rs @@ -0,0 +1,12 @@ +//! Which fill a source slot sets + +use serde_json::Value; +use texturecraft_engine::core::Channel; + +/// Which fill the slot sets, and how +pub(crate) enum FillSourceTarget { + /// A mask fill effect: one grayscale value, set with `effect.set` + Mask { effect: u64 }, + /// One channel of a fill layer or content fill (`base` names it), set with `layer.fill.set` + Channel { base: Value, channel: Channel }, +} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 172017d9..95880e2d 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -15,7 +15,7 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::elided; -const SLOT_HEIGHT: f32 = 52.0; +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; @@ -48,7 +48,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: } let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); - paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); let items = |thumbs: &mut Thumbs| { filter_effects() @@ -90,11 +90,11 @@ fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret -fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { - let tk = Tokens::get(ui.ctx()); +/// A slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, `caption` over `name`, caret (fill source slots share it) +pub(crate) fn paint(ui: &Ui, rect: Rect, (highlighted, focused): (bool, bool), thumbnail: Option, (caption, name): (&str, &str)) { + let tokens = Tokens::get(ui.ctx()); let painter = ui.painter(); - let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + let (fill, border) = if highlighted { (tokens.row_hover, tokens.button_border) } else { (tokens.field, tokens.field_border) }; painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); if focused { painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); @@ -102,19 +102,19 @@ fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Optio if let Some(texture) = 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); + painter.image(texture, 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 = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + let lines = [(caption, CAPTION_FONT_SIZE, tokens.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tokens.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 highlighted { tk.text } else { tk.text_dim }; + let caret_color = if highlighted { tokens.text } else { tokens.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/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index d5246c68..a6da9f4d 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -10,25 +10,15 @@ use texturecraft_engine::core::{ use crate::TextureCraftApp; use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_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::widgets::{combo, section, slider_edit}; -/// Random seeds stay below this, short enough to read and type. -const SEED_RANGE: u32 = 10_000; -/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. -const SEED_MIX: u32 = 2_654_435_761; - -/// Font size of the notes under a control. -const NOTE_FONT_SIZE: f32 = 10.5; - /// 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; -/// Width of the names in the Attributes section, so their values line up. -const ATTRIBUTE_KEY_WIDTH: f32 = 80.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()); @@ -187,18 +177,6 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: Outpu .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); } -/// The most powers of two a resolution factor scales by, either way. -const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); - -/// "Same as context", or the fraction or multiple a resolution factor stands for. -fn factor_label(factor: i8) -> String { - match factor { - 0 => tr("Same as context").to_string(), - negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), - positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), - } -} - /// 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); @@ -258,13 +236,6 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { ui.data_mut(|data| data.insert_temp(typing_id, typing)); } -/// A seed different from `current`, from the clock. -fn random_seed(current: u32) -> u32 { - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); - let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; - if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } -} - /// 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); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs new file mode 100644 index 00000000..9034cc49 --- /dev/null +++ b/crates/ui-egui/src/gray_slider.rs @@ -0,0 +1,54 @@ +//! A gray value from black to white, as the reference shows a pattern's colors: a gradient bar with a knob, the value, and a button that inverts it + +use egui::{Rect, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as ic; + +use crate::i18n::tr; +use crate::theme::Tokens; + +const BAR_HEIGHT: f32 = 8.0; +const BAR_ROUNDING: f32 = 2.0; +const KNOB_RADIUS: f32 = 6.0; +const KNOB_STROKE: f32 = 1.5; +const BAR_BORDER_WIDTH: f32 = 1.0; +/// The narrowest bar, room for the knob to move +const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0; + +/// `label` and `value` over a black-to-white bar and an Invert value button: `Some(merge)` on every frame that changes it, as [`crate::widgets::slider_edit`] +pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.label(label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(format!("{value:.2}"))); + }); + ui.horizontal(|ui| { + let mut edit = None; + let button_width = ui.spacing().interact_size.y; + let width = (ui.available_width() - button_width - ui.spacing().item_spacing.x).max(MIN_BAR_WIDTH); + let (rect, response) = ui.allocate_exact_size(vec2(width, KNOB_RADIUS * 2.0 + KNOB_STROKE * 2.0), Sense::click_and_drag()); + let bar = Rect::from_center_size(rect.center(), vec2(rect.width() - KNOB_RADIUS * 2.0, BAR_HEIGHT)); + if let Some(pointer) = response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) { + *value = ((pointer.x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); + edit = Some(response.dragged() && !response.drag_started()); + } + + let painter = ui.painter(); + let mut mesh = egui::Mesh::default(); + for (corner, gray) in [(bar.left_top(), 0), (bar.right_top(), 255), (bar.right_bottom(), 255), (bar.left_bottom(), 0)] { + mesh.colored_vertex(corner, egui::Color32::from_gray(gray)); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(mesh); + painter.rect_stroke(bar, BAR_ROUNDING, Stroke::new(BAR_BORDER_WIDTH, tokens.field_border), egui::StrokeKind::Outside); + let knob = egui::pos2(bar.left() + bar.width() * value.clamp(0.0, 1.0), bar.center().y); + painter.circle(knob, KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, tokens.text_strong)); + + if ui.button(ic::CIRCLE_HALF).on_hover_text(tr("Invert value")).clicked() { + *value = 1.0 - *value; + edit = Some(false); + } + edit + }) + .inner +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f1aaa9b8..17587de3 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -156,7 +156,9 @@ mod tests { /// The labels of the menu catalog, panels, shortcuts, shelf tabs and engine enums that are /// translated where they are shown. fn catalog_keys() -> Vec<&'static str> { - use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; + use texturecraft_engine::core::{ + BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind, TileBlending, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, + }; use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params}; let mut keys: Vec<&'static str> = Vec::new(); keys.extend(crate::menus::TOP); @@ -176,6 +178,11 @@ mod tests { keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); + keys.extend(TileShape::ALL.iter().map(|shape| shape.label())); + keys.extend(TileSizeMode::ALL.iter().map(|mode| mode.label())); + keys.extend(TileInputDistribution::ALL.iter().map(|distribution| distribution.label())); + keys.extend(TileSymmetry::ALL.iter().map(|symmetry| symmetry.label())); + keys.extend(TileBlending::ALL.iter().map(|blending| blending.label())); keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label())); keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); for filter in FILTERS { diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index 27dc5f67..29f99dac 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -40,20 +40,39 @@ pub struct LayerPanel { service: ThumbService, textures: HashMap, frame: u64, + /// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`] + pictures_begun: bool, /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. pub(crate) folded: HashSet<(u64, bool)>, } +/// How soon to look again for pictures still rendering (milliseconds) +const POLL_INTERVAL_MS: u64 = 40; + impl LayerPanel { /// Start drawing the panel for this frame. pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.frame += 1; - self.service.begin_frame(session, now); + self.begin_pictures(session, now); // Deleted layer IDs must not accumulate in panel state self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); } + /// Notice document changes once per frame, whether the panel or a picture outside it asks first + fn begin_pictures(&mut self, session: &Session, now: f64) { + if !self.pictures_begun { + self.pictures_begun = true; + self.service.begin_frame(session, now); + } + } + + /// The texture of `target` for a picture outside the panel (a fill source slot, a source picker's anchor points), which renders while the panel is hidden too + pub(crate) fn texture_outside(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + self.begin_pictures(session, ctx.input(|input| input.time)); + self.texture(ctx, session, target) + } + /// The texture of `target`, queuing its render (call only for rows that are on screen). pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { let view = self.service.get(session, target); @@ -72,10 +91,14 @@ impl LayerPanel { Some(id) } - /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + /// Finish the frame once everything shown has asked for its pictures: collect them, start the missing ones and ask for another frame while work is outstanding pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if !std::mem::take(&mut self.pictures_begun) { + return; + } + if self.service.poll(session) { - ctx.request_repaint_after(Duration::from_millis(40)); + ctx.request_repaint_after(Duration::from_millis(POLL_INTERVAL_MS)); } if self.textures.len() > CACHE_ENTRIES * 2 { let frame = self.frame; @@ -110,6 +133,29 @@ mod tests { assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); } + #[test] + fn a_picture_outside_the_panel_renders_while_the_panel_is_hidden() { + // Long enough for the render worker on a busy machine + const ATTEMPTS: usize = 500; + const WAIT: Duration = Duration::from_millis(10); + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let context = Context::default(); + let mut panel = LayerPanel::default(); + + // The panel never begins a frame: only the outside picture asks + let picture = (0..ATTEMPTS).find_map(|_| { + let picture = panel.texture_outside(&context, &session, target); + panel.end(&context, &session); + if picture.is_none() { + std::thread::sleep(WAIT); + } + picture + }); + + assert!(picture.is_some(), "the picture renders without the Layers panel"); + } + #[test] fn evicted_and_dropped_thumbnail_handles_release_textures() { let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 74d92580..fcab0a7d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod angle_dial; mod bake_job; pub mod bake_mode; mod bake_scene; @@ -20,10 +21,13 @@ pub mod docking; pub mod export_templates; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_source_slot; +mod fill_source_target; mod filter_slot; pub mod fonts; mod generator_panel; pub mod gpu; +mod gray_slider; mod grid_tile; pub mod i18n; pub mod id_color_pick; @@ -40,6 +44,8 @@ mod orb_shape; pub mod parity; mod path_hit; mod path_surface_cache; +mod pattern_panel; +mod pattern_target; pub mod pbr_import; mod preview_image; mod preview_request; @@ -50,8 +56,13 @@ mod project_config; pub mod properties_popup; mod rail_popup; pub mod render_mode; +mod resource_panel; mod resource_picker; +mod resource_picker_anchor; +mod resource_picker_choice; mod resource_picker_item; +mod resource_picker_tab; +mod resource_picker_tile; mod running_bake; pub mod saved_search; mod screen_color_pick; @@ -68,6 +79,7 @@ pub mod state; pub mod symmetry; pub mod theme; pub mod thumbs; +mod tile_edits; pub mod titlebar; pub mod toolbar; pub mod ui_state_store; @@ -776,6 +788,8 @@ impl eframe::App for TextureCraftApp { let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + // The Layers panel and the source slots have asked for their pictures by now + self.layer_panel.end(&ctx, &self.session); #[cfg(not(target_arch = "wasm32"))] updates_ui::show(self, &ctx); toasts(self, &ctx); diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs new file mode 100644 index 00000000..6fb277b3 --- /dev/null +++ b/crates/ui-egui/src/pattern_panel.rs @@ -0,0 +1,374 @@ +//! A pattern's properties under its fill source slot, laid out like the reference app's: attributes, resolution, parameters, image inputs + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + OutputResolution, Procedural, ProceduralKind, ResolutionMode, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, +}; + +use crate::TextureCraftApp; +use crate::dock::{image_drop, image_menu}; +use crate::i18n::{tr, trf}; +use crate::pattern_target::PatternTarget; +use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; +use crate::theme::Tokens; +use crate::tile_edits::TileEdits; +use crate::widgets::{combo, section, slider_edit}; + +/// The pattern scale slider's range (repeats per projection unit) +const SCALE_RANGE: std::ops::RangeInclusive = 0.1..=100.0; +const CONTRAST_RANGE: std::ops::RangeInclusive = 0.0..=8.0; + +/// The settings of `pattern`: its attributes, resolution, parameters and, for the Tile Generator, its image inputs +pub(crate) fn pattern_properties(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let id = |name: &str| format!("pattern_{name}_{}", target.salt); + section(ui, &id("attributes"), tr("Attributes"), false, |ui| attributes(ui, pattern.kind)); + section(ui, &id("resolution"), tr("Resolution"), false, |ui| resolution(app, ui, target, pattern)); + section(ui, &id("parameters"), tr("Parameters"), true, |ui| { + seed_row(app, ui, target, pattern); + match pattern.tile.as_deref() { + Some(tile) => tile_parameters(app, ui, target, pattern, tile), + None => pattern_parameters(app, ui, target, pattern), + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + restore_defaults(app, target, pattern); + } + }); + }); + }); + if let Some(tile) = pattern.tile.as_deref() { + section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); + } +} + +/// Sends `pattern` again (its kind, scale, seed, contrast, balance and invert) with `extra` to its fill +pub(crate) fn send(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural, extra: Value) { + let mut params = target.base.clone(); + let fields = json!({ + "procedural": pattern.kind.label(), + "scale": pattern.scale, + "seed": pattern.seed, + "contrast": pattern.contrast, + "balance": pattern.balance, + "invert": pattern.invert, + }); + if let (Some(params), Value::Object(fields), Value::Object(extra)) = (params.as_object_mut(), fields, extra) { + params.extend(fields); + params.extend(extra); + } + app.run(target.command, params); +} + +/// What a pattern makes, its category and its tags (read only) +fn attributes(ui: &mut Ui, kind: ProceduralKind) { + let tokens = Tokens::get(ui.ctx()); + let description = match kind { + ProceduralKind::TileGenerator => tr("Shapes laid out in a grid of tiles: rows, offsets, random size, rotation and brightness."), + _ => tr("A procedural pattern mixing two values."), + }; + let tags = [tr("pattern"), tr(kind.label()), tr("grayscale")].join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Patterns")), (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 pattern's resolution is based on, the factor applied to it, and the size it comes to +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let tokens = Tokens::get(ui.ctx()); + let current = pattern.resolution; + combo(ui, tr("Resolution"), tr(current.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == current.mode, tr(mode.label())).clicked() { + send(app, target, pattern, json!({"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 current.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", current.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == current.custom, format!("{size} × {size}")).clicked() { + send(app, target, pattern, json!({"customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(current.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == current.factor, factor_label(factor)).clicked() { + send(app, target, pattern, json!({"resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the pattern is drawn coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.resolution) else { return }; + let size = current.output_size(texture_set, texture_set); + 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(format!("{size} × {size}"))); + }); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let typing_id = ui.make_persistent_id(("pattern_seed_typing", &target.salt)); + 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 = pattern.seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + let merge = field.dragged() && !field.drag_started(); + send(app, target, &Procedural { seed: typed, ..pattern.clone() }, json!({"merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &pattern.seed)])).clicked() { + send(app, target, &Procedural { seed: random_seed(pattern.seed), ..pattern.clone() }, json!({})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// Scale, contrast and invert of a pattern other than the Tile Generator +fn pattern_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let mut edited = pattern.clone(); + let invert_edit = ui.checkbox(&mut edited.invert, tr("Invert")).changed().then_some(false); + let scale_edit = slider_edit(ui, tr("Pattern scale"), &mut edited.scale, SCALE_RANGE, 1); + let contrast_edit = slider_edit(ui, tr("Contrast"), &mut edited.contrast, CONTRAST_RANGE, 2); + if let Some(merge) = invert_edit.or(scale_edit).or(contrast_edit) { + send(app, target, &edited, json!({"merge": merge})); + } +} + +/// Puts the pattern's parameters and resolution back to the defaults of its kind; its image inputs stay +fn restore_defaults(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural) { + let defaults = Procedural::new(pattern.kind); + let mut extra = json!({ + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + // The images stay: Restore defaults puts back the parameters, not the inputs + if let Some(tile) = pattern.tile.as_deref() { + extra["tileDefaults"] = json!(true); + extra["tile"] = json!({"inputs": tile.inputs, "backgroundImage": tile.background_image}); + } + send(app, target, &defaults, extra); +} + +/// The Tile Generator's settings, in the reference app's sections +fn tile_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let mut edits = TileEdits::default(); + let mut invert = pattern.invert; + if ui.checkbox(&mut invert, tr("Invert")).changed() { + send(app, target, &Procedural { invert, ..pattern.clone() }, json!({})); + } + edits.slider(ui, tr("Position"), "position", tile.position, 0.0..=1.0); + edits.slider(ui, tr("Contrast"), "contrast", tile.contrast, 0.0..=1.0); + let mut amount = tile.amount; + let mut amount_edit = None; + for (label, count) in [tr("X amount"), tr("Y amount")].into_iter().zip(amount.iter_mut()) { + let mut shown = *count as f32; + if let Some(merge) = slider_edit(ui, label, &mut shown, *TileGenerator::AMOUNT.start() as f32..=*TileGenerator::AMOUNT.end() as f32, 0) { + *count = shown.round() as u32; + amount_edit = Some(merge); + } + } + if let Some(merge) = amount_edit { + edits.set("amount", json!(amount), merge); + } + edits.check(ui, tr("Non-square expansion"), "nonSquareExpansion", tile.non_square_expansion); + + let id = |name: &str| format!("tile_{name}_{}", target.salt); + ui.indent(id("sections"), |ui| { + section(ui, &id("pattern"), tr("Pattern"), false, |ui| shape_section(ui, &mut edits, tile)); + section(ui, &id("size"), tr("Size"), false, |ui| size_section(ui, &mut edits, tile)); + section(ui, &id("position"), tr("Position"), false, |ui| position_section(ui, &mut edits, tile)); + section(ui, &id("rotation"), tr("Rotation"), false, |ui| { + edits.angle(ui, tr("Rotation"), "rotation", tile.rotation); + edits.slider(ui, tr("Rotation random"), "rotationRandom", tile.rotation_random, 0.0..=1.0); + }); + section(ui, &id("color"), tr("Color"), false, |ui| color_section(ui, &mut edits, tile)); + }); + + if let Some(merge) = edits.merge { + send(app, target, pattern, json!({"tile": Value::Object(edits.settings), "merge": merge})); + } +} + +/// The shape each tile draws and how it is turned and mirrored +fn shape_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.choice(ui, tr("Type"), "shape", tile.shape, &TileShape::ALL, TileShape::label); + for (index, (label, size)) in [tr("Resolution X"), tr("Resolution Y")].into_iter().zip(tile.shape_resolution).enumerate() { + combo(ui, label, size.to_string(), |ui| { + for option in TileGenerator::SHAPE_RESOLUTIONS { + if ui.selectable_label(option == size, option.to_string()).clicked() { + let mut resolution = tile.shape_resolution; + if let Some(side) = resolution.get_mut(index) { + *side = option; + } + edits.set("shapeResolution", json!(resolution), false); + } + } + }); + } + edits.slider(ui, tr("Specific"), "specific", tile.specific, 0.0..=1.0); + edits.angle(ui, tr("Angle"), "shapeAngle", tile.shape_angle); + edits.slider(ui, tr("Scale"), "shapeScale", tile.shape_scale, 0.0..=1.0); + edits.pair(ui, [tr("Size X"), tr("Size Y")], "shapeSize", tile.shape_size, 0.0..=1.0); + edits.count(ui, tr("Tiling"), "shapeTiling", tile.shape_tiling, TileGenerator::SHAPE_TILING); + edits.check(ui, tr("Rotation 45°"), "shapeDiagonal", tile.shape_diagonal); + edits.check(ui, tr("Non-square expansion"), "shapeNonSquareExpansion", tile.shape_non_square_expansion); + edits.choice(ui, tr("Input distribution"), "inputDistribution", tile.input_distribution, &TileInputDistribution::ALL, TileInputDistribution::label); + combo(ui, tr("Rotation"), format!("{}°", u32::from(tile.quarter_turns) * 90), |ui| { + for turns in 0..4u8 { + if ui.selectable_label(turns == tile.quarter_turns, format!("{}°", u32::from(turns) * 90)).clicked() { + edits.set("quarterTurns", json!(turns), false); + } + } + }); + edits.slider(ui, tr("Rotation random"), "quarterTurnRandom", tile.quarter_turn_random, 0.0..=1.0); + edits.check(ui, tr("Quincunx flip"), "quincunxFlip", tile.quincunx_flip); + edits.slider(ui, tr("Symmetry random"), "symmetryRandom", tile.symmetry_random, 0.0..=1.0); + edits.choice(ui, tr("Symmetry mode"), "symmetry", tile.symmetry, &TileSymmetry::ALL, TileSymmetry::label); +} + +/// How big each shape is: the controls of its size mode, then scale and its randomness +fn size_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.choice(ui, tr("Size mode"), "sizeMode", tile.size_mode, &TileSizeMode::ALL, TileSizeMode::label); + edits.pair(ui, [tr("Middle size horizontal"), tr("Middle size vertical")], "middleSize", tile.middle_size, 0.0..=1.0); + match tile.size_mode { + TileSizeMode::NormalInterstice => { + // Each axis's gap, then its randomness, as the reference lists them + let (mut gap, mut random) = (tile.interstice, tile.interstice_random); + let mut gap_edit = None; + let mut random_edit = None; + let labels = [(tr("Interstice X"), tr("Interstice X random")), (tr("Interstice Y"), tr("Interstice Y random"))]; + for ((gap_label, random_label), (gap, random)) in labels.into_iter().zip(gap.iter_mut().zip(random.iter_mut())) { + gap_edit = gap_edit.or(slider_edit(ui, gap_label, gap, 0.0..=1.0, 2)); + random_edit = random_edit.or(slider_edit(ui, random_label, random, 0.0..=1.0, 2)); + } + if let Some(merge) = gap_edit { + edits.set("interstice", json!(gap), merge); + } + if let Some(merge) = random_edit { + edits.set("intersticeRandom", json!(random), merge); + } + } + TileSizeMode::NormalSize => edits.pair(ui, [tr("Size X"), tr("Size Y")], "size", tile.size, 0.0..=1.0), + // The shape is the largest square its cell holds: no size of its own + TileSizeMode::KeepRatio => {} + TileSizeMode::Absolute => edits.pair(ui, [tr("Size X"), tr("Size Y")], "sizeAbsolute", tile.size_absolute, 0.0..=1.0), + TileSizeMode::Pixel => edits.pair(ui, [tr("Size X"), tr("Size Y")], "sizePixel", tile.size_pixel, 0.0..=TileGenerator::MAX_SIZE_PIXELS), + } + if matches!(tile.size_mode, TileSizeMode::Absolute | TileSizeMode::Pixel) { + edits.pair(ui, [tr("Size random X"), tr("Size random Y")], "sizeRandom", tile.size_random, 0.0..=1.0); + } + edits.slider(ui, tr("Scale"), "scale", tile.scale, 0.0..=TileGenerator::MAX_SCALE); + edits.slider(ui, tr("Scale random"), "scaleRandom", tile.scale_random, 0.0..=1.0); + edits.count(ui, tr("Scale random seed"), "scaleRandomSeed", tile.scale_random_seed, 0..=TileGenerator::MAX_RANDOM_SEED); +} + +/// Where each shape sits: the row offset, its randomness and the shift of the whole grid +fn position_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.slider(ui, tr("Offset"), "offset", tile.offset, 0.0..=1.0); + edits.slider(ui, tr("Offset random"), "offsetRandom", tile.offset_random, 0.0..=1.0); + edits.count(ui, tr("Offset random seed"), "offsetRandomSeed", tile.offset_random_seed, 0..=TileGenerator::MAX_RANDOM_SEED); + edits.check(ui, tr("Vertical offset"), "verticalOffset", tile.vertical_offset); + edits.pair(ui, [tr("Position random X"), tr("Position random Y")], "positionRandom", tile.position_random, 0.0..=1.0); + edits.pair(ui, [tr("Global offset X"), tr("Global offset Y")], "globalOffset", tile.global_offset, 0.0..=1.0); +} + +/// Each shape's brightness, the tiles hidden and how overlapping shapes combine +fn color_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.gray(ui, tr("Color"), "color", tile.color); + edits.slider(ui, tr("Luminance random"), "luminanceRandom", tile.luminance_random, 0.0..=1.0); + edits.check(ui, tr("Luminance by number"), "luminanceByNumber", tile.luminance_by_number); + edits.check(ui, tr("Luminance by scale"), "luminanceByScale", tile.luminance_by_scale); + edits.check(ui, tr("Checker mask"), "checkerMask", tile.checker_mask); + edits.check(ui, tr("Horizontal mask"), "horizontalMask", tile.horizontal_mask); + edits.check(ui, tr("Vertical mask"), "verticalMask", tile.vertical_mask); + edits.slider(ui, tr("Random mask"), "randomMask", tile.random_mask, 0.0..=1.0); + edits.check(ui, tr("Invert mask"), "invertMask", tile.invert_mask); + edits.choice(ui, tr("Blending"), "blending", tile.blending, &TileBlending::ALL, TileBlending::label); + edits.gray(ui, tr("Background"), "background", tile.background); + edits.slider(ui, tr("Global opacity"), "opacity", tile.opacity, 0.0..=1.0); + edits.check(ui, tr("Reverse rendering order"), "reverseOrder", tile.reverse_order); +} + +/// The images the Tile Generator can draw in its tiles, and the one under them +fn image_inputs(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let tokens = Tokens::get(ui.ctx()); + let mut inputs = tile.inputs.clone(); + let mut changed = false; + for index in 0..TileGenerator::MAX_INPUTS { + let current = inputs.get(index).cloned(); + let label = trf("Pattern input {number}", &[("number", &(index + 1))]); + if let Some(picked) = input_slot(app, ui, &label, current.as_deref()) { + match (picked, inputs.get_mut(index)) { + (Some(name), Some(slot)) => *slot = name, + (Some(name), None) => inputs.push(name), + (None, Some(_)) => { + inputs.remove(index); + } + (None, None) => {} + } + changed = true; + } + // Inputs fill in order: one empty slot after the last image + if current.is_none() { + break; + } + } + if changed { + send(app, target, pattern, json!({"tile": {"inputs": inputs}})); + } + if let Some(picked) = input_slot(app, ui, tr("Background"), tile.background_image.as_deref()) { + send(app, target, pattern, json!({"tile": {"backgroundImage": picked}})); + } + if tile.shape != TileShape::Image { + ui.label(RichText::new(tr("The pattern inputs are drawn when the shape type is Custom image input.")).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + } +} + +/// One image input: its name and image, a menu to pick another and a button that empties it. `Some(pick)` when changed (`None`: emptied) +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, label: &str, current: Option<&str>) -> Option> { + let tokens = Tokens::get(ui.ctx()); + let mut picked = None; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.label(RichText::new(label).strong()); + ui.label(RichText::new(current.unwrap_or(tr("Empty"))).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if current.is_some() && ui.button(ic::X).on_hover_text(tr("Empty this input")).clicked() { + picked = Some(None); + } + ui.menu_button(ic::IMAGE, |ui| { + if let Some(name) = image_menu(app, ui) { + picked = Some(Some(name)); + } + }) + .response + .on_hover_text(tr("Pick an image")); + }); + }); + }); + if let Some(name) = image_drop(ui, &group.response) { + picked = Some(Some(name)); + } + picked +} diff --git a/crates/ui-egui/src/pattern_target.rs b/crates/ui-egui/src/pattern_target.rs new file mode 100644 index 00000000..3b01be28 --- /dev/null +++ b/crates/ui-egui/src/pattern_target.rs @@ -0,0 +1,11 @@ +//! Where a pattern panel's edits go + +use serde_json::Value; + +/// Where a pattern's edits go: `command` with `base` params naming its fill (and channel, with the colors a pattern maps to) +pub(crate) struct PatternTarget { + pub command: &'static str, + pub base: Value, + /// Keeps the sections of two patterns shown at once apart + pub salt: String, +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 7e6469d6..9f7296db 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -115,14 +115,17 @@ pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { use texturecraft_engine::core::{Procedural, Projection}; use texturecraft_engine::geom::glam::{Vec2, Vec3}; - let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; - let mut img = ColorImage::filled([size, size], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); - let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + // The Tile Generator's tile counts set its frequency: its swatch shows its grid once + let defaults = Procedural::new(kind); + let scale = if kind == ProceduralKind::TileGenerator { defaults.scale } else { PROCEDURAL_SCALE }; + let pattern = Procedural { scale, ..defaults }; + let mut image = ColorImage::filled([size, size], Color32::BLACK); + for (index, pixel) in image.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((index % size) as f32 + 0.5) / size as f32, ((index / size) as f32 + 0.5) / size as f32); + let value = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *pixel = Color32::from_gray((value.clamp(0.0, 1.0) * 255.0) as u8); } - img + image } /// White-on-black `size²` swatch of library alpha `alpha` diff --git a/crates/ui-egui/src/resource_panel.rs b/crates/ui-egui/src/resource_panel.rs new file mode 100644 index 00000000..d4716d38 --- /dev/null +++ b/crates/ui-egui/src/resource_panel.rs @@ -0,0 +1,33 @@ +//! What the generator and pattern panels share: the attribute rows' key width, note size, the resolution factor's label and a random seed + +use texturecraft_engine::core::OutputResolution; + +use crate::i18n::tr; + +/// Width of the names in the Attributes section, so their values line up +pub(crate) const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; +/// Font size of the notes under a control +pub(crate) const NOTE_FONT_SIZE: f32 = 10.5; + +/// Random seeds stay below this, short enough to read and type +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range +const SEED_MIX: u32 = 2_654_435_761; +/// The most powers of two a resolution factor scales by, either way +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for +pub(crate) fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// A seed different from `current`, from the clock +pub(crate) fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 5b119c2f..e1c17c1a 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -1,9 +1,15 @@ -//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name; a fill source's picker adds a second tab with the anchor points it can read -use egui::{Id, Response, Stroke, Ui}; +use egui::{Id, Response, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::core::LayerId; use crate::i18n::tr; +use crate::resource_picker_anchor::ResourcePickerAnchor; +use crate::resource_picker_choice::ResourcePickerChoice; use crate::resource_picker_item::ResourcePickerItem; +use crate::resource_picker_tab::ResourcePickerTab; +use crate::resource_picker_tile::ResourcePickerTile; use crate::shelf; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; @@ -15,6 +21,33 @@ const PICKER_WIDTH: f32 = 320.0; const PICKER_HEIGHT: f32 = 340.0; const CURRENT_OUTLINE_WIDTH: f32 = 1.5; const TILE_ROUNDING: f32 = 3.0; +/// Group headers read as the shelf's section titles, a size above the tile labels +const GROUP_FONT_SIZE: f32 = 13.0; +const GROUP_GAP: f32 = 2.0; + +/// The tab strip along the popup's top edge: its height, the tabs' padding, rounding and the gap between them +const TAB_STRIP_HEIGHT: f32 = 28.0; +const TAB_PADDING: f32 = 10.0; +const TAB_ICON_GAP: f32 = 6.0; +const TAB_ROUNDING: f32 = 4.0; +const TAB_GAP: f32 = 4.0; +const TAB_INSET: f32 = 4.0; +const TAB_FONT_SIZE: f32 = 12.0; +/// How much darker the strip is than the popup body +const TAB_STRIP_DARKEN: f32 = 0.2; + +/// Anchor tiles: the shelf's tile size, the picture's size and place, the anchor badge in its corner and the channel line's size +const ANCHOR_TILE_SIZE: egui::Vec2 = vec2(72.0, 86.0); +const ANCHOR_PICTURE_SIZE: f32 = 56.0; +const ANCHOR_PICTURE_TOP: f32 = 4.0; +const ANCHOR_BADGE_SIZE: f32 = 13.0; +const ANCHOR_BADGE_INSET: f32 = 2.0; +const ANCHOR_BADGE_ICON_SIZE: f32 = 10.0; +/// Space kept clear at each side of an anchor tile's name +const ANCHOR_LABEL_INSET: f32 = 3.0; +const ANCHOR_LABEL_FONT_SIZE: f32 = 9.5; +const ANCHOR_LABEL_GAP: f32 = 3.0; +const ANCHOR_LINE_HEIGHT: f32 = 11.0; /// Opens the picker `popup_id` with an empty, focused search field, or closes it pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { @@ -30,6 +63,11 @@ pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { }); } +/// Whether picker `popup_id` is open: its tiles are worth gathering only then +pub(crate) fn is_open(ctx: &egui::Context, popup_id: Id) -> bool { + egui::Popup::is_id_open(ctx, popup_id) +} + /// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) pub(crate) fn show( slot: &Response, @@ -39,12 +77,57 @@ pub(crate) fn show( items: impl FnOnce(&mut Thumbs) -> Vec, preview: impl Fn(&'static str) -> ShelfPreview, ) -> Option<&'static str> { - let ctx = slot.ctx.clone(); - if !egui::Popup::is_id_open(&ctx, popup_id) { + if !is_open(&slot.ctx, popup_id) { return None; } let items = items(thumbs); + let tiles = items + .iter() + .map(|item| { + let id = item.id; + let preview = &preview; + ResourcePickerTile { + key: id.to_string(), + label: item.label.to_string(), + group: item.group, + thumbnail: item.thumbnail.clone(), + preview: Box::new(move || preview(id)), + } + }) + .collect(); + match popup(slot, popup_id, thumbs, (current, None), tiles, None) { + Some(ResourcePickerChoice::Resource(key)) => items.iter().find(|item| item.id == key).map(|item| item.id), + _ => None, + } +} + +/// Draws fill source picker `popup_id` at `slot` while open, with its Resources and Anchor points tabs: returns the tile clicked; `current` is the key of the source shown, `current_anchor` the anchor it reads (its tab opens first) +pub(crate) fn show_sources( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + (current, current_anchor): (Option<&str>, Option), + tiles: Vec>, + anchors: Vec, +) -> Option { + if !is_open(&slot.ctx, popup_id) { + return None; + } + + popup(slot, popup_id, thumbs, (current, current_anchor), tiles, Some(anchors)) +} + +/// The popup: the tabs when there are anchors to offer, the search field, then the tiles of the shown tab +fn popup( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + (current, current_anchor): (Option<&str>, Option), + tiles: Vec>, + anchors: Option>, +) -> Option { + let ctx = slot.ctx.clone(); let mut picked = None; egui::Popup::from_response(slot) .id(popup_id) @@ -55,11 +138,18 @@ pub(crate) fn show( .show(|ui| { ui.set_width(PICKER_WIDTH); let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let tab = match &anchors { + Some(_) => tab_strip(ui, popup_id, just_opened && current_anchor.is_some()), + None => ResourcePickerTab::Resources, + }; let query = search_field(ui, popup_id, just_opened); egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { // A search that leaves few tiles must not shrink the popup, or egui moves it ui.set_min_height(PICKER_HEIGHT); - picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + picked = match (tab, &anchors) { + (ResourcePickerTab::Anchors, Some(anchors)) => anchor_grid(ui, anchors, &query, current_anchor).map(ResourcePickerChoice::Anchor), + _ => grid(ui, thumbs, &tiles, &query, current, just_opened).map(ResourcePickerChoice::Resource), + }; }); }); @@ -69,6 +159,52 @@ pub(crate) fn show( picked } +/// The tabs on the popup's top edge: a darker strip, the shown tab in the body's color so it joins the list below. Returns the shown tab +fn tab_strip(ui: &mut Ui, popup_id: Id, open_anchors: bool) -> ResourcePickerTab { + let tokens = Tokens::get(ui.ctx()); + let tab_id = popup_id.with("tab"); + let mut shown = if open_anchors { + ResourcePickerTab::Anchors + } else { + ui.data(|data| data.get_temp::(tab_id)).unwrap_or(ResourcePickerTab::Resources) + }; + + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_STRIP_HEIGHT), Sense::hover()); + let body = ui.visuals().window_fill; + ui.painter().rect_filled(strip, 0.0, body.lerp_to_gamma(egui::Color32::BLACK, TAB_STRIP_DARKEN)); + let font = egui::FontId::proportional(TAB_FONT_SIZE); + let mut left = strip.left() + TAB_INSET; + for (tab, icon, label) in [(ResourcePickerTab::Resources, ic::SQUARES_FOUR, tr("Resources")), (ResourcePickerTab::Anchors, ic::ANCHOR, tr("Anchor points"))] + { + let icon_width = ui.painter().layout_no_wrap(icon.to_string(), font.clone(), tokens.text).size().x; + let label_width = ui.painter().layout_no_wrap(label.to_string(), font.clone(), tokens.text).size().x; + let width = TAB_PADDING * 2.0 + icon_width + TAB_ICON_GAP + label_width; + let rect = egui::Rect::from_min_max(pos2(left, strip.top() + TAB_INSET), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, popup_id.with(label), Sense::click()); + if response.clicked() { + shown = tab; + } + let on = shown == tab; + if on { + ui.painter().rect_filled(rect, egui::CornerRadius { nw: TAB_ROUNDING as u8, ne: TAB_ROUNDING as u8, sw: 0, se: 0 }, body); + } + let color = if on { + tokens.text_strong + } else if response.hovered() { + tokens.text + } else { + tokens.text_dim + }; + let painter = ui.painter(); + painter.text(pos2(rect.left() + TAB_PADDING, rect.center().y), egui::Align2::LEFT_CENTER, icon, font.clone(), color); + painter.text(pos2(rect.left() + TAB_PADDING + icon_width + TAB_ICON_GAP, rect.center().y), egui::Align2::LEFT_CENTER, label, font.clone(), color); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, on, label)); + left += width + TAB_GAP; + } + ui.data_mut(|data| data.insert_temp(tab_id, shown)); + shown +} + /// The search field, focused the frame the picker opens; returns the lowercase query fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); @@ -82,32 +218,31 @@ fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { query } -/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked -fn grid( - ui: &mut Ui, - thumbs: &mut Thumbs, - items: &[ResourcePickerItem], - query: &str, - current: Option<&str>, - reveal_current: bool, - preview: &impl Fn(&'static str) -> ShelfPreview, -) -> Option<&'static str> { - let tk = Tokens::get(ui.ctx()); - let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); +/// A group's title over its tiles, as the shelf's section titles +fn group_header(ui: &mut Ui, text: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.add_space(GROUP_GAP); + ui.label(egui::RichText::new(text).size(GROUP_FONT_SIZE).color(tokens.text)); +} + +/// The tiles matching `query` under group headers, `current` outlined; returns the key of the one clicked +fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tiles: &[ResourcePickerTile<'_>], query: &str, current: Option<&str>, reveal_current: bool) -> Option { + let tokens = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerTile<'_>> = tiles.iter().filter(|tile| shelf::matches(query, &[&tile.label, &tile.key])).collect(); let mut picked = None; - for group in shelf::categories(&shown, |item| item.group) { - shelf::header(ui, group); + for group in shelf::categories(&shown, |tile| tile.group) { + group_header(ui, group); shelf::tiles(ui, |ui| { - for item in shown.iter().filter(|item| item.group == group) { - let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); - if current == Some(item.id) { + for tile in shown.iter().filter(|tile| tile.group == group) { + let response = shelf::tile(ui, thumbs, tile.thumbnail.as_ref(), || (tile.preview)(), &tile.label, None); + if current == Some(tile.key.as_str()) { if reveal_current { response.scroll_to_me(Some(egui::Align::Center)); } - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); } if response.clicked() { - picked = Some(item.id); + picked = Some(tile.key.clone()); } } }); @@ -115,6 +250,63 @@ fn grid( picked } +/// The anchor points matching `query` as tiles: a picture of what each reads, an anchor badge, the layer and the channel +fn anchor_grid(ui: &mut Ui, anchors: &[ResourcePickerAnchor], query: &str, current: Option) -> Option { + let tokens = Tokens::get(ui.ctx()); + if anchors.is_empty() { + ui.label(egui::RichText::new(tr("No anchor point below this layer.")).color(tokens.text_dim)); + return None; + } + + let shown: Vec<&ResourcePickerAnchor> = anchors.iter().filter(|anchor| shelf::matches(query, &[&anchor.name, tr(anchor.channel)])).collect(); + let mut picked = None; + shelf::tiles(ui, |ui| { + for anchor in shown { + let response = anchor_tile(ui, anchor); + if current == Some(anchor.anchor) { + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(anchor.anchor); + } + } + }); + picked +} + +/// One anchor tile, the shelf tile's size: the picture, the anchor badge in its corner, the layer's name and the channel under it +fn anchor_tile(ui: &mut Ui, anchor: &ResourcePickerAnchor) -> Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(ANCHOR_TILE_SIZE, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &anchor.name)); + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); + } + let picture = egui::Rect::from_min_size( + pos2(rect.center().x - ANCHOR_PICTURE_SIZE * 0.5, rect.top() + ANCHOR_PICTURE_TOP), + vec2(ANCHOR_PICTURE_SIZE, ANCHOR_PICTURE_SIZE), + ); + painter.rect_filled(picture, TILE_ROUNDING, tokens.field); + if let Some(texture) = anchor.picture { + painter.image(texture, picture, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + let badge = egui::Rect::from_min_size( + picture.right_bottom() - vec2(ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET, ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET), + vec2(ANCHOR_BADGE_SIZE, ANCHOR_BADGE_SIZE), + ); + painter.rect_filled(badge, TILE_ROUNDING, tokens.panel); + painter.text(badge.center(), egui::Align2::CENTER_CENTER, ic::ANCHOR, egui::FontId::proportional(ANCHOR_BADGE_ICON_SIZE), tokens.text); + + let font = egui::FontId::proportional(ANCHOR_LABEL_FONT_SIZE); + let width = rect.width() - ANCHOR_LABEL_INSET * 2.0; + let name = crate::widgets::elided(painter, anchor.layer.clone(), ANCHOR_LABEL_FONT_SIZE, tokens.text, width); + let top = picture.bottom() + ANCHOR_LABEL_GAP; + painter.galley(pos2(rect.center().x - name.size().x * 0.5, top), name, tokens.text); + painter.text(pos2(rect.center().x, top + ANCHOR_LINE_HEIGHT), egui::Align2::CENTER_TOP, tr(anchor.channel), font, tokens.text_dim); + response.on_hover_text(&anchor.name) +} + /// Where the picker keeps its search text fn search_id(popup_id: Id) -> Id { popup_id.with("search") diff --git a/crates/ui-egui/src/resource_picker_anchor.rs b/crates/ui-egui/src/resource_picker_anchor.rs new file mode 100644 index 00000000..d15bf8e4 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_anchor.rs @@ -0,0 +1,14 @@ +//! One tile of a fill source picker's Anchor points tab + +use egui::TextureId; +use texturecraft_engine::core::LayerId; + +/// One tile of the Anchor points tab: the anchor, its layer's name, the channel it is read in and a picture of that channel there +pub(crate) struct ResourcePickerAnchor { + pub anchor: LayerId, + /// The anchor's full name ("layer / anchor"), for its tooltip and screen readers + pub name: String, + pub layer: String, + pub channel: &'static str, + pub picture: Option, +} diff --git a/crates/ui-egui/src/resource_picker_choice.rs b/crates/ui-egui/src/resource_picker_choice.rs new file mode 100644 index 00000000..432be0db --- /dev/null +++ b/crates/ui-egui/src/resource_picker_choice.rs @@ -0,0 +1,9 @@ +//! What a fill source picker's click picked + +use texturecraft_engine::core::LayerId; + +/// What a fill source picker's click picked +pub(crate) enum ResourcePickerChoice { + Resource(String), + Anchor(LayerId), +} diff --git a/crates/ui-egui/src/resource_picker_tab.rs b/crates/ui-egui/src/resource_picker_tab.rs new file mode 100644 index 00000000..3b9c6b87 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_tab.rs @@ -0,0 +1,8 @@ +//! The tabs of a fill source picker + +/// The tabs of a fill source picker +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ResourcePickerTab { + Resources, + Anchors, +} diff --git a/crates/ui-egui/src/resource_picker_tile.rs b/crates/ui-egui/src/resource_picker_tile.rs new file mode 100644 index 00000000..9131f1cd --- /dev/null +++ b/crates/ui-egui/src/resource_picker_tile.rs @@ -0,0 +1,14 @@ +//! One tile of a resource picker's Resources tab + +use egui::TextureHandle; + +use crate::shelf_preview::ShelfPreview; + +/// One tile of the Resources tab: the key a pick returns, its label and group, its picture and its hover preview +pub(crate) struct ResourcePickerTile<'a> { + pub key: String, + pub label: String, + pub group: &'static str, + pub thumbnail: Option, + pub preview: Box ShelfPreview + 'a>, +} diff --git a/crates/ui-egui/src/tile_edits.rs b/crates/ui-egui/src/tile_edits.rs new file mode 100644 index 00000000..e05c33a9 --- /dev/null +++ b/crates/ui-egui/src/tile_edits.rs @@ -0,0 +1,85 @@ +//! The edits one frame of the Tile Generator's controls makes + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::angle_dial::angle_dial; +use crate::gray_slider::gray_slider; +use crate::i18n::tr; +use crate::widgets::{combo, slider_edit}; + +/// The edits one frame of the Tile Generator's controls makes: settings by command name, and whether they continue a drag +#[derive(Default)] +pub(crate) struct TileEdits { + pub settings: serde_json::Map, + pub merge: Option, +} + +impl TileEdits { + pub(crate) fn set(&mut self, key: &str, value: Value, merge: bool) { + self.settings.insert(key.to_string(), value); + self.merge = Some(self.merge.unwrap_or(true) && merge); + } + + pub(crate) fn slider(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: f32, range: std::ops::RangeInclusive) { + if let Some(merge) = slider_edit(ui, label, &mut value, range, 2) { + self.set(key, json!(value), merge); + } + } + + pub(crate) fn count(&mut self, ui: &mut Ui, label: &str, key: &str, value: u32, range: std::ops::RangeInclusive) { + let mut shown = value as f32; + if let Some(merge) = slider_edit(ui, label, &mut shown, *range.start() as f32..=*range.end() as f32, 0) { + self.set(key, json!(shown.round() as u32), merge); + } + } + + /// Two sliders for one `[horizontal, vertical]` setting + pub(crate) fn pair(&mut self, ui: &mut Ui, labels: [&str; 2], key: &str, mut value: [f32; 2], range: std::ops::RangeInclusive) { + let mut merge = None; + for (label, component) in labels.into_iter().zip(value.iter_mut()) { + merge = merge.or(slider_edit(ui, label, component, range.clone(), 2)); + } + if let Some(merge) = merge { + self.set(key, json!(value), merge); + } + } + + pub(crate) fn check(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: bool) { + if ui.checkbox(&mut value, label).changed() { + self.set(key, json!(value), false); + } + } + + pub(crate) fn angle(&mut self, ui: &mut Ui, label: &str, key: &str, mut degrees: f32) { + if let Some(merge) = angle_dial(ui, label, &mut degrees) { + self.set(key, json!(degrees), merge); + } + } + + /// A gray from black to white with a button that inverts it, as the reference's color rows + pub(crate) fn gray(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: f32) { + if let Some(merge) = gray_slider(ui, label, &mut value) { + self.set(key, json!(value), merge); + } + } + + /// A menu of `choices`, sent by their saved names + pub(crate) fn choice( + &mut self, + ui: &mut Ui, + label: &str, + key: &str, + current: T, + choices: &[T], + name: fn(T) -> &'static str, + ) { + combo(ui, label, tr(name(current)), |ui| { + for choice in choices { + if ui.selectable_label(*choice == current, tr(name(*choice))).clicked() { + self.set(key, json!(format!("{choice:?}")), false); + } + } + }); + } +} diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index ea48beb4..591f9baa 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -1,4 +1,4 @@ -//! A fill channel takes an image resource from its source menu. +//! A fill channel takes an image resource from its source picker use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -6,26 +6,22 @@ use serde_json::json; use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; -/// The Roughness channel's name in Properties (the rightmost "Roughness" label). +/// The Roughness channel's source slot in Properties fn roughness<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - harness.get_all_by_label("Roughness").max_by(|a, b| a.rect().right().total_cmp(&b.rect().right())).unwrap() + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness") } -/// Opens the source menu of the Roughness channel, which sits in the row of the channel's name. -fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>) { - const ROW_CENTER_TOLERANCE_POINTS: f32 = 6.0; - - // Allow the scroll animation to finish before locating the menu +/// Opens the source picker of the Roughness channel from its slot +fn open_roughness_source_picker(harness: &mut Harness<'_, TextureCraftApp>) { + // Allow the scroll animation to finish before the click roughness(harness).scroll_to_me(); harness.run_steps(30); - let row = roughness(harness).rect().center().y; - let menu = harness.get_all_by_label(egui_phosphor::regular::DOTS_THREE).find(|n| (n.rect().center().y - row).abs() < ROW_CENTER_TOLERANCE_POINTS).unwrap(); - menu.click(); - harness.run_steps(2); + roughness(harness).click(); + harness.run_steps(3); } #[test] -fn a_fill_channel_takes_an_image_from_its_source_menu() { +fn a_fill_channel_takes_an_image_from_its_source_picker() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut png_bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 255])).write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap(); @@ -38,8 +34,8 @@ fn a_fill_channel_takes_an_image_from_its_source_menu() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_menu(&mut harness); - harness.get_by_label(&name).click(); + open_roughness_source_picker(&mut harness); + harness.get_by_role_and_label(egui::Role::Button, &name).click(); harness.run_steps(3); let LayerKind::Fill(fill) = &harness.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; @@ -48,7 +44,7 @@ fn a_fill_channel_takes_an_image_from_its_source_menu() { /// A resource that did not decode is not offered, since the commands that take an image refuse it. #[test] -fn the_source_menu_offers_only_images_that_were_decoded() { +fn the_source_picker_offers_only_images_that_were_decoded() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut png_bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 255])).write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap(); @@ -63,7 +59,7 @@ fn the_source_menu_offers_only_images_that_were_decoded() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_menu(&mut harness); + open_roughness_source_picker(&mut harness); assert!(harness.query_by_label(&name).is_some(), "a decoded image is offered"); assert!(harness.query_by_label("broken.png").is_none(), "an image that did not decode is not"); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 4f454304..71169c4f 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -42,3 +42,4 @@ mod tool_availability; mod toolbar; mod symmetry; +mod tile_generator_panel; diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs new file mode 100644 index 00000000..3ac4e60d --- /dev/null +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -0,0 +1,208 @@ +//! The pattern panel and the fill source picker: a mask fill picks the Tile Generator and its settings edit it + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{EffectKind, LayerId, Procedural, ProceduralKind, Source, TileGenerator}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with an anchor point on a fill layer, and above it a fill layer whose black mask holds a uniform mask fill, selected +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + execute(&mut session, "layer.add.fill", &json!({"height": 0.6})).unwrap(); + execute(&mut session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(); + 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.fill", &json!({"value": 1.0})).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)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn source(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Source { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { source, .. } => source.clone(), + _ => panic!("expected a mask fill"), + } +} + +fn pattern(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Procedural { + match source(harness, effect) { + Source::Procedural { pattern, .. } => pattern, + other => panic!("expected a pattern, the fill reads {other:?}"), + } +} + +/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile` +fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_label(tile).click(); + harness.run_steps(3); +} + +/// Where a slider's track is grabbed, from its label's left end and bottom, and how far it is dragged (points) +const TRACK_GRAB_INSET: f32 = 20.0; +const TRACK_BELOW_LABEL: f32 = 10.0; +const DRAG_DISTANCE: f32 = 120.0; + +/// How long `settle` gives the render worker: 40 rounds of 50 ms, two seconds +const SETTLE_ROUNDS: usize = 40; +const SETTLE_WAIT: std::time::Duration = std::time::Duration::from_millis(50); +const FRAMES_PER_ROUND: usize = 3; + +/// Runs frames until the thumbnails rendered off the UI thread arrive +fn settle(harness: &mut Harness<'_, TextureCraftApp>) { + for _ in 0..SETTLE_ROUNDS { + harness.run_steps(FRAMES_PER_ROUND); + std::thread::sleep(SETTLE_WAIT); + } +} + +/// Drags the track under slider `label` to the right +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + // The track runs under the label: grab it near its left end and drag well to the right + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + TRACK_GRAB_INSET, rect.bottom() + TRACK_BELOW_LABEL); + let end = start + egui::vec2(DRAG_DISTANCE, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn the_picker_sets_a_mask_fill_to_the_tile_generator_and_back_to_a_value() { + let (mut harness, effect) = harness(false); + pick(&mut harness, "Tile Generator"); + assert_eq!(pattern(&harness, effect).kind, ProceduralKind::TileGenerator); + + pick(&mut harness, "Uniform value"); + assert!(matches!(source(&harness, effect), Source::Uniform(_))); +} + +#[test] +fn the_anchor_points_tab_picks_an_anchor() { + let (mut harness, effect) = harness(false); + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_label("Anchor points").click(); + harness.run_steps(3); + // An anchor tile is labelled " / ", as the anchors below a layer are listed + let project = &harness.state().session.doc.project; + let owner = project.layers.values().find(|layer| layer.content_effects.iter().any(|effect| effect.name == "Height")).unwrap(); + let label = format!("{} / Height", owner.name); + harness.get_by_role_and_label(Role::Button, &label).click(); + harness.run_steps(3); + assert!(source(&harness, effect).anchor().is_some()); +} + +/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the mask +#[test] +fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + let lower = execute(&mut session, "layer.add.fill", &json!({"name": "Lower"})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.white", &json!({})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask", "name": "Wear"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); + session.update(); + 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.focus(Panel::Properties); + harness.run_steps(6); + + let slot = harness.get_by_role_and_label(Role::ComboBox, "Grayscale"); + + assert_eq!(slot.value().as_deref(), Some("Lower · Mask")); +} + +#[test] +fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + let history = harness.state().session.history_labels().len(); + + drag_slider(&mut harness, "X amount"); + let tile = pattern(&harness, effect).tile.unwrap(); + assert!(tile.amount[0] > TileGenerator::default().amount[0], "the drag adds columns: {:?}", tile.amount); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "one drag is one undo step"); + + 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!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn tile_generator_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, effect) = harness(true); + + // The picker over the slot, both tabs + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("picker-resources.png")).unwrap(); + harness.get_by_label("Anchor points").click(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("picker-anchors.png")).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.state_mut().session.update(); + 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(6); + harness.render().unwrap().save(directory.join(format!("tile-panel-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::Dark; + + for (sections, name) in [(["Pattern", "Size"], "pattern-size"), (["Position", "Rotation"], "position-rotation")] { + for section in sections { + // A section's title can also be a control's label above it ("Position"): the title is the last one + harness.get_all_by_label(section).last().unwrap().scroll_to_me(); + // The scroll animates: the title must be on screen before the click + harness.run_steps(12); + harness.get_all_by_label(section).last().unwrap().click(); + harness.run_steps(3); + } + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("tile-sections-{name}.png"))).unwrap(); + } + harness.get_all_by_label("Color").last().unwrap().scroll_to_me(); + harness.run_steps(12); + harness.get_all_by_label("Color").last().unwrap().click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("tile-sections-color.png")).unwrap(); + + // A changed pattern, in the 2D view + let edits = json!({"effect": effect.0, "tile": {"shape": "Disc", "amount": [8, 4], "offset": 0.5, "scaleRandom": 0.6, "luminanceRandom": 0.5}}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("tile-adjusted.png")).unwrap(); +} From 7c28d4f5f5611a25e799e0d535ce082213558c25 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:43:05 +0000 Subject: [PATCH 4/9] Tile Generator image inputs The Custom image input shape draws one of the pattern's input images in each tile, picked at random or by tile number, through the shape's tiling, angle, scale and turns; the background image shows under the shapes instead of the background value. Patterns read images through a PatternContext (its resolution and the image resources), which the compositor passes; procedural() keeps evaluating without images. --- crates/compose/src/below.rs | 6 +- crates/compose/src/eval.rs | 10 +- crates/compose/src/lib.rs | 2 + crates/compose/src/pattern.rs | 63 ++++-- crates/compose/src/pattern_context.rs | 12 ++ crates/compose/src/tile_pattern.rs | 210 +++++++++++++++++--- crates/compose/src/tile_random_stream.rs | 1 + crates/compose/tests/cache_and_instances.rs | 40 ++++ crates/engine/src/session.rs | 2 +- crates/engine/tests/it/tile_generator.rs | 50 +++++ 10 files changed, 338 insertions(+), 58 deletions(-) create mode 100644 crates/compose/src/pattern_context.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 81868e66..4a2187ed 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -143,11 +143,7 @@ impl StackKey { let mut referenced_images = BTreeSet::new(); if !images.is_empty() { let mut record_image_reference = |source: &Source| { - if let Source::Image { name, .. } = source - && let Some((name, _)) = images.get_key_value(name) - { - referenced_images.insert(name); - } + referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name)); }; for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { if let LayerKind::Fill(fill) = &layer.kind { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c8423295..43bd814c 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -21,7 +21,8 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv, image_samples, pattern_pixels, procedural_sized, world_noise}; +use crate::pattern::{Coords, decal_uv, image_samples, pattern_pixels, procedural_in, world_noise}; +use crate::pattern_context::PatternContext; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; const NCH: usize = Channel::ALL.len(); @@ -1424,12 +1425,13 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Procedural { pattern, low, high } => { let (coords, projection, _) = self.projected(projection); let pixels = if pattern.resolution.can_reduce() { - let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(self.inp.tile_res(), |set| set.resolution); - pattern_pixels(pattern, self.inp.tile_res(), texture_set) + let uv_tile = self.inp.tile_res(); + let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); + pattern_pixels(pattern, uv_tile, texture_set) } else { None }; - let amount = procedural_sized(pattern, projection, &coords, pixels); + let amount = procedural_in(pattern, projection, &coords, &PatternContext { pixels, images: Some(self.inp.images) }); mix3(*low, *high, amount) } Source::Image { name, normal_format } => { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index f80e441c..e8de0d5e 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -16,6 +16,7 @@ pub mod eval; mod held_fields; mod image_identity; pub mod pattern; +mod pattern_context; pub mod store; pub mod thumb; mod tile_pattern; @@ -27,5 +28,6 @@ pub use eval::{ BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours, }; +pub use pattern_context::PatternContext; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 44da3236..b8b26524 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -4,6 +4,11 @@ use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_texel::noise; +use crate::pattern_context::PatternContext; + +/// Smaller pattern scales are read as this: a pattern stretched over ten thousand repeats of its projection +const MIN_PATTERN_SCALE: f32 = 1e-4; + /// Where a texel is, for pattern evaluation. #[derive(Clone, Copy, Debug)] pub struct Coords { @@ -143,7 +148,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { let (g1, _, _) = noise::cellular((p * 2.7 + Vec3::splat(13.0)).to_array(), seed ^ 0x6B); smoothstep(0.08, 0.16, f1).min(smoothstep(0.06, 0.12, g1)) } - ProceduralKind::TileGenerator => crate::tile_pattern::value(&crate::tile_pattern::DEFAULT, p.truncate(), seed), + ProceduralKind::TileGenerator => crate::tile_pattern::value(&crate::tile_pattern::DEFAULT, p.truncate(), seed, None), ProceduralKind::Chips => { let (f1, _, _) = noise::cellular((p * 2.0).to_array(), seed ^ 0x45); let n = noise::fbm(a, 5, seed, noise::perlin) + (f1 - 0.5) * 0.25; @@ -201,16 +206,15 @@ fn shape(pr: &Procedural, v: f32) -> f32 { if pr.invert { 1.0 - v } else { v } } -/// Evaluate a procedural through a projection, at full resolution +/// Evaluate a procedural through a projection, at full resolution and without images pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { - procedural_sized(pattern, projection, coords, None) + procedural_in(pattern, projection, coords, &PatternContext::default()) } -/// Evaluate a procedural through a projection, drawn as an image of `pixels` texels per side over one repeat of the projection (read back bilinearly) when its resolution asks for one: see [`pattern_pixels`]. `None` evaluates it exactly -pub fn procedural_sized(pattern: &Procedural, projection: &Projection, coords: &Coords, pixels: Option) -> f32 { - let pattern_scale = pattern.scale.max(1e-4); - let cells = pixels.map(|pixels| pixels as f32 / pattern_scale); - let sample = |point: Vec3| plane_value(pattern, point, cells); +/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads +pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 { + let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE); + let sample = |point: Vec3| plane_value(pattern, point, context); let value = match projection { Projection::Uv { scale, rotation, offset } => { let (sn, cs) = rotation.to_radians().sin_cos(); @@ -269,23 +273,25 @@ pub fn pattern_pixels(pattern: &Procedural, uv_tile: u32, texture_set: u32) -> O (size < uv_tile).then_some(size) } -/// The pattern at `point` of its plane, read from an image of `cells` texels per unit (bilinear) when given -fn plane_value(pr: &Procedural, point: Vec3, cells: Option) -> f32 { - let Some(cells) = cells.filter(|cells| cells.is_finite() && *cells > 0.0) else { return pattern_value(pr, point) }; +/// The pattern at `point` of its plane, read from an image of `context.pixels` texels per repeat (bilinear) when given +fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 { + let cells = context.pixels.map(|pixels| pixels as f32 / pattern.scale.max(MIN_PATTERN_SCALE)).filter(|cells| cells.is_finite() && *cells > 0.0); + let Some(cells) = cells else { return pattern_value(pattern, point, context) }; + let grid = point.truncate() * cells - 0.5; let base = grid.floor(); let fraction = grid - base; - let at = |dx: f32, dy: f32| pattern_value(pr, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z)); + let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context); let top = at(0.0, 0.0) + (at(1.0, 0.0) - at(0.0, 0.0)) * fraction.x; let bottom = at(0.0, 1.0) + (at(1.0, 1.0) - at(0.0, 1.0)) * fraction.x; top + (bottom - top) * fraction.y } /// The pattern at `point` of its plane, exactly -fn pattern_value(pr: &Procedural, point: Vec3) -> f32 { - match (&pr.tile, pr.kind) { - (Some(tile), ProceduralKind::TileGenerator) => crate::tile_pattern::value(tile, point.truncate(), pr.seed), - _ => raw(pr.kind, point, pr.seed), +fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 { + match (&pattern.tile, pattern.kind) { + (Some(tile), ProceduralKind::TileGenerator) => crate::tile_pattern::value(tile, point.truncate(), pattern.seed, context.images), + _ => raw(pattern.kind, point, pattern.seed), } } @@ -382,6 +388,31 @@ pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 { #[cfg(test)] mod tests { use super::*; + use texturecraft_core::{OutputResolution, ResolutionMode}; + + #[test] + fn a_pattern_is_drawn_coarser_only_below_the_uv_tiles_resolution() { + let with = |resolution: OutputResolution| pattern_pixels(&Procedural { resolution, ..Procedural::new(ProceduralKind::Clouds) }, 1024, 2048); + assert_eq!(with(OutputResolution::default()), None, "by default a pattern is evaluated per texel"); + assert_eq!(with(OutputResolution { factor: -1, ..OutputResolution::default() }), Some(512)); + assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 256, factor: 0 }), Some(256)); + assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 2048, factor: 0 }), None, "a finer image than the UV tile changes nothing"); + } + + #[test] + fn a_coarser_pattern_reads_its_cells_bilinearly() { + let pattern = Procedural { scale: 1.0, ..Procedural::new(ProceduralKind::Clouds) }; + let coarse = PatternContext { pixels: Some(4), ..PatternContext::default() }; + let at = |x: f32, context: &PatternContext| { + procedural_in(&pattern, &Projection::default(), &Coords { uv: Vec2::new(x, 0.375), pos: Vec3::ZERO, nrm: Vec3::Y }, context) + }; + let exact = PatternContext::default(); + // Cell centres of a 4-texel image sit at 0.125, 0.375…: there the coarse pattern is exact, between them it blends them + assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5); + let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5; + assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse)); + assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); + } #[test] fn every_pattern_and_projection_stays_in_range() { diff --git a/crates/compose/src/pattern_context.rs b/crates/compose/src/pattern_context.rs new file mode 100644 index 00000000..09b6b0a1 --- /dev/null +++ b/crates/compose/src/pattern_context.rs @@ -0,0 +1,12 @@ +//! What evaluating a pattern needs besides the texel: the resolution it is drawn at and the images it reads + +use crate::store::ImageStore; + +/// What a pattern reads beyond the texel's coordinates (fields can be added; build it with `..PatternContext::default()`) +#[derive(Clone, Copy, Default)] +pub struct PatternContext<'a> { + /// Texels per side of the image the pattern is drawn as over one repeat of the projection (see [`crate::pattern::pattern_pixels`]); None draws it exactly + pub pixels: Option, + /// The image resources a pattern's inputs name; None reads them as empty + pub images: Option<&'a ImageStore>, +} diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs index 490a0d37..5b725f38 100644 --- a/crates/compose/src/tile_pattern.rs +++ b/crates/compose/src/tile_pattern.rs @@ -2,9 +2,10 @@ use std::sync::LazyLock; -use texturecraft_core::{TileBlending, TileGenerator, TileShape, TileSizeMode, TileSymmetry}; +use texturecraft_core::{TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry}; use texturecraft_geom::glam::Vec2; +use crate::store::{ImageRes, ImageStore}; use crate::tile_random_stream::TileRandomStream; /// The settings a Tile Generator pattern saved without its own reads @@ -27,8 +28,6 @@ const WAVES_BASE_CYCLES: f32 = 1.5; const WAVES_SPECIFIC_CYCLES: f32 = 6.0; /// Narrower than this, a size or a bevel is none const EPSILON: f32 = 1e-6; -/// Tiles a texel looks at, at most, along each axis (bounds the work of huge or far-moved shapes) -const MAX_REACH: i32 = 16; fn smoothstep(t: f32) -> f32 { let t = t.clamp(0.0, 1.0); @@ -44,6 +43,7 @@ fn shape(kind: TileShape, u: f32, v: f32, specific: f32) -> f32 { if u.abs() > 1.0 || v.abs() > 1.0 { return 0.0; } + let r = u.hypot(v); match kind { TileShape::Square => 1.0, @@ -82,7 +82,7 @@ fn shape(kind: TileShape, u: f32, v: f32, specific: f32) -> f32 { let distance = (u.abs() - half_length).max(0.0).hypot(v); (1.0 - (distance / CAPSULE_RADIUS).powi(2)).clamp(0.0, 1.0) } - // The image shape reads the pattern's input images, which the plane alone cannot: nothing until they are given + // The image shape draws an input image instead (see `pattern`): without one it is empty TileShape::Image => 0.0, } } @@ -92,16 +92,17 @@ fn unrotate(point: Vec2, turns: f32) -> Vec2 { if turns == 0.0 { return point; } + let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos(); Vec2::new(cos * point.x + sin * point.y, -sin * point.x + cos * point.y) } -/// The pattern section: tile-local (u, v) through the shape's tiling, angle, scale, size and 45° turn, then the shape -fn pattern(tile: &TileGenerator, local: Vec2) -> f32 { +/// The pattern section: tile-local (u, v) through the shape's tiling, angle, scale, size and 45° turn, then the shape (`input` for the image shape) +fn pattern(tile: &TileGenerator, mut local: Vec2, input: Option<&ImageRes>) -> f32 { if local.x.abs() > 1.0 || local.y.abs() > 1.0 { return 0.0; } - let mut local = local; + if tile.shape_tiling > 1 { // The shape repeats tiling × tiling times, but one copy shows: the one at index ceil(tiling / 2) − 1 from the top left let count = tile.shape_tiling as f32; @@ -110,6 +111,7 @@ fn pattern(tile: &TileGenerator, local: Vec2) -> f32 { if cell.x.floor() != shown || cell.y.floor() != shown { return 0.0; } + local = (cell - shown) * 2.0 - 1.0; } local = unrotate(local, tile.shape_angle / 360.0); @@ -117,14 +119,34 @@ fn pattern(tile: &TileGenerator, local: Vec2) -> f32 { if size.x <= EPSILON || size.y <= EPSILON { return 0.0; } + local /= size; if tile.shape_diagonal { local = unrotate(local, 0.125) * std::f32::consts::SQRT_2; } + if tile.shape == TileShape::Image { + return input.map_or(0.0, |image| image_shape(image, local)); + } + let samples = Vec2::new(tile.shape_resolution[0] as f32, tile.shape_resolution[1] as f32); sampled_shape(tile, local, samples) } +/// An input image over the shape's square, as gray (the average of its color) +fn image_shape(image: &ImageRes, local: Vec2) -> f32 { + if local.x.abs() > 1.0 || local.y.abs() > 1.0 { + return 0.0; + } + + let at = (local + 1.0) * 0.5; + gray(image.sample(at.x, at.y)) +} + +/// The gray of an image texel: the average of its color +fn gray([red, green, blue, _]: [f32; 4]) -> f32 { + ((red + green + blue) / 3.0).clamp(0.0, 1.0) +} + /// The shape read from an image of `samples` texels over its square, bilinearly, as the shape is drawn at its own resolution fn sampled_shape(tile: &TileGenerator, local: Vec2, samples: Vec2) -> f32 { let grid = (local + 1.0) * 0.5 * samples - 0.5; @@ -150,8 +172,14 @@ fn wrap(delta: f32, span: f32) -> f32 { delta - (delta / span).round() * span } -/// What one tile gives a texel (its shape times its luminance), or None when it is hidden or does not reach it -fn tile_value(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), (columns, rows): (i32, i32), point: Vec2) -> Option { +/// What one tile gives a texel (its shape times its luminance), or None when hidden or out of reach; `inputs` are its input images +fn tile_value( + tile: &TileGenerator, + seed: u32, + (column, row): (i32, i32), + (columns, rows): (i32, i32), + (point, inputs): (Vec2, &[Option<&ImageRes>]), +) -> Option { let total = columns * rows; let number = column * rows + row; let index = (if tile.reverse_order { total - 1 - number } else { number }) as u32; @@ -192,10 +220,16 @@ fn tile_value(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), (colum local.y = -local.y; } - let value = pattern(tile, local); + let input = match tile.input_distribution { + _ if inputs.is_empty() => None, + TileInputDistribution::Random => inputs.get((TileRandomStream::Input.draw(seed, index) * inputs.len() as f32) as usize).copied().flatten(), + TileInputDistribution::ByNumber => inputs.get(number as usize % inputs.len()).copied().flatten(), + }; + let value = pattern(tile, local, input); if value <= 0.0 { return None; } + let mut luminance = 1.0 - tile.luminance_random * TileRandomStream::Luminance.draw(seed, index); if tile.luminance_by_number { luminance *= (number + 1) as f32 / total as f32; @@ -268,13 +302,12 @@ fn reach(tile: &TileGenerator, counts: Vec2) -> Vec2 { /// The cells along an axis of `count` whose centers can be within `reach` of `position` (in cells): each once, at most `count` fn near(position: f32, reach: f32, count: i32) -> impl Iterator { - let first = (position - reach - 0.5).floor() as i32; - let last = (position + reach - 0.5).ceil() as i32; - let span = last - first + 1; - let kept = span.clamp(1, count.min(MAX_REACH * 2 + 1)); - // A capped span keeps the cells nearest the texel - let first = first + (span - kept) / 2; - (first..first + kept).map(move |index| index.rem_euclid(count)) + let first = (position - reach - 0.5).floor(); + let last = (position + reach - 0.5).ceil(); + // A reach past the whole grid visits each cell once; float math keeps a hostile reach from overflowing + let span = (last - first + 1.0).min(count as f32).max(1.0) as i32; + let first = first as i32; + (first..first.saturating_add(span)).map(move |index| index.rem_euclid(count)) } /// The shift along its line of line `line` (a row, or a column with a vertical offset), in cells @@ -282,14 +315,25 @@ fn line_shift(tile: &TileGenerator, line: i32) -> f32 { tile.offset * line as f32 + tile.offset_random * TileRandomStream::Offset.draw(tile.offset_random_seed, line as u32) } -/// The pattern's value at `point` of its plane (one unit = the whole grid, repeating) -pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32) -> f32 { - let tile = tile.clamped_without_images(); - let (columns, rows) = (tile.amount[0] as i32, tile.amount[1] as i32); +/// The pattern's value at `point` of its plane (one unit = the whole grid, repeating); `images` holds the images its inputs name +pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32, images: Option<&ImageStore>) -> f32 { + let image = |name: &str| images.and_then(|images| images.get(name)).map(|image| &**image); + let mut slots: [Option<&ImageRes>; TileGenerator::MAX_INPUTS] = [None; TileGenerator::MAX_INPUTS]; + let count = tile.inputs.len().min(TileGenerator::MAX_INPUTS); + if tile.shape == TileShape::Image { + for (slot, name) in slots.iter_mut().zip(&tile.inputs) { + *slot = image(name); + } + } + let inputs = &slots[..count]; + let background = tile.background_image.as_deref().and_then(image); + + // Commands and saved projects keep the settings in range; the counts are guarded as they size the loops + let (columns, rows) = (tile.amount[0].clamp(1, *TileGenerator::AMOUNT.end()) as i32, tile.amount[1].clamp(1, *TileGenerator::AMOUNT.end()) as i32); let counts = Vec2::new(columns as f32, rows as f32); let point = Vec2::new(point.x.rem_euclid(1.0), point.y.rem_euclid(1.0)); let cell = (point - Vec2::from(tile.global_offset)) * counts; - let reach = reach(&tile, counts); + let reach = reach(tile, counts); let mut sum = 0.0f32; let mut colored = 0.0f32; @@ -311,30 +355,33 @@ pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32) -> f32 { // Lines (rows, or columns with a vertical offset) shift their tiles along them, so the tiles near the texel are found per line if tile.vertical_offset { for column in near(cell.x, reach.x, columns) { - for row in near(cell.y - line_shift(&tile, column), reach.y, rows) { - if let Some(value) = tile_value(&tile, seed, (column, row), (columns, rows), point) { + for row in near(cell.y - line_shift(tile, column), reach.y, rows) { + if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) { add(value); } } } } else { for row in near(cell.y, reach.y, rows) { - for column in near(cell.x - line_shift(&tile, row), reach.x, columns) { - if let Some(value) = tile_value(&tile, seed, (column, row), (columns, rows), point) { + for column in near(cell.x - line_shift(tile, row), reach.x, columns) { + if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) { add(value); } } } } - finish(&tile, sum, colored) + let background = background.map_or(tile.background, |image| gray(image.sample(point.x, point.y))); + finish(tile, sum, colored, background) } -/// The combined tiles over the background, through the pattern's opacity and its position/contrast window -fn finish(tile: &TileGenerator, sum: f32, colored: f32) -> f32 { +/// The combined tiles over `background`, through the pattern's opacity and its position/contrast window +fn finish(tile: &TileGenerator, sum: f32, colored: f32, background: f32) -> f32 { let alpha = sum.clamp(0.0, 1.0) * tile.opacity; let color = colored.clamp(0.0, 1.0) * tile.opacity; - let value = (tile.background * (1.0 - alpha) + color).clamp(0.0, 1.0); - window(value, tile.position, tile.contrast) + let value = (background * (1.0 - alpha) + color).clamp(0.0, 1.0); + let windowed = window(value, tile.position, tile.contrast); + // Out-of-range settings drawn as they are must not leave a non-number in the texture + if windowed.is_finite() { windowed } else { 0.0 } } /// The position/contrast window: position picks the input range stretched to 0..1 (0.5 keeps it), contrast narrows it around its middle @@ -346,6 +393,7 @@ fn window(value: f32, position: f32, contrast: f32) -> f32 { if half <= EPSILON { return f32::from(u8::from(value >= middle)); } + ((value - (middle - half)) / (2.0 * half)).clamp(0.0, 1.0) } @@ -354,7 +402,7 @@ mod tests { use super::*; fn at(tile: &TileGenerator, x: f32, y: f32) -> f32 { - value(tile, Vec2::new(x, y), 1) + value(tile, Vec2::new(x, y), 1, None) } /// Bell shapes peak only at their tile's center, so the brightest texel of a cell shows where its tile is @@ -393,6 +441,63 @@ mod tests { assert!(at(&turned, 0.5, 0.3) > at(&turned, 0.5, 0.7), "the bright side moved from the left to the top"); } + /// Whether a disc of a 2 × 1 grid's first tile, centered at (0.25, 0.5), covers the point `right` and `down` of its center + fn first_disc_covers(tile: &TileGenerator, right: f32, down: f32) -> bool { + at(tile, 0.25 + right, 0.5 + down) > 0.5 + } + + #[test] + fn each_size_mode_sizes_the_shape_its_own_way() { + let discs = TileGenerator { shape: TileShape::Disc, amount: [2, 1], ..TileGenerator::default() }; + assert!(first_disc_covers(&discs, 0.2, 0.0) && first_disc_covers(&discs, 0.0, 0.4), "without a gap the disc fills its 0.5 × 1 cell"); + + // Half the cell: 0.25 wide and 0.5 high, so the disc ends 0.125 right and 0.25 below its center + let halved = TileGenerator { size_mode: TileSizeMode::NormalSize, size: [0.5, 0.5], ..discs.clone() }; + assert!(first_disc_covers(&halved, 0.1, 0.0) && !first_disc_covers(&halved, 0.15, 0.0)); + assert!(first_disc_covers(&halved, 0.0, 0.2) && !first_disc_covers(&halved, 0.0, 0.3)); + + // The largest square of the cell is 0.5 wide and high, whatever the size is set to + let square = TileGenerator { size_mode: TileSizeMode::KeepRatio, ..halved.clone() }; + assert!(first_disc_covers(&square, 0.2, 0.0) && first_disc_covers(&square, 0.0, 0.2) && !first_disc_covers(&square, 0.0, 0.3)); + + // A fifth of the pattern: the disc ends 0.1 from its center, in a share of the pattern or in pixels of the 2048 reference + let absolute = TileGenerator { size_mode: TileSizeMode::Absolute, size_absolute: [0.2, 0.2], ..discs.clone() }; + let pixel = TileGenerator { size_mode: TileSizeMode::Pixel, size_pixel: [0.2 * PIXEL_REFERENCE; 2], ..discs.clone() }; + for sized in [&absolute, &pixel] { + assert!(first_disc_covers(sized, 0.08, 0.0) && !first_disc_covers(sized, 0.12, 0.0), "{:?}", sized.size_mode); + assert!(first_disc_covers(sized, 0.0, 0.08) && !first_disc_covers(sized, 0.0, 0.12), "{:?}", sized.size_mode); + } + } + + #[test] + fn size_randomness_shrinks_shapes_sized_absolutely_or_in_pixels_only() { + // Sixteen texels across each of the 4 × 4 cells: enough for the covered count to move when the discs shrink + const SAMPLES_PER_SIDE: usize = 64; + let center = |sample: usize| (sample as f32 + 0.5) / SAMPLES_PER_SIDE as f32; + let covered = |tile: &TileGenerator| { + (0..SAMPLES_PER_SIDE).flat_map(|y| (0..SAMPLES_PER_SIDE).map(move |x| (x, y))).filter(|(x, y)| at(tile, center(*x), center(*y)) > 0.5).count() + }; + let fifth = [0.2, 0.2]; + let discs = TileGenerator { + shape: TileShape::Disc, + amount: [4, 4], + size: [0.8, 0.8], + size_absolute: fifth, + size_pixel: fifth.map(|share| share * PIXEL_REFERENCE), + ..TileGenerator::default() + }; + let random = TileGenerator { size_random: [1.0, 1.0], ..discs.clone() }; + + for mode in [TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio] { + let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() }); + assert_eq!(covered(&plain), covered(&random), "{mode:?} ignores the size randomness"); + } + for mode in [TileSizeMode::Absolute, TileSizeMode::Pixel] { + let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() }); + assert!(covered(&random) < covered(&plain), "{mode:?}: random sizes shrink the discs"); + } + } + #[test] fn masks_hide_their_rows_columns_and_checkers() { let checker = TileGenerator { checker_mask: true, ..bells([2, 2]) }; @@ -427,6 +532,47 @@ mod tests { } } + /// An image `size` texels wide whose left half is `left` and right half `right` + fn halves(left: f32, right: f32) -> std::sync::Arc { + let size = 8; + let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect(); + std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false }) + } + + #[test] + fn the_image_shape_draws_its_inputs_in_turn_by_pattern_number() { + let images: ImageStore = [("dark".to_string(), halves(0.2, 0.2)), ("bright".to_string(), halves(0.9, 0.9))].into(); + let tile = TileGenerator { + shape: TileShape::Image, + amount: [2, 1], + inputs: vec!["dark".into(), "bright".into()], + input_distribution: TileInputDistribution::ByNumber, + ..TileGenerator::default() + }; + // Tile 0 (left) draws the first input, tile 1 the second + let left = value(&tile, Vec2::new(0.25, 0.5), 1, Some(&images)); + let right = value(&tile, Vec2::new(0.75, 0.5), 1, Some(&images)); + assert!((left - 0.2).abs() < 0.01 && (right - 0.9).abs() < 0.01, "{left} {right}"); + assert_eq!(value(&tile, Vec2::new(0.25, 0.5), 1, None), 0.0, "missing images draw nothing"); + } + + #[test] + fn an_image_input_keeps_its_orientation_in_the_tile() { + let images: ImageStore = [("halves".to_string(), halves(0.0, 1.0))].into(); + let tile = TileGenerator { shape: TileShape::Image, amount: [1, 1], inputs: vec!["halves".into()], ..TileGenerator::default() }; + assert!(value(&tile, Vec2::new(0.3, 0.5), 1, Some(&images)) < 0.05, "the image's left half is on the tile's left"); + assert!(value(&tile, Vec2::new(0.7, 0.5), 1, Some(&images)) > 0.95); + } + + #[test] + fn the_background_image_shows_between_the_shapes() { + let images: ImageStore = [("ground".to_string(), halves(0.4, 0.4))].into(); + let tile = TileGenerator { background_image: Some("ground".into()), interstice: [0.5, 0.5], ..bells([2, 2]) }; + // Between the bells only the background is left + assert!((value(&tile, Vec2::new(0.0, 0.0), 1, Some(&images)) - 0.4).abs() < 0.01); + assert_eq!(value(&tile, Vec2::new(0.0, 0.0), 1, None), 0.0, "without the image the background value stays"); + } + #[test] fn hostile_settings_neither_crash_nor_leave_the_range() { let hostile = TileGenerator { diff --git a/crates/compose/src/tile_random_stream.rs b/crates/compose/src/tile_random_stream.rs index 9a79d49a..cf719ea5 100644 --- a/crates/compose/src/tile_random_stream.rs +++ b/crates/compose/src/tile_random_stream.rs @@ -18,6 +18,7 @@ pub(crate) enum TileRandomStream { SizeY, IntersticeX, IntersticeY, + Input, } /// Odd multipliers spreading the seed, the stream and the index over the hash, and its start (the golden ratio's and xxHash32's primes) diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index ead117eb..f58b9ea4 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -742,6 +742,46 @@ fn a_live_stroke_releases_the_fields_kept_before_it_started() { assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs"); } +#[test] +fn cached_stack_tracks_the_images_a_tile_generator_reads() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; + let mut pattern = Procedural::new(ProceduralKind::TileGenerator); + pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into()); + fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }); + + let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: 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, background) in [("cold", None), ("added", Some(1.0)), ("replaced", Some(0.4))] { + if let Some(value) = background { + images.insert("plate".into(), image_with_value(value)); + } + + fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} + #[test] fn cached_stack_tracks_referenced_images_only() { use std::sync::Arc; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index cb970042..b61a74bd 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -589,7 +589,7 @@ impl Session { let uses_added_resource = |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill, Source}; - let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name)); + let uses_source = |source: &Source| source.images().into_iter().any(|name| added_resource_names.iter().any(|added| added.as_str() == name)); let uses_fill = |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); let project = &self.doc.project; diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs index 5394162a..30270b65 100644 --- a/crates/engine/tests/it/tile_generator.rs +++ b/crates/engine/tests/it/tile_generator.rs @@ -135,6 +135,10 @@ fn a_mask_fill_picks_and_edits_a_pattern_with_effect_set() { // A value takes the mask fill back from the pattern only through a uniform source pick, so a stray value is ignored as before execute(&mut session, "effect.set", &json!({"effect": effect, "value": 0.3})).unwrap(); assert_eq!(mask_pattern(&session, effect).kind, ProceduralKind::TileGenerator); + + execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3})).unwrap(); + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "a uniform pick reads the value again"); } #[test] @@ -185,3 +189,49 @@ fn removing_unused_resources_keeps_the_images_a_tile_generator_reads() { assert!(session.doc.resources.contains_key(&background), "the background image is still read"); assert!(!session.doc.resources.contains_key(&unused)); } + +/// The composited base color of every texel of the texture set +fn base_colors(session: &mut Session) -> Vec { + session.update(); + let composite = &session.caches[0].composite; + let size = composite.resolution; + (0..size * size).map(|texel| composite.value(Channel::BaseColor, texel % size, texel / size)[0]).collect() +} + +#[test] +fn the_compositor_draws_a_tile_generators_image_input() { + let mut session = session(); + let input = import_gray(&mut session, "plate.png"); + tile_fill(&mut session); + // One tile with no gap: the image covers the whole texture + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}})).unwrap(); + + let colors = base_colors(&mut session); + let mid_gray = colors.iter().filter(|value| (**value - 0.5).abs() < 0.05).count(); + assert!(mid_gray > colors.len() / 2, "the image's gray reaches the texture, not an empty shape: {mid_gray} of {}", colors.len()); +} + +#[test] +fn importing_the_image_a_tile_generator_names_redraws_it() { + let mut session = session(); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": ["plate.png"], "amount": [1, 1]}})).unwrap(); + let before = base_colors(&mut session); + + assert_eq!(import_gray(&mut session, "plate.png"), "plate.png"); + let after = base_colors(&mut session); + + assert_ne!(before, after, "the image that arrived later reaches the texture"); +} + +#[test] +fn a_coarser_pattern_resolution_changes_the_composite() { + let mut session = session(); + tile_fill(&mut session); + let exact = base_colors(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolutionFactor": -3})).unwrap(); + let coarse = base_colors(&mut session); + let changed = exact.iter().zip(&coarse).filter(|(exact, coarse)| (**exact - **coarse).abs() > 0.05).count(); + assert!(changed > 0, "an eighth of the resolution blurs the bricks' bevels"); +} From d858fdba3635c749f96f3bc48c330927d7d6749d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:45:26 +0000 Subject: [PATCH 5/9] Pattern edits take the seed with tile settings, a uniform pick outranks them, gray rows take a typed value, the output size follows the UV tiles --- crates/compose/src/tile_random_stream.rs | 32 +++++++++++++ crates/engine/src/layer_cmds.rs | 1 + crates/engine/src/mask_cmds.rs | 6 ++- crates/engine/tests/it/tile_generator.rs | 24 ++++++++++ crates/ui-egui/src/gray_slider.rs | 13 +++--- crates/ui-egui/src/pattern_panel.rs | 8 ++-- crates/ui-egui/src/resource_panel.rs | 38 +++++++++++++++- crates/ui-egui/src/widgets.rs | 11 ++++- .../ui-egui/tests/it/tile_generator_panel.rs | 45 ++++++++++++++++++- 9 files changed, 162 insertions(+), 16 deletions(-) diff --git a/crates/compose/src/tile_random_stream.rs b/crates/compose/src/tile_random_stream.rs index cf719ea5..57b0236b 100644 --- a/crates/compose/src/tile_random_stream.rs +++ b/crates/compose/src/tile_random_stream.rs @@ -51,3 +51,35 @@ impl TileRandomStream { (hash >> (u32::BITS - DRAW_BITS)) as f32 / (1u32 << DRAW_BITS) as f32 } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A draw keeps 24 bits, so `bits / 2^24` is the value exactly + fn exact(bits: u32) -> f32 { + bits as f32 / (1u32 << DRAW_BITS) as f32 + } + + /// Saved projects keep only the seed and the settings, so a changed draw would move the tiles of existing textures + #[test] + fn draws_stay_the_values_saved_projects_were_made_with() { + assert_eq!(TileRandomStream::Luminance.draw(0, 0), exact(6_969_297)); + assert_eq!(TileRandomStream::Rotation.draw(1, 7), exact(11_123_133)); + assert_eq!(TileRandomStream::Input.draw(u32::MAX, u32::MAX), exact(6_943_220)); + } + + #[test] + fn draws_are_below_one_and_differ_by_seed_stream_and_index() { + let first = TileRandomStream::Scale.draw(3, 5); + + assert_eq!(first, TileRandomStream::Scale.draw(3, 5), "the same seed, stream and index draw the same value"); + assert_ne!(first, TileRandomStream::Scale.draw(4, 5)); + assert_ne!(first, TileRandomStream::Offset.draw(3, 5)); + assert_ne!(first, TileRandomStream::Scale.draw(3, 6)); + for index in 0..1000 { + let value = TileRandomStream::Mask.draw(index, index); + assert!((0.0..1.0).contains(&value), "draw {index} is {value}"); + } + } +} diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 5a6074fd..82d92e5e 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -425,6 +425,7 @@ fn fill_source_from( return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings")); }; + crate::procedural_params::pattern_basics_from(params, &mut pattern); crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; Ok(Some(Source::Procedural { pattern, low, high })) } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 63af43e3..e2f3844c 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -669,14 +669,16 @@ fn set(session: &mut Session, params: &Value) -> Result { EffectKind::Filter(_) if swaps_filter => {} EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, EffectKind::Fill { source, projection } => { + // `uniform` picks the source, so it outranks settings that would edit the current pattern + let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); if let Some(anchor) = anchor { *source = anchor; } else if let Some(image) = image { *source = image; + } else if let Some(value) = uniform { + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } else if let Some(pattern) = fill_pattern(CMD, params, source)? { *source = pattern; - } else if let Some(value) = f32p(params, "uniform") { - *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. } | Source::Image { .. }) { diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs index 30270b65..152700ae 100644 --- a/crates/engine/tests/it/tile_generator.rs +++ b/crates/engine/tests/it/tile_generator.rs @@ -64,6 +64,18 @@ fn tile_settings_alone_edit_the_channels_pattern() { assert_eq!(tile.specific, TileGenerator::default().specific, "settings not named keep their value"); } +#[test] +fn tile_settings_with_a_seed_edit_both() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "seed": 9, "invert": true})).unwrap(); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(tile(&pattern).amount, [3, 3]); + assert_eq!((pattern.seed, pattern.invert), (9, true), "the seed and invert beside a tile setting are applied, not dropped"); +} + #[test] fn picking_the_tile_generator_again_keeps_its_settings() { let mut session = session(); @@ -141,6 +153,18 @@ fn a_mask_fill_picks_and_edits_a_pattern_with_effect_set() { assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "a uniform pick reads the value again"); } +#[test] +fn a_uniform_pick_outranks_pattern_edits_on_a_mask_fill() { + let mut session = session(); + let effect = mask_fill(&mut session); + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3, "seed": 4})).unwrap(); + + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "the fill reads the value, not the pattern"); +} + #[test] fn a_mask_fill_added_with_tile_settings_keeps_them() { let mut session = session(); diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs index 9034cc49..0ea4dfd2 100644 --- a/crates/ui-egui/src/gray_slider.rs +++ b/crates/ui-egui/src/gray_slider.rs @@ -5,6 +5,7 @@ use egui_phosphor::regular as ic; use crate::i18n::tr; use crate::theme::Tokens; +use crate::widgets::value_header; const BAR_HEIGHT: f32 = 8.0; const BAR_ROUNDING: f32 = 2.0; @@ -17,16 +18,18 @@ const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0; /// `label` and `value` over a black-to-white bar and an Invert value button: `Some(merge)` on every frame that changes it, as [`crate::widgets::slider_edit`] pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option { let tokens = Tokens::get(ui.ctx()); + let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2); ui.horizontal(|ui| { - ui.label(label); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(format!("{value:.2}"))); - }); - ui.horizontal(|ui| { - let mut edit = None; + let mut edit = typed; let button_width = ui.spacing().interact_size.y; let width = (ui.available_width() - button_width - ui.spacing().item_spacing.x).max(MIN_BAR_WIDTH); let (rect, response) = ui.allocate_exact_size(vec2(width, KNOB_RADIUS * 2.0 + KNOB_STROKE * 2.0), Sense::click_and_drag()); let bar = Rect::from_center_size(rect.center(), vec2(rect.width() - KNOB_RADIUS * 2.0, BAR_HEIGHT)); + if response.is_pointer_button_down_on() { + // A grab of the bar ends typing, so the field shows the dragged value + ui.data_mut(|data| data.remove_temp::(field)); + ui.memory_mut(|memory| memory.surrender_focus(field)); + } if let Some(pointer) = response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) { *value = ((pointer.x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); edit = Some(response.dragged() && !response.drag_started()); diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs index 6fb277b3..19801e65 100644 --- a/crates/ui-egui/src/pattern_panel.rs +++ b/crates/ui-egui/src/pattern_panel.rs @@ -11,7 +11,7 @@ use crate::TextureCraftApp; use crate::dock::{image_drop, image_menu}; use crate::i18n::{tr, trf}; use crate::pattern_target::PatternTarget; -use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; +use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, output_size_label, random_seed}; use crate::theme::Tokens; use crate::tile_edits::TileEdits; use crate::widgets::{combo, section, slider_edit}; @@ -108,11 +108,11 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pa }) .on_hover_text(tr("Scales the base resolution: below 1 the pattern is drawn coarser and smoothed back up.")); - let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.resolution) else { return }; - let size = current.output_size(texture_set, texture_set); + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; + let size_label = output_size_label(¤t, texture_set); 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(format!("{size} × {size}"))); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); }); } diff --git a/crates/ui-egui/src/resource_panel.rs b/crates/ui-egui/src/resource_panel.rs index d4716d38..987899bc 100644 --- a/crates/ui-egui/src/resource_panel.rs +++ b/crates/ui-egui/src/resource_panel.rs @@ -1,6 +1,6 @@ -//! What the generator and pattern panels share: the attribute rows' key width, note size, the resolution factor's label and a random seed +//! What the generator and pattern panels share: the attribute rows' key width, note size, the resolution factor's label, the output size readout and a random seed -use texturecraft_engine::core::OutputResolution; +use texturecraft_engine::core::{OutputResolution, TextureSet}; use crate::i18n::tr; @@ -25,9 +25,43 @@ pub(crate) fn factor_label(factor: i8) -> String { } } +/// The output size `resolution` gives in `texture_set`: one size, or the smallest and largest when its UV tiles differ +pub(crate) fn output_size_label(resolution: &OutputResolution, texture_set: &TextureSet) -> String { + let sizes = || texture_set.uv_tiles.iter().map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)); + let whole_set = resolution.output_size(texture_set.resolution, texture_set.resolution); + let (smallest, largest) = (sizes().min().unwrap_or(whole_set), sizes().max().unwrap_or(whole_set)); + if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") } +} + /// A seed different from `current`, from the clock pub(crate) fn random_seed(current: u32) -> u32 { let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } } + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::ResolutionMode; + + use super::*; + + #[test] + fn the_output_size_follows_each_uv_tile() { + let mut set = TextureSet::new("Tiles", 0, 1024); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 256); + let per_tile = OutputResolution::default(); + let whole_set = OutputResolution { mode: ResolutionMode::TextureSet, ..per_tile }; + + assert_eq!(output_size_label(&per_tile, &set), "256–1024 × 256–1024", "tiles of different sizes show the smallest and the largest"); + assert_eq!(output_size_label(&whole_set, &set), "1024 × 1024", "the texture set's size is the same for every tile"); + } + + #[test] + fn a_set_without_uv_tiles_shows_its_own_size() { + let set = TextureSet::new("Plain", 0, 512); + + assert_eq!(output_size_label(&OutputResolution::default(), &set), "512 × 512"); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index bdf0bb7a..e549431e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -29,10 +29,10 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R slider_inner(ui, label, value, range, decimals).1 } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { +/// 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) { let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); - let width = ui.available_width(); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() @@ -78,6 +78,13 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang .inner }) .inner; + (field, edit) +} + +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) = value_header(ui, label, value, range, decimals); let (rect, mut response) = ui.allocate_exact_size(vec2(width, 14.0), 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/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 3ac4e60d..fe762b66 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -2,7 +2,7 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use serde_json::json; use texturecraft_engine::core::{EffectKind, LayerId, Procedural, ProceduralKind, Source, TileGenerator}; use texturecraft_engine::{ViewMode, execute}; @@ -154,6 +154,42 @@ fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { assert_eq!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); } +/// The gray rows take a typed value, so they can be set without a pointer +#[test] +fn a_gray_value_typed_in_its_field_applies() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + // A section's title can also be a control's label above it: the title is the last one + harness.get_all_by_label("Color").last().unwrap().scroll_to_me(); + harness.run_steps(12); + harness.get_all_by_label("Color").last().unwrap().click(); + harness.run_steps(6); + harness.get_by_label("Background").scroll_to_me(); + harness.run_steps(12); + let field = |harness: &Harness<'_, TextureCraftApp>| { + let row = harness.get_by_label("Background").rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center() + }; + + let at = field(&harness); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + for key in [egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace] { + harness.key_press(key); + harness.run_steps(1); + } + for character in "0.5".chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(pattern(&harness, effect).tile.unwrap().background, 0.5); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn tile_generator_snapshots() { @@ -181,6 +217,13 @@ fn tile_generator_snapshots() { } harness.state_mut().ui.prefs.brightness = Brightness::Dark; + // Open, the section also holds a menu labelled "Resolution": its title is the first one + harness.get_by_label("Resolution").click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("tile-resolution.png")).unwrap(); + harness.get_all_by_label("Resolution").next().unwrap().click(); + harness.run_steps(6); + for (sections, name) in [(["Pattern", "Size"], "pattern-size"), (["Position", "Rotation"], "position-rotation")] { for section in sections { // A section's title can also be a control's label above it ("Position"): the title is the last one From 7ceb03a52ebc84f6ef395d0f364c9eca0e97f845 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:38:48 +0000 Subject: [PATCH 6/9] The source picker offers images to mask fills, and a pattern's scale leaves the fill's projection alone --- crates/engine/src/mask_cmds.rs | 12 ++++- crates/engine/tests/it/tile_generator.rs | 19 +++++++- crates/ui-egui/src/dock.rs | 1 - crates/ui-egui/src/fill_source_slot.rs | 44 ++++++++++--------- crates/ui-egui/tests/it/fill_channel_image.rs | 17 +++---- .../ui-egui/tests/it/tile_generator_panel.rs | 11 +++++ 6 files changed, 71 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e2f3844c..ed93fa6f 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, 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), 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), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, 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), 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?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -685,8 +685,16 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } + // While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone + let mut placement = params.clone(); + if matches!(source, Source::Procedural { .. }) + && let Some(fields) = placement.as_object_mut() + { + fields.remove("scale"); + } + // Preserve projection fields that the edit does not supply - *projection = projection_from(params, CMD, Some(&*projection))?; + *projection = projection_from(&placement, CMD, Some(&*projection))?; } EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, EffectKind::Compare { tolerance, .. } => { diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs index 152700ae..bdfef7a1 100644 --- a/crates/engine/tests/it/tile_generator.rs +++ b/crates/engine/tests/it/tile_generator.rs @@ -1,7 +1,9 @@ //! The Tile Generator pattern and pattern resolutions through engine commands use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind, Procedural, ProceduralKind, ResolutionMode, Source, TileGenerator, TileShape}; +use texturecraft_engine::core::{ + Channel, EffectKind, LayerId, LayerKind, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileGenerator, TileShape, +}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -165,6 +167,21 @@ fn a_uniform_pick_outranks_pattern_edits_on_a_mask_fill() { assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "the fill reads the value, not the pattern"); } +/// A fill effect's `scale` is also its projection's: while it reads a pattern, the pattern takes it +#[test] +fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() { + let mut session = session(); + let effect = mask_fill(&mut session); + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap(); + + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &edited.kind else { panic!("the fill reads a pattern") }; + assert_eq!(pattern.scale, 3.0); + assert_eq!(*projection, Projection::default(), "the projection keeps its scale"); +} + #[test] fn a_mask_fill_added_with_tile_settings_keeps_them() { let mut session = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 63877e2e..6f21b035 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2654,7 +2654,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe Source::Image { .. } => { projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); } - _ => {} } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs index ba8ff6dc..2f7b0beb 100644 --- a/crates/ui-egui/src/fill_source_slot.rs +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -52,8 +52,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarg return; } - let images = matches!(fill, FillSourceTarget::Channel { .. }); - let tiles = tiles(app, &ctx, images); + let tiles = tiles(app, &ctx); let anchors: Vec = anchors .iter() .map(|(anchor, name)| ResourcePickerAnchor { @@ -127,8 +126,8 @@ fn current_key(source: &Source) -> Option { } } -/// The Resources tab: the patterns, the project's images (`images`) and a uniform value -fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context, images: bool) -> Vec> { +/// The Resources tab: the patterns, the project's images and a uniform value +fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context) -> Vec> { let mut tiles: Vec> = ProceduralKind::ALL .into_iter() .map(|kind| ResourcePickerTile { @@ -139,20 +138,18 @@ fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context, images: bool) -> Vec)> = app.session.images.iter().map(|(name, image)| (name.clone(), image.clone())).collect(); - names.sort_by(|a, b| a.0.cmp(&b.0)); - for (name, image) in names { - let thumbnail = Some(app.thumbs.image(ctx, &name, &image)); - let preview_name = name.clone(); - tiles.push(ResourcePickerTile { - key: format!("{IMAGE_PREFIX}{name}"), - label: name, - group: tr("Images"), - thumbnail, - preview: Box::new(move || ShelfPreview::Image(preview_name.clone(), image.clone())), - }); - } + let mut names: Vec<(String, Arc)> = app.session.images.iter().map(|(name, image)| (name.clone(), image.clone())).collect(); + names.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, image) in names { + let thumbnail = Some(app.thumbs.image(ctx, &name, &image)); + let preview_name = name.clone(); + tiles.push(ResourcePickerTile { + key: format!("{IMAGE_PREFIX}{name}"), + label: name, + group: tr("Images"), + thumbnail, + preview: Box::new(move || ShelfPreview::Image(preview_name.clone(), image.clone())), + }); } tiles.push(ResourcePickerTile { key: UNIFORM_KEY.to_string(), @@ -171,9 +168,14 @@ fn pick_resource(app: &mut TextureCraftApp, fill: &FillSourceTarget, key: &str) (FillSourceTarget::Mask { effect }, Some(kind)) => { app.run("effect.set", json!({"effect": effect, "procedural": kind.label()})); } - (FillSourceTarget::Mask { effect }, None) => { - app.run("effect.set", json!({"effect": effect, "uniform": 1.0})); - } + (FillSourceTarget::Mask { effect }, None) => match key.strip_prefix(IMAGE_PREFIX) { + Some(name) => { + app.run("effect.set", json!({"effect": effect, "image": name})); + } + None => { + app.run("effect.set", json!({"effect": effect, "uniform": 1.0})); + } + }, (FillSourceTarget::Channel { base, channel }, Some(kind)) => { let (low, high) = pattern_range(*channel); app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "procedural": kind.label(), "low": low, "high": high}))); diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index 591f9baa..b03a4440 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -126,11 +126,12 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + // The mask fill's slot opens the source picker + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").scroll_to_me(); harness.run_steps(30); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label(&image_name).click(); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, &image_name).click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; @@ -144,10 +145,10 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); - let image_label = format!("Image: {image_name}"); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some(image_label.as_str())).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Uniform value").click(); + assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Uniform value").click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index fe762b66..37c8f2fc 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -248,4 +248,15 @@ fn tile_generator_snapshots() { harness.state_mut().session.update(); settle(&mut harness); harness.render().unwrap().save(directory.join("tile-adjusted.png")).unwrap(); + + // An image as the mask fill's source: the slot names it over its projection + let mut png_bytes = Vec::new(); + image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([if (x + y) % 2 == 0 { 230 } else { 40 }; 4])) + .write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png) + .unwrap(); + let name = harness.state_mut().session.import_resource_bytes("checks.png", png_bytes).unwrap(); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "image": name})).unwrap(); + harness.state_mut().session.update(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("mask-fill-image.png")).unwrap(); } From 7d1573d49179ef9b9a2d555c3f660a661fb7cc6c Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 01:17:09 +0000 Subject: [PATCH 7/9] Auto: Fix tile rendering, panel edits, and localized test harnesses Respect per-UV-tile resolution when reducing procedural patterns. Cover rotated tiles across repeat boundaries without counting overlapping copies more than once. Preserve both contrast and invert edits when committed together, with regression coverage. Pin tile-panel tests to English and allow missing glyphs in the image-menu preview-cache harness. --- crates/compose/src/eval.rs | 40 +++++++++- crates/compose/src/tile_pattern.rs | 78 ++++++++++++++++--- crates/ui-egui/src/dock.rs | 4 +- crates/ui-egui/src/pattern_panel.rs | 5 +- .../ui-egui/tests/it/tile_generator_panel.rs | 32 ++++++++ 5 files changed, 144 insertions(+), 15 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 43bd814c..8f779281 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -119,6 +119,11 @@ impl Inputs<'_> { fn tile_res(&self) -> u32 { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } + + /// The current UV tile can occupy only part of its atlas block + fn tile_res_at(&self, x: u32, y: u32) -> u32 { + ((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1) + } } /// The composited channels of one texture set. @@ -1425,7 +1430,7 @@ impl<'a, 'b> Texel<'a, 'b> { Source::Procedural { pattern, low, high } => { let (coords, projection, _) = self.projected(projection); let pixels = if pattern.resolution.can_reduce() { - let uv_tile = self.inp.tile_res(); + let uv_tile = self.inp.tile_res_at(self.x, self.y); let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); pattern_pixels(pattern, uv_tile, texture_set) } else { @@ -2709,6 +2714,39 @@ mod tests { out } + #[test] + fn procedural_resolution_uses_each_uv_tiles_scale() { + let mut fixture = fixture(); + let set = &mut fixture.project.texture_sets[0]; + set.uv_tiles = vec![1001, 1002]; + set.resolution = 64; + set.tile_resolutions.insert(1002, 32); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 64); + let block_scales = set.block_scales(); + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales, + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + + assert_eq!(inputs.tile_res_at(0, 0), 64); + assert_eq!(inputs.tile_res_at(64, 0), 32); + + let mut pattern = Procedural::new(ProceduralKind::Checker); + pattern.resolution.factor = -1; + + assert_eq!(pattern_pixels(&pattern, inputs.tile_res_at(0, 0), 64), Some(32)); + assert_eq!(pattern_pixels(&pattern, inputs.tile_res_at(64, 0), 64), Some(16)); + } + fn fill_layer(p: &mut Project, color: [f32; 3], rough: f32) -> LayerId { let id = p.alloc_id(); let mut fill = Fill::default(); diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs index 41a3aea7..c756072f 100644 --- a/crates/compose/src/tile_pattern.rs +++ b/crates/compose/src/tile_pattern.rs @@ -28,6 +28,8 @@ const WAVES_BASE_CYCLES: f32 = 1.5; const WAVES_SPECIFIC_CYCLES: f32 = 6.0; /// Narrower than this, a size or a bevel is none const EPSILON: f32 = 1e-6; +/// Valid tile settings reach at most three neighboring copies along an axis +const MAX_PERIODIC_COPY: f32 = 3.0; fn smoothstep(t: f32) -> f32 { let t = t.clamp(0.0, 1.0); @@ -211,24 +213,45 @@ fn tile_value( let delta = Vec2::new(wrap(point.x - center.x, 1.0), wrap(point.y - center.y, 1.0)); let turns = (tile.rotation + tile.rotation_random * TileRandomStream::Rotation.draw(seed, index) * 360.0) / 360.0; - let mut local = unrotate(delta, turns) * 2.0 / size; - for _ in 0..quarter_turns(tile, seed, (column, row), index) { - local = Vec2::new(local.y, -local.x); - } + let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos(); + let radius = Vec2::new(cos.abs() * size.x + sin.abs() * size.y, sin.abs() * size.x + cos.abs() * size.y) * 0.5; + let first = (-radius - delta).ceil().max(Vec2::splat(-MAX_PERIODIC_COPY)); + let last = (radius - delta).floor().min(Vec2::splat(MAX_PERIODIC_COPY)); + let quarter_turns = quarter_turns(tile, seed, (column, row), index); let mirrors = tile.symmetry_random * 0.5; - if tile.symmetry != TileSymmetry::Vertical && TileRandomStream::MirrorX.draw(seed, index) < mirrors { - local.x = -local.x; - } - if tile.symmetry != TileSymmetry::Horizontal && TileRandomStream::MirrorY.draw(seed, index) < mirrors { - local.y = -local.y; - } + let mirror_x = tile.symmetry != TileSymmetry::Vertical && TileRandomStream::MirrorX.draw(seed, index) < mirrors; + let mirror_y = tile.symmetry != TileSymmetry::Horizontal && TileRandomStream::MirrorY.draw(seed, index) < mirrors; let input = match tile.input_distribution { _ if inputs.is_empty() => None, TileInputDistribution::Random => inputs.get((TileRandomStream::Input.draw(seed, index) * inputs.len() as f32) as usize).copied().flatten(), TileInputDistribution::ByNumber => inputs.get(number as usize % inputs.len()).copied().flatten(), }; - let value = pattern(tile, local, input); + let mut value = 0.0f32; + // A rotated shape may cross a repeat boundary even when the nearest copy misses it + for copy_y in first.y as i32..=last.y as i32 { + let y = delta.y + copy_y as f32; + if y.abs() > radius.y { + continue; + } + for copy_x in first.x as i32..=last.x as i32 { + let x = delta.x + copy_x as f32; + if x.abs() > radius.x { + continue; + } + let mut local = Vec2::new(cos * x + sin * y, -sin * x + cos * y) * 2.0 / size; + for _ in 0..quarter_turns { + local = Vec2::new(local.y, -local.x); + } + if mirror_x { + local.x = -local.x; + } + if mirror_y { + local.y = -local.y; + } + value = value.max(pattern(tile, local, input)); + } + } if value <= 0.0 { return None; } @@ -410,6 +433,39 @@ mod tests { value(tile, Vec2::new(x, y), 1, None) } + #[test] + fn rotated_tiles_cover_the_repeat_boundary_once() { + let tile = TileGenerator { + shape: TileShape::Square, + amount: [1, 1], + size_mode: TileSizeMode::NormalSize, + size: [1.0, 0.1], + scale: 2.0, + rotation: 45.0, + blending: TileBlending::Add, + ..TileGenerator::default() + }; + + assert!(at(&tile, 0.99, 0.01) > 0.99); + assert!(at(&tile, 0.99, 0.01) <= 1.0); + } + + #[test] + fn overlapping_periodic_copies_contribute_one_tile_value() { + let tile = TileGenerator { + shape: TileShape::Square, + amount: [1, 1], + size_mode: TileSizeMode::NormalSize, + size: [1.0, 1.0], + scale: 2.0, + color: 0.4, + blending: TileBlending::Add, + ..TileGenerator::default() + }; + + assert!((at(&tile, 0.5, 0.5) - 0.4).abs() < EPSILON); + } + /// Bell shapes peak only at their tile's center, so the brightest texel of a cell shows where its tile is fn bells(amount: [u32; 2]) -> TileGenerator { TileGenerator { shape: TileShape::Bell, amount, ..TileGenerator::default() } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 5fb007be..7d308129 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1398,7 +1398,9 @@ mod image_menu_tests { let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); let app = TextureCraftApp::new(&creation_context, session); - Ok(Harness::builder().with_size(egui::vec2(320.0, 400.0)).with_context_setup(crate::theme::install).build_ui_state( + + // Translated menu labels may need fonts this preview-cache test does not load + Ok(Harness::builder().with_size(egui::vec2(320.0, 400.0)).with_context_setup(crate::theme::install).allow_missing_glyphs().build_ui_state( |ui, (app, picked)| { if let Some(name) = image_menu(app, ui) { *picked = Some(name); diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs index 507ed52c..7afe7662 100644 --- a/crates/ui-egui/src/pattern_panel.rs +++ b/crates/ui-egui/src/pattern_panel.rs @@ -174,7 +174,7 @@ fn tile_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarge let mut edits = TileEdits::default(); let mut invert = pattern.invert; if ui.checkbox(&mut invert, tr("Invert")).changed() { - send(app, target, &Procedural { invert, ..pattern.clone() }, json!({})); + edits.merge = Some(false); } edits.slider(ui, tr("Position"), "position", tile.position, 0.0..=1.0); edits.slider(ui, tr("Contrast"), "contrast", tile.contrast, 0.0..=1.0); @@ -205,7 +205,8 @@ fn tile_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarge }); if let Some(merge) = edits.merge { - send(app, target, pattern, json!({"tile": Value::Object(edits.settings), "merge": merge})); + let edited = (invert != pattern.invert).then(|| Procedural { invert, ..pattern.clone() }); + send(app, target, edited.as_ref().unwrap_or(pattern), json!({"tile": Value::Object(edits.settings), "merge": merge})); } } diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index d9a9ee95..40bfaa04 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -25,6 +25,7 @@ fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); let builder = if render { builder.wgpu() } else { builder }; let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.close(Panel::Layers); harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.state_mut().ui.dock.focus(Panel::Properties); @@ -129,6 +130,7 @@ fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { execute(&mut session, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); session.update(); let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.dock.focus(Panel::Properties); harness.run_steps(6); @@ -193,6 +195,36 @@ fn a_gray_value_typed_in_its_field_applies() { assert_eq!(pattern(&harness, effect).tile.unwrap().background, 0.5); } +#[test] +fn typing_tile_contrast_then_clicking_invert_preserves_both_edits() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + let contrast = harness.get_by_label("Contrast"); + contrast.scroll_to_me(); + harness.run_steps(12); + let row = harness.get_by_label("Contrast").rect().center().y; + let at = harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center(); + + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + for key in [egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace] { + harness.key_press(key); + harness.run_steps(1); + } + for character in "0.5".chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + harness.get_by_label("Invert").click(); + harness.run_steps(3); + + let edited = pattern(&harness, effect); + assert_eq!(edited.tile.unwrap().contrast, 0.5); + assert!(edited.invert); +} + #[test] #[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] fn tile_generator_snapshots() { From 0611d461d99a1f17d29ffbc0890898cdda1f5a2f Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 01:43:10 +0000 Subject: [PATCH 8/9] Auto: Remove anchor preview visibility test and waiting helper Delete source_picker_renders_only_visible_anchors and the associated settle_anchor_previews helper from the fill-source picker tests. --- crates/ui-egui/src/fill_source_slot.rs | 56 -------------------------- 1 file changed, 56 deletions(-) diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs index 598ac41f..a87ecc9d 100644 --- a/crates/ui-egui/src/fill_source_slot.rs +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -241,22 +241,6 @@ mod tests { context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-image-")).count() } - fn settle_anchor_previews(harness: &mut Harness<'_, (TextureCraftApp, Vec<(LayerId, String)>)>) { - // Allow the worker to finish on a busy machine - const ATTEMPTS: usize = 500; - const WAIT: std::time::Duration = std::time::Duration::from_millis(10); - for _ in 0..ATTEMPTS { - if !harness.state().0.layer_panel.service().busy() { - return; - } - - std::thread::sleep(WAIT); - harness.run_steps(2); - } - - assert!(!harness.state().0.layer_panel.service().busy(), "the anchor preview queue should settle"); - } - #[test] fn source_picker_images_render_on_scroll_and_release_on_removal() { const IMAGE_COUNT: usize = 128; @@ -297,46 +281,6 @@ mod tests { eprintln!("picker image previews: initial {initial_previews}, after scroll {scrolled_previews}, after removal 0"); } - #[test] - fn source_picker_renders_only_visible_anchors() { - const ANCHOR_COUNT: usize = 128; - let mut session = Session::new_project("picker", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); - execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(); - let mut anchors = Vec::new(); - for index in 0..ANCHOR_COUNT { - let name = format!("anchor-{index:03}"); - let result = execute(&mut session, "effect.add.anchor", &json!({"name": name})).unwrap(); - anchors.push((LayerId(result["effect"].as_u64().unwrap()), name)); - } - execute(&mut session, "layer.add.fill", &json!({"height": 0.0})).unwrap(); - let mut harness = picker_harness(session, anchors); - - harness.get_by_role_and_label(egui::Role::ComboBox, "Source").click(); - harness.run_steps(3); - settle_anchor_previews(&mut harness); - let service = harness.state().0.layer_panel.service(); - eprintln!("hidden anchor previews: rendered {}, retained {}", service.rendered, service.cached()); - - assert_eq!(service.rendered, 0, "the hidden Anchor points tab must not render its targets"); - assert_eq!(service.cached(), 0); - - harness.get_by_role_and_label(egui::Role::Tab, "Anchor points").click(); - harness.run_steps(3); - settle_anchor_previews(&mut harness); - let initial_previews = harness.state().0.layer_panel.service().rendered; - - assert!(initial_previews > 0 && initial_previews < ANCHOR_COUNT as u64); - assert_eq!(harness.state().0.layer_panel.service().cached() as u64, initial_previews); - - harness.get_by_role_and_label(egui::Role::Button, "anchor-100").scroll_to_me(); - harness.run_steps(30); - settle_anchor_previews(&mut harness); - let scrolled_previews = harness.state().0.layer_panel.service().rendered; - - assert!(scrolled_previews > initial_previews && scrolled_previews < ANCHOR_COUNT as u64); - eprintln!("visible anchor previews: initial {initial_previews}, after scroll {scrolled_previews}"); - } - #[test] fn source_tiles_defer_image_previews_until_drawn() { let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); From d7739b0645f60108a0df112fce769e061b07bb8a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:59:37 -0500 Subject: [PATCH 9/9] Use shared strict glTF URI percent decoding --- Cargo.lock | 7 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/gltf.rs | 32 ++++++++++++++------------ 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1befa39f..8bad56c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -851,10 +851,11 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a)", "miniz_oxide 0.9.1", + "serde_json", ] [[package]] @@ -970,7 +971,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2f7e212e..983ec031 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,7 @@ craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774 # Isolated aligned writer; existing archive readers retain their pin and behavior. craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "70e562aa88436b6b79a997215b4fa4f6a6b1838a", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 92e52f72..379a71d3 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -292,21 +292,23 @@ fn check_buffer_uris(doc: &gltf::Document) -> Result<()> { } pub(crate) fn percent_decode(s: &str) -> Option { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while let Some(&c) = b.get(i) { - let hex = |k: usize| b.get(k).and_then(|h| (*h as char).to_digit(16)); - match (c, hex(i + 1), hex(i + 2)) { - (b'%', Some(h), Some(l)) => { - out.push((h * 16 + l) as u8); - i += 3; - } - _ => { - out.push(c); - i += 1; - } + craft_mesh::gltf::uri_decode_strict(s) +} + +#[cfg(test)] +mod uri_decode_tests { + use super::percent_decode; + + #[test] + fn strict_shared_uri_decoder_preserves_reference_policy() { + assert_eq!(percent_decode("texture%20é%2B.png"), Some("texture é+.png".into())); + assert_eq!(percent_decode("a+b%GG%2"), Some("a+b%GG%2".into())); + assert_eq!(percent_decode("%252e%252e"), Some("%2e%2e".into())); + // Decoding does not replace the external-reference confinement checks. + assert_eq!(percent_decode("%2e%2e%2fsecret"), Some("../secret".into())); + assert_eq!(percent_decode("%00"), Some("\0".into())); + for uri in ["%FF", "%C0%AF", "%ED%A0%80", "%E2%82"] { + assert_eq!(percent_decode(uri), None, "{uri}"); } } - String::from_utf8(out).ok() }