Merge remote-tracking branch 'origin/main' into docs/colour-param-space

# Conflicts:
#	crates/engine/src/layer_cmds.rs
#	crates/engine/src/mask_cmds.rs
This commit is contained in:
FredApps committed 2026-11-18 17:22:38 +07:00
commit ca79d108e4
58 files changed
+4060 -469

No files matched your search

Generated
+4 -3
View File
@@ -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",
+1 -1
View File
@@ -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"] }
+1 -5
View File
@@ -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 {
+55 -9
View File
@@ -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_symmetric, image_samples, procedural, world_noise};
use crate::pattern::{Coords, decal_uv_symmetric, 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();
@@ -124,6 +125,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.
@@ -1442,11 +1448,6 @@ impl<'a, 'b> Texel<'a, 'b> {
match source {
Source::Uniform(value) => *value,
// A gradient map: on color channels the value picks a color along the stops
Source::Procedural { pattern, ramp, .. } if kind == ChannelKind::Color && !ramp.is_empty() => {
let (coords, projection, _) = self.projected(projection);
texturecraft_core::gradient(ramp, procedural(pattern, projection, &coords)).unwrap_or_default()
}
Source::Anchor { anchor, channel, ramp } if kind == ChannelKind::Color && !ramp.is_empty() => {
let value = self.anchored(*anchor, *channel);
@@ -1455,10 +1456,22 @@ impl<'a, 'b> Texel<'a, 'b> {
let lightness = if signed { lum(value) * 0.5 + 0.5 } else { lum(value) };
texturecraft_core::gradient(ramp, lightness).unwrap_or_default()
}
Source::Procedural { pattern, low, high, .. } => {
Source::Procedural { pattern, low, high, ramp } => {
let (coords, projection, _) = self.projected(projection);
let amount = procedural(pattern, projection, &coords);
mix3(*low, *high, amount)
let pixels = if pattern.resolution.can_reduce() {
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 {
None
};
let amount = procedural_in(pattern, projection, &coords, &PatternContext { pixels, images: Some(self.inp.images) });
if kind == ChannelKind::Color && !ramp.is_empty() {
texturecraft_core::gradient(ramp, amount).unwrap_or_default()
} else {
mix3(*low, *high, amount)
}
}
Source::Image { name, normal_format } => {
let Some(image) = self.inp.images.get(name) else { return [0.5; 3] };
@@ -2818,6 +2831,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();
+4
View File
@@ -16,9 +16,12 @@ pub mod eval;
mod held_fields;
mod image_identity;
pub mod pattern;
mod pattern_context;
pub mod solo;
pub mod store;
pub mod thumb;
mod tile_pattern;
mod tile_random_stream;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
@@ -26,6 +29,7 @@ pub use eval::{
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
};
pub use pattern_context::PatternContext;
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+87 -20
View File
@@ -4,6 +4,11 @@ use texturecraft_core::{Decal, DecalFlip, 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 {
@@ -26,7 +31,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
((n - 0.45) * 4.0 + 0.5).clamp(0.0, 1.0)
}
ProceduralKind::Scratches => {
// Long thin streaks: noise stretched along one axis, sharpened to lines.
// Stretch noise along one axis to make thin streaks
let q = Vec3::new(p.x * 0.15, p.y * 6.0, p.z * 6.0);
let n = noise::perlin(q.to_array(), seed);
let line = 1.0 - ((n - 0.5).abs() * 40.0).min(1.0);
@@ -43,8 +48,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
}
ProceduralKind::Gradient => p.x.rem_euclid(1.0),
ProceduralKind::Wood => {
// Rings across Y (warped by low-frequency noise), latewood darkening sharply before
// each ring boundary; fine fibers stretched along X.
// Warp ring boundaries and add fine fibers along X
let warp = noise::fbm([p.x * 0.18, p.y * 0.6, p.z], 3, seed, noise::perlin);
let t = ((p.y + (warp - 0.5) * 0.9) * 5.0).rem_euclid(1.0);
let ring = 1.0 - smoothstep(0.45, 1.0, t);
@@ -53,8 +57,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
(ring * 0.6 + fiber * 0.25 + tone * 0.15).clamp(0.0, 1.0)
}
ProceduralKind::Bricks => {
// Bricks 1 × 0.5 in running bond; per-brick tone in the top 15 % so low/high map to
// mortar/brick colors without washing the bricks out.
// Keep per-brick tone near its high value so mortar stays distinct
let row = (p.y * 2.0).floor();
let x = p.x + if (row as i32).rem_euclid(2) == 1 { 0.5 } else { 0.0 };
let (col, fx, fy) = (x.floor(), x.rem_euclid(1.0), (p.y * 2.0).rem_euclid(1.0));
@@ -68,10 +71,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed))
}
ProceduralKind::Weave | ProceduralKind::Twill => {
// Warp along X, weft along Y: in each cell the thread on top shows its round
// cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill
// floats over two cells and steps one cell per row, so the floats line up in diagonal
// ribs, the weft darker than the warp.
// Alternate top threads for plain weave or step them into twill ribs
let c = (p * 2.0).floor();
let f = p * 2.0 - c;
let pi = std::f32::consts::PI;
@@ -112,8 +112,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
}
ProceduralKind::Voronoi => noise::cellular(a, seed).2,
ProceduralKind::Streaks => {
// Drips: thin columns along Y, each segment starting at a random height and fading
// as it runs down (Y is up), over two offset column grids.
// Offset column grids make sparse drips that fade downwards
let drip = |x: f32, salt: u32| {
let cx = x * 6.0;
let col = cx.floor() as i32;
@@ -129,7 +128,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
(drip(p.x, 0).max(drip(p.x + 0.37, 1) * 0.8) * (0.6 + 0.4 * fine)).clamp(0.0, 1.0)
}
ProceduralKind::Smudges => {
// Sparse elliptical prints with concentric ridges, over soft greasy smudges.
// Blend ridged elliptical prints with soft smudges
let w = noise::perlin((p * 1.3).to_array(), seed ^ 0x61) - 0.5;
let q = Vec3::new(p.x * 1.15 + w * 0.3, p.y * 0.85 + w * 0.3, p.z);
let (f1, _, id) = noise::cellular(q.to_array(), seed);
@@ -143,6 +142,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, 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;
@@ -200,16 +200,22 @@ 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 and without images
pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 {
let pattern_scale = pattern.scale.max(1e-4);
procedural_in(pattern, projection, coords, &PatternContext::default())
}
/// 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();
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 +223,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 +232,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 +248,50 @@ 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<u32> {
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 `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(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context);
let top_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * fraction.x;
top + (bottom - top) * fraction.y
}
/// The pattern at `point` of its plane, exactly
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),
}
}
/// 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] {
@@ -374,6 +415,32 @@ 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();
// Coarse reads are exact at cell centers and blend between 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() {
+12
View File
@@ -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<u32>,
/// The image resources a pattern's inputs name; None reads them as empty
pub images: Option<&'a ImageStore>,
}
+658
View File
@@ -0,0 +1,658 @@
//! 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, 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
pub(crate) static DEFAULT: LazyLock<TileGenerator> = 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;
/// 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);
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 draws an input image instead (see `pattern`): without one it is empty
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 (`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;
}
if tile.shape_tiling > 1 {
// Tiling shows the copy just above and left of center
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;
}
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;
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_left = at(0.0, 0.0);
let bottom_left = at(0.0, 1.0);
let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x;
let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * 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 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<f32> {
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 (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;
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 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;
}
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<Item = i32> {
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
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); `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 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);
}
};
// Each shifted line needs its own nearby tile search
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, 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, inputs)) {
add(value);
}
}
}
}
let background = background.map_or(tile.background, |image| gray(image.sample(point.x, point.y)));
finish(tile, sum, colored, background)
}
/// 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 = (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
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, 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() }
}
#[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");
}
/// 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 has the same extent in absolute and reference pixels
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]) };
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);
}
}
}
/// An image `size` texels wide whose left half is `left` and right half `right`
fn halves(left: f32, right: f32) -> std::sync::Arc<ImageRes> {
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 {
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));
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! 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,
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)
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
}
}
#[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}");
}
}
}
@@ -749,6 +749,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], ramp: Vec::new() });
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;
+88 -7
View File
@@ -14,6 +14,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;
@@ -23,6 +29,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)]
@@ -278,10 +290,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,
@@ -305,6 +319,7 @@ impl ProceduralKind {
ProceduralKind::Smudges,
ProceduralKind::Pores,
ProceduralKind::Chips,
ProceduralKind::TileGenerator,
];
pub fn label(self) -> &'static str {
match self {
@@ -331,6 +346,7 @@ impl ProceduralKind {
ProceduralKind::Smudges => "Fingerprints",
ProceduralKind::Pores => "Pores",
ProceduralKind::Chips => "Paint chips",
ProceduralKind::TileGenerator => "Tile Generator",
}
}
pub fn parse(s: &str) -> Option<ProceduralKind> {
@@ -351,11 +367,34 @@ 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<Box<TileGenerator>>,
/// 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<Option<Box<TileGenerator>>, D::Error> {
let saved: Option<Box<TileGenerator>> = 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() }
}
}
@@ -401,6 +440,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 gradient map stops of a procedural or anchor source (empty: none).
pub fn ramp(&self) -> &[[f32; 3]] {
match self {
@@ -1167,7 +1215,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<Item = &str> {
let sources: Vec<&Source> = match self {
EffectKind::Fill { source, .. } => vec![source],
@@ -1175,10 +1223,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)
}
}
@@ -1268,6 +1313,42 @@ 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();
+23
View File
@@ -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",
}
}
}
+265
View File
@@ -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<String>,
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<String>,
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<u32> = 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<u32> = 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<Item = &str> {
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,
}
}
}
@@ -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",
}
}
}
+67
View File
@@ -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",
}
}
}
+32
View File
@@ -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",
}
}
}
+22
View File
@@ -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",
}
}
}
+2 -1
View File
@@ -26,7 +26,8 @@ pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, 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,
PathShape, Procedural, 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,
+17 -8
View File
@@ -7,15 +7,24 @@ 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, ramp } => with_ramp(
json!({
fn source_json(source: &Source) -> Value {
match source {
Source::Uniform(value) => json!({ "uniform": value }),
Source::Procedural { pattern, low, high, ramp } => {
let mut report = json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
}),
ramp,
),
});
if !pattern.resolution.is_default() {
report["resolution"] =
json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor });
}
if let Some(tile) = &pattern.tile {
report["tile"] = crate::procedural_params::tile_report(tile);
}
with_ramp(report, ramp)
}
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, ramp } => with_ramp(json!({ "anchor": anchor.0, "channel": channel.id() }), ramp),
+137 -91
View File
@@ -3,7 +3,8 @@
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Project, Projection, Source,
BlendMode, Channel, ChannelBlend, ChannelKind, EffectKind, Fill, Layer, LayerId, LayerKind, NormalFormat, Procedural, ProceduralKind, Project, Projection,
Source,
};
use crate::commands::{
@@ -95,7 +96,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set fill source",
[],
None,
"{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|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?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
"{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|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?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
has_layer,
fill_set
),
@@ -521,104 +522,77 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
}
}
fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
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"))?;
fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
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(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 colors = ramp_param(p, ch)?;
let init_ramp = boolp(p, "gradientMap") == Some(true);
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 colors = ramp_param(params, channel)?;
let init_ramp = boolp(params, "gradientMap") == Some(true);
if init_ramp && colors.is_some() {
return Err(bad("layer.fill.set", "give `gradientMap` or `colors`, not both"));
return Err(bad(CMD, "give `gradientMap` or `colors`, not both"));
}
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, ramp: Vec::new() })
} 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() || colors.is_some() || init_ramp {
None
} else {
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `colors`, `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"));
let source = fill_source_from(session, params, (target, channel), normal_format)?;
if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp {
return Err(bad(
CMD,
"give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `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"));
}
// Changing only the normal format or gradient stops leaves the layer channel on or off
let touches_channel = source.is_some() || enabled.is_some();
s.edit("Set fill", |s| {
let f = fill_mut(s, target)?;
session.edit("Set fill", |session| {
let fill = fill_mut(session, 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")),
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")),
}
}
let colors = if init_ramp { initial_ramp(ch, &source, f.sources.get(&ch))? } else { colors };
let source = with_ramp(ch, f.sources.get(&ch), source, colors)?;
let current = fill.sources.get(&channel);
let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors };
let source = with_ramp(channel, current, source, colors)?;
match target {
// 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);
}
// Removing stops (`colors: []`) from a channel the fill does not have adds nothing
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && !f.sources.contains_key(&ch) => {}
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && current.is_none() => {}
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);
}
}
}
@@ -627,23 +601,94 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The gradient map stops `colors` gives for channel `ch` (None when absent, empty to remove).
fn ramp_param(p: &Value, ch: Channel) -> Result<Option<Vec<[f32; 3]>>> {
let Some(list) = p.get("colors").filter(|v| !v.is_null()) else { return Ok(None) };
let parsed: Option<Vec<[f32; 3]>> =
list.as_array().and_then(|a| a.iter().map(|c| crate::commands::color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect());
match parsed {
Some(c) if c.len() <= 16 && (c.is_empty() || ch.kind() == texturecraft_core::ChannelKind::Color) => Ok(Some(c)),
Some(c) if c.len() <= 16 => Err(bad("layer.fill.set", "`colors` (a gradient map) goes on a color channel")),
_ => Err(bad("layer.fill.set", "`colors` must be up to 16 colors ([r, g, b] linear or \"#rrggbb\")")),
/// 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<NormalFormat>,
) -> Result<Option<Source>> {
const CMD: &str = "layer.fill.set";
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 same kind keeps its resolution and Tile Generator settings
let current = fill_mut(session, target)?.sources.get(&channel);
if let Some(Source::Procedural { pattern: current, .. }) = current
&& current.kind == kind
{
pattern.resolution = current.resolution;
pattern.tile = current.tile.clone();
}
crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?;
return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() }));
}
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 { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else {
return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings"));
};
let mut pattern = pattern.clone();
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: *low, high: *high, ramp: Vec::new() }))
}
/// The gradient map stops from `colors` (None when absent, empty to remove).
fn ramp_param(params: &Value, channel: Channel) -> Result<Option<Vec<[f32; 3]>>> {
const MAX_GRADIENT_STOPS: usize = 16;
let Some(list) = params.get("colors").filter(|value| !value.is_null()) else { return Ok(None) };
let invalid = || bad("layer.fill.set", "`colors` must be up to 16 colors ([r, g, b] linear or \"#rrggbb\")");
let list = list.as_array().filter(|list| list.len() <= MAX_GRADIENT_STOPS).ok_or_else(invalid)?;
let colors: Vec<_> = list
.iter()
.map(|color| crate::commands::color_of(color).map(|rgb| rgb.map(|component| component.clamp(0.0, 1.0))).ok_or_else(invalid))
.collect::<Result<_>>()?;
if !colors.is_empty() && channel.kind() != ChannelKind::Color {
return Err(bad("layer.fill.set", "`colors` (a gradient map) goes on a color channel"));
}
Ok(Some(colors))
}
/// The stops `gradientMap: true` turns on for channel `ch`: those the source already has, else a
/// procedural's low, midpoint and high (so its look holds) or an anchor's black, gray and white.
/// `source` is the one the call sets, else the channel's `current` one.
fn initial_ramp(ch: Channel, source: &Option<Source>, current: Option<&Source>) -> Result<Option<Vec<[f32; 3]>>> {
if ch.kind() != texturecraft_core::ChannelKind::Color {
fn initial_ramp(channel: Channel, source: Option<&Source>, current: Option<&Source>) -> Result<Option<Vec<[f32; 3]>>> {
if channel.kind() != ChannelKind::Color {
return Err(bad("layer.fill.set", "`gradientMap` goes on a color channel"));
}
@@ -651,7 +696,7 @@ fn initial_ramp(ch: Channel, source: &Option<Source>, current: Option<&Source>)
return Ok(Some(kept.to_vec()));
}
match source.as_ref().or(current) {
match source.or(current) {
Some(Source::Procedural { low, high, .. }) => Ok(Some(vec![*low, std::array::from_fn(|k| (low[k] + high[k]) * 0.5), *high])),
Some(Source::Anchor { .. }) => Ok(Some(vec![[0.0; 3], [0.5; 3], [1.0; 3]])),
_ => Err(bad("layer.fill.set", "`gradientMap` needs a procedural or an anchor on the channel")),
@@ -662,8 +707,8 @@ fn initial_ramp(ch: Channel, source: &Option<Source>, current: Option<&Source>)
/// `colors` when given, else those of `current`, so picking another pattern or anchor keeps them.
/// Only color channels keep stops, so a source copied onto another channel loses them; removing
/// stops (`colors: []`) where there are none changes nothing.
fn with_ramp(ch: Channel, current: Option<&Source>, source: Option<Source>, colors: Option<Vec<[f32; 3]>>) -> Result<Option<Source>> {
let adds = colors.as_ref().is_some_and(|c| !c.is_empty());
fn with_ramp(channel: Channel, current: Option<&Source>, source: Option<Source>, colors: Option<Vec<[f32; 3]>>) -> Result<Option<Source>> {
let adds = colors.as_ref().is_some_and(|colors| !colors.is_empty());
let needs = || bad("layer.fill.set", "`colors` needs a procedural or an anchor on the channel");
let mut source = match (source, current) {
(Some(source), _) => source,
@@ -672,12 +717,13 @@ fn with_ramp(ch: Channel, current: Option<&Source>, source: Option<Source>, colo
_ => return Ok(None),
};
let kept = match current {
Some(current) if ch.kind() == texturecraft_core::ChannelKind::Color => current.ramp().to_vec(),
_ => Vec::new(),
};
match &mut source {
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => *ramp = colors.unwrap_or(kept),
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => {
*ramp = colors.unwrap_or_else(|| match current {
Some(current) if channel.kind() == ChannelKind::Color => current.ramp().to_vec(),
_ => Vec::new(),
});
}
_ if adds => return Err(needs()),
_ => {}
}
+1
View File
@@ -53,6 +53,7 @@ mod stencil_look;
mod preserve;
pub mod preset_cmds;
pub mod preview;
mod procedural_params;
pub mod project_cmds;
pub mod quick_mask;
pub mod resource_cmds;
+52 -24
View File
@@ -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<CommandSpec> {
"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? ([r,g,b] linear or \"#rrggbb\" sRGB), 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? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}",
has_layer,
add_fill
),
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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] linear, ...] (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] linear, ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
has_layer,
set
),
@@ -295,9 +295,6 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result<Source>
fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
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)?;
@@ -328,12 +325,8 @@ fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
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], ramp: Vec::new() }
}
@@ -378,17 +371,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
@@ -402,6 +385,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
if mode.is_none() && weights.is_none() {
return Ok(());
}
if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes"));
}
@@ -688,18 +672,32 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
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, "value")
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. } | Source::Image { .. })
{
*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, .. } => {
@@ -716,6 +714,36 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
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<Option<Source>> {
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, ramp: Vec::new() }))
}
/// 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 {
+3 -6
View File
@@ -36,19 +36,16 @@ 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<String>, depth: usize) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
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) {
+2 -1
View File
@@ -166,8 +166,9 @@ 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 { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high, ramp: Vec::new() }
Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low, high, ramp: Vec::new() }
}
/// A scalar pattern between `lo` and `hi`.
+142
View File
@@ -0,0 +1,142 @@
//! 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<TileGenerator> {
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<Value> {
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<T: Copy + std::fmt::Debug>(all: &[T], label: fn(T) -> &'static str, text: &str) -> Option<String> {
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::<Map<String, Value>>())
}
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
}
+1 -1
View File
@@ -717,7 +717,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;
+2 -7
View File
@@ -89,15 +89,10 @@ 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 { kind, scale, seed, contrast, balance: 0.0, invert: false },
low: [0.0; 3],
high: [1.0; 3],
ramp: Vec::new(),
},
source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] },
}
}
+21 -1
View File
@@ -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();
+1
View File
@@ -35,6 +35,7 @@ mod project_recovery;
mod sample;
mod solo;
mod thumbs;
mod tile_generator;
mod tool_availability;
mod tool_settings;
mod tools;
+320
View File
@@ -0,0 +1,320 @@
//! 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, Projection, 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 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();
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");
// Only an explicit uniform pick replaces an active pattern
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]
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");
}
/// 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();
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));
}
/// The composited base color of every texel of the texture set
fn base_colors(session: &mut Session) -> Vec<f32> {
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");
}
#[test]
fn a_tile_generator_gradient_map_reads_the_image_input() {
let mut session = session();
let input = import_gray(&mut session, "plate.png");
tile_fill(&mut session);
let colors = [[0.0; 3], [1.0, 0.0, 0.0]];
execute(
&mut session,
"layer.fill.set",
&json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}, "colors": colors}),
)
.unwrap();
let red = base_colors(&mut session);
let mid_red = red.iter().filter(|value| (**value - 0.5).abs() < 0.05).count();
assert!(mid_red > red.len() / 2, "the gradient map recolors the input image's gray: {mid_red} of {}", red.len());
assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 64, 64)[1], 0.0);
}
#[test]
fn a_tile_generator_gradient_map_keeps_the_selected_resolution() {
let mut session = session();
let layer = tile_fill(&mut session);
let colors = [[0.0; 3], [1.0, 0.0, 0.0]];
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "colors": colors})).unwrap();
let exact = base_colors(&mut session);
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolution": "uvTile", "resolutionFactor": -3})).unwrap();
let coarse = base_colors(&mut session);
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap();
let row = inspected["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap();
let source = &row["fill"]["sources"]["baseColor"];
assert_ne!(exact, coarse, "the gradient map samples the coarser pattern");
assert_eq!(source["colors"], json!(colors));
assert_eq!(source["resolution"]["mode"], "UvTile");
assert_eq!(source["resolution"]["factor"], -3);
assert_eq!(source["tile"]["amount"], json!(TileGenerator::default().amount));
}
+17 -15
View File
@@ -292,21 +292,23 @@ fn check_buffer_uris(doc: &gltf::Document) -> Result<()> {
}
pub(crate) fn percent_decode(s: &str) -> Option<String> {
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()
}
+52
View File
@@ -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<bool> {
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<bool> {
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
}
+113 -153
View File
@@ -6,8 +6,8 @@ use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, ChannelBlend, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink,
ProceduralKind, Projection, Source,
BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam,
MaterialLink, Projection, Source,
};
use texturecraft_engine::filter_lib::scalar_params;
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
@@ -15,6 +15,7 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
use crate::TextureCraftApp;
use crate::filter_slot::SLOT_HEIGHT;
use crate::i18n::{n_, tr, trf};
use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height};
use crate::shelf::{Asset, ShelfDrag};
@@ -239,7 +240,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, tokens.accent));
}
});
app.layer_panel.end(ui.ctx(), &app.session);
select_all_layers(app, ui);
}
@@ -1703,7 +1703,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);
@@ -2688,13 +2690,13 @@ fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option<Value
}
}
/// `base` with the fields of `extra` added.
fn with(base: &Value, extra: Value) -> 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).
@@ -2737,7 +2739,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)
@@ -2976,9 +2978,9 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base: &Value,
}
/// The decal's mirrored copy on the other side of the mesh: the axis it is mirrored across and how its image is flipped
fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base: &Value) {
fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, decal: &Decal, base: &Value) {
let axes = ["X", "Y", "Z"];
let axis = d.symmetry.map(|symmetry| usize::from(symmetry.axis));
let axis = decal.symmetry.map(|symmetry| usize::from(symmetry.axis));
let mut picked = None;
combo(ui, tr("Mirror across"), axis.and_then(|axis| axes.get(axis).copied()).unwrap_or_else(|| tr("Off")), |ui| {
if ui.selectable_label(axis.is_none(), tr("Off")).clicked() && axis.is_some() {
@@ -2991,7 +2993,7 @@ fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base
}
});
if let Some(symmetry) = d.symmetry {
if let Some(symmetry) = decal.symmetry {
let flips = [(DecalFlip::None, tr("None"), "none"), (DecalFlip::U, "U", "u"), (DecalFlip::V, "V", "v")];
let current = flips.iter().find(|flip| flip.0 == symmetry.flip).map_or("", |flip| flip.1);
combo(ui, tr("Flip the copy's image"), current, |ui| {
@@ -3003,7 +3005,7 @@ fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base
});
}
if let Some(symmetry) = d.symmetry {
if let Some(symmetry) = decal.symmetry {
// The plane moves within the mesh, as the symmetry popup's axis position does
let (lo, hi) = app.session.mesh.bounds();
let limit = ((hi - lo) * 0.5)[usize::from(symmetry.axis.min(2))];
@@ -3018,135 +3020,105 @@ fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base
}
}
/// 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();
}
if c.kind() == ChannelKind::Color {
gradient_map_item(app, ui, &fill.source(c), &set);
}
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();
}
})
/// Space a fill channel's color swatch leaves at the group's right edge
const CHANNEL_SWATCH_MARGIN: f32 = 4.0;
/// Width of a pattern's low and high swatches
const PATTERN_RANGE_SWATCH_WIDTH: f32 = 60.0;
/// Size of the gradient map menu icon beside the fill source slot
const FILL_CHANNEL_MENU_ICON_SIZE: f32 = 13.0;
const GRADIENT_MAP_HINT: &str = n_("Colors the procedural or anchor from dark to light through color stops");
/// The source slot, source settings and gradient map of one fill channel
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 default_source = Source::uniform_of(channel);
let source = fill.sources.get(&channel).unwrap_or(&default_source);
let is_color = channel.kind() == ChannelKind::Color;
let group = ui.group(|ui| {
let slot = crate::fill_source_target::FillSourceTarget::Channel { base: base.clone(), channel };
if is_color {
ui.allocate_ui_with_layout(vec2(ui.available_width(), SLOT_HEIGHT), egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.menu_button(RichText::new(ic::DOTS_THREE).size(FILL_CHANNEL_MENU_ICON_SIZE), |ui| gradient_map_item(app, ui, source, &set))
.response
.on_hover_text(tr("Channel source: uniform value, procedural, image or anchor"));
.on_hover_text(tr(GRADIENT_MAP_HINT));
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label())));
});
});
let ramp = fill.source(c).ramp().to_vec();
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 && ramp.is_empty() {
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));
}
}
if c.kind() == ChannelKind::Color && !ramp.is_empty() {
ramp_editor(app, ui, &ramp, &format!("ramp_{salt}_{}", c.id()), &set);
}
});
// 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})));
} else {
crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label())));
}
match source {
Source::Uniform(value) if is_color => {
let mut value = *value;
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})));
}
}
Source::Uniform(value) => {
let mut value = value[0];
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, range, 2) {
app.run("layer.fill.set", set(json!({"value": value, "merge": merge})));
}
}
Source::Procedural { pattern, low, high, ramp } => {
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 is_color && ramp.is_empty() {
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));
}
}
if is_color && !source.ramp().is_empty() {
ramp_editor(app, ui, source.ramp(), &format!("ramp_{salt}_{}", channel.id()), &set);
}
});
// 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 Gradient Map item of a color channel's source menu: turns the color stops of its
/// The Gradient Map item beside a color channel's source slot: turns the color stops of its
/// procedural (starting from its low and high, so the look holds) or anchor on, or off.
fn gradient_map_item(app: &mut TextureCraftApp, ui: &mut Ui, source: &Source, set: &impl Fn(Value) -> Value) {
let can = matches!(source, Source::Procedural { .. } | Source::Anchor { .. });
let on = !source.ramp().is_empty();
let hint = tr("Colors the procedural or anchor from dark to light through color stops");
let hint = tr(GRADIENT_MAP_HINT);
let item = ui.add_enabled_ui(can, |ui| ui.selectable_label(on, tr("Gradient Map"))).inner;
if item.on_hover_text(hint).on_disabled_hover_text(hint).clicked() {
let params = if on { json!({ "colors": [] }) } else { json!({ "gradientMap": true }) };
@@ -3198,26 +3170,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}));
}
@@ -3228,6 +3185,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));
@@ -3250,7 +3211,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
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));
+301
View File
@@ -0,0 +1,301 @@
//! 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<Arc<ImageRes>> =
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 tiles = tiles(app, &ctx);
let anchors: Vec<ResourcePickerAnchor> = anchors
.iter()
.map(|(anchor, name)| ResourcePickerAnchor {
anchor: *anchor,
name: name.clone(),
layer: layer_name(app, *anchor),
channel: read_label(app, *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, |ui, anchor| {
app.layer_panel.texture_outside(ui.ctx(), &app.session, ThumbTarget::Stage { effect: anchor, channel })
});
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<egui::TextureId>) {
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<String> {
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 and a uniform value
fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context) -> Vec<ResourcePickerTile<'static>> {
let mut tiles: Vec<ResourcePickerTile<'static>> = 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),
image: None,
preview: Box::new(move || ShelfPreview::Procedural(kind)),
})
.collect();
let mut names: Vec<(String, Arc<ImageRes>)> = 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 preview_name = name.clone();
tiles.push(ResourcePickerTile {
key: format!("{IMAGE_PREFIX}{name}"),
label: name,
group: tr("Images"),
thumbnail: None,
image: Some(image.clone()),
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)),
image: None,
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) => 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})));
}
(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]),
}
}
#[cfg(test)]
mod tests {
use egui_kittest::{Harness, kittest::Queryable};
use texturecraft_engine::core::LayerKind;
use texturecraft_engine::{Session, execute, geom::primitives};
use super::*;
fn picker_harness(session: Session, anchors: Vec<(LayerId, String)>) -> Harness<'static, (TextureCraftApp, Vec<(LayerId, String)>)> {
let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default());
let app = TextureCraftApp::new(&creation_context, session);
Harness::builder().with_size(vec2(500.0, 700.0)).with_context_setup(crate::theme::install).build_ui_state(
|ui, (app, anchors)| {
let layer = app.session.selected_layer().unwrap();
let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") };
let source = fill.source(Channel::Height);
let target = FillSourceTarget::Channel { base: json!({"layer": layer.0}), channel: Channel::Height };
show(app, ui, &target, &source, (anchors, "Source"));
app.layer_panel.end(ui.ctx(), &app.session);
},
(app, anchors),
)
}
fn image_preview_count(context: &egui::Context) -> usize {
context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-image-")).count()
}
#[test]
fn source_picker_images_render_on_scroll_and_release_on_removal() {
const IMAGE_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();
for index in 0..IMAGE_COUNT {
let name = format!("picker-image-{index:03}.png");
session.doc.resources.insert(name.clone(), Arc::new(vec![0]));
session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false }));
}
let mut harness = picker_harness(session, Vec::new());
harness.get_by_role_and_label(egui::Role::ComboBox, "Source").click();
harness.run_steps(30);
let initial_previews = image_preview_count(&harness.ctx);
assert!(initial_previews > 0 && initial_previews < IMAGE_COUNT, "only visible images should have previews: {initial_previews}");
harness.run_steps(3);
assert_eq!(image_preview_count(&harness.ctx), initial_previews, "warm frames reuse image previews");
let first_name = "picker-image-000.png";
harness.get_by_role_and_label(egui::Role::Button, first_name).scroll_to_me();
harness.run_steps(30);
let scrolled_previews = image_preview_count(&harness.ctx);
harness.get_by_role_and_label(egui::Role::Button, first_name).click();
harness.run_steps(3);
assert!(scrolled_previews > initial_previews, "scrolling must render newly visible image tiles");
let app = &mut harness.state_mut().0;
let layer = app.session.selected_layer().unwrap();
let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") };
assert_eq!(fill.source(Channel::Height), Source::image(first_name));
app.session.images.clear();
app.thumbs.sync_images(&app.session.images, app.session.revision + 1);
assert_eq!(image_preview_count(&harness.ctx), 0, "removed images release all picker preview textures");
eprintln!("picker image previews: initial {initial_previews}, after scroll {scrolled_previews}, after removal 0");
}
#[test]
fn source_tiles_defer_image_previews_until_drawn() {
let mut session = texturecraft_engine::sample_session(128, 64).unwrap();
for index in 0..128 {
let name = format!("picker-{index:03}.png");
session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false }));
}
let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default());
let mut app = TextureCraftApp::new(&creation_context, session);
let context = egui::Context::default();
let tiles = tiles(&mut app, &context);
let image_previews = context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-")).count();
assert_eq!(tiles.iter().filter(|tile| tile.key.starts_with(IMAGE_PREFIX)).count(), 128);
assert_eq!(image_previews, 0, "opening the picker must not resample all project images");
}
}
+12
View File
@@ -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 },
}
+9 -9
View File
@@ -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<egui::TextureId>, (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);
}
+1 -30
View File
@@ -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);
+57
View File
@@ -0,0 +1,57 @@
//! 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;
use crate::widgets::value_header;
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<bool> {
let tokens = Tokens::get(ui.ctx());
let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2);
ui.horizontal(|ui| {
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::<String>(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());
}
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
}
+8 -1
View File
@@ -186,7 +186,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);
@@ -207,6 +209,11 @@ mod tests {
keys.extend(texturecraft_engine::HISTORY_TEMPLATES);
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 {
+80 -4
View File
@@ -40,20 +40,39 @@ pub struct LayerPanel {
service: ThumbService,
textures: HashMap<ThumbTarget, (u64, TextureHandle, u64)>,
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)));
}
/// Advance the picture frame once, 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.frame += 1;
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<TextureId> {
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<TextureId> {
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,57 @@ 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 outside_pictures_release_old_textures_while_the_panel_is_hidden() {
let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap();
let context = Context::default();
let initial_textures = context.tex_manager().read().num_allocated();
let mut panel = LayerPanel::default();
// Outside pictures begin frames even when the Layers panel never does
let missing = ThumbTarget::Content { layer: LayerId(u64::MAX), channel: Channel::BaseColor };
panel.texture_outside(&context, &session, missing);
for index in 0..CACHE_ENTRIES * 2 + 1 {
let target = ThumbTarget::Content { layer: LayerId(index as u64), channel: Channel::BaseColor };
let image = egui::ColorImage::filled([64, 64], egui::Color32::WHITE);
let texture = context.load_texture("layer-thumb", image, TextureOptions::LINEAR);
panel.textures.insert(target, (1, texture, panel.frame));
}
assert_eq!(context.tex_manager().read().num_allocated(), initial_textures + CACHE_ENTRIES * 2 + 1);
panel.end(&context, &session);
for _ in 0..2 {
panel.texture_outside(&context, &session, missing);
panel.end(&context, &session);
}
assert_eq!(panel.textures.len(), 0, "old outside pictures should leave the GPU cache");
assert_eq!(context.tex_manager().read().num_allocated(), initial_textures);
}
#[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();
@@ -128,7 +202,9 @@ mod tests {
panel.textures.insert(target, (1, texture, panel.frame));
}
let kept = evicted.pop().unwrap();
panel.end(&context, &session);
panel.begin(&session, 1.0);
panel.end(&context, &session);
panel.begin(&session, 2.0);
panel.textures.values_mut().find(|(_, texture, _)| texture.id() == kept).unwrap().2 = panel.frame;
panel.end(&context, &session);
+17
View File
@@ -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 ask;
mod bake_job;
pub mod bake_mode;
@@ -19,10 +20,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;
@@ -49,6 +53,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;
@@ -59,8 +65,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;
@@ -80,6 +91,7 @@ mod surface_paint_point;
pub mod symmetry;
pub mod theme;
pub mod thumbs;
mod tile_edits;
pub mod titlebar;
pub mod toolbar;
pub mod ui_state_store;
@@ -871,6 +883,7 @@ impl eframe::App for TextureCraftApp {
toolbar::rail(self, ui);
}
}
let hide_ui = self.ui.hide_ui;
let tokens = theme::Tokens::get(&ctx);
@@ -878,6 +891,10 @@ impl eframe::App for TextureCraftApp {
let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) };
egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) });
windows::show(self, &ctx);
// Finish after the dock and windows have requested their thumbnails
self.layer_panel.end(&ctx, &self.session);
#[cfg(not(target_arch = "wasm32"))]
updates_ui::show(self, &ctx);
toasts(self, &ctx);
+378
View File
@@ -0,0 +1,378 @@
//! 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, output_size_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<f32> = 0.1..=100.0;
const CONTRAST_RANGE: std::ops::RangeInclusive<f32> = 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()) else { return };
let size_label = output_size_label(&current, 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(size_label));
});
}
/// 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::<bool>(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() {
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);
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 {
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}));
}
}
/// 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<Option<String>> {
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
}
+11
View File
@@ -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,
}
+10 -7
View File
@@ -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`
+67
View File
@@ -0,0 +1,67 @@
//! 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, TextureSet};
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)),
}
}
/// 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");
}
}
+241 -24
View File
@@ -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,60 @@ pub(crate) fn show(
items: impl FnOnce(&mut Thumbs) -> Vec<ResourcePickerItem>,
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(),
image: None,
preview: Box::new(move || preview(id)),
}
})
.collect();
match popup(slot, popup_id, thumbs, (current, None), tiles, None, |_, _| 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<LayerId>),
tiles: Vec<ResourcePickerTile<'_>>,
anchors: Vec<ResourcePickerAnchor>,
picture: impl FnMut(&Ui, LayerId) -> Option<egui::TextureId>,
) -> Option<ResourcePickerChoice> {
if !is_open(&slot.ctx, popup_id) {
return None;
}
popup(slot, popup_id, thumbs, (current, current_anchor), tiles, Some(anchors), picture)
}
/// 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<LayerId>),
tiles: Vec<ResourcePickerTile<'_>>,
anchors: Option<Vec<ResourcePickerAnchor>>,
mut picture: impl FnMut(&Ui, LayerId) -> Option<egui::TextureId>,
) -> Option<ResourcePickerChoice> {
let ctx = slot.ctx.clone();
let mut picked = None;
egui::Popup::from_response(slot)
.id(popup_id)
@@ -55,11 +141,20 @@ pub(crate) fn show(
.show(|ui| {
ui.set_width(PICKER_WIDTH);
let just_opened = ui.data_mut(|data| data.remove_temp::<bool>(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, &mut picture).map(ResourcePickerChoice::Anchor)
}
_ => grid(ui, thumbs, &tiles, &query, current, just_opened).map(ResourcePickerChoice::Resource),
};
});
});
@@ -69,6 +164,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::<ResourcePickerTab>(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 +223,38 @@ 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<String> {
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,
|ui, thumbs| tile.image.as_ref().map(|image| thumbs.image(ui.ctx(), &tile.label, image)).or_else(|| tile.thumbnail.clone()),
|| (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 +262,76 @@ 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<LayerId>,
picture: &mut impl FnMut(&Ui, LayerId) -> Option<egui::TextureId>,
) -> Option<LayerId> {
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, picture);
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, picture: &mut impl FnMut(&Ui, LayerId) -> Option<egui::TextureId>) -> 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));
// Offscreen tiles must not queue composition of their anchor stacks
if !ui.is_rect_visible(rect) {
return response;
}
let texture = picture(ui, anchor.anchor);
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) = texture {
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")
@@ -0,0 +1,12 @@
//! One tile of a fill source picker's Anchor points tab
use texturecraft_engine::core::LayerId;
/// One tile of the Anchor points tab: the anchor, its layer's name and the channel it is read in
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,
}
@@ -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),
}
@@ -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,
}
@@ -0,0 +1,18 @@
//! One tile of a resource picker's Resources tab
use std::sync::Arc;
use egui::TextureHandle;
use texturecraft_engine::compose::ImageRes;
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<TextureHandle>,
pub image: Option<Arc<ImageRes>>,
pub preview: Box<dyn Fn() -> ShelfPreview + 'a>,
}
+6 -5
View File
@@ -508,7 +508,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
let response = tile_in_view(
ui,
&mut app.thumbs,
texture.as_ref(),
|_, _| texture,
|thumbs| match entry {
ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)),
_ => entry.preview(session),
@@ -554,7 +554,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
pub(crate) fn tile(
ui: &mut Ui,
thumbs: &mut Thumbs,
texture: Option<&egui::TextureHandle>,
texture: impl FnOnce(&Ui, &mut Thumbs) -> Option<egui::TextureHandle>,
preview: impl FnOnce() -> ShelfPreview,
label: &str,
drag: Option<&Asset>,
@@ -566,7 +566,7 @@ pub(crate) fn tile(
fn tile_in_view(
ui: &mut Ui,
thumbs: &mut Thumbs,
texture: Option<&egui::TextureHandle>,
texture: impl FnOnce(&Ui, &mut Thumbs) -> Option<egui::TextureHandle>,
preview: impl FnOnce(&mut Thumbs) -> Option<ShelfPreview>,
label: &str,
drag: Option<&Asset>,
@@ -576,6 +576,7 @@ fn tile_in_view(
let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() };
let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let texture = if ui.is_rect_visible(rect) { texture(ui, thumbs) } else { None };
if let Some(asset) = drag
&& response.drag_started()
{
@@ -588,7 +589,7 @@ fn tile_in_view(
}
let image_rect = view.thumbnail_rect(rect);
thumbnail(painter, texture, image_rect, &tokens);
thumbnail(painter, texture.as_ref(), image_rect, &tokens);
if view.name_beside() {
let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP;
let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text));
@@ -599,7 +600,7 @@ fn tile_in_view(
}
let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None };
response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label))
response.on_hover_ui(|ui| hover_preview(ui, texture.as_ref(), big.as_ref(), label))
}
/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness
+85
View File
@@ -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<String, Value>,
pub merge: Option<bool>,
}
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<f32>) {
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<u32>) {
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<f32>) {
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<T: Copy + PartialEq + std::fmt::Debug>(
&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);
}
}
});
}
}
+21 -6
View File
@@ -29,15 +29,16 @@ 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<f32>, decimals: usize) -> (Response, Option<bool>) {
/// 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<f32>, decimals: usize) -> (egui::Id, Option<bool>) {
const MIN_VALUE_WIDTH: f32 = 44.0;
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()
.map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x)
.fold(44.0, f32::max);
.fold(MIN_VALUE_WIDTH, f32::max);
let mut edit = None;
let field = ui
.horizontal(|ui| {
@@ -45,6 +46,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let id = ui.next_auto_id();
let shown = format!("{value:.decimals$}");
// Keep unfinished input while the document value is re-read each frame
let mut text = ui.data(|data| data.get_temp::<String>(id)).unwrap_or_else(|| shown.clone());
let response = ui.add(
@@ -59,6 +61,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang
ui.data_mut(|data| data.insert_temp(id, text.clone()));
} else {
ui.data_mut(|data| data.remove_temp::<String>(id));
// Escape can lose focus before the app consumes the key
let escape =
ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
@@ -78,7 +81,18 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang
.inner
})
.inner;
let (rect, mut response) = ui.allocate_exact_size(vec2(width, 14.0), Sense::click_and_drag());
(field, edit)
}
fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive<f32>, decimals: usize) -> (Response, Option<bool>) {
const TRACK_HEIGHT: f32 = 14.0;
const TRACK_INSET: f32 = 5.0;
const TRACK_WIDTH: f32 = 2.0;
const KNOB_RADIUS: f32 = 4.5;
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, TRACK_HEIGHT), Sense::click_and_drag());
if response.is_pointer_button_down_on() {
ui.data_mut(|data| data.remove_temp::<String>(field));
ui.memory_mut(|memory| memory.surrender_focus(field));
@@ -89,11 +103,12 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang
if (response.dragged() || response.clicked())
&& let Some(pointer) = response.interact_pointer_pos()
{
let fraction = ((pointer.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0);
let fraction = ((pointer.x - rect.left() - TRACK_INSET) / (rect.width() - TRACK_INSET * 2.0).max(1.0)).clamp(0.0, 1.0);
let next = minimum + (maximum - minimum) * fraction;
if (next - *value).abs() > f32::EPSILON {
*value = next;
response.mark_changed();
// Later frames of one drag share its undo step
edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::<bool>(response.id), true)));
}
@@ -103,7 +118,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang
}
let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 };
track(ui, &response, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, fraction, 2.0, 4.5);
track(ui, &response, rect.left() + TRACK_INSET..=rect.right() - TRACK_INSET, rect.center().y, fraction, TRACK_WIDTH, KNOB_RADIUS);
(response, edit)
}
+22 -25
View File
@@ -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");
@@ -130,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;
@@ -148,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;
+1
View File
@@ -71,3 +71,4 @@ mod user_smart_mask;
mod stencil;
mod symmetry;
mod symmetry_2d;
mod tile_generator_panel;
+10 -5
View File
@@ -199,13 +199,18 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() {
h.run_steps(3);
assert!(matches!(reader_source(&h, high), Source::Uniform(_)), "a new fill starts as a uniform value");
// Its source picker lists the anchor of the layer below
h.get_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me();
// The Anchor points tab lists the mask anchor of the layer below
h.get_by_role_and_label(Role::ComboBox, "Grayscale").scroll_to_me();
h.run_steps(30);
h.get_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Uniform value")).unwrap().click();
h.run_steps(2);
h.get_by_label_contains("Anchor: Low / mask /").click();
h.get_by_role_and_label(Role::ComboBox, "Grayscale").click();
h.run_steps(3);
h.get_by_role_and_label(Role::Tab, "Anchor points").click();
h.run_steps(3);
let label = format!("Low / mask / {}", effect_name(&h, anchor));
h.get_by_role_and_label(Role::Button, &label).click();
h.run_steps(3);
let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the fill reads an anchor: {:?}", reader_source(&h, high)) };
assert_eq!(read.0, anchor, "the fill reads the anchor of Low");
@@ -0,0 +1,298 @@
//! 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, by};
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.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);
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 "<layer> / <anchor>", 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.prefs.language = "en".into();
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());
}
/// 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]
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() {
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;
// 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
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();
// 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();
}
+29
View File
@@ -828,3 +828,32 @@ fn mask_fill_image_snapshot() {
assert!(harness.query_by_label("Projection").is_some(), "image projection is editable");
save(&mut harness, &output_dir, "mask-fill-image-selected");
}
#[test]
#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"]
fn tile_generator_gradient_map_snapshot() {
use serde_json::json;
use texturecraft_engine::execute;
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
std::fs::create_dir_all(&output_dir).unwrap();
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "layer.add.fill", &json!({})).unwrap();
execute(
&mut session,
"layer.fill.set",
&json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}),
)
.unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().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);
harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me();
harness.run_steps(30);
assert!(harness.query_by_label_contains("Add color").is_some());
save(&mut harness, &output_dir, "tile-generator-gradient-map");
}