mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 10:03:56 +01:00
Merge pull request #842 from Rebornim/feat/layers-pass
Layers panel parity: smart material picker, flatten folder, effect moves and remove, generator names, height-combination mask, Pick layer
This commit is contained in:
44 files changed
+2765
-132
No files matched your search
+259
-42
@@ -4,6 +4,7 @@
|
||||
|
||||
mod draw_placement;
|
||||
mod evaluation_inputs;
|
||||
mod layers_at;
|
||||
pub(crate) mod thumbnail;
|
||||
|
||||
use std::borrow::Cow;
|
||||
@@ -33,6 +34,7 @@ use crate::fill_copies::FillCopies;
|
||||
use crate::fill_copy::FillCopy;
|
||||
use crate::fill_depth::FillDepth;
|
||||
use crate::fill_place::FillPlace;
|
||||
use crate::flatten_folder_error::FlattenFolderError;
|
||||
use crate::generator_maps::GeneratorMaps;
|
||||
use crate::held_fields::HeldFields;
|
||||
use crate::mask_gray::MaskGray;
|
||||
@@ -52,6 +54,7 @@ use crate::wear;
|
||||
use crate::wear_inputs::WearInputs;
|
||||
use draw_placement::DrawPlacement;
|
||||
use evaluation_inputs::EvaluationInputs;
|
||||
pub use layers_at::layers_at;
|
||||
|
||||
const NCH: usize = Channel::ALL.len();
|
||||
|
||||
@@ -1419,6 +1422,17 @@ fn below_plan<'a>(
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
stack_plan_below(inp, draw, channels, (tile_x, tile_y), fields)
|
||||
}
|
||||
|
||||
/// Plan the whole stack up to a draw, whatever the draw reads
|
||||
fn stack_plan_below<'a>(
|
||||
inp: &EvaluationInputs<'a>,
|
||||
draw: (LayerId, usize),
|
||||
channels: &[Channel],
|
||||
(tile_x, tile_y): (u32, u32),
|
||||
fields: Option<&'a Fields>,
|
||||
) -> Vec<Node<'a>> {
|
||||
let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() };
|
||||
let compare_effects = layer_mask(inp.project, draw.0).into_iter().flat_map(|mask| mask.effects.iter());
|
||||
let planned = compared_channels(compare_effects, channels.to_vec());
|
||||
@@ -3034,6 +3048,7 @@ fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool {
|
||||
}
|
||||
|
||||
/// Per-texel context.
|
||||
#[derive(Clone)]
|
||||
struct Texel<'a, 'b> {
|
||||
inp: &'b Inputs<'a>,
|
||||
x: u32,
|
||||
@@ -3061,6 +3076,7 @@ struct Texel<'a, 'b> {
|
||||
|
||||
/// What a layer contributes (its mask, its content value and coverage per channel): evaluated
|
||||
/// (`Off`), evaluated and recorded, or replayed from a recording.
|
||||
#[derive(Clone)]
|
||||
enum Tape<'t> {
|
||||
Off,
|
||||
Record(Vec<f32>),
|
||||
@@ -3430,11 +3446,20 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
#[inline(always)]
|
||||
fn fill_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) {
|
||||
let FillPlace { fill, projection, depth, covers_all } = place;
|
||||
let sampling = fill.sampling;
|
||||
let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, sampling, depth) };
|
||||
if let Some(Source::Image { name, normal_format }) = source
|
||||
&& sampling.alpha_coverage
|
||||
&& cover > 0.0
|
||||
{
|
||||
let (value, alpha) = self.image_value::<true>(name, *normal_format, projection, sampling, ch.kind());
|
||||
return (value, cover * alpha);
|
||||
}
|
||||
|
||||
let value = match source {
|
||||
Some(source) => self.source(source, projection, fill.sampling, ch.kind()),
|
||||
Some(source) => self.source(source, projection, sampling, ch.kind()),
|
||||
None => ch.default_value(),
|
||||
};
|
||||
let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, fill.sampling, depth) };
|
||||
(value, cover)
|
||||
}
|
||||
|
||||
@@ -3466,7 +3491,8 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
};
|
||||
|
||||
let (coords, cover) = self.projected(proj);
|
||||
if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha {
|
||||
// With per-channel alpha the caller applies image coverage
|
||||
if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha || sampling.alpha_coverage {
|
||||
return cover * self.tile_cover(proj, &coords, sampling);
|
||||
}
|
||||
|
||||
@@ -3543,49 +3569,61 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
mix3(*low, *high, amount)
|
||||
}
|
||||
}
|
||||
Source::Image { name, normal_format } => {
|
||||
let Some(image) = self.inp.images.get(name) else { return [0.5; 3] };
|
||||
|
||||
let (coords, _) = self.projected(projection);
|
||||
let samples = self.image_uvs(projection, &coords);
|
||||
let footprints = match sampling.filtering {
|
||||
Filtering::BilinearHq => self.footprints(projection, &samples, image),
|
||||
Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3],
|
||||
};
|
||||
|
||||
// Blend projected planes in the same space when any of them reads a linear mip
|
||||
let is_srgb_color = kind == ChannelKind::Color && image.srgb;
|
||||
let planes = samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0);
|
||||
let blend_linear = is_srgb_color && planes.clone().any(|(_, footprint)| crate::store::uses_mips(footprint));
|
||||
let mut rgb = [0.0; 3];
|
||||
for ((uv, weight), footprint) in planes {
|
||||
let sampled = if blend_linear {
|
||||
image.sample_srgb_color(uv.x, uv.y, sampling, footprint)
|
||||
} else {
|
||||
image.sample_filtered(uv.x, uv.y, sampling, footprint)
|
||||
};
|
||||
|
||||
for (total, value) in rgb.iter_mut().zip(sampled) {
|
||||
*total += value * weight;
|
||||
}
|
||||
}
|
||||
|
||||
match kind {
|
||||
ChannelKind::Color if is_srgb_color && !blend_linear => rgb.map(texturecraft_texel::srgb_to_linear),
|
||||
|
||||
// Normal channels are OpenGL (+Y up the image): a DirectX image's green flips
|
||||
ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]],
|
||||
ChannelKind::Color | ChannelKind::NormalMap => rgb,
|
||||
|
||||
// A one-value channel or mask reads the image's gray, so a color image works as a mask
|
||||
ChannelKind::Scalar => [lum(rgb); 3],
|
||||
ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3],
|
||||
}
|
||||
}
|
||||
Source::Image { name, normal_format } => self.image_value::<false>(name, *normal_format, projection, sampling, kind).0,
|
||||
Source::Anchor { anchor, channel, .. } => self.anchor_value(*anchor, *channel, kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sample the image through the projection and interpret its color for the requested channel.
|
||||
fn image_value<const WITH_ALPHA: bool>(
|
||||
&mut self,
|
||||
name: &str,
|
||||
normal_format: NormalFormat,
|
||||
projection: &Projection,
|
||||
sampling: Sampling,
|
||||
kind: ChannelKind,
|
||||
) -> ([f32; 3], f32) {
|
||||
let Some(image) = self.inp.images.get(name) else { return ([0.5; 3], 0.0) };
|
||||
|
||||
let (coords, _) = self.projected(projection);
|
||||
let samples = self.image_uvs(projection, &coords);
|
||||
let footprints = match sampling.filtering {
|
||||
Filtering::BilinearHq => self.footprints(projection, &samples, image),
|
||||
Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3],
|
||||
};
|
||||
|
||||
// Blend projected planes in the same space when any of them reads a linear mip
|
||||
let is_srgb_color = kind == ChannelKind::Color && image.srgb;
|
||||
let planes = samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0);
|
||||
let blend_linear = is_srgb_color && planes.clone().any(|(_, footprint)| crate::store::uses_mips(footprint));
|
||||
let mut rgb = [0.0; 3];
|
||||
let mut alpha = 0.0;
|
||||
for ((uv, weight), footprint) in planes {
|
||||
let sampled =
|
||||
if blend_linear { image.sample_srgb_color(uv.x, uv.y, sampling, footprint) } else { image.sample_filtered(uv.x, uv.y, sampling, footprint) };
|
||||
|
||||
for (total, value) in rgb.iter_mut().zip(sampled) {
|
||||
*total += value * weight;
|
||||
}
|
||||
if WITH_ALPHA {
|
||||
alpha += sampled[3] * weight;
|
||||
}
|
||||
}
|
||||
|
||||
let value = match kind {
|
||||
ChannelKind::Color if is_srgb_color && !blend_linear => rgb.map(texturecraft_texel::srgb_to_linear),
|
||||
|
||||
// Normal channels are OpenGL so a DirectX image's green flips
|
||||
ChannelKind::NormalMap if normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]],
|
||||
ChannelKind::Color | ChannelKind::NormalMap => rgb,
|
||||
|
||||
// Scalar and signed channels read the image's luminance
|
||||
ChannelKind::Scalar => [lum(rgb); 3],
|
||||
ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3],
|
||||
};
|
||||
(value, alpha.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// The value anchor point `anchor` recorded for `channel`, read as `kind` (colors read as gray
|
||||
/// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the
|
||||
/// channel default.
|
||||
@@ -5581,6 +5619,149 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti
|
||||
Some(out.into_iter().flatten().collect())
|
||||
}
|
||||
|
||||
/// The premultiplied value and coverage (last) of a Normal layer that shows `shown` over `under`, covering at least `coverage`, with straight values inside `range` (Multiply or Overlay hide each component by a different amount, so the coverage grows where a straight value would leave it); None where it shows the stack as it is
|
||||
fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, (low, high): (f32, f32)) -> Option<[f32; 4]> {
|
||||
let needed = under.iter().zip(shown).take(comps).fold(coverage, |needed, (under, shown)| {
|
||||
let change = shown - under;
|
||||
let room = if change > 0.0 { high - under } else { under - low };
|
||||
if change.abs() <= f32::EPSILON || room <= 0.0 { needed } else { needed.max(change.abs() / room) }
|
||||
});
|
||||
let coverage = needed.min(1.0);
|
||||
if coverage <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Over `under`, the layer shows its premultiplied value plus what it leaves of the stack
|
||||
let mut premultiplied = [0.0, 0.0, 0.0, coverage];
|
||||
for ((slot, under), shown) in premultiplied.iter_mut().zip(under).zip(shown).take(comps) {
|
||||
*slot = shown - (1.0 - coverage) * under;
|
||||
}
|
||||
Some(premultiplied)
|
||||
}
|
||||
|
||||
/// One tile of a flattened folder's mask: (tile, mask value + coverage data)
|
||||
pub type FlatMaskTile = ((u32, u32), Vec<u16>);
|
||||
|
||||
/// How far past its channel's range a folder's result may sit as rounding noise
|
||||
const RANGE_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
/// A flattened folder: its content tiles and its mask tiles
|
||||
pub type FlattenedFolder = (Vec<FlatTile>, Vec<FlatMaskTile>);
|
||||
|
||||
/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel and per channel a mask compares, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither)
|
||||
pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Result<FlattenedFolder, FlattenFolderError> {
|
||||
let set = inputs.project.texture_set(inputs.ts).map_err(|_| FlattenFolderError::NotAFolder)?;
|
||||
if !inputs.project.content_layer(id).is_some_and(Layer::is_group) {
|
||||
return Err(FlattenFolderError::NotAFolder);
|
||||
}
|
||||
|
||||
// Force visibility so hidden folders can be flattened
|
||||
let mut forced_visible = inputs.project.clone();
|
||||
if let Some(layer) = forced_visible.layers.get_mut(&id) {
|
||||
layer.visible = true;
|
||||
}
|
||||
let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs };
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let mut visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors);
|
||||
prepare_generators(&mut visible_inputs, Some(id));
|
||||
let planned_channels = evaluation_channels(&visible_inputs, set.channel_list());
|
||||
let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles);
|
||||
|
||||
// None for a tile where the folder's result leaves the range its image can hold
|
||||
let out: Option<Vec<(Vec<FlatTile>, Option<FlatMaskTile>)>> = tiles
|
||||
.par_iter()
|
||||
.map(|&(tx, ty)| {
|
||||
let nodes = plan(&visible_inputs, &[id], &planned_channels, tx, ty, 0, Some(&fields));
|
||||
let Some(node) = nodes.first() else { return Some((Vec::new(), None)) };
|
||||
let Content::Group(children) = &node.content else { return Some((Vec::new(), None)) };
|
||||
|
||||
let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields));
|
||||
|
||||
// Initialize signed channels at encoded zero
|
||||
let mut buffers: Vec<(Channel, Vec<u16>, bool)> = node
|
||||
.chans
|
||||
.iter()
|
||||
.filter_map(|planned| Channel::ALL.get(planned.ch).map(|channel| (*channel, vec![0u16; TILE_AREA * (planned.comps + 1)], false)))
|
||||
.collect();
|
||||
for (channel, buffer, _) in &mut buffers {
|
||||
if channel.kind() == ChannelKind::Signed {
|
||||
for pixel in buffer.as_chunks_mut::<2>().0 {
|
||||
pixel[0] = to_u16_signed(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let masked = node.mask.is_some() || node.parts.is_some();
|
||||
let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]);
|
||||
|
||||
for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) {
|
||||
// Evaluate the lower stack once for all three probes
|
||||
let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0);
|
||||
over_below.anchors_below(&below, (id, 0));
|
||||
let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value));
|
||||
|
||||
// Record mask anchors before evaluating children that read them
|
||||
let folder_mask = over_below.node_mask(node);
|
||||
|
||||
// Black and white probes estimate coverage against different backgrounds
|
||||
let over = |mut stack: Acc| {
|
||||
let mut texel = over_below.clone();
|
||||
texel.eval(children, &mut stack);
|
||||
stack
|
||||
};
|
||||
let (low, high, shown) = (over([[0.0; 3]; NCH]), over([[1.0; 3]; NCH]), over(stack_below));
|
||||
for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) {
|
||||
let (Some(low), Some(high), Some(shown), Some(under)) =
|
||||
(low.get(planned.ch), high.get(planned.ch), shown.get(planned.ch), stack_below.get(planned.ch))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let comps = planned.comps.min(3);
|
||||
let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::<f32>() / comps as f32;
|
||||
let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) };
|
||||
let premultiplied = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range);
|
||||
|
||||
// Clipping matters only where the folder mask exposes the result
|
||||
let clipped = match premultiplied {
|
||||
Some(values) => {
|
||||
let coverage = values[3];
|
||||
let min = range.0 * coverage - RANGE_TOLERANCE;
|
||||
let max = range.1 * coverage + RANGE_TOLERANCE;
|
||||
values.iter().take(comps).any(|value| *value < min || *value > max)
|
||||
}
|
||||
None => shown.iter().zip(under).take(comps).any(|(shown, under)| (shown - under).abs() > RANGE_TOLERANCE),
|
||||
};
|
||||
if clipped && folder_mask > 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(premultiplied) = premultiplied else { continue };
|
||||
|
||||
*laid_down = true;
|
||||
let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue };
|
||||
let coverage = premultiplied[3];
|
||||
for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) {
|
||||
*slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) };
|
||||
}
|
||||
if let Some(slot) = pixel.get_mut(planned.comps) {
|
||||
*slot = to_u16(coverage);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) {
|
||||
pixel.copy_from_slice(&[to_u16(folder_mask), u16::MAX]);
|
||||
}
|
||||
}
|
||||
|
||||
let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect();
|
||||
Some((content, mask.map(|mask| ((tx, ty), mask))))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let (content, masks): (Vec<_>, Vec<_>) = out.ok_or(FlattenFolderError::ValueOutOfRange)?.into_iter().unzip();
|
||||
Ok((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -7715,6 +7896,42 @@ soft {soft:?}"
|
||||
assert!(raised.iter().zip(flattened).any(|(raised, flat)| (*raised - flat).abs() > 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cropped_framed_fill_applies_its_image_alpha_once_with_alpha_coverage() {
|
||||
let mut f = fixture();
|
||||
let mut images = ImageStore::default();
|
||||
images.insert("half".to_owned(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 1.0, 1.0, 0.5]], false)));
|
||||
let id = fill_layer(&mut f.project, [0.0; 3], 0.5);
|
||||
let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") };
|
||||
fill.sources.insert(Channel::BaseColor, Source::image("half"));
|
||||
fill.projection = Projection::Planar {
|
||||
scale: 1.0,
|
||||
axis: 1,
|
||||
offset: [0.0; 3],
|
||||
uv: Default::default(),
|
||||
projector: texturecraft_core::Projector { crop: texturecraft_core::ShapeCrop::Cropped, ..Default::default() },
|
||||
placed: Some(texturecraft_core::Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 1.0, 0.0],
|
||||
up: [0.0, 0.0, -1.0],
|
||||
size: [4.0, 4.0],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 1.0,
|
||||
symmetry: None,
|
||||
flip: [false; 2],
|
||||
}),
|
||||
};
|
||||
let plain = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32);
|
||||
let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") };
|
||||
fill.sampling.alpha_coverage = true;
|
||||
|
||||
let covered = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32);
|
||||
|
||||
assert!(!close(plain, Channel::BaseColor.default_value()), "the fill lands on the plane");
|
||||
assert!(close(covered, plain), "alpha coverage {covered:?}, image alpha {plain:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn micro_height_uses_the_live_stroke_and_restores_the_committed_anchor_after_cancel() {
|
||||
let (mut fixture, images) = micro_height_fixture();
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Which layers lay something down at one texel, for R + click on the model
|
||||
|
||||
use super::{
|
||||
Acc, BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels,
|
||||
evaluation_fields, mix_group, plan, prepare_generators,
|
||||
};
|
||||
|
||||
/// Below this weight a layer leaves the texel unchanged (one 16-bit step)
|
||||
const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0;
|
||||
|
||||
/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down. Projection depth maps come from `projectors` when it serves `inputs.mesh`
|
||||
pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec<Channel>)> {
|
||||
let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() };
|
||||
|
||||
let gbuf = inputs.gbuf;
|
||||
let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI);
|
||||
if !covered {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// A cache built for another mesh would hand out its depth maps
|
||||
let unbound = ProjectorDepthCache::default();
|
||||
let served = projectors.serves(inputs.mesh);
|
||||
let mut inputs = EvaluationInputs::new(inputs, if served { projectors } else { &unbound });
|
||||
|
||||
// The viewport's anchor heights are kept for the next query
|
||||
if served {
|
||||
inputs = inputs.of_the_session_stack();
|
||||
}
|
||||
prepare_generators(&mut inputs, None);
|
||||
|
||||
let inputs = &inputs;
|
||||
let channels = evaluation_channels(inputs, set.channel_list());
|
||||
|
||||
// Plan the neighborhood that filters and anchors can read
|
||||
let (tile_x, tile_y) = (x / TILE, y / TILE);
|
||||
let fields = evaluation_fields(inputs, &channels, &[(tile_x, tile_y)]);
|
||||
let nodes = plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields));
|
||||
let offset = ((y % TILE) * TILE + x % TILE) as usize;
|
||||
let mut texel = Texel::new(inputs, x, y, offset, 0.0);
|
||||
|
||||
let mut stack = Channel::ALL.map(Channel::default_value);
|
||||
let mut found = Vec::new();
|
||||
texel.layers_laying_down(&nodes, &mut stack, [1.0; NCH], shown, &mut found);
|
||||
|
||||
// The stack runs bottom first
|
||||
found.reverse();
|
||||
found
|
||||
}
|
||||
|
||||
impl Texel<'_, '_> {
|
||||
/// Composite `nodes` (bottom first) over `stack`, pushing the leaf layers that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them)
|
||||
fn layers_laying_down(&mut self, nodes: &[Node], stack: &mut Acc, weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec<Channel>)>) {
|
||||
for node in nodes {
|
||||
// A mask comparing with the layers below reads the stack under its own layer
|
||||
self.below = Some(*stack);
|
||||
let mask = self.node_mask(node);
|
||||
if mask <= 0.0 {
|
||||
// A masked-out layer still records its anchor points
|
||||
self.eval(std::slice::from_ref(node), stack);
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut node_weights = [0.0; NCH];
|
||||
for chan in node.chans.iter().filter(|chan| shown.iter().any(|channel| channel.index() == chan.ch)) {
|
||||
if let (Some(weight), Some(slot)) = (weights.get(chan.ch), node_weights.get_mut(chan.ch)) {
|
||||
*slot = weight * chan.opacity * mask;
|
||||
}
|
||||
}
|
||||
|
||||
match &node.content {
|
||||
Content::Group(children) => {
|
||||
let mut inner = *stack;
|
||||
let first_child = found.len();
|
||||
self.layers_laying_down(children, &mut inner, node_weights, shown, found);
|
||||
mix_group(stack, &inner, &node.chans, mask);
|
||||
|
||||
// The folder instance is the selectable row for its source's children
|
||||
if found.len() > first_child && self.inp.project.layers.get(&node.draw.0).and_then(|layer| layer.instance_source()).is_some() {
|
||||
let contributed: Vec<Channel> =
|
||||
shown.iter().copied().filter(|channel| found[first_child..].iter().any(|(_, channels)| channels.contains(channel))).collect();
|
||||
found.truncate(first_child);
|
||||
found.push((node.draw.0, contributed));
|
||||
}
|
||||
}
|
||||
content => {
|
||||
let changed: Vec<Channel> = shown
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|channel| {
|
||||
node.chans.iter().filter(|chan| chan.ch == channel.index()).any(|chan| {
|
||||
let weight = node_weights.get(chan.ch).copied().unwrap_or(0.0);
|
||||
|
||||
// Replace lays its value down at full weight wherever the layer has content
|
||||
weight > SMALLEST_WEIGHT
|
||||
&& self
|
||||
.content(content, chan)
|
||||
.is_some_and(|(_, coverage)| chan.blend == BlendMode::Replace || weight * coverage > SMALLEST_WEIGHT)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if !changed.is_empty() {
|
||||
found.push((node.draw.0, changed));
|
||||
}
|
||||
|
||||
self.eval(std::slice::from_ref(node), stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// Why a folder can't be flattened
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FlattenFolderError {
|
||||
NotAFolder,
|
||||
|
||||
/// Its layers add up past what an image holds, which baking would clip
|
||||
ValueOutOfRange,
|
||||
}
|
||||
@@ -27,6 +27,7 @@ pub mod fill_copies;
|
||||
pub mod fill_copy;
|
||||
mod fill_depth;
|
||||
mod fill_place;
|
||||
mod flatten_folder_error;
|
||||
pub mod frame_placement;
|
||||
mod fur_lock;
|
||||
mod generator_maps;
|
||||
@@ -78,9 +79,10 @@ pub use display::{DisplayKind, kinds_for, tile_bytes};
|
||||
pub use effect_histogram::EffectHistogram;
|
||||
pub use eval::{
|
||||
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached,
|
||||
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles,
|
||||
stack_reads_neighbours,
|
||||
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_texels, mask_values,
|
||||
pad_tiles, stack_reads_neighbours,
|
||||
};
|
||||
pub use flatten_folder_error::FlattenFolderError;
|
||||
pub use mask_gray::MaskGray;
|
||||
pub use padding_maps::PaddingMaps;
|
||||
pub use pattern_context::PatternContext;
|
||||
|
||||
@@ -27,6 +27,11 @@ impl ProjectorDepthCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its depth maps were built for `mesh`
|
||||
pub(crate) fn serves(&self, mesh: &Mesh) -> bool {
|
||||
std::ptr::eq(self.mesh.as_ptr(), mesh)
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option<Arc<FillDepth>> {
|
||||
// Rasterization is serial so tile workers can wait for a single build
|
||||
let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
|
||||
@@ -2428,10 +2428,16 @@ pub struct Effect {
|
||||
|
||||
impl Effect {
|
||||
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
|
||||
// Generators are named after their kind, as filters are
|
||||
let name = match &kind {
|
||||
EffectKind::Generator(generator) => generator.kind.label(),
|
||||
_ => kind.name(),
|
||||
};
|
||||
|
||||
// Generators and fills that build a mask usually add on top of the background
|
||||
Effect {
|
||||
id,
|
||||
name: kind.name().to_string(),
|
||||
name: name.to_string(),
|
||||
visible: true,
|
||||
kind,
|
||||
blend: BlendMode::Normal,
|
||||
|
||||
@@ -14,12 +14,15 @@ pub struct Sampling {
|
||||
pub scale: ScaleMode,
|
||||
#[serde(default, skip_serializing_if = "FillSymmetry::is_default")]
|
||||
pub symmetry: FillSymmetry,
|
||||
/// Each channel's image alpha is how much of that channel shows (the images a folder is flattened into)
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub alpha_coverage: bool,
|
||||
}
|
||||
|
||||
impl Sampling {
|
||||
/// What fills saved before the sampling choices existed did: plain bilinear
|
||||
pub const SAVED_BEFORE: Sampling =
|
||||
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF };
|
||||
Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF, alpha_coverage: false };
|
||||
|
||||
/// Serde default for fills saved before the field existed
|
||||
pub fn saved_before() -> Sampling {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{BlendMode, EffectKind, Sampling, Source};
|
||||
use texturecraft_core::{BlendMode, Channel, EffectKind, Sampling, Source};
|
||||
use texturecraft_paint::alphas;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_layer, strp};
|
||||
use crate::commands::{CommandSpec, bad, content_param, has_layer, strp};
|
||||
use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
@@ -24,9 +24,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add mask with height combination",
|
||||
["Layers", "Mask"],
|
||||
None,
|
||||
"{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected",
|
||||
"{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected. The layer's height channel, if it has one, blends Normal",
|
||||
has_layer,
|
||||
|s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(()))
|
||||
|s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |s| height_blends_normal(s, p))
|
||||
),
|
||||
cmd!(
|
||||
"effect.add.colorSelection",
|
||||
@@ -40,6 +40,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Where a height-combination mask shows the layer, the layer's height replaces the height below instead of mixing with it
|
||||
fn height_blends_normal(s: &mut Session, p: &Value) -> Result<()> {
|
||||
let id = content_param(s, "mask.add.heightCombination", p)?;
|
||||
if let Some(blend) = s.doc.project.layers.get_mut(&id).and_then(|layer| layer.channels.get_mut(&Channel::Height)) {
|
||||
blend.mode = BlendMode::Normal;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource
|
||||
fn add_bitmap(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "mask.add.bitmap";
|
||||
|
||||
@@ -193,6 +193,46 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(),
|
||||
(spec.enabled)(s)
|
||||
}
|
||||
|
||||
/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (one drawing the effect) were selected
|
||||
fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> {
|
||||
let refused = match check_enabled(spec, s) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(why) => why,
|
||||
};
|
||||
let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId);
|
||||
let ts = s.ts();
|
||||
let project = &s.doc.project;
|
||||
let in_active_set = |id| project.locate(id).is_some_and(|(found, _, _)| found == ts);
|
||||
let named_layer = id_param("layer").filter(|_| spec.params.contains("layer?")).filter(|id| in_active_set(*id));
|
||||
let named_effect = id_param("effect").filter(|_| spec.params.starts_with("{effect"));
|
||||
|
||||
// An effect's layer may sit in another texture set, drawn here by an instance
|
||||
let layer_drawing_effect = || {
|
||||
let owner = project.effect(named_effect?)?.0;
|
||||
if in_active_set(owner) {
|
||||
return Some(owner);
|
||||
}
|
||||
|
||||
project.texture_set(ts).ok()?.stack.iter().copied().find(|id| project.render_tree(&[*id]).contains(&owner))
|
||||
};
|
||||
let Some(id) = named_layer.or_else(layer_drawing_effect) else { return Err(refused) };
|
||||
|
||||
let selected = s.selected.insert(ts, id);
|
||||
let target = s.target;
|
||||
if let Some(effect) = named_effect {
|
||||
s.target = crate::StackTarget::Effect(effect);
|
||||
}
|
||||
|
||||
let enabled = check_enabled(spec, s);
|
||||
|
||||
s.target = target;
|
||||
match selected {
|
||||
Some(old) => s.selected.insert(ts, old),
|
||||
None => s.selected.remove(&ts),
|
||||
};
|
||||
enabled
|
||||
}
|
||||
|
||||
pub fn find(id: &str) -> Option<&'static CommandSpec> {
|
||||
command_specs().iter().find(|c| c.id == id)
|
||||
}
|
||||
@@ -201,7 +241,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> {
|
||||
/// `merge: true` its edits continue the previous undo step of the same label (drags).
|
||||
pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
|
||||
check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
|
||||
check_enabled_for(spec, s, params).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
|
||||
let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false));
|
||||
let result = (spec.run)(s, params);
|
||||
s.merge_edits = outer;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Which way a step of `effect.moveUp` / `effect.moveDown` moves an effect
|
||||
|
||||
/// Which way an effect moves one place: up is later in its stack (rows list the top first)
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum EffectStep {
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
@@ -19,9 +19,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
)]
|
||||
}
|
||||
|
||||
/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section)
|
||||
/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) and its alpha coverage (a flattened folder's shape)
|
||||
pub fn reset_sampling(current: Sampling) -> Sampling {
|
||||
Sampling { symmetry: current.symmetry, ..Sampling::default() }
|
||||
Sampling { symmetry: current.symmetry, alpha_coverage: current.alpha_coverage, ..Sampling::default() }
|
||||
}
|
||||
|
||||
/// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept
|
||||
|
||||
@@ -87,6 +87,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
select
|
||||
),
|
||||
cmd!(
|
||||
"layer.layersAt",
|
||||
"Layers under the cursor",
|
||||
[],
|
||||
None,
|
||||
"{x, y, viewport?: [w,h]} a point on the mesh — {layers: [{layer, name, channels}]}: the layers laying something down there in the shown channels, top first, each with the channels it changes there (R + click lists them)",
|
||||
always,
|
||||
layers_at
|
||||
),
|
||||
cmd!(
|
||||
"layer.pickAt",
|
||||
"Pick layer under the cursor",
|
||||
[],
|
||||
None,
|
||||
"{x, y, viewport?: [w,h], layer?} a point on the mesh — selects the top layer laying something down there in the shown channels, or `layer`, refused when it lays nothing down there (R + click)",
|
||||
always,
|
||||
pick_at
|
||||
),
|
||||
cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename),
|
||||
cmd!(
|
||||
"layer.visible",
|
||||
@@ -282,6 +300,35 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer {
|
||||
folder
|
||||
}
|
||||
|
||||
fn pick_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) };
|
||||
|
||||
let viewport = crate::tool_cmds::viewport_of(s, p);
|
||||
|
||||
// An explicitly supplied layer must parse before falling back to the top layer
|
||||
let wanted = match p.get("layer").filter(|layer| !layer.is_null()) {
|
||||
Some(_) => Some(u64p(p, "layer").map(LayerId).ok_or_else(|| bad("layer.pickAt", "`layer` must be a layer id"))?),
|
||||
None => None,
|
||||
};
|
||||
let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
fn layers_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.layersAt", "`x` and `y` are required")) };
|
||||
|
||||
let viewport = crate::tool_cmds::viewport_of(s, p);
|
||||
let (_, layers) = s.layers_under(texturecraft_geom::glam::Vec2::new(x, y), viewport)?;
|
||||
let layers: Vec<Value> = layers
|
||||
.iter()
|
||||
.map(|(id, channels)| {
|
||||
let name = s.doc.project.layers.get(id).map(|layer| layer.name.as_str()).unwrap_or_default();
|
||||
json!({ "layer": id.0, "name": name, "channels": channels.iter().map(|channel| channel.id()).collect::<Vec<_>>() })
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "layers": layers }))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if boolp(p, "all") == Some(true) {
|
||||
return crate::layer_selection::select_all(s);
|
||||
|
||||
+212
-19
@@ -1,9 +1,16 @@
|
||||
//! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted
|
||||
//! pixels when a texture set changes size.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind};
|
||||
use texturecraft_texel::TileImage;
|
||||
use texturecraft_compose::FlattenFolderError;
|
||||
use texturecraft_compose::eval::FlatTile;
|
||||
use texturecraft_core::{
|
||||
Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source,
|
||||
};
|
||||
use texturecraft_formats::DecodedImage;
|
||||
use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16};
|
||||
|
||||
use crate::commands::{CommandSpec, boolp, has_layer, layer_param};
|
||||
use crate::session::{Document, StackTarget};
|
||||
@@ -19,7 +26,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Flatten layer",
|
||||
["Layers"],
|
||||
Some("Ctrl+M"),
|
||||
"{layer?} — a fill or masked paint layer becomes a plain paint layer",
|
||||
"{layer?} — a fill or masked paint layer becomes a plain paint layer; a folder becomes a new fill layer above it holding one image per channel (its mask baked into a painted mask) and is hidden",
|
||||
has_layer,
|
||||
flatten
|
||||
),
|
||||
@@ -197,38 +204,224 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, "layer.flatten", p)?;
|
||||
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
|
||||
let layer = s.doc.project.layer(id)?.clone();
|
||||
// An instance flattens what it draws into a plain layer of its own.
|
||||
|
||||
// An instance flattens what it draws into a plain layer of its own
|
||||
let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?;
|
||||
if content.is_group() {
|
||||
return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into()));
|
||||
return flatten_folder(s, ts, &layer, &content);
|
||||
}
|
||||
|
||||
s.update();
|
||||
let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size;
|
||||
let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?;
|
||||
s.edit("Flatten layer", |s| {
|
||||
for c in Channel::ALL {
|
||||
s.doc.pixels.layers.remove(&(id, c));
|
||||
for channel in Channel::ALL {
|
||||
s.doc.pixels.layers.remove(&(id, channel));
|
||||
}
|
||||
let effects: Vec<LayerId> = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect();
|
||||
s.doc.pixels.masks.retain(|e, _| !effects.contains(e));
|
||||
s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e));
|
||||
for (c, (tx, ty), data) in flat {
|
||||
let img = s.doc.pixels.layer_mut(id, c, size);
|
||||
img.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
|
||||
let effects: Vec<LayerId> =
|
||||
layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()).map(|effect| effect.id).collect();
|
||||
s.doc.pixels.masks.retain(|effect, _| !effects.contains(effect));
|
||||
s.doc.pixels.layers.retain(|(effect, _), _| !effects.contains(effect));
|
||||
|
||||
for (channel, (tx, ty), data) in flat {
|
||||
let image = s.doc.pixels.layer_mut(id, channel, size);
|
||||
image.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
|
||||
}
|
||||
|
||||
let channels = s.doc.project.texture_set(ts)?.channel_list();
|
||||
let l = s.doc.project.layer_mut(id)?;
|
||||
l.kind = LayerKind::Paint;
|
||||
l.mask = None;
|
||||
l.content_effects.clear();
|
||||
l.height_mask = Default::default();
|
||||
l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect();
|
||||
let flattened = s.doc.project.layer_mut(id)?;
|
||||
flattened.kind = LayerKind::Paint;
|
||||
flattened.mask = None;
|
||||
flattened.content_effects.clear();
|
||||
flattened.height_mask = Default::default();
|
||||
flattened.channels = content.channels.into_iter().filter(|(channel, _)| channels.contains(channel)).collect();
|
||||
s.target = StackTarget::Content;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
/// Flatten `folder` (drawing `drawn`: itself, or an instance's source) of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did
|
||||
fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> Result<Value> {
|
||||
// A single fill image would repeat on each UV tile
|
||||
if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 {
|
||||
return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into()));
|
||||
}
|
||||
|
||||
// Protect visible readers that would lose an anchor
|
||||
if folder.visible && anchor_read_outside(&s.doc.project, folder.id) {
|
||||
return Err(EngineError::Other("a layer outside the folder reads one of its anchor points: flattening would change it".into()));
|
||||
}
|
||||
|
||||
s.update();
|
||||
let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size;
|
||||
let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default();
|
||||
let flattened = s
|
||||
.with_inputs(ts, |inputs| Some(texturecraft_compose::flatten_folder(inputs, folder.id, &tiles)))
|
||||
.ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let (content, mask) = flattened.map_err(|error| {
|
||||
EngineError::Other(match error {
|
||||
FlattenFolderError::NotAFolder => "nothing to flatten".into(),
|
||||
FlattenFolderError::ValueOutOfRange => "the folder's layers go past what an image holds: flattening would clip them".into(),
|
||||
})
|
||||
})?;
|
||||
let images = channel_images(content, size)?;
|
||||
if images.is_empty() {
|
||||
return Err(EngineError::Other("the folder shows nothing to flatten".into()));
|
||||
}
|
||||
|
||||
let (flat, decoded_images) = s.edit("Flatten folder", |s| {
|
||||
let mut decoded_images = Vec::with_capacity(images.len());
|
||||
let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() };
|
||||
for (channel, png, image) in images {
|
||||
let file_name = format!("{} flattened {}.png", folder.name, channel.id());
|
||||
let name = s.add_image_resource_bytes(&file_name, png)?;
|
||||
fill.sources.insert(channel, Source::image(name.clone()));
|
||||
decoded_images.push((name, crate::resource_cmds::decoded(image)));
|
||||
}
|
||||
|
||||
// Cancel ancestor transforms so baked texels stay in place
|
||||
let around = s.doc.project.contents_around(folder.id);
|
||||
fill.projection = ContentsOffset::new(around.scale.recip(), -around.rotation).apply(&fill.projection);
|
||||
|
||||
// Enabling a channel without an image would cover the stack with its default
|
||||
let channels: Vec<Channel> = fill.sources.keys().copied().collect();
|
||||
let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels);
|
||||
layer.visible = folder.visible;
|
||||
for (channel, blend) in &mut layer.channels {
|
||||
blend.opacity = drawn.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity);
|
||||
}
|
||||
if !mask.is_empty() {
|
||||
let paint = s.doc.project.alloc_id();
|
||||
let mut baked = Mask::new(MaskBackground::Black);
|
||||
baked.effects.push(Effect::new(paint, EffectKind::Paint));
|
||||
layer.mask = Some(baked);
|
||||
let image = s.doc.pixels.mask_mut(paint, size);
|
||||
for ((tx, ty), data) in mask {
|
||||
image.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
|
||||
}
|
||||
}
|
||||
|
||||
let flat = s.doc.project.insert_layer(ts, layer, Some(folder.id), false)?;
|
||||
s.doc.project.layer_mut(folder.id)?.visible = false;
|
||||
s.select_one(ts, flat);
|
||||
s.target = StackTarget::Content;
|
||||
Ok((flat, decoded_images))
|
||||
})?;
|
||||
|
||||
// Cache decoded images only after the undoable document edit succeeds
|
||||
s.images.extend(decoded_images);
|
||||
|
||||
Ok(json!({ "layer": flat.0 }))
|
||||
}
|
||||
|
||||
/// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away
|
||||
fn anchor_read_outside(project: &Project, folder: LayerId) -> bool {
|
||||
// Hiding the folder does not hide an instance's source row elsewhere
|
||||
let mut hidden = BTreeSet::new();
|
||||
let mut unvisited = vec![folder];
|
||||
while let Some(id) = unvisited.pop() {
|
||||
if hidden.insert(id) {
|
||||
unvisited.extend(project.layers.get(&id).into_iter().flat_map(|layer| layer.children().iter().copied()));
|
||||
}
|
||||
}
|
||||
|
||||
// Track masks and content still drawn through outside instances
|
||||
let drawn_again: Vec<_> = project
|
||||
.locate(folder)
|
||||
.into_iter()
|
||||
.flat_map(|(ts, _, _)| project.walk(ts))
|
||||
.filter(|(id, _)| !hidden.contains(id) && project.layers.get(id).is_some_and(|layer| layer.instance_source().is_some()))
|
||||
.map(|(id, _)| mask_and_content_owners(project, id))
|
||||
.collect();
|
||||
|
||||
let anchors = project.render_tree(&[folder]).into_iter().filter_map(|id| project.layers.get(&id)).flat_map(|layer| {
|
||||
let effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter());
|
||||
effects.filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(|effect| (layer.id, effect.id))
|
||||
});
|
||||
|
||||
anchors.into_iter().any(|(owner, anchor)| {
|
||||
project.anchor_readers(anchor).into_iter().any(|(reader, reading)| {
|
||||
!hidden.contains(&reader) || drawn_again.iter().any(|drawn| draws(project, drawn, reader, reading) && !draws(project, drawn, owner, Some(anchor)))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The layers whose masks and the layers whose content drawing layer `root` reads: an instance's own mask stands in for its source's
|
||||
fn mask_and_content_owners(project: &Project, root: LayerId) -> (BTreeSet<LayerId>, BTreeSet<LayerId>) {
|
||||
let (mut masks, mut contents, mut visited) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new());
|
||||
let mut unvisited = vec![root];
|
||||
while let Some(id) = unvisited.pop() {
|
||||
if !visited.insert(id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
masks.insert(project.mask_owner(id));
|
||||
if let Some(content) = project.content_layer(id) {
|
||||
contents.insert(content.id);
|
||||
unvisited.extend(content.children().iter().copied());
|
||||
}
|
||||
}
|
||||
(masks, contents)
|
||||
}
|
||||
|
||||
/// Whether a draw reading `owners` (see [`mask_and_content_owners`]) includes `effect` of layer `layer`, or the layer's own fill when None
|
||||
fn draws(project: &Project, (masks, contents): &(BTreeSet<LayerId>, BTreeSet<LayerId>), layer: LayerId, effect: Option<LayerId>) -> bool {
|
||||
let mask = project.layers.get(&layer).and_then(|layer| layer.mask.as_ref());
|
||||
let in_mask = mask.is_some_and(|mask| mask.effects.iter().any(|other| Some(other.id) == effect));
|
||||
if in_mask { masks.contains(&layer) } else { contents.contains(&layer) }
|
||||
}
|
||||
|
||||
/// One flattened tile of a channel: (tile, value + coverage data)
|
||||
type ChannelTile = ((u32, u32), Vec<u16>);
|
||||
|
||||
/// Flattened tiles as one 16-bit RGBA PNG per channel and its decoded pixels (straight values as a fill reads them, coverage in the alpha), in channel order
|
||||
fn channel_images(tiles: Vec<FlatTile>, size: (u32, u32)) -> Result<Vec<(Channel, Vec<u8>, DecodedImage)>> {
|
||||
let (width, height) = size;
|
||||
let mut by_channel: std::collections::BTreeMap<Channel, Vec<ChannelTile>> = Default::default();
|
||||
for (channel, tile, data) in tiles {
|
||||
by_channel.entry(channel).or_default().push((tile, data));
|
||||
}
|
||||
|
||||
by_channel
|
||||
.into_iter()
|
||||
.map(|(channel, tiles)| {
|
||||
let comps = channel.components();
|
||||
let mut rgba = vec![0u16; width as usize * height as usize * 4];
|
||||
for ((tx, ty), data) in tiles {
|
||||
for (offset, texel) in data.chunks_exact(comps + 1).enumerate() {
|
||||
let (x, y) = (tx * TILE + offset as u32 % TILE, ty * TILE + offset as u32 / TILE);
|
||||
let coverage = texel.get(comps).copied().map_or(0.0, from_u16);
|
||||
if x >= width || y >= height || coverage <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let straight = |i: usize| {
|
||||
let premultiplied = texel.get(i).copied().unwrap_or(0);
|
||||
let value = if channel.kind() == ChannelKind::Signed { from_u16_signed(premultiplied) } else { from_u16(premultiplied) };
|
||||
value / coverage
|
||||
};
|
||||
let rgb = match channel.kind() {
|
||||
ChannelKind::Color => [0, 1, 2].map(|i| linear_to_srgb(straight(i))),
|
||||
ChannelKind::NormalMap => [0, 1, 2].map(straight),
|
||||
ChannelKind::Scalar => [straight(0); 3],
|
||||
|
||||
// A fill reads a signed channel's image gray as -1..1
|
||||
ChannelKind::Signed => [(straight(0) + 1.0) * 0.5; 3],
|
||||
};
|
||||
let start = (y as usize * width as usize + x as usize) * 4;
|
||||
if let Some(pixel) = rgba.get_mut(start..start + 4) {
|
||||
pixel.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), to_u16(coverage)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (png, image) = texturecraft_formats::rgba16_resource(width, height, &rgba)
|
||||
.map_err(|error| EngineError::Other(format!("flattened {}: {error}", channel.id())))?;
|
||||
Ok((channel, png, image))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Picking a layer on the mesh (R + click in the viewport, `layer.layersAt` and `layer.pickAt`): the layers laying something down where the mesh is clicked, and selecting one of them
|
||||
|
||||
use texturecraft_core::{Channel, LayerId, LayerKind};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{PickCtx, stroke::pick_filtered};
|
||||
|
||||
use crate::session::ViewMode;
|
||||
use crate::{EngineError, Result, Session, StackTarget};
|
||||
|
||||
/// A texture set and the layers laying something down at one of its texels, top first, each with the channels it changes there
|
||||
pub type LayersUnder = (usize, Vec<(LayerId, Vec<Channel>)>);
|
||||
|
||||
impl Session {
|
||||
/// The texture set and texel of the mesh under `screen`, None off the mesh
|
||||
pub fn texel_under(&self, screen: Vec2, viewport: Vec2) -> Option<(usize, (u32, u32))> {
|
||||
let visible_set = |material| {
|
||||
let ts = self.texture_set_of_material(material)?;
|
||||
self.doc.project.texture_sets.get(ts).filter(|set| set.visible).map(|_| ts)
|
||||
};
|
||||
let nearest = self.pick(screen, viewport)?;
|
||||
let (hit, ts) = match visible_set(nearest.material) {
|
||||
Some(ts) => (nearest, ts),
|
||||
None => {
|
||||
// Only search past the first hit when its material is hidden
|
||||
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &self.camera, viewport };
|
||||
let hit = pick_filtered(&ctx, screen, &|triangle| visible_set(self.mesh.material_of(triangle as usize).unwrap_or(0)).is_some())?;
|
||||
(hit, visible_set(hit.material)?)
|
||||
}
|
||||
};
|
||||
|
||||
let cache = self.caches.get(ts)?;
|
||||
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
|
||||
let texel = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
|
||||
Some((ts, texel))
|
||||
}
|
||||
|
||||
/// The layers laying something down at `texel` of texture set `ts` in the shown channels (every channel outside a single-channel view), top first, each with the channels it changes there
|
||||
pub fn layers_at_texel(&self, ts: usize, texel: (u32, u32)) -> Vec<(LayerId, Vec<Channel>)> {
|
||||
let shown = match self.view {
|
||||
ViewMode::Channel(channel) => vec![channel],
|
||||
_ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(),
|
||||
};
|
||||
// Match the visibility of the active solo view
|
||||
let solo_view = self.solo_view();
|
||||
self.with_inputs(ts, |inputs| {
|
||||
let inputs =
|
||||
texturecraft_compose::Inputs { project: solo_view.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs };
|
||||
Some(texturecraft_compose::layers_at(&inputs, &self.projector_depth_cache, texel, &shown))
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`])
|
||||
pub fn layers_under(&self, screen: Vec2, viewport: Vec2) -> Result<LayersUnder> {
|
||||
let (ts, texel) = self.texel_under(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
Ok((ts, self.layers_at_texel(ts, texel)))
|
||||
}
|
||||
|
||||
/// Select `wanted` when it lays something down under `screen`, else the top layer there
|
||||
pub fn pick_layer(&mut self, screen: Vec2, viewport: Vec2, wanted: Option<LayerId>) -> Result<LayerId> {
|
||||
let (ts, layers) = self.layers_under(screen, viewport)?;
|
||||
let picked = match wanted {
|
||||
Some(wanted) => layers.iter().find(|(id, _)| *id == wanted).ok_or_else(|| EngineError::Other("that layer lays nothing down here".into()))?,
|
||||
None => layers.first().ok_or_else(|| EngineError::Other("no visible layer lays anything down here".into()))?,
|
||||
};
|
||||
let id = picked.0;
|
||||
|
||||
// Finish the current set's path and discard its clone source before switching
|
||||
if ts != self.ts() {
|
||||
self.finish_path()?;
|
||||
self.tool.clone_source = None;
|
||||
}
|
||||
self.active_set = ts;
|
||||
self.select_one(ts, id);
|
||||
self.open_folders_holding(id);
|
||||
self.target = StackTarget::Content;
|
||||
self.revision = self.revision.wrapping_add(1);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Expand every collapsed folder holding `id`, so the Layers panel shows its row
|
||||
fn open_folders_holding(&mut self, id: LayerId) {
|
||||
let mut child = id;
|
||||
while let Some((_, Some(folder), _)) = self.doc.project.locate(child) {
|
||||
if let Some(LayerKind::Group { collapsed, .. }) = self.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) {
|
||||
*collapsed = false;
|
||||
}
|
||||
child = folder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ pub mod decal_cmds;
|
||||
pub mod distance_params;
|
||||
pub mod effect_blending_cmds;
|
||||
pub mod effect_clipboard;
|
||||
mod effect_step;
|
||||
pub mod file_cmds;
|
||||
pub mod fill_alpha;
|
||||
pub mod fill_hit_test;
|
||||
@@ -38,6 +39,7 @@ pub mod inspect;
|
||||
pub mod instance_cmds;
|
||||
pub mod layer_cmds;
|
||||
pub mod layer_ops;
|
||||
mod layer_pick;
|
||||
pub mod layer_selection;
|
||||
pub mod link_cmds;
|
||||
pub mod log;
|
||||
|
||||
@@ -10,6 +10,7 @@ use texturecraft_core::{
|
||||
use crate::anchored_micro_edit::AnchoredMicroEdit;
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::distance_params::distance_from;
|
||||
use crate::effect_step::EffectStep;
|
||||
use crate::generator_input::GeneratorInput;
|
||||
use crate::layer_cmds::{projection_from, projection_from_fields};
|
||||
use crate::mask_owner::MaskOwner;
|
||||
@@ -118,6 +119,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
duplicate_effect
|
||||
),
|
||||
cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect),
|
||||
cmd!(
|
||||
"effect.moveUp",
|
||||
"Move effect up",
|
||||
["Layers"],
|
||||
Some("Alt+Up"),
|
||||
"{effect?: the selected effect} — one place up its stack (applied later)",
|
||||
has_layer,
|
||||
|s, p| step_effect(s, p, EffectStep::Up)
|
||||
),
|
||||
cmd!(
|
||||
"effect.moveDown",
|
||||
"Move effect down",
|
||||
["Layers"],
|
||||
Some("Alt+Down"),
|
||||
"{effect?: the selected effect} — one place down its stack (applied earlier)",
|
||||
has_layer,
|
||||
|s, p| step_effect(s, p, EffectStep::Down)
|
||||
),
|
||||
cmd!(
|
||||
"effect.histogram",
|
||||
"Effect input histogram",
|
||||
@@ -1019,6 +1038,9 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The name every generator effect got before they were named after their kind
|
||||
const FORMER_GENERATOR_NAME: &str = "Generator";
|
||||
|
||||
/// Edit visibility, blending, name, effect parameters, or a filter's type
|
||||
pub(crate) fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.set";
|
||||
@@ -1100,6 +1122,13 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
session.edit("Edit effect", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let Some(generator) = swapped_generator {
|
||||
// Preserve custom names when swapping generator kinds
|
||||
if let EffectKind::Generator(old) = &edited.kind
|
||||
&& (edited.name == old.kind.label() || edited.name == FORMER_GENERATOR_NAME)
|
||||
{
|
||||
edited.name = generator.kind.label().to_string();
|
||||
}
|
||||
|
||||
edited.kind = EffectKind::Generator(generator);
|
||||
}
|
||||
if let Some((kind, label)) = swapped {
|
||||
@@ -1389,6 +1418,28 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Move an effect one place in its stack (one undo step; nothing at its end)
|
||||
fn step_effect(s: &mut Session, p: &Value, step: EffectStep) -> Result<Value> {
|
||||
let cmd = match step {
|
||||
EffectStep::Up => "effect.moveUp",
|
||||
EffectStep::Down => "effect.moveDown",
|
||||
};
|
||||
if p.get("effect").is_some_and(|effect| !effect.is_null()) && u64p(p, "effect").is_none() {
|
||||
return Err(bad(cmd, "`effect` must be an effect id"));
|
||||
}
|
||||
|
||||
let effect = effect_id(s, p, cmd)?;
|
||||
let (list, index) = stack_of(&mut s.doc.project, effect).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?;
|
||||
let to = match step {
|
||||
EffectStep::Up if index + 1 < list.len() => index + 1,
|
||||
EffectStep::Down if index > 0 => index - 1,
|
||||
_ => return Ok(json!({ "moved": false })),
|
||||
};
|
||||
|
||||
move_effect(s, &json!({ "effect": effect.0, "index": to }))?;
|
||||
Ok(json!({ "moved": true }))
|
||||
}
|
||||
|
||||
fn remove_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(s, p, "effect.remove")?;
|
||||
s.edit("Remove effect", |s| {
|
||||
|
||||
@@ -55,6 +55,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
|
||||
Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb))
|
||||
}
|
||||
|
||||
/// Refuse resource files over [`MAX_BYTES`]
|
||||
fn within_byte_limit(file_name: &str, bytes: &[u8]) -> Result<()> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Disambiguate a sanitized resource name without losing its archive key on save.
|
||||
pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String {
|
||||
if !taken(&base) {
|
||||
@@ -95,12 +104,23 @@ impl Session {
|
||||
self.add_image_resource_prefixed("", file_name, bytes, max_texels)
|
||||
}
|
||||
|
||||
/// Store encoded pixels in the document during an edit; the caller can cache the decoded pixels after commit
|
||||
pub(crate) fn add_image_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
within_byte_limit(file_name, &bytes)?;
|
||||
Ok(self.insert_image_resource_bytes("", file_name, bytes))
|
||||
}
|
||||
|
||||
fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>, max_texels: u64) -> Result<String> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
|
||||
}
|
||||
within_byte_limit(file_name, &bytes)?;
|
||||
|
||||
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
|
||||
let name = self.insert_image_resource_bytes(prefix, file_name, bytes);
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Store `bytes` under a unique, sanitized name from `file_name` and `prefix`; returns the name
|
||||
fn insert_image_resource_bytes(&mut self, prefix: &str, file_name: &str, bytes: Vec<u8>) -> String {
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
|
||||
let mut base = sanitize_resource_name(leaf);
|
||||
|
||||
@@ -116,9 +136,7 @@ impl Session {
|
||||
let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some());
|
||||
|
||||
self.doc.resources.insert(name.clone(), Arc::new(bytes));
|
||||
self.images.insert(name.clone(), decoded(image));
|
||||
|
||||
Ok(name)
|
||||
name
|
||||
}
|
||||
|
||||
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
|
||||
|
||||
@@ -554,7 +554,7 @@ pub struct Session {
|
||||
/// are unchanged, so back-to-back dabs start instantly.
|
||||
pub(crate) depth_cache: Option<DepthCache>,
|
||||
/// Projection fill depth maps shared by this session's tile batches.
|
||||
projector_depth_cache: texturecraft_compose::ProjectorDepthCache,
|
||||
pub(crate) projector_depth_cache: texturecraft_compose::ProjectorDepthCache,
|
||||
/// The polygon fill box being dragged
|
||||
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
|
||||
/// The user's export presets (kept when another project opens).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source};
|
||||
use texturecraft_engine::core::{BlendMode, Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source};
|
||||
use texturecraft_engine::fill_alpha::resource_name;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
@@ -75,6 +75,41 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b
|
||||
assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_height_combination_makes_the_layers_height_blend_normal_in_the_same_step() {
|
||||
let (mut s, layer) = fill();
|
||||
execute(&mut s, "layer.blend", &json!({"layer": layer.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap();
|
||||
let height_mode = |s: &Session| s.doc.project.layer(layer).unwrap().channels.get(&Channel::Height).map(|blend| blend.mode);
|
||||
let before = height_mode(&s);
|
||||
assert!(before.is_some_and(|mode| mode != BlendMode::Normal), "the height starts out blending another way");
|
||||
|
||||
execute(&mut s, "mask.add.heightCombination", &json!({"layer": layer.0})).unwrap();
|
||||
assert_eq!(height_mode(&s), Some(BlendMode::Normal));
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(height_mode(&s), before, "one undo takes the mask and the blend back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instances_height_combination_sets_its_shared_height_blend_and_owns_its_mask() {
|
||||
let (mut session, source) = fill();
|
||||
execute(&mut session, "layer.blend", &json!({"layer": source.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap();
|
||||
let instance = execute(&mut session, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap();
|
||||
let original_height_mode = session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode;
|
||||
|
||||
execute(&mut session, "mask.add.heightCombination", &json!({"layer": instance.0})).unwrap();
|
||||
|
||||
let source_layer = session.doc.project.layer(source).unwrap();
|
||||
assert_eq!(source_layer.blend(Channel::Height).unwrap().mode, BlendMode::Normal);
|
||||
assert!(source_layer.mask.is_none(), "the source keeps its own mask state");
|
||||
assert!(session.doc.project.layer(instance).unwrap().mask.is_some());
|
||||
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode, original_height_mode);
|
||||
assert!(session.doc.project.layer(instance).unwrap().mask.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_selections_go_in_the_mask_and_are_selected() {
|
||||
let (mut s, layer) = fill();
|
||||
|
||||
@@ -691,3 +691,75 @@ fn a_color_histogram_has_its_components_and_luminance() {
|
||||
assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]);
|
||||
assert!(roughness.get("components").is_none(), "one value has no components");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_effect_moves_up_and_down_while_its_layer_content_is_selected() {
|
||||
let mut s = session();
|
||||
let layer = LayerId(id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let add = |s: &mut Session| id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
let (bottom, top) = (add(&mut s), add(&mut s));
|
||||
let order = |s: &Session| s.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
s.target = StackTarget::Content;
|
||||
|
||||
execute(&mut s, "effect.moveUp", &json!({"effect": bottom})).unwrap();
|
||||
|
||||
assert_eq!(order(&s), [top, bottom]);
|
||||
|
||||
execute(&mut s, "effect.moveDown", &json!({"effect": bottom})).unwrap();
|
||||
|
||||
assert_eq!(order(&s), [bottom, top]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_named_effect_does_not_move_the_selected_effect() {
|
||||
let mut session = session();
|
||||
let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
let (bottom, _) = (add(&mut session), add(&mut session));
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer, "target": bottom})).unwrap();
|
||||
let before = session.doc.project.clone();
|
||||
|
||||
let result = execute(&mut session, "effect.moveUp", &json!({"effect": "invalid"}));
|
||||
|
||||
assert!(result.unwrap_err().to_string().contains("must be an effect id"));
|
||||
assert_eq!(session.doc.project, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copying_a_named_effects_blending_preserves_an_anchor_selection() {
|
||||
let mut session = session();
|
||||
let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
let filter = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": layer})).unwrap(), "effect");
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer, "target": anchor})).unwrap();
|
||||
let selection = session.selected_layer();
|
||||
|
||||
execute(&mut session, "effect.blending.copy", &json!({"effect": filter})).unwrap();
|
||||
|
||||
assert!(session.blending_clipboard.is_some(), "the command copies the named filter's blending");
|
||||
assert_eq!(session.target, StackTarget::Effect(LayerId(anchor)));
|
||||
assert_eq!(session.selected_layer(), selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successive_effect_steps_can_share_one_undo_step() {
|
||||
let mut session = session();
|
||||
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect");
|
||||
let (bottom, middle, top) = (add(&mut session), add(&mut session), add(&mut session));
|
||||
let order = |session: &Session| session.doc.project.layers[&layer].content_effects.iter().map(|effect| effect.id.0).collect::<Vec<_>>();
|
||||
let steps_before = session.history_labels().len();
|
||||
|
||||
execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap();
|
||||
execute(&mut session, "effect.moveUp", &json!({"effect": bottom, "merge": true})).unwrap();
|
||||
let end = execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap();
|
||||
|
||||
assert_eq!(order(&session), [middle, top, bottom]);
|
||||
assert_eq!(end, json!({"moved": false}));
|
||||
assert_eq!(session.history_labels().len(), steps_before + 1);
|
||||
|
||||
execute(&mut session, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(order(&session), [bottom, middle, top]);
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Flattening a folder: a new fill layer above it reads one image per channel and its mask is baked, so the stack looks the same with the folder hidden
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{LayerId, LayerKind};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, StackTarget, execute};
|
||||
|
||||
/// The test project's texture size
|
||||
const RESOLUTION: u32 = 256;
|
||||
|
||||
/// Largest difference a flattened texel may show (16-bit images, straight values recovered from premultiplied ones)
|
||||
const TOLERANCE: f32 = 4e-3;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
|
||||
s.viewport = Vec2::new(400.0, 400.0);
|
||||
s.camera.yaw = 0.0;
|
||||
s.camera.pitch = 0.0;
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
fn id(reply: Value) -> u64 {
|
||||
reply["layer"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) {
|
||||
execute(s, "tool.brush", &json!({"size": size, "hardness": 40})).unwrap();
|
||||
execute(s, "tool.stroke", &json!({ "points": points })).unwrap();
|
||||
}
|
||||
|
||||
/// Every channel's composited value at every texel
|
||||
fn composite(s: &mut Session) -> Vec<[f32; 3]> {
|
||||
s.update();
|
||||
let channels = s.doc.project.texture_set(0).unwrap().channel_list();
|
||||
let composite = &s.caches[0].composite;
|
||||
channels.iter().flat_map(|c| (0..composite.height).flat_map(move |y| (0..composite.resolution).map(move |x| composite.value(*c, x, y)))).collect()
|
||||
}
|
||||
|
||||
fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 {
|
||||
// `f32::max` drops a NaN operand, so a broken composite would compare as equal
|
||||
assert!(a.iter().chain(b).flatten().all(|value| value.is_finite()), "the composite holds only finite values");
|
||||
a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flattened_folder_looks_the_same_as_the_folder_and_undoes_in_one_step() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "roughness": 0.2, "height": -0.3})).unwrap());
|
||||
let below = composite(&mut s);
|
||||
|
||||
// A folder over it: a masked red fill and a soft roughness stroke, with a stroke in the folder's own mask
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.9, "height": 0.4})).unwrap());
|
||||
s.target = StackTarget::Mask;
|
||||
stroke(&mut s, 30, [[170, 200], [230, 200]]);
|
||||
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.6})).unwrap();
|
||||
stroke(&mut s, 20, [[200, 160], [200, 240]]);
|
||||
execute(&mut s, "layer.select", &json!({"layer": folder})).unwrap();
|
||||
s.target = StackTarget::Mask;
|
||||
stroke(&mut s, 40, [[160, 215], [240, 215]]);
|
||||
let before = composite(&mut s);
|
||||
|
||||
assert!(largest_difference(&before, &below) > 0.1, "the folder shows over the layer below");
|
||||
|
||||
let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
|
||||
let after = composite(&mut s);
|
||||
|
||||
assert!(matches!(s.doc.project.layer(LayerId(flat)).unwrap().kind, LayerKind::Fill(_)), "the folder becomes a fill layer");
|
||||
assert!(!s.doc.project.layer(LayerId(folder)).unwrap().visible, "the folder is hidden under it");
|
||||
assert!(s.doc.project.layer(LayerId(flat)).unwrap().mask.is_some(), "the folder's mask is baked into the new layer");
|
||||
assert!(largest_difference(&after, &before) < TOLERANCE, "{}", largest_difference(&after, &before));
|
||||
|
||||
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut reopened), &before) < TOLERANCE, "the baked images keep their coverage when reopened");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert!(s.doc.project.layer(LayerId(flat)).is_err(), "one undo step removes the flattened layer");
|
||||
assert!(s.doc.project.layer(LayerId(folder)).unwrap().visible, "and shows the folder again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap());
|
||||
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap();
|
||||
stroke(&mut s, 40, [[160, 200], [240, 200]]);
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap());
|
||||
execute(&mut s, "mask.add.heightCombination", &json!({"layer": folder})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// Inside a folder, layers blending with Multiply, Screen or Overlay over the layers below the folder hide each part of the stack by a different amount: the flattened layer still shows what they did
|
||||
#[test]
|
||||
fn a_flattened_folder_looks_the_same_when_its_layers_blend_with_the_layers_below_it() {
|
||||
for mode in ["multiply", "screen", "overlay"] {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.8], "roughness": 0.4})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.9, 0.3, 0.1], "roughness": 0.7})).unwrap());
|
||||
for channel in ["baseColor", "roughness"] {
|
||||
execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": channel, "mode": mode})).unwrap();
|
||||
}
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{mode}: {}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hidden folder shows nothing, so the layer it flattens into is hidden too
|
||||
#[test]
|
||||
fn a_hidden_folder_flattens_into_a_hidden_layer() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap());
|
||||
|
||||
assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder");
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change");
|
||||
}
|
||||
|
||||
/// A generator whose micro height reads an anchor point bakes as the viewport shows it
|
||||
#[test]
|
||||
fn a_flattened_folder_keeps_a_generators_anchor_micro_height() {
|
||||
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap();
|
||||
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap()["effect"].as_u64().unwrap();
|
||||
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap();
|
||||
let generator = execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap()["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// A folder holding this one lays its Scale and Rotation on every fill inside it: the baked images stay where they were baked
|
||||
#[test]
|
||||
fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let inner = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
stroke(&mut s, 30, [[170, 190], [230, 210]]);
|
||||
execute(&mut s, "folder.contents.set", &json!({"layer": outer, "scale": 2.0, "rotation": 45.0})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": inner})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// A fill reads one image again on every UV tile, so a folder of a set with several tiles is refused instead of baked wrong
|
||||
#[test]
|
||||
fn flattening_a_folder_over_several_uv_tiles_is_refused() {
|
||||
let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": fill})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": fill, "procedural": "checker", "scale": 3.0})).unwrap();
|
||||
assert!(s.doc.project.texture_sets[0].uv_tiles.len() > 1, "the plane spans two UV tiles");
|
||||
let before = composite(&mut s);
|
||||
let steps = s.history_labels().len();
|
||||
|
||||
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
|
||||
|
||||
if flattened.is_ok() {
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
assert!(flattened.is_err(), "refused");
|
||||
assert_eq!(s.history_labels().len(), steps, "and nothing is changed");
|
||||
}
|
||||
|
||||
/// A flatten that fails once its images are stored keeps none of their decoded pixels
|
||||
#[test]
|
||||
fn a_failed_folder_flatten_keeps_no_decoded_images() {
|
||||
let mut s = session();
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
let decoded = s.images.len();
|
||||
|
||||
// The new layer gets a taken id, so placing it in the stack fails after its images are in
|
||||
s.doc.project.next_id = folder;
|
||||
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
|
||||
|
||||
let error = flattened.unwrap_err().to_string();
|
||||
assert!(error.contains("already exists"), "failed placing the new layer: {error}");
|
||||
assert_eq!(s.images.len(), decoded);
|
||||
}
|
||||
|
||||
/// A child reading an anchor point of the folder's own mask keeps what it read
|
||||
#[test]
|
||||
fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": folder, "target": "mask", "value": 0.4})).unwrap();
|
||||
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// An instance of a folder draws at its source's channel opacity, so it flattens at it
|
||||
#[test]
|
||||
fn a_flattened_folder_instance_keeps_the_folders_opacity() {
|
||||
let mut s = session();
|
||||
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.25})).unwrap();
|
||||
|
||||
// With the folder selected the instance would go inside it
|
||||
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
|
||||
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
|
||||
execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": instance})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// Hiding a folder takes its anchor points with it, so a layer outside reading one would change: refused, nothing touched
|
||||
#[test]
|
||||
fn flattening_a_folder_whose_anchor_point_is_read_outside_it_is_refused() {
|
||||
let mut s = session();
|
||||
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.0})).unwrap());
|
||||
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
|
||||
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
|
||||
execute(&mut s, "layer.move", &json!({"layer": reader, "above": folder})).unwrap();
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor, "anchorChannel": "roughness"})).unwrap();
|
||||
let project = s.doc.project.clone();
|
||||
|
||||
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
|
||||
assert_eq!(s.doc.project, project, "nothing was added or hidden");
|
||||
}
|
||||
|
||||
/// An instance's own mask goes with the hidden instance, and an outside layer stays on screen when only an instance of it sits in the folder
|
||||
#[test]
|
||||
fn flattening_is_refused_for_anchor_points_read_through_instances() {
|
||||
let mut s = session();
|
||||
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
|
||||
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
|
||||
let read = |s: &mut Session, anchor: u64| {
|
||||
execute(s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap();
|
||||
};
|
||||
let anchor = |s: &mut Session, layer: u64, target: &str| {
|
||||
execute(s, "effect.add.anchor", &json!({"layer": layer, "target": target})).unwrap()["effect"].as_u64().unwrap()
|
||||
};
|
||||
|
||||
// The anchor point sits in the instance's own mask
|
||||
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
|
||||
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
|
||||
execute(&mut s, "layer.move", &json!({"layer": reader, "above": instance})).unwrap();
|
||||
execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap();
|
||||
let own = anchor(&mut s, instance, "mask");
|
||||
read(&mut s, own);
|
||||
|
||||
assert!(execute(&mut s, "layer.flatten", &json!({"layer": instance})).is_err(), "the instance's own anchor point is read outside it");
|
||||
|
||||
// The reader is also instanced inside the folder, and reads an anchor point there
|
||||
execute(&mut s, "layer.remove", &json!({"layer": instance})).unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": child})).unwrap();
|
||||
execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap();
|
||||
let inside = anchor(&mut s, child, "content");
|
||||
read(&mut s, inside);
|
||||
|
||||
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside");
|
||||
}
|
||||
|
||||
/// An instance above the folder draws a reader from inside it, without the anchor point that reader reads
|
||||
#[test]
|
||||
fn flattening_is_refused_when_an_instance_outside_draws_a_reader_from_inside() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap();
|
||||
let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": child})).unwrap();
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap());
|
||||
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
|
||||
let project = s.doc.project.clone();
|
||||
|
||||
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
|
||||
assert_eq!(s.doc.project, project, "nothing was added or hidden");
|
||||
}
|
||||
|
||||
/// An instance with its own mask draws the folder's children without the folder's mask and its anchor points
|
||||
#[test]
|
||||
fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mask() {
|
||||
let mut s = session();
|
||||
let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap());
|
||||
execute(&mut s, "mask.add.white", &json!({"layer": folder})).unwrap();
|
||||
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap();
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap();
|
||||
execute(&mut s, "layer.select", &json!({"layer": base})).unwrap();
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap());
|
||||
execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap();
|
||||
execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err());
|
||||
}
|
||||
|
||||
/// A mask comparing a channel the set no longer has reads the folder's layers holding only that channel, before and after
|
||||
#[test]
|
||||
fn a_flattened_folder_keeps_what_its_masks_compare_in_a_removed_channel() {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap();
|
||||
stroke(&mut s, 40, [[160, 200], [240, 200]]);
|
||||
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap());
|
||||
execute(&mut s, "mask.add.heightCombination", &json!({"layer": top})).unwrap();
|
||||
execute(&mut s, "textureSet.channel.remove", &json!({"channel": "height"})).unwrap();
|
||||
let before = composite(&mut s);
|
||||
|
||||
execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap();
|
||||
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
|
||||
/// Linear dodge can take a folder's result past what an image holds, which the folder's opacity then mixes back: refused, not clipped
|
||||
#[test]
|
||||
fn flattening_a_folder_adding_up_past_white_is_refused() {
|
||||
// The last folder's mask hides everything it adds, so nothing is clipped
|
||||
for (added, masked, overflows) in [(0.25, false, false), (0.75, false, true), (0.75, true, false)] {
|
||||
let mut s = session();
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.5})).unwrap());
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.1, 0.1, 0.1], "roughness": added})).unwrap());
|
||||
execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": "roughness", "mode": "linearDodge"})).unwrap();
|
||||
execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.5})).unwrap();
|
||||
if masked {
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap();
|
||||
}
|
||||
let before = composite(&mut s);
|
||||
let project = s.doc.project.clone();
|
||||
|
||||
let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder}));
|
||||
|
||||
if flattened.is_ok() {
|
||||
assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before));
|
||||
}
|
||||
assert_eq!(flattened.is_err(), overflows, "added roughness {added}, masked {masked}: {flattened:?}");
|
||||
if overflows {
|
||||
assert_eq!(s.doc.project, project, "nothing was added or hidden");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Generator effects are named after their kind, and a name taken from the kind follows a kind change
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::LayerId;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// A sample session with a new generator of `kind` on its top layer's mask
|
||||
fn generator(kind: &str) -> (Session, LayerId) {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
let added = execute(&mut session, "effect.add.generator", &json!({"generator": kind})).unwrap();
|
||||
|
||||
(session, LayerId(added["effect"].as_u64().unwrap()))
|
||||
}
|
||||
|
||||
fn name(session: &Session, effect: LayerId) -> String {
|
||||
session.doc.project.effect(effect).unwrap().1.name.clone()
|
||||
}
|
||||
|
||||
fn set(session: &mut Session, effect: LayerId, params: Value) {
|
||||
let mut params = params;
|
||||
params["effect"] = json!(effect.0);
|
||||
execute(session, "effect.set", ¶ms).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_generator_takes_its_kinds_name_and_keeps_following_it() {
|
||||
let (mut session, effect) = generator("dirt");
|
||||
assert_eq!(name(&session, effect), "Dirt");
|
||||
|
||||
set(&mut session, effect, json!({"generator": "curvature"}));
|
||||
|
||||
assert_eq!(name(&session, effect), "Curvature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chosen_name_survives_a_kind_change() {
|
||||
let (mut session, effect) = generator("dirt");
|
||||
set(&mut session, effect, json!({"name": "Grime"}));
|
||||
|
||||
set(&mut session, effect, json!({"generator": "curvature"}));
|
||||
assert_eq!(name(&session, effect), "Grime");
|
||||
|
||||
set(&mut session, effect, json!({"generator": "dirt", "name": "Dust"}));
|
||||
assert_eq!(name(&session, effect), "Dust", "a name given with the change wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_projects_generic_generator_name_follows_its_next_kind_change() {
|
||||
let (mut session, effect) = generator("dirt");
|
||||
set(&mut session, effect, json!({"name": "Generator"}));
|
||||
|
||||
set(&mut session, effect, json!({"generator": "curvature"}));
|
||||
|
||||
assert_eq!(name(&session, effect), "Curvature");
|
||||
}
|
||||
@@ -276,3 +276,21 @@ fn budgeted_updates_spread_work_and_end_identical() {
|
||||
assert!(s.caches[0].composite == full, "chunked compositing gives the same pixels");
|
||||
assert!(s.memory().composites > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inherited_mask_effect_moves_from_another_texture_set_with_no_layer_selected() {
|
||||
let mut s = session();
|
||||
let source = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "mask.add.black", &json!({"layer": source.0})).unwrap();
|
||||
let add = |s: &mut Session| id(execute(s, "effect.add.fill", &json!({"layer": source.0, "target": "mask", "value": 0.5})).unwrap(), "effect");
|
||||
let (lower, upper) = (add(&mut s), add(&mut s));
|
||||
execute(&mut s, "layer.instance", &json!({"layer": source.0, "ts": 1})).unwrap();
|
||||
s.active_set = 1;
|
||||
s.selected.clear();
|
||||
|
||||
execute(&mut s, "effect.move", &json!({"effect": lower.0, "index": 1})).unwrap();
|
||||
|
||||
let order: Vec<LayerId> = s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
|
||||
assert_eq!(order, [upper, lower]);
|
||||
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! act on every selected layer in one undo step.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{LayerId, LayerKind};
|
||||
use texturecraft_engine::core::{BlendMode, Channel, LayerId, LayerKind};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::layer_selection::stack_rows;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
@@ -523,3 +523,35 @@ fn moving_layers_into_a_folder_in_another_set_preserves_the_document() {
|
||||
assert_eq!(s.history_labels(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rows_controls_act_on_its_layer_with_no_layer_selected() {
|
||||
let mut s = session();
|
||||
let [a, ..] = four(&mut s);
|
||||
// An undo can leave no layer selected; the row's eye and blend menu still name their layer
|
||||
s.selected.clear();
|
||||
|
||||
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
|
||||
execute(&mut s, "layer.blend", &json!({"layer": a.0, "channel": "baseColor", "mode": "Multiply"})).unwrap();
|
||||
let layer = s.doc.project.layer(a).unwrap();
|
||||
assert!(!layer.visible, "the eye hid its layer");
|
||||
assert_eq!(layer.blend(Channel::BaseColor).map(|b| b.mode), Some(BlendMode::Multiply), "the blend menu changed its layer");
|
||||
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
|
||||
assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_effect_rows_menu_moves_its_effect_with_no_layer_selected() {
|
||||
let mut s = session();
|
||||
let [a, ..] = four(&mut s);
|
||||
let add =
|
||||
|s: &mut Session| execute(s, "effect.add.filter", &json!({"layer": a.0, "target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap();
|
||||
let (lower, upper) = (add(&mut s), add(&mut s));
|
||||
s.selected.clear();
|
||||
|
||||
execute(&mut s, "effect.move", &json!({"effect": lower, "index": 1})).unwrap();
|
||||
|
||||
let order: Vec<u64> = s.doc.project.layer(a).unwrap().content_effects.iter().map(|effect| effect.id.0).collect();
|
||||
assert_eq!(order, [upper, lower]);
|
||||
assert_eq!(s.selected_layer(), None, "the selection stays as it was");
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{LayerId, LayerKind};
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, Solo, execute};
|
||||
|
||||
/// The middle of the sphere in the test viewport, where the lower paint layer is painted
|
||||
const MIDDLE: [f32; 2] = [200.0, 200.0];
|
||||
|
||||
/// A spot on the sphere left of the middle, where only the upper paint layer is painted
|
||||
const LEFT: [f32; 2] = [130.0, 200.0];
|
||||
|
||||
/// The test stack: (session, the fill at the bottom, a paint layer over the middle, a paint layer over the left spot above it)
|
||||
fn stack() -> (Session, u64, u64, u64) {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
s.viewport = Vec2::new(400.0, 400.0);
|
||||
s.camera.yaw = 0.0;
|
||||
s.camera.pitch = 0.0;
|
||||
let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
let middle = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 100})).unwrap();
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[190, 200], [210, 200]]})).unwrap();
|
||||
let left = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap());
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[125, 200], [135, 200]]})).unwrap();
|
||||
s.update();
|
||||
(s, fill, middle, left)
|
||||
}
|
||||
|
||||
fn id(reply: Value) -> u64 {
|
||||
reply["layer"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, [x, y]: [f32; 2]) -> Option<u64> {
|
||||
execute(s, "layer.pickAt", &json!({"x": x, "y": y})).ok().map(id)
|
||||
}
|
||||
|
||||
/// The layers `layer.layersAt` lists at a spot, top first, each with the channels it changes there
|
||||
fn layers_at(s: &mut Session, [x, y]: [f32; 2]) -> Vec<(u64, Vec<String>)> {
|
||||
let reply = execute(s, "layer.layersAt", &json!({"x": x, "y": y})).unwrap();
|
||||
let channels = |row: &Value| row["channels"].as_array().unwrap().iter().map(|channel| channel.as_str().unwrap().to_owned()).collect();
|
||||
reply["layers"].as_array().unwrap().iter().map(|row| (id(row.clone()), channels(row))).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spot_lists_the_layers_laying_something_there_top_first_and_a_pick_selects_the_one_asked_for() {
|
||||
let (mut s, fill, middle, left) = stack();
|
||||
execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "roughness", "opacity": 0.0})).unwrap();
|
||||
|
||||
let listed = layers_at(&mut s, MIDDLE);
|
||||
let order: Vec<u64> = listed.iter().map(|(layer, _)| *layer).collect();
|
||||
assert_eq!(order, [middle, fill], "the layer painted elsewhere is left out; the top one comes first");
|
||||
assert!(
|
||||
!listed[0].1.contains(&"roughness".to_owned()) && listed[1].1.contains(&"roughness".to_owned()),
|
||||
"a channel at zero opacity is not among the ones the layer changes there"
|
||||
);
|
||||
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(middle), "a plain pick selects the top layer");
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(middle), "the same spot again keeps the top layer");
|
||||
let picked = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": fill})).map(id).ok();
|
||||
assert_eq!(picked, Some(fill), "a listed layer is selected when asked for");
|
||||
assert_eq!(s.selected_layer_id().map(|layer| layer.0), Some(fill));
|
||||
assert!(
|
||||
execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": left})).is_err(),
|
||||
"a layer not laying anything down there is refused"
|
||||
);
|
||||
assert_eq!(click(&mut s, LEFT), Some(left), "another spot picks its own top layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_layers_and_channels_out_of_view_lay_nothing_down() {
|
||||
let (mut s, fill, middle, _) = stack();
|
||||
execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "baseColor", "opacity": 0.0})).unwrap();
|
||||
execute(&mut s, "viewport.view", &json!({"mode": "baseColor"})).unwrap();
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(fill), "in the base colour view the layer at zero base colour opacity shows nothing");
|
||||
|
||||
execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap();
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(middle), "the material view counts its other channels");
|
||||
|
||||
execute(&mut s, "layer.visible", &json!({"layer": middle, "visible": false})).unwrap();
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(fill), "a hidden layer is skipped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() {
|
||||
let (mut s, _, middle, _) = stack();
|
||||
execute(&mut s, "layer.group", &json!({"layer": middle})).unwrap();
|
||||
let inner = s.selected_layer_id().unwrap();
|
||||
execute(&mut s, "layer.group", &json!({"layer": inner.0})).unwrap();
|
||||
let outer = s.selected_layer_id().unwrap();
|
||||
for folder in [inner, outer] {
|
||||
if let Some(LayerKind::Group { collapsed, .. }) = s.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) {
|
||||
*collapsed = true;
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(middle));
|
||||
|
||||
let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. });
|
||||
assert!(open(inner) && open(outer), "both folders holding the picked layer are open");
|
||||
}
|
||||
|
||||
/// Each height-combination mask compares with the layers below its own layer, not below another's
|
||||
#[test]
|
||||
fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() {
|
||||
let (mut s, ..) = stack();
|
||||
let add = |s: &mut Session, height: f32| id(execute(s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "height": height})).unwrap());
|
||||
let base = add(&mut s, 0.0);
|
||||
let lower = add(&mut s, 0.3);
|
||||
execute(&mut s, "mask.add.heightCombination", &json!({"layer": lower})).unwrap();
|
||||
let raised = add(&mut s, 0.6);
|
||||
let upper = add(&mut s, 0.9);
|
||||
execute(&mut s, "mask.add.heightCombination", &json!({"layer": upper})).unwrap();
|
||||
for layer in [base, raised] {
|
||||
execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "height", "mode": "Normal"})).unwrap();
|
||||
}
|
||||
execute(&mut s, "layer.blend", &json!({"layer": raised, "channel": "baseColor", "enabled": false})).unwrap();
|
||||
s.update();
|
||||
|
||||
let listed: Vec<u64> = layers_at(&mut s, MIDDLE).into_iter().map(|(layer, _)| layer).collect();
|
||||
|
||||
assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}");
|
||||
assert!(listed.contains(&upper), "and so does the upper one: {listed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pick_of_something_that_is_not_a_layer_id_is_refused() {
|
||||
let (mut s, ..) = stack();
|
||||
let selected = s.selected_layer();
|
||||
|
||||
let reply = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": "fill"}));
|
||||
|
||||
assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}");
|
||||
assert_eq!(s.selected_layer(), selected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_soloed_layer_is_the_only_one_listed_and_picked() {
|
||||
let (mut s, fill, ..) = stack();
|
||||
s.set_solo(Some(Solo { layer: LayerId(fill), ignore_mask: false }));
|
||||
s.update();
|
||||
|
||||
let order: Vec<u64> = layers_at(&mut s, MIDDLE).iter().map(|(layer, _)| *layer).collect();
|
||||
|
||||
assert_eq!(order, [fill], "the layers solo hides are not on screen");
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(fill));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_instance_is_listed_once_and_picks_its_own_row() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
s.viewport = Vec2::splat(400.0);
|
||||
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.1, 0.1]})).unwrap());
|
||||
id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.25})).unwrap());
|
||||
let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder, "ts": 1})).unwrap());
|
||||
s.update();
|
||||
let point = (100..300)
|
||||
.step_by(10)
|
||||
.flat_map(|y| (100..300).step_by(10).map(move |x| [x as f32, y as f32]))
|
||||
.find(|point| {
|
||||
s.texel_under(Vec2::from(*point), s.viewport).is_some_and(|(ts, (x, y))| {
|
||||
let gbuf = &s.caches[ts].gbuf;
|
||||
ts == 1 && gbuf.surface(&s.mesh, (y * gbuf.width + x) as usize).is_some()
|
||||
})
|
||||
})
|
||||
.expect("a covered texel of the ball's second texture set");
|
||||
|
||||
let listed = layers_at(&mut s, point);
|
||||
let picked = click(&mut s, point);
|
||||
|
||||
assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::<Vec<_>>(), [instance]);
|
||||
assert!(listed[0].1.iter().any(|channel| channel == "baseColor"));
|
||||
assert!(listed[0].1.iter().any(|channel| channel == "roughness"));
|
||||
assert_eq!(picked, Some(instance));
|
||||
assert_eq!(s.ts(), 1);
|
||||
assert_eq!(s.selected_layer(), Some(LayerId(instance)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_pick_passes_through_hidden_texture_sets() {
|
||||
let rear = primitives::sphere(1.0, 48, 24);
|
||||
let mut mesh = rear.clone();
|
||||
for position in &mut mesh.positions {
|
||||
position.z += 2.5;
|
||||
}
|
||||
|
||||
mesh.append(&rear);
|
||||
let mut s = Session::new_project("t", mesh, "builtin:sphere", None, 128).unwrap();
|
||||
s.viewport = Vec2::splat(400.0);
|
||||
s.camera.yaw = 0.0;
|
||||
s.camera.pitch = 0.0;
|
||||
let near = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap());
|
||||
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
|
||||
let far = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap());
|
||||
s.update();
|
||||
assert_eq!(click(&mut s, MIDDLE), Some(near), "the visible near sphere owns this pixel");
|
||||
|
||||
execute(&mut s, "textureSet.visible", &json!({"ts": 0, "visible": false})).unwrap();
|
||||
let listed = layers_at(&mut s, MIDDLE);
|
||||
let picked = click(&mut s, MIDDLE);
|
||||
|
||||
assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::<Vec<_>>(), [far]);
|
||||
assert_eq!(picked, Some(far));
|
||||
assert_eq!(s.ts(), 1);
|
||||
}
|
||||
@@ -36,11 +36,13 @@ mod filter_support;
|
||||
mod filter_swap;
|
||||
mod filter_transform;
|
||||
mod filters;
|
||||
mod flatten_folder;
|
||||
mod folder_contents;
|
||||
mod frame_selection;
|
||||
mod generator_custom_grunge;
|
||||
mod generator_inputs;
|
||||
mod generator_micro_details;
|
||||
mod generator_names;
|
||||
mod generator_sections;
|
||||
mod generator_swap;
|
||||
mod generator_texture;
|
||||
@@ -51,6 +53,7 @@ mod high_poly_missed;
|
||||
mod instances;
|
||||
mod ior_specular;
|
||||
mod layer_multi_select;
|
||||
mod layer_pick;
|
||||
mod mask_clone_smudge;
|
||||
mod mask_export;
|
||||
mod mask_fill_source;
|
||||
|
||||
@@ -173,6 +173,21 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator<Item = f32
|
||||
Ok((png, DecodedImage { width, height, rgba, srgb: true }))
|
||||
}
|
||||
|
||||
/// A 16-bit RGBA PNG of `samples` (red, green, blue and alpha per pixel, `width × height`, top row first) and its decoded pixels, as reloading it gives them: one channel of a flattened folder
|
||||
pub fn rgba16_resource(width: u32, height: u32, samples: &[u16]) -> Result<(Vec<u8>, DecodedImage)> {
|
||||
let texels = u64::from(width) * u64::from(height);
|
||||
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)")));
|
||||
}
|
||||
|
||||
let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?;
|
||||
let png = encode_resource_png(&image)?;
|
||||
|
||||
// Divide as the PNG decoder does for RGBA, so reload is bit-identical
|
||||
let rgba = samples.as_chunks::<4>().0.iter().map(|pixel| pixel.map(|sample| f32::from(sample) / f32::from(u16::MAX))).collect();
|
||||
Ok((png, DecodedImage { width, height, rgba, srgb: true }))
|
||||
}
|
||||
|
||||
fn encode_resource_png(image: &Image) -> Result<Vec<u8>> {
|
||||
let options = EncodeOptions { png_compression: PngCompression::Fast, ..EncodeOptions::default() };
|
||||
craft_image_codecs::encode(image, Format::Png, &options).map_err(|error| FormatError::Invalid(error.to_string()))
|
||||
@@ -299,6 +314,23 @@ mod tests {
|
||||
assert!(gray16_resource(2, 1, [0.5].into_iter()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_rgba16_resource_matches_reload_for_every_sample_value() {
|
||||
// Every value in each of red, green, blue and alpha, with gray pixels as scalar channels write them
|
||||
let mixed = (0..=u16::MAX).flat_map(|value| [value, value.wrapping_add(1), value.wrapping_add(2), value.wrapping_mul(3)]);
|
||||
let gray = (0..=u16::MAX).flat_map(|value| [value, value, value, u16::MAX - value]);
|
||||
let samples: Vec<u16> = mixed.chain(gray).collect();
|
||||
|
||||
let (png, decoded) = rgba16_resource(512, 256, &samples).unwrap();
|
||||
|
||||
let reloaded = decode_image(&png).unwrap();
|
||||
assert_eq!((decoded.width, decoded.height, decoded.srgb), (reloaded.width, reloaded.height, reloaded.srgb));
|
||||
for (index, (cached, saved)) in decoded.rgba.iter().zip(&reloaded.rgba).enumerate() {
|
||||
assert_eq!(cached, saved, "pixel {index}");
|
||||
}
|
||||
assert!(rgba16_resource(2, 1, &[0; 4]).is_err(), "too few samples for the size");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray16_stops_after_one_excess_pixel() {
|
||||
let mut pixels_read = 0;
|
||||
|
||||
@@ -45,7 +45,7 @@ pub use export::{
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile,
|
||||
SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names,
|
||||
};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_resource};
|
||||
pub use mesh_export::{
|
||||
GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options,
|
||||
usd_layer_with_textures, usd_texture_bindings,
|
||||
|
||||
@@ -30,10 +30,15 @@ pub struct SurfaceHit {
|
||||
|
||||
/// Pick the mesh at a viewport pixel (origin top-left).
|
||||
pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option<SurfaceHit> {
|
||||
pick_filtered(ctx, screen, &|_| true)
|
||||
}
|
||||
|
||||
/// Pick the nearest triangle accepted by `filter` at a viewport pixel.
|
||||
pub fn pick_filtered(ctx: &PickCtx, screen: Vec2, filter: &dyn Fn(u32) -> bool) -> Option<SurfaceHit> {
|
||||
let vp = ctx.viewport.max(Vec2::ONE);
|
||||
let ndc = Vec2::new(screen.x / vp.x * 2.0 - 1.0, 1.0 - screen.y / vp.y * 2.0);
|
||||
let ray = ctx.camera.ray(ndc, vp.x / vp.y);
|
||||
let hit = ctx.bvh.closest(ray.origin, ray.dir, f32::MAX)?;
|
||||
let hit = ctx.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, filter)?;
|
||||
let s = surface_at(ctx.mesh, hit.tri, hit.u, hit.v)?;
|
||||
Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen })
|
||||
}
|
||||
|
||||
+51
-11
@@ -215,7 +215,7 @@ const SELECTED_LAYER_TINT: f32 = 0.3;
|
||||
const EYE_CHIP_INSET: f32 = 1.0;
|
||||
const EYE_CHIP_ROUNDING: f32 = 4.0;
|
||||
/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops.
|
||||
const THUMBNAIL_ROUNDING: f32 = 2.0;
|
||||
pub(crate) const THUMBNAIL_ROUNDING: f32 = 2.0;
|
||||
const THUMBNAIL_BORDER_WIDTH: f32 = 1.0;
|
||||
const HIDDEN_STRIKE_WIDTH: f32 = 1.5;
|
||||
const DROP_LINE_WIDTH: f32 = 2.0;
|
||||
@@ -280,6 +280,8 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5];
|
||||
/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part.
|
||||
const EFFECT_BLEND_WIDTH: f32 = 82.0;
|
||||
const EFFECT_OPACITY_WIDTH: f32 = 36.0;
|
||||
/// Width of the column at an effect row's right end holding its remove cross
|
||||
const EFFECT_REMOVE_WIDTH: f32 = 17.0;
|
||||
/// Hover tint of alternating layer rows
|
||||
const ALTERNATE_LAYER_SHADE: f32 = 0.45;
|
||||
/// Maximum layer-tree nesting shown by the dock
|
||||
@@ -309,7 +311,8 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) {
|
||||
|
||||
/// Preserve the effect eye, preview and a readable name before spending space on nesting.
|
||||
fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 {
|
||||
(level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0))
|
||||
let remove_column = ROW_CONTROL_GAP + EFFECT_REMOVE_WIDTH + ROW_RIGHT_PADDING;
|
||||
(level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - remove_column).max(0.0))
|
||||
}
|
||||
|
||||
/// X of the centre of the eye column at indent `level` in a row spanning from `left`.
|
||||
@@ -400,6 +403,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height));
|
||||
let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag());
|
||||
row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name));
|
||||
if app.layer_panel.reveal == Some(layer.id) {
|
||||
app.layer_panel.reveal = None;
|
||||
row.scroll_to_me(None);
|
||||
}
|
||||
|
||||
let painter = ui.painter().clone();
|
||||
|
||||
@@ -924,7 +931,7 @@ fn blend_controls(
|
||||
(picked, field.changed().then_some((percent / 100.0, merge)))
|
||||
}
|
||||
|
||||
/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`.
|
||||
/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn effect_row(
|
||||
app: &mut TextureCraftApp,
|
||||
@@ -983,11 +990,20 @@ fn effect_row(
|
||||
painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim));
|
||||
}
|
||||
|
||||
// Hide blend controls when the name needs the room
|
||||
// Keep the remove hitbox clear of the overlay scrollbar
|
||||
let remove =
|
||||
Rect::from_min_max(pos2(rect.right() - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH, rect.top()), pos2(rect.right() - ROW_CONTROL_GAP, rect.bottom()));
|
||||
let remove_hit = Rect::from_min_max(remove.min, pos2(remove.right().min(rect.right() - ui.spacing().scroll.bar_width), remove.bottom()));
|
||||
let remove_response = ui.interact(remove_hit, ui.scope_id().with(("eff_remove", effect_id.0)), Sense::click()).on_hover_text(tr("Remove effect"));
|
||||
remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, trf("Remove effect {name}", &[("name", &effect.name)])));
|
||||
let remove_color = if remove_response.hovered() { tokens.text } else { tokens.text_dim };
|
||||
painter.text(remove.center(), egui::Align2::CENTER_CENTER, ic::X, egui::FontId::proportional(EYE_FONT_SIZE), remove_color);
|
||||
|
||||
// Show blending controls only when the name has room
|
||||
let name_left = thumbnail.right() + THUMBNAIL_GAP;
|
||||
let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH;
|
||||
let controls_left = remove.left() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH;
|
||||
let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH;
|
||||
let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING };
|
||||
let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { remove.left() - ROW_RIGHT_PADDING };
|
||||
let name_color = if visible { tokens.text } else { tokens.text_dim };
|
||||
let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == effect_id.0);
|
||||
if renaming {
|
||||
@@ -1022,6 +1038,9 @@ fn effect_row(
|
||||
|
||||
if eye_response.clicked() {
|
||||
app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible}));
|
||||
} else if remove_response.clicked() {
|
||||
app.run("effect.remove", json!({"effect": effect_id.0}));
|
||||
return;
|
||||
} else if row.double_clicked() && !renaming {
|
||||
app.ui.rename = Some((effect_id.0, effect.name.clone()));
|
||||
} else if row.clicked() {
|
||||
@@ -1081,6 +1100,23 @@ fn effect_row(
|
||||
}
|
||||
}
|
||||
|
||||
// Rows list the stack top first and index 0 is its bottom, so up is one index higher
|
||||
ui.separator();
|
||||
if let Some(index) = position(effect_id.0) {
|
||||
let top = stack.len() - 1;
|
||||
for (label, to, enabled) in [
|
||||
(tr("Move up"), index + 1, index < top),
|
||||
(tr("Move down"), index.saturating_sub(1), index > 0),
|
||||
(tr("Move to top"), top, index < top),
|
||||
(tr("Move to bottom"), 0, index > 0),
|
||||
] {
|
||||
if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
|
||||
app.run("effect.move", json!({"effect": effect_id.0, "index": to}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Blending options can apply across channels or effects
|
||||
ui.separator();
|
||||
let blends = effect.kind.blends();
|
||||
@@ -1316,6 +1352,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con
|
||||
run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none());
|
||||
run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none());
|
||||
run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true);
|
||||
run(app, ui, tr("Add mask with height combination"), "mask.add.heightCombination", json!({"layer": layer_id}), true);
|
||||
if !content_thumbnail {
|
||||
ui.separator();
|
||||
mask_management_menu(app, ui, layer, false);
|
||||
@@ -1325,7 +1362,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con
|
||||
ui.separator();
|
||||
solo_menu(app, ui, layer.id);
|
||||
ui.separator();
|
||||
run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group());
|
||||
let flatten = if layer.is_group() { tr("Flatten folder") } else { tr("Flatten layer") };
|
||||
run(app, ui, flatten, "layer.flatten", json!({"layer": layer_id}), true);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if ui.button(tr("Create smart material")).clicked() {
|
||||
let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name)));
|
||||
@@ -2705,11 +2743,13 @@ mod layer_layout_tests {
|
||||
for level in 0..=14 {
|
||||
for preview in [18.0, 21.6, 28.0] {
|
||||
let indent = effect_row_indent(width, level, preview);
|
||||
let eye_right = 7.0 + indent + 16.0;
|
||||
let preview_left = 7.0 + indent + 22.0;
|
||||
let name_left = preview_left + preview + 8.0;
|
||||
let eye_right = ROW_LEFT_PADDING + indent + EYE_SIZE;
|
||||
let preview_left = ROW_LEFT_PADDING + indent + EYE_COLUMN_WIDTH;
|
||||
let name_left = preview_left + preview + THUMBNAIL_GAP;
|
||||
let name_end = width - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH - ROW_RIGHT_PADDING;
|
||||
|
||||
assert!(eye_right < preview_left);
|
||||
assert!(name_left + 20.0 <= width - 6.0 + 0.001);
|
||||
assert!(name_left + MIN_NAME_WIDTH <= name_end + 0.001, "width {width}, level {level}, preview {preview}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -755,6 +755,7 @@ pub fn fixed_gestures_grid(ui: &mut egui::Ui) {
|
||||
pub fn fixed_gestures() -> Vec<(String, String)> {
|
||||
let stencil = crate::viewport::STENCIL_KEY.name();
|
||||
let clone = crate::viewport::CLONE_SOURCE_KEY.name();
|
||||
let pick = crate::viewport::PICK_LAYER_KEY.name();
|
||||
let keyed = |template: &str| trf(template, &[("key", &stencil)]);
|
||||
vec![
|
||||
(tr("Alt + LMB drag").into(), tr("Orbit").into()),
|
||||
@@ -776,6 +777,7 @@ pub fn fixed_gestures() -> Vec<(String, String)> {
|
||||
(keyed("{key} + RMB drag"), tr("Scale the stencil").into()),
|
||||
(keyed("{key} + MMB drag"), tr("Move the stencil").into()),
|
||||
(trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()),
|
||||
(trf("{key} + LMB", &[("key", &pick)]), tr("Select the layer under the cursor; several there: pick one from a list").into()),
|
||||
(tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()),
|
||||
(tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()),
|
||||
(tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()),
|
||||
@@ -832,6 +834,7 @@ mod tests {
|
||||
let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name());
|
||||
assert!(has(&format!("{s} + LMB drag"), "Rotate") && has(&format!("{s} + RMB drag"), "Scale") && has(&format!("{s} + MMB drag"), "Move"));
|
||||
assert!(has(&format!("{v} + LMB"), "Clone"));
|
||||
assert!(has(&format!("{} + LMB", crate::viewport::PICK_LAYER_KEY.name()), "Select the layer"));
|
||||
for (gesture, what) in [
|
||||
("Shift + LMB", "straight line"),
|
||||
("Shift + RMB drag", "environment light"),
|
||||
|
||||
@@ -45,6 +45,9 @@ pub struct LayerPanel {
|
||||
pictures_begun: bool,
|
||||
/// The open stack, with `true` for a layer's mask. This belongs to the panel view.
|
||||
pub(crate) expanded_effects: Option<(LayerId, bool)>,
|
||||
/// The selected layer the panel last drew, and the one whose row scrolls into view because the selection moved to it (a pick on the mesh, a command)
|
||||
shown_selection: Option<LayerId>,
|
||||
pub(crate) reveal: Option<LayerId>,
|
||||
}
|
||||
|
||||
/// How soon to look again for pictures still rendering (milliseconds)
|
||||
@@ -59,6 +62,13 @@ impl LayerPanel {
|
||||
pub(crate) fn begin(&mut self, session: &Session, now: f64) {
|
||||
self.begin_pictures(session, now);
|
||||
|
||||
// A newly selected layer scrolls into view once
|
||||
let selected = session.selected_layer();
|
||||
if selected != self.shown_selection {
|
||||
self.shown_selection = selected;
|
||||
self.reveal = selected;
|
||||
}
|
||||
|
||||
self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The layers under the pointer while R is held over the 3D view: a label names the top one live, and a click lists every layer there to pick from
|
||||
|
||||
use egui::{Color32, Key, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::compose::ThumbTarget;
|
||||
use texturecraft_engine::core::{Channel, LayerId};
|
||||
use texturecraft_engine::geom::OrbitCamera;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::session::ViewMode;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::state::Mode;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// The list's row height, thumbnail side and the room around a row's contents (points)
|
||||
const ROW_HEIGHT: f32 = 36.0;
|
||||
const THUMBNAIL_SIZE: f32 = 28.0;
|
||||
const ROW_PADDING: f32 = 6.0;
|
||||
|
||||
/// The narrowest the list gets, so short names still give a comfortable click target (points)
|
||||
const MIN_LIST_WIDTH: f32 = 160.0;
|
||||
|
||||
/// How far the list sits right of and below the click, clear of the pointer (points)
|
||||
const LIST_OFFSET: f32 = 8.0;
|
||||
|
||||
/// Gap the list keeps from the view's edges
|
||||
const VIEW_MARGIN: f32 = 4.0;
|
||||
|
||||
/// Room between the list's frame and its rows (points)
|
||||
const LIST_MARGIN: i8 = 2;
|
||||
|
||||
/// Text sizes of a row's name and of the channels line under it
|
||||
const NAME_FONT_SIZE: f32 = 12.0;
|
||||
const CHANNELS_FONT_SIZE: f32 = 11.0;
|
||||
|
||||
/// Width of the accent edge around the focused row (points)
|
||||
const FOCUS_EDGE_WIDTH: f32 = 1.0;
|
||||
|
||||
/// The list of layers laying something down where R + click landed
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct LayerPickList {
|
||||
/// Where the click landed on screen, and in viewport pixels for `layer.pickAt`
|
||||
at: Pos2,
|
||||
point: Vec2,
|
||||
/// The view the list stays inside
|
||||
bounds: Rect,
|
||||
/// The viewport size and camera `point` was taken in: a change to either closes the list
|
||||
viewport_and_camera: (Vec2, OrbitCamera),
|
||||
/// The layers there, top first, each with the channels it changes there
|
||||
rows: Vec<(LayerId, Vec<Channel>)>,
|
||||
/// The document revision the rows were read at: any change, or another project, closes the list
|
||||
revision: u64,
|
||||
/// The list's first frame: its top row takes the keyboard focus
|
||||
opening: bool,
|
||||
/// Closed by a press outside it: until every button is up, that press neither paints nor reopens it
|
||||
closing: bool,
|
||||
}
|
||||
|
||||
/// The cached label for the texel under the pointer: (texture set, texel, document revision, view) and its text
|
||||
type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String);
|
||||
|
||||
/// R + click at `at` (`point` in viewport pixels) in the view `bounds`: one layer there is selected straight away, several open the list
|
||||
pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Rect) {
|
||||
let viewport = app.session.viewport;
|
||||
match app.session.layers_under(point, viewport) {
|
||||
Ok((_, rows)) if rows.len() > 1 => {
|
||||
app.layer_pick_list = Some(LayerPickList {
|
||||
at,
|
||||
point,
|
||||
bounds,
|
||||
viewport_and_camera: (viewport, app.session.camera),
|
||||
rows,
|
||||
revision: app.session.revision,
|
||||
opening: true,
|
||||
closing: false,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the list takes the views' clicks: open, or closing until the press that closed it ends
|
||||
pub(crate) fn blocks_view_input(app: &TextureCraftApp) -> bool {
|
||||
app.layer_pick_list.is_some()
|
||||
}
|
||||
|
||||
/// What the label at the pointer says over viewport pixel `point`: the top layer there and how many more, None off the mesh; recomputed only when the texel, document or view changes
|
||||
pub(crate) fn hover_label(app: &TextureCraftApp, ui: &Ui, point: Vec2) -> Option<String> {
|
||||
let session = &app.session;
|
||||
let (ts, texel) = session.texel_under(point, session.viewport)?;
|
||||
let key = (ts, texel, session.revision, session.view);
|
||||
let id = egui::Id::unique("layer_pick_hover_label");
|
||||
if let Some((cached, label)) = ui.data(|data| data.get_temp::<HoverLabel>(id))
|
||||
&& cached == key
|
||||
{
|
||||
return Some(label);
|
||||
}
|
||||
|
||||
let layers = session.layers_at_texel(ts, texel);
|
||||
let name = |id: &LayerId| session.doc.project.layers.get(id).map(|layer| layer.name.clone()).unwrap_or_default();
|
||||
let label = match layers.as_slice() {
|
||||
[] => tr("No layer here").to_owned(),
|
||||
[(top, _)] => name(top),
|
||||
[(top, _), more @ ..] => trf("{name} +{n} more", &[("name", &name(top)), ("n", &more.len())]),
|
||||
};
|
||||
ui.data_mut(|data| data.insert_temp::<HoverLabel>(id, (key, label.clone())));
|
||||
Some(label)
|
||||
}
|
||||
|
||||
/// The list's area, whose rect egui remembers between frames
|
||||
fn area_id() -> egui::Id {
|
||||
egui::Id::unique("layer_pick_list")
|
||||
}
|
||||
|
||||
/// Draws the open list; a row click selects its layer; Esc, a press outside or a document or view change closes it
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let (any_down, pressed_at, escape) =
|
||||
ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape)));
|
||||
let shown = ctx.memory(|memory| memory.area_rect(area_id()));
|
||||
match &mut app.layer_pick_list {
|
||||
Some(list) if app.ui.mode != Mode::Painting || escape || list.revision != app.session.revision => app.layer_pick_list = None,
|
||||
Some(list) if list.closing => {
|
||||
if !any_down {
|
||||
app.layer_pick_list = None;
|
||||
}
|
||||
}
|
||||
Some(list) if list.viewport_and_camera != (app.session.viewport, app.session.camera) => app.layer_pick_list = None,
|
||||
Some(list) if pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))) => list.closing = true,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if app.layer_pick_list.as_ref().is_some_and(|list| list.closing) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(mut list) = app.layer_pick_list.take() else { return };
|
||||
|
||||
let tokens = Tokens::get(ctx);
|
||||
let mut picked = None;
|
||||
let width = list_width(app, ctx, &list.rows);
|
||||
|
||||
// Open beside the pointer on the side with room
|
||||
let bounds = list.bounds.shrink(VIEW_MARGIN);
|
||||
let frame_width = width + 2.0 * f32::from(LIST_MARGIN);
|
||||
let left = if list.at.x + LIST_OFFSET + frame_width > bounds.right() { list.at.x - LIST_OFFSET - frame_width } else { list.at.x + LIST_OFFSET };
|
||||
let at = pos2(left, list.at.y + LIST_OFFSET);
|
||||
egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds).show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::same(LIST_MARGIN)).show(ui, |ui| {
|
||||
// A deep stack scrolls inside the view
|
||||
egui::ScrollArea::vertical().max_height(bounds.height() - 2.0 * f32::from(LIST_MARGIN)).show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
// Use egui's arrow navigation to move focus between rows
|
||||
for (index, (layer, channels)) in list.rows.iter().enumerate() {
|
||||
let response = row(app, ui, *layer, channels, width);
|
||||
if list.opening && index == 0 {
|
||||
response.request_focus();
|
||||
}
|
||||
if response.clicked() {
|
||||
picked = Some(*layer);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if let Some(layer) = picked {
|
||||
let viewport = app.session.viewport;
|
||||
app.run("layer.pickAt", json!({"x": list.point.x, "y": list.point.y, "viewport": [viewport.x, viewport.y], "layer": layer.0}));
|
||||
} else {
|
||||
list.opening = false;
|
||||
app.layer_pick_list = Some(list);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows' width: the widest name or channels line beside the thumbnail
|
||||
fn list_width(app: &TextureCraftApp, ctx: &egui::Context, rows: &[(LayerId, Vec<Channel>)]) -> f32 {
|
||||
let text_width = |text: String, font: egui::FontId| ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text, font, Color32::WHITE).size().x);
|
||||
let widest = rows
|
||||
.iter()
|
||||
.map(|(layer, channels)| {
|
||||
let name = text_width(layer_name(app, *layer), crate::theme::semibold(NAME_FONT_SIZE));
|
||||
name.max(text_width(channels_line(channels), egui::FontId::proportional(CHANNELS_FONT_SIZE)))
|
||||
})
|
||||
.fold(0.0, f32::max);
|
||||
(THUMBNAIL_SIZE + widest + ROW_PADDING * 3.0).max(MIN_LIST_WIDTH)
|
||||
}
|
||||
|
||||
/// One row: the layer's content thumbnail, its name and the channels it changes at the spot
|
||||
fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Channel], width: f32) -> egui::Response {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let name = layer_name(app, layer);
|
||||
let channels = channels_line(channels);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover());
|
||||
let response = ui.interact(rect, egui::Id::unique("layer_pick_row").with(layer.0), Sense::click());
|
||||
let selected = app.session.selected_layer() == Some(layer);
|
||||
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &name));
|
||||
|
||||
// Give keyboard focus a visible border
|
||||
let painter = ui.painter();
|
||||
if response.hovered() || response.has_focus() {
|
||||
painter.rect_filled(rect, tokens.radius, crate::dock::selected_layer_fill(&tokens));
|
||||
}
|
||||
if response.has_focus() {
|
||||
painter.rect_stroke(rect, tokens.radius, Stroke::new(FOCUS_EDGE_WIDTH, tokens.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
let thumbnail = Rect::from_min_size(pos2(rect.left() + ROW_PADDING, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
|
||||
painter.rect_filled(thumbnail, crate::dock::THUMBNAIL_ROUNDING, tokens.field);
|
||||
let target = ThumbTarget::Content { layer, channel: app.ui.layer_channel };
|
||||
|
||||
// Rows scrolled out of view ask for no thumbnail
|
||||
if ui.is_rect_visible(thumbnail)
|
||||
&& let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target)
|
||||
{
|
||||
painter.image(texture, thumbnail, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
|
||||
let text_left = thumbnail.right() + ROW_PADDING;
|
||||
painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_BOTTOM, name, crate::theme::semibold(NAME_FONT_SIZE), tokens.text_strong);
|
||||
painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_TOP, channels, egui::FontId::proportional(CHANNELS_FONT_SIZE), tokens.text_dim);
|
||||
response
|
||||
}
|
||||
|
||||
fn layer_name(app: &TextureCraftApp, layer: LayerId) -> String {
|
||||
app.session.doc.project.layers.get(&layer).map(|layer| layer.name.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The channels a layer changes at the spot, by their names
|
||||
fn channels_line(channels: &[Channel]) -> String {
|
||||
channels.iter().map(|channel| tr(channel.label())).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons and remove
|
||||
//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons, the smart material picker and remove
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::Session;
|
||||
use texturecraft_engine::core::{Layer, LayerId};
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -21,12 +24,14 @@ mod bitmap_choice;
|
||||
mod item_icon;
|
||||
mod menu_icon;
|
||||
mod pick;
|
||||
mod smart_material_choice;
|
||||
|
||||
pub(crate) use add_item::AddItem;
|
||||
use bitmap_choice::BitmapChoice;
|
||||
pub(crate) use item_icon::ItemIcon;
|
||||
pub(crate) use menu_icon::MenuIcon;
|
||||
pub(crate) use pick::Pick;
|
||||
use smart_material_choice::SmartMaterialChoice;
|
||||
|
||||
/// The row's height and its controls' height
|
||||
const BAR_HEIGHT: f32 = 40.0;
|
||||
@@ -37,14 +42,16 @@ const CONTROL_ROUNDING: u8 = 5;
|
||||
const SIDE_PADDING: f32 = 8.0;
|
||||
|
||||
const CHANNEL_WIDTH: f32 = 88.0;
|
||||
/// The channel list's width when the row gets tight: "Material" and its caret still fit, and the row fits a 1280 pt wide window's Layers panel
|
||||
const CHANNEL_MIN_WIDTH: f32 = 70.0;
|
||||
/// A menu button: its icon, then its caret
|
||||
const MENU_BUTTON_WIDTH: f32 = 32.0;
|
||||
const MENU_BUTTON_WIDTH: f32 = 30.0;
|
||||
const MENU_ICON_X: f32 = 11.0;
|
||||
const MENU_CARET_INSET: f32 = 8.0;
|
||||
const MENU_ICON_SIZE: f32 = 14.0;
|
||||
const MASK_ICON_SIZE: f32 = 12.0;
|
||||
const CARET_SIZE: f32 = 11.0;
|
||||
const BUTTON_WIDTH: f32 = 24.0;
|
||||
const BUTTON_WIDTH: f32 = 23.0;
|
||||
const ICON_SIZE: f32 = 14.0;
|
||||
/// Air after the channel list, between the two menu buttons, before the add-layer buttons and between them
|
||||
const CHANNEL_GAP: f32 = 6.0;
|
||||
@@ -52,16 +59,16 @@ const MENU_GAP: f32 = 3.0;
|
||||
const GROUP_GAP: f32 = 8.0;
|
||||
const BUTTON_GAP: f32 = 2.0;
|
||||
const CHANNEL_TEXT_X: f32 = 8.0;
|
||||
const CHANNEL_CARET_INSET: f32 = 10.0;
|
||||
const CHANNEL_CARET_INSET: f32 = 9.0;
|
||||
const CHANNEL_CARET_SIZE: f32 = 12.0;
|
||||
const TEXT_SIZE: f32 = 12.0;
|
||||
|
||||
/// The row's width besides the channel list's: its padding, the two menu buttons and their gaps
|
||||
const MENUS_ROW_WIDTH: f32 = 2.0 * SIDE_PADDING + CHANNEL_GAP + 2.0 * MENU_BUTTON_WIDTH + MENU_GAP;
|
||||
/// The three add-layer buttons and Remove
|
||||
const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP;
|
||||
/// The width every control takes in one row
|
||||
const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH;
|
||||
/// The three add-layer buttons, the smart material button and Remove
|
||||
const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + MENU_BUTTON_WIDTH + 4.0 * BUTTON_GAP;
|
||||
/// The smallest width that holds every control in one row, the channel list at its narrowest
|
||||
const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_MIN_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH;
|
||||
|
||||
/// A hanging menu: its caption, rows, icon and text columns and its smallest width
|
||||
pub(crate) const MENU_PADDING: f32 = 4.0;
|
||||
@@ -105,8 +112,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let mut x = bar.left() + SIDE_PADDING;
|
||||
let control = |x: f32, top: f32, width: f32| Rect::from_min_size(pos2(x, top), vec2(width, CONTROL_HEIGHT));
|
||||
|
||||
// Narrower still, the channel list gives up width before a menu button leaves the panel
|
||||
let channel_width = CHANNEL_WIDTH.min(width - MENUS_ROW_WIDTH).max(0.0);
|
||||
// Keep menu buttons inside by shrinking the channel control first
|
||||
let channel_room = if two_rows { width - MENUS_ROW_WIDTH } else { width - MENUS_ROW_WIDTH - GROUP_GAP - LAYER_BUTTONS_WIDTH };
|
||||
let channel_width = CHANNEL_WIDTH.min(channel_room).max(0.0);
|
||||
channel_list(app, ui, control(x, top, channel_width), &tokens);
|
||||
x += channel_width + CHANNEL_GAP;
|
||||
|
||||
@@ -119,16 +127,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
x += MENU_BUTTON_WIDTH + GROUP_GAP;
|
||||
|
||||
let (top, mut x) = if two_rows { (top + BAR_HEIGHT, bar.left() + SIDE_PADDING) } else { (top, x) };
|
||||
for (glyph, label, command) in [
|
||||
(ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"),
|
||||
(ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill"),
|
||||
(ic::FOLDER_SIMPLE, tr("Add folder"), "layer.add.group"),
|
||||
] {
|
||||
for (glyph, label, command) in [(ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill")] {
|
||||
if plain_button(ui, control(x, top, BUTTON_WIDTH), glyph, label, &tokens).clicked() {
|
||||
app.run(command, Value::Null);
|
||||
}
|
||||
x += BUTTON_WIDTH + BUTTON_GAP;
|
||||
}
|
||||
let smart_materials = ui.scope_id().with("smart_material_picker");
|
||||
picker_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add smart material"), MenuIcon::Glyph(ic::STACK), smart_materials, &tokens);
|
||||
x += MENU_BUTTON_WIDTH + BUTTON_GAP;
|
||||
if plain_button(ui, control(x, top, BUTTON_WIDTH), ic::FOLDER_SIMPLE, tr("Add folder"), &tokens).clicked() {
|
||||
app.run("layer.add.group", Value::Null);
|
||||
}
|
||||
x += BUTTON_WIDTH + BUTTON_GAP;
|
||||
let remove = control((bar.right() - SIDE_PADDING - BUTTON_WIDTH).max(x), top, BUTTON_WIDTH);
|
||||
if plain_button(ui, remove, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), &tokens).clicked() {
|
||||
app.run("layer.remove", Value::Null);
|
||||
@@ -144,6 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
if let Some(layer) = selected {
|
||||
bitmap_picker(app, &anchor, popup(layer), layer);
|
||||
}
|
||||
smart_material_picker(app, &anchor, smart_materials);
|
||||
}
|
||||
|
||||
/// Layer `id` of the project, when there is one
|
||||
@@ -260,6 +272,19 @@ pub(crate) fn menu_button(
|
||||
picked
|
||||
}
|
||||
|
||||
/// A button drawn like a menu button whose click opens or closes resource picker `popup`; it keeps its button face while the picker is open
|
||||
fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id, tokens: &Tokens) {
|
||||
let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
|
||||
if response.clicked() {
|
||||
resource_picker::toggle(ui.ctx(), popup);
|
||||
}
|
||||
if response.hovered() || response.has_focus() || egui::Popup::is_id_open(ui.ctx(), popup) {
|
||||
ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button);
|
||||
}
|
||||
button_face(ui.painter(), rect, icon, tokens);
|
||||
}
|
||||
|
||||
/// The toolbar menus' frame: chrome fill, field border, hard shadow
|
||||
pub(crate) fn menu_frame(tokens: &Tokens) -> Frame {
|
||||
Frame::NONE.fill(tokens.chrome).stroke(Stroke::new(1.0, tokens.field_border)).corner_radius(CornerRadius::same(MENU_ROUNDING)).shadow(Shadow {
|
||||
@@ -475,3 +500,77 @@ fn bitmap_tabs(session: &Session) -> Vec<PickerTab<BitmapChoice>> {
|
||||
let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }];
|
||||
vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }]
|
||||
}
|
||||
|
||||
/// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does
|
||||
fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) {
|
||||
// Opening the picker can be the first use of the saved library
|
||||
if egui::Popup::is_id_open(&anchor.ctx, popup) {
|
||||
crate::shelf::scan_library(app);
|
||||
}
|
||||
|
||||
let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default());
|
||||
match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) {
|
||||
Some(SmartMaterialChoice::BuiltIn(id)) => {
|
||||
app.run("material.apply", json!({"material": id}));
|
||||
}
|
||||
Some(SmartMaterialChoice::Saved(path)) => {
|
||||
app.run("material.load", json!({"path": path.display().to_string()}));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved
|
||||
fn smart_material_tabs(library: &[PathBuf]) -> Vec<PickerTab<SmartMaterialChoice>> {
|
||||
let built_in = MATERIALS
|
||||
.iter()
|
||||
.filter(|material| material.smart)
|
||||
.map(|material| ResourcePickerItem {
|
||||
id: SmartMaterialChoice::BuiltIn(material.id),
|
||||
label: tr(material.label).to_owned(),
|
||||
caption: Some(tr(material.category)),
|
||||
picture: TilePicture::Material(material.id),
|
||||
})
|
||||
.collect();
|
||||
let saved: Vec<_> = library
|
||||
.iter()
|
||||
// The load command requires a UTF-8 path
|
||||
.filter(|path| !crate::shelf::is_saved_mask(path) && path.to_str().is_some())
|
||||
.map(|path| ResourcePickerItem {
|
||||
id: SmartMaterialChoice::Saved(path.clone()),
|
||||
label: crate::shelf::saved_material_name(path).to_owned(),
|
||||
caption: None,
|
||||
picture: TilePicture::Glyph(ic::SPHERE),
|
||||
})
|
||||
.collect();
|
||||
let mut groups = vec![PickerGroup { header: Some(tr("Smart materials")), items: built_in }];
|
||||
if !saved.is_empty() {
|
||||
groups.push(PickerGroup { header: Some(tr("Your assets")), items: saved });
|
||||
}
|
||||
vec![PickerTab { icon: ic::STACK, name: tr("Smart materials"), groups }]
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_smart_material_picker_lists_only_files_it_can_name_to_the_load_command() {
|
||||
let unnameable = PathBuf::from(std::ffi::OsString::from_vec(b"/library/rust\xff.tcmat".to_vec()));
|
||||
let tabs = smart_material_tabs(&[unnameable, PathBuf::from("/library/steel.tcmat")]);
|
||||
|
||||
let saved: Vec<_> = tabs
|
||||
.iter()
|
||||
.flat_map(|tab| &tab.groups)
|
||||
.flat_map(|group| &group.items)
|
||||
.filter_map(|item| match &item.id {
|
||||
SmartMaterialChoice::Saved(path) => Some(path.as_path()),
|
||||
SmartMaterialChoice::BuiltIn(_) => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
assert_eq!(saved, [std::path::Path::new("/library/steel.tcmat")]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! A pick of the Layers toolbar's smart material picker
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// A built-in smart material by id, or one the user saved, by file
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub(super) enum SmartMaterialChoice {
|
||||
BuiltIn(&'static str),
|
||||
Saved(PathBuf),
|
||||
}
|
||||
@@ -81,6 +81,7 @@ mod inactive_set_hint;
|
||||
mod instance_properties;
|
||||
pub mod keymap;
|
||||
pub mod layer_panel;
|
||||
pub mod layer_pick_list;
|
||||
mod layer_toolbar;
|
||||
mod layout_dialog;
|
||||
mod levels_display;
|
||||
@@ -365,6 +366,8 @@ pub struct TextureCraftApp {
|
||||
pub moving_on_model: Option<move_on_model::MoveOnModel>,
|
||||
/// The Properties popup a right click in a view opens.
|
||||
pub properties_popup: Option<properties_popup::PropertiesPopup>,
|
||||
/// The layers under an R + click in the 3D view to pick one from
|
||||
pub layer_pick_list: Option<layer_pick_list::LayerPickList>,
|
||||
properties_scroll: property_sheet::PropertiesScroll,
|
||||
/// The color selection the next click in the 3D or 2D view picks an ID color for
|
||||
pub picking_id_color: Option<id_color_pick::IdColorPick>,
|
||||
@@ -536,6 +539,7 @@ impl TextureCraftApp {
|
||||
last_paint_uv: None,
|
||||
moving_on_model: None,
|
||||
properties_popup: None,
|
||||
layer_pick_list: None,
|
||||
properties_scroll: property_sheet::PropertiesScroll::default(),
|
||||
picking_id_color: None,
|
||||
picking_symmetry_plane: false,
|
||||
|
||||
@@ -567,6 +567,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
crate::import_resources::keys_in(app, input, nothing_focused, popup_open);
|
||||
} else if popup_open || modal_open || export_input_active {
|
||||
// The open list, dialog or export input handles the key
|
||||
} else if escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
// The list opens over an armed eyedropper or point pick, so it closes first
|
||||
app.layer_pick_list = None;
|
||||
} else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.picking_color = None;
|
||||
} else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
|
||||
@@ -384,7 +384,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[(ShelfEntry, Option<u
|
||||
}
|
||||
|
||||
/// Whether a library file is a saved smart mask (not a smart material)
|
||||
fn is_saved_mask(path: &std::path::Path) -> bool {
|
||||
pub(crate) fn is_saved_mask(path: &std::path::Path) -> bool {
|
||||
path.extension().is_some_and(|extension| extension == texturecraft_engine::smart_masks::SMART_MASK_EXT)
|
||||
}
|
||||
|
||||
@@ -427,7 +427,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
|
||||
|
||||
/// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan_library(app: &mut TextureCraftApp) {
|
||||
pub(crate) fn scan_library(app: &mut TextureCraftApp) {
|
||||
if app.library.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -453,10 +453,10 @@ fn scan_library(app: &mut TextureCraftApp) {
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn scan_library(_: &mut TextureCraftApp) {}
|
||||
pub(crate) fn scan_library(_: &mut TextureCraftApp) {}
|
||||
|
||||
/// A saved smart material's name: its file name without the extension
|
||||
fn saved_material_name(path: &std::path::Path) -> &str {
|
||||
pub(crate) fn saved_material_name(path: &std::path::Path) -> &str {
|
||||
path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME)
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE};
|
||||
pub const STENCIL_KEY: egui::Key = egui::Key::S;
|
||||
/// Hold this key with the Clone tool and click to set the source
|
||||
pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V;
|
||||
/// Hold this key with any tool and click the mesh to select the layer laying something down there
|
||||
pub const PICK_LAYER_KEY: egui::Key = egui::Key::R;
|
||||
|
||||
pub const VIEW_3D: u64 = 1;
|
||||
pub const VIEW_2D: u64 = 2;
|
||||
@@ -164,6 +166,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
crate::properties_popup::show(app, ui.ctx());
|
||||
crate::layer_pick_list::show(app, ui.ctx());
|
||||
|
||||
if mode == crate::state::Mode::Rendering {
|
||||
crate::render_mode::show(app, ui, full);
|
||||
@@ -914,11 +917,26 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}));
|
||||
}
|
||||
|
||||
// Layer picking takes precedence over the active painting tool
|
||||
let r_held = layer_pick_key(app, ui);
|
||||
if r_held
|
||||
&& !alt
|
||||
&& app.layer_pick_list.is_none()
|
||||
&& response.clicked_by(PointerButton::Primary)
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
crate::layer_pick_list::click(app, pointer, local(pointer), rect);
|
||||
}
|
||||
|
||||
// The layer list consumes clicks before any armed picker
|
||||
let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app);
|
||||
|
||||
// A 3D generator's armed point pick: a click sets the point there instead of painting
|
||||
let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session);
|
||||
if let Some(pick) = point_pick {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
if !alt
|
||||
&& !layer_pick_takes_click
|
||||
&& response.clicked_by(PointerButton::Primary)
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
@@ -938,6 +956,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
if picking_focus_distance {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
if !alt
|
||||
&& !layer_pick_takes_click
|
||||
&& response.clicked_by(PointerButton::Primary)
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
@@ -950,11 +969,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
// A dismissing click cannot paint or place a decal through the rail popup
|
||||
let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx());
|
||||
|
||||
crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held);
|
||||
crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held || r_held);
|
||||
|
||||
// A press that closes an open colour picker only closes it: it neither paints nor moves a projection
|
||||
let picker = crate::color_picker::blocks_view_press(ui.ctx());
|
||||
let popup = app.properties_popup.is_some() || rail_popup || picker;
|
||||
let popup = app.properties_popup.is_some() || crate::layer_pick_list::blocks_view_input(app) || rail_popup || picker;
|
||||
|
||||
// A pending ID color pick or eyedropper takes the next click instead of the brush
|
||||
let picking = app.picking_id_color.is_some() || app.picking_color.is_some();
|
||||
@@ -973,6 +992,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color);
|
||||
}
|
||||
if !alt
|
||||
&& !layer_pick_takes_click
|
||||
&& response.clicked_by(PointerButton::Primary)
|
||||
&& let Some(position) = response.interact_pointer_pos()
|
||||
{
|
||||
@@ -985,8 +1005,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
}
|
||||
|
||||
// Only a press on a projection handle moves the selected fill
|
||||
let gizmo_free =
|
||||
!adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx());
|
||||
let gizmo_free = !adjusting
|
||||
&& !alt
|
||||
&& !holding
|
||||
&& !s_held
|
||||
&& !v_held
|
||||
&& !r_held
|
||||
&& !focus_pick
|
||||
&& !popup
|
||||
&& !picking
|
||||
&& touch.is_none()
|
||||
&& !DecalDrop::blocks_input(ui.ctx());
|
||||
let gizmo = ShownGizmo::of(app, rect);
|
||||
let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at)));
|
||||
let frame_drag = gizmo_free && began_on_handle && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref());
|
||||
@@ -1003,6 +1032,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let plane_pick = !popup
|
||||
&& !s_held
|
||||
&& !v_held
|
||||
&& !r_held
|
||||
&& !focus_pick
|
||||
&& !picking
|
||||
&& touch.is_none()
|
||||
@@ -1014,6 +1044,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& !adjusting
|
||||
&& !s_held
|
||||
&& !v_held
|
||||
&& !r_held
|
||||
&& !focus_pick
|
||||
&& !popup
|
||||
&& !picking
|
||||
@@ -1033,6 +1064,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& !adjusting
|
||||
&& !s_held
|
||||
&& !v_held
|
||||
&& !r_held
|
||||
&& !focus_pick
|
||||
&& !picking
|
||||
&& touch.is_none()
|
||||
@@ -1087,11 +1119,14 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
app.session.continue_stroke(local(pointer), pressure);
|
||||
remember_line_anchor(app, local(pointer));
|
||||
}
|
||||
if response.drag_stopped_by(PointerButton::Primary)
|
||||
&& let Err(error) = app.session.end_stroke()
|
||||
{
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
}
|
||||
|
||||
// Finish a stroke even if a later keypress blocks painting
|
||||
if response.drag_stopped_by(PointerButton::Primary)
|
||||
&& app.session.stroke_active()
|
||||
&& let Err(error) = app.session.end_stroke()
|
||||
{
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
|
||||
let set_hover = app
|
||||
@@ -1110,6 +1145,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
polygon_fill_box_overlay(ui, rect, fill_box);
|
||||
|
||||
// Announce the contributing layer while the pick key is held
|
||||
if r_held
|
||||
&& app.layer_pick_list.is_none()
|
||||
&& let Some(hover) = response.hover_pos()
|
||||
&& let Some(label) = crate::layer_pick_list::hover_label(app, ui, local(hover))
|
||||
{
|
||||
layer_pick_hint(ui, rect, hover, &label);
|
||||
}
|
||||
|
||||
// Route shelf drops by asset type to a layer, decal, or brush
|
||||
crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d);
|
||||
|
||||
@@ -1117,6 +1161,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let mut symmetry_cursor = None;
|
||||
if tool_acts(app)
|
||||
&& !navigating
|
||||
&& !r_held
|
||||
&& response.hovered()
|
||||
&& brush_tool(app.session.tool.tool)
|
||||
&& (app.session.tool.tool != Tool::Path || adjusting)
|
||||
@@ -1758,6 +1803,53 @@ fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool {
|
||||
&& !crate::framework::widget_has_keyboard(ui.ctx())
|
||||
}
|
||||
|
||||
/// R held over a view in painting mode, outside a text field: clicks select the layer under the cursor
|
||||
fn layer_pick_key(app: &TextureCraftApp, ui: &Ui) -> bool {
|
||||
app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(PICK_LAYER_KEY)) && !ui.ctx().egui_wants_keyboard_input()
|
||||
}
|
||||
|
||||
/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held, announced as it changes
|
||||
fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let painter = ui.painter_at(rect);
|
||||
let font = egui::TextStyle::Small.resolve(ui.style());
|
||||
let mut text = egui::text::LayoutJob::simple_singleline(label.to_owned(), font, tokens.text);
|
||||
text.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 2.0 * LAYER_PICK_HINT_PADDING).max(0.0));
|
||||
let galley = painter.layout_job(text);
|
||||
|
||||
let frame = layer_pick_hint_frame(rect, hover, galley.size());
|
||||
let at = frame.min + vec2(LAYER_PICK_HINT_PADDING, LAYER_PICK_HINT_PADDING);
|
||||
painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel);
|
||||
painter.rect_stroke(
|
||||
frame,
|
||||
egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8),
|
||||
Stroke::new(LAYER_PICK_HINT_BORDER_WIDTH, tokens.separator),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
painter.galley(at, galley, tokens.text);
|
||||
|
||||
let announced = ui.interact(frame, egui::Id::unique("layer_pick_hint"), egui::Sense::empty());
|
||||
announced.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label));
|
||||
ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite));
|
||||
}
|
||||
|
||||
/// The layer pick label's frame around text of `size`: beside the pointer, slid back inside `view` near its edges
|
||||
fn layer_pick_hint_frame(view: Rect, hover: Pos2, size: egui::Vec2) -> Rect {
|
||||
let inset = egui::Vec2::splat(LAYER_PICK_HINT_PADDING);
|
||||
let size = (size + 2.0 * inset).min(view.size());
|
||||
let preferred = hover + egui::Vec2::splat(LAYER_PICK_HINT_OFFSET) - inset;
|
||||
let origin = preferred.min(view.max - size).max(view.min);
|
||||
Rect::from_min_size(origin, size)
|
||||
}
|
||||
|
||||
/// How far the layer pick label sits right of and below the pointer, and the room around its text (points)
|
||||
const LAYER_PICK_HINT_OFFSET: f32 = 16.0;
|
||||
const LAYER_PICK_HINT_PADDING: f32 = 4.0;
|
||||
|
||||
/// Width of the layer pick label's border (points)
|
||||
const LAYER_PICK_HINT_BORDER_WIDTH: f32 = 1.0;
|
||||
|
||||
/// Crosshair where the Clone tool reads from.
|
||||
fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) {
|
||||
if let Some(center) = project(app, rect, pos) {
|
||||
@@ -2256,6 +2348,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let painting = tool_acts(app)
|
||||
&& !projection_hint
|
||||
&& app.properties_popup.is_none()
|
||||
&& !crate::layer_pick_list::blocks_view_input(app)
|
||||
&& !crate::rail_popup::blocks_paint_input(app, ui.ctx())
|
||||
&& !crate::color_picker::blocks_view_press(ui.ctx())
|
||||
&& !alt
|
||||
@@ -2573,6 +2666,22 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel:
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_layer_pick_label_stays_inside_the_view_at_its_edges() {
|
||||
let view = Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0));
|
||||
let size = vec2(120.0, 14.0);
|
||||
for hover in [view.min, view.center(), view.right_center() - vec2(2.0, 0.0), view.max - vec2(2.0, 2.0)] {
|
||||
let frame = layer_pick_hint_frame(view, hover, size);
|
||||
|
||||
assert!(view.contains_rect(frame), "hover {hover:?}: {frame:?}");
|
||||
}
|
||||
|
||||
let wide = layer_pick_hint_frame(view, view.center(), vec2(600.0, 14.0));
|
||||
|
||||
assert!(view.contains_rect(wide), "a label wider than the view still fits: {wide:?}");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn hovering_a_texture_set_row_previews_it_without_selecting_it() {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options
|
||||
//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its cross removes it, its blend mode and opacity sit at its right, and its menu holds the Blending options
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
@@ -65,6 +65,107 @@ fn dragging_an_effect_row_reorders_its_stack() {
|
||||
assert_eq!(order(&harness), [a, c, b]);
|
||||
}
|
||||
|
||||
/// An effect row's menu moves it one step or to an end of its stack; a move past an end is greyed
|
||||
#[test]
|
||||
fn an_effect_rows_menu_moves_it_within_its_stack() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let mut add =
|
||||
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
|
||||
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let mut harness = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 1400.0))
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
|
||||
harness.run_steps(4);
|
||||
click_selected_content_thumbnail(&mut harness);
|
||||
let order =
|
||||
|harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| {
|
||||
harness.get_by_label(row).click_secondary();
|
||||
harness.run_steps(3);
|
||||
harness.get_by_label(item).click();
|
||||
harness.run_steps(3);
|
||||
};
|
||||
|
||||
menu_item(&mut harness, "Effect A", "Move up");
|
||||
assert_eq!(order(&harness), [b, a, c]);
|
||||
menu_item(&mut harness, "Effect A", "Move to top");
|
||||
assert_eq!(order(&harness), [b, c, a]);
|
||||
menu_item(&mut harness, "Effect C", "Move down");
|
||||
assert_eq!(order(&harness), [c, b, a]);
|
||||
menu_item(&mut harness, "Effect A", "Move to bottom");
|
||||
assert_eq!(order(&harness), [a, c, b]);
|
||||
|
||||
harness.get_by_label("Effect A").click_secondary();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.get_by_label("Move down").accesskit_node().is_disabled(), "the bottom effect can't go lower");
|
||||
assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
/// Alt+Up and Alt+Down move the selected effect one place in its stack; at its end it stays
|
||||
#[test]
|
||||
fn alt_up_and_down_move_the_selected_effect() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let mut add =
|
||||
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
|
||||
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let mut harness = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 1400.0))
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
|
||||
harness.run_steps(4);
|
||||
click_selected_content_thumbnail(&mut harness);
|
||||
let order =
|
||||
|harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| {
|
||||
harness.key_press_modifiers(egui::Modifiers::ALT, key);
|
||||
harness.run_steps(3);
|
||||
};
|
||||
harness.get_by_label("Effect A").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
press(&mut harness, egui::Key::ArrowUp);
|
||||
assert_eq!(order(&harness), [b, a, c]);
|
||||
press(&mut harness, egui::Key::ArrowUp);
|
||||
assert_eq!(order(&harness), [b, c, a]);
|
||||
press(&mut harness, egui::Key::ArrowUp);
|
||||
assert_eq!(order(&harness), [b, c, a], "the top effect stays");
|
||||
press(&mut harness, egui::Key::ArrowDown);
|
||||
assert_eq!(order(&harness), [b, a, c]);
|
||||
}
|
||||
|
||||
/// The cross at an effect row's right end removes that effect alone, in one undo step
|
||||
#[test]
|
||||
fn an_effect_rows_cross_removes_it() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
|
||||
let mut add =
|
||||
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
|
||||
let a = add("Effect A");
|
||||
add("Effect B");
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let mut harness = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 1400.0))
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
|
||||
harness.run_steps(4);
|
||||
click_selected_content_thumbnail(&mut harness);
|
||||
let undo_steps = harness.state().session.history_labels().len();
|
||||
|
||||
let at = harness.get_by_label("Remove effect Effect B").rect().center();
|
||||
harness.drag_at(at);
|
||||
harness.drop_at(at);
|
||||
harness.run_steps(3);
|
||||
|
||||
let remaining = harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
|
||||
assert_eq!(remaining, [a]);
|
||||
assert_eq!(harness.state().session.history_labels().len(), undo_steps + 1);
|
||||
}
|
||||
|
||||
/// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows
|
||||
#[test]
|
||||
fn an_effect_row_sets_its_blend_mode_and_opacity() {
|
||||
@@ -85,9 +186,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() {
|
||||
harness.state_mut().ui.layer_material_view = false;
|
||||
harness.run_steps(2);
|
||||
|
||||
// From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field
|
||||
// Left of the remove cross: a 4-point gap, then the 82-point pair of mode menu and opacity field
|
||||
let row = harness.get_by_label("Effect A").rect();
|
||||
let pair_right = row.right() - 4.0;
|
||||
let pair_right = harness.get_by_label("Remove effect Effect A").rect().left() - 4.0;
|
||||
let pair_left = pair_right - 82.0;
|
||||
let mode_at = egui::pos2(pair_left + 20.0, row.center().y);
|
||||
harness.drag_at(mode_at);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! The Layers panel's top row: Add effect greys what can't go where the selection is, Add mask adds a mask with its effect, and
|
||||
//! Bitmap adds nothing until a texture is picked
|
||||
//! Bitmap adds nothing until a texture is picked; Add smart material adds the smart material picked
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source};
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
use texturecraft_engine::{StackTarget, execute};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
@@ -130,6 +131,38 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer()
|
||||
assert!(mask_kinds(&harness, opener).is_empty(), "nor the layer that opened it");
|
||||
}
|
||||
|
||||
/// The selected texture set's top-level layers, bottom to top
|
||||
fn stack(harness: &Harness<'_, TextureCraftApp>) -> Vec<LayerId> {
|
||||
let session = &harness.state().session;
|
||||
session.doc.project.texture_set(session.ts()).unwrap().stack.clone()
|
||||
}
|
||||
|
||||
/// Add smart material opens a picker of the smart materials only; a pick adds its folder right above the selected layer
|
||||
#[test]
|
||||
fn add_smart_material_adds_the_picked_smart_material_above_the_selection() {
|
||||
let (mut harness, layer) = app();
|
||||
let smart = MATERIALS.iter().find(|material| material.smart).unwrap();
|
||||
let simple = MATERIALS.iter().find(|material| !material.smart).unwrap();
|
||||
let tiles_of = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).map(|node| node.rect()).collect::<Vec<_>>();
|
||||
let (smart_before, simple_before) = (tiles_of(&harness, smart.label), tiles_of(&harness, simple.label));
|
||||
|
||||
click_widget(&mut harness, Role::Button, "Add smart material");
|
||||
let new_tile = tiles_of(&harness, smart.label).into_iter().find(|tile| !smart_before.contains(tile));
|
||||
|
||||
assert!(egui::Popup::is_any_open(&harness.ctx), "the button opens the picker");
|
||||
assert_eq!(tiles_of(&harness, simple.label).len(), simple_before.len(), "simple materials stay out of it");
|
||||
|
||||
let before = stack(&harness);
|
||||
click_at(&mut harness, new_tile.expect("a tile for the smart material").center());
|
||||
let after = stack(&harness);
|
||||
let added: Vec<_> = after.iter().filter(|id| !before.contains(id)).copied().collect();
|
||||
|
||||
assert_eq!(added.len(), 1, "one folder added: {added:?}");
|
||||
let place = |id: LayerId| after.iter().position(|shown| *shown == id).unwrap();
|
||||
assert_eq!(place(added[0]), place(layer) + 1, "right above the selection");
|
||||
assert!(!egui::Popup::is_any_open(&harness.ctx), "the pick closes the picker");
|
||||
}
|
||||
|
||||
/// A floating Layers panel this narrow cannot hold the toolbar on one row
|
||||
const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0];
|
||||
|
||||
@@ -152,7 +185,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() {
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
let [left, _, width, _] = NARROW_LAYERS;
|
||||
|
||||
for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] {
|
||||
for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add smart material", "Add folder", "Remove layer"] {
|
||||
let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect();
|
||||
|
||||
assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel");
|
||||
@@ -218,3 +251,23 @@ fn the_channel_list_starts_on_material_and_picks_a_channel_or_material_again() {
|
||||
assert!(harness.state().ui.layer_material_view, "Material shows the whole material again");
|
||||
assert_eq!(harness.state().ui.layer_channel, Channel::Roughness, "the rows keep the last channel's blending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_smart_material_shows_the_keyboard_focus() {
|
||||
let (mut harness, _) = app();
|
||||
let button = harness.get_by_role_and_label(Role::Button, "Add smart material").rect();
|
||||
let fills = |harness: &Harness<'_, TextureCraftApp>| {
|
||||
harness
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.filter(|clipped| matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == button && shape.fill != egui::Color32::TRANSPARENT))
|
||||
.count()
|
||||
};
|
||||
assert_eq!(fills(&harness), 0, "no face at rest");
|
||||
|
||||
harness.get_by_role_and_label(Role::Button, "Add smart material").focus();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(fills(&harness) > 0, "the focused button is drawn");
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! document, and the thumbnail images arrive from the worker.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use egui_kittest::kittest::{NodeT, Queryable, by};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::compose::ThumbTarget;
|
||||
use texturecraft_engine::core::{Channel, LayerId};
|
||||
@@ -238,7 +238,8 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() {
|
||||
let row = harness.get_by_label("Effect A").rect();
|
||||
assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}");
|
||||
|
||||
let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0);
|
||||
// The nesting gives way to the row's edge, eye column, preview, gap, name and remove column
|
||||
let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 27.0).max(0.0);
|
||||
click(&mut harness, egui::pos2(row.left() + 15.0 + indent, row.center().y));
|
||||
|
||||
let content = &harness.state().session.doc.project.layers[&layer].content_effects;
|
||||
@@ -385,7 +386,7 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> {
|
||||
#[test]
|
||||
fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() {
|
||||
let h = narrow_harness();
|
||||
let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect());
|
||||
let buttons = ["Add paint layer", "Add fill layer", "Add smart material", "Add folder"].map(|label| h.get_by_label(label).rect());
|
||||
|
||||
let wand = h.get_by_label("Add effect").rect();
|
||||
let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect();
|
||||
@@ -508,6 +509,19 @@ fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui::
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_row_menu_adds_a_height_combination_to_the_clicked_layers_mask() {
|
||||
let (mut h, layer) = harness();
|
||||
let row = h.get_by_label("Masked fill").rect();
|
||||
right_click(&mut h, row.center());
|
||||
h.get_by_label("Add mask with height combination").click();
|
||||
h.run_steps(3);
|
||||
|
||||
let mask = h.state().session.doc.project.layers[&layer].mask.clone().unwrap();
|
||||
assert_eq!(mask.effects.len(), 2, "the compare lands in the existing mask");
|
||||
assert!(mask.effects.iter().any(|effect| matches!(effect.kind, texturecraft_engine::core::EffectKind::Compare { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_context_menu_solos_a_layer_without_touching_the_document() {
|
||||
let (mut h, layer) = harness();
|
||||
@@ -751,3 +765,260 @@ fn dragging_a_row_opacity_adds_one_undo_step() {
|
||||
assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h));
|
||||
assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step");
|
||||
}
|
||||
|
||||
/// When the selection moves to a layer below the panel's visible rows (a pick on the mesh, a command), its row scrolls into view
|
||||
#[test]
|
||||
fn a_newly_selected_layer_out_of_view_scrolls_into_view() {
|
||||
let (mut h, _) = harness();
|
||||
for index in 0..20 {
|
||||
execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": format!("Filler {index}")})).unwrap();
|
||||
}
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
let bottom = h.state().session.doc.project.texture_sets[h.state().session.ts()].stack[0];
|
||||
let name = h.state().session.doc.project.layers[&bottom].name.clone();
|
||||
|
||||
let before = h.get_by_label(&name).rect();
|
||||
assert!(before.top() > properties_top(&h), "the bottom layer starts out of view");
|
||||
execute(&mut h.state_mut().session, "layer.select", &json!({"layer": bottom.0})).unwrap();
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let after = h.get_by_label(&name).rect();
|
||||
assert!(after.bottom() <= properties_top(&h), "its row is inside the panel");
|
||||
}
|
||||
|
||||
/// The top of the Properties tab, which sits under the Layers panel
|
||||
fn properties_top(h: &Harness<'_, TextureCraftApp>) -> f32 {
|
||||
h.query_all(by().role(egui::Role::Tab).label_contains("Properties")).next().map(|tab| tab.rect().top()).unwrap_or(f32::MAX)
|
||||
}
|
||||
|
||||
/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer, and Escape closes it
|
||||
#[test]
|
||||
fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() {
|
||||
let (mut h, _) = harness();
|
||||
let session = &mut h.state_mut().session;
|
||||
let lower = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Lower fill", "color": "#aa3322"})).unwrap(), "layer"));
|
||||
let upper = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Upper fill", "color": "#2233aa"})).unwrap(), "layer"));
|
||||
let empty = LayerId(id(execute(session, "layer.add.paint", &json!({"name": "Empty on top"})).unwrap(), "layer"));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
let steps = h.state().session.history_labels().len();
|
||||
let view = h.state().viewport_rect;
|
||||
let in_list = |h: &Harness<'_, TextureCraftApp>, name: &str| h.get_all_by_label(name).map(|node| node.rect()).find(|rect| view.contains(rect.center()));
|
||||
let open_list = |h: &mut Harness<'_, TextureCraftApp>| {
|
||||
let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
h.event(key(true));
|
||||
h.hover_at(view.center());
|
||||
h.run_steps(1);
|
||||
click(h, view.center());
|
||||
h.event(key(false));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
};
|
||||
|
||||
open_list(&mut h);
|
||||
|
||||
assert!(in_list(&h, "Upper fill").is_some() && in_list(&h, "Lower fill").is_some(), "both fills under the click are listed over the view");
|
||||
assert!(in_list(&h, "Empty on top").is_none(), "the empty top layer lays nothing down there");
|
||||
assert_eq!(h.state().session.selected_layer(), Some(empty), "opening the list selects nothing yet");
|
||||
|
||||
h.key_press(egui::Key::ArrowDown);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert_eq!(h.state().session.selected_layer(), Some(lower), "Down from the top row and Enter select the second layer");
|
||||
assert!(h.state().layer_pick_list.is_none(), "picking closes the list");
|
||||
|
||||
open_list(&mut h);
|
||||
let row = in_list(&h, "Upper fill").unwrap().center();
|
||||
click(&mut h, row);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert_eq!(h.state().session.selected_layer(), Some(upper), "the clicked row's layer is selected");
|
||||
assert_eq!(h.state().session.history_labels().len(), steps, "no stroke was painted");
|
||||
|
||||
// The first Escape moves egui's focus off the top row: the list must close on it all the same
|
||||
open_list(&mut h);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "Escape closes the list");
|
||||
assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing");
|
||||
}
|
||||
|
||||
/// Two fills over the whole model, so R + click opens the list; returns the 3D view
|
||||
fn two_fills(h: &mut Harness<'_, TextureCraftApp>) -> egui::Rect {
|
||||
for name in ["Lower fill", "Upper fill"] {
|
||||
execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": name, "color": "#aa3322"})).unwrap();
|
||||
}
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
h.state().viewport_rect
|
||||
}
|
||||
|
||||
/// R + click at the middle of the 3D view
|
||||
fn open_pick_list(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
let middle = h.state().viewport_rect.center();
|
||||
let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
h.event(key(true));
|
||||
h.hover_at(middle);
|
||||
h.run_steps(1);
|
||||
click(h, middle);
|
||||
h.event(key(false));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
assert!(h.state().layer_pick_list.is_some(), "the list is open");
|
||||
}
|
||||
|
||||
/// The list opened over an armed point pick is the innermost thing: Escape closes it first, and a press that closes it sets no point
|
||||
#[test]
|
||||
fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_pick() {
|
||||
let (mut h, _) = harness();
|
||||
let view = two_fills(&mut h);
|
||||
execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap();
|
||||
let effect = id(execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "3dDistance"})).unwrap(), "effect");
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
let generator = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone();
|
||||
let armed =
|
||||
|h: &Harness<'_, TextureCraftApp>| h.get_by_label("Pick 3D Position on the mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True);
|
||||
h.get_by_label("Pick 3D Position on the mesh").click();
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
assert!(armed(&h), "the pick is armed");
|
||||
let before = generator(&h);
|
||||
|
||||
open_pick_list(&mut h);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "Escape closes the list");
|
||||
assert!(armed(&h), "and leaves the point pick armed");
|
||||
|
||||
open_pick_list(&mut h);
|
||||
click(&mut h, view.center() - egui::vec2(60.0, 40.0));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "a press outside closes the list");
|
||||
assert_eq!(generator(&h), before, "and sets no point");
|
||||
assert!(armed(&h));
|
||||
}
|
||||
|
||||
/// The list names layers of the stack it was opened on: an edit, an undo or another project closes it
|
||||
#[test]
|
||||
fn the_layer_pick_list_closes_when_the_document_changes() {
|
||||
let (mut h, _) = harness();
|
||||
two_fills(&mut h);
|
||||
open_pick_list(&mut h);
|
||||
|
||||
execute(&mut h.state_mut().session, "edit.undo", &Value::Null).unwrap();
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none());
|
||||
}
|
||||
|
||||
/// In the split view, a press on the 2D view that closes the list paints nothing there
|
||||
#[test]
|
||||
fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() {
|
||||
let (mut h, _) = harness();
|
||||
two_fills(&mut h);
|
||||
execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap();
|
||||
h.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split;
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
let view = h.state().viewport_rect;
|
||||
let over_2d = egui::pos2(view.right() + view.width() * 0.5, view.center().y);
|
||||
let steps = h.state().session.history_labels().len();
|
||||
open_pick_list(&mut h);
|
||||
|
||||
click(&mut h, over_2d);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "the press closes the list");
|
||||
assert_eq!(h.state().session.history_labels().len(), steps, "and paints no stroke");
|
||||
|
||||
click(&mut h, over_2d);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().session.history_labels().len() > steps, "the next press paints there");
|
||||
}
|
||||
|
||||
/// The list holds the spot it was opened on: a view that changed size or camera no longer has it under that point
|
||||
#[test]
|
||||
fn the_layer_pick_list_closes_when_the_view_changes() {
|
||||
let (mut h, _) = harness();
|
||||
two_fills(&mut h);
|
||||
open_pick_list(&mut h);
|
||||
|
||||
h.state_mut().session.camera.yaw += 0.5;
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "the camera turned");
|
||||
|
||||
open_pick_list(&mut h);
|
||||
h.set_size(egui::vec2(1300.0, 1000.0));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "the view was resized");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r_and_a_click_leaves_an_armed_eyedropper_armed() {
|
||||
let (mut h, _) = harness();
|
||||
two_fills(&mut h);
|
||||
h.state_mut().picking_color = Some(egui::Id::unique("armed eyedropper"));
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
assert!(h.state().picking_color.is_some(), "armed before the list opens");
|
||||
|
||||
open_pick_list(&mut h);
|
||||
|
||||
assert!(h.state().picking_color.is_some());
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(h.state().layer_pick_list.is_none(), "Escape closes the list first");
|
||||
assert!(h.state().picking_color.is_some(), "and leaves the eyedropper armed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_released_while_r_is_held_ends() {
|
||||
let (mut h, _) = harness();
|
||||
execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap();
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
let middle = h.state().viewport_rect.center();
|
||||
let end = middle + egui::vec2(60.0, 0.0);
|
||||
h.drag_at(middle);
|
||||
h.run_steps(1);
|
||||
h.hover_at(middle + egui::vec2(30.0, 0.0));
|
||||
h.run_steps(1);
|
||||
assert!(h.state().session.stroke_active(), "the stroke is under way");
|
||||
|
||||
h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
h.hover_at(end);
|
||||
h.run_steps(1);
|
||||
h.drop_at(end);
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(!h.state().session.stroke_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_under_the_pointer_is_announced_while_r_is_held() {
|
||||
let (mut h, _) = harness();
|
||||
let view = two_fills(&mut h);
|
||||
h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
h.hover_at(view.center());
|
||||
h.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let announced = h.query_all(by().label_contains("Upper fill +")).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite);
|
||||
|
||||
assert!(announced, "the layer's name is announced without moving the focus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_layer_pick_hint_stays_inside_the_viewport() {
|
||||
let (mut harness, _) = harness();
|
||||
let view = two_fills(&mut harness);
|
||||
let layer_name = "Wide fill ".repeat(24);
|
||||
execute(&mut harness.state_mut().session, "layer.rename", &json!({"name": layer_name})).unwrap();
|
||||
|
||||
harness.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
harness.hover_at(view.center());
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
let hint = harness.query_all(by().label_contains(layer_name.trim())).find(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite).unwrap();
|
||||
assert!(view.contains_rect(hint.rect()), "the whole hint fits in the viewport");
|
||||
}
|
||||
@@ -22,7 +22,8 @@ Submitting the current name leaves history unchanged. The project file keeps its
|
||||
`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. `effect.move {effect,
|
||||
index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies
|
||||
one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the
|
||||
one just above itself. `effect.moveUp {effect?}` / `effect.moveDown {effect?}` move the named (or
|
||||
selected) effect one place and reply `{moved}` (false at that end). `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the
|
||||
layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask.
|
||||
`layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer`
|
||||
is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and
|
||||
@@ -37,7 +38,18 @@ layer, the others in stack order; `layer.duplicate` puts the copies in one block
|
||||
topmost selected layer. Without `layer`, `layer.remove`, `layer.duplicate`,
|
||||
`layer.group` and `layer.visible` act on every selected layer; each of them and `layer.move
|
||||
{layers, above | index}` also take an explicit `layers` list. `session.inspect` lists the
|
||||
selection as `selectedLayers` (top row first).
|
||||
selection as `selectedLayers` (top row first). A command that takes `layer` is checked against
|
||||
the named layer of the active texture set, so it runs even with nothing selected.
|
||||
|
||||
`layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a
|
||||
viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels).
|
||||
`layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there.
|
||||
Both commands skip hidden texture sets and respect solo. A folder instance is listed by its own
|
||||
row, with the channels drawn by its source.
|
||||
`layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's
|
||||
result as image resources, and hides the folder; it is refused for a texture set with several UV
|
||||
tiles, for a visible folder holding an anchor point that a layer outside it reads, and for a
|
||||
folder whose layers' blend modes go past a channel's range (an image would clip the result).
|
||||
|
||||
`mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the
|
||||
texture set's resolution: black where the mesh does not cover the texture, with the orientation
|
||||
|
||||
@@ -46,6 +46,23 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
one layer alone in the 3D and 2D views, optionally without its mask (Alt+Shift+click, or
|
||||
**Solo layer without its mask**), to judge a material hidden behind a mask. It is only a view:
|
||||
the document, the undo history, saving, exporting and baking never see it.
|
||||
- **Pick a layer on the model:** hold R over the 3D view, with any tool: a label at the pointer
|
||||
names the top layer laying something down there (the shown channel in a single-channel view)
|
||||
and how many more. Click: one layer there is selected; several open a list at the pointer with
|
||||
each one's thumbnail, name and the channels it changes there, to pick from (Up/Down, Enter, Esc
|
||||
work too). Closed folders holding the picked layer open and its row scrolls into view.
|
||||
- **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the
|
||||
folder's result as one image per channel, with the folder's mask painted into the new layer's
|
||||
mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked
|
||||
as they look over them at that moment. Flattening is refused for a texture set with several UV
|
||||
tiles, when an outside layer reads one of the folder's anchor points, or when the resulting
|
||||
values cannot be reproduced within the generated images' value ranges.
|
||||
- **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's
|
||||
Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack.
|
||||
- **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in
|
||||
and saved smart materials.
|
||||
- **Height combination masks** (Add mask menus) also set the layer's height to blend Normal.
|
||||
On an instance, the mask belongs to the instance and the height blend follows the shared content.
|
||||
- **Several layers at once:** Shift+click a layer to select the rows from the last clicked one,
|
||||
Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer
|
||||
over the Layers panel to select every shown row (folder rows and the layers of open folders).
|
||||
|
||||
Reference in new issue
Block a user