mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-19 22:10:42 +01:00
Merge main into docs/roadmap-2026-11-02d
This commit is contained in:
commit
27251c8b4b
13 files changed
+355
-32
No files matched your search
@@ -1846,6 +1846,101 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Tiles [`effect_histogram`] samples at most (a million texels).
|
||||
const HISTOGRAM_TILES: usize = 256;
|
||||
|
||||
/// The tiles [`effect_histogram`] reads: an even sample of at most [`HISTOGRAM_TILES`], which
|
||||
/// keeps the cost flat up to 8K. The stride is odd: a power of two would divide the row length
|
||||
/// and sample the same few columns.
|
||||
fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> {
|
||||
let all = all_tiles(width, height);
|
||||
let stride = all.len().div_ceil(HISTOGRAM_TILES).max(1) | 1;
|
||||
all.into_iter().step_by(stride).collect()
|
||||
}
|
||||
|
||||
/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask
|
||||
/// below it, or (a content effect) the layer's `channel` below it where the layer has content,
|
||||
/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers
|
||||
/// (in an even sample of tiles on large sets); None for an unknown effect.
|
||||
pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option<Vec<u32>> {
|
||||
let (owner, _) = inp.project.effect(effect)?;
|
||||
let bins = bins.max(1);
|
||||
// Evaluate the layer forced visible, its mask enabled, cut just below the effect.
|
||||
let mut cut = inp.project.clone();
|
||||
let l = cut.layers.get_mut(&owner)?;
|
||||
l.visible = true;
|
||||
let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) {
|
||||
Some((m, k)) => {
|
||||
m.enabled = true;
|
||||
m.effects.truncate(k);
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let k = l.content_effects.iter().position(|e| e.id == effect)?;
|
||||
l.content_effects.truncate(k);
|
||||
false
|
||||
}
|
||||
};
|
||||
let cut_inp = Inputs { project: &cut, preview: None, ..*inp };
|
||||
let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height);
|
||||
// A field covers the bounding box of the tiles it is built for, which for a scattered sample
|
||||
// is the whole set: with a neighbourhood filter below, each tile gets its own.
|
||||
let probe = neighbourhood_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default());
|
||||
let shared = probe.is_empty().then_some(probe);
|
||||
let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1);
|
||||
let hist = tiles
|
||||
.par_iter()
|
||||
.map(|&(tx, ty)| {
|
||||
let own;
|
||||
let fields = match &shared {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
own = neighbourhood_fields(&cut_inp, &channels, &[(tx, ty)]);
|
||||
&own
|
||||
}
|
||||
};
|
||||
let mut h = vec![0u32; bins];
|
||||
// The mask is planned on its own: a layer with nothing drawn plans no node.
|
||||
let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None };
|
||||
let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) };
|
||||
let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c)));
|
||||
if mask.is_none() && content.is_none() {
|
||||
return h;
|
||||
}
|
||||
let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields));
|
||||
for (x, y, o) in tile_texels(inp.gbuf, tx, ty) {
|
||||
let mut tex = Texel::new(&cut_inp, x, y, o, 0.0);
|
||||
if !full.is_empty() {
|
||||
tex.anchors_below(&full, owner);
|
||||
}
|
||||
if let Some(m) = &mask {
|
||||
if let Some(b) = h.get_mut(bin(tex.mask(m))) {
|
||||
*b += 1;
|
||||
}
|
||||
} else if let Some((n, c)) = content
|
||||
&& let Some((v, _)) = tex.content(&n.content, c)
|
||||
{
|
||||
// As levels reads them (`per_unit`); normal maps pass through levels unchanged.
|
||||
let (vals, signed) = match c.kind {
|
||||
ChannelKind::Color => (&v[..], false),
|
||||
ChannelKind::Scalar => (&v[..1], false),
|
||||
ChannelKind::Signed => (&v[..1], true),
|
||||
ChannelKind::NormalMap => (&v[..0], false),
|
||||
};
|
||||
for x in vals {
|
||||
if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) {
|
||||
*b += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
h
|
||||
})
|
||||
.reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect());
|
||||
Some(hist)
|
||||
}
|
||||
|
||||
/// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data).
|
||||
pub type FlatTile = (Channel, (u32, u32), Vec<u16>);
|
||||
|
||||
@@ -1962,6 +2057,17 @@ mod tests {
|
||||
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_samples_spread_over_every_column() {
|
||||
assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole");
|
||||
for size in [2048, 4096, 8192] {
|
||||
let tiles = histogram_tiles(size, size);
|
||||
let columns: std::collections::BTreeSet<u32> = tiles.iter().map(|t| t.0).collect();
|
||||
assert!(tiles.len() <= HISTOGRAM_TILES, "{size}: {} tiles", tiles.len());
|
||||
assert!(columns.len() as u32 >= size / TILE / 2, "{size}: only {} columns", columns.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_stack_gives_channel_defaults() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -16,7 +16,7 @@ pub mod store;
|
||||
pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, tile_bytes};
|
||||
pub use eval::{
|
||||
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image,
|
||||
pad_tiles,
|
||||
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer,
|
||||
mask_image, pad_tiles,
|
||||
};
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
@@ -194,21 +194,8 @@ impl Session {
|
||||
/// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per
|
||||
/// channel over the set's covered tiles. None for folders or a set not ready.
|
||||
pub(crate) fn flatten(&self, ts: usize, id: LayerId) -> Option<Vec<texturecraft_compose::eval::FlatTile>> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect();
|
||||
let empty = Default::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
project: &self.doc.project,
|
||||
ts,
|
||||
mesh: &self.mesh,
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &self.doc.pixels,
|
||||
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
texturecraft_compose::flatten_layer(&inputs, id, &tiles)
|
||||
let tiles: Vec<(u32, u32)> = self.caches.get(ts)?.covered_tiles.iter().copied().collect();
|
||||
self.with_inputs(ts, |inp| texturecraft_compose::flatten_layer(inp, id, &tiles))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use texturecraft_core::{
|
||||
Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::layer_cmds::projection_from;
|
||||
use crate::session::StackTarget;
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
@@ -99,6 +99,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
set
|
||||
),
|
||||
cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect),
|
||||
cmd!(
|
||||
"effect.histogram",
|
||||
"Effect input histogram",
|
||||
[],
|
||||
None,
|
||||
"{effect, channel?: for content effects (default: the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1]}",
|
||||
always,
|
||||
histogram
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -373,6 +382,22 @@ fn effect_id(p: &Value, cmd: &str) -> Result<LayerId> {
|
||||
u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required"))
|
||||
}
|
||||
|
||||
/// The distribution of the values entering an effect (what a levels effect remaps).
|
||||
fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.histogram";
|
||||
let eid = effect_id(p, CMD)?;
|
||||
let (owner, _) = s.doc.project.effect(eid).ok_or_else(|| bad(CMD, format!("no effect {}", eid.0)))?;
|
||||
let l = s.doc.project.layer(owner)?;
|
||||
let content = l.content_effects.iter().any(|e| e.id == eid);
|
||||
let channel = match channel_param(CMD, p, "channel")? {
|
||||
Some(c) => c,
|
||||
None => l.channels.keys().next().copied().unwrap_or(Channel::BaseColor),
|
||||
};
|
||||
let bins = u64p(p, "bins").unwrap_or(64).clamp(2, 256) as usize;
|
||||
let counts = s.effect_histogram(eid, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?;
|
||||
Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) })
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(p, "effect.set")?;
|
||||
let blend = blend_param("effect.set", p, "blend")?;
|
||||
|
||||
@@ -65,6 +65,9 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05),
|
||||
m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32),
|
||||
m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25),
|
||||
m("platinum", "Platinum", METAL, [0.673, 0.637, 0.585], 1.0, 0.2),
|
||||
m("zinc", "Zinc", METAL, [0.664, 0.824, 0.85], 1.0, 0.38),
|
||||
m("cobalt", "Cobalt", METAL, [0.662, 0.655, 0.634], 1.0, 0.3),
|
||||
m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4),
|
||||
m("rust", "Rust", METAL, [0.3, 0.1, 0.03], 0.0, 0.85),
|
||||
// Woods.
|
||||
@@ -73,6 +76,7 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5),
|
||||
m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65),
|
||||
m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75),
|
||||
m("bark", "Bark", WOOD, [0.14, 0.1, 0.07], 0.0, 0.9),
|
||||
m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48),
|
||||
// Stone, masonry and earth.
|
||||
m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9),
|
||||
@@ -86,6 +90,8 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("slate", "Slate", STONE, [0.11, 0.115, 0.13], 0.0, 0.72),
|
||||
m("sandstone", "Sandstone", STONE, [0.52, 0.38, 0.23], 0.0, 0.9),
|
||||
m("terrazzo", "Terrazzo", STONE, [0.7, 0.69, 0.66], 0.0, 0.3),
|
||||
m("sand", "Sand", STONE, [0.52, 0.41, 0.26], 0.0, 0.95),
|
||||
m("mud", "Mud", STONE, [0.12, 0.08, 0.05], 0.0, 0.6),
|
||||
// Plastics, rubber, composites.
|
||||
m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16),
|
||||
m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6),
|
||||
@@ -102,12 +108,15 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08),
|
||||
m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03),
|
||||
m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45),
|
||||
m("ice", "Ice", GLASS, [0.72, 0.82, 0.88], 0.0, 0.12),
|
||||
m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4),
|
||||
// Organic.
|
||||
m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5),
|
||||
m("wax", "Candle Wax", ORGANIC, [0.8, 0.72, 0.55], 0.0, 0.35),
|
||||
m("cork", "Cork", ORGANIC, [0.36, 0.21, 0.1], 0.0, 0.85),
|
||||
m("paper", "Paper", ORGANIC, [0.82, 0.81, 0.77], 0.0, 0.92),
|
||||
m("snow", "Snow", ORGANIC, [0.85, 0.87, 0.9], 0.0, 0.6),
|
||||
m("bone", "Bone", ORGANIC, [0.7, 0.63, 0.5], 0.0, 0.55),
|
||||
// Smart materials.
|
||||
sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45),
|
||||
sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5),
|
||||
@@ -232,10 +241,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0));
|
||||
match m.id {
|
||||
// ---- Metals -------------------------------------------------------------------------
|
||||
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => {
|
||||
plain_metal(b, clouds_rough(7))
|
||||
}
|
||||
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum"
|
||||
| "cobalt" => plain_metal(b, clouds_rough(7)),
|
||||
"steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)),
|
||||
// Zinc plate: large crystalline spangles.
|
||||
"zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))),
|
||||
// Brushing lines run along X; the highlights stretch across them (a quarter turn).
|
||||
"steel_brushed_aniso" => one(
|
||||
b,
|
||||
@@ -275,6 +285,19 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
}
|
||||
// Stone chips in a pale binder, polished flat.
|
||||
"terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))),
|
||||
// Fine grains in soft wind ripples.
|
||||
"sand" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))),
|
||||
),
|
||||
// Glossy wet patches over rougher, drier mud.
|
||||
"mud" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 3.0, 29, 1.0, [0.05, 0.035, 0.02], [0.17, 0.12, 0.075]), gray(P::Grunge, 3.0, 29, 0.85, 0.2)),
|
||||
height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)),
|
||||
),
|
||||
),
|
||||
"cork" => {
|
||||
one(b, plus(dielectric(pat(P::Noise, 6.0, 17, 1.0, [0.25, 0.14, 0.06], [0.45, 0.28, 0.13]), u(0.85)), height(gray(P::Pores, 20.0, 17, -0.01, 0.0))))
|
||||
}
|
||||
@@ -310,6 +333,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
),
|
||||
),
|
||||
"plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))),
|
||||
// Dark, deep furrows between gray-brown ridges.
|
||||
"bark" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))),
|
||||
),
|
||||
"wood_painted" => one(
|
||||
b,
|
||||
plus(
|
||||
@@ -413,6 +441,27 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
"wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])),
|
||||
// ---- Glass (the Transmission channel; the base color tints the light going through) ----
|
||||
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])),
|
||||
// Clear with cloudy patches of trapped air.
|
||||
"ice" => one(
|
||||
b,
|
||||
plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]),
|
||||
),
|
||||
// Bright, rough and slightly translucent.
|
||||
"snow" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 4.0, 33, 1.0, [0.8, 0.82, 0.86], [0.88, 0.89, 0.9]), gray(P::Noise, 1.0, 33, 0.5, 0.7)),
|
||||
[(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))],
|
||||
),
|
||||
),
|
||||
// Porous, ivory to tan, with a little light under the surface.
|
||||
"bone" => one(
|
||||
b,
|
||||
plus(
|
||||
dielectric(pat(P::Clouds, 5.0, 35, 1.0, [0.58, 0.5, 0.37], m.base), clouds_rough(35)),
|
||||
[(ScatterWeight, u(0.3)), (Height, gray(P::Pores, 16.0, 35, -0.006, 0.0))],
|
||||
),
|
||||
),
|
||||
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])),
|
||||
// ---- Smart materials ----------------------------------------------------------------
|
||||
"steel_painted_worn" => {
|
||||
|
||||
@@ -773,12 +773,12 @@ impl Session {
|
||||
self.caches.get_mut(ts).map(|c| std::mem::take(&mut c.upload).into_iter().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask).
|
||||
pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
let (ts, _, _) = self.doc.project.locate(id)?;
|
||||
/// `f` on the compositor inputs of texture set `ts` (without a live stroke; None for a set
|
||||
/// not ready).
|
||||
pub(crate) fn with_inputs<R>(&self, ts: usize, f: impl FnOnce(&texturecraft_compose::Inputs) -> Option<R>) -> Option<R> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let empty = BakedMaps::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
f(&texturecraft_compose::Inputs {
|
||||
project: &self.doc.project,
|
||||
ts,
|
||||
mesh: &self.mesh,
|
||||
@@ -788,11 +788,24 @@ impl Session {
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
let gray = texturecraft_compose::mask_image(&inputs, id, size)?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask).
|
||||
pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
let (ts, _, _) = self.doc.project.locate(id)?;
|
||||
let gray = self.with_inputs(ts, |inp| texturecraft_compose::mask_image(inp, id, size))?;
|
||||
Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect())
|
||||
}
|
||||
|
||||
/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's
|
||||
/// mask, or for a content effect the layer's `channel` (None for an unknown effect).
|
||||
pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option<Vec<u32>> {
|
||||
let (owner, _) = self.doc.project.effect(effect)?;
|
||||
let (ts, _, _) = self.doc.project.locate(owner)?;
|
||||
self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins))
|
||||
}
|
||||
|
||||
pub fn baked(&self, ts: usize) -> Option<&BakedMaps> {
|
||||
self.doc.baked.get(&ts)
|
||||
}
|
||||
|
||||
@@ -111,3 +111,49 @@ fn painting_into_a_content_paint_effect() {
|
||||
assert!(s.doc.pixels.layer(LayerId(e), Channel::Roughness).is_none());
|
||||
assert!(center(&mut s, Channel::Roughness)[0] > 0.85);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_counts_what_an_effect_reads() {
|
||||
let mut s = session();
|
||||
let hist = |s: &mut Session, p: Value| {
|
||||
let r = execute(s, "effect.histogram", &p).unwrap();
|
||||
let bins: Vec<u64> = r["bins"].as_array().unwrap().iter().map(|b| b.as_u64().unwrap()).collect();
|
||||
(r["target"].as_str().unwrap().to_string(), bins)
|
||||
};
|
||||
// Only the bucket holding the value is filled.
|
||||
let one = |bins: &[u64], k: usize| bins.iter().enumerate().all(|(i, b)| (*b > 0) == (i == k));
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [0.25, 0.25, 0.25], "roughness": 0.75})).unwrap();
|
||||
let lv = id(execute(&mut s, "effect.add.levels", &json!({"target": "content", "inLow": 0.5})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
|
||||
let (target, bins) = hist(&mut s, json!({"effect": lv, "channel": "roughness", "bins": 4}));
|
||||
assert_eq!(target, "content");
|
||||
assert!(one(&bins, 3), "roughness 0.75: {bins:?}");
|
||||
// The effect itself and those above it are left out; the default channel is the first.
|
||||
let (_, bins) = hist(&mut s, json!({"effect": lv, "bins": 4}));
|
||||
assert!(one(&bins, 1), "base color 0.25, components pooled: {bins:?}");
|
||||
assert_eq!(bins.iter().sum::<u64>() % 3, 0);
|
||||
// A mask's levels reads the mask below it.
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.3})).unwrap();
|
||||
let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
let (target, bins) = hist(&mut s, json!({"effect": ml, "bins": 4}));
|
||||
assert_eq!(target, "mask");
|
||||
assert!(one(&bins, 1), "mask 0.3: {bins:?}");
|
||||
assert_eq!(hist(&mut s, json!({"effect": ml})).1.len(), 64);
|
||||
// Below a blur, every tile builds its own neighbourhood field; the texels counted stay the same.
|
||||
let texels: u64 = bins.iter().sum();
|
||||
execute(&mut s, "effect.remove", &json!({"effect": ml})).unwrap();
|
||||
execute(&mut s, "effect.add.filter", &json!({"target": "mask", "filter": "blur", "radius": 4})).unwrap();
|
||||
let ml = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
let (_, blurred) = hist(&mut s, json!({"effect": ml, "bins": 4}));
|
||||
assert_eq!(blurred.iter().sum::<u64>(), texels);
|
||||
assert_eq!(blurred.iter().enumerate().max_by_key(|(_, b)| **b).map(|(i, _)| i), Some(1), "{blurred:?}");
|
||||
// A paint layer with nothing painted yet still has its mask.
|
||||
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
|
||||
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"target": "mask", "value": 0.6})).unwrap();
|
||||
let pl = id(execute(&mut s, "effect.add.levels", &json!({"target": "mask"})).unwrap(), "effect");
|
||||
assert!(one(&hist(&mut s, json!({"effect": pl, "bins": 4})).1, 2), "an empty paint layer's mask");
|
||||
assert!(execute(&mut s, "effect.histogram", &json!({"effect": 999_999})).is_err());
|
||||
assert!(execute(&mut s, "effect.histogram", &json!({"effect": lv, "channel": "nope"})).is_err());
|
||||
}
|
||||
@@ -16,7 +16,7 @@ use crate::i18n::{n_, tr, trf};
|
||||
use crate::shelf::{Asset, ShelfDrag};
|
||||
use crate::state::PropsTab;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit};
|
||||
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit};
|
||||
|
||||
const TAG_COLORS: [Color32; 8] = [
|
||||
Color32::from_rgb(0xc0, 0x40, 0x40),
|
||||
@@ -1582,6 +1582,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
}
|
||||
EffectKind::Levels(l) => {
|
||||
ui.label(caption(tr("Levels")));
|
||||
levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high));
|
||||
let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high];
|
||||
let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")];
|
||||
let mut done = false;
|
||||
@@ -1664,6 +1665,38 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel
|
||||
/// picked here), with the input range marked. Recomputed after a document change once no
|
||||
/// pointer button is held, so dragging a slider keeps the last one.
|
||||
fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) {
|
||||
let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor);
|
||||
if layer.content_effects.iter().any(|e| e.id == eid) {
|
||||
let pick = egui::Id::unique(("levels_channel", eid.0));
|
||||
let chans: Vec<Channel> = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect();
|
||||
channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel);
|
||||
combo(ui, tr("Channel"), tr(channel.label()), |ui| {
|
||||
for c in chans {
|
||||
if ui.selectable_label(c == channel, tr(c.label())).clicked() {
|
||||
ui.data_mut(|d| d.insert_temp(pick, c));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let key = egui::Id::unique(("levels_histogram", eid.0, channel));
|
||||
let rev = app.session.revision;
|
||||
let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc<Vec<u32>>)>(key)) {
|
||||
Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h),
|
||||
_ => app.session.effect_histogram(eid, channel, 64).map(|h| {
|
||||
let h = std::sync::Arc::new(h);
|
||||
ui.data_mut(|d| d.insert_temp(key, (rev, h.clone())));
|
||||
h
|
||||
}),
|
||||
};
|
||||
if let Some(counts) = counts {
|
||||
histogram(ui, &counts, range);
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of filter effect `id`.
|
||||
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
|
||||
@@ -105,6 +105,31 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive<f32>, y: f32, t:
|
||||
p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring));
|
||||
}
|
||||
|
||||
/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well
|
||||
/// the width of the panel, the part of 0..1 outside `range` dimmed.
|
||||
pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover());
|
||||
let p = ui.painter_at(rect);
|
||||
p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
|
||||
let inner = rect.shrink(3.0);
|
||||
let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
|
||||
let w = inner.width() / counts.len().max(1) as f32;
|
||||
for (i, c) in counts.iter().enumerate() {
|
||||
let h = inner.height() * *c as f32 / max;
|
||||
let x = inner.left() + i as f32 * w;
|
||||
p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim);
|
||||
}
|
||||
let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0);
|
||||
let shade = tk.field.gamma_multiply(0.7);
|
||||
p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade);
|
||||
p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade);
|
||||
for t in [range.0, range.1] {
|
||||
p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent));
|
||||
}
|
||||
resp
|
||||
}
|
||||
|
||||
/// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel.
|
||||
pub fn elided(painter: &egui::Painter, text: impl Into<String>, size: f32, color: Color32, max_width: f32) -> std::sync::Arc<egui::Galley> {
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged
|
||||
//! or clicked to.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use egui_kittest::kittest::{Queryable, by};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{EffectKind, LayerId};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
@@ -50,6 +51,28 @@ fn dragging_the_effect_opacity_applies_it() {
|
||||
assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect));
|
||||
}
|
||||
|
||||
/// The combo box in the row of the "Channel" label.
|
||||
fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> {
|
||||
let row = h.get_by_label("Channel").rect().center().y;
|
||||
h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap()
|
||||
}
|
||||
|
||||
/// A content levels effect offers a channel for its histogram; picking one keeps it selected.
|
||||
#[test]
|
||||
fn content_levels_pick_the_histogram_channel() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap();
|
||||
texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap();
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.run_steps(4);
|
||||
assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel");
|
||||
channel_picker(&h).click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Roughness").click();
|
||||
h.run_steps(3);
|
||||
assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicking_the_effect_opacity_applies_it() {
|
||||
let (mut h, effect) = harness();
|
||||
|
||||
@@ -61,4 +61,16 @@ fn window_snapshots() {
|
||||
h.state_mut().ui.windows.export = false;
|
||||
h.state_mut().ui.windows.settings = true;
|
||||
save(&mut h, &dir, "window-settings");
|
||||
h.state_mut().ui.windows.settings = false;
|
||||
// A mask's levels effect over clouds: the histogram in Properties.
|
||||
let s = &mut h.state_mut().session;
|
||||
for (id, p) in [
|
||||
("layer.add.fill", serde_json::json!({"color": [0.8, 0.3, 0.1]})),
|
||||
("mask.add.black", serde_json::Value::Null),
|
||||
("effect.add.fill", serde_json::json!({"target": "mask", "procedural": "clouds"})),
|
||||
("effect.add.levels", serde_json::json!({"target": "mask", "inLow": 0.3, "inHigh": 0.8})),
|
||||
] {
|
||||
texturecraft_engine::execute(s, id, &p).unwrap();
|
||||
}
|
||||
save(&mut h, &dir, "properties-levels");
|
||||
}
|
||||
@@ -13,6 +13,8 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f
|
||||
Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke`
|
||||
behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and
|
||||
painted tile count, so an agent can verify its work without a screenshot.
|
||||
`effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels
|
||||
effect's input), so an agent can pick its input range from the data.
|
||||
|
||||
## Control channel (desktop app)
|
||||
|
||||
|
||||
+5
-3
@@ -36,7 +36,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
contrast/luminosity, color balance, gradient map, posterize, clamp, invert, threshold,
|
||||
grayscale, replace color, edge detect, normal invert, baked lighting, blur, directional and
|
||||
slope blur, sharpen, high pass, bevel, glow, warp, directional warp, mosaic and four material
|
||||
finishes), fills and paint.
|
||||
finishes), fills and paint. **Levels** shows a histogram of what it reads (the mask below it,
|
||||
or a content channel you pick) with its input range marked.
|
||||
**Anchor points** record the stack at a layer so masks and fills higher up can react to it.
|
||||
- **Masks** with a white or black background and a stack of effects: painted strokes, fills,
|
||||
**mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction
|
||||
@@ -46,8 +47,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
grain, bricks, fabric weave, twill, leather grain, marble veins, Voronoi, paint chips…) or your own
|
||||
**images**, through UV, tri-planar, planar, spherical, cylindrical or decal projection.
|
||||
Alt+click a material channel (of a fill or the brush) to keep that channel alone.
|
||||
- **54 materials** (metals from measured reflectance, car paint, brushed anisotropic steel,
|
||||
velvet, skin, wax, glass, woods, stone, plastics, fabric, leather, ceramic, rust, cork, paper), **21 smart
|
||||
- **63 materials** (metals from measured reflectance, car paint, brushed anisotropic steel,
|
||||
velvet, skin, wax, glass, ice, woods, bark, stone, sand, mud, snow, bone, plastics, fabric,
|
||||
leather, ceramic, rust, cork, paper), **21 smart
|
||||
materials** (rusted iron, worn paint, oxidized copper, bronze statue, weathered wood, mossy
|
||||
brick and stone, sun-faded paint…) and **18 smart masks**, all procedural, so they work at any
|
||||
resolution. Drag them from the tabbed, searchable shelf onto the layer stack or straight onto
|
||||
|
||||
Reference in new issue
Block a user