Merge pull request #765 from Rebornim/split/698-5-filters

Properties (5/5, stacked on #764): filters
This commit is contained in:
Chris Hassebrook authored and GitHub committed 2026-11-23 03:02:45 -05:00
commit 2e8337ed62
137 files changed
+15769 -970

No files matched your search

+35 -5
View File
@@ -11,11 +11,11 @@ use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::{Arc, Weak};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_core::{BakedMap, Channel, EffectKind, Filter, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_geom::Mesh;
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::eval::{Inputs, PaintTarget, lights_material};
use crate::held_fields::HeldFields;
use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
@@ -104,6 +104,8 @@ pub struct StackKey {
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, ImageIdentity)>,
/// The viewport environment, its rotation (bits) and its image when it is an imported one, where Baked Lighting Environment lights with them
environment: Option<(String, u32, Option<ImageIdentity>)>,
}
impl StackKey {
@@ -158,6 +160,8 @@ impl StackKey {
fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name);
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
// A filter's image inputs, also one its mode leaves unread: that only empties the cache more often
effect.inputs.values().flat_map(Source::images).for_each(&mut record_image_name);
match &effect.kind {
EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name),
EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name),
@@ -172,6 +176,16 @@ impl StackKey {
let image_identities =
referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
let lit = render_tree
.iter()
.filter_map(|id| project.layers.get(id))
.flat_map(|layer| layer.content_effects.iter())
.any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })));
let environment = lit.then(|| {
let image = project.display.environment_resource().and_then(|name| images.get(name)).map(ImageIdentity::new);
(project.display.environment.clone(), project.display.env_rotation.to_bits(), image)
});
Some(StackKey {
set,
roots,
@@ -179,6 +193,7 @@ impl StackKey {
pixels: pixel_handles,
baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
images: image_identities,
environment,
})
}
}
@@ -188,7 +203,13 @@ impl StackKey {
/// changed (same set, roots, layers, baked maps and images; the same images by id, channel
/// and size). None when anything else differs: the caller recomposites everything.
pub fn changed_tiles(&self, other: &StackKey) -> Option<BTreeSet<(u32, u32)>> {
if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images {
if self.set != other.set
|| self.roots != other.roots
|| self.layers != other.layers
|| self.baked != other.baked
|| self.images != other.images
|| self.environment != other.environment
{
return None;
}
@@ -417,8 +438,17 @@ impl BelowCache {
let project = inp.project;
let set = project.texture_set(inp.ts).ok()?;
// Anchor readers and compare masks reading layers depend on the stack below them
if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_stack)) {
// Replaying cached colors would reuse the material below a lighting or validation effect
if project
.render_tree(&set.stack)
.iter()
.filter_map(|id| project.layers.get(id))
.any(|layer| layer.reads_stack() || layer.content_effects.iter().any(|effect| effect.visible && lights_material(&effect.kind)))
{
if self.key.is_some() {
self.clear();
}
return None;
}
+64
View File
@@ -0,0 +1,64 @@
//! The lower envelope of parabolas that turns a line of squared distances into each place's squared distance to the nearest feature
/// The lower envelope of the parabolas over a line of squared distances, which gives each place's squared distance to the nearest feature along it and the line before
#[derive(Default)]
pub(crate) struct DistanceEnvelope {
/// The parabolas still lowest somewhere: their vertex and where their stretch begins
parabolas: Vec<(usize, f64)>,
/// The line as it was
heights: Vec<f32>,
}
impl DistanceEnvelope {
/// Replace `line` with each place's squared distance to the nearest feature
pub(crate) fn lower(&mut self, line: &mut [f32]) {
self.heights.clear();
self.heights.extend_from_slice(line);
self.parabolas.clear();
let heights = &self.heights;
// In f64, where squared places and their sums stay exact past 4096 texels and a wide line cannot overflow a 32-bit usize
let lifted = |at: usize| f64::from(heights.get(at).copied().unwrap_or(f32::MAX)) + at as f64 * at as f64;
for at in 0..heights.len() {
let mut start = f64::NEG_INFINITY;
while let Some(&(vertex, from)) = self.parabolas.last() {
let crossing = (lifted(at) - lifted(vertex)) / (2.0 * (at - vertex) as f64);
if crossing <= from {
self.parabolas.pop();
} else {
start = crossing;
break;
}
}
self.parabolas.push((at, start));
}
let mut current = 0;
for (at, out) in line.iter_mut().enumerate() {
while self.parabolas.get(current + 1).is_some_and(|(_, from)| *from < at as f64) {
current += 1;
}
if let Some(&(vertex, _)) = self.parabolas.get(current) {
*out = (at as f32 - vertex as f32).powi(2) + heights.get(vertex).copied().unwrap_or(f32::MAX);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Past 4096 texels a squared place is no longer exact in f32: two close features at the end of a wide line still each read 0
#[test]
fn close_features_far_along_a_wide_line_stay_exact() {
const FAR: f32 = 4.0e8;
let mut line = vec![FAR; 10_000];
line[9_950] = 1.0;
line[9_951] = 0.0;
DistanceEnvelope::default().lower(&mut line);
assert_eq!(line[9_949..9_954], [2.0, 1.0, 0.0, 1.0, 4.0]);
}
}
+217
View File
@@ -0,0 +1,217 @@
//! The viewport environment's diffuse light as spherical harmonics, worked out once per environment, and Baked Lighting Environment's shading with it
use std::sync::{Arc, Mutex, Weak};
use texturecraft_core::project::DisplaySettings;
use texturecraft_core::{Channel, DIELECTRIC_REFLECTANCE, finite_unit, mix3};
use texturecraft_geom::glam::Vec3;
use crate::environment_sky::{VIEWPORT_WIDTH, dir_of, environment_linear, radiance, sh_basis, sh9_averaged};
use crate::store::{ImageRes, ImageStore};
/// The diffuse light of the viewport environment and the turn the viewport gives it
#[derive(Clone, Copy)]
pub struct EnvironmentSh {
coefficients: [[f32; 3]; 9],
/// The viewport's environment rotation (radians)
rotation: f32,
}
/// The last coefficients, keyed by a built-in name or the identity of an imported image
type CacheEntry = (String, Option<Weak<ImageRes>>, [[f32; 3]; 9]);
static CACHE: Mutex<Option<CacheEntry>> = Mutex::new(None);
impl EnvironmentSh {
/// The diffuse light of the environment `display` shows (an imported image from `images`), worked out once per environment
pub fn of(display: &DisplaySettings, images: &ImageStore) -> EnvironmentSh {
let image = display.environment_resource().and_then(|name| images.get(name));
let same = |entry: &CacheEntry| match (&entry.1, &image) {
(Some(identity), Some(image)) => std::ptr::eq(identity.as_ptr(), Arc::as_ptr(image)),
(None, None) => entry.0 == display.environment,
_ => false,
};
let rotation = display.env_rotation.to_radians();
let cached = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().filter(|entry| same(entry)).map(|entry| entry.2);
if let Some(coefficients) = cached {
return EnvironmentSh { coefficients, rotation };
}
// Average outside the lock so a Rayon worker can take another tile that needs the cache
let coefficients = match image {
Some(image) => image_sh(image),
None => built_in_sh(&display.environment),
};
*CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((display.environment.clone(), image.map(Arc::downgrade), coefficients));
EnvironmentSh { coefficients, rotation }
}
/// The diffuse light reaching a surface facing world direction `normal` with the environment turned `horizontal` and tilted `vertical` (radians) past the viewport's turn
pub fn irradiance(&self, normal: Vec3, horizontal: f32, vertical: f32) -> Vec3 {
let (sin_tilt, cos_tilt) = vertical.sin_cos();
let tilted = Vec3::new(normal.x, cos_tilt * normal.y - sin_tilt * normal.z, sin_tilt * normal.y + cos_tilt * normal.z);
// Turned as the viewport turns its environment
let (sin_turn, cos_turn) = (self.rotation + horizontal).sin_cos();
let direction = Vec3::new(cos_turn * tilted.x - sin_turn * tilted.z, tilted.y, sin_turn * tilted.x + cos_turn * tilted.z);
let light = sh_basis(direction).iter().zip(&self.coefficients).fold(Vec3::ZERO, |sum, (basis, coefficient)| sum + Vec3::from(*coefficient) * *basis);
light.max(Vec3::ZERO)
}
/// Baked Lighting Environment's lit base color: linear `albedo`, its metal read from `channels` (straight values by [`Channel::index`]), in `light` (the environment's diffuse light at the surface, exposure applied), darkened by ambient occlusion `ao` by `[diffuse, specular]` occlusion. The viewer looks straight at the surface, so what it reflects is the light around the normal
pub fn shade(albedo: [f32; 3], light: Vec3, ao: f32, [diffuse_occlusion, specular_occlusion]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] {
let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 };
let metal = finite_unit(channels.get(Channel::Metallic.index()).map_or(0.0, |m| m[0]));
let f0 = mix3([DIELECTRIC_REFLECTANCE; 3], albedo, metal);
let diffuse = 1.0 + (ao - 1.0) * finite_unit(diffuse_occlusion);
let specular = 1.0 + (ao - 1.0) * finite_unit(specular_occlusion);
let incoming = light.to_array();
std::array::from_fn(|k| finite_unit(albedo[k] * (1.0 - metal) * incoming[k] * diffuse + f0[k] * incoming[k] * specular))
}
}
/// The coefficients of built-in environment `name` as the viewport works them out: drawn at its width, then averaged
fn built_in_sh(name: &str) -> [[f32; 3]; 9] {
let (width, height) = (VIEWPORT_WIDTH, VIEWPORT_WIDTH / 2);
sh9_averaged(width, height, |x, y| radiance(name, dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// The coefficients of an imported equirect image, every texel averaged in as the viewport does
fn image_sh(image: &ImageRes) -> [[f32; 3]; 9] {
let linear = |v: f32| environment_linear(v, image.srgb);
sh9_averaged(image.width, image.height, |x, y| {
let texel = image.rgba.get((y as usize) * image.width as usize + x as usize).copied().unwrap_or([0.0; 4]);
Vec3::new(linear(texel[0]), linear(texel[1]), linear(texel[2]))
})
}
#[cfg(test)]
mod tests {
use super::*;
/// A uniform environment lights every direction alike, whatever the turn; brighter skies light more
#[test]
fn a_uniform_image_lights_every_way_alike() {
for (width, height) in [(1, 1), (32, 16)] {
let image = ImageRes::new(width, height, vec![[0.5, 0.5, 0.5, 1.0]; (width * height) as usize], false);
let sh = EnvironmentSh { coefficients: image_sh(&image), rotation: 1.0 };
for normal in [Vec3::Y, Vec3::X, Vec3::NEG_Y, Vec3::new(0.6, 0.0, 0.8)] {
let light = sh.irradiance(normal, 0.3, 0.7);
assert!((light - Vec3::splat(0.5)).abs().max_element() < 0.02, "{width}x{height} {normal}: {light}");
}
}
}
/// The studio's key light is up and to one side: a surface facing up gets more light than one facing down, and turning the environment moves the light around
#[test]
fn a_built_in_lights_by_where_the_surface_faces_and_turns() {
let display = DisplaySettings { environment: "Studio Soft".into(), ..DisplaySettings::default() };
let sh = EnvironmentSh::of(&display, &ImageStore::default());
assert!(sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum() > 2.0 * sh.irradiance(Vec3::NEG_Y, 0.0, 0.0).element_sum());
let side = Vec3::new(0.7, 0.0, 0.7).normalize();
let (here, turned) = (sh.irradiance(side, 0.0, 0.0), sh.irradiance(side, std::f32::consts::PI, 0.0));
assert!((here - turned).abs().max_element() > 0.05, "{here} vs {turned}");
let night = EnvironmentSh::of(&DisplaySettings { environment: "Night".into(), ..DisplaySettings::default() }, &ImageStore::default());
assert!(night.irradiance(Vec3::Y, 0.0, 0.0).element_sum() < sh.irradiance(Vec3::Y, 0.0, 0.0).element_sum(), "the cache follows the environment");
}
#[test]
fn replacing_an_imported_environment_releases_its_image() {
let display = DisplaySettings { environment: "resource:lighting".into(), ..DisplaySettings::default() };
for color in [[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]] {
let image = Arc::new(ImageRes::new(32, 16, vec![color; 32 * 16], false));
let image_identity = Arc::downgrade(&image);
let images = ImageStore::from([("lighting".into(), image)]);
let lighting = EnvironmentSh::of(&display, &images);
drop(images);
let irradiance = lighting.irradiance(Vec3::Y, 0.0, 0.0);
assert!(irradiance.distance(Vec3::new(color[0], color[1], color[2])) < 0.02);
assert!(image_identity.upgrade().is_none(), "lighting should release the decoded image with its store");
}
}
/// Tiles on the thread pool that ask for a new light finish: the light is worked out with the cache unlocked, so a worker that steals another tile while it waits for its share of the averaging never waits for its own lock
#[test]
fn tiles_asking_for_a_new_light_on_the_thread_pool_finish() {
use rayon::prelude::*;
const WORKERS: usize = 8;
const TILES: usize = 1024;
// One tile in so many asks for the light; the rest finish at once, so their workers are free to steal the averaging's work
const LIT_EVERY: usize = 128;
const ROUNDS: usize = 20;
const PATIENCE: std::time::Duration = std::time::Duration::from_secs(60);
let (done, finished) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let Ok(pool) = rayon::ThreadPoolBuilder::new().num_threads(WORKERS).build() else { return };
pool.install(|| {
for round in 0..ROUNDS {
// Each round shows another environment, so its first tile misses the cache
let environment = if round % 2 == 0 { "Sunset" } else { "Night" };
let display = DisplaySettings { environment: environment.into(), ..DisplaySettings::default() };
(0..TILES).into_par_iter().filter(|tile| tile % LIT_EVERY == 0).for_each(|_| {
EnvironmentSh::of(&display, &ImageStore::default());
});
}
});
let _ = done.send(());
});
assert!(finished.recv_timeout(PATIENCE).is_ok(), "the tiles deadlocked on the cache");
}
/// Diffuse occlusion darkens non-metals by the ambient occlusion; metals take their light from the reflections, which only specular occlusion darkens
#[test]
fn occlusion_darkens_the_diffuse_and_the_reflections_apart() {
let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect();
let light = Vec3::splat(1.0);
let dielectric = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert!(dielectric([1.0, 0.0]) < dielectric([0.0, 0.0]) * 0.5);
channels[Channel::Metallic.index()] = [1.0; 3];
let metal = |occlusion| EnvironmentSh::shade([0.5; 3], light, 0.2, occlusion, &channels)[0];
assert_eq!(metal([1.0, 0.0]), metal([0.0, 0.0]));
assert!(metal([0.0, 1.0]) < metal([0.0, 0.0]) * 0.5);
}
/// The coefficients of `radiance` read at every place of a fine grid, the integral the averaged ones must match
fn fine_sh(width: u32, radiance: impl Fn(Vec3) -> Vec3) -> [[f32; 3]; 9] {
let height = width / 2;
crate::environment_sky::sh9(width, height, |x, y| radiance(dir_of((x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32)))
}
/// Sunset's sun is smaller than a texel of a coarse grid: averaging the viewport's drawing keeps its light, as the viewport does
#[test]
fn a_small_sun_lights_as_the_viewport_shows_it() {
let display = DisplaySettings { environment: "Sunset".into(), ..DisplaySettings::default() };
let baked = EnvironmentSh::of(&display, &ImageStore::default()).coefficients;
let fine = fine_sh(1024, |direction| radiance("Sunset", direction));
for (baked, fine) in baked.iter().zip(&fine) {
for (baked, fine) in baked.iter().zip(fine) {
assert!((baked - fine).abs() < 0.02, "{baked} vs {fine}");
}
}
}
/// An imported image's small bright patch counts though it falls between the texels a coarse read would take
#[test]
fn a_small_bright_patch_of_an_image_counts() {
const BRIGHT: f32 = 500.0;
let (width, height) = (1024u32, 512u32);
let patch = |x: u32, y: u32| (97..101).contains(&x) && (193..197).contains(&y);
let rgba = (0..width * height).map(|i| if patch(i % width, i / width) { [BRIGHT, BRIGHT, BRIGHT, 1.0] } else { [0.0, 0.0, 0.0, 1.0] }).collect();
let image = ImageRes::new(width, height, rgba, false);
let averaged = image_sh(&image)[0][0];
let exact = crate::environment_sky::sh9(width, height, |x, y| if patch(x, y) { Vec3::splat(BRIGHT) } else { Vec3::ZERO })[0][0];
assert!(exact > 0.01 && (averaged - exact).abs() < exact * 0.05, "{averaged} vs {exact}");
}
}
+174
View File
@@ -0,0 +1,174 @@
//! The built-in environments (drawn in code, no image assets) and their diffuse light as spherical harmonics, for the viewport and Baked Lighting Environment
use std::f32::consts::{PI, TAU};
use rayon::prelude::*;
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::soft_box::SoftBox;
/// The width the viewport draws a built-in environment at (half as tall)
pub const VIEWPORT_WIDTH: u32 = 512;
/// The width an environment is box-averaged down to before its diffuse light is worked out: averaging keeps a sun smaller than a texel
const SH_WIDTH: u32 = 128;
/// The brightest radiance the viewport keeps of an imported environment (it stores half floats)
const HALF_FLOAT_MAX: f32 = 65_000.0;
/// The irradiance convolution factor of each SH band (the cosine lobe's π, 2π/3 and π/4), one per coefficient
const COSINE_LOBE_BANDS: [f32; 9] = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0];
/// The linear radiance of a component `v` of an imported environment's texel (sRGB-encoded when `srgb`): not a number is 0, capped at the half-float range, sRGB at 1
pub fn environment_linear(v: f32, srgb: bool) -> f32 {
let v = if v.is_finite() { v.clamp(0.0, HALF_FLOAT_MAX) } else { 0.0 };
if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v }
}
/// The direction at equirect place `u = φ / 2π`, `v = θ / π`: `(sin θ cos φ, cos θ, sin θ sin φ)`, row 0 straight up
pub fn dir_of(u: f32, v: f32) -> Vec3 {
let (theta, phi) = (v * PI, u * TAU);
Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
/// The equirect place of direction `d`
pub fn uv_of(d: Vec3) -> Vec2 {
let phi = d.z.atan2(d.x);
Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI)
}
/// Smoothstep of `t` over 0..1
pub(crate) fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// How fast a sky turns from its horizon to its zenith and to its ground (powers of the height; under 1 turns early)
const ZENITH_FALLOFF: f32 = 0.6;
const GROUND_FALLOFF: f32 = 0.25;
/// A sky blending `horizon` up to `zenith` and down to `ground`
fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(ZENITH_FALLOFF)) } else { horizon.lerp(ground, (-d.y).powf(GROUND_FALLOFF)) }
}
/// The Sunset sun's disc: the cosine of its edge from the centre, the width of its soft rim, and its brightness
const SUN_EDGE_COS: f32 = 0.9985;
const SUN_EDGE_WIDTH: f32 = 0.0012;
const SUN_RADIANCE: f32 = 120.0;
/// The light a built-in environment `name` sends from direction `d` (unknown names give the default studio)
pub fn radiance(name: &str, d: Vec3) -> Vec3 {
if name == "Sunset" {
let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05));
let sun_dir = dir_of(0.12, 0.47);
let sun = smooth((d.dot(sun_dir) - SUN_EDGE_COS) / SUN_EDGE_WIDTH) * SUN_RADIANCE;
return base + Vec3::new(1.0, 0.6, 0.3) * sun;
}
let (azimuth, elevation) = SoftBox::angles(d);
match name {
"Studio Contrast" => {
let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01));
base + SoftBox { azimuth: 35.0, elevation: 30.0, half_width: 22.0, half_height: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -150.0, elevation: 40.0, half_width: 6.0, half_height: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(azimuth, elevation)
}
"Overcast" => {
let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15));
base + SoftBox { azimuth: 60.0, elevation: 55.0, half_width: 40.0, half_height: 25.0, color: Vec3::splat(0.6) }.eval(azimuth, elevation)
}
"Warehouse" => {
let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06));
for k in 0..6 {
c += SoftBox { azimuth: -150.0 + k as f32 * 60.0, elevation: 50.0, half_width: 6.0, half_height: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }
.eval(azimuth, elevation);
}
c + SoftBox { azimuth: 90.0, elevation: 5.0, half_width: 30.0, half_height: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(azimuth, elevation)
}
"Night" => {
let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005));
base + SoftBox { azimuth: 20.0, elevation: 15.0, half_width: 10.0, half_height: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -110.0, elevation: 10.0, half_width: 12.0, half_height: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(azimuth, elevation)
}
// "Studio Soft" (default)
_ => {
let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07));
base + SoftBox { azimuth: 40.0, elevation: 35.0, half_width: 28.0, half_height: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(azimuth, elevation)
+ SoftBox { azimuth: -125.0, elevation: 20.0, half_width: 35.0, half_height: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(azimuth, elevation)
+ SoftBox { azimuth: 175.0, elevation: 55.0, half_width: 8.0, half_height: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(azimuth, elevation)
}
}
}
/// The 9 real spherical-harmonics basis functions at unit direction `d` (the standard band 0..2 constants)
pub fn sh_basis(d: Vec3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
}
/// Diffuse irradiance as 9 SH coefficients of the equirect image `width` x `height` whose texels `radiance` gives (already convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance)
pub fn sh9(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3) -> [[f32; 3]; 9] {
let (w, h) = (width.max(1), height.max(1));
// Sample each large texel across its angular footprint so a constant sky lights all directions
const MIN_COLUMNS: u32 = 32;
const MIN_ROWS: u32 = 16;
let samples_x = MIN_COLUMNS.div_ceil(w);
let samples_y = MIN_ROWS.div_ceil(h);
let (w, h) = (w * samples_x, h * samples_y);
let mut sums = [Vec3::ZERO; 9];
for y in 0..h {
let theta = PI * (y as f32 + 0.5) / h as f32;
let solid_angle = (TAU / w as f32) * (PI / h as f32) * theta.sin();
for x in 0..w {
let direction = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
// No firefly clamp: the projection integrates, so a bright sun lights diffuse fully
let weighted = radiance(x / samples_x, y / samples_y) * solid_angle;
for (sum, basis) in sums.iter_mut().zip(sh_basis(direction)) {
*sum += weighted * basis;
}
}
}
std::array::from_fn(|k| (sums[k] * COSINE_LOBE_BANDS[k] / PI).to_array())
}
/// [`sh9`] of the equirect image `width` x `height` whose texels `radiance` gives, box-halved while wider than [`SH_WIDTH`] (an odd last row or column is dropped, as the viewport drops it)
pub fn sh9_averaged(width: u32, height: u32, radiance: impl Fn(u32, u32) -> Vec3 + Sync) -> [[f32; 3]; 9] {
if width <= SH_WIDTH {
return sh9(width, height, radiance);
}
let mut image = half(width, height, radiance);
while image.0 > SH_WIDTH {
let (w, h, data) = &image;
image = half(*w, *h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO));
}
let (w, h, data) = image;
sh9(w, h, |x, y| data.get((y * w + x) as usize).copied().unwrap_or(Vec3::ZERO))
}
/// The equirect image `width` x `height` whose texels `texel` gives, box-downsampled by 2 (wrapping around, clamped at the poles): its width, height and texels
pub fn half(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> (u32, u32, Vec<Vec3>) {
let (w, h) = ((width / 2).max(1), (height / 2).max(1));
let get = |x: u32, y: u32| texel(x % width.max(1), y.min(height.saturating_sub(1)));
let mut data = vec![Vec3::ZERO; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, texel) in row.iter_mut().enumerate() {
let (sx, sy) = (x as u32 * 2, y as u32 * 2);
*texel = (get(sx, sy) + get(sx + 1, sy) + get(sx, sy + 1) + get(sx + 1, sy + 1)) * 0.25;
}
});
(w, h, data)
}
+2019 -188
View File
File diff suppressed because it is too large. Load diff
+41 -3
View File
@@ -1,11 +1,12 @@
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex, OnceLock};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use texturecraft_core::{FillSymmetry, LayerId, Project, Projection, Sampling};
use texturecraft_core::{FillSymmetry, Filter, LayerId, PreparedGradient, Project, Projection, Sampling};
use super::Inputs;
use crate::ProjectorDepthCache;
use crate::environment_sh::EnvironmentSh;
use crate::fill_depth::FillDepth;
use crate::pattern::mesh_frame;
use crate::projector_depth_cache::ViewDepth;
@@ -17,13 +18,33 @@ const MAX_EVALUATION_VIEWS: usize = 10;
pub(super) struct EvaluationInputs<'a> {
inputs: &'a Inputs<'a>,
projectors: &'a ProjectorDepthCache,
environment: OnceLock<EnvironmentSh>,
instance_draws: OnceLock<HashMap<(usize, LayerId), usize>>,
depth_maps: Mutex<Vec<ViewDepth>>,
gradients: Mutex<HashMap<usize, Arc<PreparedGradient>>>,
}
impl<'a> EvaluationInputs<'a> {
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
Self { inputs, projectors, instance_draws: OnceLock::new(), depth_maps: Mutex::new(Vec::new()) }
Self {
inputs,
projectors,
environment: OnceLock::new(),
instance_draws: OnceLock::new(),
depth_maps: Mutex::new(Vec::new()),
gradients: Mutex::default(),
}
}
pub(super) fn environment(&self) -> EnvironmentSh {
if let Some(environment) = self.environment.get() {
return *environment;
}
// Rayon may enter another plan while taking samples for the first one
let environment = EnvironmentSh::of(&self.project.display, self.images);
let _ = self.environment.set(environment);
environment
}
/// Each path through nested folder instances gets a stable identity within an evaluation.
@@ -65,6 +86,23 @@ impl<'a> EvaluationInputs<'a> {
depth_maps.push((key, depth.clone()));
depth
}
pub(super) fn gradient(&self, filter: &'a Filter) -> Option<Arc<PreparedGradient>> {
if !matches!(filter, Filter::GradientMap { linear: false, .. }) {
return None;
}
// The borrowed project keeps filter addresses stable for this evaluation
let key = std::ptr::from_ref(filter) as usize;
let mut gradients = self.gradients.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(prepared) = gradients.get(&key) {
return Some(Arc::clone(prepared));
}
let prepared = Arc::new(PreparedGradient::of(filter)?);
gradients.insert(key, Arc::clone(&prepared));
Some(prepared)
}
}
impl<'a> Deref for EvaluationInputs<'a> {
+8
View File
@@ -13,7 +13,10 @@ pub mod below;
mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
mod distance_envelope;
mod effect_histogram;
pub mod environment_sh;
pub mod environment_sky;
pub mod eval;
mod fabric;
pub mod fill_copies;
@@ -33,6 +36,9 @@ pub mod projector_cover;
pub mod projector_depth;
mod projector_depth_cache;
pub mod projector_view;
mod shape_distance;
mod slope_texel;
mod soft_box;
pub mod solo;
pub mod store;
pub mod thumb;
@@ -41,6 +47,8 @@ mod tile_pattern;
mod tile_random_stream;
mod timber;
pub mod warp;
mod warp_source_sample;
mod warp_texel;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
+402
View File
@@ -0,0 +1,402 @@
//! Filters drawn from the distance to the shapes' edge: Bevel, Bevel Smooth and Directional Distance
use rayon::prelude::*;
use texturecraft_core::{Bevel, BevelBlur, BevelCorner, DirectionalDistance, Filter, lum};
use crate::distance_envelope::DistanceEnvelope;
use crate::eval::{MIN_ALPHA, blur};
/// From a texel's centre to the edge between it and the nearest texel across: half a texel short of their centres' distance
const EDGE_OFFSET: f32 = 0.5;
/// Components of a texel with color and coverage (red, green, blue, alpha)
const RGBA_COMPONENTS: usize = 4;
/// Color components of a texel, before its alpha
const COLOR_COMPONENTS: usize = 3;
/// Where a texel's alpha sits among its components
const ALPHA_INDEX: usize = 3;
/// What a texel becomes from its index, whether it is inside the shapes and its own value
type TexelResult<'a> = dyn Fn(usize, bool, f32) -> f32 + Sync + 'a;
/// Lay distance filter `filter` over premultiplied `data` (`width` × `height` texels of `components`; content's shapes from its luminance), `tile_resolution` texels across a UV tile, mixed in by `opacity`; its Distance Map `grays` (0..1 a texel) scales the distance texel by texel
pub(crate) fn distance_filter(
data: &mut [f32],
(cover, grays): (&[f32], &[f32]),
components: usize,
(width, height): (usize, usize),
filter: &Filter,
tile_resolution: u32,
opacity: f32,
) {
let map = |texel: usize| grays.get(texel).copied().unwrap_or(1.0);
let value = |pixel: &[f32]| match pixel {
[r, g, b, alpha] if *alpha > MIN_ALPHA => lum([r / alpha, g / alpha, b / alpha]),
[value] => *value,
_ => 0.0,
};
let shapes = |inside: &(dyn Fn(f32) -> bool + Sync)| -> Vec<bool> {
data.par_chunks(components).zip(cover.par_iter()).map(|(pixel, covered)| *covered > 0.0 && inside(value(pixel))).collect()
};
let smoothed = |field: &mut [f32], texels: f32| {
let radius = texels.round() as usize;
if radius > 0 {
blur(field, width, height, radius);
}
};
// Per texel: whether it is inside the shapes, and what it becomes from its own value
let (inside, result): (Vec<bool>, Box<TexelResult<'_>>) = match filter {
Filter::DistanceBevel(bevel) => {
let inside = shapes(&|value| value >= Bevel::EDGE);
let edge = edge_distances(&inside, (width, height), bevel.corner == BevelCorner::Angular);
let reach = bevel.reach(tile_resolution);
let mut slope: Vec<f32> = inside.par_iter().zip(edge.par_iter()).map(|(inside, edge)| bevel.slope(*inside, *edge, reach)).collect();
drop(edge);
let smoothing_radius = bevel.smoothing_texels(tile_resolution).round() as usize;
if smoothing_radius > 0 {
match bevel.blur {
BevelBlur::Uniform => blur(&mut slope, width, height, smoothing_radius),
BevelBlur::NonUniform => {
let mut blurred = slope.clone();
blur(&mut blurred, width, height, smoothing_radius);
// Keep the foot sharp and blur the top at full strength
slope.par_iter_mut().zip(blurred).for_each(|(sharp, blurred)| *sharp += (blurred - *sharp) * *sharp);
}
}
}
let bevel = *bevel;
(inside, Box::new(move |texel, inside, value| bevel.apply(inside, value, slope.get(texel).copied().unwrap_or(1.0))))
}
Filter::BevelSmooth(smooth) => {
let inside = shapes(&|value| smooth.inside(value));
let edge = edge_distances(&inside, (width, height), false);
let (reach, curve) = (smooth.reach(tile_resolution), smooth.curve());
let mut ramp: Vec<f32> = inside
.par_iter()
.zip(edge.par_iter())
.enumerate()
.map(|(texel, (inside, edge))| smooth.value(curve, *inside, *edge, reach * map(texel)))
.collect();
drop(edge);
smoothed(&mut ramp, smooth.smoothing_texels(tile_resolution));
(inside, Box::new(move |texel, _, value| ramp.get(texel).copied().unwrap_or(value)))
}
Filter::DirectionalDistance(trail) => {
let inside = shapes(&|value| value >= DirectionalDistance::EDGE);
let along = trail_distances(&inside, (width, height), crate::eval::direction(trail.angle), trail.reach(tile_resolution));
let trail = *trail;
// A share of the full reach is a larger share of a texel's shorter one; no trail where the map is black, the shapes stay
let shortened = move |texel: usize| {
along.get(texel).copied().flatten().and_then(|along| match map(texel) {
_ if along <= 0.0 => Some(0.0),
gray if gray > 0.0 => Some(along / gray),
_ => None,
})
};
(inside, Box::new(move |texel, _, _| trail.value(shortened(texel).filter(|along| *along <= 1.0))))
}
_ => return,
};
let has_alpha = components == RGBA_COMPONENTS;
data.par_chunks_mut(components).zip(inside.par_iter()).zip(cover.par_iter()).enumerate().for_each(|(texel, ((pixel, inside), covered))| {
if *covered <= 0.0 {
return;
}
// Content is premultiplied by its coverage, which stays
let coverage = if has_alpha { pixel.get(ALPHA_INDEX).copied().unwrap_or(0.0) } else { 1.0 };
for slot in pixel.iter_mut().take(components.min(COLOR_COMPONENTS)) {
let before = if has_alpha { if coverage > MIN_ALPHA { *slot / coverage } else { 0.0 } } else { *slot };
let after = result(texel, *inside, before);
*slot = (before + (after - before) * opacity) * coverage;
}
});
}
/// Every texel's distance (texels) to the edge between it and the nearest texel on the other side of the shapes `inside`: straight-line, or the larger axis distance when `angular`
fn edge_distances(inside: &[bool], (width, height): (usize, usize), angular: bool) -> Vec<f32> {
let distances = if angular { chessboard_distances } else { straight_distances };
let mut to_inside = distances(inside, (width, height), true);
let to_outside = distances(inside, (width, height), false);
to_inside
.par_iter_mut()
.zip(to_outside)
.zip(inside)
.for_each(|((to_inside, to_outside), inside)| *to_inside = (if *inside { to_outside } else { *to_inside } - EDGE_OFFSET).max(0.0));
to_inside
}
/// Each texel's straight-line distance to the nearest texel on the requested side.
fn straight_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
// Start beyond the region so a line without a feature stays out of reach
let far = ((width + height) as f32).powi(2);
let mut rows: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
rows.par_chunks_mut(width.max(1)).for_each_init(DistanceEnvelope::default, |envelope, row| envelope.lower(row));
let mut columns: Vec<f32> = (0..width * height).map(|at| rows.get((at % height.max(1)) * width + at / height.max(1)).copied().unwrap_or(far)).collect();
columns.par_chunks_mut(height.max(1)).for_each_init(DistanceEnvelope::default, |envelope, column| envelope.lower(column));
// Reuse the row buffer for the final distances in row-major order
rows.resize(width * height, far);
for (index, distance) in rows.iter_mut().enumerate() {
*distance = columns.get((index % width.max(1)) * height + index / width.max(1)).copied().unwrap_or(far).sqrt();
}
rows
}
/// Each texel's distance to the nearest texel on the requested side, measured along the larger axis.
fn chessboard_distances(inside: &[bool], (width, height): (usize, usize), target_side: bool) -> Vec<f32> {
let far = (width + height) as f32;
let mut distances: Vec<f32> = inside.iter().map(|inside| if *inside == target_side { 0.0 } else { far }).collect();
// One pass down from the texels above and left, one up from those below and right
let step = |distances: &mut [f32], (x, y): (usize, usize), neighbours: [(isize, isize); 4]| {
let nearest = neighbours
.iter()
.filter_map(|(dx, dy)| {
let (neighbour_x, neighbour_y) = (x.checked_add_signed(*dx)?, y.checked_add_signed(*dy)?);
(neighbour_x < width && neighbour_y < height).then(|| distances.get(neighbour_y * width + neighbour_x).copied()).flatten()
})
.fold(f32::MAX, f32::min);
if let Some(slot) = distances.get_mut(y * width + x) {
*slot = slot.min(nearest + 1.0);
}
};
for y in 0..height {
for x in 0..width {
step(&mut distances, (x, y), [(-1, 0), (-1, -1), (0, -1), (1, -1)]);
}
}
for y in (0..height).rev() {
for x in (0..width).rev() {
step(&mut distances, (x, y), [(1, 0), (1, 1), (0, 1), (-1, 1)]);
}
}
distances
}
/// For every texel, how far (a share of `reach` texels) the nearest texel of the shapes `inside` lies behind it against `direction`, if one is in reach
fn trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let steps = trail_steps((width, height), direction, reach);
// Each row of shapes as bits, a row without one as no words: steps landing on it find nothing
let shapes: Vec<Vec<u64>> = inside.par_chunks(width.max(1)).map(row_bits).collect();
let mut distances = vec![None; width * height];
distances.par_chunks_mut(width.max(1)).enumerate().for_each(|(y, row)| trail_row(row, y, &shapes, &steps));
distances
}
/// The texel steps back along a trail against `direction`, nearest first, each with its share of `reach`: texel coordinates are whole, so every texel takes the same steps
fn trail_steps((width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<(isize, isize, f32)> {
// Steps of one texel along the direction's longer axis visit every column (or row) the trail crosses, so no thin shape is stepped over
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
let mut steps: Vec<(isize, isize, f32)> = Vec::new();
for sample in 0..=samples {
let back = sample as f32 * step;
// Rounded half up, so a whole texel coordinate added to it rounds the same; a NaN direction lands nowhere
let (across, down) = ((0.5 - direction[0] * back).floor(), (0.5 - direction[1] * back).floor());
if !(across.is_finite() && down.is_finite()) {
break;
}
// A step as long as the region leaves it from every texel, and never comes back in
let (across, down) = (across as isize, down as isize);
if across.unsigned_abs() >= width || down.unsigned_abs() >= height {
break;
}
// Rounding puts several samples on one texel: the nearest counts
if steps.last().is_some_and(|(last_across, last_down, _)| (*last_across, *last_down) == (across, down)) {
continue;
}
steps.push((across, down, if reach > 0.0 { back / reach } else { 0.0 }));
}
steps
}
/// A row of shapes as bits, [`u64::BITS`] texels a word; no words when it has none
fn row_bits(row: &[bool]) -> Vec<u64> {
if !row.contains(&true) {
return Vec::new();
}
let mut words = vec![0u64; row.len().div_ceil(WORD_BITS)];
for (word, texels) in words.iter_mut().zip(row.chunks(WORD_BITS)) {
*word = texels.iter().enumerate().filter(|(_, inside)| **inside).fold(0, |bits, (bit, _)| bits | 1 << bit);
}
words
}
/// Texels in a word of a row's bits
const WORD_BITS: usize = u64::BITS as usize;
/// Row `y`'s trail distances into `row`: a step at a time, every texel the step brings onto a shape takes its share, unless an earlier step did
fn trail_row(row: &mut [Option<f32>], y: usize, shapes: &[Vec<u64>], steps: &[(isize, isize, f32)]) {
let width = row.len();
let mut found = vec![0u64; width.div_ceil(WORD_BITS)];
let mut unfound = width;
// The last word's bits past the row's end are no texels
let last_word = found.len().saturating_sub(1);
let tail = width % WORD_BITS;
let last_word_texels = if tail > 0 { (1u64 << tail) - 1 } else { u64::MAX };
for (across, down, share) in steps {
// A step past the region's top or bottom leaves it for good
let Some(source) = y.checked_add_signed(*down).and_then(|source_y| shapes.get(source_y)) else { break };
if source.is_empty() {
continue;
}
for (word, found_word) in found.iter_mut().enumerate() {
let in_row = if word == last_word { last_word_texels } else { u64::MAX };
let landed = bits_from(source, (word * WORD_BITS) as isize + across) & !*found_word & in_row;
*found_word |= landed;
let mut remaining = landed;
while remaining != 0 {
let bit = remaining.trailing_zeros() as usize;
remaining &= remaining - 1;
if let Some(slot) = row.get_mut(word * WORD_BITS + bit) {
*slot = Some(*share);
}
unfound = unfound.saturating_sub(1);
}
}
if unfound == 0 {
break;
}
}
}
/// The [`WORD_BITS`] bits of row bits `source` from texel `start` on, none past either end
fn bits_from(source: &[u64], start: isize) -> u64 {
let bits = WORD_BITS as isize;
let (word, shift) = (start.div_euclid(bits), start.rem_euclid(bits) as u32);
let at = |index: isize| usize::try_from(index).ok().and_then(|index| source.get(index)).copied().unwrap_or(0);
let low = at(word) >> shift;
if shift == 0 { low } else { low | at(word + 1) << (u64::BITS - shift) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn distances_are_straight_or_chessboard() {
// One feature texel in the middle of a 5 × 5 region
let mut feature = vec![false; 25];
feature[12] = true;
let straight = straight_distances(&feature, (5, 5), true);
let chessboard = chessboard_distances(&feature, (5, 5), true);
assert_eq!((straight[12], straight[13], chessboard[13]), (0.0, 1.0, 1.0));
assert!((straight[0] - 8f32.sqrt()).abs() < 1e-5, "{}", straight[0]);
assert_eq!(chessboard[0], 2.0, "a corner is as far as its larger axis");
let none = straight_distances(&[false; 4], (2, 2), true);
assert!(none.iter().all(|distance| *distance >= 4.0), "no feature is beyond the region");
}
#[test]
fn distances_keep_rows_and_columns_apart_in_a_region_wider_than_tall() {
// One feature texel at column 1, row 0 of a 7 × 3 region
let (width, height) = (7, 3);
let mut feature = vec![false; width * height];
feature[1] = true;
let straight = straight_distances(&feature, (width, height), true);
let chessboard = chessboard_distances(&feature, (width, height), true);
let at = |x: usize, y: usize| y * width + x;
assert_eq!((straight[at(1, 0)], straight[at(6, 0)], straight[at(1, 2)]), (0.0, 5.0, 2.0));
assert!((straight[at(6, 2)] - 29f32.sqrt()).abs() < 1e-5, "{}", straight[at(6, 2)]);
assert_eq!((chessboard[at(6, 0)], chessboard[at(0, 2)], chessboard[at(6, 2)]), (5.0, 2.0, 5.0));
}
#[test]
fn a_trail_finds_the_nearest_shape_behind_a_texel_as_a_share_of_its_reach() {
// A shape at column 0 of a 5 × 2 region; the trail runs towards +x, so a texel looks back towards -x
let (width, height) = (5, 2);
let inside: Vec<bool> = (0..width * height).map(|texel| texel % width == 0).collect();
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], 4.0);
assert_eq!(trail[0], Some(0.0), "on the shape");
assert_eq!(trail[2], Some(0.5), "two texels behind, half the reach");
assert_eq!(trail[width + 4], Some(1.0), "at the reach's end");
}
#[test]
fn a_long_trail_steps_over_no_thin_shape() {
// A one-texel shape at column 0 of an 8 × 1 region, with a reach far longer than the region
let (width, height) = (8, 1);
let inside: Vec<bool> = (0..width * height).map(|texel| texel == 0).collect();
let reach = 128.0;
let trail = trail_distances(&inside, (width, height), [1.0, 0.0], reach);
assert_eq!(trail[3], Some(3.0 / reach), "three texels behind");
assert!(trail.iter().all(Option::is_some), "every texel behind the shape is in its trail: {trail:?}");
}
/// The trail as every texel walks it on its own, one sample at a time: what the shared steps must match
fn walked_trail_distances(inside: &[bool], (width, height): (usize, usize), direction: [f32; 2], reach: f32) -> Vec<Option<f32>> {
let longer_axis = direction[0].abs().max(direction[1].abs());
let samples = if reach > 0.0 && longer_axis > 0.0 { (reach * longer_axis).ceil() as usize } else { 0 };
let step = if samples > 0 { reach / samples as f32 } else { 0.0 };
(0..width * height)
.into_par_iter()
.map(|texel| {
let (x, y) = ((texel % width) as f32, (texel / width) as f32);
(0..=samples)
.map(|sample| {
let back = sample as f32 * step;
(back, (x - direction[0] * back + 0.5).floor(), (y - direction[1] * back + 0.5).floor())
})
.take_while(|(_, sample_x, sample_y)| *sample_x >= 0.0 && *sample_y >= 0.0 && (*sample_x as usize) < width && (*sample_y as usize) < height)
.find_map(|(back, sample_x, sample_y)| inside[sample_y as usize * width + sample_x as usize].then(|| back / reach))
})
.collect()
}
#[test]
fn shared_trail_steps_find_what_each_texel_walking_its_own_finds() {
// Sparse rows end partway through a word
// Keep the region small enough to avoid rounding nearly tied rays into different texels
let (width, height) = (150, 97);
let mut seed = 12345u32;
let inside: Vec<bool> = (0..width * height)
.map(|_| {
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(seed >> 16) % 97 < 2
})
.collect();
for angle in [0.0, 17.0, 45.0, 90.0, 135.0, 200.0, 290.0, 333.0] {
for reach in [9.3, 60.0, 400.0] {
let direction = crate::eval::direction(angle);
let shared = trail_distances(&inside, (width, height), direction, reach);
let walked = walked_trail_distances(&inside, (width, height), direction, reach);
assert!(walked.iter().any(Option::is_some) && walked.iter().any(Option::is_none), "{angle}° {reach}: a field with texels in and out of reach");
assert_eq!(shared, walked, "{angle}° reach {reach}");
}
}
}
}
+46
View File
@@ -0,0 +1,46 @@
//! What a Blur Slope filter reads for one texel: its source's slope, then the values downhill of it
use texturecraft_core::{SlopeBlending, SourceSlopeBlur, SourceWarp};
use crate::eval::LINE_SAMPLES;
use crate::warp_source_sample::WarpSourceSample;
use crate::warp_texel::{Input, Sample, keep_extreme_read};
/// A source rising less than this across a texel is flat
const FLAT_STEEPNESS: f32 = 1e-6;
/// Blur Slope `slope` at texel `(x, y)` into `acc`: the reads downhill of it, blended
pub(crate) fn slope_texel(
slope: &SourceSlopeBlur,
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&slope.source, slope.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let probe = SourceWarp::probe_texels(res);
let downhill = [source.at(x - probe, y) - source.at(x + probe, y), source.at(x, y - probe) - source.at(x, y + probe)];
let steepness = downhill[0].hypot(downhill[1]);
// A flat spot keeps its value
if steepness.is_nan() || steepness <= FLAT_STEEPNESS {
sample(x, y, acc);
return;
}
let [dx, dy] = downhill.map(|rise| rise / steepness);
let reach = slope.move_texels(res);
let read_count = slope.samples((reach.ceil() as u32).clamp(1, LINE_SAMPLES.unsigned_abs()));
let step = reach / read_count as f32;
let along = (0..=read_count).map(|read| read as f32 * step);
if slope.blending == SlopeBlending::Blur {
for t in along {
sample(x + dx * t, y + dy * t, acc);
}
return;
}
let reads = along.map(|t| (x + dx * t, y + dy * t));
keep_extreme_read(reads, slope.blending == SlopeBlending::Max, comps, acc, sample);
}
+35
View File
@@ -0,0 +1,35 @@
//! A soft rectangular light of the built-in environments
use texturecraft_geom::glam::Vec3;
/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees)
pub(crate) struct SoftBox {
pub azimuth: f32,
pub elevation: f32,
pub half_width: f32,
pub half_height: f32,
pub color: Vec3,
}
/// Where the light starts to fade, as a share of its half size, and over how much of it
const EDGE_FADE_START: f32 = 0.8;
const EDGE_FADE_WIDTH: f32 = 0.4;
impl SoftBox {
/// Convert the sampled direction to degrees once for all the lights
pub fn angles(direction: Vec3) -> (f32, f32) {
let elevation = direction.y.clamp(-1.0, 1.0).asin().to_degrees();
let azimuth = direction.z.atan2(direction.x).to_degrees();
(azimuth, elevation)
}
/// The light the box sends along the sampled azimuth and elevation
pub fn eval(&self, azimuth: f32, elevation: f32) -> Vec3 {
// The azimuth difference wrapped to -180..180 degrees
let azimuth_step = ((azimuth - self.azimuth + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (azimuth_step.abs() / self.half_width, (elevation - self.elevation).abs() / self.half_height);
let edge = |t: f32| 1.0 - crate::environment_sky::smooth((t - EDGE_FADE_START) / EDGE_FADE_WIDTH);
self.color * edge(x) * edge(y)
}
}
+127
View File
@@ -0,0 +1,127 @@
//! A warp's or slope blur's source as read around one texel
use texturecraft_core::{WarpSource, WarpSourceMode, lum};
use crate::eval::{MIN_ALPHA, texel_noise};
use crate::warp_texel::{Input, MIN_READ_WEIGHT, Sample};
/// A warp's or slope blur's source at one texel's neighbourhood
pub(crate) struct WarpSourceSample<'a> {
source: &'a WarpSource,
/// The default noise's seed
seed: u32,
res: u32,
comps: usize,
sample: Sample<'a>,
input: Input<'a>,
/// Half the texels the source is blurred across, worked out once per texel
half_blur: f32,
tiling: f32,
tile_origin: [f32; 2],
tile_size: [f32; 2],
}
impl<'a> WarpSourceSample<'a> {
/// Read the source around `texel`. Atlas blocks retain their full stride even when a UV tile has fewer texels.
pub(crate) fn new(
source: &'a WarpSource,
seed: u32,
texel: [f32; 2],
(res, comps): (u32, usize),
(block_size, tile_size): ([u32; 2], [u32; 2]),
(sample, input): (Sample<'a>, Input<'a>),
) -> Self {
let tiling = source.tiling_factor();
let tile_origin = if source.mode != WarpSourceMode::DefaultNoise && tiling != 1.0 {
std::array::from_fn(|axis| {
let stride = block_size[axis].max(1) as f32;
(texel[axis] / stride).floor() * stride
})
} else {
[0.0; 2]
};
Self {
source,
seed,
res,
comps,
sample,
input,
half_blur: source.blur_texels(res) / 2.0,
tiling,
tile_origin,
tile_size: tile_size.map(|size| size.max(1) as f32),
}
}
/// The source at texel position `(x, y)` after its blur, Balance and Contrast
pub(crate) fn at(&self, x: f32, y: f32) -> f32 {
let half = self.half_blur;
let value = if half > 0.0 {
let corners = [(-half, -half), (half, -half), (-half, half), (half, half)];
let (sum, count) = corners.iter().filter_map(|(dx, dy)| self.raw(x + dx, y + dy)).fold((0.0f32, 0u8), |(sum, count), read| (sum + read, count + 1));
if count == 0 { WarpSource::MID_GRAY } else { sum / f32::from(count) }
} else {
self.raw(x, y).unwrap_or(WarpSource::MID_GRAY)
};
self.source.shape(value)
}
/// The source at texel position `(x, y)` before it is shaped; None where the values it filters cover nothing
fn raw(&self, x: f32, y: f32) -> Option<f32> {
if self.source.mode == WarpSourceMode::DefaultNoise {
return Some(WarpSource::stretch_noise(texel_noise(x, y, [0.0; 2], self.res, self.source.noise_scale(), self.seed)));
}
let [x, y] = if self.tiling == 1.0 {
[x, y]
} else {
let repeat = |axis: usize, position: f32| {
let origin = self.tile_origin[axis];
let size = self.tile_size[axis];
let repeated = ((position - origin + 0.5) * self.tiling).rem_euclid(size) - 0.5;
// Keep the bilinear taps in this UV tile at the ends of each repeat
origin + repeated.clamp(0.0, size - 1.0)
};
[repeat(0, x), repeat(1, y)]
};
if self.source.mode == WarpSourceMode::CustomNoise {
return (self.input)(x, y);
}
let mut read = [0.0f32; 5];
(self.sample)(x, y, &mut read);
match (self.comps, read) {
// Content stays premultiplied by its own coverage
(4, [r, g, b, alpha, _]) if alpha > MIN_ALPHA => Some(lum([r / alpha, g / alpha, b / alpha])),
(1, [value, .., weight]) if weight > MIN_READ_WEIGHT => Some(value / weight),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tiled_input_reads_stay_within_the_current_atlas_block() {
let source = WarpSource { mode: WarpSourceMode::CustomNoise, tiling: 2.0, ..WarpSource::LIBRARY };
let sample = |_x, _y, _read: &mut [f32; 5]| {};
let input = |x: f32, y: f32| {
assert!((64.0..=95.0).contains(&x) && (128.0..=159.0).contains(&y), "read at {x}, {y}");
Some(((x - 64.0) + (y - 128.0)) / 64.0)
};
let tiled = WarpSourceSample::new(&source, 0, [94.0, 158.0], (32, 1), ([64; 2], [32; 2]), (&sample, &input));
let first_repeat = tiled.at(69.0, 135.0);
let second_repeat = tiled.at(85.0, 151.0);
assert_eq!(first_repeat, second_repeat);
assert_ne!(tiled.at(70.0, 135.0), first_repeat);
assert!(tiled.at(63.0, 160.0).is_finite());
}
}
+80
View File
@@ -0,0 +1,80 @@
//! What a Warp filter reads for one texel: its source, then the moves its mode makes
use texturecraft_core::{SourceWarp, WarpBlending, WarpMode};
use crate::warp_source_sample::WarpSourceSample;
/// Bilinear sample at an absolute texel position into an accumulator (components, then weight), as [`crate::eval`]'s gather reads
pub(crate) type Sample<'a> = &'a dyn Fn(f32, f32, &mut [f32; 5]);
/// The filter's Custom Noise image input at an absolute texel position; None where the values it filters cover nothing
pub(crate) type Input<'a> = &'a dyn Fn(f32, f32) -> Option<f32>;
/// A read weighing less than this covers nothing
pub(crate) const MIN_READ_WEIGHT: f32 = 1e-6;
/// Warp `warp` at texel `(x, y)` into `acc`: where its source sends it, or those reads blended
pub(crate) fn warp_texel(
(warp, directions): (&SourceWarp, &[[f32; 2]]),
(x, y): (f32, f32),
(res, comps): (u32, usize),
tile_sizes: ([u32; 2], [u32; 2]),
acc: &mut [f32; 5],
(sample, input): (Sample<'_>, Input<'_>),
) {
let source = WarpSourceSample::new(&warp.source, warp.seed, [x, y], (res, comps), tile_sizes, (sample, input));
let reach = warp.move_texels(res);
if warp.mode == WarpMode::Warp {
let probe = SourceWarp::probe_texels(res);
let rise = [source.at(x + probe, y) - source.at(x - probe, y), source.at(x, y + probe) - source.at(x, y - probe)];
let [dx, dy] = warp.slope_move(rise, res);
sample(x + dx, y + dy, acc);
return;
}
let directions = directions.iter().copied();
let displacement = |at_x, at_y| SourceWarp::amount(source.at(at_x, at_y)) * reach;
if warp.mode == WarpMode::MultiDirectional && warp.blending == WarpBlending::Chain {
let (end_x, end_y) = directions.fold((x, y), |(at_x, at_y), [dx, dy]| {
let along = displacement(at_x, at_y);
(at_x + dx * along, at_y + dy * along)
});
sample(end_x, end_y, acc);
return;
}
// Independent directions share the source at the original texel
let along = displacement(x, y);
let reads = directions.map(|[dx, dy]| (x + dx * along, y + dy * along));
if warp.mode == WarpMode::MultiDirectional && matches!(warp.blending, WarpBlending::Max | WarpBlending::Min) {
keep_extreme_read(reads, warp.blending == WarpBlending::Max, comps, acc, sample);
} else {
for (at_x, at_y) in reads {
sample(at_x, at_y, acc);
}
}
}
/// Keeps in `acc` the largest (or smallest) of the reads at `positions`, component by component; reads that cover nothing are skipped
pub(crate) fn keep_extreme_read(positions: impl Iterator<Item = (f32, f32)>, larger: bool, comps: usize, acc: &mut [f32; 5], sample: Sample<'_>) {
let mut picked: Option<[f32; 5]> = None;
for (at_x, at_y) in positions {
let mut read = [0.0f32; 5];
sample(at_x, at_y, &mut read);
if read[4] <= MIN_READ_WEIGHT {
continue;
}
let read = read.map(|component| component / read[4]);
picked = Some(match picked {
Some(so_far) => std::array::from_fn(|k| if larger { so_far[k].max(read[k]) } else { so_far[k].min(read[k]) }),
None => read,
});
}
if let Some(picked) = picked {
let kept = comps.min(4);
acc[..kept].copy_from_slice(&picked[..kept]);
acc[4] = 1.0;
}
}
+94 -22
View File
@@ -7,9 +7,11 @@ use std::collections::BTreeMap;
use texturecraft_compose::{
BelowCache, Composite, Inputs, MaskGray, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached,
};
use texturecraft_core::project::ENV_RESOURCE_PREFIX;
use texturecraft_core::{
BakedMap, BlendMode, Channel, ColorSelection, CompareOp, CompareSource, ContentsOffset, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind,
HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
GrayscaleConversion, HeightMask, ImageInput, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, TileImage, to_u16};
@@ -74,7 +76,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position))));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask));
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
for b in f.project.layer_mut(group).unwrap().channels.values_mut() {
@@ -88,7 +90,7 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 })));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0, wrap: false })));
let top = add(f, 0, LayerKind::Paint, Some(blurred));
let img = f.pixels.layer_mut(top, Channel::BaseColor, (RES, RES));
for y in 40..200 {
@@ -253,7 +255,7 @@ fn generator_mask(f: &mut Fixture, kind: GeneratorKind, blur: Option<f32>) -> Ma
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(g)));
if let Some(radius) = blur {
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius })));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius, wrap: false })));
}
mask
}
@@ -317,8 +319,8 @@ fn nested_stack(f: &mut Fixture) -> Nested {
blend(f, g2_above, BlendMode::Overlay, 0.7);
put(f, 0, Some(g2), LayerKind::Instance { source: base }, Some(Mask::new(MaskBackground::White)));
let g1_above = put(f, 0, Some(g1), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Wood, 0.2, 0.8))]), None);
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0 }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0 }));
let hsl = effect(f, EffectKind::Filter(Filter::Hsl { hue: 0.2, saturation: 0.1, lightness: 0.0, perceptive: false }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 20.0, wrap: false }));
f.project.layer_mut(g1_above).unwrap().content_effects.extend([hsl, blur]);
blend(f, g1_above, BlendMode::Screen, 0.5);
let mask = generator_mask(f, GeneratorKind::Position, Some(30.0));
@@ -549,7 +551,7 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
// Behind a blur the cut reads the filtered field; before it, the unfiltered content
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0, wrap: false }));
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
let blurred = reference(&f, 0);
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
@@ -577,12 +579,12 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
&mut f,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1, divider: 1 })));
let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
let top = add(&mut f, 0, LayerKind::Paint, None);
paint_rect(&mut f, top, (30, 40), (150, 100), 0.4);
let plain = reference(&f, 0);
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 }));
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3, divider: 1 }));
f.project.layer_mut(base).unwrap().content_effects.push(warp);
let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 }));
f.project.layer_mut(streaks).unwrap().content_effects.push(line);
@@ -676,7 +678,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
// Changing the hot mask must invalidate the retained fields
let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap();
let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap();
blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0 });
blur.kind = EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false });
let (images, baked) = (Default::default(), Default::default());
cache.ahead = Vec::new();
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
@@ -715,7 +717,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
&mut fixture,
EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default(), sampling: Default::default() },
));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0, wrap: false })));
add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred));
// Keep the blurred layer visible under the hot layer
@@ -963,30 +965,90 @@ fn flat_image(value: f32) -> std::sync::Arc<texturecraft_compose::ImageRes> {
}
#[test]
fn id_map_image_changes_invalidate_stack_key() {
fn filter_input_and_id_map_image_changes_invalidate_stack_key() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let conversion = GrayscaleConversion { custom_input: true, ..GrayscaleConversion::LIBRARY };
let mut filter = effect(&mut fixture, EffectKind::Filter(Filter::GrayscaleConversion(conversion)));
filter.inputs.insert(ImageInput::CUSTOM_INPUT.id.into(), Source::image("input"));
let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1);
selection.id_map = Some("id".into());
let selection = effect(&mut fixture, EffectKind::ColorSelection(selection));
let layer = fixture.project.layer_mut(bottom_layer).unwrap();
layer.content_effects.push(filter);
layer.mask = Some(Mask::new(MaskBackground::White));
layer.mask.as_mut().unwrap().effects.push(selection);
let mut images = texturecraft_compose::ImageStore::default();
images.insert("input".into(), flat_image(0.1));
images.insert("id".into(), flat_image(0.1));
let original = stack_key(&fixture, &images);
images.insert("id".into(), flat_image(0.9));
for name in ["input", "id"] {
let original = stack_key(&fixture, &images);
images.insert(name.into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != original, "replacing the id image must invalidate the cache");
assert!(stack_key(&fixture, &images) != original, "replacing the {name} image must invalidate the cache");
}
}
#[test]
fn the_environment_keys_the_stack_only_while_environment_lighting_reads_it() {
let mut fixture = fixture();
heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let mut images = texturecraft_compose::ImageStore::default();
images.insert("sky".into(), flat_image(0.5));
fixture.project.display.environment = format!("{ENV_RESOURCE_PREFIX}sky");
let unlit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
assert_eq!(stack_key(&fixture, &images), unlit, "without Baked Lighting Environment the turn changes nothing");
let lighting =
Filter::EnvironmentLighting { horizontal: 0.0, vertical: 0.0, exposure: 0.0, height_intensity: 0.0, ambient_occlusion: 0.0, specular_occlusion: 0.0 };
let lighting = effect(&mut fixture, EffectKind::Filter(lighting));
fixture.project.layer_mut(bottom_layer).unwrap().content_effects.push(lighting);
let lit = stack_key(&fixture, &images);
fixture.project.display.env_rotation += 90.0;
let turned = stack_key(&fixture, &images);
assert!(turned != lit, "turning the environment invalidates the cache");
assert_eq!(lit.changed_tiles(&turned), None, "and recomposites every tile");
images.insert("sky".into(), flat_image(0.9));
assert!(stack_key(&fixture, &images) != turned, "replacing the environment image invalidates the cache");
}
#[test]
fn painting_metallic_updates_validation_on_a_layer_above_it() {
let mut fixture = fixture();
let metal = add(&mut fixture, 0, LayerKind::Paint, None);
let color = add(&mut fixture, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.12; 3]))]), None);
let color_layer = fixture.project.layer_mut(color).unwrap();
color_layer.channels.retain(|channel, _| *channel == Channel::BaseColor);
let validation = effect(&mut fixture, EffectKind::Filter(Filter::PbrValidate(texturecraft_core::PbrValidate::LIBRARY)));
fixture.project.layer_mut(color).unwrap().content_effects.push(validation);
let mut cache = BelowCache::default();
cache.set_hot(Some(metal));
let coordinate = RES / 2;
let tiles = [(coordinate / TILE, coordinate / TILE)];
let before = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
fixture.pixels.layer_mut(metal, Channel::Metallic, (RES, RES)).set(coordinate, coordinate, &[u16::MAX; 2]);
let fresh = run(&fixture, 0, &tiles, None).value(Channel::BaseColor, coordinate, coordinate);
let updated = run(&fixture, 0, &tiles, Some(&mut cache)).value(Channel::BaseColor, coordinate, coordinate);
assert_ne!(fresh, before, "the same color is valid for a dielectric and too dark for a metal");
assert_eq!(updated, fresh, "replaying the stack must reevaluate material-dependent validation");
}
/// A folder of set `ts` holding a Clouds fill whose content or mask is blurred by 8; returns the folder and the fill
fn folder_of_blurred_clouds(f: &mut Fixture, ts: usize, folder: Option<LayerId>, blur_on: BlurOn) -> (LayerId, LayerId) {
let held = put(f, ts, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None);
let clouds = put(f, ts, Some(held), fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None);
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0 }));
let blur = effect(f, EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }));
match blur_on {
BlurOn::Content => f.project.layer_mut(clouds).unwrap().content_effects.push(blur),
BlurOn::Mask => {
@@ -1123,7 +1185,7 @@ fn compare_uses_the_stack_below_each_draw_of_an_instanced_folder() {
let folder = add(&mut fixture, 0, LayerKind::folder(), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::LayersBelow));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 32.0 })));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 32.0, wrap: false })));
let red = fill(&[(Channel::BaseColor, Source::Uniform([1.0, 0.0, 0.0]))]);
put(&mut fixture, 0, Some(folder), red, Some(mask));
add(&mut fixture, 0, base(0.9), None);
@@ -1164,19 +1226,29 @@ fn sparse_compare_mask_reads_filtered_content_through_the_full_blur_radius() {
fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, SIZE);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(roughness_compare(&mut fixture, CompareSource::ThisLayer));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 256.0 })));
mask.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 256.0, wrap: false })));
let roughness = fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]);
let layer = add(&mut fixture, 0, roughness, Some(mask));
let edge = effect(&mut fixture, EffectKind::Filter(Filter::EdgeDetect { width: 8.0 }));
fixture.project.layer_mut(layer).unwrap().content_effects.push(edge);
let (images, baked) = (Default::default(), Default::default());
let inputs = inputs(&fixture, 0, &images, &baked);
let center = SIZE / 2;
let full = mask_texels(&inputs, layer).unwrap();
let tile = mask_values(&inputs, layer, &[(center / TILE, center / TILE)]).unwrap();
for (wrap, x) in [(false, center), (true, 0)] {
let EffectKind::Filter(Filter::Blur { wrap: enabled, .. }) =
&mut fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().effects.last_mut().unwrap().kind
else {
panic!("expected blur")
};
assert_eq!(tile.get(center, center)[0], to_u16(full[(center * SIZE + center) as usize]));
*enabled = wrap;
let inputs = inputs(&fixture, 0, &images, &baked);
let full = mask_texels(&inputs, layer).unwrap();
let tile = mask_values(&inputs, layer, &[(x / TILE, center / TILE)]).unwrap();
assert_eq!(tile.get(x, center)[0], to_u16(full[(center * SIZE + x) as usize]), "wrap={wrap}");
}
}
#[test]
+92
View File
@@ -0,0 +1,92 @@
//! Anisotropic Kuwahara's settings: a painterly smoothing that follows the direction of the strokes
use serde::{Deserialize, Serialize};
/// An Anisotropic Kuwahara filter: each texel takes the mean of the calmest sector of an ellipse turned along the local direction
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnisotropicKuwahara {
/// Extract Direction Custom Input: the direction comes from the filter's Custom Input instead of the channel
pub custom_input: bool,
/// Texels at 2K the ellipse reaches (0..10)
pub radius: f32,
/// How much neighbouring sectors overlap (0 = hard sector edges)
pub smoothness: f32,
/// How strongly the calmest sector wins over the others (0.25..1)
pub sharpness: f32,
/// How far around a texel its direction is averaged, as a share of the radius
pub tensor_smoothness: f32,
/// How much the ellipse stretches along the direction where the direction is clear (0 = a circle)
pub anisotropy: f32,
/// Degrees the ellipse turns from the extracted direction
pub angle: f32,
}
impl AnisotropicKuwahara {
/// A new Anisotropic Kuwahara
pub const LIBRARY: AnisotropicKuwahara =
AnisotropicKuwahara { custom_input: false, radius: 5.0, smoothness: 0.25, sharpness: 0.25, tensor_smoothness: 0.1, anisotropy: 1.0, angle: 0.0 };
/// The largest Radius, in texels at 2K
pub const MAX_RADIUS: f32 = 10.0;
/// The least Sharpness
pub const MIN_SHARPNESS: f32 = 0.25;
/// Sectors the ellipse is split into
pub const SECTORS: usize = 8;
/// The sector weighing exponent at a Sharpness of 0 and of 1 (Sharpness stops at [`Self::MIN_SHARPNESS`], so the least it weighs with is 5.5)
const SHARPNESS_EXPONENT_MIN: f32 = 2.0;
const SHARPNESS_EXPONENT_MAX: f32 = 16.0;
/// The sample falloff exponent at no Smoothness (1 at full Smoothness)
const SECTOR_EXPONENT_MAX: f32 = 16.0;
/// How far around a texel its direction is read, as a share of the radius (Tensor Smoothness, 0..1)
pub fn tensor_reach(&self) -> f32 {
if self.tensor_smoothness.is_finite() { self.tensor_smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.tensor_smoothness }
}
/// The exponent a sector's spread is weighed with: higher picks the calmest sector more sharply
pub fn sharpness_exponent(&self) -> f32 {
let sharpness = if self.sharpness.is_finite() { self.sharpness.clamp(Self::MIN_SHARPNESS, 1.0) } else { Self::LIBRARY.sharpness };
Self::SHARPNESS_EXPONENT_MIN + sharpness * (Self::SHARPNESS_EXPONENT_MAX - Self::SHARPNESS_EXPONENT_MIN)
}
/// How sharply a sample's weight falls off away from a sector's middle: smoother sectors overlap more
pub fn sector_exponent(&self) -> f32 {
let smoothness = if self.smoothness.is_finite() { self.smoothness.clamp(0.0, 1.0) } else { Self::LIBRARY.smoothness };
1.0 + (1.0 - smoothness) * (Self::SECTOR_EXPONENT_MAX - 1.0)
}
/// The ellipse's semi-axes (along, across the direction) for `radius` texels where the direction is `clear` (0..1)
pub fn axes(&self, radius: f32, clear: f32) -> (f32, f32) {
let stretch = if self.anisotropy.is_finite() { self.anisotropy.clamp(0.0, 1.0) } else { Self::LIBRARY.anisotropy } * clear.clamp(0.0, 1.0);
(radius * (1.0 + stretch), radius / (1.0 + stretch))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_clear_direction_stretches_the_ellipse() {
let filter = AnisotropicKuwahara::LIBRARY;
assert_eq!(filter.axes(4.0, 0.0), (4.0, 4.0));
assert_eq!(filter.axes(4.0, 1.0), (8.0, 2.0));
assert_eq!(AnisotropicKuwahara { anisotropy: 0.0, ..filter }.axes(4.0, 1.0), (4.0, 4.0));
assert!(AnisotropicKuwahara { sharpness: 1.0, ..filter }.sharpness_exponent() > filter.sharpness_exponent());
assert!(AnisotropicKuwahara { smoothness: 1.0, ..filter }.sector_exponent() < filter.sector_exponent());
}
#[test]
fn sharpness_weighs_on_a_line_from_its_exponent_at_0_to_its_exponent_at_1() {
let at = |sharpness: f32| AnisotropicKuwahara { sharpness, ..AnisotropicKuwahara::LIBRARY }.sharpness_exponent();
assert_eq!(at(AnisotropicKuwahara::MIN_SHARPNESS), 5.5, "the least Sharpness, a quarter of the way along");
assert_eq!(at(0.0), 5.5, "below the least, the least");
assert_eq!(at(1.0), 16.0, "the most Sharpness weighs with the most exponent");
}
}
+98
View File
@@ -0,0 +1,98 @@
//! The Bevel filter's settings and the slope it gives a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelBlur, BevelCorner, SIZE_REFERENCE_RES};
/// Shapes (values at or above [`Bevel::EDGE`]) sloped at their edge: inwards for a negative distance, outwards for a positive one
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Bevel {
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
/// How far the slope reaches from the edge, a fraction of the UV tile: inwards below 0, outwards above (−1..1)
pub distance: f32,
pub corner: BevelCorner,
/// How much the slope is blurred (0..5, [`Bevel::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
pub blur: BevelBlur,
}
impl Bevel {
/// The Bevel filter as the library adds it
pub const LIBRARY: Bevel = Bevel { wrap: false, distance: -0.1, corner: BevelCorner::Round, smoothing: 0.0, blur: BevelBlur::NonUniform };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 4.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 5.0;
/// Whether the slope lies inside the shapes
pub fn inward(&self) -> bool {
self.distance <= 0.0 || self.distance.is_nan()
}
/// How many texels the slope reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
let distance = if self.distance.is_finite() { self.distance.abs().min(1.0) } else { 0.0 };
distance * res as f32
}
/// How many texels the slope is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The slope (0..1) at a texel `edge` texels from the shapes' edge, inside them or not, rising from 0 at its foot to 1 at its top
pub fn slope(&self, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
match (self.inward(), inside) {
(true, true) => along,
(false, false) => 1.0 - along,
(true, false) => 0.0,
(false, true) => 1.0,
}
}
/// The result at a texel of `value`, inside the shapes or not, on `slope`: an inward slope scales the shapes, an outward one rises around them
pub fn apply(&self, inside: bool, value: f32, slope: f32) -> f32 {
match (self.inward(), inside) {
(true, true) => value * slope,
(false, false) => value.max(slope),
_ => value,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_negative_distance_slopes_inwards_and_a_positive_one_outwards() {
let inward = Bevel::LIBRARY;
assert_eq!(inward.reach(2048), 204.8);
assert_eq!((inward.slope(true, 0.0, 10.0), inward.slope(true, 5.0, 10.0), inward.slope(true, 20.0, 10.0)), (0.0, 0.5, 1.0));
assert_eq!(inward.apply(true, 0.8, 0.5), 0.4, "inside, scaled down towards the edge");
assert_eq!(inward.apply(false, 0.3, 0.0), 0.3, "outside untouched");
let outward = Bevel { distance: 0.1, ..inward };
assert_eq!((outward.slope(false, 0.0, 10.0), outward.slope(false, 5.0, 10.0), outward.slope(false, 20.0, 10.0)), (1.0, 0.5, 0.0));
assert_eq!(outward.apply(false, 0.2, 0.5), 0.5, "rises around the shapes");
assert_eq!(outward.apply(true, 0.7, 1.0), 0.7, "inside untouched");
}
#[test]
fn hostile_settings_stay_in_range() {
let bevel = Bevel { distance: f32::NAN, smoothing: f32::INFINITY, ..Bevel::LIBRARY };
assert_eq!((bevel.reach(2048), bevel.smoothing_texels(2048)), (0.0, 0.0));
assert_eq!(bevel.slope(true, 3.0, 0.0), 1.0, "no reach leaves the shapes whole");
let excessive = Bevel { distance: -9.0, smoothing: 9.0, ..bevel };
assert_eq!(excessive.reach(1024), 1024.0);
assert_eq!(excessive.smoothing_texels(2048), Bevel::SMOOTHING_MAX * Bevel::SMOOTHING_TEXELS, "smoothing stops at its largest");
}
}
+35
View File
@@ -0,0 +1,35 @@
//! How a Bevel's Smoothing spreads over its slope
use serde::{Deserialize, Serialize};
/// Where a Bevel's Smoothing blurs its slope
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelBlur {
/// Sharp at the slope's foot, smoother towards its top
#[default]
NonUniform,
/// The same blur over the whole slope
Uniform,
}
impl BevelBlur {
/// Every blur mode, in the order a switch shows them
pub const ALL: [BevelBlur; 2] = [BevelBlur::NonUniform, BevelBlur::Uniform];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelBlur::NonUniform => "Non-Uniform",
BevelBlur::Uniform => "Uniform",
}
}
/// The id `effect.set {blurMode}` takes
pub fn id(self) -> &'static str {
match self {
BevelBlur::NonUniform => "nonUniform",
BevelBlur::Uniform => "uniform",
}
}
}
+35
View File
@@ -0,0 +1,35 @@
//! The shape a Bevel gives the corners it rounds off
use serde::{Deserialize, Serialize};
/// How a Bevel measures the distance from a shape's edge, which shows at its corners
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelCorner {
/// Straight-line distance: corners the bevel goes around come out round
#[default]
Round,
/// The larger of the horizontal and vertical distance: corners stay square
Angular,
}
impl BevelCorner {
/// Every corner type, in the order a switch shows them
pub const ALL: [BevelCorner; 2] = [BevelCorner::Round, BevelCorner::Angular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelCorner::Round => "Round",
BevelCorner::Angular => "Angular",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
BevelCorner::Round => "round",
BevelCorner::Angular => "angular",
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which side of a shape's edge a Bevel Smooth ramps on
use serde::{Deserialize, Serialize};
/// The side of the edge a Bevel Smooth's ramp lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BevelDirection {
/// From the edge outwards, the shapes staying white
#[default]
Out,
/// From the edge inwards, around the shapes staying black
In,
/// Across the edge, mid gray on it
InOut,
}
impl BevelDirection {
/// Every direction, in the order a switch shows them
pub const ALL: [BevelDirection; 3] = [BevelDirection::Out, BevelDirection::In, BevelDirection::InOut];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
BevelDirection::Out => "Out",
BevelDirection::In => "In",
BevelDirection::InOut => "In/Out",
}
}
/// The id `effect.set {direction}` takes
pub fn id(self) -> &'static str {
match self {
BevelDirection::Out => "out",
BevelDirection::In => "in",
BevelDirection::InOut => "inOut",
}
}
}
+117
View File
@@ -0,0 +1,117 @@
//! The Bevel Smooth filter's settings and the ramp it draws from a shape's edge
use serde::{Deserialize, Serialize};
use crate::{BevelDirection, RampCurve, SIZE_REFERENCE_RES, at_or_above_threshold, finite_unit};
/// A smooth ramp from the edge of the shapes (values at or above `threshold`), outwards, inwards or across it
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BevelSmooth {
pub direction: BevelDirection,
/// How far the ramp reaches from the edge, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// How much the ramp is blurred (0..10, [`BevelSmooth::SMOOTHING_TEXELS`] texels at 2K each)
pub smoothing: f32,
/// Moves the ramp up or down before its curve (−1..1)
pub curve_offset: f32,
/// Bends the ramp: below 0 it rises later, above 0 sooner (−1..1)
pub curve_shape: f32,
/// Values at or above it are inside the shapes (Mask Threshold, 0..1)
pub threshold: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
/// Reads past the texture's edges from the far side (Bevel Wrap)
pub wrap: bool,
}
impl BevelSmooth {
/// The Bevel Smooth filter as the library adds it
pub const LIBRARY: BevelSmooth = BevelSmooth {
direction: BevelDirection::Out,
distance: 0.1,
smoothing: 1.0,
curve_offset: 0.0,
curve_shape: 0.0,
threshold: 0.5,
multiplier: 1.0,
wrap: false,
};
/// Texels at 2K a unit of Smoothing blurs over
pub const SMOOTHING_TEXELS: f32 = 2.0;
/// The largest Smoothing
pub const SMOOTHING_MAX: f32 = 10.0;
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// How many texels the ramp reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// How many texels the ramp is blurred over at `res` texels across a UV tile
pub fn smoothing_texels(&self, res: u32) -> f32 {
let smoothing = if self.smoothing.is_finite() { self.smoothing.clamp(0.0, Self::SMOOTHING_MAX) } else { 0.0 };
smoothing * Self::SMOOTHING_TEXELS * res as f32 / SIZE_REFERENCE_RES
}
/// The curve the ramp takes (Curve Offset and Curve Shape), worked out once per filter
pub fn curve(&self) -> RampCurve {
RampCurve::new(self.curve_offset, self.curve_shape)
}
/// The ramp at a texel `edge` texels from the shapes' edge, inside them or not, bent by [`BevelSmooth::curve`]
pub fn value(&self, curve: RampCurve, inside: bool, edge: f32, reach: f32) -> f32 {
let along = if reach > 0.0 && edge.is_finite() { (edge / reach).clamp(0.0, 1.0) } else { 1.0 };
let curved = curve.apply(along);
match (self.direction, inside) {
(BevelDirection::Out, true) => 1.0,
(BevelDirection::Out, false) => 1.0 - curved,
(BevelDirection::In, true) => curved,
(BevelDirection::In, false) => 0.0,
(BevelDirection::InOut, true) => 0.5 + 0.5 * curved,
(BevelDirection::InOut, false) => 0.5 - 0.5 * curved,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The ramp with the curve worked out as the filter does
fn ramp(filter: BevelSmooth, inside: bool, edge: f32, reach: f32) -> f32 {
filter.value(filter.curve(), inside, edge, reach)
}
#[test]
fn the_ramp_lies_on_its_direction_side() {
let out = BevelSmooth::LIBRARY;
assert_eq!(out.reach(2048), 204.8);
assert!(out.inside(0.5) && !out.inside(0.49));
assert_eq!((ramp(out, true, 3.0, 10.0), ramp(out, false, 0.0, 10.0), ramp(out, false, 5.0, 10.0), ramp(out, false, 20.0, 10.0)), (1.0, 1.0, 0.5, 0.0));
let inward = BevelSmooth { direction: BevelDirection::In, ..out };
assert_eq!((ramp(inward, false, 3.0, 10.0), ramp(inward, true, 5.0, 10.0), ramp(inward, true, 20.0, 10.0)), (0.0, 0.5, 1.0));
let both = BevelSmooth { direction: BevelDirection::InOut, ..out };
assert_eq!(
(ramp(both, true, 0.0, 10.0), ramp(both, false, 0.0, 10.0), ramp(both, true, 10.0, 10.0), ramp(both, false, 10.0, 10.0)),
(0.5, 0.5, 1.0, 0.0)
);
}
#[test]
fn curve_offset_and_shape_bend_the_ramp() {
let inward = BevelSmooth { direction: BevelDirection::In, ..BevelSmooth::LIBRARY };
assert_eq!(ramp(BevelSmooth { curve_offset: 0.25, ..inward }, true, 5.0, 10.0), 0.75);
assert!(ramp(BevelSmooth { curve_shape: 0.5, ..inward }, true, 5.0, 10.0) > 0.5, "rises sooner");
assert!(ramp(BevelSmooth { curve_shape: -0.5, ..inward }, true, 5.0, 10.0) < 0.5, "rises later");
assert_eq!(BevelSmooth { multiplier: 0.5, ..inward }.reach(2048), 102.4);
let hostile = BevelSmooth { distance: f32::NAN, curve_offset: f32::NAN, curve_shape: f32::INFINITY, threshold: f32::NAN, ..inward };
assert_eq!((hostile.reach(2048), ramp(hostile, true, 1.0, 0.0)), (0.0, 1.0));
}
}
+132
View File
@@ -0,0 +1,132 @@
//! Color Match's settings: the colors moved so a source color lands on a target color
use serde::{Deserialize, Serialize};
use crate::{SourceColorMode, TargetColorMode, oklab};
/// A Color Match filter: every color moved, in OKLab, by the step from its source color to its target color
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorMatch {
/// Source Color Mode: the color moved from
pub source_mode: SourceColorMode,
/// Source Color (linear), read in Source Color Mode Parameter
pub source_color: [f32; 3],
/// Target Color Mode: the color moved to
pub target_mode: TargetColorMode,
/// Target Color (linear), read in Target Color Mode Parameter
pub target_color: [f32; 3],
/// Custom Color Variation: the colors keep at most Hue, Chroma and Luma of their difference from the source
pub custom_variation: bool,
/// Hue (degrees): how far a hue may stay from the target's
pub hue: f32,
/// Chroma: how far a chroma may stay from the target's
pub chroma: f32,
/// Luma: how far a lightness may stay from the target's
pub luma: f32,
}
impl ColorMatch {
/// Mid gray (128 sRGB) in linear
const GRAY: [f32; 3] = [0.215_860_5; 3];
/// The most Hue keeps (degrees): two hues are at most half a turn apart
pub const MAX_HUE_DEGREES: f32 = 180.0;
/// The most Chroma keeps (OKLab chroma)
pub const MAX_CHROMA: f32 = 1.0;
/// The most Luma keeps (OKLab lightness, 0..1)
pub const MAX_LUMA: f32 = 1.0;
/// A new Color Match: the texture's mean moves to the target and every texel keeps all of its difference from the mean (Color Variation at its widest), so the layer keeps its pattern until a variation is lowered
pub const LIBRARY: ColorMatch = ColorMatch {
source_mode: SourceColorMode::Average,
source_color: Self::GRAY,
target_mode: TargetColorMode::Parameter,
target_color: Self::GRAY,
custom_variation: true,
hue: Self::MAX_HUE_DEGREES,
chroma: Self::MAX_CHROMA,
luma: Self::MAX_LUMA,
};
/// Linear `color` moved by the step from `source` to `target`; without Custom Color Variation it keeps all of its difference from the source, with it at most Hue, Chroma and Luma of it (all 0: the target color itself). Hostile values give the color back
pub fn apply(&self, color: [f32; 3], source: [f32; 3], target: [f32; 3]) -> [f32; 3] {
let lab = |color: [f32; 3]| oklab::from_linear(color.map(|component| component.max(0.0)));
let [lightness, a, b] = lab(color);
let [source_lightness, source_a, source_b] = lab(source);
let [target_lightness, target_a, target_b] = lab(target);
let moved = if self.custom_variation {
self.move_polar(polar([lightness, a, b]), polar([source_lightness, source_a, source_b]), polar([target_lightness, target_a, target_b]))
} else {
[target_lightness + lightness - source_lightness, target_a + a - source_a, target_b + b - source_b]
};
matched_linear(color, moved)
}
#[inline]
pub(super) fn move_polar(
&self,
[lightness, chroma, hue]: [f32; 3],
[source_lightness, source_chroma, source_hue]: [f32; 3],
[target_lightness, target_chroma, target_hue]: [f32; 3],
) -> [f32; 3] {
let limit = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
let keep = |difference: f32, max: f32| difference.clamp(-max, max);
let turn = (hue - source_hue + std::f32::consts::PI).rem_euclid(std::f32::consts::TAU) - std::f32::consts::PI;
let out_lightness = target_lightness + keep(lightness - source_lightness, limit(self.luma, Self::MAX_LUMA));
let out_chroma = (target_chroma + keep(chroma - source_chroma, limit(self.chroma, Self::MAX_CHROMA))).max(0.0);
let out_hue = target_hue + keep(turn, limit(self.hue, Self::MAX_HUE_DEGREES).to_radians());
[out_lightness, out_chroma * out_hue.cos(), out_chroma * out_hue.sin()]
}
}
pub(super) fn polar([lightness, a, b]: [f32; 3]) -> [f32; 3] {
[lightness, a.hypot(b), b.atan2(a)]
}
pub(super) fn matched_linear(original: [f32; 3], lab: [f32; 3]) -> [f32; 3] {
let out = oklab::to_linear(lab);
if out.iter().all(|value| value.is_finite()) { out.map(|value| value.clamp(0.0, 1.0)) } else { original }
}
#[cfg(test)]
mod tests {
use super::*;
fn near(a: [f32; 3], b: [f32; 3]) -> bool {
a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
}
#[test]
fn the_source_color_lands_on_the_target_and_variation_is_kept_as_asked() {
let red = [0.6, 0.1, 0.05];
let blue = [0.05, 0.1, 0.6];
let lighter_red = [0.8, 0.2, 0.1];
let lightness = |color: [f32; 3]| oklab::from_linear(color)[0];
// Without Custom Color Variation every difference from the source is kept
let keep_all = ColorMatch { custom_variation: false, ..ColorMatch::LIBRARY };
let moved = keep_all.apply(lighter_red, red, blue);
assert!(near(keep_all.apply(red, red, blue), blue), "the source itself becomes the target");
assert!(lightness(moved) > lightness(blue) + 0.05, "a lighter texel stays lighter than the target");
assert!(moved[2] > moved[0], "and turns blue");
// Custom Color Variation at 0: every color is the target
let flat = ColorMatch { luma: 0.0, chroma: 0.0, hue: 0.0, ..ColorMatch::LIBRARY };
assert!(near(flat.apply(lighter_red, red, blue), blue));
// A new Color Match's widest limits keep the lightness difference again
let library = ColorMatch::LIBRARY;
assert!(lightness(library.apply(lighter_red, red, blue)) > lightness(blue) + 0.05, "a new Color Match keeps the variation");
// Luma alone: the lightness difference kept up to it
let luma_only = ColorMatch { luma: 0.02, ..flat };
let limited = lightness(luma_only.apply(lighter_red, red, blue)) - lightness(blue);
assert!((limited - 0.02).abs() < 1e-3, "lightness kept up to Luma: {limited}");
let hostile = ColorMatch { hue: f32::NAN, chroma: f32::INFINITY, luma: -1.0, ..flat };
assert!(hostile.apply([f32::NAN, 0.5, 0.5], red, blue).iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)));
}
}
+63
View File
@@ -0,0 +1,63 @@
//! How Grayscale Conversion turns a color into gray
use serde::{Deserialize, Serialize};
use crate::GrayscaleMode;
/// The gray Grayscale Conversion reads from a color: a [`GrayscaleMode`], or its own weights per component
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ConversionMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Red, Green, Blue and Alpha times their weights, summed
#[default]
ChannelsWeights,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl ConversionMode {
/// Every mode, in the order a list shows them
pub const ALL: [ConversionMode; 5] =
[ConversionMode::Desaturation, ConversionMode::ChannelsWeights, ConversionMode::Average, ConversionMode::Max, ConversionMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "Channels Weights",
other => other.mode().map_or("", GrayscaleMode::label),
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
ConversionMode::ChannelsWeights => "channelsWeights",
other => other.mode().map_or("", GrayscaleMode::id),
}
}
/// The gray of straight color `rgb` with coverage `alpha`, `weights` for Red, Green, Blue and Alpha
pub fn gray(self, rgb: [f32; 3], alpha: f32, weights: [f32; 4]) -> f32 {
match self.mode() {
Some(mode) => mode.gray(rgb),
None => rgb[0] * weights[0] + rgb[1] * weights[1] + rgb[2] * weights[2] + alpha * weights[3],
}
}
/// The gradient's grayscale mode this one matches (None for Channels Weights)
fn mode(self) -> Option<GrayscaleMode> {
match self {
ConversionMode::Desaturation => Some(GrayscaleMode::Desaturation),
ConversionMode::ChannelsWeights => None,
ConversionMode::Average => Some(GrayscaleMode::Average),
ConversionMode::Max => Some(GrayscaleMode::Max),
ConversionMode::Min => Some(GrayscaleMode::Min),
}
}
}
+144
View File
@@ -0,0 +1,144 @@
//! The shapes Gradient Curve remaps values through
use serde::{Deserialize, Serialize};
use crate::layer::smoothstep;
/// Stairs climbs in this many flat steps
const STAIRS_STEPS: f32 = 4.0;
/// Triangular rises and falls this many times
const TRIANGULAR_TEETH: f32 = 2.0;
/// A remap curve from 0..1 onto 0..1
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CurvePreset {
/// A quarter circle: rises fast, then flattens
#[default]
Round,
/// A quarter circle the other way: flat, then rises fast
Pinch,
/// Four flat steps
Stairs,
EaseOut,
Ease,
EaseIn,
/// Up to the middle and back down, rounded at the top
PeakOut,
/// Up to the middle and back down in straight lines
Peak,
/// Up to the middle and back down, pointed at the top
PeakIn,
/// Half a sine wave
Bump,
/// Two humps
DoubleBump,
/// Two straight teeth
Triangular,
}
impl CurvePreset {
/// Every preset, in the order the Preset list shows them
pub const ALL: [CurvePreset; 12] = [
CurvePreset::Round,
CurvePreset::Pinch,
CurvePreset::Stairs,
CurvePreset::EaseOut,
CurvePreset::Ease,
CurvePreset::EaseIn,
CurvePreset::PeakOut,
CurvePreset::Peak,
CurvePreset::PeakIn,
CurvePreset::Bump,
CurvePreset::DoubleBump,
CurvePreset::Triangular,
];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
CurvePreset::Round => "Round",
CurvePreset::Pinch => "Pinch",
CurvePreset::Stairs => "Stairs",
CurvePreset::EaseOut => "Ease Out",
CurvePreset::Ease => "Ease",
CurvePreset::EaseIn => "Ease In",
CurvePreset::PeakOut => "Peak Out",
CurvePreset::Peak => "Peak",
CurvePreset::PeakIn => "Peak In",
CurvePreset::Bump => "Bump",
CurvePreset::DoubleBump => "Double Bump",
CurvePreset::Triangular => "Triangular",
}
}
/// The id `effect.set {preset}` takes
pub fn id(self) -> &'static str {
match self {
CurvePreset::Round => "round",
CurvePreset::Pinch => "pinch",
CurvePreset::Stairs => "stairs",
CurvePreset::EaseOut => "easeOut",
CurvePreset::Ease => "ease",
CurvePreset::EaseIn => "easeIn",
CurvePreset::PeakOut => "peakOut",
CurvePreset::Peak => "peak",
CurvePreset::PeakIn => "peakIn",
CurvePreset::Bump => "bump",
CurvePreset::DoubleBump => "doubleBump",
CurvePreset::Triangular => "triangular",
}
}
/// The curve at `t` (clamped to 0..1; a non-finite `t` reads 0)
pub fn at(self, t: f32) -> f32 {
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
let peak = 1.0 - (2.0 * t - 1.0).abs();
let y = match self {
CurvePreset::Round => (1.0 - (1.0 - t) * (1.0 - t)).sqrt(),
CurvePreset::Pinch => 1.0 - (1.0 - t * t).sqrt(),
CurvePreset::Stairs => ((t * STAIRS_STEPS).floor() / (STAIRS_STEPS - 1.0)).min(1.0),
CurvePreset::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
CurvePreset::Ease => smoothstep(0.0, 1.0, t),
CurvePreset::EaseIn => t * t,
CurvePreset::PeakOut => peak.sqrt(),
CurvePreset::Peak => peak,
CurvePreset::PeakIn => peak * peak,
CurvePreset::Bump => (std::f32::consts::PI * t).sin(),
CurvePreset::DoubleBump => (2.0 * std::f32::consts::PI * t).sin().abs(),
CurvePreset::Triangular => 1.0 - ((2.0 * TRIANGULAR_TEETH * t) % 2.0 - 1.0).abs(),
};
y.clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Samples across 0..1 that every curve is read at
const SAMPLES: usize = 64;
#[test]
fn every_preset_stays_in_range_and_reads_a_non_finite_t_as_0() {
for preset in CurvePreset::ALL {
let values: Vec<f32> = (0..=SAMPLES).map(|i| preset.at(i as f32 / SAMPLES as f32)).collect();
assert!(values.iter().all(|value| (0.0..=1.0).contains(value)), "{}", preset.id());
assert_eq!(preset.at(f32::NAN), preset.at(0.0), "{}", preset.id());
assert_eq!(preset.at(f32::INFINITY), preset.at(0.0), "{}", preset.id());
}
}
#[test]
fn stairs_has_four_levels_and_triangular_two_teeth() {
let mut levels: Vec<f32> = (0..=SAMPLES).map(|i| CurvePreset::Stairs.at(i as f32 / SAMPLES as f32)).collect();
levels.dedup();
assert_eq!(levels, [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]);
let triangular = |t: f32| CurvePreset::Triangular.at(t);
assert_eq!([triangular(0.0), triangular(0.25), triangular(0.5), triangular(0.75), triangular(1.0)], [0.0, 1.0, 0.0, 1.0, 0.0]);
}
}
+59
View File
@@ -0,0 +1,59 @@
//! The Directional Distance filter's settings and the trail it draws from the shapes
use serde::{Deserialize, Serialize};
use crate::finite_unit;
/// A trail fading away from the shapes (values at or above [`DirectionalDistance::EDGE`]) towards `angle`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectionalDistance {
/// How far the trail reaches, a fraction of the UV tile (0..0.3)
pub distance: f32,
/// Where the trail runs to, in degrees counterclockwise from the right (270 runs down)
pub angle: f32,
/// Hardens the trail's fade (0..1)
pub contrast: f32,
/// Scales the distance (Distance Map Multiplier, 0..1)
pub multiplier: f32,
}
impl DirectionalDistance {
/// The Directional Distance filter as the library adds it
pub const LIBRARY: DirectionalDistance = DirectionalDistance { distance: 0.1, angle: 270.0, contrast: 0.0, multiplier: 1.0 };
/// Values at or above it are inside the shapes
pub const EDGE: f32 = 0.5;
/// The most contrast reaches: a hard step, kept off a division by zero
const HARDEST: f32 = 0.99;
/// How many texels the trail reaches at `res` texels across a UV tile
pub fn reach(&self, res: u32) -> f32 {
finite_unit(self.distance) * finite_unit(self.multiplier) * res as f32
}
/// The trail where the nearest shape behind a texel is `along` of the reach away (0 on a shape), or none is in reach
pub fn value(&self, along: Option<f32>) -> f32 {
let Some(along) = along.filter(|along| along.is_finite()) else { return 0.0 };
let fade = 1.0 - along.clamp(0.0, 1.0);
let contrast = if self.contrast.is_finite() { self.contrast.clamp(0.0, Self::HARDEST) } else { 0.0 };
(0.5 + (fade - 0.5) / (1.0 - contrast)).clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_trail_fades_with_distance_and_contrast_hardens_it() {
let trail = DirectionalDistance::LIBRARY;
assert_eq!(trail.reach(2048), 204.8);
assert_eq!((trail.value(Some(0.0)), trail.value(Some(0.25)), trail.value(None)), (1.0, 0.75, 0.0));
let hard = DirectionalDistance { contrast: 0.5, ..trail };
assert_eq!((hard.value(Some(0.25)), hard.value(Some(0.8))), (1.0, 0.0));
let hostile = DirectionalDistance { distance: f32::NAN, contrast: f32::INFINITY, multiplier: -1.0, ..trail };
assert_eq!((hostile.reach(2048), hostile.value(Some(f32::NAN))), (0.0, 0.0));
}
}
+31
View File
@@ -0,0 +1,31 @@
//! One of Baked Lighting Stylized's extra lights
use serde::{Deserialize, Serialize};
/// A light from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), of strength `intensity` in `color`
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DirectionalLight {
pub azimuth: f32,
pub elevation: f32,
pub intensity: f32,
pub color: [f32; 3],
}
impl DirectionalLight {
/// An unlit white light from `azimuth`, 45 degrees up
pub const fn off(azimuth: f32) -> DirectionalLight {
DirectionalLight { azimuth, elevation: 45.0, intensity: 0.0, color: [1.0; 3] }
}
/// The unit direction toward the light
pub fn direction(&self) -> [f32; 3] {
toward(self.azimuth, self.elevation)
}
}
/// The unit direction toward a light at `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees)
fn toward(azimuth: f32, elevation: f32) -> [f32; 3] {
let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos();
let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos();
[cos_elevation * sin_azimuth, sin_elevation, cos_elevation * cos_azimuth]
}
+181
View File
@@ -0,0 +1,181 @@
//! Gradient's Input Transformation: how a texel becomes the position it reads on the ramp
use serde::{Deserialize, Serialize};
use crate::grayscale_mode::GrayscaleMode;
use crate::{ChannelKind, finite_unit, lum, per_unit};
/// Keep the transition finite just below full contrast
const MIN_STEEPNESS: f32 = 1e-3;
/// The balance that leaves the gray as it is
pub(crate) const NEUTRAL_BALANCE: f32 = 0.5;
/// The gray, blurred, balanced, contrasted and maybe inverted value a gradient looks up
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GradientInput {
/// How a color becomes gray (masks and scalar channels are gray already)
pub mode: GrayscaleMode,
/// Blurs the gray before the lookup, in texels at 2K (0..16)
pub blur: f32,
/// Shifts the gray: above 0.5 lighter, below darker
pub balance: f32,
/// Steepens the gray around its middle: 1 is a hard step
pub contrast: f32,
pub invert: bool,
}
impl Default for GradientInput {
/// What gradients read in projects saved before the Input Transformation: luma, untouched
fn default() -> Self {
GradientInput { mode: GrayscaleMode::Luma, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false }
}
}
impl GradientInput {
/// The library's starting transformation: the average of the components, untouched
pub const LIBRARY: GradientInput = GradientInput { mode: GrayscaleMode::Average, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, invert: false };
/// Whether it reads gradients as projects saved before it did (skipped when saving)
pub fn is_unchanged(&self) -> bool {
*self == GradientInput::default()
}
/// The ramp position of gray `x`
pub fn shape(&self, x: f32) -> f32 {
// Preserve the exact input when the transformation is neutral
if self.balance == NEUTRAL_BALANCE && self.contrast == 0.0 && !self.invert {
return x;
}
shape_gray(x, self.balance, self.contrast, self.invert)
}
/// Apply a gradient to a channel using its ramp sampler
pub fn map(&self, kind: ChannelKind, value: [f32; 3], sample: impl Fn(f32) -> Option<[f32; 3]>) -> Option<[f32; 3]> {
if kind == ChannelKind::Color {
return sample(self.shape(self.mode.gray(value)));
}
// Preserve the signed-channel mapping and leave normals alone
Some(per_unit(kind, value, |gray| sample(self.shape(gray)).map_or(gray, lum)))
}
}
/// Gray `x` balanced (0.5 keeps it), contrasted around mid gray (0 keeps it, 1 is a step at 0.5) and maybe inverted, in 0..1
pub fn shape_gray(x: f32, balance: f32, contrast: f32, invert: bool) -> f32 {
let balanced = finite_unit(x) + finite_unit(balance) - NEUTRAL_BALANCE;
let contrast = finite_unit(contrast);
let shaped = if contrast == 1.0 {
f32::from(balanced >= NEUTRAL_BALANCE)
} else {
let steep = (1.0 - contrast).max(MIN_STEEPNESS);
finite_unit((balanced - NEUTRAL_BALANCE) / steep + NEUTRAL_BALANCE)
};
if invert { 1.0 - shaped } else { shaped }
}
/// A ramp stop's place and color
type Stop = (f32, [f32; 3]);
pub(crate) fn ramp_stops<'a>(colors: &'a [[f32; 3]], positions: &'a [f32]) -> impl ExactSizeIterator<Item = Stop> + 'a {
let last = colors.len().saturating_sub(1);
colors.iter().copied().enumerate().map(move |(index, color)| {
let even_position = || if last == 0 { 0.0 } else { index as f32 / last as f32 };
let position = positions.get(index).copied().filter(|position| position.is_finite()).unwrap_or_else(even_position);
let position = if position <= 0.0 { 0.0 } else { position.min(1.0) };
(position, color)
})
}
/// The color at `t` on a ramp of `colors` placed at `positions` (each 0..1, evenly spaced where missing), blended in linear or sRGB
pub fn ramp(colors: &[[f32; 3]], positions: &[f32], linear: bool, t: f32) -> Option<[f32; 3]> {
let stops = ramp_stops(colors, positions);
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
// Keep the last stop at or before the sample and the first stop after it
let (mut before, mut after): (Option<Stop>, Option<Stop>) = (None, None);
for (position, color) in stops {
if position <= t {
if before.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_ge()) {
before = Some((position, color));
}
} else if after.is_none_or(|(so_far, _)| position.total_cmp(&so_far).is_lt()) {
after = Some((position, color));
}
}
let ((before_place, before_color), (after_place, after_color)) = match (before, after) {
(Some(before), Some(after)) => (before, after),
(Some(only), None) | (None, Some(only)) => (only, only),
(None, None) => return None,
};
let encode = |color: [f32; 3]| if linear { color } else { color.map(linear_to_srgb) };
Some(interpolate((before_place, encode(before_color)), (after_place, encode(after_color)), linear, t))
}
pub(crate) fn interpolate((before_place, before_color): Stop, (after_place, after_color): Stop, linear: bool, t: f32) -> [f32; 3] {
let share = if after_place > before_place { ((t - before_place) / (after_place - before_place)).clamp(0.0, 1.0) } else { 0.0 };
let color = std::array::from_fn(|component| before_color[component] + (after_color[component] - before_color[component]) * share);
if linear { color } else { color.map(srgb_to_linear) }
}
// A copy of texturecraft_texel's: texel and core are both layer 0, so core cannot use it
/// sRGB transfer of a linear component
pub(crate) fn linear_to_srgb(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// Linear value of an sRGB component
pub(crate) fn srgb_to_linear(v: f32) -> f32 {
let v = v.clamp(0.0, 1.0);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_ramp_reads_its_stops_in_place_order_whatever_their_list_order() {
let (black, gray, white) = ([0.0; 3], [0.5; 3], [1.0; 3]);
let colors = [white, black, gray];
let positions = [1.0, 0.0, 0.5];
let quarter = ramp(&colors, &positions, true, 0.25);
let ends = (ramp(&colors, &positions, true, 0.0), ramp(&colors, &positions, true, 1.0));
let past_one_stop = ramp(&[gray, white], &[0.5, 0.5], true, 0.25);
assert_eq!(ramp(&[black, white], &[0.0, -0.0], true, 0.0), Some(white));
assert_eq!(quarter, Some([0.25; 3]));
assert_eq!(ends, (Some(black), Some(white)));
assert_eq!(past_one_stop, Some(gray), "before the first stop, its color");
assert_eq!(ramp(&[], &[], true, 0.5), None);
}
#[test]
fn full_contrast_separates_neighbors_of_mid_gray() {
let below = shape_gray(0.49975, NEUTRAL_BALANCE, 1.0, false);
let above = shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, false);
assert_eq!((below, above), (0.0, 1.0));
assert_eq!(shape_gray(0.50025, NEUTRAL_BALANCE, 1.0, true), below);
}
#[test]
fn an_untouched_input_passes_every_gray_on_bit_for_bit() {
const SAMPLES: u16 = 1000;
let untouched = [GradientInput::default(), GradientInput::LIBRARY];
let grays = (0..=SAMPLES).map(|step| f32::from(step) / f32::from(SAMPLES)).chain([-0.25, 1.5]);
for input in untouched {
for gray in grays.clone() {
assert_eq!(input.shape(gray).to_bits(), gray.to_bits(), "{input:?} at {gray}");
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Grayscale Conversion's settings: which gray it reads and how it shapes it
use serde::{Deserialize, Serialize};
use crate::blend::lum;
use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray};
use crate::layer::per_unit;
use crate::{ChannelKind, ConversionMode};
/// A Grayscale Conversion filter: the gray of the current channel (or of its Custom Input), balanced, contrasted and maybe inverted
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GrayscaleConversion {
/// Channel Input Custom Input: the gray of the filter's Custom Input instead of the channel's
pub custom_input: bool,
pub invert: bool,
pub balance: f32,
pub contrast: f32,
pub mode: ConversionMode,
/// Channels Weights' Red, Green, Blue and Alpha
pub weights: [f32; 4],
}
impl GrayscaleConversion {
/// A new Grayscale Conversion: a third of each color component, alpha left out
pub const LIBRARY: GrayscaleConversion = GrayscaleConversion {
custom_input: false,
invert: false,
balance: NEUTRAL_BALANCE,
contrast: 0.0,
mode: ConversionMode::ChannelsWeights,
weights: [0.33, 0.33, 0.33, 0.0],
};
/// The settings a Grayscale filter saved before them takes on its first edit: its luminance weights, so it looks the same
pub fn of_luminance() -> GrayscaleConversion {
let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]].map(lum);
GrayscaleConversion { weights: [red, green, blue, 0.0], ..Self::LIBRARY }
}
/// The shaped gray of straight color `rgb` with coverage `alpha`
pub fn gray(&self, rgb: [f32; 3], alpha: f32) -> f32 {
shape_gray(self.mode.gray(rgb, alpha, self.weights), self.balance, self.contrast, self.invert)
}
/// `v` of a `kind` channel (coverage `alpha`) or `custom_input` turned gray: colors gray, scalar and signed in their range, normals as they are
pub fn channel_value(&self, kind: ChannelKind, v: [f32; 3], custom_input: Option<[f32; 3]>, alpha: f32) -> [f32; 3] {
match (kind, custom_input) {
(ChannelKind::NormalMap, _) => v,
(ChannelKind::Color, None) => [self.gray(v, alpha); 3],
(ChannelKind::Color, Some(input)) => [self.gray(input, alpha); 3],
(_, None) => per_unit(kind, v, |x| self.gray([x; 3], alpha)),
(_, Some(input)) => per_unit(kind, v, |_| self.gray(input, alpha)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_saved_grayscale_keeps_its_luminance() {
let color = [0.8, 0.3, 0.1];
assert!((GrayscaleConversion::of_luminance().gray(color, 1.0) - lum(color)).abs() < 1e-5);
}
#[test]
fn weights_balance_contrast_and_invert_shape_the_gray() {
let only_red = GrayscaleConversion { weights: [1.0, 0.0, 0.0, 0.0], ..GrayscaleConversion::LIBRARY };
assert!((only_red.gray([0.6, 1.0, 1.0], 1.0) - 0.6).abs() < 1e-6);
let alpha = GrayscaleConversion { weights: [0.0, 0.0, 0.0, 1.0], ..GrayscaleConversion::LIBRARY };
assert!((alpha.gray([1.0; 3], 0.25) - 0.25).abs() < 1e-6, "Alpha weighs the coverage");
let inverted = GrayscaleConversion { invert: true, mode: ConversionMode::Max, ..GrayscaleConversion::LIBRARY };
assert!((inverted.gray([0.2, 0.7, 0.1], 1.0) - 0.3).abs() < 1e-6);
let contrasted = GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..GrayscaleConversion::LIBRARY };
assert_eq!(contrasted.gray([0.6; 3], 1.0), 1.0);
}
#[test]
fn only_colors_turn_gray() {
let conversion = GrayscaleConversion::LIBRARY;
let height = conversion.channel_value(ChannelKind::Signed, [-0.6; 3], None, 1.0);
let normal = conversion.channel_value(ChannelKind::NormalMap, [0.2, 0.7, 0.9], None, 1.0);
assert!(height.iter().all(|x| (x + 0.6).abs() < 0.02), "a signed height keeps its sign: {height:?}");
assert_eq!(normal, [0.2, 0.7, 0.9]);
}
}
+58
View File
@@ -0,0 +1,58 @@
//! How a color becomes the gray a gradient looks up
use serde::{Deserialize, Serialize};
/// The gray a color reads as, before a gradient maps it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum GrayscaleMode {
/// Halfway between the lightest and darkest component
Desaturation,
/// Weighted by how bright each component looks (what gradients read in projects saved before the modes)
#[default]
Luma,
/// The components' mean
Average,
/// The lightest component
Max,
/// The darkest component
Min,
}
impl GrayscaleMode {
/// Every mode, in the order a list shows them
pub const ALL: [GrayscaleMode; 5] = [GrayscaleMode::Desaturation, GrayscaleMode::Luma, GrayscaleMode::Average, GrayscaleMode::Max, GrayscaleMode::Min];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "Desaturation",
GrayscaleMode::Luma => "Luma",
GrayscaleMode::Average => "Average",
GrayscaleMode::Max => "Max",
GrayscaleMode::Min => "Min",
}
}
/// The id `effect.set {grayscaleMode}` takes
pub fn id(self) -> &'static str {
match self {
GrayscaleMode::Desaturation => "desaturation",
GrayscaleMode::Luma => "luma",
GrayscaleMode::Average => "average",
GrayscaleMode::Max => "max",
GrayscaleMode::Min => "min",
}
}
/// The gray of linear color `[r, g, b]`
pub fn gray(self, [r, g, b]: [f32; 3]) -> f32 {
match self {
GrayscaleMode::Desaturation => (r.max(g).max(b) + r.min(g).min(b)) / 2.0,
GrayscaleMode::Luma => crate::blend::lum([r, g, b]),
GrayscaleMode::Average => (r + g + b) / 3.0,
GrayscaleMode::Max => r.max(g).max(b),
GrayscaleMode::Min => r.min(g).min(b),
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! Height To Normal's settings: the layer's Height turned into its Normal
use serde::{Deserialize, Serialize};
/// A Height To Normal filter: the normal of the slopes of the layer's Height, over or in place of its Normal
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HeightToNormal {
/// Overwrite Existing Normal: the made normal replaces the Normal below instead of being laid over it
pub overwrite: bool,
/// Use World Units: the slope comes from Surface Size and Height Depth instead of Normal Intensity
pub world_units: bool,
/// Surface Size (cm): how wide a UV tile is on the model
pub surface_size: f32,
/// Height Depth (cm): how deep a height of 1 is
pub height_depth: f32,
/// Normal Intensity: how strongly the slopes tilt the normal without world units
pub intensity: f32,
}
impl HeightToNormal {
/// A new Height To Normal
pub const LIBRARY: HeightToNormal = HeightToNormal { overwrite: true, world_units: true, surface_size: 300.0, height_depth: 16.0, intensity: 10.0 };
/// The smallest Surface Size: whole cm, so the reference's 0.1 rounds up to 1
pub const MIN_SURFACE_SIZE: f32 = 1.0;
/// The largest Surface Size (cm)
pub const MAX_SURFACE_SIZE: f32 = 1000.0;
/// The largest Height Depth (cm)
pub const MAX_HEIGHT_DEPTH: f32 = 100.0;
/// The largest Normal Intensity
pub const MAX_INTENSITY: f32 = 50.0;
/// Height Depth over Surface Size a Normal Intensity of 1 tilts like (so the default 10 matches the default 16 cm over 300 cm)
const INTENSITY_UNIT: f32 = Self::LIBRARY.height_depth / Self::LIBRARY.surface_size / Self::LIBRARY.intensity;
/// How much a change of height per texel tilts the normal at `res` texels across a UV tile (0 for hostile values)
pub fn strength(&self, res: u32) -> f32 {
let finite = |value: f32, max: f32| if value.is_finite() { value.clamp(0.0, max) } else { 0.0 };
if self.world_units && !self.surface_size.is_finite() {
return 0.0;
}
let per_tile = if self.world_units {
finite(self.height_depth, Self::MAX_HEIGHT_DEPTH) / finite(self.surface_size, Self::MAX_SURFACE_SIZE).max(Self::MIN_SURFACE_SIZE)
} else {
finite(self.intensity, Self::MAX_INTENSITY) * Self::INTENSITY_UNIT
};
per_tile * res as f32
}
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
let strength = self.strength(res);
let (x, y) = (-gx * strength, gy * strength);
let length = (x * x + y * y + 1.0).sqrt();
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn world_units_and_normal_intensity_tilt_the_normal_up_the_slope() {
let filter = HeightToNormal::LIBRARY;
assert_eq!(filter.normal([0.0, 0.0], 2048), [0.0, 0.0, 1.0], "a flat height");
let [x, y, z] = filter.normal([0.01, 0.0], 2048);
assert!(x < 0.0 && y == 0.0 && z > 0.0, "rising to the right faces left");
let expected = 0.01 * 16.0 / 300.0 * 2048.0;
assert!((-x / z - expected).abs() < 1e-4, "16 cm over 300 cm");
let intensity = HeightToNormal { world_units: false, ..filter };
assert!((intensity.strength(2048) - filter.strength(2048)).abs() < 1e-3, "Normal Intensity 10 matches the world default");
assert!(HeightToNormal { intensity: 20.0, ..intensity }.strength(2048) > intensity.strength(2048));
assert!(HeightToNormal { height_depth: 32.0, ..filter }.strength(2048) > filter.strength(2048));
assert_eq!(filter.normal([0.0, 0.01], 2048)[1].signum(), 1.0, "rising down the image faces up");
assert_eq!(HeightToNormal { surface_size: f32::NAN, ..filter }.strength(2048), 0.0);
let hostile = HeightToNormal { surface_size: f32::NAN, height_depth: f32::INFINITY, ..filter };
assert!(hostile.normal([1.0, 1.0], 2048).iter().all(|v| v.is_finite()));
}
}
+84
View File
@@ -0,0 +1,84 @@
//! The color space a Highpass filter works in
use serde::{Deserialize, Serialize};
use crate::gradient_input::{linear_to_srgb, srgb_to_linear};
/// ACEScg (AP1) to linear sRGB (Rec. 709) primaries, white point adapted (the published ACES matrix)
const AP1_TO_REC709: [[f32; 3]; 3] = [[1.705_05, -0.621_79, -0.083_26], [-0.130_26, 1.140_80, -0.010_55], [-0.024_00, -0.128_97, 1.152_97]];
/// Linear sRGB (Rec. 709) to ACEScg (AP1) primaries: the inverse of [`AP1_TO_REC709`]
const REC709_TO_AP1: [[f32; 3]; 3] = [[0.613_10, 0.339_52, 0.047_37], [0.070_19, 0.916_35, 0.013_45], [0.020_62, 0.109_57, 0.869_81]];
/// Where a Highpass takes its detail: in the working space (masks always), or in sRGB from linear sRGB or ACEScg colors
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum HighpassSpace {
/// The values as they are (what a Highpass did in projects saved before the Color Space)
#[default]
Working,
/// Colors read as linear sRGB, filtered sRGB encoded
SrgbFromLinear,
/// Colors read as ACEScg, filtered sRGB encoded
SrgbFromAcescg,
}
impl HighpassSpace {
/// Every space, in the order a list shows them
pub const ALL: [HighpassSpace; 3] = [HighpassSpace::Working, HighpassSpace::SrgbFromLinear, HighpassSpace::SrgbFromAcescg];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
HighpassSpace::Working => "Working space / Mask",
HighpassSpace::SrgbFromLinear => "sRGB (from Linear sRGB)",
HighpassSpace::SrgbFromAcescg => "sRGB (from ACEScg)",
}
}
/// The id `effect.set {colorSpace}` takes
pub fn id(self) -> &'static str {
match self {
HighpassSpace::Working => "working",
HighpassSpace::SrgbFromLinear => "srgbFromLinear",
HighpassSpace::SrgbFromAcescg => "srgbFromAcescg",
}
}
/// Straight color `rgb` in this space
pub fn encode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(linear_to_srgb),
HighpassSpace::SrgbFromAcescg => times(&AP1_TO_REC709, rgb).map(linear_to_srgb),
}
}
/// Straight color `rgb` of this space back in the working space
pub fn decode(self, rgb: [f32; 3]) -> [f32; 3] {
match self {
HighpassSpace::Working => rgb,
HighpassSpace::SrgbFromLinear => rgb.map(srgb_to_linear),
HighpassSpace::SrgbFromAcescg => times(&REC709_TO_AP1, rgb.map(srgb_to_linear)),
}
}
}
/// Matrix `m` times column `v`
fn times(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
m.map(|row| row[0] * v[0] + row[1] * v[1] + row[2] * v[2])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_space_round_trips_a_color_in_its_gamut() {
for space in HighpassSpace::ALL {
let back = space.decode(space.encode([0.5, 0.4, 0.3]));
assert!(back.iter().zip([0.5, 0.4, 0.3]).all(|(a, b)| (a - b).abs() < 2e-3), "{space:?}: {back:?}");
}
assert!((HighpassSpace::SrgbFromLinear.encode([0.214; 3])[0] - 0.5).abs() < 1e-2, "linear mid gray is sRGB 0.5");
}
}
+89
View File
@@ -0,0 +1,89 @@
//! An image a filter reads besides the stack it filters (its image inputs), as a source on the filter's effect
use crate::{Filter, Source, SourceColorMode, TargetColorMode, WarpSourceMode};
/// One image input of a filter: the key its source is stored under on the effect, its name and the gray it reads until a source is set
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ImageInput {
pub id: &'static str,
pub label: &'static str,
/// The gray the input reads while no source is set (what the filter did before it had the input)
pub default: f32,
/// Added by a mode of the filter (shown under that mode), not one of its Image inputs
pub by_mode: bool,
}
impl ImageInput {
/// Bevel Smooth's and Directional Distance's Distance Map: scales the distance per texel
pub const DISTANCE_MAP: ImageInput = ImageInput { id: "distanceMap", label: "Distance Map", default: 1.0, by_mode: false };
/// Warp's and Blur Slope's Custom Noise (Source Type Custom Noise): the source its texels move or read along; mid gray moves nothing
pub const CUSTOM_NOISE: ImageInput = ImageInput { id: "customNoise", label: "Custom Noise", default: 0.5, by_mode: true };
/// The Custom Input of Grayscale Conversion (the color it reads instead of the channel) and Anisotropic Kuwahara (its direction's gray); mid gray until set
pub const CUSTOM_INPUT: ImageInput = ImageInput { id: "customInput", label: "Custom Input", default: 0.5, by_mode: true };
/// Color Match's Input (Source Color Mode Input): the color each texel moves from; mid gray until set
pub const SOURCE_INPUT: ImageInput = ImageInput { id: "input", label: "Input", default: 0.5, by_mode: true };
/// Color Match's Image Input (Target Color Mode Image Input): the color each texel moves to; mid gray until set
pub const TARGET_INPUT: ImageInput = ImageInput { id: "imageInput", label: "Image Input", default: 0.5, by_mode: true };
/// The image inputs `filter` reads now (a mode's input only while that mode is on)
pub fn of(filter: &Filter) -> Vec<ImageInput> {
Self::all(filter).iter().copied().filter(|input| input.is_on(filter)).collect()
}
/// The input of `filter` stored under `id`, also while its mode is off
pub fn named(filter: &Filter, id: &str) -> Option<ImageInput> {
Self::all(filter).iter().find(|input| input.id == id).copied()
}
/// Every image input `filter` has, its modes' inputs also while those modes are off
fn all(filter: &Filter) -> &'static [ImageInput] {
match filter {
Filter::BevelSmooth(_) | Filter::DirectionalDistance(_) => &[Self::DISTANCE_MAP],
Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_) => &[Self::CUSTOM_NOISE],
Filter::GrayscaleConversion(_) | Filter::AnisotropicKuwahara(_) => &[Self::CUSTOM_INPUT],
Filter::ColorMatch(_) => &[Self::SOURCE_INPUT, Self::TARGET_INPUT],
_ => &[],
}
}
/// Whether `filter` reads this input now: an input a mode adds only while that mode is on
fn is_on(&self, filter: &Filter) -> bool {
match filter {
Filter::SourceWarp(warp) => warp.source.mode == WarpSourceMode::CustomNoise,
Filter::SourceSlopeBlur(slope) => slope.source.mode == WarpSourceMode::CustomNoise,
Filter::GrayscaleConversion(conversion) => conversion.custom_input,
Filter::AnisotropicKuwahara(kuwahara) => kuwahara.custom_input,
Filter::ColorMatch(matcher) if *self == Self::SOURCE_INPUT => matcher.source_mode == SourceColorMode::Input,
Filter::ColorMatch(matcher) => matcher.target_mode == TargetColorMode::ImageInput,
_ => true,
}
}
/// The source the input reads while none is set
pub fn default_source(&self) -> Source {
Source::Uniform([self.default; 3])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{BevelSmooth, SourceWarp, WarpSource};
#[test]
fn a_warp_has_its_custom_noise_only_in_that_source_mode() {
let warp = SourceWarp::LIBRARY;
assert!(ImageInput::of(&Filter::SourceWarp(warp)).is_empty());
let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, ..warp.source }, ..warp };
assert_eq!(ImageInput::of(&Filter::SourceWarp(custom)), vec![ImageInput::CUSTOM_NOISE]);
assert_eq!(ImageInput::named(&Filter::SourceWarp(warp), "customNoise"), Some(ImageInput::CUSTOM_NOISE), "kept while the mode is off");
assert_eq!(ImageInput::of(&Filter::BevelSmooth(BevelSmooth::LIBRARY)), vec![ImageInput::DISTANCE_MAP]);
assert_eq!(ImageInput::named(&Filter::BevelSmooth(BevelSmooth::LIBRARY), "customNoise"), None);
assert_eq!(ImageInput::DISTANCE_MAP.default_source(), Source::Uniform([1.0; 3]));
}
}
+569 -85
View File
@@ -1,10 +1,16 @@
//! Layers, masks, effects and fill sources.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{Backface, BakedMap, BlendMode, Channel, ChannelKind, CompareSource, ContentsOffset, DepthCulling, Projector, RandomizedSeed, ShapeCrop, lum};
use crate::curve_preset::CurvePreset;
use crate::gradient_input::{GradientInput, ramp, shape_gray};
use crate::{
AnisotropicKuwahara, Backface, BakedMap, Bevel, BevelSmooth, BlendMode, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, DepthCulling,
DirectionalDistance, DirectionalLight, GrayscaleConversion, HeightToNormal, HighpassSpace, MaskOutline, Mirror, PbrValidate, Projector, RandomizedSeed,
ShapeCrop, SourceSlopeBlur, SourceWarp, StylizedLighting, SunAndSky, ThresholdMode, TileTransform, finite_unit, lum,
};
mod curvature_detail;
mod curvature_mode;
@@ -884,7 +890,8 @@ impl Levels {
const MIN_GAMMA: f32 = 1e-3;
pub fn apply(&self, x: f32) -> f32 {
let between = (x - self.in_low) / (self.in_high - self.in_low).max(Self::MIN_INPUT_RANGE);
let range = self.in_high - self.in_low;
let between = (x - self.in_low) / if range > 0.0 { range } else { Self::MIN_INPUT_RANGE };
// Past the input handles an unclamped remap carries on in a straight line (gamma only bends the part between them)
let between = if self.clamp || (0.0..=1.0).contains(&between) { between.clamp(0.0, 1.0).powf(1.0 / self.gamma.max(Self::MIN_GAMMA)) } else { between };
@@ -1050,13 +1057,21 @@ impl Generator {
pub enum Filter {
Blur {
radius: f32,
/// Reads past the texture's edges from its opposite side, so tiling textures stay seamless; off in projects saved before it
#[serde(default, skip_serializing_if = "is_false")]
wrap: bool,
},
Sharpen {
amount: f32,
},
Invert,
/// Invert switched off: changes nothing until it is switched back on ([`Filter::Invert`])
InvertOff,
Threshold {
level: f32,
/// Which side of `level` turns white; at or above it in projects saved before the modes
#[serde(default, skip_serializing_if = "ThresholdMode::is_default")]
mode: ThresholdMode,
},
/// Hue/saturation/lightness shift (color channels; lightness only on grays and masks).
/// `hue` is in turns, `saturation` and `lightness` in −1..1; all zero = unchanged.
@@ -1064,25 +1079,76 @@ pub enum Filter {
hue: f32,
saturation: f32,
lightness: f32,
/// Shifts in a perceptual color space (OKLCh), so a hue turn keeps the colors' lightness; plain HSL in projects saved before it
#[serde(default, skip_serializing_if = "is_false")]
perceptive: bool,
},
/// Contrast around mid gray and a luminosity shift, both −1..1 (0 = unchanged).
ContrastLuminosity {
contrast: f32,
luminosity: f32,
},
/// Contrast, luminosity (both −1..1, 0 = unchanged) and saturation (0..1, 0.5 = unchanged) for the shadows, midtones and highlights, each `[contrast, luminosity, saturation]`, weighted by the texel's lightness as [`Filter::ColorBalance`]
ColorCorrect {
shadows: [f32; 3],
midtones: [f32; 3],
highlights: [f32; 3],
},
/// Color offsets (−1..1 per component) weighted towards the shadows, midtones and highlights.
ColorBalance {
shadows: [f32; 3],
midtones: [f32; 3],
highlights: [f32; 3],
},
/// Luminance mapped through evenly spaced colors (linear RGB; scalars read their gray).
/// The texel's gray (after `input`) mapped through a ramp of colors (scalars read the ramp's gray)
GradientMap {
colors: Vec<[f32; 3]>,
/// Where each color sits on the ramp (0..1); evenly spaced in projects saved before
#[serde(default, skip_serializing_if = "Vec::is_empty")]
positions: Vec<f32>,
/// How many of `colors` the ramp uses (2..10), the rest kept for later; all of them in projects saved before
#[serde(default, skip_serializing_if = "Option::is_none")]
quantity: Option<u8>,
/// How a texel becomes the position it reads; luma, untouched, in projects saved before
#[serde(default, skip_serializing_if = "GradientInput::is_unchanged")]
input: GradientInput,
/// Blends neighbouring colors in linear RGB (off: in sRGB, as a color picker shows them); on in projects saved before
#[serde(default = "yes", skip_serializing_if = "is_true")]
linear: bool,
/// Shows the ramp itself across the texture (left to right) in place of the mapped values
#[serde(default, skip_serializing_if = "is_false")]
debug: bool,
},
/// Values remapped through a preset curve, after balance, contrast and invert like a gradient's input
GradientCurve {
preset: CurvePreset,
invert: bool,
balance: f32,
contrast: f32,
},
/// A color read off a gradient source at `position` across it (`vertical`: down it); the source is a uniform color
GradientDynamic {
vertical: bool,
position: f32,
color: [f32; 3],
},
/// Quantize to `levels` steps (2..64).
Posterize {
levels: f32,
/// Steps the content's coverage too (Apply to Alpha); off in projects saved before it
#[serde(default, skip_serializing_if = "is_false")]
alpha: bool,
},
/// The values between `min` and `max` eased from black to white (smoothstep); outside them black or white
Smoothstep {
min: f32,
max: f32,
},
/// Heights flipped (`invert`), scaled by `multiply` and raised by `offset` around mid gray
HeightAdjust {
invert: bool,
offset: f32,
multiply: f32,
},
/// Keep values within `min..max`.
Clamp {
@@ -1094,6 +1160,9 @@ pub enum Filter {
HistogramScan {
position: f32,
contrast: f32,
/// Scans from the other end: the position read as 1 − position (Invert Position); off in projects saved before it
#[serde(default, skip_serializing_if = "is_false")]
invert_position: bool,
},
/// The values squeezed towards `position`: `range` 1 keeps them, 0 sets them all to it.
HistogramRange {
@@ -1104,68 +1173,147 @@ pub enum Filter {
HistogramShift {
offset: f32,
},
/// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K,
/// `scale` noise features per UV unit.
/// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K, `scale` noise features per UV unit (projects saved before the warp modes; new ones are [`Filter::SourceWarp`])
Warp {
intensity: f32,
scale: f32,
seed: u32,
/// Divides `intensity` (1, 10, 100 or 1000) for fine displacements; 1 in projects saved before it
#[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")]
divider: u16,
},
/// Blur along one direction: `radius` in texels at 2K, `angle` in degrees.
DirectionalBlur {
radius: f32,
angle: f32,
},
/// Smear values downhill along a noise height field ("slope blur"): `radius` in texels at
/// 2K, `scale` noise features per UV unit.
/// Values smeared downhill along a noise height field: `radius` in texels at 2K, `scale` noise features per UV unit (projects saved before its source settings)
SlopeBlur {
radius: f32,
scale: f32,
seed: u32,
/// Divides `radius` like [`Filter::Warp`]'s divider
#[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")]
divider: u16,
},
/// The detail finer than `radius` (texels at 2K) around mid gray: the value minus its blur.
HighPass {
radius: f32,
/// Color Space: colors filtered in sRGB from linear sRGB or ACEScg
#[serde(default, skip_serializing_if = "is_working_space")]
space: HighpassSpace,
/// Apply To Alpha: the content's coverage takes its detail too
#[serde(default, skip_serializing_if = "is_false")]
alpha: bool,
},
/// Gradient magnitude across `width` texels at 2K: edges light, flat areas black.
EdgeDetect {
width: f32,
},
/// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees).
/// Like [`Filter::Warp`], but every texel moves along one direction (`angle` in degrees; projects saved before the warp modes)
DirectionalWarp {
intensity: f32,
angle: f32,
scale: f32,
seed: u32,
/// Divides `intensity` like [`Filter::Warp`]'s divider
#[serde(default = "unit_divider", skip_serializing_if = "is_unit_divider")]
divider: u16,
},
/// Colors to their luminance (scalars and masks unchanged).
/// Colors to their luminance (scalars and masks unchanged): projects saved before Grayscale Conversion's settings
Grayscale,
/// The gray of every channel (or of its Custom Input) by its mode and weights, balanced, contrasted and maybe inverted
GrayscaleConversion(GrayscaleConversion),
/// Flip the green component of normal maps (OpenGL ↔ DirectX); other channels unchanged.
NormalInvert,
/// Shapes rounded off at their edges: values ramp up from 0 at a shape's edge to their own
/// level over about `width` texels at 2K (a mask's or height's bevel).
Bevel {
width: f32,
/// Reads past the texture's edges like [`Filter::Blur`]'s wrap
#[serde(default, skip_serializing_if = "is_false")]
wrap: bool,
},
/// Square cells `size` texels at 2K across, each the value at its center.
/// Shapes sloped at their edge, inwards or outwards over a share of the UV tile (projects saved before keep [`Filter::Bevel`])
DistanceBevel(Bevel),
/// Texels read from where a source sends them, in one of the warp modes (projects saved before keep [`Filter::Warp`] and [`Filter::DirectionalWarp`])
SourceWarp(SourceWarp),
/// Values read downhill along a source's slope, blended (projects saved before keep [`Filter::SlopeBlur`])
SourceSlopeBlur(SourceSlopeBlur),
/// A smooth ramp from the shapes' edge, outwards, inwards or across it
BevelSmooth(BevelSmooth),
/// A trail fading away from the shapes in one direction
DirectionalDistance(DirectionalDistance),
/// One side of an axis (or one quarter) of each UV tile copied over the rest
Mirror(Mirror),
/// Each UV tile's content scaled, turned, moved and flipped, repeating or not
Transform(TileTransform),
/// A band along the edge where values cross a threshold
MaskOutline(MaskOutline),
/// Square cells `size` texels at 2K across, each the value at its center (Pixelate; see [`Filter::pixels_amount`])
Mosaic {
size: f32,
/// Steps the content's coverage into the cells too (Apply To Alpha); on in projects saved before the switch
#[serde(default = "yes", skip_serializing_if = "is_true")]
alpha: bool,
},
/// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around
/// bright areas.
/// Painterly smoothing along the strokes' direction: each texel the mean of the calmest sector around it
AnisotropicKuwahara(AnisotropicKuwahara),
/// Base colors outside the physically plausible ranges shown in red (reads the layer's metal)
PbrValidate(PbrValidate),
/// Height To Normal: the layer's Height turned into its Normal
HeightToNormal(HeightToNormal),
/// Color Match: the colors moved so a source color (the texture's mean by default) lands on a target color
ColorMatch(ColorMatch),
/// Stair-stepped edges smoothed by blending across them (FXAA)
Fxaa {
/// Smooths the content's coverage too (Affect Alpha Channel)
#[serde(default, skip_serializing_if = "is_false")]
alpha: bool,
},
/// Adds a blur of the values (`radius` texels at 2K) times `amount`: light bleeds around bright areas (projects saved before the halo glow below)
Glow {
radius: f32,
amount: f32,
},
/// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by
/// `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y
/// (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals.
/// A halo in `color` around the shapes (content coverage, mask values), inside them below 0 `width`; see [`Filter::HALO_REACH`]
HaloGlow {
/// Laid on a mask as white rather than the color's luminance (Used on a Mask)
on_mask: bool,
/// Ends sharper (Mode Precise) instead of fading out (Soft)
precise: bool,
width: f32,
spread: f32,
opacity: f32,
color: [f32; 3],
},
/// The shapes in `color` laid under them, moved `distance` of a UV tile away from a light at `angle` and blurred over `size`
DropShadow {
angle: f32,
distance: f32,
size: f32,
spread: f32,
opacity: f32,
color: [f32; 3],
},
/// Lighting painted into the base color: `ambient` (times the baked ambient occlusion by `occlusion`) plus a directional light of strength `light` from `azimuth` around +Y (degrees from +Z) and `elevation` above the horizon (degrees), on the mesh's normals. `stylized` adds sky colors, more lights, cavity, edges and highlights (Baked Lighting Stylized); projects saved before have none and light as they did
BakedLighting {
azimuth: f32,
elevation: f32,
light: f32,
ambient: f32,
occlusion: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
stylized: Option<Box<StylizedLighting>>,
},
/// The base color lit by the viewport environment (its diffuse light), turned `horizontal` and tilted `vertical` degrees, brighter by 2^`exposure`, on the mesh's normals tilted by the baked height (`height_intensity`) and darkened by the baked ambient occlusion (`ambient_occlusion` on the diffuse light, `specular_occlusion` on the reflections)
EnvironmentLighting {
horizontal: f32,
vertical: f32,
exposure: f32,
height_intensity: f32,
ambient_occlusion: f32,
specular_occlusion: f32,
},
/// Colors near `from` (within `tolerance`, fading out over `softness`, as RGB distance
/// 0..1) shifted by `to − from`, so their shading and texture stay (linear RGB).
@@ -1175,13 +1323,77 @@ pub enum Filter {
tolerance: f32,
softness: f32,
},
/// No filter picked yet: changes nothing
Empty,
}
/// Whether a switch is on, its default where it defaults to on (not saved then)
/// The divider of projects saved before intensities had one
fn unit_divider() -> u16 {
1
}
/// Serde default of a switch that was on in projects saved before it existed
fn yes() -> bool {
true
}
/// Whether a switch is on, its default where it defaults to [`yes`] (not saved then)
fn is_true(on: &bool) -> bool {
*on
}
/// Whether a high pass runs in the working color space, its default (not saved then)
fn is_working_space(space: &HighpassSpace) -> bool {
*space == HighpassSpace::Working
}
/// Whether a switch is off, its default (not saved then)
fn is_false(on: &bool) -> bool {
!*on
}
/// Whether `divider` leaves its intensity as it is (not saved then)
fn is_unit_divider(divider: &u16) -> bool {
*divider == 1
}
/// The fewest and most steps a posterize keeps
pub const POSTERIZE_LEVELS_MIN: f32 = 2.0;
pub const POSTERIZE_LEVELS_MAX: f32 = 64.0;
/// Filter sizes are given in texels at 2K, as in the reference workflow
pub const SIZE_REFERENCE_RES: f32 = 2048.0;
/// `x` (0..1) rounded to `levels` steps (2..64) from black to white
pub fn posterize(x: f32, levels: f32) -> f32 {
let steps = (levels.clamp(POSTERIZE_LEVELS_MIN, POSTERIZE_LEVELS_MAX).round() - 1.0).max(1.0);
let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
(x * steps).round() / steps
}
/// Bounds of a smoothstep closer than this are a step: easing over a narrower span would divide by almost nothing
const MIN_SMOOTHSTEP_SPAN: f32 = 1e-6;
/// 0 at or below `min`, 1 at or above `max`, eased between them (swapped bounds are read in order; equal bounds are a step)
pub(crate) fn smoothstep(min: f32, max: f32, x: f32) -> f32 {
let (low, high) = (finite_or(min.min(max), 0.0), finite_or(min.max(max), 1.0));
if !x.is_finite() {
return 0.0;
}
if high - low <= MIN_SMOOTHSTEP_SPAN {
return if x >= high { 1.0 } else { 0.0 };
}
let t = ((x - low) / (high - low)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// `v`, or `fallback` where it is not a number
fn finite_or(v: f32, fallback: f32) -> f32 {
if v.is_finite() { v } else { fallback }
}
/// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1.
fn shift_unit(x: f32, amount: f32) -> f32 {
let a = amount.clamp(-1.0, 1.0);
@@ -1225,11 +1437,28 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [
if s <= 0.0 {
return [l; 3];
}
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
let p = 2.0 * l - q;
[hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)]
}
/// Smooth weights of the shadows, midtones and highlights at lightness `l` (0..1), summing to 1: shadows fade out and highlights in with lightness
fn tone_weights(l: f32) -> (f32, f32, f32) {
((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l)
}
/// [`hsl_adjust`] in OKLCh: the hue turns and the chroma scales (`saturation` −1 = gray, 1 = twice as vivid) at the color's own perceived lightness, which `lightness` then pushes towards white or black (linear 0..1 colors)
pub fn perceptive_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] {
let clean = |x: f32| if x.is_finite() { x } else { 0.0 };
let [l, a, b] = crate::oklab::from_linear(rgb.map(|v| clean(v).clamp(0.0, 1.0)));
let (sin, cos) = (clean(hue) * std::f32::consts::TAU).sin_cos();
let chroma = 1.0 + clean(saturation).clamp(-1.0, 1.0);
let (a, b) = ((a * cos - b * sin) * chroma, (a * sin + b * cos) * chroma);
let l = shift_unit(l.clamp(0.0, 1.0), clean(lightness));
crate::oklab::to_linear([l, a, b]).map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 })
}
/// Apply a 0..1 function to each component of a channel value: signed values map through
/// 0..1, normals are left alone.
pub fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
@@ -1253,6 +1482,74 @@ pub fn gradient(colors: &[[f32; 3]], t: f32) -> Option<[f32; 3]> {
}
impl Filter {
/// The most Baked Lighting Environment's Exposure brightens or darkens, in stops
pub const ENVIRONMENT_EXPOSURE_STOPS: f32 = 5.0;
/// The choices of an intensity's divider
pub const DIVIDERS: [u16; 4] = [1, 10, 100, 1000];
/// The most colors a gradient's Color Quantity uses
pub const MAX_GRADIENT_COLORS: u8 = 10;
/// Texels at 2K a Blur Intensity (Blur, Blur Directional) of 1 reaches
pub const BLUR_INTENSITY: f32 = 16.0;
/// Texels at 2K a halo glow's Width or a drop shadow's Size of 1 reaches
pub const HALO_REACH: f32 = 128.0;
/// A drop shadow is cast at most this share of a UV tile away, either way
pub const SHADOW_DISTANCE_MAX: f32 = 0.5;
/// The noise features per UV unit a noise-driven warp or slope blur reads, at least and at most
pub const NOISE_SCALE_MIN: f32 = 0.01;
pub const NOISE_SCALE_MAX: f32 = 1000.0;
/// A gradient as projects saved before the Input Transformation read it: `colors` evenly spaced, luma, linear blending
pub fn even_gradient(colors: Vec<[f32; 3]>) -> Filter {
Filter::GradientMap { colors, positions: Vec::new(), quantity: None, input: GradientInput::default(), linear: true, debug: false }
}
/// Histogram Shift's Position (0..1) for its `offset`: a shift back by 1 − position, so 1 shifts nothing (offsets above 0 saved before the Position read as themselves, the same shift but for white and black)
pub fn shift_position(offset: f32) -> f32 {
let offset = if offset.is_finite() { offset.clamp(-1.0, 1.0) } else { 0.0 };
if offset <= 0.0 { offset + 1.0 } else { offset }
}
/// The Histogram Shift offset a Position (0..1) sets (see [`Filter::shift_position`])
pub fn shift_offset(position: f32) -> f32 {
let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 1.0 };
position - 1.0
}
/// Pixelate's Pixels Amount (cells across a UV tile) for a cell `size` in texels at 2K
pub fn pixels_amount(size: f32) -> f32 {
SIZE_REFERENCE_RES / if size.is_finite() { size.max(1.0) } else { SIZE_REFERENCE_RES }
}
/// The cell size in texels at 2K that a Pixels Amount (cells across a UV tile) sets
pub fn pixel_size(amount: f32) -> f32 {
SIZE_REFERENCE_RES / if amount.is_finite() { amount.clamp(1.0, SIZE_REFERENCE_RES) } else { 1.0 }
}
/// The colors a gradient's ramp uses: the first Color Quantity of them (all of them where it has none)
pub fn ramp_colors(&self) -> &[[f32; 3]] {
match self {
Filter::GradientMap { colors, quantity, .. } => {
colors.get(..quantity.map_or(colors.len(), |count| usize::from(count.clamp(2, Self::MAX_GRADIENT_COLORS))).min(colors.len())).unwrap_or(colors)
}
_ => &[],
}
}
/// A gradient's color at ramp position `t` (None for other filters and an empty ramp)
pub fn ramp_at(&self, t: f32) -> Option<[f32; 3]> {
let Filter::GradientMap { positions, linear, .. } = self else { return None };
let colors = self.ramp_colors();
// Evenly spaced linear ramps take the path projects saved before took, so they render bit for bit as before
if positions.is_empty() && *linear { gradient(colors, t) } else { ramp(colors, positions, *linear, t) }
}
/// Whether the filter reads neighbouring texels (the compositor runs it over a region).
pub fn is_neighbourhood(&self) -> bool {
matches!(
@@ -1267,66 +1564,114 @@ impl Filter {
| Filter::DirectionalWarp { .. }
| Filter::Bevel { .. }
| Filter::Mosaic { .. }
| Filter::Fxaa { .. }
| Filter::AnisotropicKuwahara(_)
| Filter::HeightToNormal(_)
| Filter::ColorMatch(_)
| Filter::DistanceBevel(_)
| Filter::SourceWarp(_)
| Filter::SourceSlopeBlur(_)
| Filter::BevelSmooth(_)
| Filter::DirectionalDistance(_)
| Filter::Mirror(_)
| Filter::Transform(_)
| Filter::MaskOutline(_)
| Filter::Glow { .. }
| Filter::HaloGlow { .. }
| Filter::DropShadow { .. }
)
}
/// The filter applied to one value of a channel of `kind` (masks are scalars). None for
/// neighbourhood filters and where it changes nothing (an empty gradient).
pub fn point(&self, kind: ChannelKind, v: [f32; 3]) -> Option<[f32; 3]> {
let unit = |x: f32| if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
// Histogram Scan's narrowest soft cut, so near full contrast stays a finite slope
const SCAN_MIN_WIDTH: f32 = 1e-3;
// Replace Color's least softness, so a hard edge divides by no zero
const REPLACE_MIN_SOFTNESS: f32 = 1e-6;
Some(match self {
Filter::Invert => per_unit(kind, v, |x| 1.0 - x),
Filter::Threshold { level } => per_unit(kind, v, |x| if x >= *level { 1.0 } else { 0.0 }),
Filter::Hsl { hue, saturation, lightness } => match kind {
Filter::Threshold { level, mode } => per_unit(kind, v, |x| if mode.passes(x, *level) { 1.0 } else { 0.0 }),
Filter::Hsl { hue, saturation, lightness, perceptive } => match kind {
ChannelKind::Color if *perceptive => perceptive_adjust(v, *hue, *saturation, *lightness),
ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness),
_ => per_unit(kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]),
},
Filter::ContrastLuminosity { contrast, luminosity } => {
let k = 1.0 + contrast.clamp(-1.0, 1.0);
per_unit(kind, v, |x| unit((x - 0.5) * k + 0.5 + luminosity))
let slope = 1.0 + contrast.clamp(-1.0, 1.0);
per_unit(kind, v, |x| finite_unit((x - 0.5) * slope + 0.5 + luminosity))
}
Filter::ColorCorrect { shadows, midtones, highlights } => {
// [contrast, luminosity, saturation] at the texel's lightness, weighted as color balance
let at = |lightness: f32| -> [f32; 3] {
let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness));
std::array::from_fn(|k| shadows[k] * in_shadows + midtones[k] * in_midtones + highlights[k] * in_highlights)
};
let correct = |x: f32, [contrast, luminosity, _]: [f32; 3]| (x - 0.5) * (1.0 + contrast.clamp(-1.0, 1.0)) + 0.5 + luminosity.clamp(-1.0, 1.0);
match kind {
ChannelKind::Color => {
let tone = at(lum(v));
let corrected = v.map(|x| correct(x, tone));
let gray = lum(corrected);
let gain = 2.0 * tone[2].clamp(0.0, 1.0);
corrected.map(|x| finite_unit(gray + (x - gray) * gain))
}
_ => per_unit(kind, v, |x| finite_unit(correct(x, at(x)))),
}
}
Filter::ColorBalance { shadows, midtones, highlights } => {
// Smooth weights summing to 1: shadows fade out and highlights in with lightness.
let weights = |l: f32| {
let l = unit(l);
((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l)
};
let shift = |k: usize, l: f32| {
let (s, m, h) = weights(l);
shadows.get(k).copied().unwrap_or(0.0) * s + midtones.get(k).copied().unwrap_or(0.0) * m + highlights.get(k).copied().unwrap_or(0.0) * h
let shift = |component: usize, lightness: f32| {
let (in_shadows, in_midtones, in_highlights) = tone_weights(finite_unit(lightness));
shadows.get(component).copied().unwrap_or(0.0) * in_shadows
+ midtones.get(component).copied().unwrap_or(0.0) * in_midtones
+ highlights.get(component).copied().unwrap_or(0.0) * in_highlights
};
match kind {
ChannelKind::Color => {
let l = lum(v);
std::array::from_fn(|k| unit(v[k] + shift(k, l)))
let lightness = lum(v);
std::array::from_fn(|k| finite_unit(v[k] + shift(k, lightness)))
}
_ => per_unit(kind, v, |x| unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)),
_ => per_unit(kind, v, |x| finite_unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)),
}
}
Filter::GradientMap { colors } => match kind {
ChannelKind::Color => gradient(colors, lum(v))?,
_ => per_unit(kind, v, |x| gradient(colors, x).map_or(x, lum)),
Filter::GradientMap { input, .. } => input.map(kind, v, |position| self.ramp_at(position))?,
Filter::GradientCurve { preset, invert, balance, contrast } => per_unit(kind, v, |x| preset.at(shape_gray(x, *balance, *contrast, *invert))),
Filter::GradientDynamic { color, .. } => match kind {
ChannelKind::Color => color.map(finite_unit),
_ => per_unit(kind, v, |_| finite_unit(lum(*color))),
},
Filter::Posterize { levels } => {
let steps = (levels.clamp(2.0, 64.0).round() - 1.0).max(1.0);
per_unit(kind, v, |x| (unit(x) * steps).round() / steps)
Filter::Posterize { levels, .. } => per_unit(kind, v, |x| posterize(x, *levels)),
Filter::Smoothstep { min, max } => per_unit(kind, v, |x| smoothstep(*min, *max, x)),
Filter::HeightAdjust { invert, offset, multiply } => {
let (offset, multiply) = (finite_or(*offset, 0.0), finite_or(*multiply, 1.0));
per_unit(kind, v, |x| {
let x = if *invert { 1.0 - x } else { x };
finite_unit((x - 0.5) * multiply + 0.5 + offset)
})
}
Filter::InvertOff => v,
Filter::Clamp { min, max } => {
let (lo, hi) = (min.min(*max), min.max(*max));
per_unit(kind, v, |x| x.max(lo).min(hi))
let (low, high) = (min.min(*max), min.max(*max));
per_unit(kind, v, |x| x.max(low).min(high))
}
// Full contrast is a threshold: the position itself goes to white.
Filter::HistogramScan { position, contrast } if *contrast >= 1.0 => per_unit(kind, v, |x| if x >= *position { 1.0 } else { 0.0 }),
Filter::HistogramScan { position, contrast } => {
let width = (1.0 - contrast.clamp(0.0, 1.0)).max(1e-3);
per_unit(kind, v, |x| unit((x - position) / width + 0.5))
// Full contrast is a threshold: the position itself goes to white
Filter::HistogramScan { position, contrast, invert_position } => {
let position = if *invert_position { 1.0 - position } else { *position };
if *contrast >= 1.0 {
per_unit(kind, v, |x| if x >= position { 1.0 } else { 0.0 })
} else {
let width = (1.0 - contrast.clamp(0.0, 1.0)).max(SCAN_MIN_WIDTH);
per_unit(kind, v, |x| finite_unit((x - position) / width + 0.5))
}
}
Filter::HistogramRange { range, position } => per_unit(kind, v, |x| unit(position + (x - position) * range)),
Filter::HistogramRange { range, position } => per_unit(kind, v, |x| finite_unit(position + (x - position) * range)),
Filter::HistogramShift { offset } => per_unit(kind, v, |x| {
// Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black.
let y = unit(x) + offset.clamp(-1.0, 1.0);
unit(if y > 1.0 {
// Wrapped by hand: `rem_euclid` would also send white (1 + 0) to black
let y = finite_unit(x) + offset.clamp(-1.0, 1.0);
finite_unit(if y > 1.0 {
y - 1.0
} else if y < 0.0 {
y + 1.0
@@ -1338,23 +1683,26 @@ impl Filter {
ChannelKind::Color => [lum(v); 3],
_ => v,
},
// Read opaque here: the compositor passes the content's coverage (and a Custom Input) through `GrayscaleConversion::channel_value`
Filter::GrayscaleConversion(conversion) => conversion.channel_value(kind, v, None, 1.0),
Filter::NormalInvert => match kind {
ChannelKind::NormalMap => [v[0], 1.0 - v[1], v[2]],
_ => v,
},
Filter::ReplaceColor { from, to, tolerance, softness } => match kind {
ChannelKind::Color => {
let d = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt();
let (t, s) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0));
let w = if d <= t {
// How far the color is from `from`, 1 across the whole cube
let distance = ((v[0] - from[0]).powi(2) + (v[1] - from[1]).powi(2) + (v[2] - from[2]).powi(2)).sqrt() / 3f32.sqrt();
let (tolerance, softness) = (tolerance.clamp(0.0, 1.0), softness.clamp(0.0, 1.0));
let weight = if distance <= tolerance {
1.0
} else if d >= t + s {
} else if distance >= tolerance + softness {
0.0
} else {
let x = 1.0 - (d - t) / s.max(1e-6);
x * x * (3.0 - 2.0 * x)
let closeness = 1.0 - (distance - tolerance) / softness.max(REPLACE_MIN_SOFTNESS);
closeness * closeness * (3.0 - 2.0 * closeness)
};
std::array::from_fn(|k| unit(v[k] + (to[k] - from[k]) * w))
std::array::from_fn(|k| finite_unit(v[k] + (to[k] - from[k]) * weight))
}
_ => v,
},
@@ -1368,8 +1716,25 @@ impl Filter {
| Filter::DirectionalWarp { .. }
| Filter::Bevel { .. }
| Filter::Mosaic { .. }
| Filter::Fxaa { .. }
| Filter::AnisotropicKuwahara(_)
| Filter::PbrValidate(_)
| Filter::HeightToNormal(_)
| Filter::ColorMatch(_)
| Filter::DistanceBevel(_)
| Filter::SourceWarp(_)
| Filter::SourceSlopeBlur(_)
| Filter::BevelSmooth(_)
| Filter::DirectionalDistance(_)
| Filter::Mirror(_)
| Filter::Transform(_)
| Filter::MaskOutline(_)
| Filter::Glow { .. }
| Filter::BakedLighting { .. } => return None,
| Filter::HaloGlow { .. }
| Filter::DropShadow { .. }
| Filter::BakedLighting { .. }
| Filter::EnvironmentLighting { .. }
| Filter::Empty => return None,
})
}
@@ -1377,43 +1742,97 @@ impl Filter {
match self {
Filter::Blur { .. } => "Blur",
Filter::Sharpen { .. } => "Sharpen",
Filter::Invert => "Invert",
Filter::Invert | Filter::InvertOff => "Invert",
Filter::Threshold { .. } => "Threshold",
Filter::Hsl { .. } => "HSL Perceptive",
Filter::ContrastLuminosity { .. } => "Contrast/Luminosity",
Filter::ContrastLuminosity { .. } => "Contrast Luminosity",
Filter::ColorBalance { .. } => "Color Balance",
Filter::GradientMap { .. } => "Gradient Map",
Filter::ColorCorrect { .. } => "Color Correct",
Filter::GradientMap { .. } => "Gradient",
Filter::GradientCurve { .. } => "Gradient Curve",
Filter::GradientDynamic { .. } => "Gradient Dynamic",
Filter::Posterize { .. } => "Posterize",
Filter::Smoothstep { .. } => "Smoothstep",
Filter::HeightAdjust { .. } => "Height Adjust",
Filter::Clamp { .. } => "Clamp",
Filter::HistogramScan { .. } => "Histogram Scan",
Filter::HistogramRange { .. } => "Histogram Range",
Filter::HistogramShift { .. } => "Histogram Shift",
Filter::Warp { .. } => "Warp",
Filter::DirectionalBlur { .. } => "Blur Directional",
Filter::SlopeBlur { .. } => "Slope Blur",
Filter::HighPass { .. } => "High Pass",
Filter::SlopeBlur { .. } => "Blur Slope",
Filter::HighPass { .. } => "Highpass",
Filter::EdgeDetect { .. } => "Edge Detect",
Filter::DirectionalWarp { .. } => "Warp Directional",
Filter::Grayscale => "Grayscale",
Filter::Grayscale | Filter::GrayscaleConversion(_) => "Grayscale Conversion",
Filter::NormalInvert => "Normal Invert",
Filter::Bevel { .. } => "Bevel",
Filter::Mosaic { .. } => "Mosaic",
Filter::Glow { .. } => "Glow",
Filter::BakedLighting { .. } => "Baked Lighting",
Filter::Mosaic { .. } => "Pixelate",
Filter::Fxaa { .. } => "FXAA (Anti-aliasing)",
Filter::AnisotropicKuwahara(_) => "Anisotropic Kuwahara",
Filter::PbrValidate(_) => "PBR Validate (Metallic Roughness)",
Filter::HeightToNormal(_) => "Height To Normal",
Filter::ColorMatch(_) => "Color Match",
Filter::DistanceBevel(_) => "Bevel",
Filter::SourceWarp(_) => "Warp",
Filter::SourceSlopeBlur(_) => "Blur Slope",
Filter::BevelSmooth(_) => "Bevel Smooth",
Filter::DirectionalDistance(_) => "Directional Distance",
Filter::Mirror(_) => "Mirror",
Filter::Transform(_) => "Transform",
Filter::MaskOutline(_) => "Mask Outline",
Filter::Glow { .. } | Filter::HaloGlow { .. } => "Glow",
Filter::DropShadow { .. } => "Drop Shadow",
Filter::BakedLighting { .. } => "Baked Lighting Stylized",
Filter::EnvironmentLighting { .. } => "Baked Lighting Environment",
Filter::ReplaceColor { .. } => "Replace Color",
Filter::Empty => "Filter (empty)",
}
}
/// Baked lighting's factor on the base color of a surface facing `nrm` (world space) with
/// The label this filter had before it took the reference workflow's name: effects named after it still follow a swap
pub fn former_label(&self) -> Option<&'static str> {
match self {
Filter::ContrastLuminosity { .. } => Some("Contrast/Luminosity"),
Filter::SlopeBlur { .. } | Filter::SourceSlopeBlur(_) => Some("Slope Blur"),
Filter::HighPass { .. } => Some("High Pass"),
Filter::Mosaic { .. } => Some("Mosaic"),
Filter::Grayscale => Some("Grayscale"),
Filter::GradientMap { .. } => Some("Gradient Map"),
Filter::BakedLighting { .. } => Some("Baked Lighting"),
_ => None,
}
}
/// Baked lighting's factor on the base color of a surface facing `normal` (world space) with
/// ambient occlusion `ao` (None for other filters).
pub fn baked_light(&self, nrm: [f32; 3], ao: f32) -> Option<f32> {
let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion } = self else { return None };
let (sa, ca) = azimuth.to_radians().sin_cos();
let (se, ce) = elevation.to_radians().sin_cos();
let facing = (nrm[0] * ce * sa + nrm[1] * se + nrm[2] * ce * ca).max(0.0);
pub fn baked_light(&self, normal: [f32; 3], ao: f32) -> Option<f32> {
let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, .. } = self else { return None };
let (sin_azimuth, cos_azimuth) = azimuth.to_radians().sin_cos();
let (sin_elevation, cos_elevation) = elevation.to_radians().sin_cos();
// Multiplied in this order so saved projects light exactly as before
let facing = (normal[0] * cos_elevation * sin_azimuth + normal[1] * sin_elevation + normal[2] * cos_elevation * cos_azimuth).max(0.0);
let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 };
let k = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing;
Some(if k.is_finite() { k.max(0.0) } else { 1.0 })
let factor = ambient * (1.0 + (ao - 1.0) * occlusion.clamp(0.0, 1.0)) + light * facing;
Some(if factor.is_finite() { factor.max(0.0) } else { 1.0 })
}
/// The channels a new content effect of the filter starts with on (None: all of them)
pub fn starts_on(&self) -> Option<&'static [Channel]> {
match self {
// PBR Validate reads the metal but changes only the base color, so its Metal pill would do nothing
Filter::BakedLighting { .. } | Filter::EnvironmentLighting { .. } | Filter::ColorMatch(_) | Filter::PbrValidate(_) => Some(&[Channel::BaseColor]),
Filter::HeightToNormal(_) => Some(&[Channel::Normal]),
_ => None,
}
}
/// Baked Lighting Stylized's settings with its sun and sky (None for other filters and a Baked Lighting saved before them)
pub fn stylized_lighting(&self) -> Option<(&StylizedLighting, SunAndSky)> {
let Filter::BakedLighting { azimuth, elevation, light, ambient, occlusion, stylized: Some(stylized) } = self else { return None };
let sun = DirectionalLight { azimuth: *azimuth, elevation: *elevation, intensity: *light, color: stylized.sun_color };
Some((stylized, SunAndSky { sun, sky_intensity: *ambient, diffuse_ao: *occlusion }))
}
}
@@ -1647,7 +2066,7 @@ impl Layer {
LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)),
_ => false,
};
fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.kind.reads(None))
fill || self.mask.iter().flat_map(|mask| mask.effects.iter()).chain(self.content_effects.iter()).any(|effect| effect.reads(None))
}
/// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack
@@ -1667,12 +2086,43 @@ pub struct Effect {
/// A content effect's channels that blend apart from `blend` and `opacity` (none in projects saved before they existed)
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub channel_blends: BTreeMap<Channel, ChannelBlend>,
/// A content effect's channels it leaves as they are (none in projects saved before they could be switched off)
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub off_channels: BTreeSet<Channel>,
/// A filter effect's image inputs set to a source, by [`crate::ImageInput`] id (the others read their default gray)
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub inputs: BTreeMap<String, Source>,
}
impl Effect {
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
// Generators and fills that build a mask usually add on top of the background
Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0, channel_blends: BTreeMap::new() }
Effect {
id,
name: kind.name().to_string(),
visible: true,
kind,
blend: BlendMode::Normal,
opacity: 1.0,
channel_blends: BTreeMap::new(),
off_channels: BTreeSet::new(),
inputs: BTreeMap::new(),
}
}
/// The image resources the effect reads: its kind's ([`EffectKind::images_read`]) and its filter image inputs'
pub fn images_read(&self) -> impl Iterator<Item = &str> {
self.kind.images_read().chain(self.inputs.values().flat_map(Source::images))
}
/// Whether a source of the effect, or one of its image inputs, reads anchor point `anchor` (any anchor point when None)
pub fn reads(&self, anchor: Option<LayerId>) -> bool {
self.kind.reads(anchor) || self.inputs.values().any(|source| source.reads_anchor(anchor))
}
/// The source image input `input` reads: the one set on the effect, else its default gray
pub fn input(&self, input: &crate::ImageInput) -> Source {
self.inputs.get(input.id).cloned().unwrap_or_else(|| input.default_source())
}
/// How the effect blends on `channel` of its layer's content, or on its mask (`None`)
@@ -1680,6 +2130,15 @@ impl Effect {
let shared = ChannelBlend { mode: self.blend, opacity: self.opacity };
channel.and_then(|channel| self.channel_blends.get(&channel).copied()).unwrap_or(shared)
}
/// How the effect lays onto `channel` when composited: [`Self::blend_of`], at no opacity on a channel it is switched off for
pub fn applied_blend(&self, channel: Option<Channel>) -> ChannelBlend {
let blend = self.blend_of(channel);
match channel {
Some(channel) if self.off_channels.contains(&channel) => ChannelBlend { opacity: 0.0, ..blend },
_ => blend,
}
}
}
#[cfg(test)]
@@ -1717,12 +2176,13 @@ mod tests {
}
#[test]
fn a_colour_selection_id_map_is_reported_as_used() {
fn a_colour_selection_id_map_and_a_filter_image_input_are_reported_as_used() {
let mut selection = crate::ColorSelection::new(Vec::new(), 0.0);
selection.id_map = Some("id.png".into());
let effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection));
let mut effect = Effect::new(LayerId(1), EffectKind::ColorSelection(selection));
effect.inputs.insert("mask".into(), Source::image("input.png"));
assert_eq!(effect.kind.images_read().collect::<Vec<_>>(), vec!["id.png"]);
assert_eq!(effect.images_read().collect::<Vec<_>>(), vec!["id.png", "input.png"]);
}
#[test]
@@ -1836,6 +2296,9 @@ mod tests {
assert!((open.apply(0.8) - 1.5).abs() < 1e-6);
assert!((open.apply(0.4) - clamped.apply(0.4)).abs() < 1e-6, "between the handles both remap alike");
let narrow = Levels { in_high: 0.000005, gamma: 2.0, ..Levels::default() };
assert!(narrow.apply(0.0000075) > narrow.out_high);
let bent = Levels { gamma: 2.0, ..open };
assert!((bent.apply(0.0) + 0.5).abs() < 1e-6, "gamma bends only the part between the handles");
}
@@ -1909,6 +2372,21 @@ mod tests {
assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite()));
}
#[test]
fn an_untransformed_gradient_maps_bit_for_bit_as_projects_saved_before_did() {
let colors = vec![[1.0, 0.2, 0.0], [0.1, 0.4, 0.9], [0.0, 0.0, 1.0]];
let gm = Filter::even_gradient(colors.clone());
for step in 0..=1000 {
let x = step as f32 / 1000.0;
let color = [x, 0.5 * x, 1.0 - x];
assert_eq!(gm.point(ChannelKind::Color, color), gradient(&colors, lum(color)), "color {color:?}");
let height = 2.0 * x - 1.0;
let saved_before = per_unit(ChannelKind::Signed, [height; 3], |t| gradient(&colors, t).map_or(t, lum));
assert_eq!(gm.point(ChannelKind::Signed, [height; 3]), Some(saved_before), "height {height}");
}
}
#[test]
fn point_filters_map_values_and_skip_neighbourhood_filters() {
let c = ChannelKind::Color;
@@ -1917,15 +2395,17 @@ mod tests {
assert!(close(contrast.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0]));
assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3]));
let gradient_map = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] };
let gradient_map = Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
assert!(close(gradient_map.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0]));
assert!(close(gradient_map.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0]));
assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing");
assert_eq!(Filter::even_gradient(vec![]).point(c, [0.3; 3]), None, "an empty gradient changes nothing");
assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0]));
let gray_ramp = Filter::even_gradient(vec![[0.0; 3], [1.0; 3]]);
assert!(close(gray_ramp.point(ChannelKind::Signed, [-0.6; 3]).unwrap(), [-0.6; 3]), "a height reads the ramp at its 0..1 place");
assert!(close(Filter::Posterize { levels: 2.0, alpha: false }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0]));
assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic");
let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap();
let scan = |position, contrast| Filter::HistogramScan { position, contrast, invert_position: false }.point(c, [0.2, 0.5, 0.9]).unwrap();
assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values");
assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position");
@@ -1947,7 +2427,11 @@ mod tests {
assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3]));
assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0]));
for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] {
for f in [
Filter::Blur { radius: 1.0, wrap: false },
Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0, divider: 1 },
Filter::DirectionalBlur { radius: 1.0, angle: 0.0 },
] {
assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none());
}
let nan = Filter::ContrastLuminosity { contrast: f32::NAN, luminosity: f32::NAN };
+90 -2
View File
@@ -7,32 +7,77 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod anisotropic_kuwahara;
pub mod backface;
pub mod bake;
pub mod bevel;
pub mod bevel_blur;
pub mod bevel_corner;
pub mod bevel_direction;
pub mod bevel_smooth;
pub mod blend;
mod block_scales;
pub mod channel;
pub mod color_match;
pub mod color_selection;
pub mod compare_source;
pub mod contents_offset;
pub mod conversion_mode;
pub mod cook_resolution;
pub mod curve_preset;
pub mod depth_culling;
pub mod directional_distance;
pub mod directional_light;
mod env_alignment;
pub mod fill_symmetry;
pub mod gradient_input;
pub mod grayscale_conversion;
pub mod grayscale_mode;
pub mod height_to_normal;
pub mod highpass_space;
pub mod image_input;
pub mod layer;
pub mod lighting_output;
pub mod mask_outline;
pub mod mirror;
pub mod mirror_corner;
pub mod mirror_mode;
pub mod oklab;
pub mod outline_position;
pub mod pbr_validate;
mod prepared_color_match;
mod prepared_gradient;
pub mod project;
pub mod projector;
pub mod ramp_curve;
pub mod randomized_seed;
mod saved_decal;
mod saved_projection;
pub mod selection_background;
mod shadow_mode;
pub mod shape_crop;
pub mod slope_blending;
pub mod source_color_mode;
pub mod source_slope_blur;
pub mod source_warp;
pub mod stylized_lighting;
pub mod stylized_shading;
pub mod sun_and_sky;
pub mod symmetry_kind;
pub mod target_color_mode;
pub mod threshold_mode;
pub mod tile_transform;
pub mod unit_value;
pub mod validation_mode;
pub mod warp_blending;
pub mod warp_mode;
pub mod warp_source;
pub mod warp_source_mode;
/// A full turn, in degrees
pub const FULL_TURN_DEGREES: f32 = 360.0;
pub use anisotropic_kuwahara::AnisotropicKuwahara;
pub use backface::Backface;
pub use bake::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap,
@@ -41,29 +86,72 @@ pub use bake::{
NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion,
SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings,
};
pub use bevel::Bevel;
pub use bevel_blur::BevelBlur;
pub use bevel_corner::BevelCorner;
pub use bevel_direction::BevelDirection;
pub use bevel_smooth::BevelSmooth;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use color_match::ColorMatch;
pub use color_selection::ColorSelection;
pub use compare_source::CompareSource;
pub use contents_offset::ContentsOffset;
pub use conversion_mode::ConversionMode;
pub use cook_resolution::CookResolution;
pub use curve_preset::CurvePreset;
pub use depth_culling::DepthCulling;
pub use directional_distance::DirectionalDistance;
pub use directional_light::DirectionalLight;
pub use fill_symmetry::FillSymmetry;
pub use gradient_input::GradientInput;
pub use grayscale_conversion::GrayscaleConversion;
pub use grayscale_mode::GrayscaleMode;
pub use height_to_normal::HeightToNormal;
pub use highpass_space::HighpassSpace;
pub use image_input::ImageInput;
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Filtering, Generator,
GeneratorGlobal, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail,
OutputResolution, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Sampling, ScaleMode, Source, TileBlending, TileGenerator,
TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit,
OutputResolution, POSTERIZE_LEVELS_MAX, POSTERIZE_LEVELS_MIN, PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, SIZE_REFERENCE_RES,
Sampling, ScaleMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient,
hsl_adjust, per_unit, posterize,
};
pub use lighting_output::LightingOutput;
pub use mask_outline::MaskOutline;
pub use mirror::Mirror;
pub use mirror_corner::MirrorCorner;
pub use mirror_mode::MirrorMode;
pub use outline_position::OutlinePosition;
pub use pbr_validate::PbrValidate;
pub use prepared_color_match::PreparedColorMatch;
pub use prepared_gradient::PreparedGradient;
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat,
NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at,
};
pub use projector::Projector;
pub use ramp_curve::RampCurve;
pub use randomized_seed::RandomizedSeed;
pub use selection_background::SelectionBackground;
pub use shape_crop::ShapeCrop;
pub use slope_blending::SlopeBlending;
pub use source_color_mode::SourceColorMode;
pub use source_slope_blur::SourceSlopeBlur;
pub use source_warp::SourceWarp;
pub use stylized_lighting::{DIELECTRIC_REFLECTANCE, StylizedLighting};
pub use stylized_shading::{FLAT_CURVATURE, StylizedShading};
pub use sun_and_sky::SunAndSky;
pub use symmetry_kind::SymmetryKind;
pub use target_color_mode::TargetColorMode;
pub use threshold_mode::ThresholdMode;
pub use tile_transform::{FlipMode, RepeatMode, TileTransform};
pub use unit_value::{at_or_above_threshold, finite_unit};
pub use validation_mode::ValidationMode;
pub use warp_blending::WarpBlending;
pub use warp_mode::WarpMode;
pub use warp_source::WarpSource;
pub use warp_source_mode::WarpSourceMode;
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum CoreError {
+49
View File
@@ -0,0 +1,49 @@
//! What Baked Lighting Stylized paints into the base color
use serde::{Deserialize, Serialize};
/// The lit parts Baked Lighting Stylized keeps
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LightingOutput {
/// The lit surface and its highlights
#[default]
DiffuseSpecular,
/// The lit surface only (what Baked Lighting painted before it had highlights)
Diffuse,
/// The highlights only
Specular,
}
impl LightingOutput {
/// Every output, in the order a list shows them
pub const ALL: [LightingOutput; 3] = [LightingOutput::DiffuseSpecular, LightingOutput::Diffuse, LightingOutput::Specular];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "Diffuse + Specular",
LightingOutput::Diffuse => "Diffuse only",
LightingOutput::Specular => "Specular only",
}
}
/// The id `effect.set {output}` takes
pub fn id(self) -> &'static str {
match self {
LightingOutput::DiffuseSpecular => "diffuseSpecular",
LightingOutput::Diffuse => "diffuse",
LightingOutput::Specular => "specular",
}
}
/// Whether the lit surface is kept
pub fn diffuse(self) -> bool {
self != LightingOutput::Specular
}
/// Whether the highlights are kept
pub fn specular(self) -> bool {
self != LightingOutput::Diffuse
}
}
+94
View File
@@ -0,0 +1,94 @@
//! The Mask Outline filter's settings and the band it draws
use serde::{Deserialize, Serialize};
use crate::{OutlinePosition, RampCurve, at_or_above_threshold};
/// A band along the edge where values cross a threshold, outside, inside or on both sides of the shapes
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaskOutline {
pub position: OutlinePosition,
/// The band on black; otherwise it is laid over the values below
pub from_black: bool,
/// Values at or above it are inside the shapes (0..1)
pub threshold: f32,
/// How far the band reaches from the edge, a fraction of the UV tile (0..1)
pub width: f32,
/// How much of the band fades out towards its far side (0..1)
pub blur: f32,
/// Bends that fade: below 0 it falls off sooner, above 0 later (−1..1)
pub curve: f32,
}
impl MaskOutline {
/// The Mask Outline filter as the library adds it
pub const LIBRARY: MaskOutline = MaskOutline { position: OutlinePosition::Outside, from_black: true, threshold: 1.0, width: 0.05, blur: 0.0, curve: 0.0 };
/// Whether `value` is inside the shapes
pub fn inside(&self, value: f32) -> bool {
at_or_above_threshold(value, self.threshold, Self::LIBRARY.threshold)
}
/// The curve the band's fade takes (Curve), worked out once per filter
pub fn fade_curve(&self) -> RampCurve {
RampCurve::new(0.0, self.curve)
}
/// The band at a texel inside the shapes or not, `closeness` to the edge going from 1 at it to 0 at the band's reach, its fade bent by [`MaskOutline::fade_curve`]
pub fn band(&self, fade_curve: RampCurve, inside: bool, closeness: f32) -> f32 {
let closeness = if closeness.is_finite() { closeness.clamp(0.0, 1.0) } else { 0.0 };
if !self.position.covers(inside) || closeness <= 0.0 || !self.width.is_finite() || self.width <= 0.0 {
return 0.0;
}
let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 };
if blur <= 0.0 {
return 1.0;
}
fade_curve.apply(closeness / blur)
}
/// The result at a texel of value `value`: the band on black, or over the value
pub fn apply(&self, value: f32, band: f32) -> f32 {
if self.from_black { band } else { value.max(band) }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The band with the curve worked out as the filter does
fn band(filter: MaskOutline, inside: bool, closeness: f32) -> f32 {
filter.band(filter.fade_curve(), inside, closeness)
}
#[test]
fn the_band_lies_on_its_side_of_the_edge() {
let outline = MaskOutline::LIBRARY;
assert!(outline.inside(1.0) && !outline.inside(0.99));
assert_eq!(band(outline, false, 0.3), 1.0, "a hard band outside");
assert_eq!(band(outline, true, 0.3), 0.0, "nothing inside an outside band");
assert_eq!(band(outline, false, 0.0), 0.0, "nothing past its reach");
let inside = MaskOutline { position: OutlinePosition::Inside, ..outline };
assert_eq!((band(inside, true, 0.3), band(inside, false, 0.3)), (1.0, 0.0));
let both = MaskOutline { position: OutlinePosition::Both, ..outline };
assert_eq!((band(both, true, 0.3), band(both, false, 0.3)), (1.0, 1.0));
assert_eq!(outline.apply(0.4, 0.0), 0.0, "from black");
assert_eq!(MaskOutline { from_black: false, ..outline }.apply(0.4, 0.0), 0.4, "over the values");
}
#[test]
fn blur_fades_the_band_and_curve_shape_bends_the_fade() {
let soft = MaskOutline { blur: 1.0, ..MaskOutline::LIBRARY };
assert!((band(soft, false, 0.5) - 0.5).abs() < 1e-6, "a linear fade");
assert!(band(MaskOutline { curve: 0.5, ..soft }, false, 0.5) > 0.5, "falls off later");
assert!(band(MaskOutline { curve: -0.5, ..soft }, false, 0.5) < 0.5, "falls off sooner");
assert_eq!(band(MaskOutline { blur: 0.5, ..soft }, false, 0.6), 1.0, "only the far part fades");
assert_eq!(band(MaskOutline { width: f32::NAN, threshold: f32::NAN, ..soft }, false, 0.5), 0.0);
}
}
+104
View File
@@ -0,0 +1,104 @@
//! The Mirror filter's settings and where it reads each texel from
use serde::{Deserialize, Serialize};
use crate::{MirrorCorner, MirrorMode};
/// A mirror filter: one side of an axis (or one quarter) of each UV tile copied over the rest
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mirror {
/// Draws the mirror's axes over the result (Display Debug)
pub debug: bool,
pub mode: MirrorMode,
/// Where the X and Y axes sit across the tile (0..1)
pub offset: [f32; 2],
/// Copies the right (X) or bottom (Y) side instead of the left or top one
pub invert: [bool; 2],
pub corner: MirrorCorner,
}
impl Mirror {
/// The Mirror filter as the library adds it: left onto right across the middle
pub const LIBRARY: Mirror = Mirror { debug: false, mode: MirrorMode::AxisX, offset: [0.5, 0.5], invert: [false, false], corner: MirrorCorner::TopLeft };
/// Half the width of a debug axis line, in texels at 2K
pub const DEBUG_HALF_WIDTH: f32 = 2.0;
/// Where in its tile (0..1 across, 0..1 down) the texel at `uv` reads from; a copy that reaches past an edge folds back at it
pub fn source(&self, [u, v]: [f32; 2]) -> [f32; 2] {
let across = |at: f32, axis: f32, keep_after: bool| {
let copied = if keep_after { at < axis } else { at > axis };
fold(if copied { 2.0 * axis - at } else { at })
};
match self.mode {
MirrorMode::AxisX => [across(u, self.axis(0), self.invert[0]), v],
MirrorMode::AxisY => [u, across(v, self.axis(1), self.invert[1])],
MirrorMode::Corner => {
let (right, bottom) = self.corner.sides();
[across(u, 0.5, right), across(v, 0.5, bottom)]
}
}
}
/// Whether `uv` lies within `half_width` (a fraction of the tile) of one of the mirror's axes
pub fn on_axis(&self, [u, v]: [f32; 2], half_width: f32) -> bool {
let near = |at: f32, axis: f32| (at - axis).abs() <= half_width;
match self.mode {
MirrorMode::AxisX => near(u, self.axis(0)),
MirrorMode::AxisY => near(v, self.axis(1)),
MirrorMode::Corner => near(u, 0.5) || near(v, 0.5),
}
}
/// The axis position along `axis` (0 = X, 1 = Y), within the tile even from a hostile file
fn axis(&self, axis: usize) -> f32 {
let at = self.offset.get(axis).copied().unwrap_or(0.5);
if at.is_finite() { at.clamp(0.0, 1.0) } else { 0.5 }
}
}
/// `at` folded back into 0..1 at the tile's edges, as a mirror reflects
fn fold(at: f32) -> f32 {
let wrapped = at.rem_euclid(2.0);
if wrapped > 1.0 { 2.0 - wrapped } else { wrapped }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_mode_reads_the_kept_side() {
let mut mirror = Mirror::LIBRARY;
assert_eq!(mirror.source([0.25, 0.4]), [0.25, 0.4], "the left side stays");
assert_eq!(mirror.source([0.75, 0.4]), [0.25, 0.4], "the right side reads the left");
mirror.invert[0] = true;
assert_eq!(mirror.source([0.25, 0.4]), [0.75, 0.4], "inverted, the left side reads the right");
mirror.offset[0] = 0.25;
mirror.invert[0] = false;
assert_eq!(mirror.source([0.75, 0.0]), [0.25, 0.0], "a copy past the left edge folds back at it");
mirror.mode = MirrorMode::AxisY;
assert_eq!(mirror.source([0.9, 0.75]), [0.9, 0.25], "Axis Y reads the top for the bottom");
mirror.mode = MirrorMode::Corner;
mirror.corner = MirrorCorner::BottomRight;
assert_eq!(mirror.source([0.25, 0.25]), [0.75, 0.75], "every quarter reads the kept one");
assert_eq!(mirror.source([0.75, 0.75]), [0.75, 0.75]);
assert!(mirror.on_axis([0.5, 0.1], 0.01) && mirror.on_axis([0.1, 0.5], 0.01) && !mirror.on_axis([0.1, 0.1], 0.01));
}
#[test]
fn a_hostile_offset_stays_in_the_tile() {
let mirror = Mirror { offset: [f32::NAN, f32::INFINITY], ..Mirror::LIBRARY };
let [u, v] = mirror.source([0.9, 0.9]);
assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v));
}
}
+49
View File
@@ -0,0 +1,49 @@
//! The quarter a corner mirror copies
use serde::{Deserialize, Serialize};
/// The quarter of each UV tile a corner mirror keeps and copies over the other three
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorCorner {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl MirrorCorner {
/// Every corner, in the order a list shows them
pub const ALL: [MirrorCorner; 4] = [MirrorCorner::TopLeft, MirrorCorner::TopRight, MirrorCorner::BottomLeft, MirrorCorner::BottomRight];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "Top Left",
MirrorCorner::TopRight => "Top Right",
MirrorCorner::BottomLeft => "Bottom Left",
MirrorCorner::BottomRight => "Bottom Right",
}
}
/// The id `effect.set {cornerType}` takes
pub fn id(self) -> &'static str {
match self {
MirrorCorner::TopLeft => "topLeft",
MirrorCorner::TopRight => "topRight",
MirrorCorner::BottomLeft => "bottomLeft",
MirrorCorner::BottomRight => "bottomRight",
}
}
/// Whether the kept quarter is on the right half and on the bottom half
pub fn sides(self) -> (bool, bool) {
match self {
MirrorCorner::TopLeft => (false, false),
MirrorCorner::TopRight => (true, false),
MirrorCorner::BottomLeft => (false, true),
MirrorCorner::BottomRight => (true, true),
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Which way a mirror filter copies a texture
use serde::{Deserialize, Serialize};
/// The side of an axis, or the corner, a mirror filter copies over the rest of each UV tile
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MirrorMode {
/// Across a vertical axis, left onto right
#[default]
AxisX,
/// Across a horizontal axis, top onto bottom
AxisY,
/// One quarter onto the other three
Corner,
}
impl MirrorMode {
/// Every mode, in the order a list shows them
pub const ALL: [MirrorMode; 3] = [MirrorMode::AxisX, MirrorMode::AxisY, MirrorMode::Corner];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
MirrorMode::AxisX => "Mirror Axis X",
MirrorMode::AxisY => "Mirror Axis Y",
MirrorMode::Corner => "Mirror Corner",
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
MirrorMode::AxisX => "axisX",
MirrorMode::AxisY => "axisY",
MirrorMode::Corner => "corner",
}
}
}
+40
View File
@@ -0,0 +1,40 @@
//! The OKLab perceptual color space (Björn Ottosson's public construction): hue, chroma and lightness shifts that keep perceived lightness
/// Linear sRGB to OKLab `[L, a, b]`
pub fn from_linear([r, g, b]: [f32; 3]) -> [f32; 3] {
let l = (0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
[
0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
]
}
/// OKLab `[L, a, b]` back to linear sRGB (unclamped)
pub fn to_linear([lightness, a, b]: [f32; 3]) -> [f32; 3] {
let l = (lightness + 0.396_337_78 * a + 0.215_803_76 * b).powi(3);
let m = (lightness - 0.105_561_346 * a - 0.063_854_17 * b).powi(3);
let s = (lightness - 0.089_484_18 * a - 1.291_485_5 * b).powi(3);
[
4.076_741_7 * l - 3.307_711_6 * m + 0.230_969_94 * s,
-1.268_438 * l + 2.609_757_4 * m - 0.341_319_38 * s,
-0.004_196_086_3 * l - 0.703_418_6 * m + 1.707_614_7 * s,
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn colors_round_trip_and_white_has_lightness_one() {
let white = from_linear([1.0; 3]);
assert!((white[0] - 1.0).abs() < 1e-3 && white[1].abs() < 1e-3 && white[2].abs() < 1e-3, "{white:?}");
for color in [[0.8, 0.2, 0.1], [0.05, 0.5, 0.9], [0.3, 0.3, 0.3]] {
let back = to_linear(from_linear(color));
assert!(color.iter().zip(back).all(|(a, b)| (a - b).abs() < 1e-3), "{color:?} -> {back:?}");
}
}
}
+48
View File
@@ -0,0 +1,48 @@
//! Which side of a mask's edge a Mask Outline draws on
use serde::{Deserialize, Serialize};
/// The side of the threshold edge a Mask Outline's band lies on
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum OutlinePosition {
/// Around the shapes, outside them
#[default]
Outside,
/// Inside the shapes, along their edge
Inside,
/// On both sides of the edge
Both,
}
impl OutlinePosition {
/// Every position, in the order a switch shows them
pub const ALL: [OutlinePosition; 3] = [OutlinePosition::Outside, OutlinePosition::Inside, OutlinePosition::Both];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
OutlinePosition::Outside => "Outside",
OutlinePosition::Inside => "Inside",
OutlinePosition::Both => "Both",
}
}
/// The id `effect.set {maskPosition}` takes
pub fn id(self) -> &'static str {
match self {
OutlinePosition::Outside => "outside",
OutlinePosition::Inside => "inside",
OutlinePosition::Both => "both",
}
}
/// Whether the band covers a texel inside the shapes (`inside`)
pub fn covers(self, inside: bool) -> bool {
match self {
OutlinePosition::Outside => !inside,
OutlinePosition::Inside => inside,
OutlinePosition::Both => true,
}
}
}
+78
View File
@@ -0,0 +1,78 @@
//! PBR Validate (Metallic Roughness): base colors outside the physically plausible ranges shown in red
use serde::{Deserialize, Serialize};
use crate::ValidationMode;
use crate::blend::lum;
use crate::gradient_input::linear_to_srgb;
/// A PBR Validate filter: which texels it checks and the ranges it checks them against
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PbrValidate {
pub mode: ValidationMode,
/// Albedo Dark Range Threshold: the darkest valid non-metal base color, in sRGB steps of 255 (30 or 50)
pub albedo_dark: u8,
/// Metal Reflectance Range: the dimmest valid metal base color, in percent of sRGB white (60 or 70)
pub metal_low: u8,
}
impl PbrValidate {
/// A new PBR Validate: both kinds of texel, the tolerant ranges
pub const LIBRARY: PbrValidate = PbrValidate { mode: ValidationMode::Combined, albedo_dark: 30, metal_low: 60 };
/// Albedo Dark Range Threshold's choices
pub const ALBEDO_DARK: [u8; 2] = [50, 30];
/// Metal Reflectance Range's choices
pub const METAL_LOW: [u8; 2] = [70, 60];
/// The brightest valid non-metal base color, in sRGB steps of 255
const ALBEDO_BRIGHT: f32 = 240.0;
/// Metal from this value up counts as metal
const METAL_THRESHOLD: f32 = 0.5;
/// Metal Reflectance Range's choices are percent of sRGB white
const PERCENT: f32 = 100.0;
/// Base Color Range's choices are sRGB steps of 255
const SRGB_STEPS: f32 = 255.0;
/// The color of a texel outside its range
pub const INVALID: [f32; 3] = [1.0, 0.0, 0.0];
/// Straight linear base color `color` of a texel with metal `metal`: its own color when valid or not checked, red when not
pub fn check(&self, color: [f32; 3], metal: f32) -> [f32; 3] {
let srgb = linear_to_srgb(lum(color).clamp(0.0, 1.0));
let valid = if metal >= Self::METAL_THRESHOLD {
!self.mode.checks_metal() || srgb >= f32::from(self.metal_low) / Self::PERCENT
} else {
!self.mode.checks_albedo() || (f32::from(self.albedo_dark) / Self::SRGB_STEPS..=Self::ALBEDO_BRIGHT / Self::SRGB_STEPS).contains(&srgb)
};
if valid { color } else { Self::INVALID }
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient_input::srgb_to_linear;
#[test]
fn colors_outside_their_range_turn_red() {
let gray = |srgb: f32| [srgb_to_linear(srgb / 255.0); 3];
let filter = PbrValidate::LIBRARY;
assert_eq!(filter.check(gray(40.0), 0.0), gray(40.0), "above 30 sRGB");
assert_eq!(filter.check(gray(20.0), 0.0), PbrValidate::INVALID, "too dark");
assert_eq!(filter.check(gray(250.0), 0.0), PbrValidate::INVALID, "too bright");
assert_eq!(PbrValidate { albedo_dark: 50, ..filter }.check(gray(40.0), 0.0), PbrValidate::INVALID);
assert_eq!(filter.check(gray(140.0), 1.0), PbrValidate::INVALID, "a dim metal");
assert_eq!(filter.check(gray(170.0), 1.0), gray(170.0), "60% reflective");
assert_eq!(PbrValidate { metal_low: 70, ..filter }.check(gray(170.0), 1.0), PbrValidate::INVALID);
let albedo = PbrValidate { mode: ValidationMode::Albedo, ..filter };
assert_eq!(albedo.check(gray(140.0), 1.0), gray(140.0), "Albedo leaves metal unchecked");
let metal = PbrValidate { mode: ValidationMode::Metal, ..filter };
assert_eq!(metal.check(gray(20.0), 0.0), gray(20.0), "Metal leaves non-metal unchecked");
}
}
+35
View File
@@ -0,0 +1,35 @@
//! Reusable OKLab references for moving a region of colors
use crate::color_match::{matched_linear, polar};
use crate::{ColorMatch, oklab};
/// The settings and converted references for a region with constant source and target colors
#[derive(Clone, Copy, Debug)]
pub struct PreparedColorMatch {
settings: ColorMatch,
source: [f32; 3],
target: [f32; 3],
}
impl PreparedColorMatch {
/// Prepare the fixed reference pair once for the region
pub fn new(settings: ColorMatch, source: [f32; 3], target: [f32; 3]) -> Self {
let reference = |color: [f32; 3]| {
let lab = oklab::from_linear(color.map(|component| component.max(0.0)));
if settings.custom_variation { polar(lab) } else { lab }
};
Self { settings, source: reference(source), target: reference(target) }
}
/// Move a texel using the prepared reference pair
pub fn apply(&self, color: [f32; 3]) -> [f32; 3] {
let lab = oklab::from_linear(color.map(|component| component.max(0.0)));
let moved = if self.settings.custom_variation {
self.settings.move_polar(polar(lab), self.source, self.target)
} else {
std::array::from_fn(|index| self.target[index] + lab[index] - self.source[index])
};
matched_linear(color, moved)
}
}
+35
View File
@@ -0,0 +1,35 @@
use crate::gradient_input::{interpolate, linear_to_srgb, ramp_stops};
use crate::{ChannelKind, Filter, GradientInput};
/// An sRGB gradient prepared for repeated sampling
pub struct PreparedGradient {
stops: Vec<(f32, [f32; 3])>,
input: GradientInput,
}
impl PreparedGradient {
/// Prepare an sRGB ramp by converting its endpoints once
pub fn of(filter: &Filter) -> Option<Self> {
let Filter::GradientMap { positions, linear: false, input, .. } = filter else { return None };
let mut stops: Vec<_> = ramp_stops(filter.ramp_colors(), positions).map(|(position, color)| (position, color.map(linear_to_srgb))).collect();
// Stable order preserves which stop wins at shared positions
stops.sort_by(|left, right| left.0.total_cmp(&right.0));
Some(Self { stops, input: *input })
}
/// Sample the prepared ramp at a normalized position
pub fn at(&self, position: f32) -> Option<[f32; 3]> {
let position = if position.is_finite() { position.clamp(0.0, 1.0) } else { 0.0 };
let split = self.stops.partition_point(|stop| stop.0 <= position);
let before = split.checked_sub(1).and_then(|index| self.stops.get(index)).copied();
let after = self.stops.get(split).copied();
Some(interpolate(before.or(after)?, after.or(before)?, false, position))
}
/// Apply the prepared gradient to one value
pub fn point(&self, kind: ChannelKind, value: [f32; 3]) -> Option<[f32; 3]> {
self.input.map(kind, value, |position| self.at(position))
}
}
+2 -2
View File
@@ -652,7 +652,7 @@ impl Project {
out.push((layer.id, None));
}
let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter());
out.extend(effects.filter(|e| e.kind.reads(Some(anchor))).map(|e| (layer.id, Some(e.id))));
out.extend(effects.filter(|e| e.reads(Some(anchor))).map(|e| (layer.id, Some(e.id))));
}
out
}
@@ -868,7 +868,7 @@ mod tests {
material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3]));
l.content_effects = vec![
Effect::new(fill, EffectKind::Material(material)),
Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1 })),
Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1, perceptive: false })),
Effect::new(anchor, EffectKind::Anchor),
];
let id = p.insert_layer(0, l, None, false).unwrap();
+38
View File
@@ -0,0 +1,38 @@
//! The bend Bevel Smooth's ramp and Mask Outline's fade take, sanitised once per filter
/// A Curve Shape of 1 raises a ramp to the power ¼ and −1 to the power 4, 0 leaves it straight
const CURVE_SHAPE_BASE: f32 = 4.0;
/// A 0..1 ramp moved by an offset, then raised to a power: below 0 the shape rises later, above 0 sooner
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RampCurve {
offset: f32,
exponent: f32,
}
impl RampCurve {
/// The curve moving a ramp by `offset` and bending it by `shape` (each −1..1, 0 when not finite)
pub fn new(offset: f32, shape: f32) -> RampCurve {
let bounded = |x: f32| if x.is_finite() { x.clamp(-1.0, 1.0) } else { 0.0 };
RampCurve { offset: bounded(offset), exponent: CURVE_SHAPE_BASE.powf(-bounded(shape)) }
}
/// Ramp value `along` (0..1) moved and bent
pub fn apply(self, along: f32) -> f32 {
(along + self.offset).clamp(0.0, 1.0).powf(self.exponent)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_shape_bends_and_the_offset_moves() {
assert_eq!(RampCurve::new(0.0, 0.0).apply(0.3), 0.3, "straight");
assert_eq!(RampCurve::new(0.0, 1.0).apply(0.0625), 0.5, "the power ¼ rises sooner");
assert_eq!(RampCurve::new(0.0, -1.0).apply(0.5), 0.0625, "the power 4 rises later");
assert_eq!(RampCurve::new(0.25, 0.0).apply(0.5), 0.75);
assert_eq!(RampCurve::new(f32::NAN, f32::INFINITY), RampCurve::new(0.0, 0.0), "hostile settings leave it straight");
}
}
+4 -1
View File
@@ -5,13 +5,16 @@ use serde::{Deserialize, Serialize};
use crate::{Channel, LayerId};
/// A seed changed by a folder, identified by its layer or effect and optional material channel.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RandomizedSeed {
pub layer: LayerId,
/// Position used by older files that did not identify the source.
pub index: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<(LayerId, Option<Channel>)>,
/// Filter input name when the target owns more than one seed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input: Option<String>,
pub before: u32,
pub after: u32,
}
+39
View File
@@ -0,0 +1,39 @@
//! How a Blur Slope combines what it reads downhill
use serde::{Deserialize, Serialize};
/// What a Blur Slope keeps of the values it reads along the slope
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SlopeBlending {
/// Their average: the values smeared downhill
#[default]
Blur,
/// The smallest of them, per component: light shapes eaten away downhill
Min,
/// The largest of them, per component: light shapes grown downhill
Max,
}
impl SlopeBlending {
/// Every choice, in the order a panel lists them
pub const ALL: [SlopeBlending; 3] = [SlopeBlending::Blur, SlopeBlending::Min, SlopeBlending::Max];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
SlopeBlending::Blur => "Blur",
SlopeBlending::Min => "Min",
SlopeBlending::Max => "Max",
}
}
/// The id `effect.set` takes
pub fn id(self) -> &'static str {
match self {
SlopeBlending::Blur => "blur",
SlopeBlending::Min => "min",
SlopeBlending::Max => "max",
}
}
}
+36
View File
@@ -0,0 +1,36 @@
//! Where Color Match takes the color it moves from
use serde::{Deserialize, Serialize};
/// Color Match's Source Color Mode: the mean color of the whole texture, its Source Color, or its Input image
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SourceColorMode {
#[default]
Average,
Parameter,
Input,
}
impl SourceColorMode {
/// Every mode, in the order a panel shows them
pub const ALL: [SourceColorMode; 3] = [SourceColorMode::Average, SourceColorMode::Parameter, SourceColorMode::Input];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
SourceColorMode::Average => "Average",
SourceColorMode::Parameter => "Parameter",
SourceColorMode::Input => "Input",
}
}
/// The id `effect.set {sourceColorMode}` takes
pub fn id(self) -> &'static str {
match self {
SourceColorMode::Average => "average",
SourceColorMode::Parameter => "parameter",
SourceColorMode::Input => "input",
}
}
}
+68
View File
@@ -0,0 +1,68 @@
//! The Blur Slope filter's settings and how far it reads
use serde::{Deserialize, Serialize};
use crate::{SlopeBlending, SourceWarp, WarpSource, WarpSourceMode, source_warp};
/// Values read downhill along a source's slope, averaged or kept at their smallest or largest
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceSlopeBlur {
/// The default noise's seed
pub seed: u32,
/// How far downhill a texel reads, a share of the UV tile before the divider (0..1)
pub intensity: f32,
/// Divides `intensity` (1, 10, 100 or 1000) for short smears
pub divider: u16,
pub blending: SlopeBlending,
/// The share of the reads taken along the way (0..1): fewer is faster and grainier
pub quality: f32,
pub source: WarpSource,
}
impl SourceSlopeBlur {
/// The Blur Slope filter as the library adds it
pub const LIBRARY: SourceSlopeBlur =
SourceSlopeBlur { seed: 0, intensity: 0.3, divider: 10, blending: SlopeBlending::Blur, quality: 1.0, source: WarpSource::LIBRARY };
/// How many texels downhill a texel reads at most at `res` texels across a UV tile
pub fn move_texels(&self, res: u32) -> f32 {
source_warp::move_texels(self.intensity, self.divider, res)
}
/// How many of `most` reads along the way Quality keeps (at least one past the texel itself)
pub fn samples(&self, most: u32) -> u32 {
let quality = if self.quality.is_finite() { self.quality.clamp(0.0, 1.0) } else { 1.0 };
((most as f32 * quality).round() as u32).clamp(1, most.max(1))
}
/// How many texels around a texel the filter reads at `res` texels across a UV tile: downhill, and where it measures its source's slope
pub fn reach(&self, res: u32) -> f32 {
let moves = self.move_texels(res);
if self.source.mode == WarpSourceMode::DefaultNoise {
return moves;
}
moves + SourceWarp::probe_texels(res) + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_follow_intensity_quality_and_source() {
let slope = SourceSlopeBlur::LIBRARY;
assert!((slope.move_texels(2048) - 61.44).abs() < 1e-3, "0.3 ÷ 10 of the tile");
assert_eq!((slope.samples(24), SourceSlopeBlur { quality: 0.5, ..slope }.samples(24)), (24, 12));
assert_eq!(SourceSlopeBlur { quality: 0.0, ..slope }.samples(24), 1, "always one read downhill");
assert_eq!(SourceSlopeBlur { quality: f32::NAN, ..slope }.samples(24), 24);
let custom = SourceSlopeBlur { source: WarpSource { mode: WarpSourceMode::CustomNoise, blur: 1.0, ..WarpSource::LIBRARY }, ..slope };
assert!(custom.reach(2048) >= custom.move_texels(2048) + SourceWarp::probe_texels(2048) + custom.source.blur_texels(2048) * 0.5);
let input = SourceSlopeBlur { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..slope };
assert!((input.reach(2048) - (61.44 + 8.0)).abs() < 1e-3, "plus where it measures the slope");
assert_eq!(SourceSlopeBlur { intensity: f32::INFINITY, ..slope }.move_texels(2048), 0.0);
}
}
+144
View File
@@ -0,0 +1,144 @@
//! The Warp filter's settings and the moves it makes
use serde::{Deserialize, Serialize};
use crate::{WarpBlending, WarpMode, WarpSource, WarpSourceMode, finite_unit};
/// Texels read from where a source sends them: along its slope, along one direction, or along several blended
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SourceWarp {
/// The default noise's seed
pub seed: u32,
pub mode: WarpMode,
/// How far a texel moves at most, a share of the UV tile before the divider (0..1)
pub intensity: f32,
/// Divides `intensity` (1, 10, 100 or 1000) for fine moves
pub divider: u16,
/// The direction (degrees) of the directional modes, the first of several in Multi Directional Warp
pub angle: f32,
/// How many directions a Multi Directional Warp spreads evenly around the circle (1, 2 or 4)
pub directions: u8,
pub blending: WarpBlending,
pub source: WarpSource,
}
impl SourceWarp {
/// The Warp filter as the library adds it
pub const LIBRARY: SourceWarp = SourceWarp {
seed: 0,
mode: WarpMode::Warp,
intensity: 0.1,
divider: 10,
angle: 0.0,
directions: 4,
blending: WarpBlending::Average,
source: WarpSource::LIBRARY,
};
/// The direction counts a Multi Directional Warp takes
pub const DIRECTIONS: [u8; 3] = [1, 2, 4];
/// The share of the UV tile the source's slope is measured across, on each side of a texel
pub const PROBE_SHARE: f32 = 1.0 / 256.0;
/// The source's slope (rise per UV tile) that moves a texel the whole way in Warp mode
pub const FULL_SLOPE: f32 = 4.0;
/// How many texels a texel moves at most at `res` texels across a UV tile
pub fn move_texels(&self, res: u32) -> f32 {
move_texels(self.intensity, self.divider, res)
}
/// How many texels each side of a texel Warp mode measures the source's slope across
pub fn probe_texels(res: u32) -> f32 {
(res as f32 * Self::PROBE_SHARE).max(1.0)
}
/// The directions (degrees) texels move along: none in Warp mode (the slope decides), the Angle, or Directions spread from it
pub fn angles(&self) -> impl Iterator<Item = f32> + Clone + use<> {
let angle = if self.angle.is_finite() { self.angle } else { 0.0 };
let count = match self.mode {
WarpMode::Warp => 0,
WarpMode::Directional => 1,
WarpMode::MultiDirectional if Self::DIRECTIONS.contains(&self.directions) => self.directions,
WarpMode::MultiDirectional => 1,
};
(0..count).map(move |index| angle + 360.0 * f32::from(index) / f32::from(count))
}
/// How many texels around a texel the warp reads at `res` texels across a UV tile: its moves (chained ones add up) and where it reads its source
pub fn reach(&self, res: u32) -> f32 {
let chained = self.mode == WarpMode::MultiDirectional && self.blending == WarpBlending::Chain;
let moves = self.move_texels(res) * if chained { self.angles().count().max(1) as f32 } else { 1.0 };
if self.source.mode == WarpSourceMode::DefaultNoise {
return moves;
}
let probe = if self.mode == WarpMode::Warp { Self::probe_texels(res) } else { 0.0 };
moves + probe + self.source.blur_texels(res) * std::f32::consts::FRAC_1_SQRT_2
}
/// How far (−1..1 of the move) a source value moves a texel along a direction: backwards below mid gray, forwards above
pub fn amount(value: f32) -> f32 {
if value.is_finite() { (2.0 * value - 1.0).clamp(-1.0, 1.0) } else { 0.0 }
}
/// Warp mode's move (texels) from how much the source rises across [`SourceWarp::probe_texels`] each side of a texel along x and y
pub fn slope_move(&self, rise: [f32; 2], res: u32) -> [f32; 2] {
let across = 2.0 * Self::probe_texels(res) / res.max(1) as f32;
let [x, y] = rise.map(|rise| if rise.is_finite() { rise / across / Self::FULL_SLOPE } else { 0.0 });
let length = x.hypot(y);
let fit = if length > 1.0 { 1.0 / length } else { 1.0 };
let reach = self.move_texels(res);
[x * fit * reach, y * fit * reach]
}
}
/// How many texels Intensity over Divider moves at `res` texels across a UV tile (Warp's and Blur Slope's)
pub(crate) fn move_texels(intensity: f32, divider: u16, res: u32) -> f32 {
finite_unit(intensity) / f32::from(divider.max(1)) * res as f32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn moves_follow_intensity_mode_and_directions() {
let warp = SourceWarp::LIBRARY;
assert!((warp.move_texels(2048) - 20.48).abs() < 1e-3, "0.1 ÷ 10 of the tile");
assert_eq!(warp.angles().count(), 0);
let directional = SourceWarp { mode: WarpMode::Directional, angle: 30.0, ..warp };
assert_eq!(directional.angles().collect::<Vec<_>>(), vec![30.0]);
let multi = SourceWarp { mode: WarpMode::MultiDirectional, angle: 10.0, ..warp };
assert_eq!(multi.angles().collect::<Vec<_>>(), vec![10.0, 100.0, 190.0, 280.0]);
let chained = SourceWarp { blending: WarpBlending::Chain, ..multi };
assert!((chained.reach(2048) - 4.0 * 20.48).abs() < 1e-3, "four moves one after the other");
let custom = SourceWarp { source: WarpSource { mode: WarpSourceMode::CustomNoise, blur: 1.0, ..WarpSource::LIBRARY }, ..warp };
assert!(custom.reach(2048) >= custom.move_texels(2048) + SourceWarp::probe_texels(2048) + custom.source.blur_texels(2048) * 0.5);
let input = SourceWarp { source: WarpSource { mode: WarpSourceMode::PreviousInput, ..WarpSource::LIBRARY }, ..warp };
assert!((input.reach(2048) - (20.48 + 8.0)).abs() < 1e-3, "plus where it measures the slope");
assert_eq!((SourceWarp::amount(0.0), SourceWarp::amount(0.5), SourceWarp::amount(1.0)), (-1.0, 0.0, 1.0));
}
#[test]
fn slope_moves_saturate_and_hostile_settings_stay_in_range() {
let warp = SourceWarp::LIBRARY;
let gentle = warp.slope_move([0.01, 0.0], 2048);
assert!(gentle[0] > 0.0 && gentle[0] < warp.move_texels(2048), "{gentle:?}");
let steep = warp.slope_move([1.0, 1.0], 2048);
assert!((steep[0].hypot(steep[1]) - warp.move_texels(2048)).abs() < 1e-3, "a cliff moves the whole way, no further: {steep:?}");
let hostile = SourceWarp { intensity: f32::NAN, angle: f32::INFINITY, directions: 9, divider: 0, mode: WarpMode::MultiDirectional, ..warp };
assert_eq!((hostile.move_texels(2048), hostile.angles().collect::<Vec<_>>()), (0.0, vec![0.0]));
assert_eq!(hostile.slope_move([f32::NAN, 1.0], 2048)[0], 0.0);
assert_eq!(SourceWarp { intensity: 9.0, divider: 1, ..warp }.move_texels(1024), 1024.0);
}
}
+160
View File
@@ -0,0 +1,160 @@
//! What Baked Lighting Stylized adds to Baked Lighting's sun and ambient: sky colors, two more lights, cavity, edges and highlights
use serde::{Deserialize, Serialize};
use crate::directional_light::DirectionalLight;
use crate::lighting_output::LightingOutput;
use crate::stylized_shading::StylizedShading;
use crate::sun_and_sky::SunAndSky;
/// Baked Lighting Stylized's settings past the sun's direction and strength, the sky's strength and Diffuse AO (kept on the filter, as Baked Lighting saved them)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StylizedLighting {
pub sun_color: [f32; 3],
/// The ambient light from straight above, at the horizon and from below; normals between blend them
pub sky_color: [f32; 3],
pub horizon_color: [f32; 3],
pub ground_color: [f32; 3],
/// Light 1 and Light 2
pub lights: [DirectionalLight; 2],
/// How much the cavities (concave curvature) darken the lit surface and its highlights
pub diffuse_cavity: f32,
pub specular_cavity: f32,
/// How much the baked ambient occlusion darkens the highlights
pub specular_ao: f32,
/// The concavity (and convexity, for edges) over which cavity and edges fade in: 0 is a hard step
pub cavity_smoothness: f32,
/// How much the edges (convex curvature) lighten toward white
pub edges_intensity: f32,
pub edges_smoothness: f32,
/// Reads the Specular and Glossiness channels instead of Metallic and Roughness (Input)
pub specular_glossiness: bool,
pub output: LightingOutput,
/// The reflectance of non-metals at normal incidence
pub dielectric_reflectance: f32,
/// Lights the mesh's own normals, without the baked normal and height detail (Normal Details Type Mesh only)
pub mesh_only: bool,
pub height_to_normal: f32,
}
/// The reflectance of non-metals at normal incidence
pub const DIELECTRIC_REFLECTANCE: f32 = 0.04;
impl StylizedLighting {
/// The settings that light exactly as Baked Lighting did: white light and sky, no extra lights, cavity, edges or highlights, the mesh's own normals
pub const PLAIN: StylizedLighting = StylizedLighting {
sun_color: [1.0; 3],
sky_color: [1.0; 3],
horizon_color: [1.0; 3],
ground_color: [1.0; 3],
lights: [DirectionalLight::off(90.0), DirectionalLight::off(180.0)],
diffuse_cavity: 0.0,
specular_cavity: 0.0,
specular_ao: 0.0,
cavity_smoothness: 0.25,
edges_intensity: 0.0,
edges_smoothness: 0.0,
specular_glossiness: false,
output: LightingOutput::Diffuse,
dielectric_reflectance: DIELECTRIC_REFLECTANCE,
mesh_only: true,
height_to_normal: 1.0,
};
/// A new Baked Lighting Stylized: a warm sun, a blue sky over a brown ground, highlights, and the baked normal and height detail
pub fn library() -> StylizedLighting {
StylizedLighting {
sun_color: [1.0, 0.905, 0.716],
sky_color: [0.305, 0.456, 0.791],
horizon_color: [0.644, 0.644, 0.61],
ground_color: [0.102, 0.08, 0.061],
output: LightingOutput::DiffuseSpecular,
mesh_only: false,
..StylizedLighting::PLAIN
}
}
/// These settings lit by `light`, worked out once for the shading of every texel
pub fn shading(&self, light: SunAndSky) -> StylizedShading {
StylizedShading::new(self, light)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Channel, Filter};
const UP: [f32; 3] = [0.0, 1.0, 0.0];
fn material(roughness: f32) -> Vec<[f32; 3]> {
let mut channels: Vec<[f32; 3]> = Channel::ALL.iter().map(|c| c.default_value()).collect();
channels[Channel::Roughness.index()] = [roughness; 3];
channels
}
fn light(elevation: f32, intensity: f32, sky_intensity: f32) -> SunAndSky {
SunAndSky { sun: DirectionalLight { azimuth: 0.0, elevation, intensity, color: [1.0; 3] }, sky_intensity, diffuse_ao: 0.5 }
}
/// The plain settings light as Baked Lighting did: the base color times sun facing plus occluded ambient
#[test]
fn plain_settings_light_as_baked_lighting_did() {
let legacy = Filter::BakedLighting { azimuth: 0.0, elevation: 30.0, light: 0.6, ambient: 0.4, occlusion: 0.5, stylized: None };
for (nrm, ao) in [(UP, 1.0), ([0.6, 0.8, 0.0], 0.3), ([0.0, -1.0, 0.0], 0.7)] {
let k = legacy.baked_light(nrm, ao).unwrap_or(f32::NAN);
let shaded = StylizedLighting::PLAIN.shading(light(30.0, 0.6, 0.4)).shade([0.5, 0.25, 1.0], nrm, [ao, 0.5], &material(0.5));
let expected = [0.5f32, 0.25, 1.0].map(|x| (x * k).clamp(0.0, 1.0));
assert!(shaded.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-5), "{nrm:?}: {shaded:?} vs {expected:?}");
}
}
/// The sky, horizon and ground colors light a surface by where it faces; Light 1 adds its color
#[test]
fn sky_colors_and_extra_lights() {
let colors = StylizedLighting { sky_color: [0.0, 0.0, 1.0], horizon_color: [0.0, 1.0, 0.0], ground_color: [1.0, 0.0, 0.0], ..StylizedLighting::PLAIN };
let sky = light(45.0, 0.0, 1.0);
let white = [1.0; 3];
assert_eq!(colors.shading(sky).shade(white, UP, [1.0, 0.5], &material(0.5)), [0.0, 0.0, 1.0]);
assert_eq!(colors.shading(sky).shade(white, [1.0, 0.0, 0.0], [1.0, 0.5], &material(0.5)), [0.0, 1.0, 0.0]);
assert_eq!(colors.shading(sky).shade(white, [0.0, -1.0, 0.0], [1.0, 0.5], &material(0.5)), [1.0, 0.0, 0.0]);
let mut extra = StylizedLighting::PLAIN;
extra.lights[0] = DirectionalLight { azimuth: 0.0, elevation: 90.0, intensity: 0.5, color: [1.0, 0.0, 0.0] };
let dark = light(45.0, 0.0, 0.0);
let lit = extra.shading(dark).shade(white, UP, [1.0, 0.5], &material(0.5));
assert!((lit[0] - 0.5).abs() < 1e-5 && lit[1] == 0.0, "{lit:?}");
}
/// Highlights: a smooth surface shines brighter than a rough one; Specular only keeps them alone, Diffuse only drops them
#[test]
fn highlights_follow_roughness_and_the_output() {
let sun = light(90.0, 1.0, 0.0);
let shiny = StylizedLighting { output: LightingOutput::Specular, ..StylizedLighting::library() };
let albedo = [0.0; 3];
let smooth = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2));
let rough = shiny.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.9));
assert!(smooth[0] > rough[0] + 0.1 && rough[0] > 0.0, "{smooth:?} {rough:?}");
let diffuse = StylizedLighting { output: LightingOutput::Diffuse, ..StylizedLighting::library() };
assert_eq!(diffuse.shading(sun).shade(albedo, UP, [1.0, 0.5], &material(0.2)), [0.0; 3]);
}
/// Cavities darken the lit surface by Diffuse Cavity; edges lighten toward white by Edges Intensity
#[test]
fn cavities_darken_and_edges_lighten() {
let sky = light(45.0, 0.0, 1.0);
let gray = [0.5; 3];
let cavities = StylizedLighting { diffuse_cavity: 1.0, ..StylizedLighting::PLAIN };
assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat: no cavity");
assert_eq!(cavities.shading(sky).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity");
let sun = light(90.0, 1.0, 0.0);
assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.5], &material(0.5)), gray, "flat in the sun: no cavity");
assert_eq!(cavities.shading(sun).shade(gray, UP, [1.0, 0.2], &material(0.5)), [0.0; 3], "a deep cavity in the sun");
let edges = StylizedLighting { edges_intensity: 1.0, ..StylizedLighting::PLAIN };
assert_eq!(edges.shading(sky).shade(gray, UP, [1.0, 0.9], &material(0.5)), [1.0; 3], "a sharp edge");
}
}
+207
View File
@@ -0,0 +1,207 @@
//! Baked Lighting Stylized's settings worked out once per filter, and the shading of each texel with them
use std::f32::consts::PI;
use crate::lighting_output::LightingOutput;
use crate::stylized_lighting::StylizedLighting;
use crate::sun_and_sky::SunAndSky;
use crate::{Channel, finite_unit, mix3};
/// The curvature map's value on a flat surface (below it concave, above convex)
pub const FLAT_CURVATURE: f32 = 0.5;
/// The scale that takes either side of [`FLAT_CURVATURE`] to 0..1
const CURVATURE_SIDE_SCALE: f32 = 2.0;
/// The Cook-Torrance denominator 4·(n·l)·(n·v) with the viewer straight on (n·v = 1), n·l cancelled by the light's own facing
const COOK_TORRANCE_DENOMINATOR: f32 = 4.0;
/// The roughness highlights never go below (a mirror would be a single texel of infinite light)
const MIN_ROUGHNESS: f32 = 0.08;
/// The smoothness below which cavity and edges switch on as a step
const MIN_SMOOTHNESS: f32 = 1e-3;
/// A [`StylizedLighting`] under its [`SunAndSky`], with every value that depends only on the settings worked out once
#[derive(Clone, Debug, PartialEq)]
pub struct StylizedShading {
/// The sun, Light 1 and Light 2: the unit direction toward each, its intensity and its color
lights: [([f32; 3], f32, [f32; 3]); 3],
sky_intensity: f32,
sky_color: [f32; 3],
horizon_color: [f32; 3],
ground_color: [f32; 3],
/// Diffuse AO, Specular AO, Diffuse Cavity, Specular Cavity and Edges Intensity, each 0..1
diffuse_ao: f32,
specular_ao: f32,
diffuse_cavity: f32,
specular_cavity: f32,
edges_intensity: f32,
cavity_smoothness: f32,
edges_smoothness: f32,
specular_glossiness: bool,
output: LightingOutput,
/// The reflectance of non-metals at normal incidence, 0..1
dielectric_reflectance: f32,
/// The relief the baked height gives the lit normals; None lights the mesh's own normals
relief: Option<f32>,
}
impl StylizedShading {
/// `settings` lit by `light`
pub fn new(settings: &StylizedLighting, light: SunAndSky) -> StylizedShading {
let sun = (light.sun.direction(), light.sun.intensity, settings.sun_color);
let [first, second] = settings.lights.map(|extra| (extra.direction(), extra.intensity, extra.color));
StylizedShading {
lights: [sun, first, second],
sky_intensity: light.sky_intensity,
sky_color: settings.sky_color,
horizon_color: settings.horizon_color,
ground_color: settings.ground_color,
diffuse_ao: finite_unit(light.diffuse_ao),
specular_ao: finite_unit(settings.specular_ao),
diffuse_cavity: finite_unit(settings.diffuse_cavity),
specular_cavity: finite_unit(settings.specular_cavity),
edges_intensity: finite_unit(settings.edges_intensity),
cavity_smoothness: settings.cavity_smoothness,
edges_smoothness: settings.edges_smoothness,
specular_glossiness: settings.specular_glossiness,
output: settings.output,
dielectric_reflectance: finite_unit(settings.dielectric_reflectance),
relief: (!settings.mesh_only).then_some(settings.height_to_normal),
}
}
/// The relief the baked height gives the normals it lights (Height to Normal Intensity); None lights the mesh's own normals
pub fn relief(&self) -> Option<f32> {
self.relief
}
/// The ambient light reaching a surface facing `normal` from the sky, horizon and ground
fn ambient(&self, normal: [f32; 3]) -> [f32; 3] {
let up = normal[1].clamp(-1.0, 1.0);
if up >= 0.0 { mix3(self.horizon_color, self.sky_color, up) } else { mix3(self.horizon_color, self.ground_color, -up) }
}
/// The lit base color of linear `albedo` facing `normal` (world space, unit) with baked ambient occlusion `ao` and curvature `curvature` ([`FLAT_CURVATURE`] flat), its material read from `channels` (straight values by [`Channel::index`]); the viewer looks straight at the surface
pub fn shade(&self, albedo: [f32; 3], normal: [f32; 3], [ao, curvature]: [f32; 2], channels: &[[f32; 3]]) -> [f32; 3] {
let channel = |channel: Channel| channels.get(channel.index()).copied().unwrap_or_else(|| channel.default_value());
let ao = if ao.is_finite() { ao.clamp(0.0, 1.0) } else { 1.0 };
let curvature = if curvature.is_finite() { curvature } else { FLAT_CURVATURE };
let cavity = fade_in((FLAT_CURVATURE - curvature) * CURVATURE_SIDE_SCALE, self.cavity_smoothness);
let edge = if self.output.diffuse() {
fade_in((curvature - FLAT_CURVATURE) * CURVATURE_SIDE_SCALE, self.edges_smoothness) * self.edges_intensity
} else {
0.0
};
let (roughness, f0, diffuse_albedo) = if self.specular_glossiness {
(1.0 - finite_unit(channel(Channel::Glossiness)[0]), channel(Channel::Specular).map(finite_unit), albedo)
} else {
let metal = finite_unit(channel(Channel::Metallic)[0]);
let f0 = mix3([self.dielectric_reflectance; 3], albedo, metal);
// Without highlights the whole base color is lit, as Baked Lighting did
let kept = if self.output.specular() { 1.0 - metal } else { 1.0 };
(finite_unit(channel(Channel::Roughness)[0]), f0, albedo.map(|x| x * kept))
};
let compute_diffuse = self.output.diffuse();
let compute_specular = self.output.specular();
let roughness = roughness.max(MIN_ROUGHNESS);
let sky = self.ambient(normal);
let diffuse_ao = 1.0 + (ao - 1.0) * self.diffuse_ao;
let specular_ao = 1.0 + (ao - 1.0) * self.specular_ao;
let diffuse_cavity = 1.0 - cavity * self.diffuse_cavity;
let specular_cavity = 1.0 - cavity * self.specular_cavity;
let mut diffuse = if compute_diffuse { sky.map(|sky_light| sky_light * self.sky_intensity * diffuse_ao * diffuse_cavity) } else { [0.0; 3] };
let mut specular = [0.0f32; 3];
for &(direction, intensity, color) in &self.lights {
let facing = dot(normal, direction);
if facing <= 0.0 || intensity <= 0.0 {
continue;
}
if compute_diffuse {
for (diffuse, color) in diffuse.iter_mut().zip(color) {
*diffuse += color * intensity * facing * diffuse_cavity;
}
}
if compute_specular {
let half = normalize([normal[0] + direction[0], normal[1] + direction[1], normal[2] + direction[2]]);
let normal_dot_half = dot(normal, half).max(0.0);
let highlight = ggx(normal_dot_half, roughness) / COOK_TORRANCE_DENOMINATOR * facing * specular_cavity;
for ((specular, color), f0) in specular.iter_mut().zip(color).zip(f0) {
*specular += color * intensity * highlight * schlick(f0, normal_dot_half);
}
}
}
if compute_specular {
for ((specular, f0), sky_light) in specular.iter_mut().zip(f0).zip(sky) {
*specular += f0 * sky_light * self.sky_intensity * specular_ao * specular_cavity;
}
}
std::array::from_fn(|channel| {
let lit = if compute_diffuse { diffuse_albedo[channel] * diffuse[channel] } else { 0.0 };
let shine = specular[channel];
let shaded = finite_unit(lit + shine);
finite_unit(shaded + (1.0 - shaded) * edge)
})
}
}
/// `amount` (clamped 0..1) reaching full over `smoothness`: a step when it is about 0 or not a number
fn fade_in(amount: f32, smoothness: f32) -> f32 {
let amount = amount.clamp(0.0, 1.0);
if smoothness.is_nan() || smoothness <= MIN_SMOOTHNESS {
return if amount > 0.0 { 1.0 } else { 0.0 };
}
(amount / smoothness).min(1.0)
}
/// The GGX distribution of microfacets facing `normal_dot_half` (the cosine between the normal and the half vector) at `roughness`
fn ggx(normal_dot_half: f32, roughness: f32) -> f32 {
let alpha_squared = (roughness * roughness).powi(2);
let denominator = normal_dot_half * normal_dot_half * (alpha_squared - 1.0) + 1.0;
alpha_squared / (PI * denominator * denominator)
}
/// Schlick's Fresnel of reflectance `f0` at cosine `cos`
fn schlick(f0: f32, cos: f32) -> f32 {
f0 + (1.0 - f0) * (1.0 - cos.clamp(0.0, 1.0)).powi(5)
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// `v` at unit length; a vector too short to have a direction points up
fn normalize(v: [f32; 3]) -> [f32; 3] {
const MIN_LENGTH: f32 = 1e-6;
let length = dot(v, v).sqrt();
if length > MIN_LENGTH { v.map(|x| x / length) } else { [0.0, 1.0, 0.0] }
}
#[cfg(test)]
mod tests {
use super::*;
/// A smoothness that is not a number switches cavity and edges on as a step: a flat surface stays untouched
#[test]
fn a_nan_smoothness_fades_in_as_a_step() {
assert_eq!((fade_in(0.0, f32::NAN), fade_in(0.3, f32::NAN)), (0.0, 1.0));
}
/// The relief is the Height to Normal Intensity, unless the filter lights the mesh's own normals
#[test]
fn the_relief_follows_mesh_only() {
let light = SunAndSky { sun: StylizedLighting::PLAIN.lights[0], sky_intensity: 1.0, diffuse_ao: 0.0 };
assert_eq!(StylizedShading::new(&StylizedLighting::PLAIN, light).relief(), None);
let detailed = StylizedLighting { mesh_only: false, height_to_normal: 0.7, ..StylizedLighting::PLAIN };
assert_eq!(StylizedShading::new(&detailed, light).relief(), Some(0.7));
}
}
+11
View File
@@ -0,0 +1,11 @@
//! The sun and sky Baked Lighting Stylized shades with
use crate::directional_light::DirectionalLight;
/// The sun and sky a [`StylizedLighting`](crate::StylizedLighting) shades with, kept on the filter as Baked Lighting saved them
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SunAndSky {
pub sun: DirectionalLight,
pub sky_intensity: f32,
pub diffuse_ao: f32,
}
+33
View File
@@ -0,0 +1,33 @@
//! Where Color Match takes the color it moves to
use serde::{Deserialize, Serialize};
/// Color Match's Target Color Mode: its Target Color or its Image Input
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TargetColorMode {
#[default]
Parameter,
ImageInput,
}
impl TargetColorMode {
/// Every mode, in the order a panel shows them
pub const ALL: [TargetColorMode; 2] = [TargetColorMode::Parameter, TargetColorMode::ImageInput];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
TargetColorMode::Parameter => "Parameter",
TargetColorMode::ImageInput => "Image Input",
}
}
/// The id `effect.set {targetColorMode}` takes
pub fn id(self) -> &'static str {
match self {
TargetColorMode::Parameter => "parameter",
TargetColorMode::ImageInput => "imageInput",
}
}
}
+93
View File
@@ -0,0 +1,93 @@
//! How a threshold compares a value with its level
use serde::{Deserialize, Serialize};
/// Which values a threshold turns white: those above its level, at or above it, below it, or at or below it
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ThresholdMode {
Greater,
/// What thresholds did in projects saved before the modes
#[default]
GreaterOrEqual,
Lower,
LowerOrEqual,
}
impl ThresholdMode {
/// Every mode, in the order a panel shows them
pub const ALL: [ThresholdMode; 4] = [ThresholdMode::Greater, ThresholdMode::GreaterOrEqual, ThresholdMode::Lower, ThresholdMode::LowerOrEqual];
/// The comparison sign a panel shows
pub fn sign(self) -> &'static str {
match self {
ThresholdMode::Greater => ">",
ThresholdMode::GreaterOrEqual => "≥",
ThresholdMode::Lower => "<",
ThresholdMode::LowerOrEqual => "≤",
}
}
/// The name a tooltip shows
pub fn label(self) -> &'static str {
match self {
ThresholdMode::Greater => "Greater",
ThresholdMode::GreaterOrEqual => "Greater or equal",
ThresholdMode::Lower => "Lower",
ThresholdMode::LowerOrEqual => "Lower or equal",
}
}
/// The id `effect.set {mode}` takes
pub fn id(self) -> &'static str {
match self {
ThresholdMode::Greater => "greater",
ThresholdMode::GreaterOrEqual => "greaterOrEqual",
ThresholdMode::Lower => "lower",
ThresholdMode::LowerOrEqual => "lowerOrEqual",
}
}
/// Whether `value` turns white against `level`
pub fn passes(self, value: f32, level: f32) -> bool {
match self {
ThresholdMode::Greater => value > level,
ThresholdMode::GreaterOrEqual => value >= level,
ThresholdMode::Lower => value < level,
ThresholdMode::LowerOrEqual => value <= level,
}
}
/// Whether it is the mode projects saved before the modes read as (it is then left out of a saved file)
pub fn is_default(&self) -> bool {
*self == ThresholdMode::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ChannelKind, Filter};
#[test]
fn a_threshold_saved_before_the_modes_reads_and_saves_as_before() {
let saved = r#"{"Threshold":{"level":0.5}}"#;
let filter: Filter = serde_json::from_str(saved).unwrap();
assert_eq!(filter, Filter::Threshold { level: 0.5, mode: ThresholdMode::GreaterOrEqual });
assert_eq!(serde_json::to_string(&filter).unwrap(), saved);
assert_eq!(filter.point(ChannelKind::Scalar, [0.5; 3]), Some([1.0; 3]), "a value at the level turns white as before");
}
#[test]
fn each_mode_compares_its_way() {
let at = |mode: ThresholdMode, value: f32| Filter::Threshold { level: 0.5, mode }.point(ChannelKind::Scalar, [value; 3]).map(|v| v[0]);
assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Greater, value)), [Some(0.0), Some(0.0), Some(1.0)]);
assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::Lower, value)), [Some(1.0), Some(0.0), Some(0.0)]);
assert_eq!([0.4, 0.5, 0.6].map(|value| at(ThresholdMode::LowerOrEqual, value)), [Some(1.0), Some(1.0), Some(0.0)]);
let saved = serde_json::to_string(&Filter::Threshold { level: 0.01, mode: ThresholdMode::LowerOrEqual }).unwrap();
assert!(saved.contains(r#""mode":"lowerOrEqual""#), "{saved}");
}
}
+235
View File
@@ -0,0 +1,235 @@
//! The Transform filter's settings and where it reads each texel from
use serde::{Deserialize, Serialize};
mod flip_mode;
mod repeat_mode;
pub use flip_mode::FlipMode;
pub use repeat_mode::RepeatMode;
/// A turn this close to a whole number of quarter turns (in quarter turns) keeps the tile's edges meeting as it is
const SQUARE_TURN_TOLERANCE: f32 = 1e-4;
/// A shift or step this small (a share of the tile) moves no texel
const IDENTITY_TOLERANCE: f32 = 1e-6;
/// Degrees in a quarter turn
const QUARTER_TURN_DEGREES: f32 = 90.0;
/// A Transform filter: each UV tile's content scaled, turned and moved about the tile's centre, then flipped
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TileTransform {
pub repeat: RepeatMode,
pub flip: FlipMode,
/// How many times the content fits across and down the tile (2 = twice, half as big), as a fill's Tiling
pub scaling: [f32; 2],
/// How far the content moves, in tiles; positive reads further right and down, as a fill's Offset
pub offset: [f32; 2],
/// Turns only by angles that keep the tile's edges meeting, so a repeating result stays seamless
pub tile_safe: bool,
/// Degrees
pub rotation: f32,
}
impl TileTransform {
/// The Transform filter as the library adds it: no change, repeating, tile safe
pub const LIBRARY: TileTransform = TileTransform {
repeat: RepeatMode::HorizontallyAndVertically,
flip: FlipMode::None,
scaling: [1.0, 1.0],
offset: [0.0, 0.0],
tile_safe: true,
rotation: 0.0,
};
/// The smallest and largest Scaling it renders (a hostile file's values come back within)
pub const SCALING: (f32, f32) = (0.01, 64.0);
/// The farthest Offset it renders, in tiles
pub const MAX_OFFSET: f32 = 64.0;
/// Where in the tile (0..1 across and down, before any repeat) the texel at `uv` reads from, as `linear · uv + shift`; the columns of `linear` are what one step across and one step down the result move in the source
pub fn affine(&self) -> ([[f32; 2]; 2], [f32; 2]) {
let finite = |value: f32, fallback: f32| if value.is_finite() { value } else { fallback };
let (low, high) = Self::SCALING;
let scaling = self.scaling.map(|scale| finite(scale, 1.0).clamp(low, high));
let rotation = finite(self.rotation, 0.0);
let (sin, cos) = rotation.to_radians().sin_cos();
// Turn, then scale (a fill's Tiling convention): one step across moves (cos, sin) scaled
let mut columns = [[cos * scaling[0], sin * scaling[1]], [-sin * scaling[0], cos * scaling[1]]];
let quarter_turns = rotation / QUARTER_TURN_DEGREES;
let square = (quarter_turns - quarter_turns.round()).abs() < SQUARE_TURN_TOLERANCE;
if self.tile_safe && !square {
let exact = columns;
// Whole steps of the source per tile edge keep the edges meeting; a step can never vanish
for column in &mut columns {
let rounded = column.map(f32::round);
*column = if rounded == [0.0, 0.0] {
if column[0].abs() >= column[1].abs() { [column[0].signum(), 0.0] } else { [0.0, column[1].signum()] }
} else {
rounded
};
}
// Preserve orientation when rounding would collapse the transform onto one line
if determinant(columns) <= 0.0 {
let [across, down] = columns;
let across_further = squared_distance(across, exact[0]) >= squared_distance(down, exact[1]);
columns = if across_further {
turning_step(exact[0], |step| [step, down]).map_or(columns, |step| [step, down])
} else {
turning_step(exact[1], |step| [across, step]).map_or(columns, |step| [across, step])
};
}
}
let [flip_x, flip_y] = self.flip.sides();
if flip_x {
columns[0] = columns[0].map(|v| -v);
}
if flip_y {
columns[1] = columns[1].map(|v| -v);
}
let offset = self.offset.map(|along| finite(along, 0.0).clamp(-Self::MAX_OFFSET, Self::MAX_OFFSET));
// About the tile's centre: the centre reads the centre moved by the offset
let shift = [0, 1].map(|axis| 0.5 + offset[axis] - 0.5 * (columns[0][axis] + columns[1][axis]));
(columns, shift)
}
/// Whether it changes nothing (a turn a hair short of a whole one included)
pub fn is_identity(&self) -> bool {
let (columns, shift) = self.affine();
let steps = [columns[0][0] - 1.0, columns[0][1], columns[1][0], columns[1][1] - 1.0];
steps.iter().chain(&shift).all(|along| along.abs() < IDENTITY_TOLERANCE)
}
}
/// How the second column turns from the first: positive anticlockwise, as every exact turn and scale does, 0 when they lie on one line
fn determinant([across, down]: [[f32; 2]; 2]) -> f32 {
across[0] * down[1] - across[1] * down[0]
}
fn squared_distance(a: [f32; 2], b: [f32; 2]) -> f32 {
(a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)
}
/// The whole step nearest `exact` (a corner of the cell it lies in) whose columns from `pair` turn as an exact pair does; a corner usually does; otherwise the rounded pair stays
fn turning_step(exact: [f32; 2], pair: impl Fn([f32; 2]) -> [[f32; 2]; 2]) -> Option<[f32; 2]> {
let [x, y] = exact.map(f32::floor);
[[x, y], [x + 1.0, y], [x, y + 1.0], [x + 1.0, y + 1.0]]
.into_iter()
.filter(|corner| determinant(pair(*corner)) > 0.0)
.min_by(|a, b| squared_distance(*a, exact).total_cmp(&squared_distance(*b, exact)))
}
#[cfg(test)]
mod tests {
use super::*;
impl TileTransform {
/// Where the texel at `uv` reads from in its tile (0..1), or None where the content does not repeat and no longer reaches (the renderer's read, without its bilinear corners)
fn source(&self, [u, v]: [f32; 2]) -> Option<[f32; 2]> {
let (columns, shift) = self.affine();
let at = [0, 1].map(|axis| columns[0][axis] * u + columns[1][axis] * v + shift[axis]);
match self.repeat {
RepeatMode::HorizontallyAndVertically => Some(at.map(|along| along.rem_euclid(1.0))),
RepeatMode::None => at.iter().all(|along| (0.0..=1.0).contains(along)).then_some(at),
}
}
}
fn near(a: [f32; 2], b: [f32; 2]) -> bool {
(a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4
}
#[test]
fn the_library_transform_reads_each_texel_from_itself() {
let transform = TileTransform::LIBRARY;
assert!(transform.is_identity());
assert!(near(transform.source([0.3, 0.7]).unwrap_or_default(), [0.3, 0.7]));
}
#[test]
fn scaling_offset_and_flip_move_the_reads_about_the_centre() {
let mut transform = TileTransform { scaling: [2.0, 2.0], ..TileTransform::LIBRARY };
assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.5, 0.5]), "the centre stays");
assert!(near(transform.source([0.75, 0.5]).unwrap_or_default(), [0.0, 0.5]), "twice the content: a quarter tile reads half a tile on");
transform.repeat = RepeatMode::None;
assert_eq!(transform.source([0.9, 0.5]), None, "past the content reads nothing without repeat");
transform = TileTransform { offset: [0.25, 0.0], ..TileTransform::LIBRARY };
assert!(near(transform.source([0.5, 0.5]).unwrap_or_default(), [0.75, 0.5]));
assert!(near(transform.source([0.9, 0.5]).unwrap_or_default(), [0.15, 0.5]), "the read wraps round the tile");
transform = TileTransform { flip: FlipMode::Horizontally, ..TileTransform::LIBRARY };
assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.8, 0.3]));
transform.flip = FlipMode::Vertically;
assert!(near(transform.source([0.2, 0.3]).unwrap_or_default(), [0.2, 0.7]));
}
#[test]
fn a_tile_safe_turn_moves_whole_tiles_per_edge() {
let transform = TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..TileTransform::LIBRARY };
let (columns, _) = transform.affine();
assert_eq!(columns, [[2.0, 1.0], [-1.0, 2.0]], "the turn snaps to whole steps, about 26.6°");
// A small turn of the plain tile snaps back to no turn, never to nothing
let small = TileTransform { rotation: 10.0, ..TileTransform::LIBRARY };
assert_eq!(small.affine().0, [[1.0, 0.0], [0.0, 1.0]]);
let tiny = TileTransform { scaling: [0.1, 0.1], rotation: 45.0, ..TileTransform::LIBRARY };
assert!(tiny.affine().0.iter().all(|column| column != &[0.0, 0.0]));
// Unsafe, the turn is exact
let free = TileTransform { tile_safe: false, ..transform };
assert!((free.affine().0[0][1] - 2.0 * 30f32.to_radians().sin()).abs() < 1e-5);
// A square turn keeps its scaling
let square = TileTransform { scaling: [1.5, 1.5], rotation: 90.0, ..TileTransform::LIBRARY };
assert!((square.affine().0[1][0] + 1.5).abs() < 1e-5);
// A turn just short of a whole one is square too (a tiny negative turn is stored that way)
let nearly_whole = TileTransform { scaling: [1.5, 1.5], rotation: 359.99995, ..TileTransform::LIBRARY };
assert!((nearly_whole.affine().0[0][0] - 1.5).abs() < 1e-5, "{:?}", nearly_whole.affine().0);
}
#[test]
fn a_tile_safe_turn_never_rounds_both_steps_onto_one_line() {
// Narrow and tall, turned half a quarter: both steps round straight down, so one moves off that line
let narrow = TileTransform { scaling: [0.1, 2.0], rotation: 45.0, ..TileTransform::LIBRARY };
let (columns, _) = narrow.affine();
assert!(determinant(columns) > 0.0, "the source is read in two directions: {columns:?}");
}
#[test]
fn a_turn_a_hair_short_of_a_whole_one_changes_nothing() {
for tile_safe in [true, false] {
let transform = TileTransform { rotation: 359.99998, tile_safe, ..TileTransform::LIBRARY };
assert!(transform.is_identity(), "tile safe {tile_safe}: {:?}", transform.affine());
}
assert!(!TileTransform { rotation: 359.9, tile_safe: false, ..TileTransform::LIBRARY }.is_identity());
}
#[test]
fn hostile_values_stay_in_the_tile() {
let transform = TileTransform { scaling: [f32::NAN, f32::INFINITY], offset: [f32::NAN, -1e30], rotation: f32::INFINITY, ..TileTransform::LIBRARY };
let [u, v] = transform.source([0.9, 0.9]).unwrap_or_default();
assert!((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v));
}
}
@@ -0,0 +1,49 @@
use serde::{Deserialize, Serialize};
/// Which way the Transform filter turns its result over
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FlipMode {
#[default]
None,
/// Left and right swap
Horizontally,
/// Top and bottom swap
Vertically,
HorizontallyAndVertically,
}
impl FlipMode {
/// Every mode, in the order a list shows them
pub const ALL: [FlipMode; 4] = [FlipMode::None, FlipMode::Horizontally, FlipMode::Vertically, FlipMode::HorizontallyAndVertically];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
FlipMode::None => "None",
FlipMode::Horizontally => "Horizontally",
FlipMode::Vertically => "Vertically",
FlipMode::HorizontallyAndVertically => "Horizontally & Vertically",
}
}
/// The id `effect.set {flipMode}` takes
pub fn id(self) -> &'static str {
match self {
FlipMode::None => "none",
FlipMode::Horizontally => "horizontally",
FlipMode::Vertically => "vertically",
FlipMode::HorizontallyAndVertically => "horizontallyAndVertically",
}
}
/// Whether it swaps across (left and right) and down (top and bottom)
pub fn sides(self) -> [bool; 2] {
match self {
FlipMode::None => [false, false],
FlipMode::Horizontally => [true, false],
FlipMode::Vertically => [false, true],
FlipMode::HorizontallyAndVertically => [true, true],
}
}
}
@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
/// Whether a moved texture repeats across its UV tile or leaves empty where it no longer reaches
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RepeatMode {
/// Past the tile's edge reads empty
None,
/// The tile repeats both ways, so the result stays seamless
#[default]
HorizontallyAndVertically,
}
impl RepeatMode {
/// Every mode, in the order a list shows them
pub const ALL: [RepeatMode; 2] = [RepeatMode::None, RepeatMode::HorizontallyAndVertically];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
RepeatMode::None => "None",
RepeatMode::HorizontallyAndVertically => "Horizontally & Vertically",
}
}
/// The id `effect.set {repeatMode}` takes
pub fn id(self) -> &'static str {
match self {
RepeatMode::None => "none",
RepeatMode::HorizontallyAndVertically => "horizontallyAndVertically",
}
}
}
+33
View File
@@ -0,0 +1,33 @@
//! Settings and values sanitised to the 0..1 range filters read them in
/// A value at its threshold still counts when float rounding left it a step below (a white read back as 0.99999994)
const THRESHOLD_TOLERANCE: f32 = f32::EPSILON;
/// `x` clamped to 0..1, 0 when not finite
pub fn finite_unit(x: f32) -> f32 {
if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 }
}
/// Whether `value` reaches `threshold` (clamped to 0..1, `fallback` when not finite)
pub fn at_or_above_threshold(value: f32, threshold: f32, fallback: f32) -> bool {
let threshold = if threshold.is_finite() { threshold.clamp(0.0, 1.0) } else { fallback };
value >= threshold - THRESHOLD_TOLERANCE
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn values_land_in_the_unit_range() {
assert_eq!([finite_unit(-2.0), finite_unit(0.25), finite_unit(7.0), finite_unit(f32::NAN), finite_unit(f32::INFINITY)], [0.0, 0.25, 1.0, 0.0, 0.0]);
}
#[test]
fn a_threshold_counts_a_value_rounded_just_below_it() {
assert!(at_or_above_threshold(1.0 - f32::EPSILON / 2.0, 1.0, 0.5));
assert!(!at_or_above_threshold(0.49, 0.5, 0.5));
assert!(at_or_above_threshold(0.5, f32::NAN, 0.5), "a hostile threshold falls back");
assert!(at_or_above_threshold(1.0, 9.0, 0.5), "a threshold past 1 is 1");
}
}
+46
View File
@@ -0,0 +1,46 @@
//! Which texels PBR Validate checks
use serde::{Deserialize, Serialize};
/// PBR Validate's Validation Mode: the non-metal base colors, the metal ones, or both
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ValidationMode {
Albedo,
Metal,
#[default]
Combined,
}
impl ValidationMode {
/// Every mode, in the order a switch shows them
pub const ALL: [ValidationMode; 3] = [ValidationMode::Albedo, ValidationMode::Metal, ValidationMode::Combined];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
ValidationMode::Albedo => "Albedo",
ValidationMode::Metal => "Metal",
ValidationMode::Combined => "Combined",
}
}
/// The id `effect.set {validationMode}` takes
pub fn id(self) -> &'static str {
match self {
ValidationMode::Albedo => "albedo",
ValidationMode::Metal => "metal",
ValidationMode::Combined => "combined",
}
}
/// Whether non-metal base colors are checked
pub fn checks_albedo(self) -> bool {
self != ValidationMode::Metal
}
/// Whether metal base colors are checked
pub fn checks_metal(self) -> bool {
self != ValidationMode::Albedo
}
}
+42
View File
@@ -0,0 +1,42 @@
//! How a Multi Directional Warp combines its directions
use serde::{Deserialize, Serialize};
/// How the reads of a Multi Directional Warp's directions combine
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarpBlending {
#[default]
Average,
/// The largest of them, per component
Max,
/// The smallest of them, per component
Min,
/// One move after the other, each from where the last one landed
Chain,
}
impl WarpBlending {
/// Every choice, in the order a panel lists them
pub const ALL: [WarpBlending; 4] = [WarpBlending::Average, WarpBlending::Max, WarpBlending::Min, WarpBlending::Chain];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
WarpBlending::Average => "Average",
WarpBlending::Max => "Max",
WarpBlending::Min => "Min",
WarpBlending::Chain => "Chain",
}
}
/// The id `effect.set` takes
pub fn id(self) -> &'static str {
match self {
WarpBlending::Average => "average",
WarpBlending::Max => "max",
WarpBlending::Min => "min",
WarpBlending::Chain => "chain",
}
}
}
+39
View File
@@ -0,0 +1,39 @@
//! How a Warp moves the texels it reads
use serde::{Deserialize, Serialize};
/// Which way a Warp moves texels: along its source's slope, along one direction, or along several
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarpMode {
/// Along the source's slope, each texel its own way
#[default]
Warp,
/// Along the Angle, forwards or backwards by the source
Directional,
/// Along Directions spread evenly from the Angle, blended
MultiDirectional,
}
impl WarpMode {
/// Every choice, in the order a panel lists them
pub const ALL: [WarpMode; 3] = [WarpMode::Warp, WarpMode::Directional, WarpMode::MultiDirectional];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
WarpMode::Warp => "Warp",
WarpMode::Directional => "Directional Warp",
WarpMode::MultiDirectional => "Multi Directional Warp",
}
}
/// The id `effect.set` takes
pub fn id(self) -> &'static str {
match self {
WarpMode::Warp => "warp",
WarpMode::Directional => "directional",
WarpMode::MultiDirectional => "multiDirectional",
}
}
}
+68
View File
@@ -0,0 +1,68 @@
//! The values a Warp's moves follow and how they are shaped first
use serde::{Deserialize, Serialize};
use crate::WarpSourceMode;
use crate::gradient_input::{NEUTRAL_BALANCE, shape_gray};
/// A Warp's source: noise, the values it filters or an image, blurred, balanced and contrasted
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WarpSource {
pub mode: WarpSourceMode,
/// How widely the source is averaged first (0..1, up to [`WarpSource::BLUR_SHARE`] of the UV tile)
pub blur: f32,
/// Added to the source around 0.5 (0..1)
pub balance: f32,
/// Steepens the source around mid gray (0..1)
pub contrast: f32,
/// Source frequency multiplier within a UV tile (0.01..16)
pub tiling: f32,
}
impl WarpSource {
/// The source as the library's Warp starts with it
pub const LIBRARY: WarpSource = WarpSource { mode: WarpSourceMode::DefaultNoise, blur: 0.0, balance: NEUTRAL_BALANCE, contrast: 0.0, tiling: 1.0 };
/// Noise features across a UV tile at Source Tiling 1
pub const NOISE_FEATURES: f32 = 4.0;
/// The share of the UV tile a Source Blur of 1 averages over
pub const BLUR_SHARE: f32 = 1.0 / 16.0;
/// Mid gray: the source value that moves nothing, and the noise's middle
pub const MID_GRAY: f32 = 0.5;
/// How far noise is stretched from mid gray so it spans black to white
pub const NOISE_STRETCH: f32 = 1.5;
/// The Tiling range
pub const TILING_MIN: f32 = 0.01;
pub const TILING_MAX: f32 = 16.0;
/// Noise features per UV tile
pub fn noise_scale(&self) -> f32 {
Self::NOISE_FEATURES * self.tiling_factor()
}
/// Source tiling after validating saved settings
pub fn tiling_factor(&self) -> f32 {
if self.tiling.is_finite() { self.tiling.clamp(Self::TILING_MIN, Self::TILING_MAX) } else { 1.0 }
}
/// How many texels across the source is averaged over at `res` texels across a UV tile
pub fn blur_texels(&self, res: u32) -> f32 {
let blur = if self.blur.is_finite() { self.blur.clamp(0.0, 1.0) } else { 0.0 };
blur * Self::BLUR_SHARE * res as f32
}
/// Fractal noise `noise` (around mid gray) stretched to span 0..1
pub fn stretch_noise(noise: f32) -> f32 {
if noise.is_finite() { (Self::MID_GRAY + (noise - Self::MID_GRAY) * Self::NOISE_STRETCH).clamp(0.0, 1.0) } else { Self::MID_GRAY }
}
/// Source value `value` after Balance and Contrast
pub fn shape(&self, value: f32) -> f32 {
shape_gray(value, self.balance, self.contrast, false)
}
}
+39
View File
@@ -0,0 +1,39 @@
//! What drives a Warp
use serde::{Deserialize, Serialize};
/// The values a Warp's moves follow
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarpSourceMode {
/// Fractal noise of the Warp's seed
#[default]
DefaultNoise,
/// The values the Warp filters (their luminance)
PreviousInput,
/// An image input (until one is linked: flat, so nothing moves)
CustomNoise,
}
impl WarpSourceMode {
/// Every choice, in the order a panel lists them
pub const ALL: [WarpSourceMode; 3] = [WarpSourceMode::DefaultNoise, WarpSourceMode::PreviousInput, WarpSourceMode::CustomNoise];
/// The name a panel shows
pub fn label(self) -> &'static str {
match self {
WarpSourceMode::DefaultNoise => "Default Noise",
WarpSourceMode::PreviousInput => "Previous Input",
WarpSourceMode::CustomNoise => "Custom Noise",
}
}
/// The id `effect.set` takes
pub fn id(self) -> &'static str {
match self {
WarpSourceMode::DefaultNoise => "defaultNoise",
WarpSourceMode::PreviousInput => "previousInput",
WarpSourceMode::CustomNoise => "customNoise",
}
}
}
+85
View File
@@ -0,0 +1,85 @@
//! What each library filter does, in one sentence, and the words it is found by: the Attributes of its properties
/// A library filter's description and tags
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FilterAbout {
pub description: &'static str,
pub tags: &'static [&'static str],
}
const fn about(description: &'static str, tags: &'static [&'static str]) -> FilterAbout {
FilterAbout { description, tags }
}
/// One entry per library filter id, found by its id
const ABOUT: &[(&str, FilterAbout)] = &[
("hsl", about("Shifts the hue and changes the saturation and lightness of the colors.", &["color", "hue", "saturation", "lightness"])),
("levels", about("Remaps the values between new black and white points, with a midtone gamma.", &["levels", "contrast", "remap"])),
("contrastLuminosity", about("Raises or lowers the contrast and the overall brightness.", &["contrast", "brightness"])),
("colorBalance", about("Tints the shadows, midtones and highlights each towards a color.", &["color", "tint", "balance"])),
(
"colorCorrect",
about("Corrects the contrast, luminosity and saturation of the shadows, midtones and highlights.", &["color", "correction", "saturation"]),
),
("gradientMap", about("Replaces each value by the color at its place on a gradient.", &["gradient", "color", "remap"])),
("gradientCurve", about("Bends the values through a curve preset.", &["gradient", "curve", "remap"])),
("gradientDynamic", about("Reads the colors along a gradient source at each value's position.", &["gradient", "color", "dynamic"])),
("posterize", about("Rounds the values to a few steps.", &["steps", "quantize", "flat"])),
("clamp", about("Keeps the values between a minimum and a maximum.", &["clamp", "range", "limit"])),
("smoothstep", about("Eases the values between a minimum and a maximum from black to white.", &["smoothstep", "range", "ease"])),
("heightAdjust", about("Flips, scales and raises heights around mid gray.", &["height", "offset", "multiply"])),
("histogramScan", about("Turns the values into a sharp or soft cut at a chosen position.", &["histogram", "contrast", "cut"])),
("histogramRange", about("Squeezes the values into a narrower range around a position.", &["histogram", "range"])),
("histogramShift", about("Slides the values along and wraps them around.", &["histogram", "shift", "wrap"])),
("invert", about("Turns dark into light and light into dark.", &["invert", "negative"])),
("threshold", about("Makes every value white past the threshold and black below it.", &["threshold", "black and white", "cut"])),
("grayscale", about("Turns the colors into grays.", &["grayscale", "desaturate"])),
("edgeDetect", about("Draws lines where the values change sharply.", &["edges", "outline", "lines"])),
("normalInvert", about("Flips the green component of a normal map.", &["normal", "invert", "green"])),
("bakedLighting", about("Paints sun, sky and light shading into the base color from the baked mesh maps.", &["lighting", "stylized", "shading"])),
("bakedLightingEnvironment", about("Lights the base color with the viewport environment.", &["lighting", "environment", "shading"])),
("replaceColor", about("Swaps one color for another, keeping the shading.", &["color", "replace", "swap"])),
("blur", about("Softens the input: each texel spreads into its neighbours.", &["blur", "soften"])),
("blurDirectional", about("Smears the input along one direction.", &["blur", "motion", "direction"])),
("blurSlope", about("Smears the values downhill along a noise height field.", &["blur", "slope", "flow"])),
("sharpen", about("Makes the details crisper.", &["sharpen", "detail"])),
("highPass", about("Keeps the fine details and drops the broad shapes.", &["detail", "high pass", "frequency"])),
("bevel", about("Slopes the shapes down to their edge, or raises a slope around them.", &["bevel", "edge", "slope"])),
("bevelSmooth", about("Draws a smooth ramp from the edge of the shapes.", &["bevel", "edge", "ramp"])),
("directionalDistance", about("Draws a trail fading away from the shapes towards an angle.", &["distance", "trail", "leak"])),
("glow", about("Lays a soft halo of color around the shapes.", &["glow", "halo", "light"])),
("dropShadow", about("Lays a blurred, offset shadow of the shapes under them.", &["shadow", "drop shadow"])),
("maskOutline", about("Draws a band along the edge of the shapes.", &["outline", "edge", "stroke"])),
("warp", about("Moves the texels by a noise or another source.", &["warp", "distort", "noise"])),
("mosaic", about("Breaks the input into square pixels, a set number across the UV tile.", &["pixelate", "mosaic", "cells"])),
("fxaa", about("Smooths stair-stepped edges by blending across them.", &["anti-aliasing", "edges", "smooth"])),
("anisotropicKuwahara", about("Smooths the input into painterly strokes that follow its direction.", &["painterly", "smooth", "stylize"])),
("pbrValidate", about("Shows in red the base colors outside the physically plausible ranges.", &["pbr", "validate", "albedo", "metal"])),
("colorMatch", about("Moves the colors so a source color, the texture's mean by default, lands on a target color.", &["color", "match", "recolor"])),
("heightToNormal", about("Turns the layer's height into its normal.", &["height", "normal", "convert"])),
("mirror", about("Copies one side of each UV tile over the other.", &["mirror", "symmetry", "flip"])),
("transform", about("Scales, turns, moves and flips the content of each UV tile.", &["transform", "scale", "rotate", "offset", "flip"])),
("matFinishGrind", about("Gives the material a ground finish: fine brushed lines in its roughness.", &["material", "metal", "scratches"])),
("matFinishRaw", about("Gives the material a raw finish: uneven, cloudy roughness.", &["material", "raw", "rough"])),
("matFinishSanded", about("Gives the material a sanded finish: a fine, even grain in its roughness.", &["material", "sanded", "rough"])),
("matFinishHammered", about("Gives the material a hammered finish: round dents in its roughness.", &["material", "metal", "hammered"])),
];
/// The description and tags of library filter `id` (its exact id)
pub fn of(id: &str) -> Option<FilterAbout> {
ABOUT.iter().find(|(entry, _)| *entry == id).map(|(_, about)| *about)
}
#[cfg(test)]
mod tests {
use super::of;
use crate::filter_lib::FILTERS;
#[test]
fn every_library_filter_is_described_and_tagged() {
for def in FILTERS {
let about = of(def.id).unwrap_or_else(|| panic!("{} has no description", def.id));
assert!(about.description.ends_with('.') && !about.tags.is_empty(), "{}", def.id);
}
}
}
File diff suppressed because it is too large. Load diff
+42 -13
View File
@@ -153,7 +153,7 @@ fn randomize_seeds(s: &mut Session, p: &Value) -> Result<Value> {
for (index, (target, seed)) in (0u32..).zip(seeds) {
let before = originals.get(&target).filter(|record| record.after == *seed).map_or(*seed, |record| record.before);
let after = next_seed(*seed ^ key);
randomized.push(RandomizedSeed { layer: *id, target: Some(target), index, before, after });
randomized.push(RandomizedSeed { layer: *id, target: Some((target.0, target.1)), input: target.2, index, before, after });
*seed = after;
}
}
@@ -164,7 +164,7 @@ fn randomize_seeds(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "seeds": seeds }))
}
type SeedTarget = (LayerId, Option<Channel>);
type SeedTarget = (LayerId, Option<Channel>, Option<String>);
fn take_seed_records(project: &mut Project, folder: LayerId) -> HashMap<LayerId, Vec<RandomizedSeed>> {
let mut by_layer = HashMap::<_, Vec<_>>::new();
@@ -180,7 +180,10 @@ fn original_seeds<'a>(seeds: &[(SeedTarget, &mut u32)], records: &'a [Randomized
.iter()
.filter_map(|record| {
// Old records identified a seed by its position in the layer
let target = record.target.or_else(|| seeds.get(record.index as usize).map(|(target, _)| *target))?;
let target = record
.target
.map(|(id, channel)| (id, channel, record.input.clone()))
.or_else(|| seeds.get(record.index as usize).map(|(target, _)| target.clone()))?;
Some((target, record))
})
.collect()
@@ -224,22 +227,36 @@ fn layer_seeds(layer: &mut Layer) -> Vec<(SeedTarget, &mut u32)> {
let Layer { id, kind, content_effects, mask, .. } = layer;
let mut seeds = Vec::new();
if let LayerKind::Fill(fill) = kind {
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((*id, Some(channel)), source_seed(source)?))));
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((*id, Some(channel), None), source_seed(source)?))));
}
let mut inputs = Vec::new();
let effects = content_effects.iter_mut().chain(mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()));
for effect in effects {
if matches!(effect.kind, EffectKind::Filter(_)) {
inputs.extend(effect.inputs.iter_mut().filter_map(|(name, source)| {
let seed = source_seed(source)?;
Some(((effect.id, None, Some(name.clone())), seed))
}));
}
match &mut effect.kind {
EffectKind::Fill { source, .. } => seeds.extend(source_seed(source).map(|seed| ((effect.id, None), seed))),
EffectKind::Fill { source, .. } => seeds.extend(source_seed(source).map(|seed| ((effect.id, None, None), seed))),
EffectKind::Material(fill) => {
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((effect.id, Some(channel)), source_seed(source)?))))
seeds.extend(fill.sources.iter_mut().filter_map(|(&channel, source)| Some(((effect.id, Some(channel), None), source_seed(source)?))))
}
EffectKind::Generator(generator) => seeds.push(((effect.id, None), &mut generator.seed)),
EffectKind::Generator(generator) => seeds.push(((effect.id, None, None), &mut generator.seed)),
EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => {
seeds.push(((effect.id, None), seed))
seeds.push(((effect.id, None, None), seed))
}
EffectKind::Filter(Filter::SourceWarp(warp)) => seeds.push(((effect.id, None, None), &mut warp.seed)),
EffectKind::Filter(Filter::SourceSlopeBlur(slope)) => seeds.push(((effect.id, None, None), &mut slope.seed)),
_ => {}
}
}
// Legacy positional records count only the layer and effect seeds
seeds.extend(inputs);
seeds
}
@@ -252,11 +269,23 @@ fn seed_count(layer: &Layer) -> usize {
};
let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()));
let effect_seeds: usize = effects
.map(|effect| match &effect.kind {
EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })),
EffectKind::Material(fill) => fill_seeds(fill),
EffectKind::Generator(_) | EffectKind::Filter(Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. }) => 1,
_ => 0,
.map(|effect| {
let inputs = if matches!(effect.kind, EffectKind::Filter(_)) {
effect.inputs.values().filter(|source| matches!(source, Source::Procedural { .. })).count()
} else {
0
};
inputs
+ match &effect.kind {
EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })),
EffectKind::Material(fill) => fill_seeds(fill),
EffectKind::Generator(_)
| EffectKind::Filter(
Filter::Warp { .. } | Filter::SlopeBlur { .. } | Filter::DirectionalWarp { .. } | Filter::SourceWarp(_) | Filter::SourceSlopeBlur(_),
) => 1,
_ => 0,
}
})
.sum();
own + effect_seeds
+8 -2
View File
@@ -74,6 +74,12 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
effect.channel_blends.iter().map(|(channel, blend)| (channel.id().to_string(), json!({ "blend": blend.mode.label(), "opacity": blend.opacity })));
out["channelBlends"] = Value::Object(channels.collect());
}
if !effect.off_channels.is_empty() {
out["offChannels"] = json!(effect.off_channels.iter().map(|channel| channel.id()).collect::<Vec<_>>());
}
if !effect.inputs.is_empty() {
out["inputs"] = Value::Object(effect.inputs.iter().map(|(id, source)| (id.clone(), source_json(source))).collect());
}
let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count());
let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::<usize>();
@@ -119,8 +125,8 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
EffectKind::Filter(filter) => {
out["filter"] = json!(filter);
match filter {
Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]),
Filter::Blur { radius } => out["radius"] = json!(radius),
Filter::Hsl { hue, saturation, lightness, .. } => out["hsl"] = json!([hue, saturation, lightness]),
Filter::Blur { radius, .. } => out["radius"] = json!(radius),
_ => {}
}
}
+58 -10
View File
@@ -3,8 +3,8 @@
use serde_json::{Value, json};
use texturecraft_core::{
Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, Layer, LayerId, LayerKind, NormalFormat,
Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap,
Backface, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, EffectKind, Fill, FillSymmetry, Filtering, ImageInput, Layer, LayerId, LayerKind,
NormalFormat, Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap,
};
use texturecraft_paint::alphas::{self, LibraryAlpha};
@@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set fill source",
[],
None,
"{layer? | effect?: content fill effect id | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), 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?|alpha?: library alpha id or name (its picture becomes a project image, normally alpha_<id>.png), 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 | mask fill effect id (one grayscale source: no channel, enabled, solo or normalFormat), channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high? (the same kind keeps what is not given), 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?|alpha?: library alpha id or name (its picture becomes a project image, normally alpha_<id>.png), 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)} | {effect: filter effect id, input: image input id (distanceMap, customNoise), value?|procedural?|image?|alpha?|anchor? as a mask fill's source, or clear: true (back to its default gray)}",
has_layer,
fill_set
),
@@ -566,6 +566,11 @@ fn mask_source_mut(s: &mut Session, effect: LayerId) -> Result<&mut Source> {
}
fn fill_set(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(input) = params.get("input") {
let input = input.as_str().ok_or_else(|| bad(FILL_SET, "`input` must be a filter input name"))?;
return input_set(session, params, input);
}
let target = fill_target(session, params, FILL_SET)?;
if let FillTarget::Mask(effect) = target {
return mask_fill_set(session, params, effect);
@@ -670,23 +675,62 @@ fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result<Value> {
refuse_gray_keys(p, "a mask fill")?;
let current = mask_source_mut(s, effect)?.clone();
let (source, library_alpha) = gray_source(s, p, effect, &current)?;
let (mut source, library_alpha) = gray_source(s, p, effect, &current)?;
// Setting what the fill already reads adds no undo step
if source == current && library_alpha_present(s, library_alpha) {
if gray_source_is_current(s, Some(&current), Some(&source), library_alpha) {
return Ok(Value::Null);
}
s.edit("Set fill", |s| {
if let Some(alpha) = library_alpha {
s.add_library_alpha(alpha)?;
if let (Some(alpha), Source::Image { name, .. }) = (library_alpha, &mut source) {
*name = s.add_library_alpha(alpha)?;
}
*mask_source_mut(s, effect)? = source;
Ok(())
})?;
Ok(Value::Null)
}
/// `layer.fill.set {effect, input}`: the source of a filter effect's image input `id`, or its default gray back (`clear`)
fn input_set(s: &mut Session, p: &Value, id: &str) -> Result<Value> {
let effect = u64p(p, "effect").map(LayerId).ok_or_else(|| bad(FILL_SET, "`input` goes with a filter `effect`"))?;
let found = s.doc.project.effect(effect).map(|(_, found)| found).ok_or_else(|| bad(FILL_SET, format!("no effect {}", effect.0)))?;
let EffectKind::Filter(filter) = &found.kind else { return Err(bad(FILL_SET, format!("{} is not a filter effect", effect.0))) };
let input = ImageInput::named(filter, id).ok_or_else(|| bad(FILL_SET, format!("the {} filter has no image input `{id}`", filter.label())))?;
refuse_gray_keys(p, "an image input")?;
let (source, library_alpha) = if p.get("clear").and_then(Value::as_bool) == Some(true) {
(None, None)
} else {
let (source, alpha) = gray_source(s, p, effect, &found.input(&input))?;
(Some(source), alpha)
};
// Its default gray is not stored, so a project that never set the input saves as before
let mut stored = source.filter(|source| *source != input.default_source());
// Setting what the input already reads adds no undo step
if gray_source_is_current(s, found.inputs.get(input.id), stored.as_ref(), library_alpha) {
return Ok(Value::Null);
}
s.edit("Set image input", |s| {
if let (Some(alpha), Some(Source::Image { name, .. })) = (library_alpha, &mut stored) {
*name = s.add_library_alpha(alpha)?;
}
let found = s.doc.project.effect_mut(effect).ok_or_else(|| bad(FILL_SET, "the effect is gone"))?;
match stored {
Some(source) => found.inputs.insert(input.id.to_string(), source),
None => found.inputs.remove(input.id),
};
Ok(())
})?;
Ok(Value::Null)
}
/// Refuses the [`GRAY_REFUSED_KEYS`] for `subject`, a fill with one grayscale source
fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> {
if GRAY_REFUSED_KEYS.iter().any(|key| p.get(key).is_some()) {
@@ -697,9 +741,13 @@ fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> {
Ok(())
}
/// Whether the project already holds `library_alpha`'s image (true when there is none to add)
fn library_alpha_present(s: &Session, library_alpha: Option<&LibraryAlpha>) -> bool {
library_alpha.is_none_or(|alpha| s.doc.resources.contains_key(&crate::fill_alpha::resource_name(alpha)))
/// Whether the current source already reads the requested value or library alpha
fn gray_source_is_current(s: &Session, current: Option<&Source>, requested: Option<&Source>, library_alpha: Option<&LibraryAlpha>) -> bool {
if let Some(alpha) = library_alpha {
return matches!(current, Some(Source::Image { name, .. }) if s.library_alpha(name).is_some_and(|current_alpha| current_alpha.id == alpha.id));
}
current == requested
}
/// The grayscale source `p` asks for in place of `current` (read by a mask or filter effect `effect`), and the library alpha it needs added
+3
View File
@@ -24,6 +24,7 @@ pub mod fill_hit_test;
pub mod fill_material_cmds;
pub mod fill_mode;
pub mod fill_reset_cmds;
pub mod filter_about;
pub mod filter_lib;
pub mod folder_cmds;
mod frame_target;
@@ -73,10 +74,12 @@ mod session_log;
pub mod set_cmds;
pub mod smart_masks;
mod solo;
mod stylized_lighting_params;
pub mod swatch_cmds;
pub mod template_cmds;
pub mod text_cmds;
pub mod thumbs;
mod tile_transform_params;
mod tool_availability;
pub mod tool_cmds;
pub mod tool_settings;
+58 -10
View File
@@ -12,6 +12,9 @@ use crate::mask_owner::MaskOwner;
use crate::session::StackTarget;
use crate::{EngineError, Result, Session, cmd};
/// The `filter` id of a filter effect with no filter picked
pub const EMPTY_FILTER: &str = "none";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mask.add.white", "Add white mask", ["Layers", "Mask"], None, "{layer?}", has_layer, |s, p| add_mask(s, p, MaskBackground::White)),
@@ -68,7 +71,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add filter",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
"{layer?, target?: mask|content, name?, filter?: any id or label from filter.list (warp with warpMode: warp|directional|multiDirectional, blurSlope with quality?) or \"none\" for an empty filter that changes nothing, level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], positions?: [0..1, ...], quantity?: 2..10, grayscaleMode?: desaturation|luma|average|max|min, blur?, balance?, invert?, linear?, debug?, preset?: round|pinch|stairs|easeOut|ease|easeIn|peakOut|peak|peakIn|bump|doubleBump|triangular, orientation?: horizontal|vertical, color?, levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
has_layer,
add_filter
),
@@ -95,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit effect",
[],
None,
"{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}",
"{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}",
has_layer,
set
),
@@ -295,6 +298,14 @@ fn push_effect_in(
if let Some(name) = name_param(p) {
effect.name = name.to_string();
}
// A filter that changes only some channels (lighting, validation) starts with the other channels' pills off
if content
&& let EffectKind::Filter(filter) = &effect.kind
&& let Some(on) = filter.starts_on()
{
effect.off_channels = Channel::ALL.into_iter().filter(|channel| !on.contains(channel)).collect();
}
if !content {
layer.mask.get_or_insert_with(|| Mask::new(background)).effects.push(effect);
} else if layer.is_group() {
@@ -590,7 +601,9 @@ fn add_levels(s: &mut Session, p: &Value) -> Result<Value> {
fn add_filter(s: &mut Session, p: &Value) -> Result<Value> {
let id = strp(p, "filter").unwrap_or("invert");
let kind = crate::filter_lib::build(id, p)?;
// An empty filter changes nothing until one is picked into it
let kind = if id == EMPTY_FILTER { EffectKind::Filter(Filter::Empty) } else { crate::filter_lib::build(id, p)? };
// Library filters are named after their shelf entry (material finishes are fill effects)
let mut p = p.clone();
@@ -722,6 +735,11 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(CMD, "a mask's levels remap its one value: leave out `affects`"));
}
let switched = switched_channels(params)?;
if !switched.is_empty() && on_mask {
return Err(bad(CMD, "a mask effect has one value: leave out `channels`"));
}
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
let anchor = match session.doc.project.effect(effect) {
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
@@ -759,8 +777,8 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
_ => None,
};
// Naming the filter the effect already is edits its parameters like a plain effect.set
let swapped = match strp(params, "filter") {
Some(EMPTY_FILTER) => Some(emptied_filter(session, effect)?),
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
Some(filter) => Some(swapped_filter(session, effect, filter, params)?),
None => None,
@@ -773,7 +791,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
if let Some((kind, label)) = swapped {
if let EffectKind::Filter(old) = &edited.kind
&& edited.name == old.label()
&& (edited.name == old.label() || Some(edited.name.as_str()) == old.former_label())
{
edited.name = label.to_string();
}
@@ -783,6 +801,13 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(visible) = boolp(params, "visible") {
edited.visible = visible;
}
for (channel, on) in &switched {
if *on {
edited.off_channels.remove(channel);
} else {
edited.off_channels.insert(*channel);
}
}
crate::effect_blending_cmds::set_blending(edited, channel, blend, f32p(params, "opacity"));
if let Some(name) = name_param(params) {
edited.name = name.to_string();
@@ -882,10 +907,34 @@ fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result<Optio
Ok(Some(Source::Procedural { pattern, low: range.0, high: range.1, ramp: Vec::new() }))
}
/// The content channels `channels` switches on (true) or off for an effect, e.g. {"roughness": false}
fn switched_channels(params: &Value) -> Result<Vec<(Channel, bool)>> {
const CMD: &str = "effect.set";
let Some(given) = params.get("channels") else { return Ok(Vec::new()) };
let given = given.as_object().ok_or_else(|| bad(CMD, "`channels` must be an object of channel ids to true (on) or false (off)"))?;
given
.iter()
.map(|(id, on)| {
let channel = Channel::parse(id).ok_or_else(|| bad(CMD, format!("unknown channel `{id}`")))?;
let on = on.as_bool().ok_or_else(|| bad(CMD, format!("`channels.{id}` must be true or false")))?;
Ok((channel, on))
})
.collect()
}
/// An empty filter and its label, to replace filter effect `effect`'s
fn emptied_filter(s: &Session, effect: LayerId) -> Result<(EffectKind, &'static str)> {
match s.doc.project.effect(effect) {
Some((_, Effect { kind: EffectKind::Filter(_), .. })) => Ok((EffectKind::Filter(Filter::Empty), Filter::Empty.label())),
Some((_, other)) => Err(bad("effect.set", format!("`filter` changes filter effects only, not {}", other.kind.name().to_ascii_lowercase()))),
None => Err(bad("effect.set", format!("no effect {}", effect.0))),
}
}
/// 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 {
EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id),
EffectKind::Filter(filter) => crate::filter_lib::definition(filter).map(|def| def.id),
_ => None,
}
}
@@ -899,10 +948,9 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(
}
let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?;
let mut kind = crate::filter_lib::build(def.id, &Value::Null)?;
let EffectKind::Filter(filter) = &mut kind else {
if !def.is_filter_effect() {
return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label)));
};
}
let mask = s.doc.project.layer(owner)?.mask.as_ref();
let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect));
@@ -910,7 +958,7 @@ fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(
return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label)));
}
crate::filter_lib::apply(p, filter, CMD)?;
let kind = crate::filter_lib::build_for(CMD, id, p)?;
Ok((kind, def.label))
}
+1 -1
View File
@@ -53,7 +53,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
}
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
out.extend(effect.kind.images_read().map(str::to_string));
out.extend(effect.images_read().map(str::to_string));
out.extend(crate::path_tool::path_images(&effect.kind));
}
+45 -10
View File
@@ -2,7 +2,10 @@
use rayon::prelude::*;
use texturecraft_compose::pattern::{Coords, procedural};
use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet};
use texturecraft_core::{
Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, SIZE_REFERENCE_RES, Source, TextureSet,
TileTransform,
};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::materials::{Builder, build};
@@ -88,16 +91,16 @@ pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
/// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K).
fn magnified(f: Filter, k: f32) -> Filter {
match f {
Filter::Blur { radius } => Filter::Blur { radius: radius * k },
Filter::Blur { radius, wrap } => Filter::Blur { radius: radius * k, wrap },
Filter::DirectionalBlur { radius, angle } => Filter::DirectionalBlur { radius: radius * k, angle },
Filter::SlopeBlur { radius, scale, seed } => Filter::SlopeBlur { radius: radius * k, scale, seed },
Filter::Warp { intensity, scale, seed } => Filter::Warp { intensity: intensity * k, scale, seed },
Filter::HighPass { radius } => Filter::HighPass { radius: radius * k },
Filter::SlopeBlur { radius, scale, seed, divider } => Filter::SlopeBlur { radius: radius * k, scale, seed, divider },
Filter::Warp { intensity, scale, seed, divider } => Filter::Warp { intensity: intensity * k, scale, seed, divider },
Filter::HighPass { radius, space, alpha } => Filter::HighPass { radius: radius * k, space, alpha },
Filter::EdgeDetect { width } => Filter::EdgeDetect { width: width * k },
Filter::Bevel { width } => Filter::Bevel { width: width * k },
Filter::Mosaic { size } => Filter::Mosaic { size: size * k },
Filter::Bevel { width, wrap } => Filter::Bevel { width: width * k, wrap },
Filter::Mosaic { size, alpha } => Filter::Mosaic { size: size * k, alpha },
Filter::Glow { radius, amount } => Filter::Glow { radius: radius * k, amount },
Filter::DirectionalWarp { intensity, angle, scale, seed } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed },
Filter::DirectionalWarp { intensity, angle, scale, seed, divider } => Filter::DirectionalWarp { intensity: intensity * k, angle, scale, seed, divider },
f => f,
}
}
@@ -108,9 +111,20 @@ fn magnified(f: Filter, k: f32) -> Filter {
pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let res = u32::try_from(size).ok()?.max(1);
let kind = match crate::filter_lib::build(id, &serde_json::Value::Null).ok()? {
EffectKind::Filter(f) => EffectKind::Filter(magnified(f, 2048.0 / res as f32)),
// Transform changes nothing as the library adds it: its picture shows it scaled and turned
EffectKind::Filter(Filter::Transform(transform)) => {
EffectKind::Filter(Filter::Transform(TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..transform }))
}
EffectKind::Filter(f) => EffectKind::Filter(magnified(f, SIZE_REFERENCE_RES / res as f32)),
k => k,
};
// The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black
let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_)));
render_filter_preview(kind, size, res, shapes)
}
fn render_filter_preview(kind: EffectKind, size: usize, res: u32, shapes: bool) -> Option<Vec<Option<Sample>>> {
let mesh = texturecraft_geom::primitives::plane(2.0, 2);
let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res);
let mut p = Project::new("preview", "");
@@ -118,7 +132,12 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let procedural =
|kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() };
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]));
let base = if shapes {
procedural(ProceduralKind::Checker, 3.0, [0.0; 3], [1.0; 3])
} else {
procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1])
};
fill.sources.insert(Channel::BaseColor, base);
fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3]));
fill.sources.insert(Channel::Height, procedural(ProceduralKind::Cells, 3.0, [-0.12; 3], [0.12; 3]));
let mut layer = Layer::new(p.alloc_id(), "sample", LayerKind::Fill(fill), &CHANNELS);
@@ -192,4 +211,20 @@ mod tests {
let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap());
assert!(plain != warped, "the warp shows in its preview");
}
#[test]
fn the_edge_shaping_filters_show_their_shapes_not_black() {
const SIDE_PX: u32 = 32;
let size = SIDE_PX as usize;
// Use the same checker input with an inactive filter
let checker = render_filter_preview(EffectKind::Filter(Filter::InvertOff), size, SIDE_PX, true).unwrap();
for id in ["bevelSmooth", "directionalDistance"] {
let pixels = filter(id, size).unwrap();
assert!(pixels != checker, "{id}: the preview shows the unchanged checker");
let lit: Vec<f32> = pixels.into_iter().flatten().map(|sample| sample.base.iter().sum::<f32>() / 3.0).collect();
let bright = lit.iter().filter(|value| **value > 0.25).count();
assert!(bright * 5 > lit.len(), "{id}: {bright} of {} texels lit", lit.len());
}
}
}
+17 -15
View File
@@ -779,23 +779,25 @@ impl Session {
let added_resource_names: BTreeSet<&str> =
self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect();
let is_added = |name: &str| added_resource_names.contains(name);
let uses_added_resource =
|texture_set_index: usize| {
use texturecraft_core::{EffectKind, Fill};
let added_environment = self.doc.project.display.environment_resource().is_some_and(is_added);
let uses_added_resource = |texture_set_index: usize| {
use texturecraft_core::{EffectKind, Fill, Filter};
let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package));
let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill);
let project = &self.doc.project;
!added_resource_names.is_empty()
&& project.texture_sets.get(texture_set_index).is_some_and(|set| {
project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill))
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| {
effect.kind.images_read().any(is_added) || matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))
})
})
let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package));
let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill);
let project = &self.doc.project;
!added_resource_names.is_empty()
&& project.texture_sets.get(texture_set_index).is_some_and(|set| {
project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill))
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| {
effect.images_read().any(is_added)
|| matches!(&effect.kind, EffectKind::Material(fill) if uses_link(fill))
|| (added_environment && matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })))
})
})
};
})
};
let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default());
let stack_key = |document: &Document, texture_set_index: usize| {
let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default();
@@ -0,0 +1,99 @@
//! `effect.set` keys of Baked Lighting Stylized past Baked Lighting's sun and ambient
use serde_json::Value;
use texturecraft_core::{DirectionalLight, LightingOutput, StylizedLighting};
use crate::Result;
use crate::commands::{bad, f32p};
use crate::filter_lib::{choice, set_color, two_way};
use crate::layer_cmds::FULL_TURN_DEGREES;
/// The keys that give a Baked Lighting saved before them its stylized settings
pub(crate) const KEYS: [&str; 17] = [
"sunColor",
"skyColor",
"horizonColor",
"groundColor",
"light1",
"light2",
"diffuseCavity",
"specularAo",
"specularCavity",
"cavitySmoothness",
"edgesIntensity",
"edgesSmoothness",
"input",
"output",
"dielectricReflectance",
"normalDetails",
"heightToNormal",
];
/// The highest Dielectric Reflectance, Cavity Smoothness and Height to Normal Intensity
pub const MAX_DIELECTRIC_REFLECTANCE: f32 = 0.16;
pub const MAX_CAVITY_SMOOTHNESS: f32 = 4.0;
pub const MAX_HEIGHT_TO_NORMAL: f32 = 3.0;
/// The highest intensity of Light 1 and Light 2
pub const MAX_LIGHT_INTENSITY: f32 = 2.0;
/// Whether `p` sets any stylized setting
pub(crate) fn sets_any(p: &Value) -> bool {
KEYS.iter().any(|key| p.get(*key).is_some())
}
/// Set the stylized settings `p` names on `lighting`, clamped; a bad color or choice is refused
pub(crate) fn apply(p: &Value, lighting: &mut StylizedLighting, cmd: &str) -> Result<()> {
let set = |slot: &mut f32, key: &str, high: f32| {
if let Some(value) = f32p(p, key) {
*slot = value.clamp(0.0, high);
}
};
for (key, slot) in [
("sunColor", &mut lighting.sun_color),
("skyColor", &mut lighting.sky_color),
("horizonColor", &mut lighting.horizon_color),
("groundColor", &mut lighting.ground_color),
] {
set_color(p, key, slot, cmd)?;
}
for (key, light) in ["light1", "light2"].into_iter().zip(lighting.lights.iter_mut()) {
if let Some(params) = p.get(key) {
set_light(params, light, key, cmd)?;
}
}
set(&mut lighting.diffuse_cavity, "diffuseCavity", 1.0);
set(&mut lighting.specular_ao, "specularAo", 1.0);
set(&mut lighting.specular_cavity, "specularCavity", 1.0);
set(&mut lighting.cavity_smoothness, "cavitySmoothness", MAX_CAVITY_SMOOTHNESS);
set(&mut lighting.edges_intensity, "edgesIntensity", 1.0);
set(&mut lighting.edges_smoothness, "edgesSmoothness", 1.0);
set(&mut lighting.dielectric_reflectance, "dielectricReflectance", MAX_DIELECTRIC_REFLECTANCE);
set(&mut lighting.height_to_normal, "heightToNormal", MAX_HEIGHT_TO_NORMAL);
lighting.specular_glossiness = two_way(p, "input", "metalRoughness", "specularGlossiness", cmd)?.unwrap_or(lighting.specular_glossiness);
lighting.output = choice(p, "output", &LightingOutput::ALL, LightingOutput::id, cmd)?.unwrap_or(lighting.output);
lighting.mesh_only = two_way(p, "normalDetails", "meshHeightNormal", "mesh", cmd)?.unwrap_or(lighting.mesh_only);
Ok(())
}
/// Light 1 or Light 2 from `{azimuth, elevation, intensity, color}` (any of them)
fn set_light(p: &Value, light: &mut DirectionalLight, key: &str, cmd: &str) -> Result<()> {
if !p.is_object() {
return Err(bad(cmd, format!("`{key}` must be an object {{azimuth, elevation, intensity, color}}")));
}
if let Some(degrees) = f32p(p, "azimuth") {
light.azimuth = degrees.rem_euclid(FULL_TURN_DEGREES);
}
if let Some(degrees) = f32p(p, "elevation") {
light.elevation = degrees.rem_euclid(FULL_TURN_DEGREES);
}
if let Some(intensity) = f32p(p, "intensity") {
light.intensity = intensity.clamp(0.0, MAX_LIGHT_INTENSITY);
}
set_color(p, "color", &mut light.color, cmd)
}
@@ -0,0 +1,57 @@
//! `effect.set` on a Transform filter: repeatMode, flipMode, scaling, offset, tileSafeRotation and rotation
use serde_json::Value;
use texturecraft_core::{FlipMode, RepeatMode, TileTransform};
use crate::Result;
use crate::commands::{bad, boolp, f32p, strp};
use crate::layer_cmds::FULL_TURN_DEGREES;
/// Set the Transform settings given in `p`; a value of the wrong kind is refused and changes nothing
pub(crate) fn apply(p: &Value, transform: &mut TileTransform, cmd: &str) -> Result<()> {
let mut edited = *transform;
if p.get("repeatMode").is_some() {
let id = strp(p, "repeatMode").unwrap_or_default();
edited.repeat =
RepeatMode::ALL.into_iter().find(|mode| mode.id() == id).ok_or_else(|| bad(cmd, "`repeatMode` must be none or horizontallyAndVertically"))?;
}
if p.get("flipMode").is_some() {
let id = strp(p, "flipMode").unwrap_or_default();
edited.flip = FlipMode::ALL
.into_iter()
.find(|mode| mode.id() == id)
.ok_or_else(|| bad(cmd, "`flipMode` must be none, horizontally, vertically or horizontallyAndVertically"))?;
}
let (low, high) = TileTransform::SCALING;
if let Some(scaling) = pair(p, "scaling", cmd)? {
edited.scaling = scaling.map(|scale| scale.clamp(low, high));
}
if let Some(offset) = pair(p, "offset", cmd)? {
edited.offset = offset.map(|along| along.clamp(-TileTransform::MAX_OFFSET, TileTransform::MAX_OFFSET));
}
if p.get("tileSafeRotation").is_some() {
edited.tile_safe = boolp(p, "tileSafeRotation").ok_or_else(|| bad(cmd, "`tileSafeRotation` must be true or false"))?;
}
if p.get("rotation").is_some() {
let degrees = f32p(p, "rotation").ok_or_else(|| bad(cmd, "`rotation` must be a number of degrees"))?;
edited.rotation = degrees.rem_euclid(FULL_TURN_DEGREES);
}
*transform = edited;
Ok(())
}
/// `[x, y]` (or one number for both) under `key`, if given; anything else is refused
fn pair(p: &Value, key: &str, cmd: &str) -> Result<Option<[f32; 2]>> {
let Some(value) = p.get(key) else { return Ok(None) };
let number = |item: &Value| item.as_f64().map(|value| value as f32).filter(|value| value.is_finite());
let parsed = match value {
Value::Array(items) if items.len() == 2 => items.first().and_then(number).zip(items.get(1).and_then(number)).map(|(x, y)| [x, y]),
other => number(other).map(|both| [both, both]),
};
parsed.map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be [x, y] or one number")))
}
+19 -1
View File
@@ -2,7 +2,7 @@
use serde_json::{Value, json};
use texturecraft_core::project::ENVIRONMENTS;
use texturecraft_core::{BakedMap, Channel, EnvAlignment, ShadowMode, ToneMapping};
use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
@@ -301,6 +301,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
}
let scatter_color = color_param("display.set", p, "scatterColor")?;
let (environment_before, rotation_before) = (s.doc.project.display.environment.clone(), s.doc.project.display.env_rotation);
let settings = &mut s.doc.project.display;
if let Some(picked) = environment {
settings.environment = picked;
@@ -368,10 +369,27 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
if f32p(p, "fov").is_some() {
s.camera.fov = s.doc.project.display.fov;
}
// Baked Lighting Environment lights with the viewport environment: the layers it lights composite again when that turns or changes
let display = &s.doc.project.display;
if (display.environment.as_str(), display.env_rotation) != (environment_before.as_str(), rotation_before) && lit_by_environment(&s.doc.project) {
for cache in &mut s.caches {
cache.invalidate_all();
}
}
s.revision = s.revision.wrapping_add(1);
Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null))
}
/// Whether a layer's content has a Baked Lighting Environment
fn lit_by_environment(project: &Project) -> bool {
project
.layers
.values()
.flat_map(|layer| layer.content_effects.iter())
.any(|effect| matches!(effect.kind, EffectKind::Filter(Filter::EnvironmentLighting { .. })))
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
View File
@@ -33,7 +33,7 @@ fn id(reply: Value, key: &str) -> u64 {
fn content_effects_commands_inspect_and_round_trip() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer");
let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "hue": 1.0 / 3.0})).unwrap(), "effect");
let hsl = id(execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "hsl", "mode": "regular", "hue": 1.0 / 3.0})).unwrap(), "effect");
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
assert!(s.doc.project.layer(LayerId(layer)).unwrap().mask.is_none(), "content effects don't create a mask");
+155
View File
@@ -0,0 +1,155 @@
//! The Filter effect card: an empty filter, its content channels switched on and off, Intensity's divider, Restore defaults and the Attributes it lists
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, Filter, LayerId, SourceSlopeBlur, SourceWarp};
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, center, facing_session as session, filter_of, set};
fn assert_close(actual: [f32; 3], expected: [f32; 3], what: &str) {
assert!((0..3).all(|i| (actual[i] - expected[i]).abs() < 4e-3), "{what}: {actual:?}, expected {expected:?}");
}
/// A fill layer of base color 0.2 and roughness 0.3 under content filter `params`: (layer, effect)
fn filtered_layer(s: &mut Session, params: Value) -> (u64, LayerId) {
let layer = execute(s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.3})).unwrap()["layer"].as_u64().unwrap();
(layer, add_filter(s, params))
}
/// An empty filter changes nothing and is named for it; picking a filter names it after the filter, × empties it again
#[test]
fn an_empty_filter_renders_nothing_until_one_is_picked() {
let mut s = session();
let (_, effect) = filtered_layer(&mut s, json!({"filter": "none"}));
assert_eq!(filter_of(&s, effect), Filter::Empty);
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Filter (empty)");
assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "an empty filter leaves the color");
set(&mut s, effect, json!({"filter": "invert"}));
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Invert");
assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the picked filter works");
set(&mut s, effect, json!({"filter": "none"}));
assert_eq!(filter_of(&s, effect), Filter::Empty);
assert_close(center(&mut s, Channel::BaseColor), [0.2; 3], "emptied again");
}
/// A content filter switched off for a channel leaves that channel; inspect lists it; masks refuse `channels`
#[test]
fn a_content_filter_leaves_the_channels_switched_off() {
let mut s = session();
let (layer, effect) = filtered_layer(&mut s, json!({"filter": "invert"}));
assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "every channel at first");
set(&mut s, effect, json!({"channels": {"roughness": false}}));
assert_close(center(&mut s, Channel::Roughness), [0.3; 3], "roughness switched off");
assert_close(center(&mut s, Channel::BaseColor), [0.8; 3], "the color still inverted");
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone();
let filter_row = row["contentEffects"].as_array().unwrap().iter().find(|filter_row| filter_row["id"] == effect.0).unwrap();
assert_eq!(filter_row["offChannels"], json!(["roughness"]));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_close(center(&mut s, Channel::Roughness), [0.7; 3], "one undo step");
set(&mut s, effect, json!({"channels": {"roughness": false}}));
set(&mut s, effect, json!({"channels": {"roughness": true}}));
assert!(s.doc.project.effect(effect).unwrap().1.off_channels.is_empty());
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"nope": false}})).is_err());
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channels": {"roughness": 1}})).is_err());
let masked = execute(&mut s, "effect.add.filter", &json!({"filter": "invert", "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channels": {"roughness": false}})).is_err());
}
/// Intensity ÷ Divider: warp 0.5 ÷ 10 renders as warp 0.05; only 1, 10, 100 and 1000 are taken; a divider of 1 is not saved
#[test]
fn the_divider_divides_the_intensity() {
let warp = |intensity: f32, divider: u16| {
let mut s = session();
execute(&mut s, "layer.add.fill", &Value::Null).unwrap();
execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "checker", "scale": 8.0})).unwrap();
let params = json!({"filter": "warp", "target": "content", "intensity": intensity, "seed": 5});
let effect = execute(&mut s, "effect.add.filter", &params).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "effect.set", &json!({"effect": effect, "divider": divider})).unwrap();
s.update();
(0..SIZE).step_by(7).map(|x| s.caches[0].composite.value(Channel::BaseColor, x, SIZE / 2)[0]).collect::<Vec<f32>>()
};
let divided = warp(0.5, 10);
assert_eq!(divided, warp(0.05, 1), "0.5 ÷ 10 = 0.05");
assert_ne!(divided, warp(0.5, 1), "the divider changes the warp");
let mut s = session();
let (_, effect) = filtered_layer(&mut s, json!({"filter": "blurSlope"}));
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "divider": 7})).is_err());
set(&mut s, effect, json!({"divider": 100}));
assert!(matches!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur { divider: 100, .. })));
let saved = serde_json::to_value(Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 }).unwrap();
assert_eq!(saved, json!({"Warp": {"intensity": 1.0, "scale": 2.0, "seed": 3}}), "saved as before dividers");
let loaded: Filter = serde_json::from_value(saved).unwrap();
assert_eq!(loaded, Filter::Warp { intensity: 1.0, scale: 2.0, seed: 3, divider: 1 });
}
/// Restore defaults puts the parameters back in one undo step, keeping the name and switched-off channels; none at defaults
#[test]
fn restore_defaults_puts_the_filters_parameters_back() {
let mut s = session();
let (_, effect) = filtered_layer(&mut s, json!({"filter": "warp", "name": "Wobble"}));
let defaults = filter_of(&s, effect);
let steps = s.history_labels().len();
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": false}));
assert_eq!(s.history_labels().len(), steps, "no step at defaults");
set(&mut s, effect, json!({"intensity": 0.5, "seed": 9, "divider": 100, "channels": {"height": false}}));
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap(), json!({"changed": true}));
assert_eq!(filter_of(&s, effect), defaults);
let restored = s.doc.project.effect(effect).unwrap().1.clone();
assert_eq!(restored.name, "Wobble");
assert!(restored.off_channels.contains(&Channel::Height));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(matches!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp { divider: 100, seed: 9, .. })), "one undo step");
let empty = filtered_layer(&mut s, json!({"filter": "none"})).1;
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": empty.0})).unwrap(), json!({"changed": false}));
let fill = execute(&mut s, "effect.add.fill", &json!({"target": "content"})).unwrap()["effect"].as_u64().unwrap();
assert!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": fill})).is_err());
}
#[test]
fn filter_list_describes_and_tags_every_filter() {
let mut s = session();
let listed = execute(&mut s, "filter.list", &Value::Null).unwrap();
for def in listed.as_array().unwrap() {
assert!(def["description"].as_str().is_some_and(|text| !text.is_empty()), "{def}");
assert!(def["tags"].as_array().is_some_and(|tags| !tags.is_empty()), "{def}");
}
let blur = listed.as_array().unwrap().iter().find(|def| def["id"] == "blur").unwrap();
assert_eq!(blur["tags"], json!(["blur", "soften"]));
}
+113
View File
@@ -0,0 +1,113 @@
//! The colour filters (Color Balance, Color Correct, HSL Perceptive, Contrast Luminosity) and the shared edge wrap of Blur and Bevel
use serde_json::{Value, json};
use texturecraft_engine::core::{Bevel, Channel, Filter};
use texturecraft_engine::execute;
use crate::filter_support::{center, facing_session as session, filter_of, filtered, set};
fn distance(a: [f32; 3], b: [f32; 3]) -> f32 {
(0..3).map(|i| (a[i] - b[i]).abs()).fold(0.0, f32::max)
}
/// Color Correct: neutral by default, then each tone's contrast, luminosity and saturation; one undo step per edit
#[test]
fn color_correct_changes_nothing_until_its_tones_move() {
let mut s = session();
let color = [0.6, 0.3, 0.2];
let effect = filtered(&mut s, color, json!({"filter": "colorCorrect"}));
let neutral = filter_of(&s, effect);
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Color Correct");
assert!(distance(center(&mut s, Channel::BaseColor), color) < 4e-3, "the defaults change nothing");
set(&mut s, effect, json!({"shadows": [0.0, 0.0, 0.0], "midtones": [0.0, 0.0, 0.0], "highlights": [0.0, 0.0, 0.0]}));
let gray = center(&mut s, Channel::BaseColor);
assert!((gray[0] - gray[1]).abs() < 4e-3 && (gray[1] - gray[2]).abs() < 4e-3, "saturation 0 everywhere is gray: {gray:?}");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(filter_of(&s, effect), neutral, "one undo step takes back all three tones");
set(&mut s, effect, json!({"midtones": [0.0, 0.3, 0.5], "shadows": [0.0, 0.3, 0.5], "highlights": [0.0, 0.3, 0.5]}));
let lighter = center(&mut s, Channel::BaseColor);
assert!((0..3).all(|i| lighter[i] > color[i] + 0.1), "luminosity lifts every tone: {lighter:?}");
let roughness = center(&mut s, Channel::Roughness);
assert!(roughness[0] > 0.4, "scalars take contrast and luminosity: {roughness:?}");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "midtones": "x"})).is_err());
let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!(midtones, [0.0, 0.3, 0.5], "a refused edit changes nothing");
set(&mut s, effect, json!({"midtones": [5.0, -5.0, 5.0]}));
let Filter::ColorCorrect { midtones, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!(midtones, [1.0, -1.0, 1.0], "clamped to the ranges");
}
/// HSL Perceptive: a new filter is Perceptive, projects saved before stay Regular; a perceptive hue turn keeps lightness better
#[test]
fn hsl_perceptive_turns_the_hue_at_the_same_lightness() {
let mut s = session();
let yellow = [0.8, 0.7, 0.05];
let effect = filtered(&mut s, yellow, json!({"filter": "hsl", "hue": 0.5}));
assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: true, .. }), "new filters are perceptive");
let perceptive = center(&mut s, Channel::BaseColor);
set(&mut s, effect, json!({"mode": "regular"}));
assert!(matches!(filter_of(&s, effect), Filter::Hsl { perceptive: false, .. }));
let regular = center(&mut s, Channel::BaseColor);
// Rec. 709 luminance weights
let relative_luminance = |c: [f32; 3]| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
let drift = |color: [f32; 3]| (relative_luminance(color) - relative_luminance(yellow)).abs();
assert!(drift(perceptive) < drift(regular), "perceptive {perceptive:?} regular {regular:?}");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "vivid"})).is_err());
// Saved before the mode: Regular, and saved again without the field
let old: Filter = serde_json::from_value(json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}})).unwrap();
assert_eq!(old, Filter::Hsl { hue: 0.5, saturation: 0.0, lightness: 0.0, perceptive: false });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Hsl": {"hue": 0.5, "saturation": 0.0, "lightness": 0.0}}));
}
/// Contrast Luminosity starts neutral (contrast 0) like the other colour filters
#[test]
fn contrast_luminosity_starts_neutral() {
let mut s = session();
let effect = filtered(&mut s, [0.2; 3], json!({"filter": "contrastLuminosity"}));
assert_eq!(filter_of(&s, effect), Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.0 });
assert!(distance(center(&mut s, Channel::BaseColor), [0.2; 3]) < 4e-3);
}
/// Blur and Bevel take the shared edge wrap: effect.set {wrap}, saved only when on, old projects load with it off
#[test]
fn blur_and_bevel_take_the_edge_wrap() {
let mut s = session();
let blur = filtered(&mut s, [0.2; 3], json!({"filter": "blur"}));
assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: false, .. }));
set(&mut s, blur, json!({"wrap": true}));
assert!(matches!(filter_of(&s, blur), Filter::Blur { wrap: true, .. }));
assert!(execute(&mut s, "effect.set", &json!({"effect": blur.0, "wrap": "yes"})).is_err());
let bevel = filtered(&mut s, [0.2; 3], json!({"filter": "bevel", "wrap": true}));
assert!(matches!(filter_of(&s, bevel), Filter::DistanceBevel(Bevel { wrap: true, .. })));
let old: Filter = serde_json::from_value(json!({"Blur": {"radius": 4.0}})).unwrap();
assert_eq!(old, Filter::Blur { radius: 4.0, wrap: false });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Blur": {"radius": 4.0}}), "off is not saved");
}
+176
View File
@@ -0,0 +1,176 @@
//! The gradient filters: Gradient (positions, quantity, input transformation, linear blending, debug), Gradient Curve and Gradient Dynamic
use serde_json::json;
use texturecraft_engine::core::{Channel, EffectKind, Filter, GrayscaleMode, layer::gradient};
use texturecraft_engine::execute;
use texturecraft_engine::filter_lib::{LIBRARY_GRADIENT_CURVE, LIBRARY_GRADIENT_DYNAMIC, MID_GRAY};
use crate::filter_support::{add_filter, center, center_uv, facing_session as session, filter_of, filtered, refused, set};
fn near(a: f32, b: f32) -> bool {
(a - b).abs() < 6e-3
}
/// Projects saved before read a gradient as evenly spaced colors from the texel's luma, blended in linear, and save it as before
#[test]
fn a_gradient_saved_before_reads_and_saves_as_before() {
let saved = json!({"GradientMap": {"colors": [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]}});
let filter: Filter = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(filter, Filter::even_gradient(vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]));
assert_eq!(serde_json::to_value(&filter).unwrap(), saved, "nothing new is saved");
let Filter::GradientMap { colors, input, .. } = &filter else { panic!() };
assert_eq!(input.mode, GrayscaleMode::Luma);
for t in [0.0, 0.2, 0.37, 0.5, 0.81, 1.0] {
assert_eq!(filter.ramp_at(t), gradient(colors, t), "bit for bit as before at {t}");
}
}
/// The library's Gradient: black, mid gray and white at 0, 0.5 and 1; places, quantity, invert, balance and linear blending move what a texel reads
#[test]
fn gradient_places_quantity_and_input_transformation() {
let mut s = session();
let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientMap"}));
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient");
let Filter::GradientMap { quantity, input, linear, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!((quantity, input.mode, linear), (Some(3), GrayscaleMode::Average, true));
assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY / 2.0), "halfway from black to mid gray");
set(&mut s, effect, json!({"positions": [0.0, 0.25, 1.0]}));
assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY), "mid gray moved to 0.25");
set(&mut s, effect, json!({"invert": true}));
assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.5 / 0.75)), "inverted, it reads 0.75");
set(&mut s, effect, json!({"invert": false, "balance": 0.75}));
assert!(near(center(&mut s, Channel::BaseColor)[0], MID_GRAY + (1.0 - MID_GRAY) * (0.25 / 0.75)), "balance 0.75 lifts it to 0.5");
set(&mut s, effect, json!({"balance": 0.5, "positions": [0.0, 0.5, 1.0], "linear": false}));
let srgb = center(&mut s, Channel::BaseColor)[0];
assert!(near(srgb, 0.0508), "blended in sRGB, halfway from black to mid gray is sRGB 0.25: {srgb}");
set(&mut s, effect, json!({"quantity": 4}));
assert_eq!(filter_of(&s, effect).ramp_colors().len(), 4);
refused(
&mut s,
effect,
&[
json!({"quantity": 11}),
json!({"quantity": 1}),
json!({"grayscaleMode": "x"}),
json!({"positions": [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]}),
json!({"debug": 3}),
],
);
set(&mut s, effect, json!({"grayscaleMode": "max"}));
let Filter::GradientMap { input, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!(input.mode, GrayscaleMode::Max);
}
/// A new gradient given its colors alone ramps evenly through every one of them
#[test]
fn a_gradient_given_colors_alone_ramps_evenly_through_all_of_them() {
let mut s = session();
let two = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]}));
let mid = center(&mut s, Channel::BaseColor)[0];
assert!(near(mid, 0.5), "black to white reads mid gray halfway: {mid}");
execute(&mut s, "effect.remove", &json!({"effect": two.0})).unwrap();
let five = add_filter(&mut s, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [0.25, 0.25, 0.25], [0.5, 0.5, 0.5], [0.75, 0.75, 0.75], [1, 1, 1]]}));
assert_eq!(filter_of(&s, five).ramp_colors().len(), 5, "every color is used");
}
/// Display Gradient (Debug) shows the ramp left to right across the texture
#[test]
fn display_gradient_shows_the_ramp_across_the_texture() {
let mut s = session();
let effect = filtered(&mut s, [0.9; 3], json!({"filter": "gradientMap", "debug": true}));
let (value, uv) = (center(&mut s, Channel::BaseColor), center_uv(&mut s));
let ramp = filter_of(&s, effect).ramp_at(uv.x).unwrap();
assert!((0..3).all(|k| (value[k] - ramp[k]).abs() < 0.03), "{value:?} vs {ramp:?} at u {}", uv.x);
}
/// An old gradient that gains a quantity keeps its colors' places and adds the new one at 1
#[test]
fn a_saved_gradient_keeps_its_places_when_it_gains_a_color() {
let mut s = session();
let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap"}));
if let Some(found) = s.doc.project.effect_mut(effect) {
found.kind = EffectKind::Filter(Filter::even_gradient(vec![[0.0; 3], [1.0, 0.0, 0.0], [1.0; 3]]));
}
set(&mut s, effect, json!({"quantity": 4}));
let Filter::GradientMap { colors, positions, quantity, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!((positions, quantity), (vec![0.0, 0.5, 1.0, 1.0], Some(4)));
assert_eq!(colors.last(), Some(&[1.0; 3]), "the new color starts as the last one");
}
/// A color added at 1 starts as the ramp's color there: its rightmost stop's, not the last one listed
#[test]
fn an_added_color_keeps_the_ramps_end() {
let mut s = session();
let effect = filtered(&mut s, [0.5; 3], json!({"filter": "gradientMap", "colors": [[1, 1, 1], [0, 0, 0]]}));
set(&mut s, effect, json!({"positions": [0.8, 0.2]}));
let before = filter_of(&s, effect).ramp_at(0.9);
set(&mut s, effect, json!({"quantity": 3}));
assert_eq!(before, Some([1.0; 3]), "white past its stop at 0.8");
assert_eq!(filter_of(&s, effect).ramp_at(0.9), before, "the added color at 1 keeps the end white");
}
/// Gradient Curve: values remapped through the preset after balance, contrast and invert
#[test]
fn gradient_curve_remaps_through_its_preset() {
let mut s = session();
let effect = filtered(&mut s, [0.25; 3], json!({"filter": "gradientCurve"}));
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Curve");
assert_eq!(filter_of(&s, effect), LIBRARY_GRADIENT_CURVE, "the workflow's defaults");
let round = (1.0f32 - 0.75 * 0.75).sqrt();
assert!(near(center(&mut s, Channel::BaseColor)[0], round), "Round at 0.25");
set(&mut s, effect, json!({"preset": "easeIn"}));
assert!(near(center(&mut s, Channel::BaseColor)[0], 0.0625), "Ease In at 0.25");
set(&mut s, effect, json!({"invert": true}));
assert!(near(center(&mut s, Channel::BaseColor)[0], 0.5625), "Ease In at 0.75");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "preset": "spiral"})).is_err());
let Filter::GradientCurve { preset, .. } = filter_of(&s, effect) else { panic!() };
assert_eq!(preset.id(), "easeIn", "a refused preset changes nothing");
}
/// Gradient Dynamic with a uniform Gradient Source: every texel reads that color (scalars its gray)
#[test]
fn gradient_dynamic_reads_its_uniform_source() {
let mut s = session();
let effect = filtered(&mut s, [0.9, 0.1, 0.1], json!({"filter": "gradientDynamic", "color": [0.2, 0.4, 0.6]}));
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Gradient Dynamic");
let Filter::GradientDynamic { vertical, position, .. } = LIBRARY_GRADIENT_DYNAMIC else { panic!() };
assert_eq!(filter_of(&s, effect), Filter::GradientDynamic { vertical, position, color: [0.2, 0.4, 0.6] }, "the workflow's defaults, the color given");
let color = center(&mut s, Channel::BaseColor);
assert!(near(color[0], 0.2) && near(color[1], 0.4) && near(color[2], 0.6), "{color:?}");
set(&mut s, effect, json!({"orientation": "vertical", "position": 0.7}));
let Filter::GradientDynamic { vertical, position, .. } = filter_of(&s, effect) else { panic!() };
assert!(vertical && position == 0.7);
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "orientation": "diagonal"})).is_err());
}
+160
View File
@@ -0,0 +1,160 @@
//! Filter image inputs: Bevel Smooth's and Directional Distance's Distance Map and Warp's Custom Noise read a source set on the effect
use serde_json::{Value, json};
use texturecraft_engine::core::{Effect, LayerId, Source};
use texturecraft_engine::{Session, execute};
use crate::filter_shape::shape_edge;
use crate::filter_support::{SIZE, add_filter, roughness, session, set};
/// `layer.fill.set` on image input `params` of `effect`: its result, the error as text
fn input(s: &mut Session, effect: LayerId, params: Value) -> Result<Value, String> {
let mut params = params;
params["effect"] = json!(effect.0);
execute(s, "layer.fill.set", &params).map_err(|error| error.to_string())
}
/// The image inputs `effect` holds, by input id
fn inputs(s: &Session, effect: LayerId) -> Vec<(String, Source)> {
let (_, found) = s.doc.project.effect(effect).unwrap();
found.inputs.iter().map(|(id, source)| (id.clone(), source.clone())).collect()
}
#[test]
fn a_library_alpha_input_uses_its_own_image_when_the_project_already_has_its_name() {
let mut session = session();
let effect = add_filter(&mut session, json!({"filter": "bevelSmooth"}));
let alpha_id = "round_soft";
let alpha = texturecraft_engine::paint::alphas::find(alpha_id).unwrap();
let reserved_name = texturecraft_engine::fill_alpha::resource_name(alpha);
let imported_pixels = texturecraft_engine::formats::mcmat::mesh_map_png(2, 1, &[0.25; 4]).unwrap();
session.doc.resources.insert(reserved_name.clone(), imported_pixels.clone().into());
session.sync_images();
let settings = json!({"input": "distanceMap", "alpha": alpha_id});
input(&mut session, effect, settings.clone()).unwrap();
let [(input_name, Source::Image { name, .. })] = &inputs(&session, effect)[..] else { panic!("expected one image input") };
assert_eq!(input_name, "distanceMap");
assert_ne!(name, &reserved_name);
assert_eq!(session.library_alpha(name).unwrap().id, alpha_id);
assert_eq!(session.doc.resources[&reserved_name].as_slice(), imported_pixels);
let history_length = session.history_labels().len();
input(&mut session, effect, settings).unwrap();
assert_eq!(session.history_labels().len(), history_length);
}
/// Bevel Smooth's Distance Map scales its distance texel by texel: a gray, an anchor's gray, back to white; its default is not stored; one undo step
#[test]
fn a_distance_map_scales_the_bevel_smooth_distance() {
let mut s = session();
// A layer below records a roughness of 0.5 at an anchor point
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.5})).unwrap();
let anchor = LayerId(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap());
let (at, _, _) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"}));
set(&mut s, effect, json!({"smoothing": 0.0}));
let full = roughness(&mut s, at(4));
assert!(full > 0.0 && full < 1.0, "on the ramp: {full}");
input(&mut s, effect, json!({"input": "distanceMap", "value": 0.5})).unwrap();
let half = roughness(&mut s, at(4));
assert!(half < full - 0.05, "half the distance fades sooner: {half} vs {full}");
assert_eq!(inputs(&s, effect), vec![("distanceMap".to_string(), Source::Uniform([0.5; 3]))]);
let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspected.contains("\"inputs\":{\"distanceMap\""), "inspect shows the input");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(inputs(&s, effect).is_empty(), "one undo step");
assert_eq!(roughness(&mut s, at(4)), full);
input(&mut s, effect, json!({"input": "distanceMap", "anchor": anchor.0, "anchorChannel": "roughness"})).unwrap();
assert!((roughness(&mut s, at(4)) - half).abs() < 1e-3, "the anchor's 0.5 reads as the uniform 0.5");
input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap();
assert!(inputs(&s, effect).is_empty() && roughness(&mut s, at(4)) == full, "cleared: white, as before");
let steps = s.history_labels().len();
input(&mut s, effect, json!({"input": "distanceMap", "value": 1.0})).unwrap();
input(&mut s, effect, json!({"input": "distanceMap", "clear": true})).unwrap();
assert!(inputs(&s, effect).is_empty(), "the default gray is not stored");
assert_eq!(s.history_labels().len(), steps, "setting what the input already reads adds no undo step");
for bad in [json!({"input": "nope", "value": 0.5}), json!({"input": "distanceMap", "channel": "roughness", "value": 0.5}), json!({"input": "distanceMap"})]
{
assert!(input(&mut s, effect, bad.clone()).is_err(), "{bad}");
}
assert!(input(&mut s, anchor, json!({"input": "distanceMap", "value": 0.5})).is_err(), "not a filter");
}
#[test]
fn a_malformed_filter_input_cannot_edit_the_selected_fill() {
let mut session = session();
execute(&mut session, "layer.add.fill", &json!({"roughness": 0.25})).unwrap();
let history = session.history_labels().len();
let result = execute(&mut session, "layer.fill.set", &json!({"input": false, "channel": "roughness", "value": 0.9}));
assert!(result.is_err());
assert_eq!(session.history_labels().len(), history);
}
/// Directional Distance: a black Distance Map leaves no trail
#[test]
fn a_black_distance_map_leaves_no_trail() {
let mut s = session();
let (at, _, outward) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "directionalDistance"}));
set(&mut s, effect, json!({"angle": if outward > 0 { 0.0 } else { 180.0 }, "distance": 0.05}));
assert!(roughness(&mut s, at(1)) > 0.0, "a trail");
input(&mut s, effect, json!({"input": "distanceMap", "value": 0.0})).unwrap();
assert_eq!((roughness(&mut s, at(1)), roughness(&mut s, at(-2))), (0.0, 1.0), "no trail, the shapes stay");
}
/// Warp's Custom Noise moves texels by its source; projects saved before image inputs load with none and save without them
#[test]
fn a_custom_noise_moves_the_warp() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap();
let row = SIZE / 2;
let before: Vec<f32> = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect();
let moved = |s: &mut Session| (0..SIZE).map(|x| (roughness(s, (x, row)) - before[x as usize]).abs()).fold(0.0f32, f32::max);
let effect = add_filter(&mut s, json!({"filter": "warp"}));
set(&mut s, effect, json!({"intensity": 0.05, "divider": 1, "warpMode": "directional", "sourceMode": "customNoise"}));
assert!(moved(&mut s) < 2e-3, "its default mid gray moves nothing");
input(&mut s, effect, json!({"input": "customNoise", "procedural": "gradient"})).unwrap();
assert!(moved(&mut s) > 0.01, "a source moves texels: {}", moved(&mut s));
set(&mut s, effect, json!({"sourceMode": "defaultNoise"}));
assert_eq!(inputs(&s, effect).len(), 1, "kept while another source mode is on");
let (_, found) = s.doc.project.effect(effect).unwrap();
let saved = serde_json::to_value(Effect { inputs: Default::default(), ..found.clone() }).unwrap();
assert!(saved.get("inputs").is_none(), "no inputs, no key: saves as before");
let loaded: Effect = serde_json::from_value(saved).unwrap();
assert!(loaded.inputs.is_empty(), "an effect saved before loads with none");
}
+246
View File
@@ -0,0 +1,246 @@
//! The light filters: Glow, Drop Shadow, Baked Lighting Stylized and Baked Lighting Environment
use serde_json::json;
use texturecraft_engine::core::{Channel, DirectionalLight, EffectKind, Filter, LayerId, LightingOutput};
use texturecraft_engine::filter_lib::{LIBRARY_DROP_SHADOW, LIBRARY_ENVIRONMENT_LIGHTING, LIBRARY_GLOW, library_baked_lighting};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, filter_of, refused, set};
/// A plane, so every texel faces the same way
fn session() -> Session {
Session::new_project("t", primitives::plane(2.0, 2), "builtin:plane", None, SIZE).unwrap()
}
/// A fill layer with library filter `id` in its mask: the effect
fn masked(s: &mut Session, id: &str) -> LayerId {
execute(s, "layer.add.fill", &json!({})).unwrap();
execute(s, "mask.add.black", &json!({})).unwrap();
LayerId(execute(s, "effect.add.filter", &json!({"filter": id, "target": "mask"})).unwrap()["effect"].as_u64().unwrap())
}
/// Projects saved before keep their additive glow, read and saved as they were; a new Glow is the halo, named the same
#[test]
fn a_glow_saved_before_stays_additive_and_a_new_glow_is_the_halo() {
let saved = json!({"Glow": {"radius": 16.0, "amount": 1.0}});
let filter: Filter = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(filter, Filter::Glow { radius: 16.0, amount: 1.0 });
assert_eq!(serde_json::to_value(&filter).unwrap(), saved);
let mut s = session();
let effect = masked(&mut s, "glow");
assert_eq!(filter_of(&s, effect), LIBRARY_GLOW, "the workflow's defaults");
assert_eq!(filter_of(&s, effect).label(), "Glow");
assert_eq!(filter.label(), "Glow");
}
/// Glow's Used on a Mask, Mode, Width (inner glow below 0), Spread, Opacity and Color set and clamp; bad values are refused
#[test]
fn glow_settings_set_clamp_and_refuse() {
let mut s = session();
let effect = masked(&mut s, "glow");
set(&mut s, effect, json!({"usedOnMask": true, "mode": "precise", "width": -3.0, "spread": 0.4, "opacity": 0.6, "color": [0.2, 0.4, 0.6]}));
let glow = Filter::HaloGlow { on_mask: true, precise: true, width: -1.0, spread: 0.4, opacity: 0.6, color: [0.2, 0.4, 0.6] };
assert_eq!(filter_of(&s, effect), glow);
refused(&mut s, effect, &[json!({"mode": "hard"}), json!({"usedOnMask": 1}), json!({"color": "red"})]);
assert_eq!(filter_of(&s, effect), glow);
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true));
assert_eq!(filter_of(&s, effect), LIBRARY_GLOW);
}
/// Drop Shadow: the workflow's defaults, then Angle wrapping, Distance both ways, Size, Spread, Opacity and Color
#[test]
fn drop_shadow_defaults_and_settings() {
let mut s = session();
let effect = masked(&mut s, "Drop Shadow");
assert_eq!(filter_of(&s, effect), LIBRARY_DROP_SHADOW, "the workflow's defaults");
set(&mut s, effect, json!({"angle": 450.0, "distance": -0.9, "size": 2.0, "spread": 0.3, "opacity": 0.25, "color": "#ffffff"}));
assert_eq!(filter_of(&s, effect), Filter::DropShadow { angle: 90.0, distance: -0.5, size: 1.0, spread: 0.3, opacity: 0.25, color: [1.0; 3] });
refused(&mut s, effect, &[json!({"color": [1.0]})]);
let listed = execute(&mut s, "filter.list", &json!({})).unwrap();
assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "dropShadow" && f["mask"] == true));
}
/// A content fill layer with library filter `id` on its content: the effect
fn on_content(s: &mut Session, id: &str) -> LayerId {
execute(s, "layer.add.fill", &json!({})).unwrap();
add_filter(s, json!({"filter": id}))
}
/// Projects saved before keep their Baked Lighting, read and saved as they were and named Baked Lighting Stylized; a new one takes the workflow's defaults
#[test]
fn a_baked_lighting_saved_before_stays_and_a_new_one_is_stylized() {
let saved = json!({"BakedLighting": {"azimuth": 45.0, "elevation": 45.0, "light": 0.75, "ambient": 0.5, "occlusion": 1.0}});
let filter: Filter = serde_json::from_value(saved.clone()).unwrap();
assert!(filter.stylized_lighting().is_none(), "lights as before");
assert_eq!(serde_json::to_value(&filter).unwrap(), saved);
assert_eq!(filter.label(), "Baked Lighting Stylized");
assert_eq!(filter.former_label(), Some("Baked Lighting"));
let mut s = session();
let effect = on_content(&mut s, "Baked Lighting");
let made = filter_of(&s, effect);
assert_eq!(made, library_baked_lighting(), "the workflow's sun, sky and lights");
let (stylized, _) = made.stylized_lighting().unwrap();
assert_eq!(
(stylized.output, stylized.mesh_only, stylized.dielectric_reflectance, stylized.cavity_smoothness),
(LightingOutput::DiffuseSpecular, false, 0.04, 0.25)
);
assert_eq!((stylized.lights[0].azimuth, stylized.lights[1].azimuth, stylized.lights[0].intensity), (90.0, 180.0, 0.0));
let listed = execute(&mut s, "filter.list", &json!({})).unwrap();
assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLighting" && f["mask"] == false && f["label"] == "Baked Lighting Stylized"));
}
/// The stylized settings set and clamp; one set on a Baked Lighting saved before gives it the rest lit as it was; bad choices are refused
#[test]
fn stylized_lighting_settings_set_clamp_and_refuse() {
let mut s = session();
let effect = on_content(&mut s, "bakedLighting");
let old = Filter::BakedLighting { azimuth: 45.0, elevation: 45.0, light: 0.8, ambient: 0.4, occlusion: 1.0, stylized: None };
s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old);
set(
&mut s,
effect,
json!({
"skyColor": [0.1, 0.2, 0.3], "light1": {"azimuth": 450.0, "elevation": -30.0, "intensity": 5.0, "color": "#ff0000"},
"diffuseCavity": 0.5, "cavitySmoothness": 9.0, "dielectricReflectance": 1.0, "heightToNormal": 2.0,
"input": "specularGlossiness", "output": "specular", "normalDetails": "meshHeightNormal"
}),
);
let filter = filter_of(&s, effect);
let (stylized, light) = filter.stylized_lighting().unwrap();
assert_eq!((light.sun.intensity, light.sky_intensity, stylized.sun_color), (0.8, 0.4, [1.0; 3]), "the rest as it lit");
assert_eq!(stylized.sky_color, [0.1, 0.2, 0.3]);
assert_eq!(stylized.lights[0], DirectionalLight { azimuth: 90.0, elevation: 330.0, intensity: 2.0, color: [1.0, 0.0, 0.0] });
assert_eq!((stylized.diffuse_cavity, stylized.cavity_smoothness, stylized.dielectric_reflectance, stylized.height_to_normal), (0.5, 4.0, 0.16, 2.0));
assert!(stylized.specular_glossiness && !stylized.mesh_only && stylized.output == LightingOutput::Specular);
refused(
&mut s,
effect,
&[json!({"output": "both"}), json!({"input": 1}), json!({"normalDetails": "height"}), json!({"light2": 3}), json!({"groundColor": "dirt"})],
);
assert_eq!(filter_of(&s, effect), filter, "refusals change nothing");
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true));
assert_eq!(filter_of(&s, effect).stylized_lighting().unwrap().0.output, LightingOutput::DiffuseSpecular);
}
/// Baked Lighting Environment: the workflow's defaults, only the Color pill lit, rotations wrapping and the rest clamped, Restore defaults
#[test]
fn environment_lighting_defaults_and_settings() {
let mut s = session();
let effect = on_content(&mut s, "bakedLightingEnvironment");
let made = filter_of(&s, effect);
assert_eq!(made, LIBRARY_ENVIRONMENT_LIGHTING, "the workflow's defaults");
assert_eq!((made.label(), s.doc.project.effect(effect).unwrap().1.name.as_str()), ("Baked Lighting Environment", "Baked Lighting Environment"));
let off = &s.doc.project.effect(effect).unwrap().1.off_channels;
assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness) && off.contains(&Channel::Height), "only the Color pill is lit: {off:?}");
let stylized = on_content(&mut s, "bakedLighting");
assert!(s.doc.project.effect(stylized).unwrap().1.off_channels.contains(&Channel::Metallic), "Baked Lighting Stylized lights the Color pill only too");
let blur = on_content(&mut s, "blur");
assert!(s.doc.project.effect(blur).unwrap().1.off_channels.is_empty(), "other filters work on every channel");
set(
&mut s,
effect,
json!({"horizontalRotation": 370.0, "verticalRotation": -90.0, "exposure": 9.0, "heightIntensity": -1.0, "ambientOcclusion": 0.5, "specularOcclusion": 2.0}),
);
assert_eq!(
filter_of(&s, effect),
Filter::EnvironmentLighting {
horizontal: 10.0,
vertical: 270.0,
exposure: 5.0,
height_intensity: 0.0,
ambient_occlusion: 0.5,
specular_occlusion: 1.0
}
);
assert_eq!(execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap()["changed"], json!(true));
assert_eq!(filter_of(&s, effect), made);
let listed = execute(&mut s, "filter.list", &json!({})).unwrap();
assert!(listed.as_array().unwrap().iter().any(|f| f["id"] == "bakedLightingEnvironment" && f["mask"] == false));
}
/// Baked Lighting Environment lights the base color with the viewport environment: another environment relights it, Exposure brightens it
#[test]
fn environment_lighting_follows_the_viewport_environment() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap();
let center = |s: &mut Session| {
s.update();
s.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2)
};
let unlit = center(&mut s);
let effect = add_filter(&mut s, json!({"filter": "bakedLightingEnvironment"}));
let studio = center(&mut s);
assert_ne!(studio, unlit, "the studio lights the base color");
execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap();
let night = center(&mut s);
assert!(night[0] < studio[0] * 0.5, "the night lights it less: {night:?} vs {studio:?}");
set(&mut s, effect, json!({"exposure": 3.0}));
assert!(center(&mut s)[0] > night[0], "exposure brightens it");
}
#[test]
fn reimporting_the_selected_environment_relights_the_composite() {
let mut session = session();
let image_bytes = |rgb: [u8; 3]| {
let image = image::RgbImage::from_pixel(8, 4, image::Rgb(rgb));
let mut bytes = std::io::Cursor::new(Vec::new());
image.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
bytes.into_inner()
};
let sample = |session: &mut Session| {
session.update();
session.caches[0].composite.value(Channel::BaseColor, SIZE / 2, SIZE / 2)
};
execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap();
add_filter(&mut session, json!({"filter": "bakedLightingEnvironment"}));
let name = session.import_resource_bytes("lighting.png", image_bytes([255, 0, 0])).unwrap();
execute(&mut session, "display.set", &json!({"environment": format!("resource:{name}")})).unwrap();
let red = sample(&mut session);
assert!(red[0] > red[1], "the selected resource lights the base color");
execute(&mut session, "resource.remove", &json!({"name": name})).unwrap();
let fallback = sample(&mut session);
let replacement = session.import_resource_bytes("lighting.png", image_bytes([0, 255, 0])).unwrap();
let green = sample(&mut session);
assert_eq!(replacement, name);
assert_ne!(fallback, red);
assert!(green[1] > green[0] && green != fallback, "reimporting the referenced image relights the material: {green:?}");
}
+411
View File
@@ -0,0 +1,411 @@
//! The shape filters: Threshold's modes, Mirror, Mask Outline, Bevel, Bevel Smooth, Directional Distance, Warp's modes and Blur Slope's source
use serde_json::{Value, json};
use texturecraft_engine::core::{
Bevel, BevelBlur, BevelCorner, BevelDirection, BevelSmooth, DirectionalDistance, EffectKind, Filter, MaskOutline, Mirror, MirrorCorner, MirrorMode,
OutlinePosition, SlopeBlending, SourceSlopeBlur, SourceWarp, ThresholdMode, WarpBlending, WarpMode, WarpSource, WarpSourceMode,
};
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, filter_of, refused, roughness, session, set};
/// Threshold: a new one is Greater than 0.01; each mode compares its way; one saved before keeps Greater or equal
#[test]
fn threshold_modes_compare_their_way() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap();
let effect = add_filter(&mut s, json!({"filter": "threshold"}));
assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater }, "the library defaults");
let texel = (SIZE / 4, SIZE / 2);
assert_eq!(roughness(&mut s, texel), 1.0);
set(&mut s, effect, json!({"level": 0.25}));
assert_eq!(roughness(&mut s, texel), 0.0, "a value at the level is not greater");
for (mode, white) in [("greaterOrEqual", 1.0), ("lower", 0.0), ("lowerOrEqual", 1.0)] {
set(&mut s, effect, json!({"mode": mode}));
assert_eq!(roughness(&mut s, texel), white, "{mode}");
}
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "sideways"})).is_err());
assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.25, mode: ThresholdMode::LowerOrEqual }, "a refused mode changes nothing");
execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::Threshold { level: 0.01, mode: ThresholdMode::Greater });
}
/// Mirror: the left half of each UV tile copied onto the right (inverted the other way, or a corner onto the rest), its axis white in Display Debug
#[test]
fn mirror_copies_one_side_over_the_other() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap();
let row = SIZE / 2;
let (left, right) = ((20, row), (SIZE - 1 - 20, row));
let (left_before, right_before) = (roughness(&mut s, left), roughness(&mut s, right));
assert!((left_before - right_before).abs() > 0.05, "the gradient differs across: {left_before} {right_before}");
let effect = add_filter(&mut s, json!({"filter": "mirror"}));
assert_eq!(filter_of(&s, effect), Filter::Mirror(Mirror::LIBRARY));
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mirror");
assert!((roughness(&mut s, left) - left_before).abs() < 2e-3, "the left side stays");
assert!((roughness(&mut s, right) - left_before).abs() < 2e-3, "the right side reads the left");
set(&mut s, effect, json!({"invertAxisX": true}));
assert!((roughness(&mut s, left) - right_before).abs() < 2e-3, "inverted, the left side reads the right");
set(&mut s, effect, json!({"mode": "corner", "cornerType": "topRight"}));
assert!((roughness(&mut s, (20, 20)) - roughness(&mut s, (SIZE - 1 - 20, 20))).abs() < 2e-3, "a corner mirrors across too");
let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() };
assert_eq!((mirror.mode, mirror.corner), (MirrorMode::Corner, MirrorCorner::TopRight));
set(&mut s, effect, json!({"mode": "axisX", "displayDebug": true}));
assert_eq!(roughness(&mut s, (SIZE / 2, row)), 1.0, "Display Debug draws the axis white");
refused(&mut s, effect, &[json!({"mode": "diagonal"}), json!({"cornerType": "middle"}), json!({"invertAxisY": "yes"})]);
set(&mut s, effect, json!({"axisYOffset": 3.0}));
let Filter::Mirror(mirror) = filter_of(&s, effect) else { panic!() };
assert_eq!(mirror.offset, [0.5, 1.0], "offsets clamp to the tile");
}
/// Mask Outline: a band along the edge where the gradient crosses its Threshold, outside, inside or on both sides, on black or over the values
#[test]
fn mask_outline_draws_a_band_along_the_threshold_edge() {
let mut s = session();
let (at, values, _) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "maskOutline"}));
assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Mask Outline");
set(&mut s, effect, json!({"threshold": 0.5, "width": 0.03}));
assert_eq!(roughness(&mut s, at(2)), 1.0, "outside, next to the edge");
assert_eq!(roughness(&mut s, at(8)), 0.0, "past the band");
assert_eq!(roughness(&mut s, at(-2)), 0.0, "inside the shapes");
set(&mut s, effect, json!({"maskPosition": "inside"}));
assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 0.0), "inside");
set(&mut s, effect, json!({"maskPosition": "both"}));
assert_eq!((roughness(&mut s, at(-2)), roughness(&mut s, at(2))), (1.0, 1.0), "both sides");
set(&mut s, effect, json!({"startFromBlack": false}));
let far = at(8);
assert!((roughness(&mut s, far) - values[far.0 as usize]).abs() < 2e-3, "over the values");
set(&mut s, effect, json!({"startFromBlack": true, "maskPosition": "outside", "blur": 1.0}));
let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(2)));
assert!(near > further && further > 0.0 && near < 1.0, "a blurred band fades out: {near} {further}");
refused(&mut s, effect, &[json!({"maskPosition": "around"}), json!({"startFromBlack": 1})]);
set(&mut s, effect, json!({"width": 4.0, "curveShape": -3.0}));
let Filter::MaskOutline(outline) = filter_of(&s, effect) else { panic!() };
assert_eq!((outline.position, outline.width, outline.curve), (OutlinePosition::Outside, 1.0, -1.0), "values clamp");
execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::MaskOutline(MaskOutline::LIBRARY));
}
/// A fill whose roughness is a repeating gradient: the middle row's values
fn gradient_row(s: &mut Session) -> Vec<f32> {
execute(s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap();
execute(s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap();
middle_row(s)
}
/// The composited roughness along the middle row
fn middle_row(s: &mut Session) -> Vec<f32> {
(0..SIZE).map(|x| roughness(s, (x, SIZE / 2))).collect()
}
/// A roughness gradient crossing 0.5 away from the tile's sides along the middle row: texel `steps` outward of the shapes' first texel at its edge (inward below 0), the values before any filter, and the outward direction along x
pub(crate) fn shape_edge(s: &mut Session) -> (impl Fn(i64) -> (u32, u32) + use<>, Vec<f32>, i64) {
let row = SIZE / 2;
let values = gradient_row(s);
let edge = (SIZE / 4..SIZE * 3 / 4).find(|x| (values[*x as usize] >= 0.5) != (values[*x as usize - 1] >= 0.5)).unwrap();
let (inner, outward): (u32, i64) = if values[edge as usize] >= 0.5 { (edge, -1) } else { (edge - 1, 1) };
(move |steps: i64| ((inner as i64 + steps * outward) as u32, row), values, outward)
}
/// Bevel: a negative Distance slopes the shapes down to their edge, a positive one rises around them; Smoothing, Corner Type, Blur Mode and Wrap set; one saved before keeps its width bevel
#[test]
fn bevel_slopes_inwards_or_outwards() {
let mut s = session();
let (at, values, _) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "bevel"}));
assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel");
let value = |at: (u32, u32)| values[at.0 as usize];
// Inwards over a tenth of the tile (12.8 texels here)
let (edge, outside) = (roughness(&mut s, at(0)), roughness(&mut s, at(3)));
assert!(edge < value(at(0)) * 0.2, "down at the edge: {edge} vs {}", value(at(0)));
assert!((outside - value(at(3))).abs() < 2e-3, "outside untouched");
set(&mut s, effect, json!({"distance": 0.1}));
let (near, further) = (roughness(&mut s, at(1)), roughness(&mut s, at(6)));
assert!(near > 0.8 && further > value(at(6)) && near > further, "rises around the shapes: {near} {further}");
assert!((roughness(&mut s, at(-2)) - value(at(-2))).abs() < 2e-3, "inside untouched");
set(&mut s, effect, json!({"smoothing": 2.0, "blurMode": "uniform"}));
let smoothed = roughness(&mut s, at(1));
assert!((smoothed - near).abs() > 1e-3, "smoothing blurs the slope: {smoothed} vs {near}");
set(&mut s, effect, json!({"cornerType": "angular", "wrap": true}));
refused(&mut s, effect, &[json!({"cornerType": "square"}), json!({"blurMode": "even"}), json!({"wrap": 1})]);
set(&mut s, effect, json!({"distance": -3.0, "smoothing": 9.0}));
let expected = Bevel { wrap: true, distance: -1.0, corner: BevelCorner::Angular, smoothing: 5.0, blur: BevelBlur::Uniform };
assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(expected), "values clamp");
execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::DistanceBevel(Bevel::LIBRARY));
let old: Filter = serde_json::from_value(json!({"Bevel": {"width": 16.0}})).unwrap();
assert_eq!(old, Filter::Bevel { width: 16.0, wrap: false }, "a bevel saved before keeps its width");
}
/// Bevel Smooth: a ramp from the edge outwards (shapes white), inwards (around them black) or across it (mid gray on it)
#[test]
fn bevel_smooth_ramps_from_the_edge() {
let mut s = session();
let (at, _, _) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "bevelSmooth"}));
assert_eq!(filter_of(&s, effect), Filter::BevelSmooth(BevelSmooth::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Bevel Smooth");
set(&mut s, effect, json!({"smoothing": 0.0}));
let (inside, near, further) = (roughness(&mut s, at(-3)), roughness(&mut s, at(1)), roughness(&mut s, at(6)));
assert_eq!(inside, 1.0, "out: the shapes stay white");
assert!(near > further && further > 0.0 && near < 1.0, "fades outwards: {near} {further}");
set(&mut s, effect, json!({"direction": "in"}));
let (outside, inner) = (roughness(&mut s, at(3)), roughness(&mut s, at(-3)));
assert!(outside == 0.0 && inner > 0.0 && inner < 1.0, "in: rises inwards: {outside} {inner}");
set(&mut s, effect, json!({"direction": "inOut"}));
let (edge_in, edge_out) = (roughness(&mut s, at(0)), roughness(&mut s, at(1)));
assert!(edge_in > 0.5 && edge_out < 0.5 && edge_in - edge_out < 0.2, "across: mid gray at the edge: {edge_in} {edge_out}");
set(&mut s, effect, json!({"curveOffset": 0.5}));
assert!(roughness(&mut s, at(0)) > edge_in, "the offset raises the ramp");
refused(&mut s, effect, &[json!({"direction": "up"}), json!({"wrap": "yes"})]);
set(&mut s, effect, json!({"distance": 2.0, "smoothing": 20.0, "maskThreshold": -1.0, "distanceMapMultiplier": 4.0, "curveShape": 5.0}));
let Filter::BevelSmooth(smooth) = filter_of(&s, effect) else { panic!() };
assert_eq!(
(smooth.direction, smooth.distance, smooth.smoothing, smooth.threshold, smooth.multiplier, smooth.curve_shape),
(BevelDirection::InOut, 0.3, 10.0, 0.0, 1.0, 1.0),
"values clamp"
);
}
/// Directional Distance: a trail fading away from the shapes towards its Angle, none against it
#[test]
fn directional_distance_trails_one_way() {
let mut s = session();
let (at, _, outward) = shape_edge(&mut s);
let effect = add_filter(&mut s, json!({"filter": "directionalDistance"}));
assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(DirectionalDistance::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Directional Distance");
// Along the row, away from the shapes
let away = if outward > 0 { 0.0 } else { 180.0 };
set(&mut s, effect, json!({"angle": away, "distance": 0.05}));
let (inside, near, further) = (roughness(&mut s, at(-2)), roughness(&mut s, at(1)), roughness(&mut s, at(4)));
assert_eq!(inside, 1.0, "the shapes are white");
assert!(near > further && further > 0.0, "fades away from them: {near} {further}");
set(&mut s, effect, json!({"contrast": 0.5}));
assert_eq!(roughness(&mut s, at(1)), 1.0, "contrast hardens the near trail");
set(&mut s, effect, json!({"angle": away + 180.0, "contrast": 0.0}));
assert!(roughness(&mut s, at(1)) < near, "against the angle the edge gets less trail");
set(&mut s, effect, json!({"distance": 1.0, "angle": -90.0, "contrast": 3.0, "distanceMapMultiplier": -1.0}));
let expected = DirectionalDistance { distance: 0.3, angle: 270.0, contrast: 1.0, multiplier: 0.0 };
assert_eq!(filter_of(&s, effect), Filter::DirectionalDistance(expected), "values clamp, the angle wraps");
}
/// Texels either side of a texel that must all rise (or fall) for the warp and slope tests to read it as on a slope
const SLOPE_WINDOW: usize = 8;
/// Warp: library defaults, Previous Input moving texels by their values, and blended directions
#[test]
fn warp_modes_move_texels_their_way() {
let mut s = session();
let before = gradient_row(&mut s);
let after = middle_row;
let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
let effect = add_filter(&mut s, json!({"filter": "warp"}));
assert_eq!(filter_of(&s, effect), Filter::SourceWarp(SourceWarp::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Warp");
set(&mut s, effect, json!({"intensity": 0.05, "divider": 1}));
let warped = after(&mut s);
assert!(moved(&warped) > 0.01 && warped.iter().all(|v| v.is_finite()), "the noise moves texels: {}", moved(&warped));
set(&mut s, effect, json!({"intensity": 0.0}));
assert!(moved(&after(&mut s)) < 2e-3, "no intensity, no move");
// Along the gradient where it rises: a texel above mid gray reads further up it, so it gets lighter
let rising = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k]);
let falling = |x: usize| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] < before[k]);
let light = |x: &usize| (0.6..0.85).contains(&before[*x]);
let (texel, angle) = match (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && rising(*x)) {
Some(x) => (x, 0.0),
None => ((SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| light(x) && falling(*x)).unwrap(), 180.0),
};
set(&mut s, effect, json!({"intensity": 0.05, "warpMode": "directional", "angle": angle, "sourceMode": "previousInput"}));
let directional = after(&mut s);
assert!(directional[texel] > before[texel] + 0.01, "{} -> {}", before[texel], directional[texel]);
set(&mut s, effect, json!({"sourceMode": "customNoise"}));
assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing moves");
set(&mut s, effect, json!({"warpMode": "multiDirectional", "sourceMode": "defaultNoise", "directions": 2, "blendingMode": "max"}));
let max = after(&mut s);
set(&mut s, effect, json!({"blendingMode": "min"}));
let min = after(&mut s);
set(&mut s, effect, json!({"blendingMode": "average"}));
let average = after(&mut s);
assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min");
assert!(average.iter().zip(max.iter().zip(&min)).all(|(average, (max, min))| *average <= max + 2e-3 && *average >= min - 2e-3), "the average between");
set(&mut s, effect, json!({"blendingMode": "chain", "directions": 4}));
assert!(after(&mut s).iter().all(|v| v.is_finite()));
refused(&mut s, effect, &[json!({"warpMode": "spiral"}), json!({"directions": 3}), json!({"blendingMode": "sum"}), json!({"sourceMode": "image"})]);
set(&mut s, effect, json!({"intensity": 5.0, "angle": -90.0, "sourceTiling": 99.0, "sourceBlur": -1.0, "seed": 7}));
let Filter::SourceWarp(warp) = filter_of(&s, effect) else { panic!() };
assert_eq!((warp.intensity, warp.angle, warp.source.tiling, warp.source.blur, warp.seed), (1.0, 270.0, 16.0, 0.0, 7), "values clamp, the angle wraps");
assert_eq!((warp.mode, warp.blending, warp.directions), (WarpMode::MultiDirectional, WarpBlending::Chain, 4));
}
/// Opening saved Directional Warp preserves the existing settings without a catalog reset.
#[test]
fn a_saved_directional_warp_has_no_catalog_defaults() {
let mut session = session();
let effect = add_filter(&mut session, json!({"filter": "warp"}));
let saved = json!({"DirectionalWarp": {"intensity": 8.0, "angle": 30.0, "scale": 4.0, "seed": 3}});
let old: Filter = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(old, Filter::DirectionalWarp { intensity: 8.0, angle: 30.0, scale: 4.0, seed: 3, divider: 1 });
assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before");
session.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old.clone());
let reset = execute(&mut session, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(reset, json!({"changed": false}));
assert_eq!(filter_of(&session, effect), old);
}
/// Blur Slope: library defaults, Min under Blur under Max, reading downhill of its Previous Input, Quality, one undo, old saves
#[test]
fn slope_blur_reads_downhill_of_its_source() {
let mut s = session();
let before = gradient_row(&mut s);
let after = middle_row;
let moved = |values: &[f32]| values.iter().zip(&before).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
let effect = add_filter(&mut s, json!({"filter": "blurSlope"}));
assert_eq!(filter_of(&s, effect), Filter::SourceSlopeBlur(SourceSlopeBlur::LIBRARY), "the library defaults");
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Blur Slope");
set(&mut s, effect, json!({"intensity": 0.05, "divider": 1}));
let blur = after(&mut s);
assert!(moved(&blur) > 0.005 && blur.iter().all(|v| v.is_finite()), "the noise's slope smears: {}", moved(&blur));
set(&mut s, effect, json!({"blendingMode": "min"}));
let min = after(&mut s);
set(&mut s, effect, json!({"blendingMode": "max"}));
let max = after(&mut s);
assert!(max.iter().zip(&min).all(|(max, min)| max + 1e-4 >= *min) && max.iter().zip(&min).any(|(max, min)| max - min > 0.01), "Max over Min");
assert!(blur.iter().zip(max.iter().zip(&min)).all(|(blur, (max, min))| *blur <= max + 2e-3 && *blur >= min - 2e-3), "Blur between");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() };
assert_eq!(slope.blending, SlopeBlending::Min, "one undo step");
// Read downhill of the gradient itself: every texel where it rises reads darker values
set(&mut s, effect, json!({"blendingMode": "blur", "sourceMode": "previousInput"}));
let downhill = after(&mut s);
let rising = (SLOPE_WINDOW..SIZE as usize - SLOPE_WINDOW).find(|x| (x - SLOPE_WINDOW..x + SLOPE_WINDOW).all(|k| before[k + 1] > before[k] + 1e-4)).unwrap();
assert!(downhill[rising] < before[rising] - 0.005, "{} -> {}", before[rising], downhill[rising]);
set(&mut s, effect, json!({"quality": 0.0}));
let coarse = after(&mut s);
assert!(coarse.iter().all(|v| v.is_finite()) && coarse != downhill, "fewer reads, another smear");
set(&mut s, effect, json!({"sourceMode": "customNoise"}));
assert!(moved(&after(&mut s)) < 2e-3, "an unlinked custom noise is flat: nothing smears");
refused(&mut s, effect, &[json!({"blendingMode": "average"}), json!({"sourceMode": "image"}), json!({"divider": 7})]);
set(&mut s, effect, json!({"intensity": 5.0, "quality": -1.0, "sourceTiling": 99.0, "sourceBlur": 2.0, "sourceBalance": 0.25, "seed": 7}));
let Filter::SourceSlopeBlur(slope) = filter_of(&s, effect) else { panic!() };
let source = WarpSource { mode: WarpSourceMode::CustomNoise, blur: 1.0, balance: 0.25, contrast: 0.0, tiling: 16.0 };
assert_eq!((slope.intensity, slope.quality, slope.source, slope.seed), (1.0, 0.0, source, 7), "values clamp");
// Saved Blur Slope keeps its existing settings
let saved = json!({"SlopeBlur": {"radius": 16.0, "scale": 4.0, "seed": 1}});
let old: Filter = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(old, Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1, divider: 1 });
assert_eq!(serde_json::to_value(&old).unwrap(), saved, "saves as before");
s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(old.clone());
let reset = execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(reset, json!({"changed": false}));
assert_eq!(filter_of(&s, effect), old);
}
#[test]
fn slope_blur_source_tiling_changes_sampled_inputs() {
let mut session = session();
let _ = gradient_row(&mut session);
let effect = add_filter(&mut session, json!({"filter": "blurSlope", "intensity": 0.05, "divider": 1}));
set(&mut session, effect, json!({"sourceMode": "customNoise"}));
execute(&mut session, "layer.fill.set", &json!({"effect": effect.0, "input": "customNoise", "procedural": "gradient"})).unwrap();
for mode in ["previousInput", "customNoise"] {
set(&mut session, effect, json!({"sourceMode": mode, "sourceTiling": 1.0}));
let original = middle_row(&mut session);
set(&mut session, effect, json!({"sourceTiling": 2.0}));
let repeated = middle_row(&mut session);
assert!(original.iter().zip(&repeated).any(|(original, repeated)| (original - repeated).abs() > 0.01), "{mode} should repeat the source");
}
}
+353
View File
@@ -0,0 +1,353 @@
//! The simple adjustment filters, the blurs, Highpass and Grayscale Conversion
use serde_json::json;
use texturecraft_engine::core::{Channel, ConversionMode, EffectKind, Filter, GrayscaleConversion, HighpassSpace, lum};
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, filter_of, roughness, session, set};
/// A session with one roughness `value` fill
fn fill(value: f32) -> Session {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": value})).unwrap();
s
}
const TEXEL: (u32, u32) = (SIZE / 4, SIZE / 2);
fn close(a: f32, b: f32) -> bool {
(a - b).abs() < 2e-3
}
/// The library defaults leave the values as they are (Posterize steps them, Invert inverts)
#[test]
fn new_simple_filters_start_where_the_reference_does() {
let cases = [
("clamp", Filter::Clamp { min: 0.0, max: 1.0 }),
("smoothstep", Filter::Smoothstep { min: 0.0, max: 1.0 }),
("heightAdjust", Filter::HeightAdjust { invert: false, offset: 0.0, multiply: 1.0 }),
("histogramScan", Filter::HistogramScan { position: 0.5, contrast: 0.0, invert_position: false }),
("histogramShift", Filter::HistogramShift { offset: 0.0 }),
("posterize", Filter::Posterize { levels: 8.0, alpha: false }),
("invert", Filter::Invert),
];
for (id, defaults) in cases {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": id}));
assert_eq!(filter_of(&s, effect), defaults, "{id}");
}
let mut s = fill(0.25);
add_filter(&mut s, json!({"filter": "clamp"}));
add_filter(&mut s, json!({"filter": "heightAdjust"}));
add_filter(&mut s, json!({"filter": "histogramScan"}));
add_filter(&mut s, json!({"filter": "histogramShift"}));
assert!(close(roughness(&mut s, TEXEL), 0.25), "Clamp, Height Adjust, Histogram Scan and Shift at their defaults change nothing");
}
/// Smoothstep eases between its bounds; Clamp keeps within them
#[test]
fn smoothstep_eases_between_minimum_and_maximum() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "smoothstep"}));
assert!(close(roughness(&mut s, TEXEL), 0.15625), "0.25 eased: 3t² − 2t³");
set(&mut s, effect, json!({"min": 0.25, "max": 0.75}));
assert!(close(roughness(&mut s, TEXEL), 0.0), "at the minimum");
set(&mut s, effect, json!({"min": 0.0, "max": 0.2}));
assert!(close(roughness(&mut s, TEXEL), 1.0), "past the maximum");
set(&mut s, effect, json!({"min": 0.25, "max": 0.25}));
assert!(close(roughness(&mut s, TEXEL), 1.0), "equal bounds are a step, the bound itself white");
}
/// Invert's switch turns it off and on in one undo step each; restore defaults turns it back on
#[test]
fn invert_switches_off_and_on() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "invert"}));
assert!(close(roughness(&mut s, TEXEL), 0.75));
set(&mut s, effect, json!({"invert": false}));
assert_eq!(filter_of(&s, effect), Filter::InvertOff);
assert!(close(roughness(&mut s, TEXEL), 0.25), "off changes nothing");
assert_eq!(filter_of(&s, effect).label(), "Invert", "still named Invert");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "invert": "yes"})).is_err());
execute(&mut s, "edit.undo", &json!({})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::Invert, "one undo step");
set(&mut s, effect, json!({"invert": false}));
execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::Invert);
// An old project's Invert still reads as before
let old: Filter = serde_json::from_value(json!("Invert")).unwrap();
assert_eq!(old, Filter::Invert);
}
/// Height Adjust flips, scales and raises around mid gray
#[test]
fn height_adjust_flips_scales_and_raises() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "heightAdjust"}));
set(&mut s, effect, json!({"multiply": 2.0}));
assert!(close(roughness(&mut s, TEXEL), 0.0), "(0.25 − 0.5) × 2 + 0.5");
set(&mut s, effect, json!({"invert": true, "offset": 0.1}));
assert!(close(roughness(&mut s, TEXEL), 1.0), "flipped to 0.75, (0.75 − 0.5) × 2 + 0.5 + 0.1 clamped");
set(&mut s, effect, json!({"multiply": 1.0, "offset": -0.2}));
assert!(close(roughness(&mut s, TEXEL), 0.55));
set(&mut s, effect, json!({"multiply": 50.0}));
assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: true, offset: -0.2, multiply: 10.0 }, "Multiply caps at 10");
}
/// Height Adjust's Offset reaches -10..10 as the reference's does
#[test]
fn height_adjust_offset_reaches_ten_either_way() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "heightAdjust"}));
set(&mut s, effect, json!({"offset": 5.0}));
let kept = filter_of(&s, effect);
set(&mut s, effect, json!({"offset": -50.0}));
assert_eq!(kept, Filter::HeightAdjust { invert: false, offset: 5.0, multiply: 1.0 }, "an offset of 5 is kept");
assert_eq!(filter_of(&s, effect), Filter::HeightAdjust { invert: false, offset: -10.0, multiply: 1.0 }, "Offset stops at -10");
}
/// Histogram Scan's Invert Position reads the position from the other end; old saves have none
#[test]
fn histogram_scan_inverts_its_position() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "histogramScan"}));
set(&mut s, effect, json!({"position": 0.2, "contrast": 1.0}));
assert!(close(roughness(&mut s, TEXEL), 1.0), "0.25 is above 0.2");
set(&mut s, effect, json!({"invertPosition": true}));
assert!(close(roughness(&mut s, TEXEL), 0.0), "0.25 is below 1 − 0.2");
let old: Filter = serde_json::from_value(json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}})).unwrap();
assert_eq!(old, Filter::HistogramScan { position: 0.5, contrast: 0.5, invert_position: false });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HistogramScan": {"position": 0.5, "contrast": 0.5}}), "saved as before");
}
/// Histogram Shift's Position: 1 shifts nothing, lower shifts back by 1 − position; offsets saved before read as themselves
#[test]
fn histogram_shift_takes_a_position() {
let mut s = fill(0.25);
let effect = add_filter(&mut s, json!({"filter": "histogramShift"}));
set(&mut s, effect, json!({"position": 0.5}));
assert_eq!(filter_of(&s, effect), Filter::HistogramShift { offset: -0.5 });
assert!(close(roughness(&mut s, TEXEL), 0.75), "0.25 − 0.5 wraps to 0.75");
assert_eq!(Filter::shift_position(-0.5), 0.5);
assert_eq!(Filter::shift_position(0.25), 0.25, "an old positive offset shows as itself");
assert_eq!(Filter::shift_position(0.0), 1.0);
}
/// Posterize steps to its Colors Amount and takes Apply to Alpha; old saves read without it and save as before
#[test]
fn posterize_takes_apply_to_alpha() {
let mut s = fill(0.3);
let effect = add_filter(&mut s, json!({"filter": "posterize"}));
set(&mut s, effect, json!({"levels": 2, "applyToAlpha": true}));
assert_eq!(filter_of(&s, effect), Filter::Posterize { levels: 2.0, alpha: true });
assert!(close(roughness(&mut s, TEXEL), 0.0));
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": 1})).is_err());
let old: Filter = serde_json::from_value(json!({"Posterize": {"levels": 4.0}})).unwrap();
assert_eq!(old, Filter::Posterize { levels: 4.0, alpha: false });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Posterize": {"levels": 4.0}}), "saved as before");
}
/// Pixelate takes Pixels Amount (cells across the UV tile) and Apply To Alpha; Mosaics saved before load and save as before
#[test]
fn pixelate_takes_pixels_amount_and_apply_to_alpha() {
let mut s = fill(0.3);
let effect = add_filter(&mut s, json!({"filter": "pixelate"}));
assert_eq!(filter_of(&s, effect), Filter::Mosaic { size: 64.0, alpha: true }, "32 pixels across, coverage stepped");
set(&mut s, effect, json!({"pixelsAmount": 7.6, "applyToAlpha": false}));
let Filter::Mosaic { size, alpha } = filter_of(&s, effect) else { panic!() };
assert!(close(Filter::pixels_amount(size), 8.0) && !alpha, "a whole Pixels Amount: {size}");
assert!(close(roughness(&mut s, TEXEL), 0.3), "a uniform fill stays");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "no"})).is_err());
let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string();
assert!(inspect.contains("Pixelate"), "named after the reference workflow");
let old: Filter = serde_json::from_value(json!({"Mosaic": {"size": 32.0}})).unwrap();
assert_eq!(old, Filter::Mosaic { size: 32.0, alpha: true });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"Mosaic": {"size": 32.0}}), "saved as before");
}
/// FXAA (Anti-aliasing) takes Affect Alpha Channel (off for a new one) and leaves flat values as they are
#[test]
fn fxaa_takes_affect_alpha_channel() {
let mut s = fill(0.3);
let effect = add_filter(&mut s, json!({"filter": "FXAA (Anti-aliasing)"}));
assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false });
set(&mut s, effect, json!({"affectAlphaChannel": true}));
assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: true });
assert!(close(roughness(&mut s, TEXEL), 0.3), "nothing to smooth on a flat fill");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "affectAlphaChannel": 2})).is_err());
execute(&mut s, "edit.undo", &json!({})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::Fxaa { alpha: false }, "one undo step");
}
/// Blur and Blur Directional take Intensity in the reference workflow's unit (16 texels at 2K each); radius still works
#[test]
fn blurs_take_intensity() {
let mut s = fill(0.3);
let blur = add_filter(&mut s, json!({"filter": "blur"}));
assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 4.8, wrap: false }, "a new Blur starts at Blur Intensity 0.30");
set(&mut s, blur, json!({"intensity": 2.0}));
assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 32.0, wrap: false });
set(&mut s, blur, json!({"intensity": 1000.0}));
assert_eq!(filter_of(&s, blur), Filter::Blur { radius: 256.0, wrap: false }, "capped as radius is");
let directional = add_filter(&mut s, json!({"filter": "blurDirectional"}));
set(&mut s, directional, json!({"intensity": 0.5, "angle": 90}));
assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 8.0, angle: 90.0 });
set(&mut s, directional, json!({"radius": 4.0}));
assert_eq!(filter_of(&s, directional), Filter::DirectionalBlur { radius: 4.0, angle: 90.0 }, "radius in texels at 2K still sets it");
}
/// Highpass takes Radius in Blur Intensity's unit (a new one 3), Color Space and Apply To Alpha; a Highpass saved before loads and saves as before
#[test]
fn highpass_takes_radius_color_space_and_apply_to_alpha() {
let mut s = fill(0.3);
let effect = add_filter(&mut s, json!({"filter": "Highpass"}));
assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false });
assert!(close(roughness(&mut s, TEXEL), 0.5), "a flat fill has no detail: mid gray");
set(&mut s, effect, json!({"intensity": 0.5, "colorSpace": "srgbFromAcescg", "applyToAlpha": true}));
assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 8.0, space: HighpassSpace::SrgbFromAcescg, alpha: true });
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "colorSpace": "rec2020"})).is_err());
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "applyToAlpha": "yes"})).is_err());
execute(&mut s, "edit.undo", &json!({})).unwrap();
assert_eq!(filter_of(&s, effect), Filter::HighPass { radius: 48.0, space: HighpassSpace::Working, alpha: false }, "one undo step");
let old: Filter = serde_json::from_value(json!({"HighPass": {"radius": 8.0}})).unwrap();
assert_eq!(old, Filter::HighPass { radius: 8.0, space: HighpassSpace::Working, alpha: false });
assert_eq!(serde_json::to_value(&old).unwrap(), json!({"HighPass": {"radius": 8.0}}), "saved as before");
}
/// The composited base color at the test texel
fn base_color(s: &mut Session) -> [f32; 3] {
s.update();
s.caches[0].composite.value(Channel::BaseColor, TEXEL.0, TEXEL.1)
}
/// A new Grayscale Conversion weighs a third of each component; a Grayscale saved before keeps its luminance, also after its first edit
#[test]
fn grayscale_conversion_takes_its_settings_and_keeps_saved_grayscales() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap();
let effect = add_filter(&mut s, json!({"filter": "Grayscale Conversion"}));
assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::LIBRARY));
s.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Filter(Filter::Grayscale);
let saved = base_color(&mut s);
assert!(saved.iter().all(|v| close(*v, saved[0])) && close(saved[0], lum([0.8, 0.2, 0.1])), "{saved:?}");
set(&mut s, effect, json!({"balance": 0.5}));
assert_eq!(filter_of(&s, effect), Filter::GrayscaleConversion(GrayscaleConversion::of_luminance()), "the luminance weights");
assert!(close(base_color(&mut s)[0], saved[0]), "looks the same after its first edit");
set(&mut s, effect, json!({"red": 1.0, "green": 0.0, "blue": 0.0, "invert": true}));
assert!(close(base_color(&mut s)[0], 1.0 - 0.8), "Red only, inverted");
set(&mut s, effect, json!({"mode": "min", "invert": false}));
assert!(close(base_color(&mut s)[0], 0.1), "the darkest component");
set(&mut s, effect, json!({"channelInput": "customInput", "mode": "max"}));
assert!(close(base_color(&mut s)[0], 0.5), "the Custom Input reads mid gray until set");
let Filter::GrayscaleConversion(conversion) = filter_of(&s, effect) else { panic!("converted") };
assert!(conversion.custom_input && conversion.mode == ConversionMode::Max);
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "channelInput": "image"})).is_err());
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "mode": "luma"})).is_err(), "Luma is the gradients' mode");
let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string();
assert!(inspect.contains("Grayscale Conversion"));
assert_eq!(serde_json::to_value(Filter::Grayscale).unwrap(), json!("Grayscale"), "saved as before");
}
/// Grayscale Conversion turns only colors gray: a signed height keeps its sign and a normal map is left alone
#[test]
fn grayscale_conversion_keeps_heights_signed_and_normals_as_they_are() {
let mut s = session();
let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "height", "value": -0.6})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap();
s.update();
let height_before = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0];
let normal_before = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1);
add_filter(&mut s, json!({"filter": "grayscale"}));
s.update();
let height = s.caches[0].composite.value(Channel::Height, TEXEL.0, TEXEL.1)[0];
let normal = s.caches[0].composite.value(Channel::Normal, TEXEL.0, TEXEL.1);
assert!(height_before < -0.5, "the fill's height is negative: {height_before}");
assert!((height - height_before).abs() < 0.02, "a signed height keeps its sign: {height} from {height_before}");
assert!(normal.iter().zip(normal_before).all(|(after, before)| close(*after, before)), "the normal is untouched: {normal:?}");
let gray = base_color(&mut s);
assert!(close(gray[0], gray[2]), "the color turns gray: {gray:?}");
}
+258
View File
@@ -0,0 +1,258 @@
//! Anisotropic Kuwahara, PBR Validate (Metallic Roughness), Height To Normal and Color Match
use serde_json::json;
use texturecraft_engine::core::{
AnisotropicKuwahara, Channel, ColorMatch, Filter, HeightToNormal, PbrValidate, SourceColorMode, TargetColorMode, ValidationMode,
};
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, filter_of, refused, session, set, sized_session};
/// The composited base color at texel `(x, y)`
fn base_color(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] {
s.update();
s.caches[0].composite.value(Channel::BaseColor, x, y)
}
/// Texels across a set fine enough for filters measured in texels at 2K (Kuwahara's radius, a height's slope)
const FINE_SET_SIZE: u32 = 512;
/// A new Anisotropic Kuwahara starts where the reference does, takes every setting (one undo step) and smooths a noisy fill
#[test]
fn anisotropic_kuwahara_takes_its_settings_and_smooths() {
let mut s = sized_session(FINE_SET_SIZE);
let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap();
let pattern = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 64, "low": [0, 0, 0], "high": [1, 1, 1]});
execute(&mut s, "layer.fill.set", &pattern).unwrap();
let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect();
let before: Vec<f32> = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect();
let effect = add_filter(&mut s, json!({"filter": "Anisotropic Kuwahara"}));
assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(AnisotropicKuwahara::LIBRARY));
set(&mut s, effect, json!({"radius": AnisotropicKuwahara::MAX_RADIUS}));
let after: Vec<f32> = texels.iter().map(|t| base_color(&mut s, *t)[0]).collect();
let steps = |v: &[f32]| v.windows(2).map(|w| (w[1] - w[0]).abs()).sum::<f32>();
assert!(steps(&after) < steps(&before) * 0.9, "smoother: {} vs {}", steps(&after), steps(&before));
let all = json!({"extractDirection": "customInput", "radius": 20.0, "smoothness": 0.5, "sharpness": 0.1,
"tensorSmoothness": 0.3, "anisotropy": 0.4, "angle": 390.0});
set(&mut s, effect, all);
let expected = AnisotropicKuwahara {
custom_input: true,
radius: AnisotropicKuwahara::MAX_RADIUS,
smoothness: 0.5,
sharpness: 0.25,
tensor_smoothness: 0.3,
anisotropy: 0.4,
angle: 30.0,
};
assert_eq!(filter_of(&s, effect), Filter::AnisotropicKuwahara(expected), "clamped, the angle wrapped");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "extractDirection": "luma"})).is_err());
let read = base_color(&mut s, texels[0]);
assert!(read.iter().all(|v| v.is_finite()), "a flat Custom Input reads no direction: {read:?}");
execute(&mut s, "edit.undo", &json!({})).unwrap();
let Filter::AnisotropicKuwahara(undone) = filter_of(&s, effect) else { panic!("still Kuwahara") };
assert_eq!(undone, AnisotropicKuwahara { radius: AnisotropicKuwahara::MAX_RADIUS, ..AnisotropicKuwahara::LIBRARY }, "one undo step");
let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string();
assert!(inspect.contains("Anisotropic Kuwahara"));
}
/// PBR Validate starts with the Color and Metal pills on, shows a too dark non-metal base color in red, leaves the metal as it is and takes its three switches
#[test]
fn pbr_validate_marks_implausible_base_colors() {
let mut s = session();
let texel = (SIZE / 4, SIZE / 2);
// sRGB 20: darker than both dark thresholds
let dark = 0.007;
execute(&mut s, "layer.add.fill", &json!({"color": [dark, dark, dark], "metallic": 0.0})).unwrap();
let effect = add_filter(&mut s, json!({"filter": "pbrValidate"}));
assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate::LIBRARY));
let off = &s.doc.project.effect(effect).unwrap().1.off_channels;
assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Metallic) && off.contains(&Channel::Roughness), "{off:?}");
assert_eq!(base_color(&mut s, texel), PbrValidate::INVALID, "too dark");
assert_eq!(s.caches[0].composite.value(Channel::Metallic, texel.0, texel.1)[0], 0.0, "the metal is left as it is");
set(&mut s, effect, json!({"validationMode": "metal"}));
let shown = base_color(&mut s, texel);
assert!((shown[0] - dark).abs() < 1e-3, "Metal leaves non-metal colors unchecked: {shown:?}");
set(&mut s, effect, json!({"validationMode": "albedo", "albedoDarkRangeThreshold": 50, "metalReflectanceRange": 70}));
assert_eq!(filter_of(&s, effect), Filter::PbrValidate(PbrValidate { mode: ValidationMode::Albedo, albedo_dark: 50, metal_low: 70 }));
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "albedoDarkRangeThreshold": 40})).is_err());
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "validationMode": "all"})).is_err());
}
/// The composited packed normal at texel `(x, y)`
fn normal(s: &mut Session, (x, y): (u32, u32)) -> [f32; 3] {
s.update();
s.caches[0].composite.value(Channel::Normal, x, y)
}
/// How far the packed normals of `texels` tilt from flat, summed
fn tilt(s: &mut Session, texels: &[(u32, u32)]) -> f32 {
texels.iter().map(|texel| normal(s, *texel)).map(|[x, y, _]| (x - 0.5).abs() + (y - 0.5).abs()).sum()
}
/// Height To Normal starts with the Normal pill only, turns the layer's height into its normal, overwrites or overlays it, one undo step
#[test]
fn height_to_normal_turns_the_height_into_the_normal() {
let mut s = sized_session(FINE_SET_SIZE);
let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap();
let bumps = json!({"layer": fill, "channel": "height", "procedural": "Clouds", "scale": 16, "low": [-0.05, -0.05, -0.05], "high": [0.05, 0.05, 0.05]});
execute(&mut s, "layer.fill.set", &bumps).unwrap();
let texels: Vec<(u32, u32)> = (0..32).map(|k| (FINE_SET_SIZE / 4 + k, FINE_SET_SIZE / 2)).collect();
assert!(tilt(&mut s, &texels) < 1e-3, "a fill's own normal is flat");
let color = base_color(&mut s, texels[0]);
let effect = add_filter(&mut s, json!({"filter": "heightToNormal"}));
assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(HeightToNormal::LIBRARY));
let off = &s.doc.project.effect(effect).unwrap().1.off_channels;
assert!(!off.contains(&Channel::Normal) && off.contains(&Channel::BaseColor) && off.contains(&Channel::Height), "{off:?}");
let made = tilt(&mut s, &texels);
assert!(made > 0.01, "the bumps tilt the normal: {made}");
assert_eq!(base_color(&mut s, texels[0]), color, "the base color is left as it is");
set(&mut s, effect, json!({"heightDepth": 64.0}));
assert!(tilt(&mut s, &texels) > made * 1.5, "deeper heights tilt more");
set(&mut s, effect, json!({"useWorldUnits": false, "normalIntensity": 0.0}));
assert!(tilt(&mut s, &texels) < 1e-3, "no intensity: flat");
execute(&mut s, "layer.fill.set", &json!({"layer": fill, "channel": "normal", "value": [0.7, 0.5, 0.95]})).unwrap();
assert!(tilt(&mut s, &texels) < 1e-3, "Overwrite Existing Normal replaces the fill's normal");
set(&mut s, effect, json!({"overwriteExistingNormal": false}));
assert!((normal(&mut s, texels[0])[0] - 0.7).abs() < 0.02, "laid over the fill's normal: {:?}", normal(&mut s, texels[0]));
let all = json!({"overwriteExistingNormal": true, "useWorldUnits": true, "surfaceSize": 0.0, "heightDepth": 500.0,
"normalIntensity": 70.0});
set(&mut s, effect, all);
let expected = HeightToNormal {
surface_size: 1.0,
height_depth: HeightToNormal::MAX_HEIGHT_DEPTH,
intensity: HeightToNormal::MAX_INTENSITY,
..HeightToNormal::LIBRARY
};
assert_eq!(filter_of(&s, effect), Filter::HeightToNormal(expected), "clamped");
assert!(normal(&mut s, texels[0]).iter().all(|v| v.is_finite()));
execute(&mut s, "edit.undo", &json!({})).unwrap();
let Filter::HeightToNormal(undone) = filter_of(&s, effect) else { panic!("still Height To Normal") };
assert!(!undone.overwrite && undone.surface_size == 300.0, "one undo step: {undone:?}");
assert!(execute(&mut s, "effect.set", &json!({"effect": effect.0, "useWorldUnits": "yes"})).is_err());
let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string();
assert!(inspect.contains("Height To Normal"));
}
/// Color Match starts with the Color pill only and moves the colors to its target keeping their pattern, all of them at the Color Variation's 0, keeping each texel's difference from the whole texture's mean without Custom Color Variation; Parameter and Image Input modes read their colors
#[test]
fn color_match_moves_the_colors_to_the_target() {
let mut s = session();
let fill = execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap()["layer"].as_u64().unwrap();
let reds = json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds", "scale": 8, "low": [0.3, 0.02, 0.02], "high": [0.9, 0.1, 0.1]});
execute(&mut s, "layer.fill.set", &reds).unwrap();
let texels: Vec<(u32, u32)> = (0..24).map(|k| (SIZE / 4 + k * 2, SIZE / 2)).collect();
let before: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect();
let spread = |colors: &[[f32; 3]]| colors.iter().map(|c| c[0]).fold(f32::MIN, f32::max) - colors.iter().map(|c| c[0]).fold(f32::MAX, f32::min);
assert!(spread(&before) > 0.05, "the clouds vary: {before:?}");
let effect = add_filter(&mut s, json!({"filter": "Color Match"}));
assert_eq!(filter_of(&s, effect), Filter::ColorMatch(ColorMatch::LIBRARY));
let off = &s.doc.project.effect(effect).unwrap().1.off_channels;
assert!(!off.contains(&Channel::BaseColor) && off.contains(&Channel::Roughness), "{off:?}");
let new: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect();
assert!(spread(&new) > 0.02, "a new Color Match keeps the pattern: {new:?}");
let redness = new.iter().map(|c| c[0] - c[2]).sum::<f32>() / new.len() as f32;
assert!(redness.abs() < 0.05, "around the gray target: {redness} {new:?}");
// Color Variation at 0: every texel is the target itself
set(&mut s, effect, json!({"hue": 0.0, "chroma": 0.0, "luma": 0.0}));
let gray = ColorMatch::LIBRARY.target_color;
for texel in &texels {
let color = base_color(&mut s, *texel);
assert!(color.iter().zip(gray).all(|(v, g)| (v - g).abs() < 2e-3), "Color Variation 0: the target itself, {color:?}");
}
// Without Custom Color Variation the texels keep their differences from the mean, now around the target
set(&mut s, effect, json!({"customColorVariation": false}));
let kept: Vec<[f32; 3]> = texels.iter().map(|t| base_color(&mut s, *t)).collect();
assert!(spread(&kept) > 0.02, "variation kept: {kept:?}");
let redness = kept.iter().map(|c| c[0] - c[2]).sum::<f32>() / kept.len() as f32;
assert!(redness.abs() < 0.05, "the reds are gray on average now: {redness} {kept:?}");
let brighter = |colors: &[[f32; 3]], a: usize, b: usize| colors[a][0] + colors[a][1] > colors[b][0] + colors[b][1];
let (lightest, darkest) =
(0..texels.len()).fold((0, 0), |(hi, lo), k| (if before[k][0] > before[hi][0] { k } else { hi }, if before[k][0] < before[lo][0] { k } else { lo }));
assert!(brighter(&kept, lightest, darkest), "the lightest red stays the lightest");
// Source Color Parameter: the texels of that color land on the target
let source = before[lightest];
set(&mut s, effect, json!({"sourceColorMode": "parameter", "sourceColor": source, "targetColor": [0.05, 0.1, 0.6]}));
let landed = base_color(&mut s, texels[lightest]);
assert!((landed[2] - 0.6).abs() < 0.01 && (landed[0] - 0.05).abs() < 0.01, "{landed:?}");
// Image Input: mid gray until a source is set
let all = json!({"sourceColorMode": "input", "targetColorMode": "imageInput", "customColorVariation": true, "hue": 400.0,
"chroma": 2.0, "luma": -1.0});
set(&mut s, effect, all);
let expected = ColorMatch {
source_mode: SourceColorMode::Input,
source_color: source,
target_mode: TargetColorMode::ImageInput,
target_color: [0.05, 0.1, 0.6],
custom_variation: true,
hue: 360.0,
chroma: 1.0,
luma: 0.0,
};
assert_eq!(filter_of(&s, effect), Filter::ColorMatch(expected), "clamped");
set(&mut s, effect, json!({"chroma": 0.0, "hue": 0.0}));
let image = base_color(&mut s, texels[0]);
assert!(image.iter().all(|v| (v - 0.5).abs() < 2e-3), "the Image Input's mid gray: {image:?}");
execute(&mut s, "edit.undo", &json!({})).unwrap();
let Filter::ColorMatch(undone) = filter_of(&s, effect) else { panic!("still Color Match") };
assert_eq!((undone.hue, undone.chroma), (360.0, 1.0), "one undo step: {undone:?}");
refused(
&mut s,
effect,
&[json!({"sourceColorMode": "median"}), json!({"targetColorMode": "input"}), json!({"customColorVariation": 1}), json!({"targetColor": "red"})],
);
let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string();
assert!(inspect.contains("Color Match"));
}
+50 -3
View File
@@ -1,9 +1,10 @@
//! What the filter tests share: their sessions and reading the composite
//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite
use texturecraft_engine::Session;
use texturecraft_engine::core::Channel;
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
/// The texture set side the filter tests paint on
pub(crate) const SIZE: u32 = 128;
@@ -45,3 +46,49 @@ pub(crate) fn center(s: &mut Session, channel: Channel) -> [f32; 3] {
let uv = center_uv(s);
s.caches[0].composite.value(channel, (uv.x * SIZE as f32) as u32, (uv.y * SIZE as f32) as u32)
}
/// The composited roughness at texel `(x, y)`
pub(crate) fn roughness(s: &mut Session, (x, y): (u32, u32)) -> f32 {
s.update();
s.caches[0].composite.value(Channel::Roughness, x, y)[0]
}
/// Content filter `params` on the selected layer: the effect
pub(crate) fn add_filter(s: &mut Session, params: Value) -> LayerId {
let mut params = params;
params["target"] = json!("content");
LayerId(execute(s, "effect.add.filter", &params).unwrap()["effect"].as_u64().unwrap())
}
/// A fill layer of base color `color` and roughness 0.3 under content filter `params`: the effect
pub(crate) fn filtered(s: &mut Session, color: [f32; 3], params: Value) -> LayerId {
execute(s, "layer.add.fill", &json!({"color": color, "roughness": 0.3})).unwrap();
add_filter(s, params)
}
/// The filter `effect` holds
pub(crate) fn filter_of(s: &Session, effect: LayerId) -> Filter {
match &s.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Filter(filter) => filter.clone(),
other => panic!("not a filter: {other:?}"),
}
}
/// `effect.set` on `effect` with `params`, which must succeed
pub(crate) fn set(s: &mut Session, effect: LayerId, params: Value) {
let mut params = params;
params["effect"] = json!(effect.0);
execute(s, "effect.set", &params).unwrap();
}
/// Each of `bad` is refused by `effect.set` on `effect`
pub(crate) fn refused(s: &mut Session, effect: LayerId, bad: &[Value]) {
for bad in bad {
let mut params = bad.clone();
params["effect"] = json!(effect.0);
assert!(execute(s, "effect.set", &params).is_err(), "{bad}");
}
}
+182 -16
View File
@@ -1,10 +1,12 @@
//! Swapping a filter effect's type in place through `effect.set {filter}`
use serde_json::{Value, json};
use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId};
use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId, SourceWarp, WarpMode, WarpSourceMode};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, StackTarget, execute};
use crate::filter_support::set;
/// A sphere project with its default layer selected
fn session() -> Session {
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap()
@@ -35,12 +37,12 @@ fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() {
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap();
set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4, "visible": false}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap();
set(&mut s, swapped, json!({"filter": "blur", "radius": 5.0}));
let blur = effect(&s, swapped);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius, .. }) if radius == 5.0), "{:?}", blur.kind);
assert_eq!(blur.name, "Blur", "a default name follows the new filter");
assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false));
assert_eq!(content_order(&s), vec![below, swapped, above]);
@@ -51,21 +53,150 @@ fn swapping_a_filter_keeps_a_name_the_user_chose() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap();
set(&mut s, id, json!({"filter": "threshold"}));
assert_eq!(effect(&s, id).name, "Flip");
}
#[test]
fn canonical_warp_and_blur_slope_can_be_added_and_swapped() {
let mut session = session();
let listed = execute(&mut session, "filter.list", &Value::Null).unwrap();
let entries = listed.as_array().unwrap();
let warp = add(&mut session, "effect.add.filter", json!({"filter": "warp", "target": "content", "warpMode": "directional", "angle": 45.0}));
assert!(
matches!(effect(&session, warp).kind, EffectKind::Filter(Filter::SourceWarp(settings)) if settings.mode == WarpMode::Directional && settings.angle == 45.0)
);
for (id, label) in [("warp", "Warp"), ("blurSlope", "Blur Slope")] {
let entry = entries.iter().find(|entry| entry["id"] == id).unwrap_or_else(|| panic!("missing {id}"));
let added = add(&mut session, "effect.add.filter", json!({"filter": id, "target": "mask"}));
assert_eq!(entry["label"], label);
assert_eq!(effect(&session, added).name, label);
assert_eq!(entry["defaults"], serde_json::to_value(effect(&session, added).kind).unwrap());
}
set(&mut session, warp, json!({"filter": "Blur Slope", "quality": 0.5, "sourceMode": "customNoise"}));
let blurred = effect(&session, warp);
assert_eq!(blurred.name, "Blur Slope");
assert!(
matches!(blurred.kind, EffectKind::Filter(Filter::SourceSlopeBlur(settings)) if settings.quality == 0.5 && settings.source.mode == WarpSourceMode::CustomNoise)
);
set(&mut session, warp, json!({"filter": "warp", "warpMode": "multiDirectional", "directions": 2}));
let warped = effect(&session, warp);
assert_eq!(warped.name, "Warp");
assert!(matches!(warped.kind, EffectKind::Filter(Filter::SourceWarp(settings)) if settings.mode == WarpMode::MultiDirectional && settings.directions == 2));
}
#[test]
fn replaced_filter_ids_are_rejected_without_editing_the_stack() {
let mut session = session();
let effect_id = add(&mut session, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let entries = execute(&mut session, "filter.list", &Value::Null).unwrap();
let before = effect(&session, effect_id);
let order = content_order(&session);
let history = session.history_labels();
for retired in ["slopeBlur", "Slope Blur", "warpDirectional", "Warp Directional", "Directional Warp"] {
let add_error = execute(&mut session, "effect.add.filter", &json!({"filter": retired, "target": "content"})).unwrap_err();
let swap_error = execute(&mut session, "effect.set", &json!({"effect": effect_id.0, "filter": retired, "warpMode": "directional"})).unwrap_err();
assert!(add_error.to_string().contains("unknown filter"), "{add_error}");
assert!(swap_error.to_string().contains("unknown filter"), "{swap_error}");
assert!(!entries.as_array().unwrap().iter().any(|entry| entry["id"] == retired || entry["label"] == retired));
}
assert_eq!(effect(&session, effect_id), before);
assert_eq!(content_order(&session), order);
assert_eq!(session.history_labels(), history);
}
#[test]
fn setting_directional_mode_on_a_modern_warp_preserves_its_seed() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "warp", "target": "content", "seed": 7}));
set(&mut s, id, json!({"filter": "warp", "warpMode": "directional"}));
let edited = effect(&s, id).kind;
assert!(matches!(edited, EffectKind::Filter(Filter::SourceWarp(warp)) if warp.mode == WarpMode::Directional && warp.seed == 7), "{edited:?}");
}
/// A content warp effect saved before the warp modes, as `filter`
fn saved_warp(s: &mut Session, filter: Filter) -> LayerId {
let id = add(s, "effect.add.filter", json!({"filter": "warp", "target": "content"}));
s.doc.project.effect_mut(id).unwrap().kind = EffectKind::Filter(filter);
id
}
#[test]
fn naming_canonical_warp_replaces_a_saved_warp_even_with_the_same_label() {
let mut session = session();
let saved = Filter::Warp { intensity: 8.0, scale: 4.0, seed: 7, divider: 1 };
let id = saved_warp(&mut session, saved.clone());
set(&mut session, id, json!({"filter": "warp"}));
assert_eq!(effect(&session, id).kind, EffectKind::Filter(Filter::SourceWarp(SourceWarp::LIBRARY)));
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(effect(&session, id).kind, EffectKind::Filter(saved));
}
#[test]
fn editing_settings_without_replacing_a_saved_warp_keeps_its_variant() {
let mut s = session();
let warp = saved_warp(&mut s, Filter::Warp { intensity: 8.0, scale: 4.0, seed: 1, divider: 1 });
let directional = saved_warp(&mut s, Filter::DirectionalWarp { intensity: 8.0, angle: 0.0, scale: 4.0, seed: 1, divider: 1 });
set(&mut s, warp, json!({"seed": 3}));
set(&mut s, directional, json!({"angle": 45.0}));
assert_eq!(effect(&s, warp).kind, EffectKind::Filter(Filter::Warp { intensity: 8.0, scale: 4.0, seed: 3, divider: 1 }));
assert_eq!(effect(&s, directional).kind, EffectKind::Filter(Filter::DirectionalWarp { intensity: 8.0, angle: 45.0, scale: 4.0, seed: 1, divider: 1 }));
}
#[test]
fn swapping_to_a_gradient_given_colors_ramps_evenly_through_them() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
set(&mut s, id, json!({"filter": "gradientMap", "colors": [[0, 0, 0], [1, 1, 1]]}));
let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") };
let halfway = gradient.ramp_at(0.5).unwrap();
assert!((halfway[0] - 0.5).abs() < 1e-3, "black to white is mid gray halfway: {halfway:?}");
}
/// A swap to a gradient given five colors and their places ramps through all five, not the library's three
#[test]
fn swapping_to_a_gradient_given_colors_and_places_uses_every_color() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
let colors = [[0.0; 3], [0.25; 3], [0.5; 3], [0.75; 3], [1.0; 3]];
set(&mut s, id, json!({"filter": "gradientMap", "colors": colors, "positions": [0.0, 0.1, 0.2, 0.3, 1.0]}));
let EffectKind::Filter(gradient) = effect(&s, id).kind else { panic!("still a filter") };
assert_eq!(gradient.ramp_colors(), colors);
assert_eq!(gradient.ramp_at(0.3), Some(colors[3]));
}
#[test]
fn one_undo_restores_the_old_filter() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap();
set(&mut s, id, json!({"filter": "sharpen"}));
execute(&mut s, "edit.undo", &Value::Null).unwrap();
let restored = effect(&s, id);
assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind);
assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level, .. }) if level == 0.3), "{:?}", restored.kind);
assert_eq!(restored.name, "Threshold");
}
@@ -74,7 +205,7 @@ fn a_mask_refuses_a_content_only_filter() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err();
let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "normalInvert"})).unwrap_err();
assert!(err.to_string().contains("not on masks"), "{err}");
assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert)));
@@ -86,15 +217,17 @@ fn a_mask_filter_swaps_in_place_on_the_mask() {
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap();
set(&mut s, swapped, json!({"blend": "Multiply", "opacity": 0.4}));
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap();
set(&mut s, swapped, json!({"filter": "blur"}));
let blur = effect(&s, swapped);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind);
assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4));
let layer = s.selected_layer().unwrap();
let mask_order: Vec<LayerId> = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
assert_eq!(mask_order, vec![below, swapped, above]);
}
@@ -103,11 +236,11 @@ fn naming_the_current_filter_edits_it_in_place() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap();
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap();
set(&mut s, id, json!({"filter": "blur", "radius": 9.0}));
set(&mut s, id, json!({"filter": "blur"}));
let blur = effect(&s, id);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind);
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius, .. }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind);
}
#[test]
@@ -115,7 +248,7 @@ fn a_name_given_with_the_swap_wins() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap();
set(&mut s, id, json!({"filter": "threshold", "name": "Edges"}));
let swapped = effect(&s, id);
assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind);
@@ -126,11 +259,11 @@ fn a_name_given_with_the_swap_wins() {
fn a_refused_swap_changes_nothing_and_adds_no_undo_step() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap();
set(&mut s, id, json!({"blend": "Multiply", "opacity": 0.4, "name": "Flip"}));
let before = effect(&s, id);
for refused in [
json!({"effect": id.0, "filter": "grayscale"}),
json!({"effect": id.0, "filter": "normalInvert"}),
json!({"effect": id.0, "filter": "nope"}),
json!({"effect": id.0, "filter": "levels"}),
json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}),
@@ -139,8 +272,10 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() {
}
assert_eq!(effect(&s, id), before);
// The last step is still the blend, opacity and name edit
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(effect(&s, id).name, "Invert");
}
@@ -153,6 +288,7 @@ fn only_filter_effects_swap_and_only_to_filters() {
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect");
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels");
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill");
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err());
assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert)));
}
@@ -170,3 +306,33 @@ fn invalid_swap_parameters_report_effect_set_and_preserve_history() {
assert_eq!(effect(&s, id), before);
assert_eq!(s.history_labels(), history);
}
#[test]
fn a_mask_takes_grayscale_conversion() {
let mut s = session();
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
set(&mut s, id, json!({"filter": "grayscale"}));
let swapped = effect(&s, id);
assert!(matches!(swapped.kind, EffectKind::Filter(Filter::GrayscaleConversion(_))), "{:?}", swapped.kind);
assert_eq!(swapped.name, "Grayscale Conversion");
}
#[test]
fn filters_carry_the_workflows_names_and_former_names_still_follow_a_swap() {
let mut s = session();
let slope = add(&mut s, "effect.add.filter", json!({"filter": "blurSlope", "target": "content"}));
assert_eq!(effect(&s, slope).name, "Blur Slope");
let names: Vec<Value> = execute(&mut s, "filter.list", &Value::Null).unwrap().as_array().unwrap().iter().map(|def| def["label"].clone()).collect();
for name in ["Contrast Luminosity", "Blur Slope", "Highpass", "Grayscale Conversion"] {
assert!(names.contains(&json!(name)), "{name} in {names:?}");
}
// A saved default name follows a swap even when the former name is no longer a command selector
let old = add(&mut s, "effect.add.filter", json!({"filter": "blurSlope", "target": "content", "name": "Slope Blur"}));
set(&mut s, old, json!({"filter": "blur"}));
assert_eq!(effect(&s, old).name, "Blur");
}
@@ -0,0 +1,89 @@
//! The Transform filter: each UV tile's content scaled, turned, moved and flipped, repeating round the tile or empty past it
use serde_json::json;
use texturecraft_engine::core::{EffectKind, Filter, FlipMode, LayerId, RepeatMode, TileTransform};
use texturecraft_engine::{Session, execute};
use crate::filter_support::{SIZE, add_filter, refused, roughness, session, set};
fn transform_of(s: &Session, effect: LayerId) -> TileTransform {
match &s.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Filter(Filter::Transform(transform)) => *transform,
other => panic!("not a transform: {other:?}"),
}
}
/// A new Transform changes nothing; Offset moves the content round the tile, Repeat mode None leaves empty past it, Flip mode turns it over
#[test]
fn transform_moves_scales_and_flips_each_tile() {
let mut s = session();
let row = SIZE / 2;
let empty = roughness(&mut s, (8, row));
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5], "roughness": 0.25})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"channel": "roughness", "procedural": "gradient"})).unwrap();
let before: Vec<f32> = (0..SIZE).map(|x| roughness(&mut s, (x, row))).collect();
let was = |x: u32| before[(x % SIZE) as usize];
let effect = add_filter(&mut s, json!({"filter": "transform"}));
assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY);
assert_eq!(s.doc.project.effect(effect).unwrap().1.name, "Transform");
for x in [20, 64, 100] {
assert!((roughness(&mut s, (x, row)) - was(x)).abs() < 1e-4, "a new Transform changes nothing at {x}");
}
// A quarter tile on: each texel reads 32 texels further right, the last ones round from the left
set(&mut s, effect, json!({"offset": [0.25, 0.0]}));
for x in [20, 50, 110] {
assert!((roughness(&mut s, (x, row)) - was(x + SIZE / 4)).abs() < 2e-3, "offset at {x}");
}
set(&mut s, effect, json!({"offset": 0.0, "flipMode": "horizontally"}));
assert!((roughness(&mut s, (20, row)) - was(SIZE - 1 - 20)).abs() < 2e-3, "flipped, the left reads the right");
// Twice across about the centre: the centre stays; without repeat the edges read empty (the layer's content is clear there)
set(&mut s, effect, json!({"flipMode": "none", "scaling": [2.0, 2.0], "repeatMode": "none"}));
assert!((roughness(&mut s, (SIZE / 2, row)) - was(SIZE / 2)).abs() < 2e-2, "the centre stays");
assert!((roughness(&mut s, (8, row)) - empty).abs() < 1e-4, "past the content reads empty");
// Repeating, texel 8 reads 2 · 8.5 / 128 − 0.5 of a tile on: between texels 80 and 81
set(&mut s, effect, json!({"repeatMode": "horizontallyAndVertically"}));
assert!((roughness(&mut s, (8, row)) - (was(80) + was(81)) / 2.0).abs() < 2e-3, "the tile comes round again");
let edited = transform_of(&s, effect);
assert_eq!((edited.repeat, edited.flip, edited.scaling), (RepeatMode::HorizontallyAndVertically, FlipMode::None, [2.0, 2.0]));
set(&mut s, effect, json!({"rotation": -30.0, "tileSafeRotation": false}));
let turned = transform_of(&s, effect);
assert_eq!((turned.rotation, turned.tile_safe), (330.0, false), "a turn reads 0..360");
refused(
&mut s,
effect,
&[
json!({"repeatMode": "sideways"}),
json!({"flipMode": "diagonal"}),
json!({"scaling": [1.0]}),
json!({"offset": "far"}),
json!({"tileSafeRotation": 1}),
],
);
assert_eq!(transform_of(&s, effect), turned, "a refused value changes nothing");
set(&mut s, effect, json!({"scaling": [1e9, -5.0]}));
assert_eq!(transform_of(&s, effect).scaling, [TileTransform::SCALING.1, TileTransform::SCALING.0], "scaling clamps");
execute(&mut s, "effect.filter.restoreDefaults", &json!({"effect": effect.0})).unwrap();
assert_eq!(transform_of(&s, effect), TileTransform::LIBRARY);
}
+24 -3
View File
@@ -129,6 +129,27 @@ fn randomize_seeds_gives_every_pattern_inside_a_new_seed_in_one_undo_step() {
assert_eq!(s.history_labels().len(), steps);
}
#[test]
fn reset_restores_a_procedural_filter_input_by_name_after_reopening() {
let (mut session, folder, fill) = folder_with_fill();
let filter = id(execute(&mut session, "effect.add.filter", &json!({"layer": fill.0, "target": "content", "filter": "colorMatch"})).unwrap(), "effect");
for (slot, seed) in [("input", 23), ("imageInput", 41)] {
execute(&mut session, "layer.fill.set", &json!({"effect": filter.0, "input": slot, "procedural": "Clouds", "seed": seed})).unwrap();
}
let seed = |session: &Session, slot: &str| match &session.doc.project.effect(filter).unwrap().1.inputs[slot] {
Source::Procedural { pattern, .. } => pattern.seed,
other => panic!("expected procedural input, got {other:?}"),
};
execute(&mut session, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
assert_ne!(seed(&session, "imageInput"), 41);
execute(&mut session, "layer.fill.set", &json!({"effect": filter.0, "input": "input", "clear": true})).unwrap();
session.doc.project = serde_json::from_slice(&serde_json::to_vec(&session.doc.project).unwrap()).unwrap();
execute(&mut session, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
assert_eq!(seed(&session, "imageInput"), 41);
}
/// The seeds of fill layer `id`'s base color and roughness patterns and of its mask's warp filter
fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) {
let layer = s.doc.project.layer(id).unwrap();
@@ -138,7 +159,7 @@ fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) {
other => panic!("not a pattern: {other:?}"),
};
let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind {
EffectKind::Filter(Filter::Warp { seed, .. }) => Some(seed),
EffectKind::Filter(Filter::SourceWarp(warp)) => Some(warp.seed),
_ => None,
});
(pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap())
@@ -213,8 +234,8 @@ fn reset_restores_original_effects_after_a_randomized_effect_is_duplicated() {
let duplicate = |session: &mut Session| id(execute(session, "effect.duplicate", &json!({"effect": original.0})).unwrap(), "effect");
let second = duplicate(&mut session);
let seed = |session: &Session, effect| match session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Filter(Filter::Warp { seed, .. }) => seed,
_ => panic!("expected warp"),
EffectKind::Filter(Filter::SourceWarp(warp)) => warp.seed,
_ => panic!("expected a library Warp filter"),
};
let before = seed(&session, original);
execute(&mut session, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
+9
View File
@@ -21,8 +21,17 @@ mod fill_patterns;
mod fill_projections;
mod fill_sampling;
mod fill_whole_material;
mod filter_card;
mod filter_colour;
mod filter_gradient;
mod filter_inputs;
mod filter_light;
mod filter_shape;
mod filter_simple;
mod filter_stylize;
mod filter_support;
mod filter_swap;
mod filter_transform;
mod filters;
mod folder_contents;
mod frame_selection;
+5 -6
View File
@@ -59,11 +59,10 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
"gradientMap",
"posterize",
"clamp",
"slopeBlur",
"blurSlope",
"matFinishGrind",
"highPass",
"edgeDetect",
"warpDirectional",
"grayscale",
"normalInvert",
"bevel",
@@ -110,7 +109,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap();
assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post)));
assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0));
assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels, .. }) if levels == 64.0));
// Material finishes also write roughness and height
let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect");
@@ -122,9 +121,9 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
// Exercise neighbourhood filters on curved geometry
for (fid, extra) in [
("blurDirectional", json!({"radius": 40, "angle": 45})),
("slopeBlur", json!({"radius": 30})),
("warp", json!({"intensity": 50})),
("warpDirectional", json!({"intensity": 50, "angle": 30})),
("blurSlope", json!({"intensity": 0.5, "divider": 1})),
("warp", json!({"intensity": 0.05})),
("warp", json!({"warpMode": "directional", "intensity": 0.05, "angle": 30})),
("highPass", json!({"radius": 20})),
("edgeDetect", json!({"width": 4})),
("bevel", json!({"width": 20})),
+17 -6
View File
@@ -1,4 +1,4 @@
//! The images a project reads beyond fill sources: a colour selection's ID map, the mask brush and its paths
//! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
@@ -27,11 +27,20 @@ fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId {
layer
}
/// [`selecting_layer`] with a Bevel Smooth that reads `input` as its Distance Map
fn layer_reading(session: &mut Session, id_map: &str, input: &str) -> LayerId {
let layer = selecting_layer(session, id_map);
let filter = execute(session, "effect.add.filter", &json!({"filter": "bevelSmooth", "target": "content"})).unwrap()["effect"].as_u64().unwrap();
execute(session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "image": input})).unwrap();
layer
}
#[test]
fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_path_read() {
fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mask_brush_and_a_path_read() {
let mut session = session();
let [id_map, path, brush, unused] = ["id.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap());
let layer = selecting_layer(&mut session, &id_map);
let [id_map, input, path, brush, unused] =
["id.png", "input.png", "path.png", "brush.png", "unused.png"].map(|name| session.import_resource_bytes(name, white_png()).unwrap());
let layer = layer_reading(&mut session, &id_map, &input);
// A path on the mask is painted with one image, then the brush moves on to another
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
@@ -45,16 +54,18 @@ fn removing_unused_resources_keeps_the_images_a_selection_the_mask_brush_and_a_p
}
#[test]
fn a_smart_material_carries_the_image_its_selection_reads() {
fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() {
let mut session = session();
let id_map = session.import_resource_bytes("id.png", white_png()).unwrap();
let layer = selecting_layer(&mut session, &id_map);
let input = session.import_resource_bytes("input.png", white_png()).unwrap();
let layer = layer_reading(&mut session, &id_map, &input);
let bytes = session.smart_material_bytes(layer, "Parts").unwrap();
let mut other = self::session();
other.add_smart_material_bytes(&bytes).unwrap();
assert!(other.doc.resources.contains_key(&id_map), "the ID map comes along");
assert!(other.doc.resources.contains_key(&input), "the filter input comes along");
}
#[test]
+175 -2
View File
@@ -269,6 +269,8 @@ fn panic_hunt() {
s.update();
}
}
hunt_filters(&hostile);
}
/// A 4 × 4 gray PNG, the image the hunted decals project
@@ -278,9 +280,9 @@ fn gray_png() -> Vec<u8> {
out
}
/// Frame edits and frame and Fill section resets on the fills they act on (a planar, a warp and a decal mask) meet hostile values without panicking; a refused edit changes nothing and adds no undo step
/// Frame edits, frame and Fill section resets and Transform filter settings on the fills they act on (a planar, a warp, a decal mask and a Transform filter) meet hostile values without panicking; a refused edit changes nothing and adds no undo step
#[test]
fn panic_hunt_frames() {
fn panic_hunt_frames_and_transforms() {
let mut s = session();
let image = s.import_resource_bytes("gray.png", gray_png()).unwrap();
let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap();
@@ -289,6 +291,7 @@ fn panic_hunt_frames() {
execute(&mut s, "layer.fill.projection", &json!({"layer": warp, "projection": "warp"})).unwrap();
let decal = execute(&mut s, "layer.add.decal", &json!({"image": image, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap();
let mask_effect = decal["maskEffect"].as_u64().unwrap();
let transform = execute(&mut s, "effect.add.filter", &json!({"filter": "transform", "target": "content"})).unwrap()["effect"].as_u64().unwrap();
s.update();
let hostile_values =
@@ -311,6 +314,15 @@ fn panic_hunt_frames() {
s.update();
}
}
let transform_keys = ["repeatMode", "flipMode", "scaling", "offset", "rotation", "tileSafeRotation"];
for key in transform_keys {
for value in &hostile_values {
let mut params = json!({"effect": transform});
params[key] = value.clone();
hunt_refused_changes_nothing(&mut s, "effect.set", &params);
}
}
}
/// Run `command` with `params` and render; refused, it must leave the project and the undo history as they were
@@ -322,6 +334,167 @@ fn hunt_refused_changes_nothing(s: &mut Session, command: &str, params: &Value)
s.update();
}
/// The number parameters library filters read, all set at once to one hostile value
const FILTER_NUMBER_KEYS: &[&str] = &[
"radius",
"intensity",
"amount",
"level",
"hue",
"saturation",
"lightness",
"contrast",
"luminosity",
"levels",
"min",
"max",
"position",
"range",
"offset",
"multiply",
"scale",
"angle",
"width",
"distance",
"smoothing",
"size",
"spread",
"opacity",
"blur",
"balance",
"quality",
"sourceBlur",
"sourceBalance",
"sourceContrast",
"sourceTiling",
"tolerance",
"softness",
"light",
"ambient",
"occlusion",
"azimuth",
"elevation",
"horizontalRotation",
"verticalRotation",
"exposure",
"heightIntensity",
"ambientOcclusion",
"specularOcclusion",
"pixelsAmount",
"curveOffset",
"curveShape",
"maskThreshold",
"distanceMapMultiplier",
"threshold",
"axisXOffset",
"axisYOffset",
"surfaceSize",
"heightDepth",
"normalIntensity",
"chroma",
"luma",
"red",
"green",
"blue",
"alpha",
"tensorSmoothness",
"anisotropy",
"sharpness",
"smoothness",
"rotation",
"scaling",
"diffuseCavity",
"specularAo",
"specularCavity",
"cavitySmoothness",
"edgesIntensity",
"edgesSmoothness",
"dielectricReflectance",
"heightToNormal",
];
/// The objects library filters read numbers from (Baked Lighting Stylized's two lights)
const FILTER_LIGHT_KEYS: &[&str] = &["light1", "light2"];
/// Every filter number parameter set to `number`, with seeds, switches and choices at their ends
fn filter_extreme(number: f64) -> Value {
let mut params = json!({"seed": u64::MAX, "wrap": true, "applyToAlpha": true, "invert": true, "directions": 4, "divider": 1000});
for key in FILTER_NUMBER_KEYS {
params[*key] = json!(number);
}
for key in FILTER_LIGHT_KEYS {
params[*key] = json!({"azimuth": number, "elevation": number, "intensity": number});
}
params
}
/// Every library filter added on the content and on a mask with `hostile` and extreme parameters, edited to extremes, and rendered; then swapped to the same way
fn hunt_filters(hostile: &[Value]) {
let extremes: Vec<Value> = [3.0e38, -3.0e38, 0.0].into_iter().map(filter_extreme).collect();
for def in texturecraft_engine::filter_lib::FILTERS {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap();
for target in ["content", "mask"] {
if target == "mask" {
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
}
for given in hostile.iter().chain(&extremes) {
let mut params = if given.is_object() { given.clone() } else { json!({}) };
params["filter"] = json!(def.id);
params["target"] = json!(target);
let added = execute(&mut s, "effect.add.filter", &params).ok().and_then(|reply| reply["effect"].as_u64());
s.update();
// Extreme values are clamped, not refused, so every filter meets them on the content
if target == "content" && extremes.contains(given) {
assert!(added.is_some(), "{} takes extreme values: {params}", def.id);
}
if let Some(effect) = added {
for edit in &extremes {
let mut edit = edit.clone();
edit["effect"] = json!(effect);
// Each accepted value reaches the compositor before the next edit replaces it
if execute(&mut s, "effect.set", &edit).is_ok() {
s.update();
}
}
}
}
}
}
hunt_filter_swaps(hostile, &extremes);
}
/// An empty filter effect on the content and on a mask swapped through `effect.set` to every library filter with each of `hostile` and `extremes`, and rendered
fn hunt_filter_swaps(hostile: &[Value], extremes: &[Value]) {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1], "roughness": 0.4})).unwrap();
for target in ["content", "mask"] {
if target == "mask" {
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
}
let added = execute(&mut s, "effect.add.filter", &json!({"filter": "none", "target": target})).unwrap();
let effect = added["effect"].as_u64().unwrap();
for def in texturecraft_engine::filter_lib::FILTERS {
for given in hostile.iter().chain(extremes) {
let mut params = if given.is_object() { given.clone() } else { json!({}) };
params["effect"] = json!(effect);
params["filter"] = json!(def.id);
// Emptied first, so each swap builds the filter anew rather than editing it in place
execute(&mut s, "effect.set", &json!({"effect": effect, "filter": "none"})).unwrap();
let _ = execute(&mut s, "effect.set", &params);
s.update();
}
}
}
}
/// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ
/// between the two, so every command that takes a colour says which form is which.
#[test]
+20 -137
View File
@@ -8,6 +8,7 @@
use std::f32::consts::{PI, TAU};
use rayon::prelude::*;
use texturecraft_compose::environment_sky;
use texturecraft_geom::glam::{Vec2, Vec3};
/// An equirect HDR image (linear RGB).
@@ -18,86 +19,9 @@ pub struct EnvImage {
pub data: Vec<[f32; 3]>,
}
pub use texturecraft_compose::environment_sky::{dir_of, radiance, sh_basis, uv_of};
pub use texturecraft_core::project::ENVIRONMENTS;
pub fn dir_of(u: f32, v: f32) -> Vec3 {
let (theta, phi) = (v * PI, u * TAU);
Vec3::new(theta.sin() * phi.cos(), theta.cos(), theta.sin() * phi.sin())
}
pub fn uv_of(d: Vec3) -> Vec2 {
let phi = d.z.atan2(d.x);
Vec2::new((phi / TAU).rem_euclid(1.0), d.y.clamp(-1.0, 1.0).acos() / PI)
}
/// A soft rectangular light: azimuth/elevation center (degrees), half sizes (degrees).
struct SoftBox {
az: f32,
el: f32,
hw: f32,
hh: f32,
color: Vec3,
}
impl SoftBox {
fn eval(&self, d: Vec3) -> Vec3 {
let el = d.y.clamp(-1.0, 1.0).asin().to_degrees();
let az = d.z.atan2(d.x).to_degrees();
let daz = ((az - self.az + 540.0).rem_euclid(360.0)) - 180.0;
let (x, y) = (daz.abs() / self.hw, (el - self.el).abs() / self.hh);
let e = |t: f32| 1.0 - smooth((t - 0.8) / 0.4);
self.color * e(x) * e(y)
}
}
fn smooth(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn sky(d: Vec3, zenith: Vec3, horizon: Vec3, ground: Vec3) -> Vec3 {
if d.y >= 0.0 { horizon.lerp(zenith, d.y.powf(0.6)) } else { horizon.lerp(ground, (-d.y).powf(0.25)) }
}
fn radiance(name: &str, d: Vec3) -> Vec3 {
match name {
"Studio Contrast" => {
let base = sky(d, Vec3::splat(0.04), Vec3::splat(0.03), Vec3::splat(0.01));
base + SoftBox { az: 35.0, el: 30.0, hw: 22.0, hh: 18.0, color: Vec3::new(14.0, 13.2, 12.0) }.eval(d)
+ SoftBox { az: -150.0, el: 40.0, hw: 6.0, hh: 30.0, color: Vec3::new(4.0, 4.4, 5.0) }.eval(d)
}
"Overcast" => {
let base = sky(d, Vec3::new(1.2, 1.25, 1.35), Vec3::new(0.95, 0.95, 0.95), Vec3::new(0.18, 0.2, 0.15));
base + SoftBox { az: 60.0, el: 55.0, hw: 40.0, hh: 25.0, color: Vec3::splat(0.6) }.eval(d)
}
"Sunset" => {
let base = sky(d, Vec3::new(0.15, 0.25, 0.55), Vec3::new(1.4, 0.65, 0.3), Vec3::new(0.08, 0.06, 0.05));
let sun_dir = dir_of(0.12, 0.47);
let sun = smooth((d.dot(sun_dir) - 0.9985) / 0.0012) * 120.0;
base + Vec3::new(1.0, 0.6, 0.3) * sun
}
"Warehouse" => {
let mut c = sky(d, Vec3::splat(0.25), Vec3::splat(0.18), Vec3::splat(0.06));
for k in 0..6 {
c += SoftBox { az: -150.0 + k as f32 * 60.0, el: 50.0, hw: 6.0, hh: 3.0, color: Vec3::new(9.0, 8.5, 7.5) }.eval(d);
}
c + SoftBox { az: 90.0, el: 5.0, hw: 30.0, hh: 12.0, color: Vec3::new(1.6, 1.8, 2.2) }.eval(d)
}
"Night" => {
let base = sky(d, Vec3::new(0.01, 0.015, 0.04), Vec3::new(0.03, 0.03, 0.06), Vec3::splat(0.005));
base + SoftBox { az: 20.0, el: 15.0, hw: 10.0, hh: 10.0, color: Vec3::new(0.4, 1.6, 4.0) }.eval(d)
+ SoftBox { az: -110.0, el: 10.0, hw: 12.0, hh: 8.0, color: Vec3::new(4.0, 0.8, 1.6) }.eval(d)
}
// "Studio Soft" (default)
_ => {
let base = sky(d, Vec3::new(0.5, 0.52, 0.56), Vec3::new(0.32, 0.32, 0.33), Vec3::new(0.08, 0.075, 0.07));
base + SoftBox { az: 40.0, el: 35.0, hw: 28.0, hh: 20.0, color: Vec3::new(5.5, 5.2, 4.8) }.eval(d)
+ SoftBox { az: -125.0, el: 20.0, hw: 35.0, hh: 22.0, color: Vec3::new(1.1, 1.25, 1.5) }.eval(d)
+ SoftBox { az: 175.0, el: 55.0, hw: 8.0, hh: 25.0, color: Vec3::new(3.0, 3.0, 3.0) }.eval(d)
}
}
}
/// Render a built-in environment (unknown names give the default studio).
pub fn environment(name: &str, width: u32) -> EnvImage {
let w = width.clamp(16, 4096);
@@ -132,16 +56,12 @@ impl EnvImage {
/// Box-downsample by 2.
pub fn half(&self) -> EnvImage {
let (w, h) = ((self.width / 2).max(1), (self.height / 2).max(1));
let mut data = vec![[0.0f32; 3]; (w * h) as usize];
data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| {
for (x, px) in row.iter_mut().enumerate() {
let (sx, sy) = (x as i64 * 2, y as i64 * 2);
let s = (self.get(sx, sy) + self.get(sx + 1, sy) + self.get(sx, sy + 1) + self.get(sx + 1, sy + 1)) * 0.25;
*px = s.to_array();
}
});
EnvImage { width: w, height: h, data }
Self::half_from(self.width, self.height, |x, y| self.get(i64::from(x), i64::from(y)))
}
fn half_from(width: u32, height: u32, texel: impl Fn(u32, u32) -> Vec3 + Sync) -> Self {
let (width, height, data) = environment_sky::half(width, height, texel);
Self { width, height, data: data.into_iter().map(|rgb| rgb.to_array()).collect() }
}
/// An imported equirect image (`rgba` row-major, top row first, sRGB-encoded when `srgb`) as
@@ -149,25 +69,27 @@ impl EnvImage {
/// range, and images larger than [`MAX_IMPORT_WIDTH`] are box-downsampled. None when the
/// pixel count does not match the size.
pub fn from_rgba(width: u32, height: u32, rgba: &[[f32; 4]], srgb: bool) -> Option<EnvImage> {
Self::from_rgb_pixels(width, height, rgba.par_iter().map(|&[r, g, b, _]| [r, g, b]), srgb)
Self::from_pixels(width, height, rgba, srgb)
}
/// An equirectangular linear RGB image with the same radiance and size limits as an RGBA import.
pub fn from_linear_rgb(width: u32, height: u32, rgb: &[[f32; 3]]) -> Option<EnvImage> {
Self::from_rgb_pixels(width, height, rgb.par_iter().copied(), false)
Self::from_pixels(width, height, rgb, false)
}
fn from_rgb_pixels(width: u32, height: u32, pixels: impl IndexedParallelIterator<Item = [f32; 3]>, srgb: bool) -> Option<EnvImage> {
fn from_pixels<const COMPONENTS: usize>(width: u32, height: u32, pixels: &[[f32; COMPONENTS]], srgb: bool) -> Option<EnvImage> {
if width == 0 || height == 0 || pixels.len() as u64 != u64::from(width) * u64::from(height) {
return None;
}
let lin = |v: f32| {
let v = if v.is_finite() { v.clamp(0.0, 65_000.0) } else { 0.0 };
if srgb { texturecraft_texel::srgb_to_linear(v.min(1.0)) } else { v }
let linear_rgb = |pixel: &[f32; COMPONENTS]| std::array::from_fn(|component| environment_sky::environment_linear(pixel[component], srgb));
let mut img = if width > MAX_IMPORT_WIDTH || height > MAX_IMPORT_WIDTH {
// Linearize only the texels that contribute to the first reduced level
Self::half_from(width, height, |x, y| Vec3::from(linear_rgb(&pixels[y as usize * width as usize + x as usize])))
} else {
Self { width, height, data: pixels.par_iter().map(linear_rgb).collect() }
};
let data = pixels.map(|pixel| pixel.map(lin)).collect();
let mut img = EnvImage { width, height, data };
while img.width > MAX_IMPORT_WIDTH || img.height > MAX_IMPORT_WIDTH {
img = img.half();
}
@@ -249,48 +171,9 @@ pub fn prefilter(env: &EnvImage, levels: u32) -> Vec<EnvImage> {
out
}
/// Diffuse irradiance as 9 SH coefficients (already convolved with the cosine lobe and divided
/// by π, so `Σ c·Y(n)` times albedo is the diffuse radiance).
/// Diffuse irradiance as 9 SH coefficients, convolved with the cosine lobe and divided by π, so `Σ c·Y(n)` times albedo is the diffuse radiance
pub fn sh9(env: &EnvImage) -> [[f32; 3]; 9] {
let mut src = env.clone();
while src.width > 128 {
src = src.half();
}
let (w, h) = (src.width, src.height);
let mut c = [Vec3::ZERO; 9];
for y in 0..h {
let theta = PI * (y as f32 + 0.5) / h as f32;
let dw = (TAU / w as f32) * (PI / h as f32) * theta.sin();
for x in 0..w {
let d = dir_of((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
// No firefly clamp: the projection integrates, so a bright sun lights diffuse fully.
let l = src.get(x as i64, y as i64) * dw;
for (k, ylm) in sh_basis(d).iter().enumerate() {
c[k] += l * *ylm;
}
}
}
let a = [PI, 2.0 * PI / 3.0, 2.0 * PI / 3.0, 2.0 * PI / 3.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0, PI / 4.0];
let mut out = [[0.0; 3]; 9];
for k in 0..9 {
out[k] = (c[k] * a[k] / PI).to_array();
}
out
}
pub fn sh_basis(d: Vec3) -> [f32; 9] {
let (x, y, z) = (d.x, d.y, d.z);
[
0.282_095,
0.488_603 * y,
0.488_603 * z,
0.488_603 * x,
1.092_548 * x * y,
1.092_548 * y * z,
0.315_392 * (3.0 * z * z - 1.0),
1.092_548 * x * z,
0.546_274 * (x * x - y * y),
]
environment_sky::sh9_averaged(env.width, env.height, |x, y| env.get(x as i64, y as i64))
}
#[cfg(test)]
+1 -1
View File
@@ -1319,7 +1319,7 @@ impl Renderer {
let img = match imported {
Some(img) => img,
None if !self.env_is_imported && self.env_name == name => return,
None => ibl::environment(name, 512),
None => ibl::environment(name, texturecraft_compose::environment_sky::VIEWPORT_WIDTH),
};
let levels = ibl::prefilter(&img, ENV_LEVELS);
+22
View File
@@ -84,3 +84,25 @@ fn reader_glyph(kind: &EffectKind) -> &'static str {
EffectKind::Fill { .. } | EffectKind::Material(_) => ic::PAINT_BUCKET,
}
}
#[cfg(test)]
mod tests {
use serde_json::{Value, json};
use texturecraft_engine::core::LayerId;
use texturecraft_engine::execute;
use super::*;
#[test]
fn a_reference_shows_the_icon_of_what_reads_the_anchor() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "layer.add.fill", &json!({"roughness": 0.5})).unwrap();
let anchor = execute(&mut session, "effect.add.anchor", &Value::Null).unwrap()["effect"].as_u64().unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
let filter = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "bevelSmooth"})).unwrap()["effect"].clone();
execute(&mut session, "layer.fill.set", &json!({"effect": filter, "input": "distanceMap", "anchor": anchor})).unwrap();
let glyphs: Vec<&str> = references(&session.doc.project, LayerId(anchor)).iter().map(|reference| reference.glyph).collect();
assert_eq!(glyphs, [ic::FUNNEL], "a filter reading the anchor shows the filter icon, not a fill's");
}
}
+4 -111
View File
@@ -6,9 +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, Effect, EffectKind, Filter, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source,
BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source,
};
use texturecraft_engine::filter_lib::scalar_params;
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
@@ -25,11 +24,6 @@ use crate::theme::{Tokens, caption};
use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit};
const FILTER_SWATCH_WIDTH: f32 = 36.0;
const FILTER_HINT_SIZE: f32 = 10.5;
/// The most colors `effect.set {colors}` takes for a gradient map
const MAX_GRADIENT_STOPS: usize = 16;
const TAG_COLORS: [Color32; 8] = [
Color32::from_rgb(0xc0, 0x40, 0x40),
Color32::from_rgb(0xd0, 0x80, 0x30),
@@ -3065,28 +3059,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option<u8> {
picked
}
/// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when
/// they changed.
fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool {
let mut changed = false;
ui.horizontal_wrapped(|ui| {
for (i, stop) in stops.iter_mut().enumerate() {
changed |= color_swatch(ui, &format!("{salt}_{i}"), stop, FILTER_SWATCH_WIDTH);
}
});
ui.horizontal(|ui| {
if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() {
stops.push(stops.last().copied().unwrap_or([1.0; 3]));
changed = true;
}
if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() {
stops.pop();
changed = true;
}
});
changed
}
/// The properties of effect `effect_id` of `layer`: each kind's own settings.
fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) {
let tokens = Tokens::get(ui.ctx());
@@ -3108,7 +3080,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]),
};
let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click());
let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::placed_fill_slot::SLOT_HEIGHT), Sense::click());
source_response.widget_info(|| egui::WidgetInfo {
current_text_value: Some(name.clone()),
..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale"))
@@ -3118,7 +3090,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
crate::resource_picker::toggle(&ctx, popup);
}
let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup);
crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name));
crate::placed_fill_slot::paint(ui, rect, (highlighted, source_response.has_focus()), (tr("Grayscale"), &name));
let current = crate::fill_material_panel::source_choice(&app.session, source);
let tabs = || crate::fill_material_panel::source_tabs(&app.session, &anchors, Color32::from_gray(204), false);
let picked = crate::resource_picker::show(&source_response, popup, &mut app.thumbs, Some(&current), current != SourceChoice::Uniform, tabs);
@@ -3220,7 +3192,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
tool_properties(app, ui);
}
}),
EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)),
EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter),
EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection),
EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => {
let settings = crate::compare_settings::CompareSettings {
@@ -3237,85 +3209,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe
}
}
/// The filter slot and the parameters of filter effect `id`
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) {
let tk = Tokens::get(ui.ctx());
let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| {
let mut params = json!({ "effect": id, "merge": merge });
params[key] = value;
app.run("effect.set", params);
};
crate::filter_slot::show(app, ui, id, filter);
if let Filter::Hsl { hue, .. } = filter {
let mut degrees = hue * 360.0;
if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) {
set(app, "hue", json!(degrees / 360.0), merge);
}
}
for (key, label, mut value, min, max) in scalar_params(filter) {
let decimals = if matches!(key, "seed" | "levels") {
0
} else if max - min > 10.0 {
1
} else {
2
};
if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) {
set(app, key, json!(value), merge);
}
}
match filter {
Filter::ColorBalance { shadows, midtones, highlights } => {
for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)]
{
ui.label(RichText::new(label).strong());
let mut balance = *rgb;
let mut edit = None;
for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) {
edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2));
}
if let Some(merge) = edit {
set(app, key, json!(balance), merge);
}
}
}
Filter::ReplaceColor { from, to, .. } => {
for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] {
let mut color = *rgb;
ui.horizontal(|ui| {
if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) {
set(app, key, json!(color), false);
}
ui.label(label);
});
}
ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
}
Filter::GradientMap { colors } => {
let mut stops = colors.clone();
if gradient_stops(ui, &format!("gradient_{id}"), &mut stops) {
set(app, "colors", json!(stops), false);
}
ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
}
Filter::Warp { .. }
| Filter::DirectionalBlur { .. }
| Filter::SlopeBlur { .. }
| Filter::DirectionalWarp { .. }
| Filter::HighPass { .. }
| Filter::EdgeDetect { .. }
| Filter::Bevel { .. }
| Filter::Mosaic { .. }
| Filter::Glow { .. } => {
ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
}
_ => {}
}
}
#[cfg(test)]
mod layer_layout_tests {
use super::*;
+6 -4
View File
@@ -233,9 +233,11 @@ pub(crate) fn source_card(
app.run("layer.fill.set", set(json!({"image": name})));
}
// Keep mode cards together by showing only Scale and Contrast
// Embedded procedural slots share the surrounding mode card
if in_card {
if let Source::Procedural { pattern, .. } = source {
if let Source::Uniform(value) = source {
uniform_rows(app, sheet, slot_of, value, &set);
} else if let Source::Procedural { pattern, .. } = source {
let mut edited = pattern.clone();
if let Some((key, value, merge)) = scale_and_contrast(sheet, &mut edited) {
let mut settings = json!({"procedural": pattern.kind.label(), "merge": merge});
@@ -426,8 +428,8 @@ fn procedural_rows(
let mut edited = pattern.clone();
let mut edit = scale_and_contrast(sheet, &mut edited);
// Only grayscale cards edit Balance and Seed here
let gray = matches!(slot_of, SourceSlot::Grayscale);
// Grayscale source cards show Balance and Seed alongside Scale and Contrast
let gray = matches!(slot_of, SourceSlot::Grayscale | SourceSlot::Input(_));
if gray {
edit = edit.or(balance_and_seed(sheet, &mut edited));
}
+35
View File
@@ -370,6 +370,41 @@ mod tests {
use super::*;
/// A repeating map far denser than the tiles drawn (Scaling 64 turned 45°) still fills the whole window, its far corner too
#[test]
fn a_dense_repeating_preview_leaves_no_bare_field() {
use texturecraft_engine::core::TileTransform;
let tokens = Tokens::for_brightness(crate::theme::Brightness::MediumDark);
let transform = TileTransform { scaling: [64.0, 64.0], rotation: 45.0, ..TileTransform::LIBRARY };
let rect = Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 100.0));
let ctx = egui::Context::default();
let output = ctx.run_ui(egui::RawInput::default(), |ui| lattice_preview(ui.painter(), rect, transform.affine(), true, &tokens));
// Whether a filled shape other than the bare field covers `point`
let covered = |point: Pos2| {
output.shapes.iter().any(|clipped| match &clipped.shape {
Shape::Rect(shape) => shape.fill != tokens.field && shape.fill != Color32::TRANSPARENT && shape.rect.contains(point),
Shape::Path(path) if path.fill != Color32::TRANSPARENT => {
let corners = &path.points;
let side = |index: usize| {
let (from, to) = (corners[index], corners[(index + 1) % corners.len()]);
(to - from).x * (point - from).y - (to - from).y * (point - from).x
};
let sides: Vec<f32> = (0..corners.len()).map(side).collect();
sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0)
}
_ => false,
})
};
for corner in [pos2(1.0, 1.0), pos2(99.0, 1.0), pos2(1.0, 99.0), pos2(99.0, 99.0)] {
assert!(covered(corner), "the preview fills {corner:?}");
}
// No renderer takes the uploads here
output.drop_without_applying_deltas();
}
/// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another
#[test]
fn the_ring_spaces_its_copies_as_the_engine_does() {
File diff suppressed because it is too large. Load diff
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more