Masks: Mask Fill with a fill layer's Properties and the Grayscale paint tab

This commit is contained in:
Rebornim committed 2026-11-22 05:30:03 +00:00
1 parent 4c8cd40c3d
commit ef3ab03243
6 files changed
+683 -81

No files matched your search

+221 -81
View File
@@ -2,12 +2,14 @@
use serde_json::{Value, json};
use texturecraft_core::{
BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask,
MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source,
BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator,
GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source,
};
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, projection_from_fields};
use crate::mask_owner::MaskOwner;
use crate::session::StackTarget;
use crate::{EngineError, Result, Session, cmd};
@@ -20,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add mask with color selection",
["Layers", "Mask"],
None,
"{layer?, color?: ID color as [r,g,b] linear or \"#rrggbb\" sRGB, tolerance?}",
"{layer?, color?: a first ID color as [r,g,b] linear or \"#rrggbb\" sRGB (default: none, pick them with effect.colorSelection.pick), tolerance?} → {effect} (in the layer's mask, a new black one if it has none; selected)",
has_layer,
add_color_mask
),
@@ -58,7 +60,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add levels",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, inLow?, inHigh?, gamma?, outLow?, outHigh?}",
"{layer?, target?: mask|content, name?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?: the one content channel it remaps (default baseColor; not normal maps, not on a mask), clamp?: values past the input handles stop at the output ends (default false)}",
has_layer,
add_levels
),
@@ -76,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add compare mask",
["Layers", "Effects"],
None,
"{layer?, name?, op?: lesser|within|greater, value?, tolerance?}",
"{layer?, name?, left?: layersBelow|thisLayer|thisMask|constant (default thisLayer), op?: lesser|within|greater (default greater), right? (default layersBelow), compareChannel? (default height), value?: the constant, tolerance?, hardness? (default 0.9)}",
has_layer,
add_compare
),
@@ -85,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add anchor point",
["Layers", "Effects"],
None,
"{layer?, target?: content|mask (content), name?} (on the content it records the stack up to this layer, in a mask the mask value at that point; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})",
"{layer?, target?: content|mask (default content), name? (default the layer's name, \"<layer> mask\" in a mask)} (on the content it records the stack up to this layer, in a mask the mask value at that point: every channel reads that gray; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})",
has_layer,
add_anchor
),
@@ -114,7 +116,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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]}",
"{effect, channel?: for content effects (default: the channel a levels effect remaps, else the layer's first channel), bins?: 2..256 (64)} → {target: mask|content, channel?, bins: [count per bucket over 0..1], luminance?, components?: [red, green, blue] (a color channel), compare?: {left, right} (a compare mask: what each side reads)}",
always,
histogram
),
@@ -141,16 +143,21 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result<Value> {
}
fn add_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]);
push_own_mask_effect(s, p, color_selection("mask.add.colorSelection", p)?, "Add mask with color selection", |_| Ok(()))
}
/// A colour selection with the `color` and `tolerance` params of command `cmd`
pub(crate) fn color_selection(cmd: &str, p: &Value) -> Result<EffectKind> {
let colors: Vec<[f32; 3]> = color_param(cmd, p, "color")?.into_iter().collect();
let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0);
with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| {
let eid = s.doc.project.alloc_id();
let l = s.doc.project.layer_mut(s.doc.project.mask_owner(id))?;
let m = l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black));
m.effects.push(Effect::new(eid, EffectKind::ColorSelection { colors: vec![color], tolerance }));
Ok(())
})?;
Ok(Value::Null)
Ok(EffectKind::ColorSelection(ColorSelection::new(colors, tolerance)))
}
/// `p` aimed at the layer's mask, whatever `target` it names
pub(crate) fn mask_target(p: &Value) -> Value {
let mut params = p.as_object().cloned().unwrap_or_default();
params.insert("target".into(), json!("mask"));
Value::Object(params)
}
/// The mask layer `id` draws with (an instance's source's unless it has its own).
@@ -232,38 +239,72 @@ fn name_param(p: &Value) -> Option<&str> {
strp(p, "name").filter(|n| !n.trim().is_empty() && n.chars().count() <= 256)
}
/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with
/// `target: "content"` or a content-only effect, to its content stack.
/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with `target: "content"` or a content-only effect, to its content stack
fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -> Result<Value> {
let label = format!("Add {}", kind.name().to_ascii_lowercase());
push_effect_as(s, p, kind, blend, &label)
}
/// [`push_effect`] as the undo step `label`
pub(crate) fn push_effect_as(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode, label: &str) -> Result<Value> {
push_effect_in(s, p, kind, blend, label, |_| Ok(()), MaskOwner::Shared)
}
/// An Add mask item's effect, `first` made in the same undo step: it goes in the layer's own mask, so an instance without one gets its own instead of changing its source's
pub(crate) fn push_own_mask_effect(s: &mut Session, p: &Value, kind: EffectKind, label: &str, first: impl FnOnce(&mut Session) -> Result<()>) -> Result<Value> {
push_effect_in(s, &mask_target(p), kind, BlendMode::Normal, label, first, MaskOwner::Own)
}
/// [`push_effect_as`] into `owner`'s mask, making the change `first` in the same undo step before adding the effect
fn push_effect_in(
s: &mut Session,
p: &Value,
mut kind: EffectKind,
blend: BlendMode,
label: &str,
first: impl FnOnce(&mut Session) -> Result<()>,
owner: MaskOwner,
) -> Result<Value> {
let content = kind.content_only() == Some(true) || content_target(p, "effect.add")?;
if kind.content_only().is_some_and(|c| c != content) {
if kind.content_only().is_some_and(|content_only| content_only != content) {
return Err(bad("effect.add", format!("{} effects go on masks, not on layer content", kind.name())));
}
let label = format!("Add {}", kind.name().to_ascii_lowercase());
let eid = with_mask(s, p, "effect.add", &label, |s, id| {
let eid = s.doc.project.alloc_id();
if let EffectKind::Levels(levels) = &mut kind {
levels_target(levels, content)?;
}
let new_effect = with_mask(s, p, "effect.add", label, |s, id| {
first(s)?;
let new_effect = s.doc.project.alloc_id();
// An instance's content and inherited mask belong to its source
let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) };
let l = s.doc.project.layer_mut(id)?;
let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
let mut e = Effect::new(eid, kind);
e.blend = blend;
if let Some(n) = name_param(p) {
e.name = n.to_string();
// An instance's content and (unless it has its own) mask belong to its source
let id = match (content, owner) {
(true, _) => s.doc.project.content_layer(id).map_or(id, |source| source.id),
(false, MaskOwner::Own) => id,
(false, MaskOwner::Shared) => s.doc.project.mask_owner(id),
};
let layer = s.doc.project.layer_mut(id)?;
let background = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. } | EffectKind::ColorSelection(_)) {
MaskBackground::Black
} else {
MaskBackground::White
};
let mut effect = Effect::new(new_effect, kind);
effect.blend = blend;
if let Some(name) = name_param(p) {
effect.name = name.to_string();
}
if !content {
l.mask.get_or_insert_with(|| Mask::new(bg)).effects.push(e);
} else if l.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", l.name)));
layer.mask.get_or_insert_with(|| Mask::new(background)).effects.push(effect);
} else if layer.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", layer.name)));
} else {
l.content_effects.push(e);
layer.content_effects.push(effect);
}
s.target = StackTarget::Effect(eid);
Ok(eid)
s.target = StackTarget::Effect(new_effect);
Ok(new_effect)
})?;
Ok(json!({ "effect": eid.0 }))
Ok(json!({ "effect": new_effect.0 }))
}
/// A source reading anchor point `anchor` for layer `reader`: the anchor must sit on a layer
@@ -409,12 +450,18 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S
Ok(weights)
}
/// An anchor point on the layer content by default, preserving previous placement, or in its mask with `target: "mask"`.
/// An anchor point on the layer content by default, preserving previous placement, or in its mask with `target: "mask"`; named after the layer ("<layer> mask" in a mask) unless given a name
fn add_anchor(session: &mut Session, params: &Value) -> Result<Value> {
// Params may be null or an object without a target: both default to the content
let mut params = params.as_object().cloned().unwrap_or_default();
params.entry("target").or_insert_with(|| json!("content"));
push_effect(session, &Value::Object(params), EffectKind::Anchor, BlendMode::Normal)
let content = strp(params, "target").is_none() || content_target(params, "effect.add.anchor")?;
let mut fields = params.as_object().cloned().unwrap_or_default();
fields.insert("target".into(), json!(if content { "content" } else { "mask" }));
if name_param(params).is_none() {
let layer = session.doc.project.layer(layer_param(session, "effect.add.anchor", params)?)?;
let name = if content { layer.name.clone() } else { format!("{} mask", layer.name) };
fields.insert("name".into(), json!(name));
}
push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal)
}
/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer
@@ -493,24 +540,55 @@ fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
push_effect(session, params, EffectKind::Generator(generator), blend)
}
pub(crate) fn levels_from(p: &Value, l: &mut Levels) {
for (k, slot) in [("inLow", &mut l.in_low), ("inHigh", &mut l.in_high), ("gamma", &mut l.gamma), ("outLow", &mut l.out_low), ("outHigh", &mut l.out_high)] {
if let Some(v) = f32p(p, k) {
*slot = if k == "gamma" { v.clamp(0.01, 10.0) } else { v.clamp(0.0, 1.0) };
pub(crate) fn levels_from(cmd: &str, p: &Value, levels: &mut Levels) -> Result<()> {
let slots = [
("inLow", &mut levels.in_low),
("inHigh", &mut levels.in_high),
("gamma", &mut levels.gamma),
("outLow", &mut levels.out_low),
("outHigh", &mut levels.out_high),
];
for (key, slot) in slots {
if let Some(value) = f32p(p, key) {
let range = if key == "gamma" { Levels::GAMMA_RANGE } else { 0.0..=1.0 };
*slot = value.clamp(*range.start(), *range.end());
}
}
if let Some(clamp) = boolp(p, "clamp") {
levels.clamp = clamp;
}
match channel_param(cmd, p, "affects")? {
// Levels pass normal maps through unchanged (`per_unit`)
Some(channel) if channel.kind() == ChannelKind::NormalMap => Err(bad(cmd, format!("levels cannot remap `{}`, a normal map", channel.id()))),
Some(channel) => {
levels.affects = Some(channel);
Ok(())
}
None => Ok(()),
}
}
/// A levels effect added to a mask remaps its one value; on the content it remaps Base color unless told otherwise
fn levels_target(levels: &mut Levels, content: bool) -> Result<()> {
if content {
levels.affects.get_or_insert(Channel::BaseColor);
} else if levels.affects.is_some() {
return Err(bad("effect.add", "a mask's levels remap its one value: leave out `affects`"));
}
Ok(())
}
fn add_levels(s: &mut Session, p: &Value) -> Result<Value> {
let mut l = Levels::default();
levels_from(p, &mut l);
push_effect(s, p, EffectKind::Levels(l), BlendMode::Normal)
let mut levels = Levels::default();
levels_from("effect.add.levels", p, &mut levels)?;
push_effect(s, p, EffectKind::Levels(levels), BlendMode::Normal)
}
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)?;
// Library filters are named after their shelf entry (material finishes are fill effects).
// Library filters are named after their shelf entry (material finishes are fill effects)
let mut p = p.clone();
if name_param(&p).is_none()
&& let (Some(d), Some(o)) = (crate::filter_lib::find(id), p.as_object_mut())
@@ -521,18 +599,56 @@ fn add_filter(s: &mut Session, p: &Value) -> Result<Value> {
}
fn add_compare(s: &mut Session, p: &Value) -> Result<Value> {
let op = match strp(p, "op").unwrap_or("greater") {
"lesser" | "less" => CompareOp::LesserThan,
"within" => CompareOp::WithinTolerance,
"greater" => CompareOp::GreaterThan,
other => return Err(bad("effect.add.compare", format!("unknown op `{other}`"))),
};
let kind =
EffectKind::Compare { op, value: f32p(p, "value").unwrap_or(0.5).clamp(0.0, 1.0), tolerance: f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0) };
let mut kind = new_compare();
compare_from("effect.add.compare", p, &mut kind)?;
push_effect(s, p, kind, BlendMode::Normal)
}
/// The `effect` param, or the selected effect.
/// A new compare mask: this layer's height over the layers below it, hardness 0.9
pub(crate) fn new_compare() -> EffectKind {
EffectKind::Compare {
op: CompareOp::GreaterThan,
value: 0.5,
tolerance: 0.1,
left: CompareSource::ThisLayer,
right: CompareSource::LayersBelow,
channel: Channel::Height,
hardness: 0.9,
}
}
/// Apply the compare parameters of `p` to `kind` (a compare effect)
fn compare_from(cmd: &str, p: &Value, kind: &mut EffectKind) -> Result<()> {
let EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } = kind else { return Ok(()) };
let named_source = |key: &str| -> Result<Option<CompareSource>> {
match strp(p, key) {
None => Ok(None),
Some(id) => CompareSource::from_id(id)
.map(Some)
.ok_or_else(|| bad(cmd, format!("unknown {key} source `{id}` (layersBelow, thisLayer, thisMask, constant)"))),
}
};
if let Some(id) = strp(p, "op") {
*op = CompareOp::from_id(id).ok_or_else(|| bad(cmd, format!("unknown op `{id}`")))?;
}
if let Some(source) = named_source("left")? {
*left = source;
}
if let Some(source) = named_source("right")? {
*right = source;
}
if let Some(compared) = channel_param(cmd, p, "compareChannel")? {
*channel = compared;
}
for (key, slot) in [("value", value), ("tolerance", tolerance), ("hardness", hardness)] {
if let Some(number) = f32p(p, key) {
*slot = number.clamp(0.0, 1.0);
}
}
Ok(())
}
/// The `effect` param, or the selected effect
pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result<LayerId> {
match (u64p(p, "effect"), s.target) {
(Some(e), _) => Ok(LayerId(e)),
@@ -541,20 +657,43 @@ pub(crate) fn effect_id(s: &Session, p: &Value, cmd: &str) -> Result<LayerId> {
}
}
/// The distribution of the values entering an effect (what a levels effect remaps).
/// Histogram bins when the call names none
const DEFAULT_HISTOGRAM_BINS: u64 = 64;
/// The fewest and most histogram bins a call takes
const HISTOGRAM_BINS_RANGE: (u64, u64) = (2, 256);
/// 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(s, 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 effect = effect_id(s, p, CMD)?;
let (owner, found) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
let remapped = match &found.kind {
EffectKind::Levels(levels) => levels.affects,
_ => None,
};
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}) })
let layer = s.doc.project.layer(owner)?;
let content = layer.content_effects.iter().any(|candidate| candidate.id == effect);
let channel = match channel_param(CMD, p, "channel")? {
Some(channel) => channel,
None => remapped.or_else(|| layer.channels.keys().next().copied()).unwrap_or(Channel::BaseColor),
};
let (fewest_bins, most_bins) = HISTOGRAM_BINS_RANGE;
let bins = u64p(p, "bins").unwrap_or(DEFAULT_HISTOGRAM_BINS).clamp(fewest_bins, most_bins) as usize;
let counts = s.effect_histogram(effect, channel, bins).ok_or_else(|| bad(CMD, "the texture set is not ready"))?;
if !content {
let mut out = json!({"target": "mask", "bins": counts.all});
if let Some([left, right]) = s.compare_histograms(effect, bins) {
out["compare"] = json!({"left": left, "right": right});
}
return Ok(out);
}
let mut out = json!({"target": "content", "channel": channel.id(), "bins": counts.all, "luminance": counts.luminance});
if !counts.components.is_empty() {
out["components"] = json!(counts.components);
}
Ok(out)
}
/// Edit visibility, blending, name, effect parameters, or a filter's type
@@ -569,6 +708,15 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))
})
.transpose()?;
let channel = channel_param(CMD, params, "channel")?;
let on_mask = crate::effect_blending_cmds::on_mask(&session.doc.project, effect);
if channel.is_some() && on_mask {
return Err(bad(CMD, "a mask effect blends one channel: leave out `channel`"));
}
if on_mask && params.get("affects").is_some() {
return Err(bad(CMD, "a mask's levels remap its one value: leave out `affects`"));
}
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
let anchor = match session.doc.project.effect(effect) {
@@ -614,6 +762,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
None => None,
};
let swaps_filter = swapped.is_some();
let id_map = crate::color_selection_cmds::id_map_param(session, params)?;
let mesh = session.mesh.clone();
session.edit("Edit effect", |session| {
@@ -630,12 +779,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(visible) = boolp(params, "visible") {
edited.visible = visible;
}
if let Some(blend) = blend {
edited.blend = blend;
}
if let Some(opacity) = f32p(params, "opacity") {
edited.opacity = opacity.clamp(0.0, 1.0);
}
crate::effect_blending_cmds::set_blending(edited, channel, blend, f32p(params, "opacity"));
if let Some(name) = name_param(params) {
edited.name = name.to_string();
}
@@ -665,7 +809,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
}
}
_ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")),
EffectKind::Levels(levels) => levels_from(params, levels),
EffectKind::Levels(levels) => levels_from(CMD, params, levels)?,
// The swapped filter was built with the parameters already
EffectKind::Filter(_) if swaps_filter => {}
@@ -698,12 +842,8 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
// Preserve projection fields that the edit does not supply
*projection = projection_from(&placement, CMD, Some(&*projection), || crate::warp_cmds::fitted_frame(&mesh))?;
}
EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?,
EffectKind::Compare { tolerance, .. } => {
if let Some(value) = f32p(params, "tolerance") {
*tolerance = value.clamp(0.0, 1.0);
}
}
EffectKind::ColorSelection(selection) => crate::color_selection_cmds::apply_params(params, selection, id_map)?,
kind @ EffectKind::Compare { .. } => compare_from(CMD, params, kind)?,
_ => {}
}
+164
View File
@@ -0,0 +1,164 @@
//! A mask fill effect edited through the `layer.fill.*` commands like any fill: its one grayscale source, its projection and its symmetry
use serde_json::{Value, json};
use texturecraft_engine::core::{EffectKind, LayerId, OutputResolution, Procedural, ProceduralKind, Projection, Source};
use texturecraft_engine::fill_alpha::resource_name;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::paint::alphas;
use texturecraft_engine::{Session, execute};
/// A paint layer whose mask holds one fill effect, and that effect
fn mask_fill() -> (Session, LayerId, LayerId) {
mask_fill_on(128)
}
/// [`mask_fill`] on a texture set `size` texels across
fn mask_fill_on(size: u32) -> (Session, LayerId, LayerId) {
let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, size).unwrap();
let layer = LayerId(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap());
let effect = LayerId(execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap());
(s, layer, effect)
}
fn source(s: &Session, effect: LayerId) -> Source {
match &s.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Fill { source, .. } => source.clone(),
other => panic!("not a mask fill: {other:?}"),
}
}
fn projection(s: &Session, effect: LayerId) -> Projection {
match &s.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Fill { projection, .. } => projection.clone(),
other => panic!("not a mask fill: {other:?}"),
}
}
/// Mask values along the texture's diagonal
fn mask_line(s: &Session, layer: LayerId) -> Vec<f32> {
let texels: Vec<(u32, u32)> = (0..16).map(|i| (i * 8 + 3, i * 8 + 5)).collect();
s.mask_at(layer, &texels).unwrap()
}
#[test]
fn a_mask_fill_takes_a_procedural_an_image_an_alpha_or_a_value_as_its_one_grayscale_source() {
let (mut s, layer, effect) = mask_fill();
let kind = ProceduralKind::ALL[0];
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "scale": 4.0})).unwrap();
let Source::Procedural { pattern, low, high, .. } = source(&s, effect) else { panic!("not a procedural: {:?}", source(&s, effect)) };
assert_eq!((pattern.kind, pattern.scale, low, high), (kind, 4.0, [0.0; 3], [1.0; 3]));
let line = mask_line(&s, layer);
assert!(line.iter().any(|value| (value - line[0]).abs() > 1e-3), "the mask follows the pattern: {line:?}");
// A parameter alone keeps the rest of the pattern
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": kind.label(), "contrast": 1.5})).unwrap();
let Source::Procedural { pattern, .. } = source(&s, effect) else { panic!("not a procedural") };
assert_eq!((pattern.scale, pattern.contrast), (4.0, 1.5));
let scratches = alphas::find("scratches").unwrap();
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "alpha": "scratches"})).unwrap();
assert_eq!(source(&s, effect), Source::image(resource_name(scratches)));
assert!(s.doc.resources.contains_key(&resource_name(scratches)));
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap();
assert_eq!(source(&s, effect), Source::Uniform([0.25; 3]));
assert!(mask_line(&s, layer).iter().all(|value| (value - 0.25).abs() < 1e-3));
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 7.0})).unwrap();
assert_eq!(source(&s, effect), Source::Uniform([1.0; 3]), "a mask value stays in 0..1");
let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(source(&s, effect), Source::image(resource_name(scratches)), "each pick is one undo step");
}
#[test]
fn a_mask_fill_has_no_channels_or_material() {
let (mut s, _, effect) = mask_fill();
let before = source(&s, effect);
for refused in [
json!({"effect": effect.0, "channel": "height", "value": 0.5}),
json!({"effect": effect.0, "enabled": false}),
json!({"effect": effect.0}),
json!({"effect": effect.0, "procedural": "no such pattern"}),
] {
assert!(execute(&mut s, "layer.fill.set", &refused).is_err(), "{refused}");
}
assert!(execute(&mut s, "layer.fill.material", &json!({"effect": effect.0, "material": null})).is_err());
assert_eq!(source(&s, effect), before);
}
#[test]
fn a_mask_fill_is_projected_and_reset_like_any_fill() {
let (mut s, _, effect) = mask_fill();
execute(&mut s, "layer.fill.projection", &json!({"effect": effect.0, "projection": "planar", "scale": 2.0, "symmetry": true})).unwrap();
assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0));
let inspected = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspected.contains("projectionSettings"), "inspect shows the mask fill's projection");
execute(&mut s, "layer.fill.resetProjection", &json!({"effect": effect.0})).unwrap();
assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 1.0), "the reset keeps the projection, at its defaults");
match &s.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Fill { sampling, .. } => assert!(sampling.symmetry.on, "the reset keeps the Symmetry section"),
other => panic!("not a mask fill: {other:?}"),
}
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(matches!(projection(&s, effect), Projection::Planar { scale, .. } if scale == 2.0), "the reset is one undo step");
}
fn resolution(s: &Session, effect: LayerId) -> OutputResolution {
match source(s, effect) {
Source::Procedural { pattern, .. } => pattern.resolution,
other => panic!("not a procedural: {other:?}"),
}
}
#[test]
fn a_procedural_source_is_made_at_its_resolution() {
let (mut s, layer, effect) = mask_fill_on(512);
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "scale": 8.0})).unwrap();
let every_texel = mask_line(&s, layer);
assert!(resolution(&s, effect).is_default());
// A quarter of the texture set's size: the pattern is made at 128 × 128 and smoothed back up
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolutionFactor": -2})).unwrap();
assert_eq!(resolution(&s, effect).factor, -2);
let coarse = mask_line(&s, layer);
assert!(coarse.iter().zip(&every_texel).any(|(sampled, exact)| (sampled - exact).abs() > 1e-3), "{coarse:?} vs {every_texel:?}");
assert!(execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string().contains("\"resolution\""), "inspect shows it");
// Another parameter keeps it; a bad size is refused and changes nothing
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "contrast": 1.0})).unwrap();
assert_eq!(resolution(&s, effect).factor, -2);
assert!(execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "big"})).is_err());
assert_eq!(resolution(&s, effect).factor, -2);
// The default size again: every texel, as before
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "procedural": "Clouds", "resolution": "auto", "resolutionFactor": 0})).unwrap();
assert!(resolution(&s, effect).is_default());
assert_eq!(mask_line(&s, layer), every_texel);
}
#[test]
fn a_pattern_saved_before_resolutions_existed_reads_and_saves_unchanged() {
let old = r#"{"kind":"Clouds","scale":4.0,"seed":1,"contrast":1.0,"balance":0.0,"invert":false}"#;
let pattern: Procedural = serde_json::from_str(old).unwrap();
assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds));
assert_eq!(serde_json::to_string(&pattern).unwrap(), old, "no resolution, no new field in the file");
}
#[test]
fn setting_the_source_a_mask_fill_already_reads_adds_no_undo_step() {
let (mut s, _, effect) = mask_fill();
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap();
let steps = s.history_labels().len();
execute(&mut s, "layer.fill.set", &json!({"effect": effect.0, "value": 0.25})).unwrap();
assert_eq!(s.history_labels().len(), steps);
assert_eq!(source(&s, effect), Source::Uniform([0.25; 3]));
}
+28
View File
@@ -0,0 +1,28 @@
//! A mask fill effect's Properties: the Fill and Symmetry sections a fill layer has, then its Grayscale section with its one source slot
use serde_json::json;
use texturecraft_engine::core::{Fill, LayerId, Projection, Sampling, Source};
use crate::TextureCraftApp;
use crate::fill_material_panel::source_card;
use crate::i18n::tr;
use crate::property_sheet::PropertySheet;
use crate::source_slot::SourceSlot;
/// Every section of mask fill effect `effect` in layer `reader`'s mask
pub(crate) fn mask_fill_sheet(
app: &mut TextureCraftApp,
sheet: &mut PropertySheet<'_>,
effect: LayerId,
source: Source,
projection: Projection,
sampling: Sampling,
reader: LayerId,
) {
let base = json!({"effect": effect.0});
let placement = Fill { projection, sampling, ..Fill::default() };
crate::fill_panel::placement_sections(app, sheet, &placement, &base, reader);
sheet.section(tr("Grayscale"), false);
source_card(app, sheet, source, &base, SourceSlot::Grayscale, reader, false);
}
+86
View File
@@ -0,0 +1,86 @@
//! The paint tools' Grayscale tab while a mask is painted: the GRAYSCALE section with the slot of the gray a stroke lays down
use egui::Ui;
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::compose::ImageStore;
use texturecraft_engine::core::{NormalFormat, Source};
use crate::TextureCraftApp;
use crate::fill_material_panel::{shown_color, source_line};
use crate::i18n::{n_, tr};
use crate::mask_source_choice::MaskSourceChoice;
use crate::picker_group::PickerGroup;
use crate::picker_tab::PickerTab;
use crate::property_sheet::PropertySheet;
use crate::resource_picker;
use crate::resource_picker_item::ResourcePickerItem;
use crate::slot_thumbnail::{paint_thumbnail, thumbnail};
use crate::theme::Tokens;
use crate::thumbs::Thumbs;
use crate::tile_picture::TilePicture;
/// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted
pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) {
PropertySheet::show(ui, "mask_paint_sheet", |sheet| {
sheet.section(tr("Grayscale"), false);
let gray = app.session.tool.mask_value;
let source = match &app.session.tool.mask_image {
Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() },
None => Source::Uniform([gray; 3]),
};
let tokens = Tokens::get(sheet.ui.ctx());
let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source);
let line = source_line(app, &source);
let image = app.session.tool.mask_image.is_some();
let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false);
let popup = sheet.ui.make_persistent_id("mask_paint_source");
if slot.pick.clicked() {
resource_picker::toggle(sheet.ui.ctx(), popup);
}
let current = match &app.session.tool.mask_image {
Some(name) => MaskSourceChoice::Image(name.clone()),
None => MaskSourceChoice::Uniform,
};
let ctx = sheet.ui.ctx().clone();
let tabs = |_: &mut Thumbs| source_tabs(&app.session.images, shown_color([gray; 3]));
match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(&current), image, tabs) {
Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"),
Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => {
app.run("tool.material", json!({"maskImage": name}));
}
Some(MaskSourceChoice::Uniform) if image => {
app.run("tool.material", json!({"maskImage": null}));
}
_ => {}
}
if slot.clear {
app.run("tool.material", json!({"maskImage": null}));
}
if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) {
app.run("tool.material", json!({"maskImage": name}));
}
if !image {
let mut value = gray;
let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0);
if edit.invert {
app.run("tool.material", json!({"maskValue": 1.0 - gray}));
} else if edit.changed.is_some() {
app.run("tool.material", json!({"maskValue": value}));
}
}
sheet.close_card();
});
}
/// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform
fn source_tabs(images: &ImageStore, uniform: egui::Color32) -> Vec<PickerTab<MaskSourceChoice>> {
let textures = ResourcePickerItem::textures(images, MaskSourceChoice::Import, |name| MaskSourceChoice::Image(name.to_owned()));
let uniform =
vec![ResourcePickerItem { id: MaskSourceChoice::Uniform, label: tr("Uniform value").to_owned(), caption: None, picture: TilePicture::Swatch(uniform) }];
let groups =
[(n_("Textures"), textures), (n_("Uniform"), uniform)].into_iter().map(|(header, items)| PickerGroup { header: Some(tr(header)), items }).collect();
vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }]
}
+9
View File
@@ -0,0 +1,9 @@
//! What the mask paint Grayscale slot's picker offers
/// One tile of the Grayscale slot's picker: one gray, an image resource, or importing one
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum MaskSourceChoice {
Uniform,
Image(String),
Import,
}
+175
View File
@@ -0,0 +1,175 @@
//! A mask fill effect's Properties: Fill | Symmetry | Grayscale tabs, the fill's projection rows, and one Grayscale slot whose picker sets its source
use egui::{Event, Modifiers, PointerButton, Pos2, Role};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::core::{Channel, EffectKind, LayerId, ProceduralKind, Projection, ResolutionMode, Source};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::move_on_model::MoveOnModel;
use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION};
/// Tall enough that Properties shows every section of a mask fill without scrolling
const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1600.0);
/// Moves of a mouse drag, one per frame
const DRAG_MOVES: usize = 40;
/// How far left a drag moves the projection on the model
const MOVE_DRAG: egui::Vec2 = egui::vec2(-60.0, 0.0);
/// The app with a paint layer whose mask holds one fill effect, that effect selected; the layer's and the effect's ids
fn app_with_mask_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) {
let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let layer = LayerId(texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap());
let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": projection})).unwrap();
let effect = LayerId(added["effect"].as_u64().unwrap());
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
// The labels below are English; a first run would speak the system's language
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, layer, effect)
}
fn mask_fill(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> (Source, Projection) {
match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Fill { source, projection, .. } => (source.clone(), projection.clone()),
other => panic!("not a mask fill: {other:?}"),
}
}
fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
harness.get_by_role_and_label(role, label).click();
harness.run_steps(SETTLE_FRAMES);
}
/// Scrolls the `role` named `label` into view first, then clicks it
fn click_below(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
harness.get_by_role_and_label(role, label).scroll_to_me();
harness.run_steps(SETTLE_FRAMES);
click(harness, role, label);
}
#[test]
fn a_mask_fill_has_fill_symmetry_and_grayscale_tabs_and_its_slot_picks_the_source() {
let (mut harness, _, effect) = app_with_mask_fill("uv");
for tab in ["Fill", "Symmetry", "Grayscale"] {
assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab");
}
assert!(harness.query_by_role_and_label(Role::Tab, "Material").is_none(), "a mask fill has no material");
assert!(harness.query_by_label("Move on model").is_some(), "the Fill section's projection rows");
click(&mut harness, Role::ComboBox, "Grayscale");
assert!(harness.query_by_role_and_label(Role::Tab, "Anchor points").is_some(), "the slot opens the source picker");
click(&mut harness, Role::ListBoxOption, "Clouds");
let (Source::Procedural { pattern, low, high, .. }, _) = mask_fill(&harness, effect) else { panic!("a procedural") };
assert_eq!((pattern.kind, low, high), (ProceduralKind::Clouds, [0.0; 3], [1.0; 3]), "a gray pattern spans black to white");
assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker");
assert!(harness.query_by_label("Scale").is_some(), "the pattern's own rows follow the slot");
for shown in ["Contrast", "Balance", "Random"] {
assert!(harness.query_by_label(shown).is_some(), "a grayscale's {shown} (Seed's dice) shows with Scale, Attributes folded");
}
// Resolution: the pattern is made at the texture set's size until another is picked
let resolution = |harness: &Harness<'_, TextureCraftApp>| match mask_fill(harness, effect).0 {
Source::Procedural { pattern, .. } => (pattern.resolution.mode, pattern.resolution.custom, pattern.resolution.factor),
other => panic!("a procedural: {other:?}"),
};
click_below(&mut harness, Role::ComboBox, "Texture set · 256");
for caption in ["Relative", "Fixed"] {
assert!(harness.query_by_role_and_label(Role::Label, caption).is_some(), "one list holds the {caption} sizes under their caption");
}
click(&mut harness, Role::ListBoxOption, "1024 × 1024");
assert_eq!(resolution(&harness), (ResolutionMode::Custom, 1024, 0));
click_below(&mut harness, Role::ComboBox, "1024 × 1024");
click(&mut harness, Role::ListBoxOption, "×4 · 1024");
assert_eq!(resolution(&harness), (ResolutionMode::Auto, 1024, 2), "1024 is the texture set's ×4");
// The slot's × puts the mask fill back to white
click(&mut harness, Role::Button, "Clear");
assert_eq!(mask_fill(&harness, effect).0, Source::Uniform([1.0; 3]));
}
/// A drag as a mouse sends it: press, hold still a frame, then small moves one per frame until released; `watch` looks at the app after each move
fn mouse_drag_watching(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2, mut watch: impl FnMut(&Harness<'_, TextureCraftApp>)) {
let button = |pos: Pos2, pressed: bool| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
harness.event(Event::PointerMoved(from));
harness.run_steps(1);
harness.event(button(from, true));
harness.run_steps(DRAG_STEP_FRAMES);
for step in 1..=DRAG_MOVES {
harness.event(Event::PointerMoved(from.lerp(to, step as f32 / DRAG_MOVES as f32)));
harness.run_steps(1);
watch(harness);
}
harness.event(button(to, false));
harness.run_steps(DRAG_STEP_FRAMES);
}
#[test]
fn a_mask_fills_projection_moves_on_the_model_and_resets_with_its_section() {
let (mut harness, layer, effect) = app_with_mask_fill("uv");
// A real drag that starts on the held button slides the mask fill's image
let button = harness.get_by_role_and_label(Role::Button, "Move on model").rect().center();
let mut held = None;
mouse_drag_watching(&mut harness, button, button + MOVE_DRAG, |harness| held = held.or(harness.state().moving_on_model));
assert_eq!(held, Some(MoveOnModel { layer, effect: Some(effect) }));
assert_eq!(harness.state().moving_on_model, None, "letting go ends it");
let Projection::Uv { offset, .. } = mask_fill(&harness, effect).1 else { panic!("still UV") };
assert!(offset[0] != 0.0 && offset[1] == 0.0, "a drag across slides the image across: {offset:?}");
click(&mut harness, Role::Button, "Fill: Reset to defaults");
assert_eq!(mask_fill(&harness, effect).1, Projection::default(), "the Fill section's reset reaches the mask fill");
}
/// A mask fill reading a content anchor point picks the channel it reads in its Grayscale card
#[test]
fn a_mask_fill_reading_a_content_anchor_picks_its_channel() {
let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let low = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap()["layer"].clone();
let anchor = texturecraft_engine::execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "content"})).unwrap()["effect"].clone();
let top = texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone();
let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": top, "target": "mask", "anchor": anchor})).unwrap();
let effect = LayerId(added["effect"].as_u64().unwrap());
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": top, "target": effect.0})).unwrap();
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("an anchor source") };
assert_eq!(channel, Channel::Height, "a new anchor source reads height");
click_below(&mut harness, Role::ComboBox, "Height");
click(&mut harness, Role::ListBoxOption, "Roughness");
let Source::Anchor { channel, .. } = mask_fill(&harness, effect).0 else { panic!("still an anchor source") };
assert_eq!(channel, Channel::Roughness, "the pick reads the anchor's roughness");
}
/// An instance showing its source's mask fill lists only the anchor points below both: one between the source and the instance is refused by the source's mask
#[test]
fn an_inherited_mask_fill_lists_only_anchors_below_its_owner() {
const BETWEEN: &str = "Edge wear between";
let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let source = texturecraft_engine::execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone();
let added = texturecraft_engine::execute(&mut session, "effect.add.fill", &json!({"layer": source, "target": "mask"})).unwrap();
let effect = LayerId(added["effect"].as_u64().unwrap());
let between = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone();
let anchor = texturecraft_engine::execute(&mut session, "effect.add.anchor", &json!({"layer": between, "target": "content"})).unwrap()["effect"].clone();
texturecraft_engine::execute(&mut session, "effect.set", &json!({"effect": anchor, "name": BETWEEN})).unwrap();
let instance = texturecraft_engine::execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone();
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": instance})).unwrap();
session.target = texturecraft_engine::StackTarget::Effect(effect);
let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
let shown = harness.query_all_by_label(BETWEEN).count();
click(&mut harness, Role::ComboBox, "Grayscale");
click(&mut harness, Role::Tab, "Anchor points");
assert_eq!(harness.query_all_by_label(BETWEEN).count(), shown, "the anchor above the source is not offered");
}