mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-22 23:40:45 +01:00
Fills: review repairs from #698
Chasse's repairs to this part's code, carried over from the #698 head (5644b7d3).
This commit is contained in:
1 parent
82b981e641
commit
a7d165e029
79 files changed
+1198
-261
No files matched your search
@@ -165,8 +165,7 @@ impl eframe::App for Shell {
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
|
||||
// winit gives the window its caption back when it changes the window's flags (maximize,
|
||||
// restore, …): take it off again before the frame is laid out.
|
||||
// Restore the frameless style after winit changes the window flags
|
||||
if let Some(guard) = self.window_frame.as_mut() {
|
||||
guard();
|
||||
}
|
||||
|
||||
@@ -284,7 +284,9 @@ mod tests {
|
||||
let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1);
|
||||
mesh.append(&texturecraft_engine::geom::primitives::plane(2.0, 1));
|
||||
let mut session = Session::new_project("Test", mesh, "two-planes", None, 128).unwrap();
|
||||
|
||||
assert_eq!(session.caches.len(), 2);
|
||||
|
||||
session.images.insert("red".into(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 0.0, 0.0, 1.0]], true)));
|
||||
execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap();
|
||||
let camera = session.camera;
|
||||
@@ -302,6 +304,7 @@ mod tests {
|
||||
assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
|
||||
|
||||
let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap();
|
||||
|
||||
assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20));
|
||||
assert_eq!(gpu.h.renderer.aux_size(1), Some(128));
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ mod tests {
|
||||
fn only_axis_planars_are_placed() {
|
||||
let bounds = (Vec3::NEG_ONE, Vec3::ONE);
|
||||
assert!(placed_from_axis(&Projection::default(), bounds).is_none());
|
||||
|
||||
let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame");
|
||||
assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none());
|
||||
assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none());
|
||||
|
||||
+169
-36
@@ -2,6 +2,7 @@
|
||||
//! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport
|
||||
//! and for export.
|
||||
|
||||
mod evaluation_inputs;
|
||||
pub(crate) mod thumbnail;
|
||||
|
||||
use std::borrow::Cow;
|
||||
@@ -18,6 +19,7 @@ use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
|
||||
|
||||
use crate::ProjectorDepthCache;
|
||||
use crate::below::{Band, BelowCache, Level, StackKey};
|
||||
use crate::curvature_sizes::CurvatureSizes;
|
||||
use crate::fill_copies::FillCopies;
|
||||
@@ -29,6 +31,7 @@ use crate::pattern_context::PatternContext;
|
||||
use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all};
|
||||
use crate::projector_depth::ProjectorDepth;
|
||||
use crate::store::{BakedMaps, ImageRes, ImageStore, PixelStore, decode};
|
||||
use evaluation_inputs::EvaluationInputs;
|
||||
|
||||
const NCH: usize = Channel::ALL.len();
|
||||
|
||||
@@ -71,6 +74,7 @@ impl Stencil {
|
||||
if c.w <= 1e-6 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]);
|
||||
let (sn, cs) = (-self.rotation).sin_cos();
|
||||
let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6);
|
||||
@@ -78,6 +82,7 @@ impl Stencil {
|
||||
if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5);
|
||||
let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] };
|
||||
Some((rgb, s[3].clamp(0.0, 1.0)))
|
||||
@@ -279,6 +284,7 @@ impl Field {
|
||||
if x < self.x0 || y < self.y0 || x >= self.x0 + self.w || y >= self.y0 + self.h {
|
||||
return None;
|
||||
}
|
||||
|
||||
let i = ((y - self.y0) * self.w + (x - self.x0)) as usize * self.comps;
|
||||
self.data.get(i..i + self.comps)
|
||||
}
|
||||
@@ -600,7 +606,7 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 {
|
||||
|
||||
/// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated
|
||||
/// up to the layer, it records the anchors below it.
|
||||
fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec<Node<'a>> {
|
||||
fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec<Node<'a>> {
|
||||
match inp.project.texture_set(inp.ts) {
|
||||
Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields),
|
||||
_ => Vec::new(),
|
||||
@@ -639,7 +645,7 @@ enum Job<'a> {
|
||||
}
|
||||
|
||||
/// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`.
|
||||
fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option<Field> {
|
||||
fn field(inp: &EvaluationInputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option<Field> {
|
||||
let effects = match job {
|
||||
Job::Mask(mask) => &mask.effects,
|
||||
Job::Content(_) => &inp.project.content_layer(id)?.content_effects,
|
||||
@@ -709,7 +715,7 @@ fn is_box_blur(op: Op) -> bool {
|
||||
/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn filter_region(
|
||||
inputs: &Inputs,
|
||||
inputs: &EvaluationInputs,
|
||||
channels: &[Channel],
|
||||
below: &Fields,
|
||||
id: LayerId,
|
||||
@@ -1021,13 +1027,19 @@ fn unpremultiply(data: &mut [f32], comps: usize) {
|
||||
/// Precompute the neighbourhood-filtered masks and content channels of every layer that needs
|
||||
/// one, over `tiles` plus the filter's reach. Walks bottom → top so each field sees the fields
|
||||
/// (and anchors) below it. Cheap when no layer has a blur or sharpen.
|
||||
pub fn neighbourhood_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields {
|
||||
pub fn neighbourhood_fields(inputs: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = EvaluationInputs::new(inputs, &projectors);
|
||||
evaluation_fields(&inputs, channels, tiles)
|
||||
}
|
||||
|
||||
fn evaluation_fields(inp: &EvaluationInputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Fields {
|
||||
let stack = inp.project.texture_set(inp.ts).map(|s| s.stack.as_slice()).unwrap_or_default();
|
||||
fields_of(inp, channels, stack, tiles)
|
||||
}
|
||||
|
||||
/// [`neighbourhood_fields`] of the layers drawn by `list` only.
|
||||
fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields {
|
||||
fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32, u32)]) -> Fields {
|
||||
let mut out = Fields::new();
|
||||
if tiles.is_empty() || inp.gbuf.width == 0 {
|
||||
return out;
|
||||
@@ -1147,7 +1159,8 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann
|
||||
if (img.width(), img.height()) == (w, h) {
|
||||
return img.tile(tx, ty).map(Cow::Borrowed);
|
||||
}
|
||||
// Empty texels of signed channels hold a signed zero.
|
||||
|
||||
// Empty texels of signed channels hold a signed zero
|
||||
let empty: Vec<u16> = match channel {
|
||||
Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(),
|
||||
_ => Vec::new(),
|
||||
@@ -1171,7 +1184,7 @@ fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u3
|
||||
Some(MaskPlan { background, effects, start })
|
||||
}
|
||||
|
||||
fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec<Node<'a>> {
|
||||
fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec<Node<'a>> {
|
||||
if depth > texturecraft_core::project::MAX_DEPTH {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -1182,7 +1195,7 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t
|
||||
/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids`
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn plan_node<'a>(
|
||||
inp: &Inputs<'a>,
|
||||
inp: &EvaluationInputs<'a>,
|
||||
id: LayerId,
|
||||
channels: &[Channel],
|
||||
tx: u32,
|
||||
@@ -1271,7 +1284,7 @@ struct LevelPlan<'a> {
|
||||
|
||||
/// Plan the path to the hot layer for tile (tx, ty); the layers before the path are left out
|
||||
/// on tiles the cache holds (`warm`).
|
||||
fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec<LevelPlan<'a>> {
|
||||
fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Channel], tx: u32, ty: u32, fields: &'a Fields, warm: bool) -> Vec<LevelPlan<'a>> {
|
||||
let last = levels.len().saturating_sub(1);
|
||||
levels
|
||||
.iter()
|
||||
@@ -1294,6 +1307,7 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3
|
||||
if a <= 0.0 {
|
||||
return (v, cov);
|
||||
}
|
||||
|
||||
let b = if cov > 0.0 { blend_chan(c, mode, v, p) } else { p };
|
||||
let nc = a + cov * (1.0 - a);
|
||||
(mix3(v, b, a / nc.max(1e-5)), nc)
|
||||
@@ -1312,8 +1326,8 @@ fn covers_every_texel(proj: &Projection, sampling: Sampling, depth: Option<&Proj
|
||||
}
|
||||
|
||||
/// A fill's projector depth (None: not culled by depth) and whether it covers every texel
|
||||
fn fill_coverage(inp: &Inputs, projection: &Projection, sampling: Sampling) -> (Option<Arc<ProjectorDepth>>, bool) {
|
||||
let depth = ProjectorDepth::of(inp.mesh, inp.bounds, projection);
|
||||
fn fill_coverage(inp: &EvaluationInputs, projection: &Projection, sampling: Sampling) -> (Option<Arc<ProjectorDepth>>, bool) {
|
||||
let depth = inp.projectors.get(inp.mesh, inp.bounds, projection);
|
||||
let covers_all = covers_every_texel(projection, sampling, depth.as_deref());
|
||||
(depth, covers_all)
|
||||
}
|
||||
@@ -1523,7 +1537,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
|
||||
/// A fill's value and coverage through `proj`, from `one` (which samples it once): with `sampling`'s symmetry on, every copy of the projection is sampled and the copies are laid over each other, the texel's own copy on top
|
||||
fn symmetric(&mut self, proj: &Projection, sampling: Sampling, mut one: impl FnMut(&mut Self) -> ([f32; 3], f32)) -> ([f32; 3], f32) {
|
||||
// Most fills have no symmetry: they are sampled directly and never pay for the surface lookup
|
||||
// Skip the world-space lookup when no symmetry copies are needed
|
||||
if !takes_symmetry(proj, sampling) {
|
||||
return one(self);
|
||||
}
|
||||
@@ -1589,7 +1603,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
/// `place`'s fill at this texel in channel `ch`, every symmetric copy laid over each other when its symmetry is on
|
||||
#[inline(always)]
|
||||
fn fill_place_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) {
|
||||
// Without symmetry the fill is sampled directly: through `symmetric`'s closure a plain fill composites about 8% slower
|
||||
// Sample directly without symmetry to keep the common path free of the copy search
|
||||
if takes_symmetry(&place.fill.projection, place.fill.sampling) {
|
||||
self.symmetric(&place.fill.projection, place.fill.sampling, |texel| texel.fill_texel(place, source, ch))
|
||||
} else {
|
||||
@@ -1646,7 +1660,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
let samples = self.image_uvs(proj, &c);
|
||||
let [(uv, _), ..] = samples;
|
||||
|
||||
// The shape is read over the footprint the image's colour is, so a shrunk image's coverage matches its averaged colour
|
||||
// Use the image's sampling footprint so minified color and coverage agree
|
||||
let alpha = image.map_or(1.0, |img| {
|
||||
let [footprint, ..] = match sampling.filtering {
|
||||
Filtering::BilinearHq => self.footprints(proj, &samples, img),
|
||||
@@ -1818,7 +1832,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
/// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked).
|
||||
fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option<f32> {
|
||||
match generator.inputs.get(&map) {
|
||||
// Generator inputs have no sampling setting: they read as projects saved before sampling choices did
|
||||
// Keep legacy sampling for generator inputs without a sampling setting
|
||||
Some(source) => Some(self.source(source, &Projection::default(), Sampling::SAVED_BEFORE, ChannelKind::Scalar)[0]),
|
||||
None => self.baked(map),
|
||||
}
|
||||
@@ -2026,8 +2040,8 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
/// is identical.
|
||||
fn eval_split(&mut self, mut acc: Acc, levels: &[LevelPlan], accs: &mut [Acc], masks: &mut [f32], warm: bool, tape: &mut Tape<'b>) -> Acc {
|
||||
let last = levels.len().saturating_sub(1);
|
||||
// Down the path: the deepest level the stack reaches (a folder masked out or not drawn
|
||||
// here stops it).
|
||||
|
||||
// A hidden or masked folder limits how far the evaluator descends
|
||||
let mut reach = last;
|
||||
for (d, lv) in levels.iter().enumerate() {
|
||||
if !warm {
|
||||
@@ -2039,6 +2053,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
if d == last {
|
||||
break;
|
||||
}
|
||||
|
||||
let m = match &lv.at {
|
||||
Some(g) => self.taped(tape, |t| t.tape_mask(g)),
|
||||
None => 0.0,
|
||||
@@ -2049,6 +2064,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
if m > 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
reach = d;
|
||||
break;
|
||||
}
|
||||
@@ -2058,7 +2074,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
{
|
||||
self.eval(std::slice::from_ref(hot), &mut acc);
|
||||
}
|
||||
// Back up: the layers after the path, then each folder's mix over the stack outside it.
|
||||
// Back up: the layers after the path, then each folder's mix over the stack outside it
|
||||
for d in (0..=reach).rev() {
|
||||
if let Some(lv) = levels.get(d) {
|
||||
self.taped(tape, |t| t.eval(&lv.above, &mut acc));
|
||||
@@ -2100,10 +2116,11 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
if tri == NO_TRI {
|
||||
return true;
|
||||
}
|
||||
|
||||
let first = tri.saturating_mul(3);
|
||||
let subs = &self.inp.mesh.submeshes;
|
||||
let holds = |k: usize| subs.get(k).is_some_and(|s| s.start <= first && first < s.start.saturating_add(s.count));
|
||||
// Submeshes are in index order; anything else is searched.
|
||||
// Submeshes are in index order; anything else is searched
|
||||
let k = subs.partition_point(|s| s.start <= first).checked_sub(1).filter(|k| holds(*k)).or_else(|| (0..subs.len()).find(|k| holds(*k)));
|
||||
k.and_then(|k| allowed.get(k).copied()).unwrap_or(true)
|
||||
}
|
||||
@@ -2154,7 +2171,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) {
|
||||
let pv = if preview { self.inp.preview } else { None };
|
||||
let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0);
|
||||
// Projection: the stencil's alpha shapes the stroke and its color is the base color.
|
||||
// Projection: the stencil's alpha shapes the stroke and its color is the base color
|
||||
let stencil = match pv.and_then(|p| p.stencil.as_ref()) {
|
||||
Some(st) if sa > 0.0 => {
|
||||
let s = self.world().and_then(|w| st.sample_world(w));
|
||||
@@ -2200,6 +2217,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
if cov <= 0.0 {
|
||||
return ([0.0; 3], 0.0);
|
||||
}
|
||||
|
||||
let inv = 1.0 / cov.max(1e-5);
|
||||
let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] };
|
||||
(v, cov.min(1.0))
|
||||
@@ -2272,7 +2290,37 @@ pub const BLOCK: u32 = 16;
|
||||
|
||||
/// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and
|
||||
/// filling it). Results are identical to [`composite_tiles`].
|
||||
pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) {
|
||||
pub fn composite_tiles_cached(inputs: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = EvaluationInputs::new(inputs, &projectors);
|
||||
composite_evaluation_tiles(&inputs, out, tiles, below);
|
||||
}
|
||||
|
||||
/// Composite tile batches with a reusable cache for the mesh owned by the caller.
|
||||
pub fn composite_tiles_with_projectors(
|
||||
inputs: &Inputs,
|
||||
mesh: &Arc<Mesh>,
|
||||
projectors: &mut ProjectorDepthCache,
|
||||
out: &mut Composite,
|
||||
tiles: &[(u32, u32)],
|
||||
mut below: Option<&mut BelowCache>,
|
||||
) {
|
||||
if !std::ptr::eq(inputs.mesh, mesh.as_ref()) {
|
||||
composite_tiles_cached(inputs, out, tiles, None);
|
||||
return;
|
||||
}
|
||||
|
||||
if projectors.bind(mesh)
|
||||
&& let Some(cache) = below.as_deref_mut()
|
||||
{
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
let inputs = EvaluationInputs::new(inputs, projectors);
|
||||
composite_evaluation_tiles(&inputs, out, tiles, below);
|
||||
}
|
||||
|
||||
fn composite_evaluation_tiles(inp: &EvaluationInputs, out: &mut Composite, tiles: &[(u32, u32)], mut below: Option<&mut BelowCache>) {
|
||||
let Ok(set) = inp.project.texture_set(inp.ts) else { return };
|
||||
if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) {
|
||||
return;
|
||||
@@ -2378,7 +2426,7 @@ fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool {
|
||||
|
||||
/// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`),
|
||||
/// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`.
|
||||
fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields {
|
||||
fn block_fields(inp: &EvaluationInputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields {
|
||||
match hot {
|
||||
Some(hot) if fresh.len() < tiles.len() => {
|
||||
let mut fields = fields_of(inp, channels, stack, fresh);
|
||||
@@ -2402,7 +2450,7 @@ type Joined = (Vec<Option<std::sync::Arc<Vec<u16>>>>, bool);
|
||||
/// Composite one block of tiles, split along the path to the hot layer when `below` holds it;
|
||||
/// returns what to cache (for at most `quota` tiles).
|
||||
fn composite_block(
|
||||
inp: &Inputs,
|
||||
inp: &EvaluationInputs,
|
||||
stack: &[LayerId],
|
||||
out: &mut Composite,
|
||||
tiles: &[(u32, u32)],
|
||||
@@ -2421,7 +2469,7 @@ fn composite_block(
|
||||
let level_count = split.map_or(0, <[Level]>::len);
|
||||
let defaults: Acc = Channel::ALL.map(Channel::default_value);
|
||||
|
||||
// Tiles split into bands of rows, so a handful of tiles still keeps every thread busy.
|
||||
// Tiles split into bands of rows, so a handful of tiles still keeps every thread busy
|
||||
let bands = TILE / BAND;
|
||||
let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect();
|
||||
let mut results: Vec<BandResult> = tasks
|
||||
@@ -2459,11 +2507,13 @@ fn composite_block(
|
||||
if y >= h {
|
||||
break;
|
||||
}
|
||||
|
||||
for lx in 0..TILE {
|
||||
let x = tx * TILE + lx;
|
||||
if x >= w {
|
||||
break;
|
||||
}
|
||||
|
||||
let gbuffer_index = (y * w + x) as usize;
|
||||
let tile_offset = (ly * TILE + lx) as usize;
|
||||
let band_offset = ((ly - band * BAND) * TILE + lx) as usize;
|
||||
@@ -2473,11 +2523,11 @@ fn composite_block(
|
||||
any = true;
|
||||
let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset));
|
||||
|
||||
// Reuse one anchor buffer per band.
|
||||
// Reuse one anchor buffer per band
|
||||
texel.anchors = std::mem::take(&mut anchors);
|
||||
match &levels {
|
||||
Some(levels) => {
|
||||
// The texel's stream starts with the stack at each level.
|
||||
// The texel's stream starts with the stack at each level
|
||||
let start = match &mut tape {
|
||||
Tape::Record(t) => {
|
||||
t.resize(t.len() + slots, 0.0);
|
||||
@@ -2518,7 +2568,7 @@ fn composite_block(
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Join the bands of each tile (in parallel; uncovered tiles are freed).
|
||||
// Join the bands of each tile (in parallel; uncovered tiles are freed)
|
||||
let joined: Vec<Joined> = results
|
||||
.par_chunks(bands as usize)
|
||||
.map(|parts| {
|
||||
@@ -2545,7 +2595,7 @@ fn composite_block(
|
||||
}
|
||||
}
|
||||
|
||||
// Tiles without covered texels cost nothing to composite: not worth caching.
|
||||
// Tiles without covered texels cost nothing to composite: not worth caching
|
||||
if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::<Option<Vec<Band>>>() {
|
||||
records.push(((tx, ty), bands));
|
||||
}
|
||||
@@ -2676,6 +2726,8 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
|
||||
/// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh
|
||||
/// Returns None without an enabled mask
|
||||
pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option<Vec<f32>> {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?;
|
||||
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
@@ -2684,7 +2736,7 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option<Vec<f32>> {
|
||||
// A hidden layer's mask is left out of the stack's preparation
|
||||
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
|
||||
|
||||
let fields = neighbourhood_fields(inputs, &channels, &coordinates);
|
||||
let fields = evaluation_fields(inputs, &channels, &coordinates);
|
||||
let width_usize = width as usize;
|
||||
let tile_side = TILE as usize;
|
||||
let mut output = vec![0.0f32; width_usize * height as usize];
|
||||
@@ -2709,6 +2761,8 @@ pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option<Vec<f32>> {
|
||||
/// Keep preview tiles at 8 bits instead of retaining the export's full float atlas
|
||||
/// Returns None without an enabled mask
|
||||
pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?;
|
||||
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
@@ -2717,7 +2771,12 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
// A hidden layer's mask is left out of the stack's preparation
|
||||
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
|
||||
|
||||
let fields = neighbourhood_fields(inputs, &channels, &coordinates);
|
||||
let fields = evaluation_fields(inputs, &channels, &coordinates);
|
||||
let size = size.max(1);
|
||||
if size <= width.min(height) && (width != size || height != size) {
|
||||
return Some(downsample_mask(inputs, id, mask, &channels, &fields, size));
|
||||
}
|
||||
|
||||
let width_usize = width as usize;
|
||||
let tile_side = TILE as usize;
|
||||
let mut atlas = vec![0u8; width_usize * height as usize];
|
||||
@@ -2736,7 +2795,6 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
}
|
||||
});
|
||||
|
||||
let size = size.max(1);
|
||||
if width == size && height == size {
|
||||
return Some(atlas);
|
||||
}
|
||||
@@ -2756,6 +2814,49 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
Some(output)
|
||||
}
|
||||
|
||||
/// Sample a smaller mask image directly into disjoint output row groups
|
||||
fn downsample_mask(inputs: &EvaluationInputs, id: LayerId, mask: &Mask, channels: &[Channel], fields: &Fields, size: u32) -> Vec<u8> {
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
let source_at = |pixel, span| ((u64::from(pixel) * u64::from(span)) / u64::from(size)) as u32;
|
||||
let first_output = |source, span| (u64::from(source) * u64::from(size)).div_ceil(u64::from(span)).min(u64::from(size)) as u32;
|
||||
let mut output = vec![0; size as usize * size as usize];
|
||||
let mut destination = output.as_mut_slice();
|
||||
let mut bands = Vec::with_capacity(height.div_ceil(TILE) as usize);
|
||||
|
||||
// Partition rows by the tile that contains each row's source texels
|
||||
for tile_y in 0..height.div_ceil(TILE) {
|
||||
let first_row = first_output(tile_y * TILE, height);
|
||||
let past_row = first_output((tile_y + 1) * TILE, height);
|
||||
if past_row > first_row {
|
||||
let (rows, rest) = destination.split_at_mut((past_row - first_row) as usize * size as usize);
|
||||
bands.push((tile_y, first_row, past_row, rows));
|
||||
destination = rest;
|
||||
}
|
||||
}
|
||||
|
||||
bands.into_par_iter().for_each(|(tile_y, first_row, past_row, rows)| {
|
||||
for tile_x in 0..width.div_ceil(TILE) {
|
||||
let first_column = first_output(tile_x * TILE, width);
|
||||
let past_column = first_output((tile_x + 1) * TILE, width);
|
||||
if first_column == past_column {
|
||||
continue;
|
||||
}
|
||||
|
||||
let offsets = (first_row..past_row).flat_map(|row| {
|
||||
let y = source_at(row, height) % TILE;
|
||||
(first_column..past_column).map(move |column| (y * TILE + source_at(column, width) % TILE) as usize)
|
||||
});
|
||||
let texels = mask_tile(inputs, id, mask, channels, fields, (tile_x, tile_y), offsets);
|
||||
let pixels = rows.chunks_exact_mut(size as usize).flat_map(|row| &mut row[first_column as usize..past_column as usize]);
|
||||
for (pixel, (_, value)) in pixels.zip(texels) {
|
||||
*pixel = (value * 255.0 + 0.5) as u8;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
/// The layer mask as one-component values at the texture set's full resolution over `tiles`
|
||||
/// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a
|
||||
/// disabled mask; None when the layer has no mask.
|
||||
@@ -2767,11 +2868,13 @@ pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option
|
||||
|
||||
/// Evaluate requested tiles directly into the stroke's mask image.
|
||||
pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let mask = layer_mask(inputs.project, id)?;
|
||||
let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list();
|
||||
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
|
||||
|
||||
let fields = neighbourhood_fields(inputs, &channels, tiles);
|
||||
let fields = evaluation_fields(inputs, &channels, tiles);
|
||||
let computed: Vec<((u32, u32), Vec<u16>)> = tiles
|
||||
.par_iter()
|
||||
.map(|&tile| {
|
||||
@@ -2794,6 +2897,8 @@ pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], imag
|
||||
/// Mask values at texture-set coordinates, in request order; None without an enabled mask
|
||||
/// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels
|
||||
pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Vec<f32>> {
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?;
|
||||
let mut output = vec![0.0; texels.len()];
|
||||
|
||||
@@ -2818,7 +2923,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Ve
|
||||
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
|
||||
|
||||
// Filters and anchors can depend on texels outside the requested tiles
|
||||
let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height));
|
||||
let fields = evaluation_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height));
|
||||
let values: Vec<(usize, f32)> = requested
|
||||
.par_iter_mut()
|
||||
.flat_map_iter(|(&tile, requests)| {
|
||||
@@ -2841,7 +2946,7 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Ve
|
||||
|
||||
/// Mask values in offset order, including zeros for uncovered texels so request groups stay aligned
|
||||
fn mask_tile<'a>(
|
||||
inputs: &'a Inputs<'a>,
|
||||
inputs: &'a EvaluationInputs<'a>,
|
||||
id: LayerId,
|
||||
mask: &'a Mask,
|
||||
channels: &[Channel],
|
||||
@@ -2902,6 +3007,8 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u
|
||||
}
|
||||
};
|
||||
let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp };
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let cut_inp = EvaluationInputs::new(&cut_inp, &projectors);
|
||||
let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height);
|
||||
// A field covers the bounding box of the tiles it is built for, which for a scattered sample
|
||||
@@ -2981,7 +3088,9 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti
|
||||
l.visible = true;
|
||||
}
|
||||
let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs };
|
||||
let fields = neighbourhood_fields(&visible_inputs, &channels, tiles);
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors);
|
||||
let fields = evaluation_fields(&visible_inputs, &channels, tiles);
|
||||
|
||||
let out: Vec<Vec<FlatTile>> = tiles
|
||||
.par_iter()
|
||||
@@ -3155,6 +3264,7 @@ mod tests {
|
||||
// Not repeating, it crops to its tile, so it has to know where each texel lands
|
||||
let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") };
|
||||
fill.sampling.wrap = texturecraft_core::UvWrap::None;
|
||||
|
||||
assert!(coords_lookups(&f) > 0);
|
||||
}
|
||||
|
||||
@@ -3173,6 +3283,7 @@ mod tests {
|
||||
// Not repeating, it crops to its tile, so each texel works its coverage out
|
||||
let Ok(LayerKind::Fill(fill)) = f.project.layer_mut(id).map(|layer| &mut layer.kind) else { panic!("fill layer") };
|
||||
fill.sampling.wrap = texturecraft_core::UvWrap::None;
|
||||
|
||||
assert!(cover_calls(&f) > 0);
|
||||
}
|
||||
|
||||
@@ -3229,17 +3340,20 @@ mod tests {
|
||||
|
||||
cache.ahead.clear();
|
||||
composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache));
|
||||
|
||||
assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers");
|
||||
|
||||
cache.ahead = all_tiles(resolution, resolution).into_iter().skip(1).collect();
|
||||
composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache));
|
||||
let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields);
|
||||
cache.clear();
|
||||
|
||||
assert!(weak_fields.upgrade().is_none(), "invalidating the cache releases intermediate anchor stages too");
|
||||
|
||||
composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache));
|
||||
let weak_fields = Arc::downgrade(&cache.held.as_ref().unwrap().fields);
|
||||
drop(cache);
|
||||
|
||||
assert!(weak_fields.upgrade().is_none(), "dropping the cache releases a cancelled run's fields");
|
||||
}
|
||||
}
|
||||
@@ -3334,6 +3448,7 @@ mod tests {
|
||||
f.project.layer_mut(id).unwrap().mask = Some(mask);
|
||||
let out = run(&f, None);
|
||||
let vals: Vec<f32> = (0..64).map(|x| out.value(Channel::BaseColor, x, 20)[0]).collect();
|
||||
|
||||
assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}");
|
||||
}
|
||||
|
||||
@@ -3390,13 +3505,17 @@ mod tests {
|
||||
// Cross tile boundaries and include duplicates, a UV hole and invalid coordinates
|
||||
let texels = [(0, 0), (0, 40), (63, 63), (64, 64), (127, 127), (0, 40), (90, 30), (128, 0), (0, 128), (u32::MAX, u32::MAX)];
|
||||
let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap();
|
||||
|
||||
assert!(values.iter().any(|value| *value > 0.99) && values.iter().take(6).any(|value| *value < 0.01));
|
||||
assert_eq!(&values[6..], &[0.0; 4]);
|
||||
assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &[]), Some(Vec::new()));
|
||||
assert!(assert_sparse_mask_matches_image(&fixture, maskless, &texels).is_none());
|
||||
|
||||
let missing = fixture.project.alloc_id();
|
||||
assert!(assert_sparse_mask_matches_image(&fixture, missing, &texels).is_none());
|
||||
|
||||
fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().enabled = false;
|
||||
|
||||
assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none());
|
||||
}
|
||||
|
||||
@@ -3440,6 +3559,7 @@ mod tests {
|
||||
assert_eq!(atlas.len(), 128 * 64);
|
||||
assert!(preview.contains(&0));
|
||||
assert!(preview.contains(&255));
|
||||
|
||||
for ((&preview_value, &sparse_value), &(x, y)) in preview.iter().zip(&sparse).zip(&sampled_texels) {
|
||||
assert!((f32::from(preview_value) / 255.0 - sparse_value).abs() <= 0.5 / 255.0 + 1e-6);
|
||||
assert!((atlas[(y * 128 + x) as usize] - sparse_value).abs() <= 1e-6);
|
||||
@@ -3497,6 +3617,7 @@ mod tests {
|
||||
filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter)));
|
||||
fixture.project.layer_mut(upper).unwrap().mask = Some(filtered);
|
||||
let values = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap();
|
||||
|
||||
assert!(values.iter().zip(&original).any(|(value, original)| (value - original).abs() > 0.1), "the filter changes the anchor values");
|
||||
}
|
||||
}
|
||||
@@ -3650,6 +3771,7 @@ mod tests {
|
||||
assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}");
|
||||
assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}");
|
||||
assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}");
|
||||
|
||||
for texel in far {
|
||||
assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}");
|
||||
}
|
||||
@@ -3852,10 +3974,12 @@ soft {soft:?}"
|
||||
let out = run(&f, None);
|
||||
assert!(close(out.value(Channel::BaseColor, 5, 5), [0.0, 1.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 5, 5));
|
||||
assert!(close(out.value(Channel::Roughness, 5, 5), [0.2; 3]), "a hue shift leaves scalars alone");
|
||||
|
||||
content_fx(&mut f, id, EffectKind::Filter(Filter::Invert));
|
||||
let out = run(&f, None);
|
||||
assert!(close(out.value(Channel::BaseColor, 5, 5), [1.0, 0.0, 1.0]));
|
||||
assert!(close(out.value(Channel::Roughness, 5, 5), [0.8; 3]));
|
||||
|
||||
// Hidden effects are skipped and opacity fades an effect
|
||||
let fx = &mut f.project.layer_mut(id).unwrap().content_effects;
|
||||
fx[0].visible = false;
|
||||
@@ -3907,8 +4031,10 @@ soft {soft:?}"
|
||||
let out = run(&f, None);
|
||||
assert!(close(out.value(Channel::BaseColor, 30, 30), [0.5; 3]), "{:?}", out.value(Channel::BaseColor, 30, 30));
|
||||
assert!(close(out.value(Channel::Roughness, 30, 30), [0.5; 3]));
|
||||
|
||||
f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != hp);
|
||||
content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 }));
|
||||
|
||||
assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.0; 3]));
|
||||
|
||||
// A checker's borders light up while cell interiors stay black
|
||||
@@ -3945,7 +4071,9 @@ soft {soft:?}"
|
||||
let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 };
|
||||
assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8]));
|
||||
assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1]));
|
||||
|
||||
let half = rc.point(ChannelKind::Color, [0.8, 0.1 + 0.15 * 3f32.sqrt(), 0.1]).unwrap();
|
||||
|
||||
assert!((half[2] - 0.45).abs() < 0.02, "halfway through the softness: {half:?}");
|
||||
assert_eq!(rc.point(ChannelKind::Scalar, [0.8; 3]), Some([0.8; 3]));
|
||||
}
|
||||
@@ -3990,6 +4118,7 @@ soft {soft:?}"
|
||||
let mut f = fixture();
|
||||
let id = fill_layer(&mut f.project, [0.1; 3], 0.2);
|
||||
content_fx(&mut f, id, EffectKind::Filter(Filter::Glow { radius: 32.0, amount: 1.0 }));
|
||||
|
||||
assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.4; 3]));
|
||||
}
|
||||
|
||||
@@ -4063,7 +4192,9 @@ soft {soft:?}"
|
||||
let images = ImageStore::default();
|
||||
let inp = inputs(&f, &images, None);
|
||||
let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap();
|
||||
|
||||
assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness));
|
||||
|
||||
let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap();
|
||||
let o = 3 * TILE as usize + 3;
|
||||
assert!((from_u16(data[o * 2]) - 0.55).abs() < 1e-3 && (from_u16(data[o * 2 + 1]) - 1.0).abs() < 1e-3);
|
||||
@@ -4508,6 +4639,7 @@ soft {soft:?}"
|
||||
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
|
||||
out.value(Channel::BaseColor, 32, 32)
|
||||
};
|
||||
|
||||
assert!(close(texel(&f, [false, false]), [1.0, 0.0, 0.0]), "the left half shows red");
|
||||
assert!(close(texel(&f, [true, false]), [0.0, 0.0, 1.0]), "Flip U shows the right half there");
|
||||
assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half");
|
||||
@@ -4533,12 +4665,13 @@ soft {soft:?}"
|
||||
fn a_shrunk_cropped_frames_coverage_averages_its_image_alpha_as_its_colour_does() {
|
||||
let f = decal_fixture(|fill| fill.sampling.filtering = Filtering::BilinearHq);
|
||||
|
||||
// Red columns a texel wide, opaque and see-through in turn, far finer than the frame's texels; not a power of two, so a full-size read lands anywhere between two columns
|
||||
// Odd-width alternating alpha stripes exercise minification between source texels
|
||||
const SIZE: u32 = 1000;
|
||||
let stripes = (0..SIZE * SIZE).map(|i| [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { 0.0 }]).collect();
|
||||
let shown = decal_texels(&composite_with_decal(&f, crate::store::ImageRes::new(SIZE, SIZE, stripes, false)));
|
||||
|
||||
assert!(!shown.is_empty(), "the frame shows");
|
||||
|
||||
let half = [0.75, 0.25, 0.25];
|
||||
assert!(
|
||||
shown.iter().all(|v| v.iter().zip(half).all(|(got, want)| (got - want).abs() < 0.05)),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use super::Inputs;
|
||||
use crate::ProjectorDepthCache;
|
||||
|
||||
pub(super) struct EvaluationInputs<'a> {
|
||||
inputs: &'a Inputs<'a>,
|
||||
pub(super) projectors: &'a ProjectorDepthCache,
|
||||
}
|
||||
|
||||
impl<'a> EvaluationInputs<'a> {
|
||||
pub(super) fn new(inputs: &'a Inputs<'a>, projectors: &'a ProjectorDepthCache) -> Self {
|
||||
Self { inputs, projectors }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Deref for EvaluationInputs<'a> {
|
||||
type Target = Inputs<'a>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.inputs
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Isolated folder evaluation with the original stack available for anchor inputs.
|
||||
|
||||
use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed};
|
||||
use super::{
|
||||
Channel, ChannelKind, Composite, EvaluationInputs, Inputs, LayerId, ProjectorDepthCache, Texel, all_tiles, evaluation_fields, plan, tile_texels, to_u16,
|
||||
to_u16_signed,
|
||||
};
|
||||
|
||||
/// Composite one layer over channel defaults, keeping anchors from the stack below it.
|
||||
pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option<Composite> {
|
||||
@@ -8,7 +11,9 @@ pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel)
|
||||
let channels = set.channel_list();
|
||||
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
|
||||
let tiles = all_tiles(width, height);
|
||||
let fields = neighbourhood_fields(inputs, &channels, &tiles);
|
||||
let projectors = ProjectorDepthCache::default();
|
||||
let inputs = &EvaluationInputs::new(inputs, &projectors);
|
||||
let fields = evaluation_fields(inputs, &channels, &tiles);
|
||||
let mut composite = Composite::with_size(&[channel], width, height);
|
||||
let output = composite.channels.get_mut(&channel)?;
|
||||
|
||||
|
||||
@@ -104,13 +104,16 @@ mod tests {
|
||||
let mut mirror = symmetry(SymmetryKind::Mirror, 0);
|
||||
mirror.position = [0.5, 0.0, 0.0];
|
||||
let left: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(-1.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
|
||||
|
||||
assert_eq!(left.len(), 2);
|
||||
|
||||
// The plane passes at x = 1 (half a radius of 2): a point at -1 sees the original at 3 first
|
||||
assert!(left[0].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(3.0, 0.2, 0.0), 1e-5));
|
||||
assert!(left[1].point(Vec3::new(-1.0, 0.2, 0.0)).abs_diff_eq(Vec3::new(-1.0, 0.2, 0.0), 1e-5));
|
||||
assert!(left[0].normal(Vec3::X).abs_diff_eq(-Vec3::X, 1e-5));
|
||||
|
||||
let right: Vec<FillCopy> = FillCopies::new(&mirror, Vec3::new(2.0, 0.0, 0.0), Vec3::ZERO, 2.0).collect();
|
||||
|
||||
assert!(right[0].point(Vec3::new(2.0, 0.3, 0.0)).abs_diff_eq(Vec3::new(2.0, 0.3, 0.0), 1e-5));
|
||||
}
|
||||
|
||||
@@ -120,6 +123,7 @@ mod tests {
|
||||
radial.count = 4;
|
||||
radial.flip = [true, false];
|
||||
let copies: Vec<FillCopy> = FillCopies::new(&radial, Vec3::X, Vec3::ZERO, 1.0).collect();
|
||||
|
||||
assert_eq!(copies.len(), 4);
|
||||
assert_eq!(copies[0].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.25, 0.5));
|
||||
assert_eq!(copies[1].uv(Vec2::new(0.25, 0.5)), Vec2::new(0.75, 0.5));
|
||||
@@ -129,6 +133,7 @@ mod tests {
|
||||
|
||||
// A texel on +Y lies in copy 1's wedge, so copy 1 comes first there
|
||||
let on_y: Vec<FillCopy> = FillCopies::new(&radial, Vec3::Y, Vec3::ZERO, 1.0).collect();
|
||||
|
||||
assert!(on_y[0].point(Vec3::Y).abs_diff_eq(Vec3::X, 1e-5));
|
||||
}
|
||||
|
||||
|
||||
@@ -240,6 +240,7 @@ mod tests {
|
||||
let flat = folded(&proj).unwrap();
|
||||
let Projector { rotation, scale, crop, .. } = projector_of(&flat);
|
||||
assert_eq!((rotation, scale, crop), ([0.0; 3], [1.0; 3], ShapeCrop::Cropped), "the turn and scale moved into the frame, the crop stayed");
|
||||
|
||||
close(&samples(&proj), &samples(&flat));
|
||||
}
|
||||
let unturned = planar(Projector::default());
|
||||
@@ -263,6 +264,7 @@ mod tests {
|
||||
match folded(&proj) {
|
||||
Some(flat) => {
|
||||
assert_eq!(cover(&proj), cover(&flat), "{scale:?}: culling changed");
|
||||
|
||||
close(&samples(&proj), &samples(&flat));
|
||||
}
|
||||
None => assert!(!culling_folds(&projector), "{scale:?}: only a scale culling cannot keep stays unfolded"),
|
||||
@@ -286,11 +288,15 @@ mod tests {
|
||||
|
||||
let width = folded(&proj).unwrap().frame().unwrap().size[0];
|
||||
let bigger = placed(&proj, &FramePlacement { scale: [place.scale[0] * 2.0, place.scale[1], place.scale[2]], ..place }, BOUNDS).unwrap();
|
||||
|
||||
assert!((bigger.frame().unwrap().size[0] - width * 2.0).abs() < 1e-4, "Scale X doubles the width");
|
||||
|
||||
let moved = placed(&proj, &FramePlacement { offset: [0.0; 3], ..place }, BOUNDS).unwrap();
|
||||
|
||||
assert!((Vec3::from(moved.frame().unwrap().center) - Vec3::new(1.0, -0.5, 0.5)).length() < 1e-4, "offset 0 = the mesh's centre");
|
||||
}
|
||||
let place = placement(&planar(Projector::default()), BOUNDS).unwrap();
|
||||
|
||||
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { scale: [0.0, 1.0, 1.0], ..place }, BOUNDS), None, "no zero size");
|
||||
assert_eq!(placed(&planar(Projector::default()), &FramePlacement { rotation: [f32::NAN; 3], ..place }, BOUNDS), None);
|
||||
assert_eq!(placement(&Projection::default(), BOUNDS), None);
|
||||
@@ -300,8 +306,11 @@ mod tests {
|
||||
fn a_frames_upright_turn_is_its_turn_round_its_normal() {
|
||||
let mut flat = Decal { normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], rotation: 30.0, offset: [0.0; 2], ..frame() };
|
||||
assert!((upright_turn(&flat).unwrap() - 30.0).abs() < 1e-3);
|
||||
|
||||
flat.rotation = -100.0;
|
||||
|
||||
assert!((upright_turn(&flat).unwrap() + 100.0).abs() < 1e-3);
|
||||
|
||||
let top = Decal { normal: [0.0, 1.0, 0.0], up: [0.0, 0.0, -1.0], rotation: 0.0, ..frame() };
|
||||
assert!(upright_turn(&top).unwrap().abs() < 1e-3, "seen from above the far side is up");
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ pub mod pattern;
|
||||
mod pattern_context;
|
||||
pub mod projector_cover;
|
||||
pub mod projector_depth;
|
||||
mod projector_depth_cache;
|
||||
pub mod projector_view;
|
||||
pub mod solo;
|
||||
pub mod store;
|
||||
@@ -42,9 +43,11 @@ pub use below::{BelowCache, StackKey};
|
||||
pub use display::{DisplayKind, kinds_for, tile_bytes};
|
||||
pub use eval::{
|
||||
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached,
|
||||
covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
|
||||
composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles,
|
||||
stack_reads_neighbours,
|
||||
};
|
||||
pub use pattern_context::PatternContext;
|
||||
pub use projector_depth_cache::ProjectorDepthCache;
|
||||
pub use solo::solo_project;
|
||||
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
|
||||
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
|
||||
@@ -678,6 +678,25 @@ pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option<
|
||||
local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos;
|
||||
}
|
||||
|
||||
frame_position(frame, local)
|
||||
}
|
||||
|
||||
/// Read the position and facing of one sample when a placed frame culls by angle
|
||||
pub(crate) fn frame_sample(frame: &Decal, projector: &Projector, position: Vec3, surface_normal: Vec3) -> Option<(Vec3, f32)> {
|
||||
let (origin, right, up, normal) = decal_axes(frame)?;
|
||||
let from_origin = position - origin;
|
||||
let local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal));
|
||||
|
||||
if !projector.turns() {
|
||||
return Some((frame_position(frame, local)?, surface_normal.dot(normal)));
|
||||
}
|
||||
|
||||
let normal = Vec3::new(surface_normal.dot(right), surface_normal.dot(up), surface_normal.dot(normal));
|
||||
let sample = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: normal });
|
||||
Some((frame_position(frame, sample.pos)?, sample.nrm.z))
|
||||
}
|
||||
|
||||
fn frame_position(frame: &Decal, local: Vec3) -> Option<Vec3> {
|
||||
let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z);
|
||||
local.is_finite().then_some(local)
|
||||
}
|
||||
@@ -750,6 +769,7 @@ mod tests {
|
||||
|
||||
// Coarse reads are exact at cell centers and blend between them
|
||||
assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5);
|
||||
|
||||
let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5;
|
||||
assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse));
|
||||
assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows");
|
||||
@@ -823,6 +843,7 @@ mod tests {
|
||||
}
|
||||
let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO);
|
||||
assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}");
|
||||
|
||||
let placed = Projection::Planar {
|
||||
scale: 1.0,
|
||||
axis: 2,
|
||||
@@ -832,6 +853,7 @@ mod tests {
|
||||
placed: Some(frame),
|
||||
};
|
||||
assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way");
|
||||
|
||||
for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] {
|
||||
let before = uv * Vec2::from(tiling) + Vec2::from(offset);
|
||||
assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before");
|
||||
@@ -909,6 +931,7 @@ mod tests {
|
||||
}
|
||||
|
||||
assert!(largest_difference < 1.0 / 65535.0, "worst difference {largest_difference}");
|
||||
|
||||
let near_axis = triplanar_weights(Vec3::new(0.2, 1.0, 0.1).normalize(), 8.0, 1.0);
|
||||
assert_eq!((near_axis.x, near_axis.z), (0.0, 0.0), "{near_axis}");
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::frame_placement::warp_reach;
|
||||
use crate::organic::smoothstep;
|
||||
use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local};
|
||||
use crate::pattern::{Coords, depth_fade, frame_crop, frame_local, frame_sample, placed_uv, projector_local};
|
||||
use crate::warp::warp_uv;
|
||||
|
||||
/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out
|
||||
@@ -94,8 +94,13 @@ pub fn backface_cover(backface: &Backface, facing: f32) -> f32 {
|
||||
|
||||
/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate)
|
||||
pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
|
||||
let local = frame_local(frame, projector, p)?;
|
||||
let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 };
|
||||
let (local, mut cover) = if projector.backface.on {
|
||||
let (local, facing) = frame_sample(frame, projector, p, nrm)?;
|
||||
(local, backface_cover(&projector.backface, facing))
|
||||
} else {
|
||||
(frame_local(frame, projector, p)?, 1.0)
|
||||
};
|
||||
|
||||
if projector.crop == ShapeCrop::Cropped {
|
||||
cover *= frame_crop(frame, local);
|
||||
}
|
||||
@@ -273,8 +278,10 @@ mod tests {
|
||||
let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0);
|
||||
let before = symmetric_before(&frame, p, nrm, center);
|
||||
mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none());
|
||||
|
||||
assert_eq!(before, now, "{p} {nrm}");
|
||||
}
|
||||
|
||||
assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::Projection;
|
||||
use texturecraft_geom::Mesh;
|
||||
@@ -21,63 +20,41 @@ pub struct ProjectorDepth {
|
||||
front: Vec<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// Built maps by their view and the mesh they come from
|
||||
type CacheEntry = (ProjectorView, u64, Arc<ProjectorDepth>);
|
||||
|
||||
/// The smallest grid cell across and up, so a flat view still divides
|
||||
const MIN_CELL_SIZE: f32 = 1e-6;
|
||||
|
||||
/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps
|
||||
const EDGE_TOLERANCE: f32 = 1e-6;
|
||||
|
||||
static CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
|
||||
|
||||
impl ProjectorDepth {
|
||||
/// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth
|
||||
pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option<Arc<ProjectorDepth>> {
|
||||
let view = ProjectorView::of(proj, bounds)?;
|
||||
let mesh_key = fingerprint(mesh);
|
||||
|
||||
// Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) {
|
||||
let (cached_view, cached_mesh, depth) = cache.remove(at);
|
||||
cache.insert(0, (cached_view, cached_mesh, depth.clone()));
|
||||
return Some(depth);
|
||||
}
|
||||
|
||||
let depth = Arc::new(ProjectorDepth::build(view, mesh)?);
|
||||
cache.insert(0, (view, mesh_key, depth.clone()));
|
||||
cache.truncate(CACHE_MAPS);
|
||||
Some(depth)
|
||||
}
|
||||
|
||||
/// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint
|
||||
pub fn forget_all() {
|
||||
CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
|
||||
/// Build the depth map of a borrowed mesh, if the projection uses depth culling.
|
||||
pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
|
||||
let view = ProjectorView::of(projection, bounds)?;
|
||||
Self::build(view, mesh).map(Arc::new)
|
||||
}
|
||||
|
||||
/// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view)
|
||||
pub fn build(view: ProjectorView, mesh: &Mesh) -> Option<ProjectorDepth> {
|
||||
let local: Vec<Option<Vec3>> = mesh.positions.iter().map(|position| view.local(*position)).collect();
|
||||
let (lo, hi) = local
|
||||
let projected: Vec<Option<Vec3>> = mesh.positions.iter().map(|position| view.local(*position)).collect();
|
||||
let (min, max) = projected
|
||||
.iter()
|
||||
.flatten()
|
||||
.fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate())));
|
||||
if lo.x > hi.x || lo.y > hi.y {
|
||||
if min.x > max.x || min.y > max.y {
|
||||
return None;
|
||||
}
|
||||
|
||||
let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE));
|
||||
let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] };
|
||||
let cell = ((max - min) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE));
|
||||
let mut depth = ProjectorDepth { view, origin: min, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] };
|
||||
let mut budget = CELL_BUDGET;
|
||||
for tri in mesh.indices.as_chunks::<3>().0 {
|
||||
let corner = |i: u32| local.get(i as usize).copied().flatten();
|
||||
let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue };
|
||||
for &[first, second, third] in mesh.indices.as_chunks::<3>().0 {
|
||||
let corner = |i: u32| projected.get(i as usize).copied().flatten();
|
||||
let (Some(a), Some(b), Some(c)) = (corner(first), corner(second), corner(third)) else { continue };
|
||||
if !depth.raster([a, b, c], &mut budget) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Some(depth)
|
||||
}
|
||||
|
||||
@@ -85,15 +62,16 @@ impl ProjectorDepth {
|
||||
fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool {
|
||||
let [a, b, c] = triangle;
|
||||
let (d1, d2) = (b - a, c - a);
|
||||
let det = d1.x * d2.y - d1.y * d2.x;
|
||||
if !det.is_finite() || det.abs() < MIN_SCREEN_AREA {
|
||||
// Seen edge on, it covers nothing
|
||||
let determinant = d1.x * d2.y - d1.y * d2.x;
|
||||
if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA {
|
||||
// An edge-on triangle covers no cells
|
||||
return true;
|
||||
}
|
||||
|
||||
let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE));
|
||||
let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / determinant, (d1.x * d2.z - d2.x * d1.z) / determinant)
|
||||
.clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE));
|
||||
|
||||
// Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5)
|
||||
// Evaluate coverage at cell centres
|
||||
let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell);
|
||||
let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc));
|
||||
let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize;
|
||||
@@ -122,17 +100,18 @@ impl ProjectorDepth {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front
|
||||
pub fn cover(&self, p: Vec3, hardness: f32) -> f32 {
|
||||
// A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN
|
||||
pub fn cover(&self, position: Vec3, hardness: f32) -> f32 {
|
||||
// Keep the layer visible when a hand-edited hardness is invalid
|
||||
if !hardness.is_finite() {
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
let Some(view_point) = self.view.local(p) else { return 1.0 };
|
||||
let Some(view_point) = self.view.local(position) else { return 1.0 };
|
||||
let at = (view_point.truncate() - self.origin) / self.cell;
|
||||
if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) {
|
||||
return 1.0;
|
||||
@@ -141,13 +120,13 @@ impl ProjectorDepth {
|
||||
let (x, y) = (at.x as usize, at.y as usize);
|
||||
let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 };
|
||||
|
||||
// The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself
|
||||
// Extend the cell's plane to avoid culling a surface against itself
|
||||
let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell;
|
||||
let slope = Vec2::new(across, up);
|
||||
let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z;
|
||||
let unit = self.view.unit();
|
||||
|
||||
// Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope
|
||||
// Add slope bias for curvature across adjacent triangles
|
||||
let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit);
|
||||
let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit;
|
||||
if width <= f32::EPSILON {
|
||||
@@ -163,19 +142,6 @@ fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 {
|
||||
(b - a).perp_dot(q - a)
|
||||
}
|
||||
|
||||
/// Which mesh a map was built for: its sizes and a spread of its vertices and indices
|
||||
fn fingerprint(mesh: &Mesh) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(mesh.positions.len(), mesh.indices.len()).hash(&mut hasher);
|
||||
for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) {
|
||||
position.to_array().map(f32::to_bits).hash(&mut hasher);
|
||||
}
|
||||
for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) {
|
||||
index.hash(&mut hasher);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Cells across and up the grid
|
||||
const SIZE: usize = 512;
|
||||
|
||||
@@ -197,12 +163,6 @@ const MAX_SLOPE_BIAS: f32 = 0.05;
|
||||
/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii
|
||||
const FADE: f32 = 0.1;
|
||||
|
||||
/// Maps kept built (each is about 3 MB)
|
||||
const CACHE_MAPS: usize = 8;
|
||||
|
||||
/// Vertices and indices the mesh fingerprint reads
|
||||
const FINGERPRINT_SAMPLES: usize = 64;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -254,22 +214,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() {
|
||||
// Unused vertices spread the fingerprint's samples so the front square's right edge is not among them
|
||||
fn interleaved_meshes_keep_their_own_projector_depth() {
|
||||
let mut mesh = two_squares(0.5, -0.5);
|
||||
mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO));
|
||||
// Add enough unused vertices for the old sample to skip the changed edge
|
||||
mesh.positions.resize(200, Vec3::ZERO);
|
||||
let mut edited = mesh.clone();
|
||||
for right in [1, 2] {
|
||||
edited.positions[right].x = 0.5;
|
||||
}
|
||||
assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint");
|
||||
assert_eq!(mesh.bounds(), edited.bounds());
|
||||
|
||||
let proj = planar_z(true, 1.0);
|
||||
let behind_the_cut = Vec3::new(0.75, 0.3, -0.5);
|
||||
let bounds = mesh.bounds();
|
||||
assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0);
|
||||
|
||||
ProjectorDepth::forget_all();
|
||||
|
||||
let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap();
|
||||
assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use texturecraft_core::Projection;
|
||||
use texturecraft_geom::{Mesh, glam::Vec3};
|
||||
|
||||
use crate::{projector_depth::ProjectorDepth, projector_view::ProjectorView};
|
||||
|
||||
type ViewDepth = (ProjectorView, Option<Arc<ProjectorDepth>>);
|
||||
|
||||
// Each map holds about 3 MiB
|
||||
const MAX_CACHED_VIEWS: usize = 8;
|
||||
|
||||
/// Reuse projector depth maps for one mesh across tile batches.
|
||||
#[derive(Default)]
|
||||
pub struct ProjectorDepthCache {
|
||||
mesh: Weak<Mesh>,
|
||||
maps: Mutex<Vec<ViewDepth>>,
|
||||
}
|
||||
|
||||
impl ProjectorDepthCache {
|
||||
pub(crate) fn bind(&mut self, mesh: &Arc<Mesh>) -> bool {
|
||||
if !std::ptr::eq(self.mesh.as_ptr(), mesh.as_ref()) {
|
||||
self.maps.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()).clear();
|
||||
self.mesh = Arc::downgrade(mesh);
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, mesh: &Mesh, bounds: (Vec3, Vec3), projection: &Projection) -> Option<Arc<ProjectorDepth>> {
|
||||
let view = ProjectorView::of(projection, bounds)?;
|
||||
|
||||
// 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());
|
||||
if let Some(index) = maps.iter().position(|(cached_view, _)| *cached_view == view) {
|
||||
let entry = maps.remove(index);
|
||||
let depth = entry.1.clone();
|
||||
maps.insert(0, entry);
|
||||
return depth;
|
||||
}
|
||||
|
||||
let depth = ProjectorDepth::build(view, mesh).map(Arc::new);
|
||||
maps.insert(0, (view, depth.clone()));
|
||||
maps.truncate(MAX_CACHED_VIEWS);
|
||||
|
||||
depth
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use texturecraft_core::{Projector, UvTransform};
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
#[test]
|
||||
fn eviction_and_mesh_replacement_release_maps_after_the_last_reader() {
|
||||
let mut cache = ProjectorDepthCache::default();
|
||||
let mut mesh = Arc::new(primitives::plane(2.0, 2));
|
||||
let mesh_reference = Arc::downgrade(&mesh);
|
||||
let bounds = mesh.bounds();
|
||||
let mut maps = Vec::new();
|
||||
let mut first_reader = None;
|
||||
|
||||
cache.bind(&mesh);
|
||||
for angle_degrees in 0..MAX_CACHED_VIEWS + 4 {
|
||||
let mut projector = Projector::depth_culled();
|
||||
projector.rotation[2] = angle_degrees as f32;
|
||||
let projection = Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None };
|
||||
let map = cache.get(&mesh, bounds, &projection).unwrap();
|
||||
let reused = cache.get(&mesh, bounds, &projection).unwrap();
|
||||
assert!(Arc::ptr_eq(&map, &reused));
|
||||
maps.push(Arc::downgrade(&map));
|
||||
if angle_degrees == 0 {
|
||||
first_reader = Some(map);
|
||||
}
|
||||
}
|
||||
|
||||
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS + 1);
|
||||
drop(first_reader);
|
||||
assert_eq!(maps.iter().filter(|map| map.upgrade().is_some()).count(), MAX_CACHED_VIEWS);
|
||||
|
||||
// Mutating a uniquely held Arc disassociates its weak references
|
||||
Arc::make_mut(&mut mesh).positions[0].y += 1.0;
|
||||
assert!(mesh_reference.upgrade().is_none());
|
||||
cache.bind(&mesh);
|
||||
assert!(maps.iter().all(|map| map.upgrade().is_none()));
|
||||
|
||||
let projection =
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None };
|
||||
let last_map = Arc::downgrade(&cache.get(&mesh, mesh.bounds(), &projection).unwrap());
|
||||
|
||||
drop(cache);
|
||||
assert!(last_map.upgrade().is_none());
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,7 @@ mod tests {
|
||||
p.layer_mut(rust).unwrap().visible = false;
|
||||
let before = p.clone();
|
||||
let view = solo_project(&p, rust, false).unwrap();
|
||||
|
||||
assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off");
|
||||
assert!(!view.layers[&below].visible, "the others are hidden");
|
||||
assert!(view.layers[&other_set].visible, "another texture set keeps its layers");
|
||||
@@ -117,9 +118,12 @@ mod tests {
|
||||
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
|
||||
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
|
||||
let view = solo_project(&p, inner, false).unwrap();
|
||||
|
||||
assert!(view.layers[&folder].visible && view.layers[&inner].visible);
|
||||
assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible);
|
||||
|
||||
let whole = solo_project(&p, folder, false).unwrap();
|
||||
|
||||
assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents");
|
||||
assert!(!whole.layers[&outside].visible);
|
||||
}
|
||||
@@ -134,8 +138,11 @@ mod tests {
|
||||
masked(&mut p, id);
|
||||
}
|
||||
let kept = solo_project(&p, inner, false).unwrap();
|
||||
|
||||
assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays");
|
||||
|
||||
let view = solo_project(&p, inner, true).unwrap();
|
||||
|
||||
assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled);
|
||||
assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched");
|
||||
assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask");
|
||||
@@ -148,6 +155,7 @@ mod tests {
|
||||
masked(&mut p, source);
|
||||
let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false);
|
||||
let view = solo_project(&p, instance, true).unwrap();
|
||||
|
||||
assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled);
|
||||
assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask");
|
||||
}
|
||||
@@ -159,6 +167,7 @@ mod tests {
|
||||
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
|
||||
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
|
||||
let view = solo_project(&p, instance, false).unwrap();
|
||||
|
||||
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,7 @@ impl ImageRes {
|
||||
if !u.is_finite() || !v.is_finite() {
|
||||
return [0.0; 4];
|
||||
}
|
||||
|
||||
bilinear(&self.rgba, self.width, self.height, u, v, (true, true))
|
||||
}
|
||||
|
||||
|
||||
@@ -6,12 +6,9 @@ use texturecraft_core::{FULL_TURN_DEGREES, Projection};
|
||||
|
||||
use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch};
|
||||
|
||||
/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MeshSize {
|
||||
pub radius: f32,
|
||||
pub uv_density: f32,
|
||||
}
|
||||
mod mesh_size;
|
||||
|
||||
pub use mesh_size::MeshSize;
|
||||
|
||||
/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round)
|
||||
fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV)
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MeshSize {
|
||||
pub radius: f32,
|
||||
pub uv_density: f32,
|
||||
}
|
||||
@@ -214,12 +214,14 @@ fn mask_with_height_follows_the_layer_height() {
|
||||
let row = TILE * 2;
|
||||
let (left, right) = (16, RES - 16);
|
||||
let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0];
|
||||
|
||||
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
|
||||
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
|
||||
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
|
||||
|
||||
// Without a mask there is nothing to combine
|
||||
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
|
||||
|
||||
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
@@ -544,11 +546,13 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
|
||||
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
|
||||
let blurred = reference(&f, 0);
|
||||
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
|
||||
|
||||
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
|
||||
assert!(one_by_one == blurred);
|
||||
}
|
||||
|
||||
@@ -584,7 +588,9 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
|
||||
assert!(one_by_one == want, "per-tile composites differ from one pass");
|
||||
|
||||
for hot in [top, streaks] {
|
||||
assert!(!check_cached(&f, 0, hot).is_empty());
|
||||
}
|
||||
@@ -665,6 +671,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
cache.ahead = Vec::new();
|
||||
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
|
||||
|
||||
assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it");
|
||||
assert!(!cache.holds_fields());
|
||||
|
||||
@@ -677,6 +684,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
|
||||
let mut inp = inputs(&fixture, 0, &images, &baked);
|
||||
inp.preview = Some(&preview);
|
||||
composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache));
|
||||
|
||||
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs");
|
||||
}
|
||||
|
||||
@@ -719,7 +727,9 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
|
||||
cache.set_hot(Some(hot));
|
||||
let mut out = Composite::new(&channels, SIZE);
|
||||
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache));
|
||||
|
||||
assert_eq!(cache.len(), bottom.len());
|
||||
|
||||
cache.budget = cache.bytes();
|
||||
|
||||
// Cache eviction during the run must rebuild missing lower-layer fields
|
||||
@@ -731,6 +741,7 @@ fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
|
||||
assert!(cache.holds_fields());
|
||||
}
|
||||
}
|
||||
|
||||
assert!(above.len() > bottom.len());
|
||||
assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path");
|
||||
}
|
||||
@@ -790,13 +801,17 @@ fn cached_stack_tracks_the_images_a_tile_generator_reads() {
|
||||
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
|
||||
let input = inputs(&fixture, 0, &images, &baked);
|
||||
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
|
||||
|
||||
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
|
||||
|
||||
let retained = cache.len() - 1;
|
||||
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
|
||||
|
||||
assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image");
|
||||
|
||||
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
composite_tiles(&input, &mut expected, &tiles);
|
||||
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
@@ -832,11 +847,14 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
let replacement = image_with_value(0.4);
|
||||
let replacement_weak = Arc::downgrade(&replacement);
|
||||
images.insert("used".into(), replacement);
|
||||
|
||||
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels");
|
||||
|
||||
previous_image = Some(replacement_weak);
|
||||
}
|
||||
"remove" => {
|
||||
images.remove("used");
|
||||
|
||||
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels");
|
||||
}
|
||||
"cold" => {}
|
||||
@@ -848,13 +866,17 @@ fn cached_stack_tracks_referenced_images_only() {
|
||||
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
|
||||
let input = inputs(&fixture, 0, &images, &baked);
|
||||
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
|
||||
|
||||
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
|
||||
|
||||
let retained = cache.len() - 1;
|
||||
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
|
||||
|
||||
assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}");
|
||||
|
||||
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
|
||||
composite_tiles(&input, &mut expected, &tiles);
|
||||
|
||||
assert!(output == expected, "{stage}");
|
||||
}
|
||||
}
|
||||
|
||||
+13
-21
@@ -10,31 +10,41 @@ mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
mod decal_flip;
|
||||
mod decal_symmetry;
|
||||
mod filtering;
|
||||
mod generator_global;
|
||||
mod micro_detail;
|
||||
mod output_resolution;
|
||||
mod resolution_mode;
|
||||
mod sampling;
|
||||
mod scale_mode;
|
||||
mod tile_blending;
|
||||
mod tile_generator;
|
||||
mod tile_input_distribution;
|
||||
mod tile_shape;
|
||||
mod tile_size_mode;
|
||||
mod tile_symmetry;
|
||||
mod uv_transform;
|
||||
mod uv_wrap;
|
||||
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
pub use decal_flip::DecalFlip;
|
||||
pub use decal_symmetry::DecalSymmetry;
|
||||
pub use filtering::Filtering;
|
||||
pub use generator_global::GeneratorGlobal;
|
||||
pub use micro_detail::MicroDetail;
|
||||
pub use output_resolution::OutputResolution;
|
||||
pub use resolution_mode::ResolutionMode;
|
||||
pub use sampling::Sampling;
|
||||
pub use scale_mode::ScaleMode;
|
||||
pub use tile_blending::TileBlending;
|
||||
pub use tile_generator::TileGenerator;
|
||||
pub use tile_input_distribution::TileInputDistribution;
|
||||
pub use tile_shape::TileShape;
|
||||
pub use tile_size_mode::TileSizeMode;
|
||||
pub use tile_symmetry::TileSymmetry;
|
||||
pub use uv_transform::UvTransform;
|
||||
pub use uv_wrap::UvWrap;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -103,6 +113,7 @@ impl HeightMask {
|
||||
if !self.enabled || !h.is_finite() {
|
||||
return m;
|
||||
}
|
||||
|
||||
(m + self.contrast * 4.0 * m * (1.0 - m) * (h + self.offset)).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
@@ -244,27 +255,6 @@ pub enum Projection {
|
||||
},
|
||||
}
|
||||
|
||||
/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UvTransform {
|
||||
pub tiling: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub offset: [f32; 2],
|
||||
}
|
||||
|
||||
impl Default for UvTransform {
|
||||
fn default() -> Self {
|
||||
UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
|
||||
}
|
||||
}
|
||||
|
||||
impl UvTransform {
|
||||
/// Whether it changes nothing, as projections saved before it existed did (not saved then)
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == UvTransform::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame a planar projection placed on the surface (a decal) projects from, in world space
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Decal {
|
||||
@@ -1789,6 +1779,7 @@ mod tests {
|
||||
];
|
||||
for saved in fills {
|
||||
let loaded: Fill = serde_json::from_str(saved).unwrap();
|
||||
|
||||
assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved");
|
||||
}
|
||||
|
||||
@@ -1798,6 +1789,7 @@ mod tests {
|
||||
];
|
||||
for saved in effects {
|
||||
let loaded: EffectKind = serde_json::from_str(saved).unwrap();
|
||||
|
||||
assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How a fill reads its image sources between texels
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum Filtering {
|
||||
/// Bilinear on the image level that matches the texel's footprint: smooth when the image is shrunk
|
||||
#[default]
|
||||
BilinearHq,
|
||||
/// Bilinear on the full image: sharp, but may shimmer where the image is shrunk
|
||||
BilinearSharp,
|
||||
/// The nearest image texel
|
||||
Nearest,
|
||||
}
|
||||
|
||||
impl Filtering {
|
||||
pub const ALL: [Filtering; 3] = [Filtering::BilinearHq, Filtering::BilinearSharp, Filtering::Nearest];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Filtering::BilinearHq => "bilinearHq",
|
||||
Filtering::BilinearSharp => "bilinearSharp",
|
||||
Filtering::Nearest => "nearest",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<Filtering> {
|
||||
Filtering::ALL.into_iter().find(|f| f.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Filtering, ScaleMode, UvWrap};
|
||||
use crate::FillSymmetry;
|
||||
|
||||
/// How a fill samples its images and what its size is set in; older fills read with [`Sampling::SAVED_BEFORE`]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct Sampling {
|
||||
#[serde(default)]
|
||||
pub filtering: Filtering,
|
||||
#[serde(default)]
|
||||
pub wrap: UvWrap,
|
||||
#[serde(default)]
|
||||
pub scale: ScaleMode,
|
||||
#[serde(default, skip_serializing_if = "FillSymmetry::is_default")]
|
||||
pub symmetry: FillSymmetry,
|
||||
}
|
||||
|
||||
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 };
|
||||
|
||||
/// Serde default for fills saved before the field existed
|
||||
pub fn saved_before() -> Sampling {
|
||||
Sampling::SAVED_BEFORE
|
||||
}
|
||||
|
||||
/// Whether it samples as fills saved before the field existed did (not saved then, so they save as they were)
|
||||
pub fn is_saved_before(&self) -> bool {
|
||||
*self == Sampling::SAVED_BEFORE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What a fill's size is set in: repeats of its tile, or the tile's length on the mesh (stored as tiling either way)
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum ScaleMode {
|
||||
#[default]
|
||||
Tiling,
|
||||
PhysicalSize,
|
||||
}
|
||||
|
||||
impl ScaleMode {
|
||||
pub const ALL: [ScaleMode; 2] = [ScaleMode::Tiling, ScaleMode::PhysicalSize];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
ScaleMode::Tiling => "tiling",
|
||||
ScaleMode::PhysicalSize => "physicalSize",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<ScaleMode> {
|
||||
ScaleMode::ALL.into_iter().find(|mode| mode.id() == id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UvTransform {
|
||||
pub tiling: [f32; 2],
|
||||
pub rotation: f32,
|
||||
pub offset: [f32; 2],
|
||||
}
|
||||
|
||||
impl Default for UvTransform {
|
||||
fn default() -> Self {
|
||||
UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
|
||||
}
|
||||
}
|
||||
|
||||
impl UvTransform {
|
||||
/// Whether it changes nothing, as projections saved before it existed did (not saved then)
|
||||
pub fn is_default(&self) -> bool {
|
||||
*self == UvTransform::default()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Whether a UV-placed fill repeats past its 0..1 tile, across, down, both or neither
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum UvWrap {
|
||||
#[default]
|
||||
Repeat,
|
||||
RepeatHorizontally,
|
||||
RepeatVertically,
|
||||
/// One tile only: outside it the fill does not cover
|
||||
None,
|
||||
}
|
||||
|
||||
impl UvWrap {
|
||||
pub const ALL: [UvWrap; 4] = [UvWrap::None, UvWrap::RepeatHorizontally, UvWrap::RepeatVertically, UvWrap::Repeat];
|
||||
|
||||
/// Command id
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
UvWrap::Repeat => "repeat",
|
||||
UvWrap::RepeatHorizontally => "repeatHorizontally",
|
||||
UvWrap::RepeatVertically => "repeatVertically",
|
||||
UvWrap::None => "none",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<UvWrap> {
|
||||
UvWrap::ALL.into_iter().find(|w| w.id() == id)
|
||||
}
|
||||
|
||||
/// Whether the fill repeats across (u) and down (v)
|
||||
pub fn repeats(self) -> (bool, bool) {
|
||||
match self {
|
||||
UvWrap::Repeat => (true, true),
|
||||
UvWrap::RepeatHorizontally => (true, false),
|
||||
UvWrap::RepeatVertically => (false, true),
|
||||
UvWrap::None => (false, false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -841,6 +841,7 @@ mod tests {
|
||||
l.as_object_mut().unwrap().remove("content_effects");
|
||||
}
|
||||
let old: Project = serde_json::from_value(v).unwrap();
|
||||
|
||||
assert!(old.layers.values().all(|l| l.content_effects.is_empty()));
|
||||
}
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ fn framed(session: &Session, command: &str, id: LayerId, effect: Option<LayerId>
|
||||
return Err(bad(command, "an axis planar reading a procedural pattern keeps its axis: placing its frame would move the pattern"));
|
||||
}
|
||||
|
||||
// A frame faces one way: culling read through an uneven or mirrored scale would hide other faces once the scale is in the frame (a placed frame keeps its edits that move no frame)
|
||||
// Keep the active projection while folding scaling would change which faces cull
|
||||
if matches!(projection, Projection::Planar { placed: None, .. }) && !culling_keeps_facing(projection) {
|
||||
return Err(bad(command, UNFOLDABLE_CULLING));
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ pub fn at_defaults(projection: &Projection, sampling: Sampling) -> bool {
|
||||
fn reset_projection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, "layer.fill.resetProjection")?;
|
||||
let (projection, sampling) = placement_mut(s, target)?;
|
||||
|
||||
if at_defaults(projection, *sampling) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
@@ -61,6 +62,7 @@ fn reset_projection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*sampling = reset_sampling(*sampling);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -84,6 +86,7 @@ mod tests {
|
||||
flip: [false; 2],
|
||||
};
|
||||
let mut kinds: Vec<Projection> = UNFRAMED_PROJECTION_IDS.iter().filter_map(|id| new_unframed_projection(id)).collect();
|
||||
|
||||
assert_eq!(kinds.len(), UNFRAMED_PROJECTION_IDS.len(), "every listed id makes a projection");
|
||||
|
||||
kinds.extend([Projection::warp(frame), Projection::decal(frame)]);
|
||||
@@ -94,7 +97,9 @@ mod tests {
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
|
||||
let reset = reset_projection_of(&turned);
|
||||
|
||||
assert_eq!(std::mem::discriminant(&reset), std::mem::discriminant(&kind), "{kind:?}");
|
||||
assert_eq!(reset.frame(), kind.frame(), "the frame stays where it is placed");
|
||||
}
|
||||
|
||||
@@ -13,6 +13,10 @@ use crate::commands::{
|
||||
use crate::layer_selection::{batch_param, ids_json};
|
||||
use crate::{EngineError, Result, Session, cmd, session::StackTarget};
|
||||
|
||||
mod fill_target;
|
||||
|
||||
pub(crate) use fill_target::FillTarget;
|
||||
|
||||
/// One full turn, in degrees (the brush's, so every angle wraps on the same turn)
|
||||
pub(crate) use texturecraft_paint::FULL_TURN_DEGREES;
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
use texturecraft_core::LayerId;
|
||||
|
||||
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's (`effect`)
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum FillTarget {
|
||||
Layer(LayerId),
|
||||
Effect(LayerId),
|
||||
}
|
||||
@@ -247,6 +247,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !s.doc.resources.contains_key(&name) {
|
||||
return Err(bad("resource.remove", format!("no resource `{name}`")));
|
||||
}
|
||||
|
||||
s.edit("Remove resource", |s| {
|
||||
s.doc.resources.remove(&name);
|
||||
Ok(())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The editing session: document, mesh, per-texture-set caches, history, tool state.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -60,7 +60,7 @@ impl SetCache {
|
||||
pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
|
||||
let (w, h) = ts.size();
|
||||
let gbuf = UvGBuffer::new(mesh, ts.material, w, h);
|
||||
// Padding stays inside each UV tile.
|
||||
// Padding stays inside each UV tile
|
||||
let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution());
|
||||
let covered = covered_tiles(&gbuf);
|
||||
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect();
|
||||
@@ -476,6 +476,8 @@ pub struct Session {
|
||||
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
|
||||
/// 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,
|
||||
/// 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).
|
||||
@@ -497,9 +499,6 @@ impl Session {
|
||||
let source = Arc::new(mesh);
|
||||
let mesh = tiled_mesh(&source, &doc.project);
|
||||
|
||||
// Depth maps built for the mesh this one replaces must not be taken for its own
|
||||
texturecraft_compose::projector_depth::ProjectorDepth::forget_all();
|
||||
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
|
||||
let (bounds_min, bounds_max) = mesh.bounds();
|
||||
@@ -547,6 +546,7 @@ impl Session {
|
||||
log: crate::log::SessionLog::new(),
|
||||
log_id: next_mesh_id(),
|
||||
depth_cache: None,
|
||||
projector_depth_cache: Default::default(),
|
||||
polygon_fill_drag: None,
|
||||
export_presets: Default::default(),
|
||||
brush_presets: Default::default(),
|
||||
@@ -827,9 +827,11 @@ impl Session {
|
||||
if changed.is_empty() && before.texture_sets.len() == self.doc.project.texture_sets.len() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.mesh = tiled_mesh(&self.source, &self.doc.project);
|
||||
self.mesh_id = next_mesh_id();
|
||||
self.depth_cache = None;
|
||||
self.projector_depth_cache = Default::default();
|
||||
for ts in changed {
|
||||
if let (Some(c), Some(set)) = (self.caches.get_mut(ts), self.doc.project.texture_sets.get(ts)) {
|
||||
*c = SetCache::new(&self.mesh, set);
|
||||
@@ -1021,6 +1023,7 @@ impl Session {
|
||||
let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None };
|
||||
let active = self.ts();
|
||||
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
|
||||
let mut mesh_bounds = None;
|
||||
let mut changed = false;
|
||||
for ts in order {
|
||||
let Some(cache) = self.caches.get_mut(ts) else { continue };
|
||||
@@ -1058,12 +1061,19 @@ impl Session {
|
||||
block_scales: cache.composite.block_scales.clone(),
|
||||
preview,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
bounds: *mesh_bounds.get_or_insert_with(|| self.mesh.bounds()),
|
||||
};
|
||||
|
||||
// Look ahead so sliced updates filter a run of tiles once
|
||||
cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() };
|
||||
texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below));
|
||||
texturecraft_compose::composite_tiles_with_projectors(
|
||||
&inputs,
|
||||
&self.mesh,
|
||||
&mut self.projector_depth_cache,
|
||||
&mut cache.composite,
|
||||
&tiles,
|
||||
Some(&mut cache.below),
|
||||
);
|
||||
|
||||
// The composited tiles and the neighbours their padding reached change
|
||||
let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles);
|
||||
@@ -1247,7 +1257,7 @@ const CHUNK: usize = 256;
|
||||
/// The most a budgeted update spends on settling tiles (what they show is already right).
|
||||
pub const SETTLE_BUDGET_MS: f64 = 6.0;
|
||||
|
||||
/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
|
||||
/// Take up to `max_tiles` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
|
||||
/// evaluate compact regions.
|
||||
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> {
|
||||
// A zero-sized request cannot select a pivot
|
||||
@@ -1259,17 +1269,26 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u
|
||||
return std::mem::take(dirty).into_iter().collect();
|
||||
}
|
||||
|
||||
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
|
||||
|
||||
// Partition by block order so only the requested chunk needs sorting
|
||||
tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
tiles.truncate(max_tiles);
|
||||
tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
|
||||
for tile in &tiles {
|
||||
dirty.remove(tile);
|
||||
// Keep only the earliest block-ordered tiles in this chunk
|
||||
let block_order = |(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x);
|
||||
let mut keys = dirty.iter().copied().map(block_order);
|
||||
let mut selected: BinaryHeap<_> = keys.by_ref().take(max_tiles).collect();
|
||||
for key in keys {
|
||||
if let Some(mut latest) = selected.peek_mut()
|
||||
&& key < *latest
|
||||
{
|
||||
*latest = key;
|
||||
}
|
||||
}
|
||||
|
||||
tiles
|
||||
selected
|
||||
.into_sorted_vec()
|
||||
.into_iter()
|
||||
.map(|(_, _, y, x)| {
|
||||
dirty.remove(&(x, y));
|
||||
(x, y)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited.
|
||||
|
||||
@@ -513,17 +513,23 @@ mod tests {
|
||||
let (mut service, jobs, results) = held_worker();
|
||||
service.begin_frame(&session, 0.0);
|
||||
service.get(&session, target);
|
||||
|
||||
assert!(service.poll(&session));
|
||||
|
||||
let job = jobs.try_recv().unwrap();
|
||||
results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap();
|
||||
|
||||
service.begin_frame(&session, 0.1);
|
||||
|
||||
assert!(service.get(&session, target).image.is_none());
|
||||
|
||||
let repaint = service.poll(&session);
|
||||
|
||||
assert!(service.is_fresh(target));
|
||||
assert!(repaint, "the frame drew before collecting the final thumbnail");
|
||||
|
||||
service.begin_frame(&session, 0.2);
|
||||
|
||||
assert!(service.get(&session, target).image.is_some());
|
||||
assert!(!service.poll(&session), "an idle cache must stop repainting");
|
||||
}
|
||||
@@ -539,6 +545,7 @@ mod tests {
|
||||
|
||||
service.begin_frame(&session, 0.1);
|
||||
service.poll(&session);
|
||||
|
||||
assert_eq!(jobs.try_recv().map(|job| job.target).ok(), Some(target), "the late request is dispatched, not dropped");
|
||||
}
|
||||
|
||||
|
||||
@@ -499,10 +499,14 @@ mod tests {
|
||||
#[test]
|
||||
fn hdr_resources_become_the_environment() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected");
|
||||
|
||||
let e = execute(&mut s, "display.set", &json!({"environment": "nonexistent"})).unwrap_err().to_string();
|
||||
|
||||
assert!(e.contains("Studio Soft"), "unknown environments are rejected with the valid names: {e}");
|
||||
assert_eq!(s.doc.project.display.environment, "Studio Soft");
|
||||
|
||||
execute(&mut s, "display.set", &json!({"environment": "Night"})).unwrap();
|
||||
let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3]));
|
||||
let mut hdr = Vec::new();
|
||||
@@ -510,6 +514,7 @@ mod tests {
|
||||
let name = s.import_resource_bytes("sky.hdr", hdr).unwrap();
|
||||
let res = &s.images[&name];
|
||||
assert!(!res.srgb && res.rgba[0][0] > 30.0, "HDR keeps values above 1");
|
||||
|
||||
let env = format!("resource:{name}");
|
||||
let r = execute(
|
||||
&mut s,
|
||||
@@ -517,12 +522,16 @@ mod tests {
|
||||
&json!({"environment": env, "specGloss": true, "parallax": true, "displacement": true, "taa": false, "scatterColor": [2.0, 0.5, 0.25], "scatterRadius": 0.3}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(r["environment"], json!(env));
|
||||
|
||||
let d = &s.doc.project.display;
|
||||
assert!(d.spec_gloss && d.parallax && d.displacement && !d.taa);
|
||||
assert_eq!((d.scatter_color, d.scatter_radius), ([1.0, 0.5, 0.25], 0.3), "scatter settings (clamped)");
|
||||
assert_eq!(d.environment_resource(), Some(name.as_str()));
|
||||
|
||||
execute(&mut s, "file.removeUnused", &Value::Null).unwrap();
|
||||
|
||||
assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used");
|
||||
}
|
||||
|
||||
@@ -530,16 +539,21 @@ mod tests {
|
||||
fn the_projection_gizmos_hide_per_project_and_old_projects_show_them() {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let shown = serde_json::to_value(&s.doc.project.display).unwrap();
|
||||
|
||||
assert!(s.doc.project.display.projection_gizmos && shown.get("projection_gizmos").is_none(), "shown by default and saved as before: {shown}");
|
||||
|
||||
let hidden = execute(&mut s, "display.set", &json!({"projectionGizmos": false})).unwrap();
|
||||
|
||||
assert!(!s.doc.project.display.projection_gizmos);
|
||||
assert_eq!(hidden["projection_gizmos"], json!(false), "hidden is saved with the project");
|
||||
assert!(s.history_labels().is_empty(), "a view flag is no undo step");
|
||||
|
||||
let reopened: texturecraft_core::project::DisplaySettings = serde_json::from_value(hidden).unwrap();
|
||||
|
||||
assert!(!reopened.projection_gizmos, "a saved project opens with its gizmos hidden");
|
||||
|
||||
let old: texturecraft_core::project::DisplaySettings = serde_json::from_value(shown).unwrap();
|
||||
|
||||
assert!(old.projection_gizmos, "a project saved before the flag shows them");
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,7 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() {
|
||||
}
|
||||
|
||||
let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
|
||||
assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert");
|
||||
}
|
||||
|
||||
@@ -65,5 +66,6 @@ fn a_pattern_parameter_given_alone_keeps_every_other_one() {
|
||||
fn another_pattern_kind_starts_from_its_defaults() {
|
||||
let (mut session, layer) = clouds_fill();
|
||||
execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap();
|
||||
|
||||
assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3]));
|
||||
}
|
||||
@@ -50,12 +50,19 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() {
|
||||
let plain = snapshot(&mut s);
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [30, 45, 60]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: rotation turns the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [0, 0, 0], "projectorScale": [2, 0.5, 1]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: per-axis scale stretches the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": 1, "offset": [0.3, 0.2, 0.1]}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), plain, "{kind}: offset moves the pattern");
|
||||
|
||||
set(&mut s, layer, json!({"offset": 0}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "{kind}: the defaults change nothing");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": [10, 20, 30], "projectorScale": [1, 2, 3]}));
|
||||
@@ -71,6 +78,7 @@ fn three_d_projection_settings_turn_stretch_and_move_every_3d_projection() {
|
||||
other => panic!("{kind}: loaded as {other:?}"),
|
||||
};
|
||||
assert_eq!(settings, Projector::default(), "{kind}: an older save has no turn or stretch");
|
||||
|
||||
set(&mut s, layer, json!({"projectorRotation": 0, "projectorScale": 1}));
|
||||
}
|
||||
|
||||
@@ -118,9 +126,12 @@ fn match_per_uv_tile_repeats_the_source_once_per_tile() {
|
||||
assert_ne!(left, right, "a UV projection runs on into the next tile");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "uvTile"}));
|
||||
|
||||
assert_eq!(projection(&s, layer), Projection::UvTile);
|
||||
|
||||
let (left, right) = tiles(&mut s);
|
||||
let worst = left.iter().zip(&right).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
|
||||
|
||||
assert!(worst < 1e-4, "every tile shows the same pattern (worst difference {worst})");
|
||||
}
|
||||
|
||||
@@ -132,13 +143,17 @@ fn cylindrical_angle_is_the_arc_one_repeat_spans() {
|
||||
set(&mut s, layer, json!({"projection": "cylindrical"}));
|
||||
let plain = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"angle": 120}));
|
||||
|
||||
assert!(matches!(projection(&s, layer), Projection::Cylindrical { angle: 120.0, .. }));
|
||||
assert_ne!(snapshot(&mut s), plain, "a third of the way round repeats three times");
|
||||
|
||||
set(&mut s, layer, json!({"angle": 360}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "360 degrees is the whole way round");
|
||||
|
||||
let mut saved = serde_json::to_value(projection(&s, layer)).unwrap();
|
||||
saved["Cylindrical"].as_object_mut().unwrap().remove("angle");
|
||||
|
||||
assert!(matches!(serde_json::from_value(saved).unwrap(), Projection::Cylindrical { angle: 360.0, .. }));
|
||||
}
|
||||
|
||||
@@ -160,6 +175,7 @@ fn shape_crop_stops_a_projection_at_its_shape() {
|
||||
set(&mut s, layer, json!({"projection": "triplanar"}));
|
||||
let plain = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"shapeCrop": "cropped"}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "the default box holds the whole mesh");
|
||||
|
||||
set(&mut s, layer, json!({"projectorScale": 0.5}));
|
||||
@@ -186,6 +202,7 @@ fn backface_culling_keeps_a_planar_projection_off_faces_turned_away() {
|
||||
let (far, near) = (facing_z(&s, -1.1, -0.05), facing_z(&s, 0.05, 1.1));
|
||||
assert!(!far.is_empty() && !near.is_empty());
|
||||
assert!(far.iter().any(|&i| plain[i] != empty[i]), "without culling the projection reaches the far side");
|
||||
|
||||
set(&mut s, layer, json!({"backfaceCulling": true, "backfaceAngle": 90, "backfaceHardness": 1}));
|
||||
let culled = snapshot(&mut s);
|
||||
assert!(far.iter().all(|&i| culled[i] == empty[i]), "faces turned away get none of the projection");
|
||||
@@ -241,6 +258,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() {
|
||||
let fill = Fill { projection: Projection::decal(frame), ..Fill::default() };
|
||||
|
||||
let saved = serde_json::to_value(&fill).unwrap();
|
||||
|
||||
assert_eq!(saved["projection"], json!({ "Decal": frame }));
|
||||
assert_eq!(serde_json::from_value::<Fill>(saved).unwrap(), fill, "and reads back the same");
|
||||
|
||||
@@ -248,6 +266,7 @@ fn placed_planars_with_a_decals_look_save_as_decals() {
|
||||
let Projection::Planar { uv, .. } = &mut turned.projection else { panic!("{:?}", turned.projection) };
|
||||
uv.rotation = 30.0;
|
||||
let saved = serde_json::to_value(&turned).unwrap();
|
||||
|
||||
assert_eq!(saved["projection"]["Planar"]["placed"], json!(frame));
|
||||
assert_eq!(serde_json::from_value::<Fill>(saved).unwrap(), turned);
|
||||
}
|
||||
@@ -265,6 +284,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
|
||||
assert_eq!((corners, depth), (Projection::FRAME_CORNERS, Projection::WARP_DEPTH));
|
||||
assert_eq!((frame.normal, frame.up), ([0.0, 0.0, 1.0], [0.0, 1.0, 0.0]), "seen from the front");
|
||||
assert!(frame.size.iter().all(|side| (side - 2.0).abs() < 1e-3) && frame.center.iter().all(|c| c.abs() < 1e-3), "around the unit sphere: {frame:?}");
|
||||
|
||||
let unpulled = snapshot(&mut s);
|
||||
assert_ne!(unpulled, empty);
|
||||
|
||||
@@ -272,7 +292,9 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
|
||||
set(&mut s, layer, json!({"warpCorners": pulled}));
|
||||
let bent = snapshot(&mut s);
|
||||
assert_ne!(bent, unpulled, "a pulled corner bends the image");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp", "rotation": 0}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), bent, "picking warp again keeps the corners");
|
||||
|
||||
set(&mut s, layer, json!({"shapeCrop": "cropped", "warpCorners": Projection::FRAME_CORNERS}));
|
||||
@@ -283,6 +305,7 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
|
||||
assert!(!beyond.is_empty() && !within.is_empty());
|
||||
assert!(beyond.iter().all(|&i| cropped[i] == empty[i]), "past its Projection Depth the warp does not reach");
|
||||
assert!(within.iter().all(|&i| cropped[i] == unpulled[i]), "within it the warp covers as before");
|
||||
|
||||
set(&mut s, layer, json!({"projectionDepth": 1}));
|
||||
let deep = snapshot(&mut s);
|
||||
assert!(beyond.iter().all(|&i| deep[i] == unpulled[i]), "a deeper warp reaches the whole sphere");
|
||||
@@ -291,15 +314,20 @@ fn warp_projection_bends_to_its_corners_reaches_its_depth_and_resets_its_frame()
|
||||
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap();
|
||||
let Projection::Warp { frame: reset, corners, depth, .. } = projection(&s, layer) else { panic!("still a warp") };
|
||||
assert_eq!((reset, corners, depth), (frame, Projection::FRAME_CORNERS, 1.0), "the frame and corners go back; the depth stays");
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "resetting a frame already reset adds no undo step");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["projection"], "Warp projection");
|
||||
assert_eq!(row["fill"]["projectionSettings"]["Warp"]["corners"], json!(Projection::FRAME_CORNERS));
|
||||
|
||||
set(&mut s, layer, json!({"projection": "planar"}));
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.resetFrame", &json!({"layer": layer.0})).is_err(), "only a warp has a frame to reset");
|
||||
}
|
||||
|
||||
@@ -314,6 +342,7 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
|
||||
set(&mut s, layer, json!({"projection": "planar", "axis": 2}));
|
||||
let Projection::Planar { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) };
|
||||
assert_eq!(projector.depth, DepthCulling::NEW, "a new planar projection culls by depth");
|
||||
|
||||
let culled = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"depthCulling": false}));
|
||||
let plain = snapshot(&mut s);
|
||||
@@ -326,18 +355,23 @@ fn depth_culling_keeps_planar_and_warp_projections_off_hidden_surfaces() {
|
||||
assert!(near.iter().all(|&i| culled[i] == plain[i]), "the near side keeps all of it");
|
||||
|
||||
set(&mut s, layer, json!({"depthCulling": true, "depthCullingHardness": 0}));
|
||||
|
||||
assert_ne!(snapshot(&mut s), culled, "a softer cull fades further behind the near side");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["projectionSettings"]["Planar"]["projector"]["depth"], json!({"on": true, "hardness": 0.0}));
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp"}));
|
||||
let Projection::Warp { projector, .. } = projection(&s, layer) else { panic!("{:?}", projection(&s, layer)) };
|
||||
assert_eq!(projector.depth, DepthCulling::NEW, "a new warp culls by depth");
|
||||
|
||||
let warped = snapshot(&mut s);
|
||||
assert!(far.iter().all(|&i| warped[i] == empty[i]), "a warp from the front leaves the far side bare");
|
||||
|
||||
let saved: Projector = serde_json::from_value(json!({"rotation": [0, 0, 0], "scale": [1, 1, 1]})).unwrap();
|
||||
|
||||
assert_eq!(saved.depth, DepthCulling { on: false, hardness: 0.75 }, "an older save has no depth culling");
|
||||
}
|
||||
|
||||
@@ -357,13 +391,17 @@ fn fill_symmetry_axis_reads_an_index_or_a_letter() {
|
||||
};
|
||||
|
||||
set(&mut s, layer, json!({"symmetryAxis": "Y"}));
|
||||
|
||||
assert_eq!(axis(&s), 1);
|
||||
|
||||
set(&mut s, layer, json!({"symmetryAxis": 2}));
|
||||
|
||||
assert_eq!(axis(&s), 2);
|
||||
|
||||
for refused in [json!("w"), json!(true), json!(-1), json!(3)] {
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": refused})).is_err(), "{refused}");
|
||||
}
|
||||
|
||||
assert_eq!(axis(&s), 2, "a refused axis changes nothing");
|
||||
}
|
||||
|
||||
@@ -392,7 +430,9 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() {
|
||||
assert!(filled(&far, &turned, &empty) > far.len() / 2, "the copy turned half round reaches the far side");
|
||||
assert!(near.iter().all(|&i| turned[i] == plain[i]), "the original keeps its own wedge");
|
||||
assert_ne!(turned, mirrored, "a turned copy is not a mirrored one");
|
||||
|
||||
set(&mut s, layer, json!({"symmetry": false}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "switched off, the copies go");
|
||||
|
||||
// A left to right ramp shows a copy's image turned over
|
||||
@@ -408,11 +448,14 @@ fn fill_symmetry_mirrors_or_turns_copies_of_a_3d_projection() {
|
||||
set(&mut s, layer, json!({"projection": "uv"}));
|
||||
let uv = snapshot(&mut s);
|
||||
set(&mut s, layer, json!({"symmetry": false}));
|
||||
|
||||
assert_eq!(snapshot(&mut s), uv, "a UV projection has no copies");
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryType": "spiral"})).is_err());
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "symmetryAxis": 3})).is_err());
|
||||
|
||||
let saved: Sampling = serde_json::from_value(json!({"filtering": "BilinearHq", "wrap": "Repeat", "scale": "Tiling"})).unwrap();
|
||||
|
||||
assert_eq!(saved.symmetry, FillSymmetry::OFF, "an older save has no symmetry");
|
||||
}
|
||||
|
||||
@@ -431,23 +474,28 @@ fn moving_an_axis_planar_places_it_as_its_frame_first() {
|
||||
let placed = projection(&s, layer);
|
||||
let Projection::Planar { placed: Some(frame), projector, .. } = &placed else { panic!("placed: {placed:?}") };
|
||||
assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "the turn is in the frame now");
|
||||
|
||||
let after = snapshot(&mut s);
|
||||
let moved = before.iter().zip(&after).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count();
|
||||
assert!(moved * 200 < before.len(), "the image stays where it was: {moved} of {} texels changed", before.len());
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "offset": [0.4, 0.0], "merge": true})).unwrap();
|
||||
|
||||
assert_ne!(snapshot(&mut s), after, "then the frame moves the image");
|
||||
let Projection::Planar { placed: Some(slid), .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
assert_eq!((slid.offset, slid.size), ([0.4, 0.0], frame.size));
|
||||
|
||||
s.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&s, layer), axis, "placing and moving is one step");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "warp", "warpCorners": [[-0.5, 0.5], [0.9, 0.9], [0.5, -0.5], [-0.5, -0.5]]}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).unwrap();
|
||||
let Projection::Warp { frame, corners, .. } = projection(&s, layer) else { panic!("still a warp") };
|
||||
assert_eq!((frame.rotation, corners[1]), (30.0, [0.9, 0.9]), "a warp's frame turns and keeps its corners");
|
||||
|
||||
set(&mut s, layer, json!({"projection": "spherical"}));
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "rotation": 30})).is_err(), "a spherical projection has no frame");
|
||||
}
|
||||
|
||||
@@ -486,6 +534,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing(
|
||||
if placed {
|
||||
set(&mut s, layer, json!({"projectorScale": 1}));
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert!(projection(&s, layer).placed().is_some(), "an even scale places the frame");
|
||||
}
|
||||
|
||||
@@ -502,6 +551,7 @@ fn a_frame_under_uneven_culling_is_refused_with_the_way_out_and_changes_nothing(
|
||||
|
||||
// A placed frame's edit that moves no frame still lands
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "flipU": true})).unwrap();
|
||||
|
||||
assert!(projection(&s, layer).frame().is_some_and(|frame| frame.flip[0]), "the flip lands on the placed frame");
|
||||
}
|
||||
|
||||
@@ -524,10 +574,14 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first(
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameOffset": [0.0, 0.0, 0.0]})).unwrap();
|
||||
let Projection::Planar { placed: Some(frame), projector, .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
assert_eq!((projector.rotation, projector.scale), ([0.0; 3], [1.0; 3]), "folded into the frame");
|
||||
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
assert!((Vec3::from(frame.center) - (lo + hi) * 0.5).length() < 1e-4, "offset 0 = the mesh's centre: {frame:?}");
|
||||
|
||||
let shown = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap();
|
||||
|
||||
assert!((shown.rotation[2] - 30.0).abs() < 1e-3 && shown.rotation[0].abs() < 1e-3, "the projector's turn shows as the frame's: {shown:?}");
|
||||
|
||||
let folded = snapshot(&mut s);
|
||||
let changed = turned.iter().zip(&folded).filter(|(a, b)| (*a - *b).abs() > 2.0 / 255.0).count();
|
||||
assert!(changed * 200 < turned.len(), "the frame was already at the centre: the image stays, {changed} of {} texels changed", turned.len());
|
||||
@@ -536,16 +590,21 @@ fn a_frame_takes_its_offset_rotation_and_scale_and_folds_its_projector_in_first(
|
||||
.unwrap();
|
||||
let Projection::Planar { placed: Some(narrow), .. } = projection(&s, layer) else { panic!("still placed") };
|
||||
assert!((narrow.size[0] - frame.size[0] * 0.5).abs() < 1e-4 && (narrow.size[1] - frame.size[1]).abs() < 1e-4, "Scale X halves the width");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "frameRotation": [0, 0, 90], "merge": true})).unwrap();
|
||||
let again = texturecraft_engine::compose::frame_placement::placement(&projection(&s, layer), (lo, hi)).unwrap();
|
||||
|
||||
assert!((again.rotation[2] - 90.0).abs() < 1e-3 && (again.scale[0] - shown.scale[0] * 0.5).abs() < 1e-4, "{again:?}");
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "a drag is one undo step");
|
||||
|
||||
s.undo().unwrap();
|
||||
|
||||
assert_eq!(snapshot(&mut s), turned, "undo puts the turned projector back");
|
||||
|
||||
for bad in [json!({"frameScale": [1, 2]}), json!({"frameOffset": "x"}), json!({"frameScale": [0, -1, "deep"]})] {
|
||||
let mut params = bad.clone();
|
||||
params["layer"] = json!(layer.0);
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", ¶ms).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
@@ -583,10 +642,12 @@ fn a_decal_edit_that_changes_nothing_adds_no_undo_step() {
|
||||
json!({"effect": mask_effect, "image": ramp}),
|
||||
] {
|
||||
execute(&mut s, "layer.decal.set", &unchanged).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "{unchanged} changes nothing");
|
||||
}
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer, "rotation": 45})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps + 1, "a turn is an edit");
|
||||
}
|
||||
|
||||
@@ -625,6 +686,7 @@ fn inspect_shows_a_mask_decals_frame_as_a_layer_decals() {
|
||||
] {
|
||||
assert!(on_request(frame), "the {name} shows its frame on the requested placement: {frame}");
|
||||
}
|
||||
|
||||
assert_eq!(layer_frame, layer_decal["decal"], "a layer decal's frame");
|
||||
assert_eq!(mask_effect["decal"], mask_decal["decal"], "a mask decal's frame");
|
||||
}
|
||||
@@ -652,6 +714,7 @@ fn a_warps_current_reach_as_depth_adds_no_undo_step() {
|
||||
|
||||
let reach = depth * frame.size[0].max(frame.size[1]);
|
||||
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "depth": reach})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "reach {reach} is the one it has");
|
||||
}
|
||||
|
||||
@@ -705,17 +768,21 @@ fn reset_fill_settings_keeps_the_projection_and_restores_its_defaults_in_one_und
|
||||
assert_eq!(reset.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the sampling is a new fill's; the symmetry stays");
|
||||
assert_eq!(reset.sources, changed.sources, "the material stays");
|
||||
assert!(texturecraft_engine::fill_reset_cmds::at_defaults(&reset.projection, reset.sampling));
|
||||
|
||||
let steps = s.history_labels().len();
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(s.history_labels().len(), steps, "resetting a Fill section at its defaults adds no undo step");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(fill(&s), changed, "one undo brings every setting back");
|
||||
assert!(execute(&mut s, "layer.fill.resetProjection", &json!({"layer": 9999})).is_err(), "no such layer");
|
||||
|
||||
// A UV fill comes back to a UV projection at tiling 1 and renders like a new fill
|
||||
set(&mut s, layer, json!({"projection": "uv", "tiling": [3, 2], "rotation": 30}));
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(fill(&s).projection, Projection::default());
|
||||
assert_eq!(snapshot(&mut s), fresh, "it renders like the new fill");
|
||||
}
|
||||
@@ -737,6 +804,7 @@ fn reset_fill_settings_keeps_a_warp_frame_and_restores_its_settings() {
|
||||
assert_ne!(moved, fitted, "the frame was moved");
|
||||
|
||||
execute(&mut s, "layer.fill.resetProjection", &json!({"layer": layer.0})).unwrap();
|
||||
|
||||
assert_eq!(projection(&s, layer), Projection::warp(moved), "still a warp: its frame stays, every setting is a new warp's");
|
||||
}
|
||||
|
||||
@@ -760,6 +828,7 @@ fn malformed_warp_corners_copy_flips_and_a_warps_own_placement_are_rejected_and_
|
||||
] {
|
||||
let mut p = bad.clone();
|
||||
p["layer"] = json!(layer.0);
|
||||
|
||||
assert!(execute(&mut s, "layer.fill.projection", &p).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
|
||||
@@ -71,10 +71,12 @@ fn filtering_decides_how_a_shrunk_image_reads() {
|
||||
let red = cache.composite.value(Channel::BaseColor, x, y)[0];
|
||||
!(0.01..=0.99).contains(&red)
|
||||
});
|
||||
|
||||
assert!(pure, "Nearest reads one image texel: black or white only");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["filtering"], json!("nearest"));
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err());
|
||||
}
|
||||
@@ -90,6 +92,7 @@ fn fills_saved_before_filtering_keep_their_look() {
|
||||
let mut saved = serde_json::to_value(fill).unwrap();
|
||||
saved.as_object_mut().unwrap().remove("sampling");
|
||||
let loaded: Fill = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE);
|
||||
assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp);
|
||||
}
|
||||
@@ -126,18 +129,22 @@ fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() {
|
||||
let near = |got: f32, want: f32| (got - want).abs() < 0.05;
|
||||
let repeat = shown(&mut s);
|
||||
assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}");
|
||||
|
||||
set(&mut s, json!({"wrap": "none"})).unwrap();
|
||||
let none = shown(&mut s);
|
||||
assert!(near(none, 0.125), "None: a quarter across, half down: {none}");
|
||||
|
||||
set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap();
|
||||
let across = shown(&mut s);
|
||||
assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}");
|
||||
|
||||
set(&mut s, json!({"wrap": "repeatVertically"})).unwrap();
|
||||
let down = shown(&mut s);
|
||||
assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}");
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["wrap"], json!("repeatVertically"));
|
||||
assert!(set(&mut s, json!({"wrap": "mirror"})).is_err());
|
||||
|
||||
@@ -187,12 +194,16 @@ fn three_d_projections_take_uv_transformations() {
|
||||
let mut saved = serde_json::to_value(projection(&s)).unwrap();
|
||||
saved["Triplanar"].as_object_mut().unwrap().remove("uv");
|
||||
let loaded: Projection = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default()));
|
||||
|
||||
set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap();
|
||||
|
||||
assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing");
|
||||
|
||||
// On a UV projection, tiling is its scale
|
||||
set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap();
|
||||
|
||||
assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0]));
|
||||
}
|
||||
|
||||
@@ -208,11 +219,13 @@ fn scale_mode_is_stored_without_changing_the_tiling() {
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
|
||||
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone();
|
||||
|
||||
assert_eq!(row["fill"]["scaleMode"], json!("physicalSize"));
|
||||
assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err());
|
||||
|
||||
let mut saved = serde_json::to_value(&fill).unwrap();
|
||||
saved["sampling"].as_object_mut().unwrap().remove("scale");
|
||||
let loaded: Fill = serde_json::from_value(saved).unwrap();
|
||||
|
||||
assert_eq!(loaded.sampling.scale, ScaleMode::Tiling);
|
||||
}
|
||||
@@ -133,6 +133,7 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
execute(&mut s, "effect.add.filter", &p).unwrap();
|
||||
}
|
||||
|
||||
assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
@@ -187,10 +188,13 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
let name = s
|
||||
.import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] }))
|
||||
.unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": "missing.png"})).is_err());
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 2, "y": 2})).is_err(), "off the mesh");
|
||||
|
||||
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
|
||||
let layer = id(r.clone(), "layer");
|
||||
|
||||
assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6);
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
assert!(matches!(f.projection, Projection::Planar { placed: Some(_), .. }));
|
||||
@@ -202,19 +206,30 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
|
||||
// Bigger, then moved along its plane, then re-placed with a click
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0)));
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap();
|
||||
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "moved away");
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"x": 170, "y": 180})).unwrap();
|
||||
|
||||
assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset");
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
|
||||
assert!(inspect.contains("Planar projection") && inspect.contains("\"decal\"") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
|
||||
|
||||
// Not a decal; one undo step per edit
|
||||
let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err());
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
}
|
||||
|
||||
@@ -239,9 +254,13 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
|
||||
// Only the effect id, with no layer selected
|
||||
s.selected.clear();
|
||||
|
||||
assert!(s.selected_layer().is_none());
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap();
|
||||
|
||||
assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported");
|
||||
|
||||
let after = effect_decal(&s, effect);
|
||||
assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0));
|
||||
assert_eq!(after.center, before.center, "the other fields stay");
|
||||
@@ -249,10 +268,12 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
|
||||
// Re-placing with a click
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap();
|
||||
|
||||
assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]);
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal");
|
||||
|
||||
// The layer decal is untouched by all of it
|
||||
@@ -261,8 +282,10 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
|
||||
// Errors: unknown effect, an effect that is not a decal, an effect of another layer
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err());
|
||||
|
||||
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
|
||||
let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect");
|
||||
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err());
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err());
|
||||
assert_eq!(effect_decal(&s, effect), before);
|
||||
@@ -270,6 +293,7 @@ fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
|
||||
// A new image replaces the effect's source, not a layer channel
|
||||
let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap();
|
||||
|
||||
assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other));
|
||||
}
|
||||
|
||||
@@ -281,8 +305,10 @@ fn decals_keep_the_image_aspect_and_flip_their_image() {
|
||||
let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap();
|
||||
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
|
||||
let layer = id(r.clone(), "layer");
|
||||
|
||||
assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image");
|
||||
assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra");
|
||||
|
||||
let size = |s: &mut Session| {
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
let Projection::Planar { placed: Some(d), .. } = &f.projection else { panic!("a decal") };
|
||||
@@ -291,33 +317,52 @@ fn decals_keep_the_image_aspect_and_flip_their_image() {
|
||||
|
||||
// A pair of sides is taken as given, unless the proportions are kept: then the width wins
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.6]);
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step");
|
||||
|
||||
// Flip U and V each on their own, kept by later edits, undone one step at a time
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0)));
|
||||
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap();
|
||||
|
||||
assert_eq!(r["decal"]["flip"], json!([true, false]));
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [true, true]);
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [false, true], "the other flip stays");
|
||||
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).1, [true, true]);
|
||||
|
||||
// A new image in the same call sets the aspect: a tall one (1:2)
|
||||
let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap();
|
||||
execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap();
|
||||
|
||||
assert_eq!(size(&mut s).0, [0.2, 0.4]);
|
||||
}
|
||||
|
||||
@@ -505,28 +550,36 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() {
|
||||
let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5});
|
||||
|
||||
let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer");
|
||||
|
||||
assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::<Vec<_>>(), [Channel::Roughness]);
|
||||
assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal");
|
||||
assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel");
|
||||
|
||||
let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap();
|
||||
|
||||
assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks");
|
||||
|
||||
let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap();
|
||||
let masked = id(added.clone(), "layer");
|
||||
let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap();
|
||||
|
||||
assert!(
|
||||
matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Planar { placed: Some(_), .. }, .. }))
|
||||
);
|
||||
assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0));
|
||||
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere");
|
||||
|
||||
let effect = &added["maskEffect"];
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap();
|
||||
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0)));
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect");
|
||||
|
||||
execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer");
|
||||
let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4});
|
||||
assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused");
|
||||
@@ -686,24 +739,32 @@ fn fill_projection_edits_keep_what_they_do_not_change() {
|
||||
};
|
||||
set(&mut s, json!({"rotation": 390, "offset": [0.25, 0.5]})).unwrap();
|
||||
set(&mut s, json!({"scale": 2})).unwrap();
|
||||
|
||||
assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 2.0], rotation: 30.0, offset: [0.25, 0.5] }, "a scale keeps the rotation and offset");
|
||||
|
||||
set(&mut s, json!({"projection": "uv", "scale": [2, 3], "offset": "far"})).unwrap();
|
||||
|
||||
assert_eq!(proj(&s), Projection::Uv { scale: [2.0, 3.0], rotation: 30.0, offset: [0.25, 0.5] }, "the same kind keeps its fields; a bad offset is ignored");
|
||||
|
||||
set(&mut s, json!({"projection": "triplanar", "offset": [1, 2, 3]})).unwrap();
|
||||
set(&mut s, json!({"sharpness": 100})).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
proj(&s),
|
||||
Projection::Triplanar { scale: 1.0, sharpness: 64.0, offset: [1.0, 2.0, 3.0], uv: Default::default(), projector: Default::default() },
|
||||
"a new kind starts from its defaults"
|
||||
);
|
||||
|
||||
set(&mut s, json!({"projection": "planar", "axis": 7, "offset": [1e9, 0, 0]})).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
proj(&s),
|
||||
Projection::Planar { scale: 1.0, axis: 2, offset: [1000.0, 0.0, 0.0], uv: Default::default(), projector: Projector::depth_culled(), placed: None },
|
||||
"hostile values are clamped"
|
||||
);
|
||||
assert!(set(&mut s, json!({"projection": "hexagonal"})).is_err());
|
||||
// The offset moves the pattern: a UV offset changes what the composite shows.
|
||||
|
||||
// The offset moves the pattern: a UV offset changes what the composite shows
|
||||
set(&mut s, json!({"projection": "uv", "scale": 1})).unwrap();
|
||||
execute(
|
||||
&mut s,
|
||||
@@ -934,6 +995,7 @@ fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited
|
||||
let bytes = session.to_project_bytes().unwrap();
|
||||
|
||||
let mut loaded = Session::from_project_bytes(&bytes).unwrap();
|
||||
|
||||
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
|
||||
|
||||
execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap();
|
||||
|
||||
@@ -202,6 +202,7 @@ fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() {
|
||||
}
|
||||
|
||||
assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask"));
|
||||
|
||||
let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap();
|
||||
let before = s.doc.project.clone();
|
||||
let history = s.history_labels();
|
||||
|
||||
@@ -610,7 +610,9 @@ mod tests {
|
||||
#[test]
|
||||
fn uv_density_is_mesh_units_per_uv_unit() {
|
||||
assert_eq!(quad().uv_density(0), Some(1.0));
|
||||
|
||||
let plane = crate::primitives::plane(3.0, 4).uv_density(0).unwrap();
|
||||
|
||||
assert!((plane - 3.0).abs() < 1e-4, "{plane}");
|
||||
assert_eq!(quad().uv_density(1), None, "no triangles of that material");
|
||||
}
|
||||
|
||||
@@ -496,6 +496,7 @@ mod tests {
|
||||
(None, Some(lib)) => lib.sample(shape.level, x, y),
|
||||
(None, None) => shape.alpha.sample(x, y, 0.4, 7),
|
||||
};
|
||||
|
||||
assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,7 +762,7 @@ fn warmth(img: &Img) -> f32 {
|
||||
fn imported_hdr_environment_lights_the_ball() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let base = render(&mut h, &frame, "env_default");
|
||||
// A procedural HDR: a hot orange sky over a dim blue ground (values far above 1).
|
||||
// A procedural HDR: a hot orange sky over a dim blue ground (values far above 1)
|
||||
let (w, hh) = (256u32, 128u32);
|
||||
let rgba = (0..w * hh).map(|i| if i / w < hh / 2 { [12.0, 4.0, 1.0, 1.0] } else { [0.02, 0.05, 0.2, 1.0] }).collect();
|
||||
let sky = ImageRes::new(w, hh, rgba, false);
|
||||
@@ -771,7 +771,9 @@ fn imported_hdr_environment_lights_the_ball() {
|
||||
assert_ne!(lit.px, base.px, "the imported environment changes the lighting");
|
||||
assert!(warmth(&lit) > warmth(&base) + 10.0, "the orange sky tints the ball");
|
||||
assert!(lit.mean(200, 100, 280, 180) > 20.0, "lit, finite shading (NaNs would render black)");
|
||||
|
||||
h.renderer.set_environment(&h.device, &h.queue, "Studio Soft", None);
|
||||
|
||||
assert_eq!(render(&mut h, &frame, "env_default_again").px, base.px, "built-ins come back");
|
||||
}
|
||||
|
||||
|
||||
@@ -519,7 +519,7 @@ fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize,
|
||||
effect_group(app, ui, &layer, depth, true, false);
|
||||
}
|
||||
|
||||
// A line under the layer and its effects separates it from the next layer.
|
||||
// A line under the layer and its effects separates it from the next layer
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let available = ui.available_rect_before_wrap();
|
||||
ui.painter().hline(available.x_range(), available.top() - 0.5, Stroke::new(1.0, tokens.separator));
|
||||
@@ -567,7 +567,6 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
|
||||
// One of several selected layers (Shift/Ctrl+click) is highlighted like the active one
|
||||
let highlighted = selected || app.session.is_layer_selected(layer.id);
|
||||
let several = selection_with(app, layer.id);
|
||||
let content_target = selected && targets_content(app);
|
||||
let preferred_size = layer_preview_size(app);
|
||||
let row_height = layer_row_height(preferred_size);
|
||||
@@ -849,8 +848,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
let shelf = row.dnd_hover_payload::<ShelfDrag>().map(|drag| drag.asset.clone());
|
||||
|
||||
// Several selected layers move together, so none of them is a place to drop them
|
||||
let in_drag = |dragged: u64| dragged == layer.id.0 || several.as_ref().is_some_and(|layers| layers.contains(&dragged));
|
||||
let moving = row.dnd_hover_payload::<u64>().is_some_and(|dragged| !in_drag(*dragged));
|
||||
let in_drag = |app: &TextureCraftApp, dragged: u64| {
|
||||
dragged == layer.id.0 || (app.session.is_layer_selected(layer.id) && app.session.is_layer_selected(LayerId(dragged)))
|
||||
};
|
||||
let moving = row.dnd_hover_payload::<u64>().is_some_and(|dragged| !in_drag(app, *dragged));
|
||||
let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent);
|
||||
let shelf_material = shelf.as_ref().is_some_and(Asset::is_material);
|
||||
if moving || shelf_material {
|
||||
@@ -867,7 +868,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside);
|
||||
}
|
||||
if let Some(dragged) = dnd_release::<u64>(&row)
|
||||
&& !in_drag(*dragged)
|
||||
&& !in_drag(app, *dragged)
|
||||
{
|
||||
match selection_with(app, LayerId(*dragged)) {
|
||||
Some(layers) => app.run("layer.move", json!({"layers": layers, "above": layer.id.0, "inside": inside})),
|
||||
@@ -1812,6 +1813,7 @@ mod image_menu_tests {
|
||||
harness.run_steps(30);
|
||||
|
||||
assert!(preview_stats(&harness.ctx).0 > initial_previews, "scrolling creates newly visible previews");
|
||||
|
||||
harness.get_by_label(&last_name).click();
|
||||
harness.run_steps(2);
|
||||
|
||||
|
||||
@@ -355,7 +355,7 @@ fn placement_rows(
|
||||
None => PreviewLower::Offset { values: &mut lower_offset, range: OFFSET_TRACK, typed: OFFSET_TYPED },
|
||||
};
|
||||
let placement = Placement { tiling, rotation, offset };
|
||||
let bounds = app.session.mesh.bounds();
|
||||
let bounds = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
|
||||
// A warp shows its frame's size and turn as its gizmo leaves them
|
||||
let warp = match &fill.projection {
|
||||
@@ -423,7 +423,7 @@ fn world_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &F
|
||||
let edited = |fields: &[NumberField]| -> Vec<f32> { fields.iter().map(|field| field.value).collect() };
|
||||
|
||||
// A placed planar or a warp: the frame, its projector folded in
|
||||
if let Some(shown) = frame_placement::placement(&fill.projection, app.session.mesh.bounds()) {
|
||||
if let Some(shown) = frame_placement::placement(&fill.projection, app.viewport_mesh_bounds.get(&app.session.mesh)) {
|
||||
let run = |app: &mut TextureCraftApp, key: &str, values: Vec<f32>, merge: bool| {
|
||||
app.run("layer.decal.set", with(base, json!({key: values, "merge": merge})));
|
||||
};
|
||||
|
||||
@@ -386,6 +386,7 @@ mod tests {
|
||||
let placement = |offset: [f32; 2]| Placement { tiling: [2.0, 2.0], rotation: 30.0, offset };
|
||||
let (still, rest) = slid_window(placement([0.0, 0.0]));
|
||||
assert_eq!(rest, [0.5, 0.5], "at Offset 0 the dot sits in the ring");
|
||||
|
||||
let slid = placement([-0.25, 0.0]);
|
||||
let (columns, dot) = slid_window(slid);
|
||||
assert_eq!(columns, still, "the view never zooms or turns for the Offset");
|
||||
|
||||
@@ -30,11 +30,13 @@ const SPAN_SLIDER: usize = 1;
|
||||
pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, projection: &Projection, sampling: Sampling, base: &Value) {
|
||||
let symmetry = sampling.symmetry;
|
||||
let run = |app: &mut TextureCraftApp, fields: Value| run_projection(app, base, fields);
|
||||
|
||||
if !projection.takes_symmetry() {
|
||||
let reason = match projection {
|
||||
Projection::UvTile => tr("Not available with Fill (Match per UV Tile)"),
|
||||
_ => tr("Not available with UV projection"),
|
||||
};
|
||||
|
||||
sheet.section_unavailable(tr("Symmetry"), reason);
|
||||
return;
|
||||
}
|
||||
@@ -51,10 +53,12 @@ pub(crate) fn symmetry_section(app: &mut TextureCraftApp, sheet: &mut PropertySh
|
||||
if let Some(kind) = picked {
|
||||
run(app, json!({"symmetryType": kind.id()}));
|
||||
}
|
||||
|
||||
let axis = symmetry.axis_index();
|
||||
if let Some(picked) = sheet.switch_tinted(tr("Axis"), &AXIS_NAMES, axis, &AXIS_COLORS) {
|
||||
run(app, json!({"symmetryAxis": picked}));
|
||||
}
|
||||
|
||||
if symmetry.kind == SymmetryKind::Radial {
|
||||
radial_rows(app, sheet, &symmetry, base);
|
||||
}
|
||||
@@ -86,10 +90,12 @@ fn radial_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, symmetr
|
||||
let picture = |painter: &Painter, rect: Rect| ring_picture(painter, rect, symmetry, axis_color, &tokens);
|
||||
let count = symmetry.copies();
|
||||
let (mut count_value, mut span_value) = (count as f32, symmetry.span);
|
||||
|
||||
let mut sliders = [
|
||||
StackSlider { label: tr("Count"), value: &mut count_value, range: COUNT_TRACK, typed: COUNT_TYPED, decimals: 0, suffix: "" },
|
||||
StackSlider { label: tr("Angle span"), value: &mut span_value, range: FillSymmetry::SPANS, typed: FillSymmetry::SPANS, decimals: 0, suffix: "°" },
|
||||
];
|
||||
|
||||
let edited = sheet.picture_sliders(&picture, &mut sliders);
|
||||
if let Some((SPAN_SLIDER, merge)) = edited {
|
||||
run_projection(app, base, json!({"angleSpan": span_value, "merge": merge}));
|
||||
|
||||
@@ -101,7 +101,8 @@ impl FrameGizmo {
|
||||
if unplaced && placing_moves_pattern(sources.into_iter()) {
|
||||
return None;
|
||||
}
|
||||
let placed = placed_from_axis(projection, app.session.mesh.bounds());
|
||||
|
||||
let placed = placed_from_axis(projection, app.viewport_mesh_bounds.get(&app.session.mesh));
|
||||
|
||||
// Where the projection lands: a projector's own turn and scale moved into the frame, as the panel's 3D projection settings show it
|
||||
let landed = folded(placed.as_ref().unwrap_or(projection))?;
|
||||
@@ -290,7 +291,7 @@ impl Gizmo for FrameGizmo {
|
||||
json!({"size": size})
|
||||
}
|
||||
FrameGrab::Turn => {
|
||||
// The sweep round the centre on the frame's own plane (across turning towards up is a positive turn), so a tilted or off-centre frame follows the pointer too
|
||||
// Measure the turn in the frame's own plane so a tilted frame follows the pointer
|
||||
let angle = |p: Pos2| self.on_plane(app, rect, p).map(|[across, up]| (up * self.decal.size[1]).atan2(across * self.decal.size[0]).to_degrees());
|
||||
let swept = angle(to)? - angle(from)?;
|
||||
let swept = (swept + HALF_TURN).rem_euclid(2.0 * HALF_TURN) - HALF_TURN;
|
||||
@@ -537,6 +538,7 @@ pub(crate) mod tests {
|
||||
assert!(slid.offset[0] > 0.0 && slid.offset[1].abs() < slid.offset[0] * 0.2, "the centre square slides it right: {slid:?}");
|
||||
assert_eq!(slid.size, axis.decal.size, "sliding keeps its size");
|
||||
assert_eq!(harness.state().session.history_labels().last().map(String::as_str), Some("Edit decal"));
|
||||
|
||||
let steps = harness.state().session.history_labels().len();
|
||||
|
||||
let placed = gizmo(&harness);
|
||||
@@ -557,6 +559,7 @@ pub(crate) mod tests {
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
let warp = gizmo(&harness);
|
||||
assert_eq!(warp.warp, Some(Projection::FRAME_CORNERS));
|
||||
|
||||
let to = warp.corners[1] + vec2(-40.0, 30.0);
|
||||
drag(&mut harness, warp.corners[1], to, Modifiers::NONE);
|
||||
let Projection::Warp { corners, frame, .. } = projection(&harness, layer) else { panic!("still a warp") };
|
||||
@@ -646,6 +649,7 @@ pub(crate) mod tests {
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
let warp = gizmo(&harness);
|
||||
assert_eq!(warp.grab(warp.sides[1]), Some(FrameGrab::Side(1)));
|
||||
|
||||
drag(&mut harness, warp.sides[1], warp.center + (warp.sides[1] - warp.center) * 0.5, Modifiers::NONE);
|
||||
let Projection::Warp { frame, corners, .. } = projection(&harness, layer) else { panic!("still a warp") };
|
||||
assert!(frame.size[0] < warp.decal.size[0] * 0.75 && (frame.size[1] - warp.decal.size[1]).abs() < 1e-4, "the right edge dot narrows it: {frame:?}");
|
||||
@@ -661,6 +665,7 @@ pub(crate) mod tests {
|
||||
let center = gizmo(&harness).center;
|
||||
let to = center + vec2(40.0, 0.0);
|
||||
press_and_move(&mut harness, center, to, Modifiers::NONE);
|
||||
|
||||
assert!(frame_dragging(&harness), "the centre square is held");
|
||||
|
||||
harness.event(egui::Event::WindowFocused(false));
|
||||
@@ -673,9 +678,12 @@ pub(crate) mod tests {
|
||||
harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32));
|
||||
harness.run_steps(1);
|
||||
}
|
||||
|
||||
assert_eq!(projection(&harness, layer), left, "moves after it leave the frame where it was");
|
||||
|
||||
harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "and add no step");
|
||||
}
|
||||
|
||||
@@ -693,6 +701,7 @@ pub(crate) mod tests {
|
||||
|
||||
harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT);
|
||||
harness.run_steps(1);
|
||||
|
||||
assert_ne!(harness.state().session.camera, camera, "Alt turns the camera");
|
||||
assert!(!frame_dragging(&harness), "and ends the frame drag");
|
||||
|
||||
@@ -700,9 +709,12 @@ pub(crate) mod tests {
|
||||
harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32));
|
||||
harness.run_steps(1);
|
||||
}
|
||||
|
||||
assert_eq!(projection(&harness, layer), slid, "Alt let go, the frame stays where the drag left it");
|
||||
|
||||
harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
@@ -722,7 +734,7 @@ pub(crate) mod tests {
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (mut harness, layer) = fill_app("warp");
|
||||
|
||||
// The frame waits at its left limit, a mesh diagonal off the ball's centre, clear of the panels on the right; the camera backs off so it shows with its arrows
|
||||
// Offset the frame from the panels and back the camera up to expose its arrows
|
||||
harness.state_mut().run("layer.decal.set", json!({"layer": layer.0, "offset": [-100.0, 0.0]})).unwrap();
|
||||
harness.state_mut().session.camera.distance *= 3.0;
|
||||
harness.run_steps(2);
|
||||
@@ -735,12 +747,14 @@ pub(crate) mod tests {
|
||||
press_and_move(&mut harness, tip, tip - inward * 25.0, Modifiers::NONE);
|
||||
|
||||
assert_eq!(projection(&harness, layer), at_limit, "past the limit the frame stays where it is");
|
||||
|
||||
move_and_let_go(&mut harness, tip - inward * 25.0, tip + inward * 25.0);
|
||||
|
||||
assert_ne!(projection(&harness, layer), at_limit, "back inside the frame moves");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag made its own undo step");
|
||||
|
||||
harness.state_mut().session.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&harness, layer), at_limit, "undo takes back the drag only");
|
||||
}
|
||||
|
||||
@@ -752,6 +766,7 @@ pub(crate) mod tests {
|
||||
|
||||
harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "roughness", "procedural": "Checker"})).unwrap();
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none(), "placing would move the pattern");
|
||||
}
|
||||
|
||||
@@ -769,11 +784,15 @@ pub(crate) mod tests {
|
||||
press_and_move(&mut harness, center, center + vec2(0.0, 30.0), Modifiers::NONE);
|
||||
harness.key_press_modifiers(Modifiers::COMMAND, egui::Key::Z);
|
||||
harness.run_steps(1);
|
||||
|
||||
assert_eq!(projection(&harness, layer), first, "Ctrl+Z undid the drag so far");
|
||||
|
||||
move_and_let_go(&mut harness, center + vec2(0.0, 30.0), center + vec2(0.0, 40.0));
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the drag's later edits made a step of their own");
|
||||
|
||||
harness.state_mut().session.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&harness, layer), first, "undo goes back to where the first drag left the frame");
|
||||
}
|
||||
|
||||
@@ -797,21 +816,28 @@ pub(crate) mod tests {
|
||||
assert!(eye.left() > projection_row.right() && (eye.center().y - projection_row.center().y).abs() < 0.5, "the eye ends the Projection row");
|
||||
|
||||
click(&mut harness, eye.center());
|
||||
|
||||
assert!(!harness.state().session.doc.project.display.projection_gizmos, "the eye hides the gizmos");
|
||||
assert!(FrameGizmo::shown(harness.state(), harness.state().viewport_rect).is_none(), "the 3D view has no frame to draw or grab");
|
||||
|
||||
let before = projection(&harness, layer);
|
||||
drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_eq!(projection(&harness, layer), before, "a drag where the centre square was moves nothing");
|
||||
|
||||
let eye = harness.get_by_label("Show projection gizmos").rect();
|
||||
click(&mut harness, eye.center());
|
||||
|
||||
assert!(harness.state().session.doc.project.display.projection_gizmos, "the eye shows them again");
|
||||
|
||||
drag(&mut harness, shown.center, shown.center + vec2(30.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_ne!(projection(&harness, layer), before, "shown, the centre square slides it again");
|
||||
|
||||
// A UV projection has no gizmo: its row keeps the whole width for the dropdown
|
||||
harness.state_mut().run("layer.fill.projection", json!({"layer": layer.0, "projection": "uv"})).unwrap();
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(harness.query_by_label("Hide projection gizmos").is_none(), "no eye without a gizmo");
|
||||
}
|
||||
|
||||
@@ -957,6 +983,7 @@ pub(crate) mod tests {
|
||||
let side = gizmo(&harness);
|
||||
drag_frames(&mut harness, layer, side.sides[0], side.center + (side.sides[0] - side.center) * 0.5, Modifiers::NONE, true, check(layer));
|
||||
let narrowed = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap();
|
||||
|
||||
assert!(narrowed.scale[1] < slid.scale[1] * 0.75 && (narrowed.scale[0] - slid.scale[0]).abs() < 1e-4, "{slid:?} -> {narrowed:?}");
|
||||
|
||||
// The view steps back so a corner shows beside the panels
|
||||
@@ -967,6 +994,7 @@ pub(crate) mod tests {
|
||||
let inside = *corner.corners.iter().find(|at| view.contains(**at)).expect("a corner in the view");
|
||||
drag_frames(&mut harness, layer, inside, corner.center + (inside - corner.center) * 0.6, Modifiers::NONE, true, check(layer));
|
||||
let scaled = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap();
|
||||
|
||||
assert!(scaled.scale[1] < narrowed.scale[1] * 0.8 && scaled.scale[0] < narrowed.scale[0] * 0.8, "a corner scales it: {scaled:?}");
|
||||
|
||||
// Move on model held with Shift turns the frame round its normal
|
||||
@@ -974,6 +1002,7 @@ pub(crate) mod tests {
|
||||
let button = harness.get_by_label("Move on model").rect().center();
|
||||
drag_frames(&mut harness, layer, button, button + vec2(-60.0, 0.0), Modifiers::SHIFT, true, check(layer));
|
||||
let turned = placement(&projection(&harness, layer), harness.state().session.mesh.bounds()).unwrap();
|
||||
|
||||
assert!((turned.rotation[2] - before.rotation[2]).abs() > 10.0, "turned: {before:?} -> {turned:?}");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 4, "one undo step per drag");
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0;
|
||||
pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<bool> {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let mut edit = typed;
|
||||
|
||||
@@ -28,6 +29,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<b
|
||||
let width = (ui.available_width() - button_width - ui.spacing().item_spacing.x).max(MIN_BAR_WIDTH);
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(width, KNOB_RADIUS * 2.0 + KNOB_STROKE * 2.0), Sense::click_and_drag());
|
||||
let bar = Rect::from_center_size(rect.center(), vec2(rect.width() - KNOB_RADIUS * 2.0, BAR_HEIGHT));
|
||||
|
||||
if response.is_pointer_button_down_on() {
|
||||
// A grab of the bar ends typing, so the field shows the dragged value
|
||||
ui.data_mut(|data| data.remove_temp::<String>(field));
|
||||
@@ -54,6 +56,7 @@ pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option<b
|
||||
*value = 1.0 - *value;
|
||||
edit = Some(false);
|
||||
}
|
||||
|
||||
edit
|
||||
})
|
||||
.inner
|
||||
|
||||
@@ -137,6 +137,7 @@ mod uv_tile_grid;
|
||||
mod uv_view_map;
|
||||
mod view_mode_picker;
|
||||
pub mod viewport;
|
||||
mod viewport_mesh_bounds;
|
||||
mod warp_checker;
|
||||
pub mod web_files;
|
||||
pub mod widgets;
|
||||
@@ -209,6 +210,7 @@ pub struct Toast {
|
||||
|
||||
pub struct TextureCraftApp {
|
||||
pub session: Session,
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds,
|
||||
/// A smooth move to a saved camera in progress.
|
||||
camera_glide: Option<CameraGlide>,
|
||||
/// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`).
|
||||
@@ -337,6 +339,7 @@ impl TextureCraftApp {
|
||||
uv_rotation_snap: None,
|
||||
uv_view_reset: false,
|
||||
session,
|
||||
viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(),
|
||||
ui,
|
||||
ui_store,
|
||||
gpu,
|
||||
|
||||
@@ -323,17 +323,21 @@ mod tests {
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
let from = pointer.at;
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press starts the hold");
|
||||
|
||||
let moved = vec2(-300.0, -20.0);
|
||||
pointer.drags(&mut harness, moved, 30, Modifiers::NONE);
|
||||
let after = RoundGizmo::of(harness.state(), rect).unwrap();
|
||||
|
||||
assert!((after.center - (before.center + moved)).length() < 2.0, "the projector follows the mouse: {:?} -> {:?}", before.center, after.center);
|
||||
assert!(pointer.hidden, "the pointer hides while held");
|
||||
assert!(pointer.at.distance(from) < 1.0, "and stays on the pad, so no screen edge stops the drag: {:?}", pointer.at);
|
||||
|
||||
let slid = projection(&harness, layer);
|
||||
assert_ne!(projector_offset(&slid), [0.0; 3], "the projector itself moved: {slid:?}");
|
||||
assert_eq!(uv_of(&slid), UvTransform::default(), "not only the image inside it");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "letting go ends it");
|
||||
assert!(!pointer.hidden && pointer.at == from, "the pointer shows again where the press began: {:?}", pointer.at);
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step per hold");
|
||||
@@ -342,6 +346,7 @@ mod tests {
|
||||
// The 3D view has its drags back: a drag on the model off the projector's handles moves nothing
|
||||
let off = on_the_model_off_the_handles(&harness);
|
||||
drag(&mut harness, off, off + vec2(60.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_eq!(projection(&harness, layer), slid, "no mode is left on");
|
||||
}
|
||||
|
||||
@@ -353,6 +358,7 @@ mod tests {
|
||||
let steps = harness.state().session.history_labels().len();
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "the hold is under way");
|
||||
|
||||
harness.input_mut().events.push(egui::Event::WindowFocused(false));
|
||||
@@ -363,6 +369,7 @@ mod tests {
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step, as letting go makes");
|
||||
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "the button still down in egui starts no new hold");
|
||||
assert_eq!(projection(&harness, layer), left, "moves after it leave the projection alone");
|
||||
}
|
||||
@@ -377,10 +384,12 @@ mod tests {
|
||||
harness.run_steps(2);
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "{layout:?}: the hold is under way");
|
||||
|
||||
harness.state_mut().run("layer.remove", json!({"layer": layer.0})).unwrap();
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, None, "{layout:?}: the hold ended with its fill");
|
||||
assert!(!pointer.hidden, "{layout:?}: the pointer shows again");
|
||||
}
|
||||
@@ -393,13 +402,19 @@ mod tests {
|
||||
let (mut harness, layer) = fill_app("triplanar");
|
||||
let pad = harness.get_by_label("Move on model").rect();
|
||||
assert!((pad.width() - pad.height()).abs() < 1.0 && pad.width() > 60.0, "Move on model is the preview square, no row of its own: {pad:?}");
|
||||
|
||||
let before = projection(&harness, layer);
|
||||
let mut pointer = SystemPointer::at(&mut harness, pad.left_top() + vec2(4.0, 4.0));
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
|
||||
assert_eq!(harness.state().moving_on_model, Some(MoveOnModel::layer(layer)), "a press at its corner starts the hold");
|
||||
|
||||
pointer.drags(&mut harness, vec2(40.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden, "the pointer is held");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(projection(&harness, layer), before, "the drag moved the projection");
|
||||
assert_eq!(harness.state().moving_on_model, None);
|
||||
}
|
||||
@@ -428,6 +443,7 @@ mod tests {
|
||||
let turned = projection(&harness, layer);
|
||||
assert!(uv_of(&turned).rotation < shifted.rotation, "the right button turns it: {shifted:?} -> {turned:?}");
|
||||
assert_eq!(projector_offset(&turned), projector_offset(&slid), "without sliding");
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Secondary, false, Modifiers::NONE);
|
||||
|
||||
wheel(&mut harness, &mut pointer);
|
||||
@@ -437,10 +453,13 @@ mod tests {
|
||||
assert!(harness.state().properties_popup.is_none(), "the right click opened no Properties popup");
|
||||
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the whole hold is one undo step");
|
||||
|
||||
let back = pointer.at;
|
||||
pointer.moves(&mut harness, over_view - back, Modifiers::NONE);
|
||||
wheel(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(harness.state().session.camera, camera, "let go, the wheel zooms the camera");
|
||||
assert_eq!(uv_of(&projection(&harness, layer)), scaled, "and leaves the projection alone");
|
||||
}
|
||||
@@ -457,13 +476,17 @@ mod tests {
|
||||
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::SHIFT);
|
||||
|
||||
assert_eq!(projection(&harness, layer), turned, "an up and down turn changes nothing");
|
||||
|
||||
pointer.drags(&mut harness, vec2(0.0, -40.0), 10, Modifiers::NONE);
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
assert_ne!(projection(&harness, layer), turned, "the slide moved the frame");
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the hold made its own undo step");
|
||||
|
||||
harness.state_mut().session.undo().unwrap();
|
||||
|
||||
assert_eq!(projection(&harness, layer), turned, "undo takes back the hold only");
|
||||
}
|
||||
|
||||
@@ -476,9 +499,11 @@ mod tests {
|
||||
let mut pointer = press_the_button(&mut harness);
|
||||
let from = pointer.at;
|
||||
wheel(&mut harness, &mut pointer);
|
||||
|
||||
assert_eq!(harness.get_by_label("Move on model").rect().center(), from, "a wheel step over the panel while held scales, it does not scroll the panel");
|
||||
let Projection::Uv { scale, .. } = projection(&harness, layer) else { panic!("still UV") };
|
||||
assert!(scale[0] < 1.0, "the wheel up makes the image bigger: {scale:?}");
|
||||
|
||||
let far = vec2(-3.0 * from.x, 0.0);
|
||||
pointer.drags(&mut harness, far, 60, Modifiers::NONE);
|
||||
let_go(&mut harness, &mut pointer);
|
||||
|
||||
@@ -44,11 +44,14 @@ fn a_put_back_pointer_never_reaches_the_edge_and_comes_back_where_the_press_bega
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden, "let go, the pointer shows again");
|
||||
assert_eq!(pointer.at, PRESS, "where the press began");
|
||||
assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it there too");
|
||||
|
||||
let moved = *harness.state();
|
||||
pointer.moves(&mut harness, vec2(30.0, 0.0), Modifiers::NONE);
|
||||
|
||||
assert_eq!(pointer.at, PRESS + vec2(30.0, 0.0), "a free pointer moves again");
|
||||
assert_eq!(*harness.state(), moved, "and drags nothing");
|
||||
}
|
||||
@@ -61,11 +64,13 @@ fn a_folded_put_back_counts_every_move_from_the_press() {
|
||||
pointer.folds = true;
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer.drags(&mut harness, vec2(1500.0, -40.0), 30, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden && pointer.put_backs >= 30, "hidden, and put back after every move: {pointer:?}");
|
||||
assert!((*harness.state() - vec2(1500.0, -40.0)).length() < 0.01, "every move counts: {:?}", harness.state());
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden && pointer.at == PRESS, "let go, it shows again where the press began: {pointer:?}");
|
||||
}
|
||||
|
||||
@@ -78,6 +83,7 @@ fn a_locked_pointer_reads_raw_motion_and_is_let_go_where_the_press_began() {
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.locked && !pointer.hidden, "let go, the pointer is free and shows");
|
||||
assert_eq!(harness.ctx.input(|input| input.pointer.latest_pos()), Some(PRESS), "egui sees it where the press began");
|
||||
}
|
||||
@@ -88,6 +94,7 @@ fn a_browser_pointer_is_not_held() {
|
||||
let mut pointer = SystemPointer::at(&mut harness, PRESS);
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
pointer.drags(&mut harness, vec2(100.0, 0.0), 10, Modifiers::NONE);
|
||||
|
||||
assert!(!pointer.hidden && pointer.put_backs == 0, "the pointer moves and shows");
|
||||
assert_eq!(*harness.state(), vec2(100.0, 0.0), "the drag reads it as it moves");
|
||||
}
|
||||
@@ -103,9 +110,12 @@ fn a_number_field_scrubs_past_the_edge_with_the_pointer_held() {
|
||||
pointer.button(&mut harness, PointerButton::Primary, true, Modifiers::NONE);
|
||||
let window = harness.ctx.content_rect().width();
|
||||
pointer.drags(&mut harness, vec2(2.0 * window, 0.0), 40, Modifiers::NONE);
|
||||
|
||||
assert!(pointer.hidden && pointer.at.distance(press) < 1.0, "the pointer is hidden and kept on the field: {pointer:?}");
|
||||
|
||||
pointer.button(&mut harness, PointerButton::Primary, false, Modifiers::NONE);
|
||||
pointer.frame(&mut harness);
|
||||
|
||||
assert!(!pointer.hidden && pointer.at == press, "let go, it shows again on the field: {pointer:?}");
|
||||
|
||||
let texturecraft_engine::core::Projection::Triplanar { offset, .. } = crate::frame_gizmo::tests::projection(&harness, layer) else {
|
||||
|
||||
@@ -37,6 +37,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke
|
||||
let length = span.length();
|
||||
let start = DOT_RADIUS + LINE_SPACING;
|
||||
let end = length - RING_RADIUS - LINE_SPACING / 2.0;
|
||||
|
||||
if length.is_finite() && end > start {
|
||||
let toward = span / length;
|
||||
let count = (((end - start) / LINE_SPACING).floor() as usize).min(MAX_LINE_DOTS);
|
||||
@@ -46,6 +47,7 @@ pub(crate) fn preview_dots(painter: &Painter, center: Pos2, position: Pos2, toke
|
||||
painter.circle_filled(at, LINE_DOT, tokens.text);
|
||||
}
|
||||
}
|
||||
|
||||
painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_UNDER, tokens.field));
|
||||
painter.circle_stroke(center, RING_RADIUS, Stroke::new(RING_LINE, tokens.text));
|
||||
painter.circle_filled(position, DOT_RADIUS + DOT_RIM, tokens.field);
|
||||
|
||||
@@ -4,6 +4,8 @@ mod gizmo;
|
||||
mod gizmo_drag;
|
||||
mod shown_gizmo;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{PointerButton, Rect};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::Session;
|
||||
@@ -32,10 +34,10 @@ pub(crate) fn input<G: Gizmo>(app: &mut TextureCraftApp, ctx: &egui::Context, re
|
||||
&& let (Some(gizmo), Some(from)) = (gizmo, ctx.input(|input| input.pointer.press_origin()))
|
||||
&& let Some(grab) = gizmo.grab(from)
|
||||
{
|
||||
drag = Some(GizmoDrag { grab, from, start: gizmo.clone(), edited_revision: None });
|
||||
drag = Some(GizmoDrag { grab, from, start: Arc::new(gizmo.clone()), edited_revision: None });
|
||||
}
|
||||
|
||||
// A window that lost the focus gets no release: the drag ends there. A release still applies a move that came in the same frame
|
||||
// Apply a final move on release and let focus loss end a drag without one
|
||||
let released = response.drag_stopped_by(PointerButton::Primary);
|
||||
let pressed = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary) || released;
|
||||
let Some(mut drag) = drag.filter(|_| pressed && !focus_lost(ctx)) else {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::Pos2;
|
||||
|
||||
use super::Gizmo;
|
||||
@@ -6,9 +8,10 @@ use super::Gizmo;
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct GizmoDrag<G: Gizmo> {
|
||||
pub(crate) grab: G::Grab,
|
||||
/// Where the drag started and the gizmo then
|
||||
/// Where the drag started
|
||||
pub(crate) from: Pos2,
|
||||
pub(crate) start: G,
|
||||
/// The starting gizmo shared by the pointer, edit and overlay paths
|
||||
pub(crate) start: Arc<G>,
|
||||
/// The session revision the drag's last edit left: later updates merge into its undo step while the history is still there
|
||||
pub(crate) edited_revision: Option<u64>,
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use texturecraft_engine::compose::frame_placement::{folded, upright_turn};
|
||||
use texturecraft_engine::compose::pattern::{Coords, decal_axes, image_samples};
|
||||
use texturecraft_engine::compose::projector_cover::projector_cover;
|
||||
use texturecraft_engine::core::{Projection, Projector, ShapeCrop};
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4};
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
@@ -134,6 +134,9 @@ const UNCOVERED: f32 = 0.45;
|
||||
/// How much of the projection reaches a ray past which it counts as covered, for the edge of its reach
|
||||
const HALF_COVERED: f32 = 0.5;
|
||||
|
||||
/// A missed ray has no coverage value in the 0..1 range
|
||||
const MISSED_RAY_COVERAGE: f32 = -1.0;
|
||||
|
||||
/// How far a ray on the edge of the projection's reach is drawn from the accent towards the shape's colour
|
||||
const EDGE_BLEND: f32 = 0.5;
|
||||
|
||||
@@ -378,18 +381,18 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t
|
||||
let supersample = supersample.max(1);
|
||||
let rays = side * supersample;
|
||||
|
||||
// Per ray: the lit colour and how much of the projection lands there (None = the background)
|
||||
let samples: Vec<Option<(Vec3, f32)>> = (0..rays * rays)
|
||||
// Pack lit RGB and coverage into one vector per ray
|
||||
let samples: Vec<Vec4> = (0..rays * rays)
|
||||
.into_par_iter()
|
||||
.map(|ray| {
|
||||
let (x, y) = (ray % rays, ray / rays);
|
||||
let across = ((x as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half;
|
||||
let down = ((y as f32 + 0.5) / rays as f32 * 2.0 - 1.0) * half;
|
||||
let origin = right * across - up * down + eye * CAMERA_DISTANCE;
|
||||
let hit = intersect(shape, origin, forward)?;
|
||||
let Some(hit) = intersect(shape, origin, forward) else { return Vec4::new(0.0, 0.0, 0.0, MISSED_RAY_COVERAGE) };
|
||||
let shade = AMBIENT + (1.0 - AMBIENT) * hit.nrm.dot(light).max(0.0);
|
||||
let (color, cover) = surface(projection, &hit, shades);
|
||||
Some((color * shade, cover))
|
||||
(color * shade).extend(cover)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -400,10 +403,13 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t
|
||||
let mut sum = Vec3::ZERO;
|
||||
for sub in 0..supersample * supersample {
|
||||
let (rx, ry) = (x * supersample + sub % supersample, y * supersample + sub / supersample);
|
||||
let color = match samples.get(ry * rays + rx).copied().flatten() {
|
||||
Some((color, cover)) if on_edge(&samples, rays, rx, ry, cover) => edge.lerp(color, EDGE_BLEND),
|
||||
Some((color, _)) => color,
|
||||
None => background,
|
||||
let sample = samples[ry * rays + rx];
|
||||
let color = if sample.w == MISSED_RAY_COVERAGE {
|
||||
background
|
||||
} else if on_edge(&samples, rays, rx, ry, sample.w) {
|
||||
edge.lerp(sample.truncate(), EDGE_BLEND)
|
||||
} else {
|
||||
sample.truncate()
|
||||
};
|
||||
sum += color;
|
||||
}
|
||||
@@ -413,7 +419,7 @@ fn render(projection: &Projection, side: usize, half: f32, supersample: usize, t
|
||||
}
|
||||
|
||||
/// Where the projection's reach ends on the shape: covered here, not on a neighbouring ray of the shape
|
||||
fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cover: f32) -> bool {
|
||||
fn on_edge(samples: &[Vec4], rays: usize, x: usize, y: usize, cover: f32) -> bool {
|
||||
if cover <= HALF_COVERED {
|
||||
return false;
|
||||
}
|
||||
@@ -421,7 +427,7 @@ fn on_edge(samples: &[Option<(Vec3, f32)>], rays: usize, x: usize, y: usize, cov
|
||||
let neighbours = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)];
|
||||
neighbours
|
||||
.into_iter()
|
||||
.any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).copied().flatten().is_some_and(|(_, cover)| cover <= HALF_COVERED))
|
||||
.any(|(nx, ny)| nx < rays && ny < rays && samples.get(ny * rays + nx).is_some_and(|sample| sample.w != MISSED_RAY_COVERAGE && sample.w <= HALF_COVERED))
|
||||
}
|
||||
|
||||
/// The unlit colour at a hit and how much of the projection reaches it, from the dark and light checker and the uncovered shape `shades` in linear light
|
||||
@@ -651,6 +657,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_view_fits_the_projector_down_to_half_the_shape() {
|
||||
assert_eq!(fitted_half(&sized(0.4)), VIEW_HALF, "a small projector keeps the plain framing");
|
||||
|
||||
let default = fitted_half(&sized(1.0));
|
||||
assert!(default > VIEW_HALF && default < MAX_VIEW_HALF, "{default}");
|
||||
assert_eq!(fitted_half(&sized(3.0)), MAX_VIEW_HALF, "x3 stops at half the shape's size");
|
||||
@@ -662,6 +669,7 @@ mod tests {
|
||||
let screen = Screen { view: View::new(), rect, half: fitted_half(&shown) };
|
||||
passed_sides(outline.points().map(|point| screen.at(point)), rect)
|
||||
};
|
||||
|
||||
assert_eq!(sides(1.0), [false; 4], "a fitted projector stays inside the square");
|
||||
assert_eq!(sides(3.0), [true; 4], "an x3 sphere runs past every side");
|
||||
|
||||
@@ -683,10 +691,12 @@ mod tests {
|
||||
for offset in [[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [1.5, 0.8, 0.0]] {
|
||||
let slid = Projection::Spherical { scale, uv, offset, projector };
|
||||
assert_eq!(fitted_half(&slid), fitted_half(&sized(1.0)), "Offset {offset:?} keeps the view");
|
||||
|
||||
let (resting, half) = resting_fit(&slid, PreviewShape::Sphere);
|
||||
let screen = Screen { view: View::new(), rect, half };
|
||||
let ring = screen.at(resting.unwrap().center);
|
||||
let dot = screen.at(ProjectorOutline::of(&slid, PreviewShape::Sphere.half_size()).unwrap().center);
|
||||
|
||||
assert!(ring.distance(rect.center()) < 1e-3, "the ring marks the middle: {ring:?}");
|
||||
assert_eq!(dot.distance(ring) > 1.0, offset != [0.0; 3], "the filled dot leaves the ring only when slid: {dot:?}");
|
||||
}
|
||||
@@ -709,6 +719,7 @@ mod tests {
|
||||
let outline = ProjectorOutline::of(&sized(1.0), PreviewShape::Sphere.half_size()).unwrap();
|
||||
let hidden = |line: &Vec<Vec3>| line.iter().filter(|point| screen.hidden(PreviewShape::Sphere, **point)).count();
|
||||
assert_eq!(hidden(&outline.lines[0]), 0, "the rim is all seen");
|
||||
|
||||
let equator = hidden(&outline.lines[1]);
|
||||
assert!(equator > 0 && equator < outline.lines[1].len(), "the equator is half hidden: {equator}");
|
||||
}
|
||||
@@ -788,15 +799,21 @@ mod tests {
|
||||
let at = pos2(10.0, 10.0);
|
||||
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
preview_frame(&ctx, &spherical(1.0), Vec::new());
|
||||
|
||||
assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "at rest: in full");
|
||||
|
||||
preview_frame(&ctx, &spherical(1.0), vec![egui::Event::PointerMoved(at), button(true)]);
|
||||
|
||||
assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "a press alone keeps the full picture: nothing changed");
|
||||
|
||||
preview_frame(&ctx, &spherical(2.0), Vec::new());
|
||||
|
||||
assert_eq!(shown_supersample(&ctx), Some(DRAG_SUPERSAMPLE), "a change while held renders lighter");
|
||||
|
||||
let dragged = shown_key(&ctx);
|
||||
|
||||
preview_frame(&ctx, &spherical(2.0), vec![button(false)]);
|
||||
|
||||
assert_eq!(shown_supersample(&ctx), Some(SUPERSAMPLE), "let go: the same picture in full");
|
||||
assert_eq!(shown_key(&ctx), dragged);
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response:
|
||||
&& !gesture_key_held
|
||||
&& !crate::viewport::focus_picking(ui.ctx())
|
||||
&& ui.input(|input| input.modifiers.is_none());
|
||||
|
||||
if !free || !response.clicked_by(PointerButton::Secondary) {
|
||||
return;
|
||||
}
|
||||
@@ -71,8 +72,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| {
|
||||
egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::ZERO).show(ui, |ui| {
|
||||
ui.set_width(PROPERTIES_POPUP_WIDTH);
|
||||
|
||||
// The area's remembered size would otherwise cap the scroll height
|
||||
ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE);
|
||||
|
||||
// A floating bar would cover the sliders' right-aligned values
|
||||
ui.spacing_mut().scroll = egui::style::ScrollStyle::solid();
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ impl PropertySheet<'_> {
|
||||
let response = self.ui.interact(Rect::from_center_size(center, CAPTION_SWITCH_HIT), id, Sense::click());
|
||||
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, on, title));
|
||||
self.pill(center, on, true);
|
||||
self.paint_control_focus(&response);
|
||||
response
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ impl<'u> PropertySheet<'u> {
|
||||
/// Paints the pending i at `glyph_x` in its slot from `slot_left`
|
||||
fn paint_info_in(&mut self, slot_left: f32, glyph_x: f32, center_y: f32) {
|
||||
let Some(tip) = self.info.take() else { return };
|
||||
|
||||
let row_top = center_y - ROW_HEIGHT / 2.0;
|
||||
let slot = Rect::from_min_size(pos2(slot_left, row_top), vec2(INFO_SLOT, ROW_HEIGHT));
|
||||
let id = self.next_id();
|
||||
@@ -69,6 +70,7 @@ impl<'u> PropertySheet<'u> {
|
||||
.inner_margin(TIP_MARGIN)
|
||||
.shadow(TIP_SHADOW);
|
||||
let text_width = anchor.width() - TIP_MARGIN.sum().x;
|
||||
|
||||
let mut tooltip = egui::Tooltip::for_enabled(&response);
|
||||
tooltip.popup = tooltip
|
||||
.popup
|
||||
|
||||
@@ -25,6 +25,7 @@ mod switch_control;
|
||||
mod tooltip;
|
||||
mod track;
|
||||
mod value_text;
|
||||
mod value_text_draft;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -44,6 +45,8 @@ use crate::theme::{Tokens, semibold};
|
||||
use open_card::OpenCard;
|
||||
use sheet_measure::SheetMeasure;
|
||||
|
||||
type SheetMeasures = egui::cache::FramePublisher<Id, SheetMeasure>;
|
||||
|
||||
/// Side padding: every row starts and ends this far inside the panel
|
||||
pub(crate) const PAD: f32 = 12.0;
|
||||
|
||||
@@ -124,7 +127,7 @@ impl<'u> PropertySheet<'u> {
|
||||
/// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen
|
||||
pub(crate) fn show<R>(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R {
|
||||
let id = ui.make_persistent_id(id_salt);
|
||||
let used = ui.data(|data| data.get_temp::<SheetMeasure>(id)).unwrap_or_default();
|
||||
let used = ui.memory_mut(|memory| memory.caches.cache::<SheetMeasures>().get(&id).copied()).unwrap_or_default();
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let mut sheet = PropertySheet {
|
||||
@@ -153,11 +156,13 @@ impl<'u> PropertySheet<'u> {
|
||||
section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top });
|
||||
}
|
||||
|
||||
// Refresh visible sheets so measurements of closed sheets expire
|
||||
let seen = sheet.seen;
|
||||
sheet.ui.memory_mut(|memory| memory.caches.cache::<SheetMeasures>().set(id, seen));
|
||||
if seen != used {
|
||||
sheet.ui.data_mut(|data| data.insert_temp(id, seen));
|
||||
sheet.ui.ctx().request_discard("Properties columns changed");
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ impl PropertySheet<'_> {
|
||||
/// One field: its tag on the left, the value on the right; drag or click to type. Named "`label` `tag`" ("Scale X")
|
||||
fn number_field(&mut self, rect: Rect, label: &str, field: &mut NumberField) -> Option<bool> {
|
||||
let id = self.next_id();
|
||||
let typing_id = id.with("typed");
|
||||
let typing_id = id.with((self.id, "typed"));
|
||||
let tokens = self.tokens;
|
||||
let painter = self.ui.painter().clone();
|
||||
painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside);
|
||||
@@ -112,26 +112,27 @@ impl PropertySheet<'_> {
|
||||
}
|
||||
|
||||
let decimals = field.decimals;
|
||||
if let Some(mut text) = self.ui.data(|data| data.get_temp::<String>(typing_id)) {
|
||||
let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER);
|
||||
let response = self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, edit);
|
||||
if let Some(mut draft) = self.typing_draft(typing_id) {
|
||||
let response =
|
||||
self.typing_edit(rect.left() + 2.0 * TAG_LETTER_INSET + TAG_TO_TYPING, rect.right() - VALUE_INSET, rect.center().y, typing_id, &mut draft);
|
||||
painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside);
|
||||
if !response.lost_focus() {
|
||||
self.ui.data_mut(|data| data.insert_temp(typing_id, text));
|
||||
self.keep_typing(typing_id, draft);
|
||||
return None;
|
||||
}
|
||||
|
||||
let untouched = self.end_typing(typing_id, &text);
|
||||
let untouched = self.end_typing(typing_id, &draft);
|
||||
let text = draft.text.trim();
|
||||
if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile
|
||||
if untouched || text.trim() == shown_number(field.value, decimals) {
|
||||
if untouched || text == shown_number(field.value, decimals) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let typed: f32 = text.trim().trim_end_matches(field.suffix).trim().parse().ok()?;
|
||||
let typed: f32 = text.trim_end_matches(field.suffix).trim().parse().ok()?;
|
||||
if !typed.is_finite() || typed == field.value {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -188,12 +188,12 @@ impl PropertySheet<'_> {
|
||||
pub(super) fn value_text_field(&mut self, id: Id, value_text: ValueText<'_>, value: f32, range: &RangeInclusive<f32>, decimals: usize) -> Option<f32> {
|
||||
let ValueText { label, right, width, center_y, shown, suffix } = value_text;
|
||||
let rect = Rect::from_min_max(pos2(right - width, center_y - ROW_HIT_HALF_HEIGHT), pos2(right, center_y + ROW_HIT_HALF_HEIGHT));
|
||||
let field_id = id.with("typed");
|
||||
let editing = self.ui.data(|data| data.get_temp::<String>(field_id));
|
||||
let field_id = id.with((self.id, "typed"));
|
||||
let editing = self.typing_draft(field_id);
|
||||
let seeded = || shown_number(value, decimals);
|
||||
|
||||
let tokens = self.tokens;
|
||||
let Some(mut typed_text) = editing else {
|
||||
let Some(mut draft) = editing else {
|
||||
self.skip_typing_edit();
|
||||
let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text);
|
||||
response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)])));
|
||||
@@ -209,25 +209,25 @@ impl PropertySheet<'_> {
|
||||
};
|
||||
|
||||
// Typing happens on the value's own line: no box, the line under it goes accent
|
||||
let edit = egui::TextEdit::singleline(&mut typed_text).id(field_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER);
|
||||
let response = self.typing_edit(rect.left(), right, center_y, edit);
|
||||
let response = self.typing_edit(rect.left(), right, center_y, field_id, &mut draft);
|
||||
self.value_line(rect.left(), right, center_y, tokens.accent);
|
||||
if !response.lost_focus() {
|
||||
self.ui.data_mut(|data| data.insert_temp(field_id, typed_text));
|
||||
self.keep_typing(field_id, draft);
|
||||
return None;
|
||||
}
|
||||
|
||||
let untouched = self.end_typing(field_id, &typed_text);
|
||||
let untouched = self.end_typing(field_id, &draft);
|
||||
let typed_text = draft.text.trim();
|
||||
if self.ui.input(|input| input.key_pressed(egui::Key::Escape)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Leaving the field as it opened changes nothing: no undo step, no rounding to the shown decimals, no overwriting a value changed meanwhile
|
||||
if untouched || typed_text.trim() == seeded() {
|
||||
if untouched || typed_text == seeded() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let typed: f32 = typed_text.trim().trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?;
|
||||
let typed: f32 = typed_text.trim_end_matches(suffix).trim_start_matches(['×', 'x']).trim().parse().ok()?;
|
||||
|
||||
// A typed value that lands on the current one (a clamp, "0.750" for 0.75) is no edit either
|
||||
typed.is_finite().then(|| kept_in(typed, range)).filter(|kept| *kept != value)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2};
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2};
|
||||
|
||||
use super::{CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, ROW_PICTURE_AIR, ROW_PICTURE_SIZE, SMALL_TEXT_SIZE, TEXT_SIZE};
|
||||
use crate::theme::semibold;
|
||||
@@ -36,7 +36,21 @@ const TOGGLE_KNOB_TRAVEL: f32 = 4.5;
|
||||
const PAIR_PITCH: f32 = 76.0;
|
||||
const PAIR_NAME_TO_PILL: f32 = 32.0;
|
||||
|
||||
/// Width of a focused control's outline in points
|
||||
const FOCUS_OUTLINE_WIDTH: f32 = 2.0;
|
||||
|
||||
impl PropertySheet<'_> {
|
||||
pub(super) fn paint_control_focus(&self, response: &Response) {
|
||||
if response.has_focus() {
|
||||
self.ui.painter().rect_stroke(
|
||||
response.rect,
|
||||
CornerRadius::same(CONTROL_RADIUS),
|
||||
Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong),
|
||||
StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index
|
||||
pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option<usize> {
|
||||
self.switch_tinted(label, options, selected, &[])
|
||||
@@ -96,6 +110,8 @@ impl PropertySheet<'_> {
|
||||
} else if response.hovered() {
|
||||
painter.rect_filled(rect.shrink(SEGMENT_INSET), CornerRadius::same(CONTROL_RADIUS), tokens.row_hover);
|
||||
}
|
||||
|
||||
self.paint_control_focus(&response);
|
||||
let runs = tints(index);
|
||||
let tint = runs.first().copied().unwrap_or(tokens.text);
|
||||
let (font, color) = if on { (semibold(SMALL_TEXT_SIZE), tint) } else { (FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim) };
|
||||
@@ -150,7 +166,9 @@ impl PropertySheet<'_> {
|
||||
if response.clicked() {
|
||||
*on = !*on;
|
||||
}
|
||||
|
||||
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, label));
|
||||
self.paint_control_focus(&response);
|
||||
response.clicked()
|
||||
}
|
||||
|
||||
@@ -165,14 +183,16 @@ impl PropertySheet<'_> {
|
||||
let hit = Rect::from_min_max(pos2(x, control.top()), pos2(pill.x + PILL_SIZE.x / 2.0, control.bottom()));
|
||||
let id = self.next_id();
|
||||
let response = self.ui.interact(hit, id, Sense::click());
|
||||
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}")));
|
||||
if response.clicked() {
|
||||
*state = !*state;
|
||||
clicked = Some(index);
|
||||
}
|
||||
|
||||
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *state, format!("{label} {name}")));
|
||||
let tokens = self.tokens;
|
||||
self.ui.painter().text(pos2(x, center_y), Align2::LEFT_CENTER, name, font.clone(), if *state { tokens.text } else { tokens.text_dim });
|
||||
self.pill(pill, *state, true);
|
||||
self.paint_control_focus(&response);
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
@@ -177,6 +177,7 @@ fn dropdown_list_hangs_from_its_button_at_its_width_and_picks() {
|
||||
let at = harness.get_by_label("Nearest").rect().center();
|
||||
click_at(&mut harness, at);
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.state().filtering, Filtering::Nearest);
|
||||
}
|
||||
|
||||
@@ -206,6 +207,7 @@ fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() {
|
||||
|
||||
harness.hover_at(reason.center());
|
||||
harness.run_steps(TOOLTIP_WAIT_FRAMES);
|
||||
|
||||
assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
//! Where a slider's value sits and how it reads
|
||||
|
||||
use egui::Id;
|
||||
use egui::text_edit::TextEditState;
|
||||
|
||||
use super::value_text_draft::ValueTextDraft;
|
||||
use crate::theme::semibold;
|
||||
|
||||
type ValueTextDrafts = egui::cache::FramePublisher<Id, Option<ValueTextDraft>>;
|
||||
|
||||
/// A value drawn right-aligned at `right` in a `width` wide box centred on `center_y`, reading `shown`; typing may end in `suffix`; it answers as `label`'s value
|
||||
pub(super) struct ValueText<'a> {
|
||||
pub(super) label: &'a dyn std::fmt::Display,
|
||||
@@ -13,41 +21,52 @@ pub(super) struct ValueText<'a> {
|
||||
/// How far below a value's centre its typing line runs
|
||||
const LINE_DROP: f32 = 9.0;
|
||||
|
||||
/// Where the field `field_id` keeps the text its typing opened with
|
||||
fn opened_id(field_id: egui::Id) -> egui::Id {
|
||||
field_id.with("opened")
|
||||
}
|
||||
|
||||
impl super::PropertySheet<'_> {
|
||||
/// Starts typing `text` into the field `field_id`, all of it selected so the first key replaces it
|
||||
pub(super) fn start_typing(&mut self, field_id: egui::Id, text: String) {
|
||||
let mut state = egui::text_edit::TextEditState::load(self.ui.ctx(), field_id).unwrap_or_default();
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text)));
|
||||
state.store(self.ui.ctx(), field_id);
|
||||
self.ui.data_mut(|data| {
|
||||
data.insert_temp(opened_id(field_id), text.clone());
|
||||
data.insert_temp(field_id, text);
|
||||
});
|
||||
pub(super) fn start_typing(&mut self, field_id: Id, text: String) {
|
||||
let mut editor = TextEditState::default();
|
||||
editor.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text)));
|
||||
self.keep_typing(field_id, ValueTextDraft { original: text.clone(), text, editor });
|
||||
self.ui.memory_mut(|memory| memory.request_focus(field_id));
|
||||
}
|
||||
|
||||
/// Ends typing into the field `field_id`; whether `typed` is still the text it opened with (left so, it changes nothing, even after the value changed meanwhile)
|
||||
pub(super) fn end_typing(&mut self, field_id: egui::Id, typed: &str) -> bool {
|
||||
let opened = self.ui.data_mut(|data| {
|
||||
data.remove::<String>(field_id);
|
||||
data.remove_temp::<String>(opened_id(field_id))
|
||||
});
|
||||
opened.is_some_and(|opened| opened.trim() == typed.trim())
|
||||
pub(super) fn typing_draft(&self, field_id: Id) -> Option<ValueTextDraft> {
|
||||
self.ui.memory_mut(|memory| memory.caches.cache::<ValueTextDrafts>().get(&field_id).cloned().flatten())
|
||||
}
|
||||
|
||||
/// Shows `edit` from `left` to `right` centred on `center_y` (an edit is never shorter than the theme's interact height), so its value sits where the shown value sat; leaves the sheet's rows where they are
|
||||
pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, edit: egui::TextEdit<'_>) -> egui::Response {
|
||||
let line = self.ui.painter().layout_no_wrap("0".to_owned(), crate::theme::semibold(super::TEXT_SIZE), self.tokens.text).size().y;
|
||||
/// Keep the draft only while its field is drawn
|
||||
pub(super) fn keep_typing(&self, field_id: Id, draft: ValueTextDraft) {
|
||||
self.ui.memory_mut(|memory| memory.caches.cache::<ValueTextDrafts>().set(field_id, Some(draft)));
|
||||
}
|
||||
|
||||
/// Ends typing and reports whether the text still matches what the field opened with
|
||||
pub(super) fn end_typing(&self, field_id: Id, draft: &ValueTextDraft) -> bool {
|
||||
self.ui.memory_mut(|memory| memory.caches.cache::<ValueTextDrafts>().set(field_id, None));
|
||||
draft.original.trim() == draft.text.trim()
|
||||
}
|
||||
|
||||
/// Shows an edit in place of the displayed value, without shifting the sheet's rows
|
||||
pub(super) fn typing_edit(&mut self, left: f32, right: f32, center_y: f32, field_id: Id, draft: &mut ValueTextDraft) -> egui::Response {
|
||||
let font = semibold(super::TEXT_SIZE);
|
||||
let line = self.ui.painter().layout_no_wrap("0".to_owned(), font.clone(), self.tokens.text).size().y;
|
||||
let height = line.max(self.ui.spacing().interact_size.y);
|
||||
let rect = egui::Rect::from_min_max(egui::pos2(left, center_y - height / 2.0), egui::pos2(right, center_y + height / 2.0));
|
||||
let layout = egui::Layout::centered_and_justified(egui::Direction::TopDown);
|
||||
let mut child = self.ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(layout));
|
||||
child.add(edit.frame(egui::Frame::NONE).margin(egui::vec2(0.0, 0.0)))
|
||||
|
||||
draft.editor.clone().store(child.ctx(), field_id);
|
||||
let output = egui::TextEdit::singleline(&mut draft.text)
|
||||
.id(field_id)
|
||||
.font(font)
|
||||
.align(egui::Align2::RIGHT_CENTER)
|
||||
.frame(egui::Frame::NONE)
|
||||
.margin(egui::Margin::ZERO)
|
||||
.show(&mut child);
|
||||
|
||||
// Keep selection and undo history with the draft instead of egui's persistent widget data
|
||||
child.data_mut(|data| data.remove::<TextEditState>(field_id));
|
||||
draft.editor = output.state;
|
||||
output.response.response
|
||||
}
|
||||
|
||||
/// Takes the one auto id [`Self::typing_edit`]'s child takes, for a value shown instead of typed: the controls after it keep their ids when typing starts or ends, so a click from one field to the next types into the one clicked
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
use egui::text_edit::TextEditState;
|
||||
|
||||
/// The input, original value, and editor state of a visible Properties field
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ValueTextDraft {
|
||||
pub(super) text: String,
|
||||
pub(super) original: String,
|
||||
pub(super) editor: TextEditState,
|
||||
}
|
||||
@@ -53,6 +53,7 @@ fn environment_cache_retains_source_identity_until_replaced() {
|
||||
|
||||
assert!(original_source.upgrade().is_none(), "replacing the resource releases its decoded pixels immediately");
|
||||
assert_ne!(first_key, gpu_scene_key(&app.session), "a new source restarts tracing under the same environment name");
|
||||
|
||||
let second = super::trace_scene(&app).env;
|
||||
assert!(!Arc::ptr_eq(&first, &second));
|
||||
assert_ne!(first.data, second.data, "replacing the image changes the lighting");
|
||||
@@ -60,6 +61,7 @@ fn environment_cache_retains_source_identity_until_replaced() {
|
||||
|
||||
app.session.images.insert("renamed".into(), replacement);
|
||||
app.session.doc.project.display.environment = "resource:renamed".into();
|
||||
|
||||
assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key");
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ impl RoundGizmo {
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let (lower, upper) = app.session.mesh.bounds();
|
||||
let (lower, upper) = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
let (mesh_center, radius) = mesh_frame((lower, upper));
|
||||
let [x, y, z] = projector.rotation.map(f32::to_radians);
|
||||
let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x);
|
||||
@@ -214,7 +214,7 @@ impl RoundGizmo {
|
||||
let right_of_rim = top.iter().copied().max_by(|first, second| first.x.total_cmp(&second.x));
|
||||
self.outline.extend([top, cap(-half_height)]);
|
||||
|
||||
// The two side lines, where the round side turns away from the camera; seen end on there are none, and the dot sits on the rim's right
|
||||
// End-on views show a rim handle because the two side lines coincide
|
||||
let side = along.cross(facing - along * facing.dot(along)).try_normalize();
|
||||
let mut sides = Vec::new();
|
||||
for edge in side.into_iter().flat_map(|side| [side, -side]) {
|
||||
@@ -273,7 +273,7 @@ impl RoundGizmo {
|
||||
(turn, self.stretch, origin)
|
||||
}
|
||||
RoundGrab::Size(axes) => {
|
||||
// How far the pointer went along the line from the centre through where the handle was grabbed (past the centre, none: a drag never flips it); the command keeps each axis's size in its limits on its own side, so does the offset worked out here
|
||||
// Clamp the drag to the command's size limits so the offset keeps the same center
|
||||
let reach = from - self.center;
|
||||
let factor = ((to - self.center).dot(reach) / reach.length().max(MIN_HANDLE_REACH).powi(2)).max(0.0);
|
||||
let stretch = Vec3::from(axes.map(|on| if on { factor } else { 1.0 })) * self.stretch;
|
||||
@@ -476,6 +476,7 @@ pub(crate) mod tests {
|
||||
let stored = &mut harness.state_mut().session.doc.project.layer_mut(layer).unwrap().kind;
|
||||
let LayerKind::Fill(Fill { projection: Projection::Cylindrical { axis, .. }, .. }) = stored else { panic!("a cylindrical fill") };
|
||||
*axis = 3;
|
||||
|
||||
assert_eq!(gizmo(&harness).outline, round_y);
|
||||
}
|
||||
|
||||
@@ -491,13 +492,16 @@ pub(crate) mod tests {
|
||||
let (projector, offset) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(offset[0] < -0.05 && offset[1].abs() < 1e-3 && offset[2].abs() < 1e-3, "the X arrow moves the centre along X: {offset:?}");
|
||||
assert_eq!(projector.rotation, [0.0; 3]);
|
||||
|
||||
let moved = gizmo(&harness);
|
||||
assert!(moved.center.x > start.center.x + 20.0, "the centre follows: {moved:?}");
|
||||
|
||||
// The Z ring (seen face on) turns it round Z; the centre stays where it is
|
||||
let clear = |p: &&Pos2| moved.rings[..2].iter().flatten().map(|other| other.distance(**p)).fold(f32::INFINITY, f32::min);
|
||||
let on_ring = *moved.rings[2].iter().max_by(|a, b| clear(a).total_cmp(&clear(b))).unwrap();
|
||||
|
||||
assert_eq!(moved.grab(on_ring), Some(RoundGrab::Ring(2)));
|
||||
|
||||
drag(&mut harness, on_ring, moved.center + (on_ring - moved.center).rot90(), Modifiers::NONE);
|
||||
let (turned, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(turned.rotation[2].abs() > 30.0 && turned.rotation[0].abs() < 1e-2, "{:?}", turned.rotation);
|
||||
@@ -507,6 +511,7 @@ pub(crate) mod tests {
|
||||
let dot = scaling.sizes.iter().find(|size| size.axes == [true; 3]).expect("the even-scale dot").at;
|
||||
let center = scaling.center;
|
||||
assert_eq!(gizmo(&harness).grab(dot), Some(RoundGrab::Size([true; 3])));
|
||||
|
||||
drag(&mut harness, dot, center + (dot - center) * 1.5, Modifiers::NONE);
|
||||
let (scaled, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(scaled.scale.iter().all(|scale| (scale - 1.5).abs() < 0.05), "the side dot scales it evenly: {:?}", scaled.scale);
|
||||
@@ -522,9 +527,11 @@ pub(crate) mod tests {
|
||||
let height = cylinder.sizes.iter().find(|size| size.axes == [false, true, false]).expect("the height handle");
|
||||
let SizeHandle { at: top, axes, along } = *height;
|
||||
assert_eq!(axes, [false, true, false], "the top handle works along the axis");
|
||||
|
||||
let along = along.expect("the height handle is a double arrow");
|
||||
assert!(along.y.abs() > 0.99, "drawn upright, along the upright axis: {along:?}");
|
||||
assert_eq!(cylinder.cursor(RoundGrab::Size(axes), false), egui::CursorIcon::ResizeVertical);
|
||||
|
||||
drag(&mut harness, top, cylinder.center + (top - cylinder.center) * 0.5, Modifiers::NONE);
|
||||
let (projector, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(projector.scale[1] < 0.7 && projector.scale[0] == 1.0 && projector.scale[2] == 1.0, "{:?}", projector.scale);
|
||||
@@ -593,6 +600,7 @@ pub(crate) mod tests {
|
||||
let center = gizmo(&harness).center;
|
||||
let to = center + vec2(40.0, 0.0);
|
||||
press_and_move(&mut harness, center, to, Modifiers::NONE);
|
||||
|
||||
assert!(round_dragging(&harness), "the centre square is held");
|
||||
|
||||
harness.event(egui::Event::WindowFocused(false));
|
||||
@@ -605,6 +613,7 @@ pub(crate) mod tests {
|
||||
harness.event(egui::Event::PointerMoved(to + vec2(20.0, 10.0) * step as f32));
|
||||
harness.run_steps(1);
|
||||
}
|
||||
|
||||
assert_eq!(projection(&harness, layer), left, "moves after it leave the projector where it was");
|
||||
}
|
||||
|
||||
@@ -622,6 +631,7 @@ pub(crate) mod tests {
|
||||
|
||||
harness.event_modifiers(egui::Event::PointerMoved(to + vec2(20.0, 0.0)), Modifiers::ALT);
|
||||
harness.run_steps(1);
|
||||
|
||||
assert_ne!(harness.state().session.camera, camera, "Alt turns the camera");
|
||||
assert!(!round_dragging(&harness), "and ends the projector drag");
|
||||
|
||||
@@ -629,9 +639,12 @@ pub(crate) mod tests {
|
||||
harness.event(egui::Event::PointerMoved(to + vec2(20.0, 5.0) * step as f32));
|
||||
harness.run_steps(1);
|
||||
}
|
||||
|
||||
assert_eq!(projection(&harness, layer), slid, "Alt let go, the projector stays where the drag left it");
|
||||
|
||||
harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step");
|
||||
}
|
||||
|
||||
@@ -646,11 +659,13 @@ pub(crate) mod tests {
|
||||
let front = gizmo(&harness);
|
||||
assert!(front.rings[0].is_empty(), "the X ring seen edge on is left out: {:?}", front.rings[0]);
|
||||
assert!(front.rings[1..].iter().all(|ring| !ring.is_empty()), "the Y and Z rings show");
|
||||
|
||||
let on_the_line = front.center + vec2(0.0, 40.0);
|
||||
assert_ne!(front.grab(on_the_line), Some(RoundGrab::Ring(0)), "a press where its line would be does not grab it");
|
||||
|
||||
harness.state_mut().session.camera.yaw = 0.5;
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows");
|
||||
}
|
||||
|
||||
@@ -678,8 +693,10 @@ pub(crate) mod tests {
|
||||
let (mut harness, layer) = fill_app("spherical");
|
||||
let start = gizmo(&harness);
|
||||
assert_eq!(start.sizes.len(), 1, "one dot: {:?}", start.sizes);
|
||||
|
||||
let dot = start.sizes[0].at;
|
||||
assert_eq!(start.grab(dot), Some(RoundGrab::Size([true; 3])));
|
||||
|
||||
drag(&mut harness, dot, start.center + (dot - start.center) * 1.4, Modifiers::NONE);
|
||||
let (scaled, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(scaled.scale.iter().all(|scale| (scale - 1.4).abs() < 0.08), "it scales evenly: {:?}", scaled.scale);
|
||||
@@ -700,6 +717,7 @@ pub(crate) mod tests {
|
||||
Some(RoundGrab::Size([true, false, false])),
|
||||
"grabbed from its tip"
|
||||
);
|
||||
|
||||
drag(&mut harness, across.at, box_gizmo.center + (across.at - box_gizmo.center) * 0.5, Modifiers::NONE);
|
||||
let (stretched, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!((stretched.scale[0] - scaled.scale[0] * 0.5).abs() < 0.05, "the X face halves it across: {:?}", stretched.scale);
|
||||
@@ -727,6 +745,7 @@ pub(crate) mod tests {
|
||||
|
||||
let start = gizmo(&harness);
|
||||
assert_eq!(start.stretch, Vec3::from(mirrored), "the gizmo reads the mirror as the projection does");
|
||||
|
||||
drag(&mut harness, start.center, start.center + vec2(30.0, -20.0), Modifiers::NONE);
|
||||
let (slid, offset) = projector_and_offset(&projection(&harness, layer));
|
||||
assert_eq!(slid.scale, mirrored, "a slide keeps the mirror");
|
||||
@@ -735,6 +754,7 @@ pub(crate) mod tests {
|
||||
let tip = gizmo(&harness).arrows[1].unwrap();
|
||||
let center = gizmo(&harness).center;
|
||||
drag(&mut harness, tip, tip + (tip - center).normalized() * 20.0, Modifiers::NONE);
|
||||
|
||||
assert_eq!(projector_and_offset(&projection(&harness, layer)).0.scale, mirrored, "so does a move along an arrow");
|
||||
|
||||
let before_turn = projector_and_offset(&projection(&harness, layer)).0;
|
||||
@@ -782,12 +802,15 @@ pub(crate) mod tests {
|
||||
let center = gizmo(&harness).center;
|
||||
harness.hover_at(center);
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "the centre square shows it slides");
|
||||
|
||||
harness.event(egui::Event::ModifiersChanged(Modifiers::ALT));
|
||||
harness.event(egui::Event::PointerMoved(center + vec2(1.0, 0.0)));
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Grab, "with Alt held it does not");
|
||||
|
||||
harness.event(egui::Event::ModifiersChanged(Modifiers::NONE));
|
||||
harness.run_steps(2);
|
||||
}
|
||||
@@ -816,6 +839,7 @@ pub(crate) mod tests {
|
||||
drag(&mut harness, center, center + vec2(-40.0, 0.0), Modifiers::COMMAND);
|
||||
harness.event(egui::Event::ModifiersChanged(Modifiers::NONE));
|
||||
harness.run_steps(2);
|
||||
|
||||
assert_ne!(harness.state().session.tool.brush.flow, flow, "the drag changes the brush");
|
||||
assert_eq!(projection(&harness, layer), before, "and leaves the projection");
|
||||
}
|
||||
@@ -859,10 +883,12 @@ pub(crate) mod tests {
|
||||
|
||||
let painted = harness.state().session.quick_mask.revision;
|
||||
click(&mut harness, edge, off);
|
||||
|
||||
assert_eq!(harness.state().session.quick_mask.revision, painted, "a press that began on the handle paints no dab");
|
||||
|
||||
// The same click a little past the handle paints
|
||||
click(&mut harness, off, off + (off - edge));
|
||||
|
||||
assert_ne!(harness.state().session.quick_mask.revision, painted, "a press off the handle paints");
|
||||
}
|
||||
|
||||
@@ -879,6 +905,7 @@ pub(crate) mod tests {
|
||||
let across = [true, true, false];
|
||||
let dot = end_on.sizes.iter().find(|size| size.axes == across).unwrap_or_else(|| panic!("the across dot: {:?}", end_on.sizes)).at;
|
||||
assert_eq!(end_on.grab(dot), Some(RoundGrab::Size(across)));
|
||||
|
||||
drag(&mut harness, dot, end_on.center + (dot - end_on.center) * 1.5, Modifiers::NONE);
|
||||
let (projector, _) = projector_and_offset(&projection(&harness, layer));
|
||||
assert!(projector.scale[0] > 1.2 && projector.scale[1] > 1.2 && projector.scale[2] == 1.0, "it scales across only: {:?}", projector.scale);
|
||||
|
||||
@@ -67,7 +67,7 @@ pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec<O
|
||||
|
||||
let symmetry = app.session.tool.brush.symmetry;
|
||||
let display = app.ui.symmetry;
|
||||
let (lo, hi) = app.session.mesh.bounds();
|
||||
let (lo, hi) = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
let origin = symmetry.origin((lo + hi) * 0.5);
|
||||
let ribbon = Ribbons::new(app, rect);
|
||||
let mut quads = Vec::new();
|
||||
@@ -123,10 +123,10 @@ pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, cursor: Option
|
||||
|
||||
let symmetry = app.session.tool.brush.symmetry;
|
||||
let display = app.ui.symmetry;
|
||||
let (lo, hi) = app.session.mesh.bounds();
|
||||
let (lo, hi) = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
let origin = symmetry.origin((lo + hi) * 0.5);
|
||||
|
||||
// Bounds scan the mesh's vertices; every cursor copy shares these measurements
|
||||
// Every cursor copy uses the same scale and visibility tolerance
|
||||
let diagonal = (hi - lo).length();
|
||||
let tolerance = diagonal * VISIBILITY_TOLERANCE;
|
||||
let brush_radius = app.session.tool.brush.size * diagonal;
|
||||
@@ -292,7 +292,7 @@ pub(crate) fn manipulator_input(app: &mut TextureCraftApp, ui: &Ui, response: &R
|
||||
};
|
||||
|
||||
if let Some(pointer) = response.interact_pointer_pos() {
|
||||
let (lo, hi) = app.session.mesh.bounds();
|
||||
let (lo, hi) = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
let half_extent = (hi - lo) * 0.5;
|
||||
let moved = Vec3::from(drag.start_offset) + manipulator.world_delta(drag.axes, pointer - drag.from);
|
||||
let offset = moved.clamp(-half_extent, half_extent).to_array();
|
||||
|
||||
@@ -335,8 +335,7 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
|
||||
let t = Tokens::for_brightness(b).with_accent(accent);
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::NULL, t));
|
||||
ctx.all_styles_mut(|s| {
|
||||
// VectorCraft's type scale: 11 small print, 13 body and controls, 15 headings (semibold),
|
||||
// 11.5 values in the monospace face.
|
||||
// Match VectorCraft's type scale for print, body, headings and monospace values
|
||||
s.text_styles = [
|
||||
(TextStyle::Small, FontId::new(11.0, FontFamily::Proportional)),
|
||||
(TextStyle::Body, FontId::new(13.0, FontFamily::Proportional)),
|
||||
@@ -345,7 +344,7 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
|
||||
(TextStyle::Monospace, FontId::new(11.5, FontFamily::Monospace)),
|
||||
]
|
||||
.into();
|
||||
// A 2-4-6-8-12 spacing scale: 6 between items, 4 between rows, controls 24 high.
|
||||
// A 2-4-6-8-12 spacing scale: 6 between items, 4 between rows, controls 24 high
|
||||
s.spacing.item_spacing = egui::vec2(6.0, 4.0);
|
||||
s.spacing.button_padding = egui::vec2(8.0, 3.0);
|
||||
s.spacing.interact_size = egui::vec2(24.0, 24.0);
|
||||
@@ -366,18 +365,18 @@ pub fn apply(ctx: &egui::Context, b: Brightness, accent: Accent) {
|
||||
v.popup_shadow = egui::epaint::Shadow { offset: [0, 4], blur: 14, spread: 0, color: Color32::from_black_alpha(if t.dark { 120 } else { 60 }) };
|
||||
v.window_shadow = egui::epaint::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(if t.dark { 140 } else { 70 }) };
|
||||
v.selection.bg_fill = t.accent_dim;
|
||||
// Selected options and selected text are lettered in the strong colour: the accent on its
|
||||
// own tint is hard to read.
|
||||
|
||||
// Strong text stays legible on the tinted selection background
|
||||
v.selection.stroke = Stroke::new(1.0, t.text_strong);
|
||||
v.hyperlink_color = t.accent;
|
||||
let w = &mut v.widgets;
|
||||
craft_ui::theme::WidgetPalette { noninteractive: t.panel, inactive: t.button, hovered: t.row_hover, active: t.tool_active, open: t.row_hover }
|
||||
.apply_to(w, t.cr(), Stroke::new(1.0, t.text));
|
||||
// Hovered and pressed lettering, and `RichText::strong` (captions), in the strong colour.
|
||||
// Hovered and pressed lettering, and `RichText::strong` (captions), in the strong colour
|
||||
w.hovered.fg_stroke.color = t.text_strong;
|
||||
w.active.fg_stroke.color = t.text_strong;
|
||||
w.noninteractive.bg_stroke = Stroke::new(1.0, t.separator);
|
||||
// Flat buttons: the outline is the face's own colour, so only text fields show it.
|
||||
// Flat buttons: the outline is the face's own colour, so only text fields show it
|
||||
w.inactive.bg_stroke = Stroke::new(1.0, t.button);
|
||||
w.hovered.bg_stroke = Stroke::new(1.0, t.field_border);
|
||||
w.active.bg_stroke = Stroke::new(1.0, t.accent);
|
||||
@@ -454,11 +453,12 @@ mod tests {
|
||||
assert!(contrast(t.accent, t.panel) >= 2.5, "{b:?} {a:?}: accent on panel");
|
||||
assert!(contrast(Color32::WHITE, t.accent_strong) >= 2.5, "{b:?} {a:?}: white on accent button");
|
||||
assert!(contrast(t.viewport_text, t.viewport) >= 3.0, "{b:?}: lettering on the views");
|
||||
// Slider rails show on the card.
|
||||
// Slider rails show on the card
|
||||
assert!(contrast(t.button_border, t.panel) >= 1.6, "{b:?}: rail on panel");
|
||||
}
|
||||
}
|
||||
// The views keep their studio slate.
|
||||
|
||||
// The views keep their studio slate
|
||||
assert_eq!(Tokens::for_brightness(Brightness::Light).viewport, Tokens::for_brightness(Brightness::Dark).viewport);
|
||||
}
|
||||
}
|
||||
@@ -895,7 +895,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let gizmo = ShownGizmo::of(app, rect);
|
||||
let frame_drag = gizmo_free && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref());
|
||||
|
||||
// Alt (or another mode) taking the pointer mid-drag ends the drag: let go of Alt, it must not resume from where it began before the camera moved
|
||||
// End the gizmo drag when navigation takes over because the camera may have moved
|
||||
if !gizmo_free {
|
||||
ShownGizmo::let_go(ui.ctx());
|
||||
}
|
||||
@@ -1031,7 +1031,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
&& let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport)
|
||||
{
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
|
||||
let (bounds_min, bounds_max) = app.session.mesh.bounds();
|
||||
let (bounds_min, bounds_max) = app.viewport_mesh_bounds.get(&app.session.mesh);
|
||||
let radius = app.session.tool.brush.size * (bounds_max - bounds_min).length();
|
||||
brush_cursor(app, ui, rect, hit.pos, hit.nrm, radius);
|
||||
symmetry_cursor = Some((hit.pos, hit.nrm));
|
||||
@@ -2542,7 +2542,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unavailable_tools_finish_strokes_and_box_fills() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives};
|
||||
|
||||
@@ -2580,17 +2580,22 @@ mod tests {
|
||||
let app = harness.state_mut();
|
||||
app.ui.mode = crate::state::Mode::Painting;
|
||||
app.session.view = ViewMode::Mask(LayerId(7));
|
||||
|
||||
assert_eq!(mask_view_layer(app), Some(LayerId(7)));
|
||||
|
||||
app.session.quick_mask.editing = true;
|
||||
|
||||
assert!(quick_mask_shown(app));
|
||||
assert_eq!(mask_view_layer(app), None, "the quick mask is on screen, not the layer mask");
|
||||
|
||||
app.session.quick_mask.editing = false;
|
||||
|
||||
assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_surfaces_release_after_a_frame_without_paths() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::{core::EffectKind, execute, geom::primitives};
|
||||
|
||||
@@ -2678,7 +2683,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::{StackTarget, execute};
|
||||
|
||||
@@ -2703,6 +2708,7 @@ mod tests {
|
||||
drag_decal_handle(&mut harness, original.center, original.center + vec2(40.0, 0.0));
|
||||
|
||||
let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind;
|
||||
|
||||
assert!(
|
||||
matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Planar { placed: Some(decal), .. }, .. } if *decal == original.decal)
|
||||
);
|
||||
@@ -2711,7 +2717,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::execute;
|
||||
|
||||
@@ -2726,18 +2732,21 @@ mod tests {
|
||||
|
||||
assert_eq!(session.ts(), 1);
|
||||
assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap());
|
||||
|
||||
let inherited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap();
|
||||
|
||||
assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal));
|
||||
|
||||
drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5);
|
||||
|
||||
let edited = crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).unwrap();
|
||||
|
||||
assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::execute;
|
||||
|
||||
@@ -2757,7 +2766,7 @@ mod tests {
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"]
|
||||
fn decal_frame_selection_snapshots() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
use texturecraft_engine::execute;
|
||||
|
||||
@@ -2769,25 +2778,31 @@ mod tests {
|
||||
let effect = original.effect.unwrap();
|
||||
let session = &mut harness.state_mut().session;
|
||||
let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone();
|
||||
|
||||
assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err());
|
||||
|
||||
harness.run_steps(6);
|
||||
|
||||
assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_some());
|
||||
|
||||
harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap();
|
||||
|
||||
let session = &mut harness.state_mut().session;
|
||||
let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone();
|
||||
execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap();
|
||||
|
||||
assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err());
|
||||
|
||||
harness.run_steps(6);
|
||||
|
||||
assert!(crate::frame_gizmo::FrameGizmo::of(harness.state(), harness.state().viewport_rect).is_none());
|
||||
|
||||
harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() {
|
||||
// The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw
|
||||
// Hold the language lock while drawing the harness
|
||||
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use texturecraft_engine::geom::{Mesh, glam::Vec3};
|
||||
|
||||
/// Axis-aligned bounds shared by projection controls for the current mesh
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ViewportMeshBounds {
|
||||
mesh: RefCell<Weak<Mesh>>,
|
||||
bounds: std::cell::Cell<(Vec3, Vec3)>,
|
||||
}
|
||||
|
||||
impl ViewportMeshBounds {
|
||||
pub(crate) fn get(&self, mesh: &Arc<Mesh>) -> (Vec3, Vec3) {
|
||||
let mut previous = self.mesh.borrow_mut();
|
||||
if previous.as_ptr() != Arc::as_ptr(mesh) {
|
||||
self.bounds.set(mesh.bounds());
|
||||
*previous = Arc::downgrade(mesh);
|
||||
}
|
||||
|
||||
self.bounds.get()
|
||||
}
|
||||
}
|
||||
@@ -449,7 +449,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut srgb = [c.r(), c.g(), c.b()];
|
||||
let hsv_of = |srgb: [u8; 3]| hsv_from_rgb(srgb.map(|v| v as f32 / 255.0));
|
||||
// Remembered with the color it was for, so hue and saturation survive black, white and grays.
|
||||
// Remembered with the color it was for, so hue and saturation survive black, white and grays
|
||||
let (mut h, mut s, mut v) = ui.data(|d| d.get_temp::<(Color32, (f32, f32, f32))>(id)).filter(|(k, _)| k == c).map_or_else(|| hsv_of(srgb), |(_, hsv)| hsv);
|
||||
let mut typed = false;
|
||||
let mut dragged = false;
|
||||
@@ -465,7 +465,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool
|
||||
(h, s, v) = hsv_of(srgb);
|
||||
}
|
||||
let border = Stroke::new(1.0, tk.field_border);
|
||||
// Saturation across, value up.
|
||||
// Saturation across, value up
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, width), Sense::click_and_drag());
|
||||
if let Some(p) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.clicked()) {
|
||||
(s, v) = (((p.x - rect.left()) / rect.width()).clamp(0.0, 1.0), 1.0 - ((p.y - rect.top()) / rect.height()).clamp(0.0, 1.0));
|
||||
@@ -500,7 +500,12 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) ->
|
||||
/// Cells across and down: fine enough that a hue strip's six ramps read smooth
|
||||
const GRID_CELLS: u32 = 24;
|
||||
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let side_vertices = GRID_CELLS as usize + 1;
|
||||
let cell_count = (GRID_CELLS * GRID_CELLS) as usize;
|
||||
// Each grid cell contributes two triangles
|
||||
let mut mesh =
|
||||
egui::Mesh { vertices: Vec::with_capacity(side_vertices * side_vertices), indices: Vec::with_capacity(cell_count * 6), ..Default::default() };
|
||||
|
||||
for j in 0..=GRID_CELLS {
|
||||
for i in 0..=GRID_CELLS {
|
||||
let (x, y) = (i as f32 / GRID_CELLS as f32, j as f32 / GRID_CELLS as f32);
|
||||
@@ -508,6 +513,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) ->
|
||||
mesh.colored_vertex(rect.lerp_inside(vec2(x, y)), Color32::from_rgb(r, g, b));
|
||||
}
|
||||
}
|
||||
|
||||
for j in 0..GRID_CELLS {
|
||||
for i in 0..GRID_CELLS {
|
||||
let top_left = j * (GRID_CELLS + 1) + i;
|
||||
@@ -516,6 +522,7 @@ fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) ->
|
||||
mesh.add_triangle(top_left + 1, bottom_left + 1, bottom_left);
|
||||
}
|
||||
}
|
||||
|
||||
painter.add(mesh);
|
||||
}
|
||||
|
||||
|
||||
@@ -145,13 +145,17 @@ fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() {
|
||||
// The outline stays anchored while the pointer is hidden inside the view
|
||||
harness.hover_at(center + egui::vec2(10.0, 0.0));
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view");
|
||||
assert_eq!(cursor(&harness), CursorIcon::None);
|
||||
|
||||
// Outside the view, the outline stays anchored and the system pointer returns
|
||||
harness.hover_at(egui::pos2(2.0, 2.0));
|
||||
harness.run_steps(3);
|
||||
|
||||
assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view");
|
||||
assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible");
|
||||
|
||||
harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl });
|
||||
harness.event(Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
harness.run_steps(2);
|
||||
|
||||
@@ -34,6 +34,7 @@ fn each_projection_shows_its_own_rows() {
|
||||
for label in ["Depth culling", "Backface culling", "Angle", "Extends Outside Shape", "Offset X", "Rotation Y", "Scale Z"] {
|
||||
assert!(shows(&harness, label), "planar: {label}");
|
||||
}
|
||||
|
||||
assert!(!shows(&harness, "Reset frame"), "planar has no frame to reset");
|
||||
|
||||
let (harness, _) = app_with_fill("warp");
|
||||
@@ -42,12 +43,14 @@ fn each_projection_shows_its_own_rows() {
|
||||
for label in ["Depth", "Reset frame", "Depth culling", "Offset X", "Rotation X", "Scale X"] {
|
||||
assert!(shows(&harness, label), "warp: {label}");
|
||||
}
|
||||
|
||||
assert!(!shows(&harness, "Backface culling"), "a warp has no backface culling");
|
||||
|
||||
let (harness, _) = app_with_fill("cylindrical");
|
||||
for label in ["Angle", "Backface culling", "Extends Outside Shape", "Offset X"] {
|
||||
assert!(shows(&harness, label), "cylindrical: {label}");
|
||||
}
|
||||
|
||||
assert!(!shows(&harness, "Depth culling"));
|
||||
|
||||
let (harness, _) = app_with_fill("triplanar");
|
||||
@@ -111,6 +114,7 @@ fn the_culling_rows_i_explains_the_row_on_hover_without_covering_its_values() {
|
||||
let before = projection(&harness, layer);
|
||||
let info = harness.get_by_label(DEPTH_CULLING_TIP).rect().center();
|
||||
click_at(&mut harness, info);
|
||||
|
||||
assert_eq!(projection(&harness, layer), before);
|
||||
}
|
||||
|
||||
@@ -173,7 +177,9 @@ fn reset_frame_puts_a_warps_corners_back() {
|
||||
fn the_3d_projection_settings_fold_away() {
|
||||
let (mut harness, _) = app_with_fill("spherical");
|
||||
assert!(harness.query_by_label("Scale X").is_some(), "the band starts open");
|
||||
|
||||
click_label(&mut harness, "3D projection settings");
|
||||
|
||||
assert!(harness.query_by_label("Scale X").is_none());
|
||||
assert!(harness.query_by_label("Spherical projection").is_some(), "the rows above it stay");
|
||||
}
|
||||
@@ -205,10 +211,13 @@ fn the_fill_caption_resets_the_whole_fill_section_to_its_projections_defaults_in
|
||||
);
|
||||
assert_eq!(after.sampling, Sampling { symmetry: changed.sampling.symmetry, ..Sampling::default() }, "the symmetry stays");
|
||||
assert!(harness.get_by_label("Fill: Reset to defaults").accesskit_node().is_disabled(), "at the defaults it is faint and inert");
|
||||
|
||||
click_at(&mut harness, reset);
|
||||
|
||||
assert_eq!(fill(&harness, layer), after, "a click at the defaults changes nothing");
|
||||
|
||||
harness.state_mut().run("edit.undo", json!({}));
|
||||
|
||||
assert_eq!(fill(&harness, layer), after_band, "one undo step brings the whole section back");
|
||||
}
|
||||
|
||||
|
||||
@@ -48,24 +48,32 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() {
|
||||
assert!(harness.query_by_label("Mirror symmetry").is_none(), "off, the section is the caption alone");
|
||||
|
||||
click_node(&mut harness, Role::CheckBox, "Symmetry");
|
||||
|
||||
assert!(symmetry(&harness, layer).on);
|
||||
assert!(harness.query_by_label("Axis position X").is_some(), "a mirror across X moves along X");
|
||||
assert!(harness.query_by_label("Count").is_none(), "a mirror has no radial rows");
|
||||
|
||||
click_node(&mut harness, Role::RadioButton, "Y");
|
||||
|
||||
assert_eq!(symmetry(&harness, layer).axis, 1);
|
||||
|
||||
click_node(&mut harness, Role::CheckBox, "Flip copy U");
|
||||
|
||||
assert_eq!(symmetry(&harness, layer).flip, [true, false]);
|
||||
|
||||
click_node(&mut harness, Role::ComboBox, "Mirror symmetry");
|
||||
click_node(&mut harness, Role::ListBoxOption, "Radial symmetry");
|
||||
|
||||
assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial);
|
||||
|
||||
for label in ["Count", "Angle span", "Axis position X", "Axis position Z"] {
|
||||
assert!(harness.query_by_label(label).is_some(), "radial round Y: {label}");
|
||||
}
|
||||
|
||||
assert!(harness.query_by_label("Axis position Y").is_none(), "the turning axis does not move along itself");
|
||||
|
||||
click_node(&mut harness, Role::CheckBox, "Symmetry");
|
||||
|
||||
assert!(!symmetry(&harness, layer).on);
|
||||
assert_eq!(symmetry(&harness, layer).kind, SymmetryKind::Radial, "switched off, the settings stay");
|
||||
}
|
||||
@@ -74,7 +82,9 @@ fn the_symmetry_switch_shows_its_rows_and_each_row_changes_the_symmetry() {
|
||||
fn a_uv_fill_says_why_in_place_of_the_symmetry_switch() {
|
||||
let (mut harness, layer) = app_with_fill("uv");
|
||||
assert!(harness.query_by_role_and_label(Role::CheckBox, "Symmetry").is_none(), "no switch to click");
|
||||
|
||||
click_label(&mut harness, "Not available with UV projection");
|
||||
|
||||
assert!(!symmetry(&harness, layer).on, "a UV projection has no symmetry to switch on");
|
||||
assert!(harness.query_by_label("Type").is_none(), "its settings stay hidden, not greyed");
|
||||
}
|
||||
@@ -87,11 +97,13 @@ fn a_count_click_that_keeps_the_count_adds_no_undo_step_and_a_drag_to_the_next_a
|
||||
|
||||
let inside = count_at(&harness, 6.2);
|
||||
click_at(&mut harness, inside);
|
||||
|
||||
assert_eq!(symmetry(&harness, layer).count, 6);
|
||||
assert_eq!(undo_depth(&harness), steps, "a count that stays six is no edit");
|
||||
|
||||
let (from, to) = (count_at(&harness, 6.0), count_at(&harness, 7.3));
|
||||
drag(&mut harness, from, to);
|
||||
|
||||
assert_eq!(symmetry(&harness, layer).count, 7);
|
||||
assert_eq!(undo_depth(&harness), steps + 1, "the drag's frames merge into one step");
|
||||
}
|
||||
|
||||
@@ -59,10 +59,12 @@ fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() {
|
||||
let center = clicked.state().viewport_rect.center();
|
||||
let before = history(&clicked).len();
|
||||
click(&mut clicked, center);
|
||||
|
||||
assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle");
|
||||
|
||||
let mut boxed = polygon_fill_app();
|
||||
drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0));
|
||||
|
||||
assert_eq!(history(&boxed).len(), before + 1);
|
||||
assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill"));
|
||||
assert!(
|
||||
@@ -81,6 +83,7 @@ fn a_box_drag_in_the_2d_view_is_one_fill() {
|
||||
let before = history(&harness).len();
|
||||
|
||||
drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0));
|
||||
|
||||
assert_eq!(history(&harness).len(), before + 1);
|
||||
assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill"));
|
||||
}
|
||||
@@ -100,10 +103,12 @@ fn a_new_press_after_release_does_not_resume_the_previous_box() {
|
||||
.events
|
||||
.extend([Event::PointerMoved(point), Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
|
||||
harness.run_steps(1);
|
||||
|
||||
assert_eq!(painted_tiles(&harness), tiles_after_drag, "a press alone must not refill the old rectangle");
|
||||
|
||||
harness.event(Event::PointerButton { pos: point, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.run_steps(1);
|
||||
|
||||
assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step");
|
||||
}
|
||||
|
||||
@@ -115,11 +120,13 @@ fn the_symmetry_toggle_is_offered_for_polygon_fill_and_a_symmetric_click_is_one_
|
||||
harness.get_by_label("Symmetry settings");
|
||||
harness.get_by_label("Symmetry").click();
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(harness.state().session.tool.brush.symmetry.any(), "the toggle turns mirroring on for the fill");
|
||||
|
||||
let center = harness.state().viewport_rect.center();
|
||||
let before = history(&harness).len();
|
||||
click(&mut harness, center);
|
||||
|
||||
assert_eq!(history(&harness).len(), before + 1, "the fill and its mirror copies are one undo step");
|
||||
assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill"));
|
||||
}
|
||||
|
||||
@@ -188,7 +188,9 @@ fn the_window_follows_the_reference_layout() {
|
||||
for labels in order.windows(2) {
|
||||
assert!(top(labels[0]) < top(labels[1]), "{} comes before {}", labels[0], labels[1]);
|
||||
}
|
||||
|
||||
assert!(h.query_by_label("Custom unit scale").is_none(), "Physical size starts collapsed");
|
||||
|
||||
let disabled = |role: Role, label: &str| h.get_by_role_and_label(role, label).accesskit_node().is_disabled();
|
||||
for (role, label) in [
|
||||
(Role::CheckBox, "Compute tangent space per fragment"),
|
||||
@@ -205,6 +207,7 @@ fn the_window_follows_the_reference_layout() {
|
||||
let center = h.get_by_role_and_label(Role::CheckBox, "Compute tangent space per fragment").rect().center();
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
|
||||
assert!(h.query_by_label("Not available yet").is_some(), "the hint of a setting TextureCraft does not have yet");
|
||||
}
|
||||
|
||||
|
||||
@@ -171,9 +171,13 @@ fn it_shows_what_the_properties_panel_shows() {
|
||||
let mut harness = harness();
|
||||
let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap();
|
||||
let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill}));
|
||||
|
||||
assert!(selected.is_ok(), "{selected:?}");
|
||||
|
||||
let projected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.projection", &json!({"layer": fill, "projection": "uv"}));
|
||||
|
||||
assert!(projected.is_ok(), "{projected:?}");
|
||||
|
||||
harness.run_steps(3);
|
||||
|
||||
let center = view_center(&harness);
|
||||
@@ -227,6 +231,7 @@ fn bake_and_render_modes_never_open_it() {
|
||||
harness.state_mut().ui.mode = mode;
|
||||
harness.run_steps(3);
|
||||
click(&mut harness, PointerButton::Secondary, center);
|
||||
|
||||
assert_eq!(harness.state().properties_popup, None, "{mode:?}");
|
||||
}
|
||||
}
|
||||
@@ -258,7 +258,9 @@ fn the_click_that_closes_the_drop_menu_paints_nothing_and_adds_no_undo_step() {
|
||||
let image = import_white_image(&mut harness);
|
||||
drop_asset(&mut harness, Asset::Texture(image), position);
|
||||
harness.run_steps(2);
|
||||
|
||||
assert!(menu_open(&harness, position));
|
||||
|
||||
let history = harness.state().session.history_labels().len();
|
||||
|
||||
// A point on the same set, away from the menu
|
||||
|
||||
@@ -829,6 +829,7 @@ fn mask_fill_image_snapshot() {
|
||||
let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") };
|
||||
assert_eq!(*source, Source::image(name));
|
||||
assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable");
|
||||
|
||||
save(&mut harness, &output_dir, "mask-fill-image-selected");
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user