From 7bd6c0ef2bdd327f58e027677c4dad3965c4a96d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:09:31 +0000 Subject: [PATCH 01/22] Generators: global adjustments, output resolution and image inputs - Global blur, balance and contrast on every generator (GeneratorGlobal). The blur blurs only the generator's own value, up to a 64-texel radius at 2K, weighted by mesh coverage; balance picks the input range that is stretched to 0..1 and contrast narrows it; invert stays last. - Output resolution (OutputResolution, ResolutionMode): Auto or UV tile, Texture set or a custom size, times a factor from 1/8 to x8, never coarser than one value per 64 texels. Below the UV tile's resolution the generator is averaged over cells and read back bilinearly. - Image inputs: each mesh map a generator reads can read an image, a uniform value or an anchor point instead. Generator inputs count as anchor and image readers (compositing order, paste, remove unused). - Blur and resolution run as a neighbourhood stage of the mask, listed the same way by every caller and only in masks. - Commands: blur, balance, contrast, resolution, customResolution, resolutionFactor on effect.add.generator / effect.set, and input with inputImage / inputValue / inputAnchor / inputBaked on effect.set. New fields are skipped when they hold their defaults and neutral settings return the value untouched, so saved projects load, save and render as before. --- crates/compose/src/eval.rs | 478 ++++++++++++++++----- crates/core/src/layer.rs | 102 ++++- crates/core/src/layer/generator_global.rs | 96 +++++ crates/core/src/layer/output_resolution.rs | 110 +++++ crates/core/src/layer/resolution_mode.rs | 32 ++ crates/core/src/lib.rs | 6 +- crates/engine/src/effect_clipboard.rs | 99 +++-- crates/engine/src/inspect.rs | 11 +- crates/engine/src/mask_cmds.rs | 80 +++- crates/engine/src/material_lib.rs | 27 +- crates/engine/tests/it/generator_inputs.rs | 77 ++++ crates/engine/tests/it/main.rs | 1 + crates/engine/tests/session.rs | 42 ++ 13 files changed, 990 insertions(+), 171 deletions(-) create mode 100644 crates/core/src/layer/generator_global.rs create mode 100644 crates/core/src/layer/output_resolution.rs create mode 100644 crates/core/src/layer/resolution_mode.rs create mode 100644 crates/engine/tests/it/generator_inputs.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index fe0bdb23..f7debf8f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -278,12 +278,24 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } +/// Below this a coverage weight counts as no coverage at all. +const MIN_COVERAGE_WEIGHT: f32 = 1e-6; +/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. +const FILTER_SIZE_RESOLUTION: f32 = 2048.0; +/// The smallest radius a filter runs at, in texels. +const MIN_FILTER_RADIUS: f32 = 0.5; +/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels. +const SHARPEN_RADIUS: f32 = 1.5; +const MIN_SHARPEN_RADIUS: f32 = 0.75; + /// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { - let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::Sharpen { amount }) => { + Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount)))) + } EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) @@ -297,6 +309,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator Some((index, texels(*width * 0.5), Op::Bevel)), EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + // Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them + EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => { + Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None))) + } EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) } @@ -597,59 +613,73 @@ 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( - inp: &Inputs, + inputs: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, effects: &[Effect], (index, radius, op): (usize, f32, Op), - (rx0, ry0, w, h): (u32, u32, u32, u32), + (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { - let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); - let comps = match job { + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); + let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); + + // A generator stage also keeps the generator's own ramp per texel, beside the stack below it (generators only act in masks) + let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) { + (Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)), + _ => None, + }; + let components = match job { + Job::Mask(_) if generator.is_some() => 2, Job::Mask(_) => 1, Job::Content(_) => 4, }; // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) - let (rx1, ry1) = (rx0 + w, ry0 + h); - let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); + let (region_right, region_bottom) = (region_x + width, region_y + height); + let region_tiles: Vec<(u32, u32)> = + (region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() - .map(|&(tx, ty)| { - let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); + .map(|&(tile_x, tile_y)| { + let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below)); + let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y)); let mut mask = None; let mut nodes = Vec::new(); + let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); mask_stack.start = start; mask = Some(mask_stack); } Job::Content(channel) => { - nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); - if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { - chan.effects.truncate(index); - chan.start = start; + nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below)); + if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + channel_plan.effects.truncate(index); + channel_plan.start = start; } } } - tile_texels(inp.gbuf, tx, ty) + tile_texels(inputs.gbuf, tile_x, tile_y) .map(|(x, y, offset)| { - let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); - if !full.is_empty() { - texel.anchors_below(&full, id); + let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset)); + if !anchor_nodes.is_empty() { + texel.anchors_below(&anchor_nodes, id); } let value = match (&mask, nodes.first()) { - (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], - (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { - Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], + (Some(mask_stack), _) => { + let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref())); + [texel.mask(mask_stack), ramp, 0.0, 0.0] + } + (None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) { + Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage], None => [0.0; 4], }, (None, None) => [0.0; 4], @@ -661,55 +691,59 @@ fn filter_region( .collect(); // Scatter into the region, a row of tiles at a time (the region is tile aligned) - let texel_count = (w * h) as usize; - let mut orig = vec![0.0f32; texel_count * comps]; + let texel_count = (width * height) as usize; + let mut stack_values = vec![0.0f32; texel_count * components]; let mut cover = vec![0.0f32; texel_count]; - let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; - let band = (TILE * w) as usize; - orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { + let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize; + let band = (TILE * width) as usize; + stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| { for &(x, y, value) in row.iter().flatten() { - let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) { *covered = 1.0; - pixel.copy_from_slice(&value[..comps]); + pixel.copy_from_slice(&value[..components]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height) - let mid = match job { + // High pass centers on the channel's middle value (0 for signed channels like height) + let middle = match job { Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { - let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let scaled_radius = neighbourhood_filters(effects, res) + let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1); + if let Some((generator, blend)) = generator { + let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution); + return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set)); + } + let scaled_radius = neighbourhood_filters(effects, tile_resolution) .find(|filter| filter.0 == index) .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); + return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity); } // Weighted so uncovered texels don't bleed in - let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); + let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, width, height, blur_radius); - let mut data = orig.clone(); - for component in 0..comps { - let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); - blur(&mut sums, width, height, blur_radius); - data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept) - let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *weight > 1e-6 + blur(&mut weights, columns, rows, blur_radius); + let mut filtered_values = stack_values.clone(); + for component in 0..components { + let mut sums: Vec = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, columns, rows, blur_radius); + filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the middle value is too (coverage itself is kept) + let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > MIN_COVERAGE_WEIGHT && let Some(slot) = pixel.get_mut(component) { let (original, blurred) = (*slot, sum / weight); let result = match op { Op::Blur(Some(amount)) => original + amount * (original - blurred), - Op::HighPass if component < 3 => original - blurred + mid * cov, + Op::HighPass if component < 3 => original - blurred + middle * coverage, // Away from 0 by at most the value itself: 0 at the edge, full inside Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), Op::Glow(amount) if component < 3 => original + amount * blurred, @@ -720,31 +754,148 @@ fn filter_region( } }); } - data + filtered_values }; // Each block keeps the result at its tile's scale (blocks are TILE aligned) - let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); - let mut levels: Vec = - (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); + let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default(); + let mut levels: Vec = (region_y..region_bottom) + .step_by(TILE as usize) + .flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y))) + .map(|(x, y)| scales.at(x, y)) + .collect(); levels.sort_by(f32::total_cmp); levels.dedup(); let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); - let mut data = filtered(first); + + // A generator stage's field is the mask alone + let field_components = if generator.is_some() { 1 } else { components }; + let mut result = filtered(first); for &scale in rest { - let other = filtered(scale); - let row = w as usize * comps; - data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { - if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { + let rescaled = filtered(scale); + let row = width as usize * field_components; + result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| { + for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() { + if scales.at(region_x + x as u32, region_y + y as u32) == scale { target.copy_from_slice(source); } } }); } - unpremultiply(&mut data, comps); - Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) + unpremultiply(&mut result, field_components); + Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result }) +} + +/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side. +fn generator_region( + generator: &Generator, + blend: BlendMode, + opacity: f32, + stack: &[f32], + cover: &[f32], + (region_x, region_y, width, height): (u32, u32, u32, u32), + (uv_tile, texture_set): (u32, u32), +) -> Vec { + let (columns, rows) = (width as usize, height as usize); + let mut ramps: Vec = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect(); + + // Coarser than the UV tile: averaged over cells, then the blur around them + let cell = generator.resolution.cell(uv_tile, texture_set) as usize; + if cell > 1 { + ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell); + } + + let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize; + if blur_radius > 0 { + let mut weights = cover.to_vec(); + blur(&mut weights, columns, rows, blur_radius); + let mut sums: Vec = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect(); + blur(&mut sums, columns, rows, blur_radius); + ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| { + if *weight > MIN_COVERAGE_WEIGHT { + *ramp = sum / weight; + } + }); + } + + // Finished and blended over the stack below, like the generator effect itself + stack + .par_chunks(2) + .zip(ramps.par_iter()) + .map(|(texel, ramp)| { + let below = texel.first().copied().unwrap_or(0.0); + let generated = finish_generator(generator, *ramp); + below + (blend1(blend, below, generated) - below) * opacity + }) + .collect() +} + +/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers. +fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec { + // Cells are aligned to absolute texel positions, so a texel's cell is the same in every region + let (first_column, first_row) = (region_x / cell, region_y / cell); + let columns = (region_x + width).div_ceil(cell) - first_column; + let rows = (region_y + height).div_ceil(cell) - first_row; + + // Each cell's coverage-weighted average, a row of cells at a time + let averages: Vec> = (0..rows) + .into_par_iter() + .flat_map_iter(|row| { + let mut sums = vec![(0.0f32, 0.0f32); columns]; + let first_y = ((first_row + row) * cell).saturating_sub(region_y); + let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height); + for y in first_y..last_y { + for x in 0..width { + let texel = y * width + x; + let covered = cover.get(texel).copied().unwrap_or(0.0); + if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) { + *sum += values.get(texel).copied().unwrap_or(0.0) * covered; + *weight += covered; + } + } + } + sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight)) + }) + .collect(); + let average = |column: isize, row: isize| -> Option { + let column = column.clamp(0, columns as isize - 1) as usize; + let row = row.clamp(0, rows as isize - 1) as usize; + averages.get(row * columns + column).copied().flatten() + }; + + let cell_size = cell as f32; + (0..height) + .into_par_iter() + .flat_map_iter(|y| (0..width).map(move |x| (x, y))) + .map(|(x, y)| { + // Position in cells, relative to the first cell's center + let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32; + let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32; + let (left, top) = (cell_x.floor(), cell_y.floor()); + let (offset_x, offset_y) = (cell_x - left, cell_y - top); + let (left, top) = (left as isize, top as isize); + let corners = [ + (left, top, (1.0 - offset_x) * (1.0 - offset_y)), + (left + 1, top, offset_x * (1.0 - offset_y)), + (left, top + 1, (1.0 - offset_x) * offset_y), + (left + 1, top + 1, offset_x * offset_y), + ]; + let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) { + Some(value) => (sum + value * corner_weight, weight + corner_weight), + None => (sum, weight), + }); + if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) } + }) + .collect() +} + +/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset. +fn finish_generator(generator: &Generator, ramp: f32) -> f32 { + let value = generator.global.apply(ramp); + let value = if generator.invert { 1.0 - value } else { value }; + let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 }; + (value + offset).clamp(0.0, 1.0) } /// Clamp filtered masks to 0..1, and turn filtered content back into straight values. @@ -1216,15 +1367,21 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's ramp at this texel, before its global blur, balance, contrast and invert. + fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); let signal = match (generator.kind, &generator.detail) { - (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), - (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), - (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { + // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only + let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; + let curvature = self.generator_input(generator, BakedMap::Curvature); + self.curvature_detail(detail, sizes, curvature) + } + (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0), (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; @@ -1241,12 +1398,29 @@ impl<'a, 'b> Texel<'a, 'b> { signal }; - // A smooth step from black to white over 2 × softness around 1 − level, then the offset - generator.shape(signal) + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(Generator::MIN_SOFTNESS); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + ramp * ramp * (3.0 - 2.0 * ramp) } - /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + /// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]). + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let ramp = self.generator_ramp(generator, curvature_sizes); + finish_generator(generator, ramp) + } + + /// 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 { + match generator.inputs.get(&map) { + Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]), + None => self.baked(map), + } + } + + /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { let combine = |edges: f32, cavities: f32| match detail.mode { CurvatureMode::Edges => edges, CurvatureMode::Cavities => cavities, @@ -1255,7 +1429,7 @@ impl<'a, 'b> Texel<'a, 'b> { }; // Without curvature to read the texel is flat: no edges or cavities - let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; + let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; @@ -2272,7 +2446,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti #[cfg(test)] mod tests { use super::*; - use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet}; + use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet}; use texturecraft_geom::primitives; struct Fixture { @@ -2564,44 +2738,156 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } - #[test] - fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + /// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask. + fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) { let mut fixture = fixture(); fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); fixture.project.texture_sets[0].resolution = 256; - let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == ridge_x { 1.0 } else { 0.5 }).collect(); fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); - let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + (fixture, layer) + } + + /// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`. + fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec, xs: std::ops::Range) -> Vec { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = effects; + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &xs.map(|x| (x, 128)).collect::>()).unwrap() + } + + /// A generator effect of `fixture`'s project. + fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect { + Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)) + } + + /// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step). + fn ridge_generator() -> Generator { + Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) } + } + + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let (mut fixture, layer) = ridge_fixture(128); + let mut row_with = |weights: [f32; 7]| { let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; - let mut mask = Mask::new(MaskBackground::Black); - mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); - fixture.project.layer_mut(layer).unwrap().mask = Some(mask); - let images = Default::default(); - let inputs = Inputs { - project: &fixture.project, - ts: 0, - mesh: &fixture.mesh, - gbuf: &fixture.gbuf, - pixels: &fixture.pixels, - baked: &fixture.baked, - block_scales: BlockScales::default(), - preview: None, - images: &images, - bounds: fixture.mesh.bounds(), - }; - mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 120..137) }; // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth let (ridge, five_texels_away) = (8, 3); - let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); - let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); } + #[test] + fn a_replaced_curvature_input_is_read_at_its_own_size_only() { + let (mut fixture, layer) = ridge_fixture(128); + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] }; + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3])); + let effect = generator_effect(&mut fixture, generator); + let row = mask_row(&mut fixture, layer, vec![effect], 120..137); + + // The largest size alone would mark the ridge and texels around it; the flat input marks nothing + assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}"); + } + + #[test] + fn generator_blur_softens_only_the_generator_not_the_stack_below() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |blur: f32| { + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); + let mut generator = ridge_generator(); + generator.global.blur = blur; + let mut lighten = generator_effect(&mut fixture, generator); + lighten.blend = BlendMode::Lighten; + mask_row(&mut fixture, layer, vec![below, lighten], 40..111) + }; + + // The row starts at x 40 and crosses a checker edge at x 64; the ridge at x 100 is texel 60, five texels left of it texel 55, and texels below 30 are out of the blur's reach + let (ridge, five_texels_away, far) = (60, 55, 0..30); + let sharp = row_with(0.0); + let blurred = row_with(1.0); + 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}"); + } + } + + #[test] + fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() { + let (mut fixture, layer) = ridge_fixture(100); + let mut row_with = |factor: i8| { + let mut generator = ridge_generator(); + generator.resolution.factor = factor; + let effect = generator_effect(&mut fixture, generator); + mask_row(&mut fixture, layer, vec![effect], 80..121) + }; + + // The row starts at x 80: the ridge at x 100 is texel 20; at an eighth of the resolution one value covers 8 texels + let (ridge, beside, far) = (20, 18, 0); + let full = row_with(0); + let eighth = row_with(-3); + assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}"); + assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}"); + assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}"); + } + + #[test] + fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() { + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 }; + let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))]; + + // A UV tile of 1024 texels in a 2-tile-wide set: callers pass the tile size or the whole set's width + let at_tile: Vec = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect(); + let at_set_width: Vec = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect(); + assert_eq!(at_tile, at_set_width); + assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage"); + } + + #[test] + fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let value_with = |fixture: &mut Fixture, input: Option| -> f32 { + let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) }; + if let Some(value) = input { + generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3])); + } + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + run(fixture, None).value(Channel::BaseColor, 20, 20)[0] + }; + + // Dirt is where ambient occlusion is dark: none on the baked white map (the stack below shows), all of it on a black input + let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0))); + assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}"); + } + #[test] fn curvature_detail_noise_keeps_flat_areas_neutral() { let mut fixture = fixture(); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 8e7c41e8..acd53874 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -4,13 +4,19 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use crate::{BlendMode, Channel, ChannelKind, lum}; +use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; mod curvature_detail; mod curvature_mode; +mod generator_global; +mod output_resolution; +mod resolution_mode; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; +pub use generator_global::GeneratorGlobal; +pub use output_resolution::OutputResolution; +pub use resolution_mode::ResolutionMode; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -526,6 +532,17 @@ impl GeneratorKind { GeneratorKind::Direction => "Light / direction", } } + + /// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace. + pub fn inputs(self) -> &'static [BakedMap] { + match self { + GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature], + GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion], + GeneratorKind::ThinAreas => &[BakedMap::Thickness], + GeneratorKind::Position | GeneratorKind::Direction => &[], + } + } + pub fn parse(s: &str) -> Option { let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], ""); GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s)) @@ -552,9 +569,25 @@ pub struct Generator { /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). #[serde(default, skip_serializing_if = "Option::is_none")] pub detail: Option, + /// Blur, balance and contrast of the finished value (neutral for generators saved before they existed). + #[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")] + pub global: GeneratorGlobal, + /// The resolution the generator is computed at (the texture set's for generators saved before it existed). + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, + /// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub inputs: BTreeMap, } impl Generator { + /// The softest a ramp gets, so its threshold never divides by zero. + pub const MIN_SOFTNESS: f32 = 1e-3; + /// The most noise a generator mixes in, and the range of its noise scale. + pub const MAX_NOISE_AMOUNT: f32 = 2.0; + pub const MIN_NOISE_SCALE: f32 = 0.01; + pub const MAX_NOISE_SCALE: f32 = 1000.0; + pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), @@ -568,7 +601,21 @@ impl Generator { GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail } + Generator { + kind, + level, + softness, + noise_amount, + noise_scale: 8.0, + seed: 7, + offset: 0.0, + direction: [0.0, 1.0, 0.0], + invert: false, + detail, + global: GeneratorGlobal::default(), + resolution: OutputResolution::default(), + inputs: BTreeMap::new(), + } } /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over @@ -1038,14 +1085,45 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Anchor points read by this effect's sources. + /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. fn reads_anchor(&self) -> bool { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), + EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()), _ => false, } } + + /// The anchor points this effect's sources read, with the channel each reads. + pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values().collect(), + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources + .into_iter() + .filter_map(|source| match source { + Source::Anchor { anchor, channel } => Some((*anchor, *channel)), + _ => None, + }) + .collect() + } + + /// The image resources this effect's sources read (a fill or a generator input). + pub fn images_read(&self) -> impl Iterator { + let sources: Vec<&Source> = match self { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Generator(generator) => generator.inputs.values().collect(), + _ => Vec::new(), + }; + sources.into_iter().filter_map(|source| match source { + Source::Image { name, .. } => Some(name.as_str()), + _ => None, + }) + } } impl Layer { @@ -1115,6 +1193,22 @@ mod tests { assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); } + #[test] + fn generators_saved_before_the_new_settings_load_and_save_unchanged() { + let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap(); + for field in ["global", "resolution", "inputs"] { + assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were"); + } + + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert!(loaded.global.is_neutral()); + + let mut blurred = Generator::new(GeneratorKind::Dirt); + blurred.global.blur = 0.5; + let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap(); + assert_eq!(round_trip, blurred); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/generator_global.rs b/crates/core/src/layer/generator_global.rs new file mode 100644 index 00000000..15349e0d --- /dev/null +++ b/crates/core/src/layer/generator_global.rs @@ -0,0 +1,96 @@ +use serde::{Deserialize, Serialize}; + +/// Adjustments every generator applies to its finished value: a blur, then balance and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct GeneratorGlobal { + /// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]). + pub blur: f32, + /// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged. + pub balance: f32, + /// Narrows the ramp around its middle (0 unchanged, 1 a hard step). + pub contrast: f32, +} + +impl GeneratorGlobal { + /// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub const MAX_BLUR: f32 = 64.0; + /// Narrower than this, the balanced range is a hard step. + pub const MIN_RANGE: f32 = 1e-6; + /// The texels per side the blur radius is measured at (2K). + pub const BLUR_RESOLUTION: f32 = 2048.0; + + pub fn is_neutral(&self) -> bool { + *self == GeneratorGlobal::default() + } + + /// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`]. + pub fn blur_radius(&self) -> f32 { + self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR + } + + /// The blur as a radius in texels at `resolution` texels per side. + pub fn blur_radius_at(&self, resolution: u32) -> f32 { + self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION + } + + /// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle. + pub fn apply(&self, value: f32) -> f32 { + if self.balance == 0.5 && self.contrast == 0.0 { + return value; + } + let balance = self.balance.clamp(0.0, 1.0); + let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0)); + let middle = (low + high) * 0.5; + let keep = 1.0 - self.contrast.clamp(0.0, 1.0); + let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep); + if high - low < GeneratorGlobal::MIN_RANGE { + return if value >= middle { 1.0 } else { 0.0 }; + } + ((value - low) / (high - low)).clamp(0.0, 1.0) + } +} + +impl Default for GeneratorGlobal { + fn default() -> Self { + GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn neutral_settings_leave_the_value_unchanged() { + let global = GeneratorGlobal::default(); + for value in [0.0, 0.1, 0.5, 0.93, 1.0] { + assert_eq!(global.apply(value), value); + } + } + + #[test] + fn balance_darkens_below_the_middle_and_brightens_above() { + let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() }; + assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black"); + assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range"); + + let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() }; + assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6); + assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white"); + + assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0); + assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0); + } + + #[test] + fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() { + let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() }; + assert_eq!(step.apply(0.49), 0.0); + assert_eq!(step.apply(0.51), 1.0); + + let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() }; + assert_eq!(half.apply(0.25), 0.0); + assert!((half.apply(0.5) - 0.5).abs() < 1e-6); + assert_eq!(half.apply(0.75), 1.0); + } +} diff --git a/crates/core/src/layer/output_resolution.rs b/crates/core/src/layer/output_resolution.rs new file mode 100644 index 00000000..6c1e8778 --- /dev/null +++ b/crates/core/src/layer/output_resolution.rs @@ -0,0 +1,110 @@ +use serde::{Deserialize, Serialize}; + +use super::resolution_mode::ResolutionMode; + +/// The resolution a generator computes its output at, before it is sampled onto the texture set. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputResolution { + pub mode: ResolutionMode, + /// Texels per side for [`ResolutionMode::Custom`]. + pub custom: u32, + /// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context). + pub factor: i8, +} + +impl OutputResolution { + /// The factors the reference app offers: 1/8 to ×8. + pub const FACTORS: std::ops::RangeInclusive = -3..=3; + /// The sizes offered for [`ResolutionMode::Custom`]. + pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096]; + /// The largest output, the largest texture set resolution. + pub const MAX_SIZE: u32 = 8192; + /// The coarsest output: one value per this many texels of the context per side (a compositing tile). + pub const MAX_CELL: u32 = 64; + + pub fn is_default(&self) -> bool { + *self == OutputResolution::default() + } + + /// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1). + pub fn can_reduce(&self) -> bool { + matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0 + } + + /// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution. + pub fn largest_cell(&self, uv_tile: u32) -> u32 { + if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) } + } + + /// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`. + pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 { + let base = match self.mode { + ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile, + ResolutionMode::TextureSet => texture_set, + ResolutionMode::Custom => self.custom, + }; + let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end()); + let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor }; + scaled.clamp((uv_tile / OutputResolution::MAX_CELL).max(1), OutputResolution::MAX_SIZE) + } + + /// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer). + pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 { + (uv_tile / self.output_size(uv_tile, texture_set)).max(1) + } +} + +impl Default for OutputResolution { + fn default() -> Self { + OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_follows_the_uv_tile() { + let resolution = OutputResolution::default(); + assert_eq!(resolution.output_size(1024, 2048), 1024); + assert_eq!(resolution.cell(1024, 2048), 1); + assert!(!resolution.can_reduce()); + } + + #[test] + fn the_texture_set_mode_reads_the_set_not_the_uv_tile() { + let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() }; + assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048"); + assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel"); + } + + #[test] + fn factors_and_custom_sizes_scale_the_output() { + let eighth = OutputResolution { factor: -3, ..OutputResolution::default() }; + assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8)); + + let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 }; + assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2)); + + let finer = OutputResolution { factor: 3, ..OutputResolution::default() }; + assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel"); + } + + #[test] + fn the_largest_cell_covers_any_texture_set() { + let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() }; + assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size"); + assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL); + assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4); + } + + #[test] + fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() { + let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX }; + assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE); + + let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 }; + assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL); + } +} diff --git a/crates/core/src/layer/resolution_mode.rs b/crates/core/src/layer/resolution_mode.rs new file mode 100644 index 00000000..ffd6a140 --- /dev/null +++ b/crates/core/src/layer/resolution_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// What a generator's output resolution is based on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ResolutionMode { + /// The context: the resolution of the UV tile it is computed for. + Auto, + /// The texture set's resolution. + TextureSet, + /// The UV tile's resolution. + UvTile, + /// A size of its own. + Custom, +} + +impl ResolutionMode { + pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom]; + + pub fn label(self) -> &'static str { + match self { + ResolutionMode::Auto => "Auto", + ResolutionMode::TextureSet => "Texture set", + ResolutionMode::UvTile => "UV tile", + ResolutionMode::Custom => "Custom", + } + } + + pub fn parse(name: &str) -> Option { + let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 75ea2405..4a17e89e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,9 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, - hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, + Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind, + Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 36aa5f3a..3f68c147 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -2,7 +2,7 @@ //! clipboard: it holds a layer or an effect. use serde_json::{Value, json}; -use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; +use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground}; use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; @@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result { Ok(json!({ "cut": eid })) } -fn paste(s: &mut Session, p: &Value) -> Result { +fn paste(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.paste"; - let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; - let layer = layer_param(s, CMD, p)?; - // The selected effect's stack, or the content or mask the selection targets. - let selected = match s.target { - StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x), + let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?; + let layer = layer_param(session, CMD, params)?; + + // The selected effect's stack, or the content or mask the selection targets + let selected = match session.target { + StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected), _ => None, }; - let in_content = |s: &Session, x: LayerId| { - s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x)) + let in_content = |session: &Session, effect_id: LayerId| { + let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner)); + owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id)) }; - let asked = strp(p, "target").is_some(); + let asked = strp(params, "target").is_some(); let content = match selected { - _ if asked => content_target(p, CMD)?, - Some(x) => in_content(s, x), - None => s.target == StackTarget::Content && s.selected_layer() == Some(layer), + _ if asked => content_target(params, CMD)?, + Some(selected) => in_content(session, selected), + None => session.target == StackTarget::Content && session.selected_layer() == Some(layer), }; - // Effects that fit one stack only go there, unless another was asked for. + + // Effects that fit one stack only go there, unless another was asked for let content = match effect.kind.content_only() { Some(only) if only != content && asked => { return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" }))); @@ -82,46 +85,52 @@ fn paste(s: &mut Session, p: &Value) -> Result { Some(only) => only, None => content, }; - // An instance's content and (unless it has its own) mask belong to its source. - let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) }; - let owner_layer = s.doc.project.layer(owner)?; + + // An instance's content and (unless it has its own) mask belong to its source + let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) }; + let owner_layer = session.doc.project.layer(owner)?; if content && owner_layer.is_group() { return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name))); } - // A fill reading an anchor point needs one below its new layer. - if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { - anchor_source(s, CMD, owner, *anchor, *channel)?; + + // Each anchor point the effect reads must be below its new layer + for (anchor, channel) in effect.kind.anchors_read() { + anchor_source(session, CMD, owner, anchor, channel)?; } - let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; - let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; - let new = s.edit("Paste effect", |s| { - let new = s.doc.project.alloc_id(); - let l = s.doc.project.layer_mut(owner)?; - let list = if content { - &mut l.content_effects + let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; + let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?; + + let pasted = session.edit("Paste effect", |session| { + let pasted = session.doc.project.alloc_id(); + let owner_layer = session.doc.project.layer_mut(owner)?; + let stack = if content { + &mut owner_layer.content_effects } else { - let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; - &mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects + let background = + if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White }; + &mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects }; - let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1); - list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() }); - // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's). - if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) { - s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0])); + let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1); + stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() }); + + // Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's) + if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) { + session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0])); } - for c in channels.iter().copied().filter(|_| content) { - if let Some(img) = src.pixels.layer(eid, c) { - s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c))); + for channel in channels.iter().copied().filter(|_| content) { + if let Some(image) = copied.pixels.layer(copied_id, channel) { + session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel))); } } - // The target belongs to the active set's selection: a paste into another set leaves it. - if let Some((lts, _, _)) = s.doc.project.locate(layer) { - s.selected.insert(lts, layer); - if lts == s.ts() { - s.target = StackTarget::Effect(new); + + // The target belongs to the active set's selection: a paste into another set leaves it + if let Some((layer_set, _, _)) = session.doc.project.locate(layer) { + session.selected.insert(layer_set, layer); + if layer_set == session.ts() { + session.target = StackTarget::Effect(pasted); } } - Ok(new) + Ok(pasted) })?; - Ok(json!({ "effect": new.0 })) + Ok(json!({ "effect": pasted.0 })) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 233e9f4c..67f70a22 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -69,9 +69,16 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { out } -/// A generator's settings, with its curvature mode and detail size weights when it has them. +/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them. fn generator_json(generator: &Generator) -> Value { - let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert }); + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast }); + if !generator.resolution.is_default() { + out["resolution"] = + json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor }); + } + if !generator.inputs.is_empty() { + out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), json!(source))).collect::>().into(); + } if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 4c286955..a617401c 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, - Procedural, ProceduralKind, Project, Source, + BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, + MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -323,13 +323,13 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R generator.softness = softness.clamp(0.0, 1.0); } if let Some(noise) = f32p(params, "noise") { - generator.noise_amount = noise.clamp(0.0, 2.0); + generator.noise_amount = noise.clamp(0.0, Generator::MAX_NOISE_AMOUNT); } if let Some(offset) = f32p(params, "offset") { generator.offset = offset.clamp(-1.0, 1.0); } if let Some(noise_scale) = f32p(params, "noiseScale") { - generator.noise_scale = noise_scale.clamp(0.01, 1000.0); + generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE); } if let Some(seed) = u64p(params, "seed") { generator.seed = seed as u32; @@ -340,6 +340,26 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(direction) = color_param(params, "direction") { generator.direction = direction; } + if let Some(blur) = f32p(params, "blur") { + generator.global.blur = blur.clamp(0.0, 1.0); + } + if let Some(balance) = f32p(params, "balance") { + generator.global.balance = balance.clamp(0.0, 1.0); + } + if let Some(contrast) = f32p(params, "contrast") { + generator.global.contrast = contrast.clamp(0.0, 1.0); + } + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } // A mode or sizes also give a curvature generator saved before detail sizes its detail let mode = params @@ -378,6 +398,35 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } +/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`. +fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result)>> { + const CMD: &str = "effect.set"; + let Some(name) = params.get("input") else { return Ok(None) }; + let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?; + let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?; + + let image = strp(params, "inputImage"); + let value = f32p(params, "inputValue"); + let anchor = u64p(params, "inputAnchor"); + let baked = boolp(params, "inputBaked") == Some(true); + let source = match (image, value, anchor, baked) { + (Some(image), None, None, false) => { + if !session.doc.resources.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}`"))); + } + Some(Source::Image { name: image.to_string(), normal_format: Default::default() }) + } + (None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])), + (None, None, Some(anchor), false) => { + let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height); + Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?) + } + (None, None, None, true) => None, + _ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")), + }; + Ok(Some((map, source))) +} + fn add_generator(session: &mut Session, params: &Value) -> Result { let kind = match strp(params, "generator") { Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, @@ -475,6 +524,12 @@ fn set(session: &mut Session, params: &Value) -> Result { _ => None, }; + // `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back + let input = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?, + _ => None, + }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(params, "filter") { Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None, @@ -508,7 +563,18 @@ fn set(session: &mut Session, params: &Value) -> Result { } match &mut edited.kind { - EffectKind::Generator(generator) => generator_from(CMD, params, generator)?, + EffectKind::Generator(generator) => { + generator_from(CMD, params, generator)?; + if let Some((map, source)) = input { + if !generator.kind.inputs().contains(&map) { + return Err(bad(CMD, format!("this generator has no `{}` input", map.id()))); + } + match source { + Some(source) => generator.inputs.insert(map, source), + None => generator.inputs.remove(&map), + }; + } + } EffectKind::Levels(levels) => levels_from(params, levels), // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index bdd2fbdd..67e30022 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and fill effects). -pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec, depth: usize) { +/// Image resources a layer subtree uses (fill sources, mask fills and generator inputs). +pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; } - let Some(l) = p.layers.get(&id) else { return }; - if let LayerKind::Fill(f) = &l.kind { - for s in f.sources.values() { - if let Source::Image { name, .. } = s { + let Some(layer) = project.layers.get(&id) else { return }; + + if let LayerKind::Fill(fill) = &layer.kind { + for source in fill.sources.values() { + if let Source::Image { name, .. } = source { out.push(name.clone()); } } - out.extend(f.link.as_ref().map(|link| link.package.clone())); + out.extend(fill.link.as_ref().map(|link| link.package.clone())); } - for e in l.mask.iter().flat_map(|m| m.effects.iter()) { - if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind { - out.push(name.clone()); - } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()) { + out.extend(effect.kind.images_read().map(str::to_string)); } - for c in l.children() { - images_used(p, *c, out, depth + 1); + for child in layer.children() { + images_used(project, *child, out, depth + 1); } } diff --git a/crates/engine/tests/it/generator_inputs.rs b/crates/engine/tests/it/generator_inputs.rs new file mode 100644 index 00000000..da36b780 --- /dev/null +++ b/crates/engine/tests/it/generator_inputs.rs @@ -0,0 +1,77 @@ +//! Generator inputs that read an anchor point or an image, through engine commands. + +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The texture set's texels per side. +const RESOLUTION: u32 = 256; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// Composited value of `channel` under the viewport center. +fn center(session: &mut Session, channel: Channel) -> [f32; 3] { + session.update(); + let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap(); + let texels = RESOLUTION as f32; + session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32) +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator). +fn anchored_generator(session: &mut Session) -> (u64, u64, u64) { + let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer"); + let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect"); + execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect"); + execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap(); + (anchor, low, generator) +} + +#[test] +fn a_generator_input_reads_the_anchor_points_value() { + let mut session = session(); + anchored_generator(&mut session); + + // The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none + let base = center(&mut session, Channel::BaseColor)[0]; + assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}"); +} + +#[test] +fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() { + let mut session = session(); + let (_, low, generator) = anchored_generator(&mut session); + execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap(); + + let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"})); + assert!(pasted.is_err(), "the anchor point is on that layer, not below it"); +} + +#[test] +fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() { + let mut session = session(); + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("occlusion.png", bytes).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e6157332..52a9ff08 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -10,6 +10,7 @@ mod content_effects; mod export_colour_space; mod filter_swap; mod filters; +mod generator_inputs; mod high_poly_missed; mod instances; mod materialcraft_link; diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 22a17cd5..e85b3767 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -524,3 +524,45 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } + +#[test] +fn generators_take_blur_balance_and_contrast() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}"); + assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}"); + assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected"); +} + +#[test] +fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"Uniform":[0.25,0.25,0.25]}}"#), "{inspect}"); + + let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5})); + assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature"); + let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"})); + assert!(missing_image.is_err(), "the image must be a resource of the project"); + let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true})); + assert!(two_sources.is_err(), "an input takes one source"); + + execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}"); +} From 03660e5a212c19de1fd81f6dde5791f3208036f4 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Wed, 11 Nov 2026 05:09:31 +0000 Subject: [PATCH 02/22] Generator panel in the reference app's layout; effect blend and opacity on their rows - The generator properties move to generator_panel.rs: Attributes (description, category, tags), Resolution, Parameters with the global adjustments first, a seed with Random and a pencil to type it, Restore defaults, and Image inputs (a picture of what each input reads, a source menu, images dropped from Assets). - Effect rows get a blend mode menu and an opacity field at their right; the effect properties no longer show them. Effect rows alternate two shades just above the panel, so they read as rows under their layer. - Layer and effect rows share the blend mode and opacity controls: the opacity reads as plain text (no field box) and one drag is one undo step. - Translations for every new string in the 9 languages. --- crates/ui-egui/src/dock.rs | 775 +++++++++++---------- crates/ui-egui/src/generator_panel.rs | 385 ++++++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/tests/it/effect_rows.rs | 79 ++- crates/ui-egui/tests/it/effect_sliders.rs | 232 +++--- crates/ui-egui/tests/it/generator_panel.rs | 128 ++++ crates/ui-egui/tests/it/layers_panel.rs | 6 +- crates/ui-egui/tests/it/main.rs | 1 + 8 files changed, 1115 insertions(+), 492 deletions(-) create mode 100644 crates/ui-egui/src/generator_panel.rs create mode 100644 crates/ui-egui/tests/it/generator_panel.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..e6ee88ac 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,8 +6,8 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, - LinkParam, MaterialLink, ProceduralKind, Projection, Source, + BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, + Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; @@ -270,6 +270,77 @@ fn row_shade(tk: &Tokens, index: usize) -> Color32 { const RIGHT_COLUMN: f32 = 58.0; /// Indent per folder level, and per level of the effect tree. const INDENT: f32 = 14.0; +/// Edge of the small icon buttons in the properties panel. +const ICON_BUTTON_SIZE: f32 = 22.0; +/// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. +const ROW_CONTROL_HEIGHT: f32 = 17.0; +const ROW_CONTROL_ROUNDING: f32 = 2.0; +/// Gap between the controls at the right of a stack row, and between them and the row's edge. +const ROW_CONTROL_GAP: f32 = 4.0; +/// Space before an effect row's eye and after its name. +const ROW_LEFT_PADDING: f32 = 7.0; +const ROW_RIGHT_PADDING: f32 = 6.0; +/// Width of the selected row's accent edge. +const SELECTED_EDGE_WIDTH: f32 = 3.0; +/// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. +const THUMBNAIL_ROUNDING: f32 = 2.0; +const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; +const HIDDEN_STRIKE_WIDTH: f32 = 1.5; +const DROP_LINE_WIDTH: f32 = 2.0; +/// The eye's size and the column it sits in (the eye and a gap before the thumbnail). +const EYE_SIZE: f32 = 16.0; +const EYE_COLUMN_WIDTH: f32 = 22.0; +/// Gap between an effect's thumbnail and its name, and the narrowest name worth showing. +const THUMBNAIL_GAP: f32 = 8.0; +const MIN_NAME_WIDTH: f32 = 20.0; +/// Font sizes in an effect row: the eye, the name, the blend mode and its caret. +const EYE_FONT_SIZE: f32 = 12.0; +const EFFECT_NAME_FONT_SIZE: f32 = 11.5; +const ROW_SMALL_FONT_SIZE: f32 = 11.0; +const CARET_FONT_SIZE: f32 = 8.0; +/// Room for the caret at the right of the blend mode's name. +const CARET_WIDTH: f32 = 10.0; +/// The blend mode menu's width, wide enough for the longest mode name. +const BLEND_MENU_MIN_WIDTH: f32 = 190.0; +/// Padding inside a row's opacity field, and the percent it moves per point dragged. +const ROW_FIELD_PADDING: f32 = 4.0; +const OPACITY_DRAG_SPEED: f64 = 0.5; +/// A layer row's eye: its hit area, its glyph size and the column it sits in. +const LAYER_EYE_SIZE: f32 = 18.0; +const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; +/// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. +const FOLDER_CARET_SIZE: f32 = 14.0; +const FOLDER_CARET_CENTER: f32 = 6.0; +/// A thumbnail's border while it is the layer's target, and how far outside it the mask-view and drop outlines sit. +const TARGET_BORDER_WIDTH: f32 = 1.5; +const HIGHLIGHT_OUTSET: f32 = 2.0; +/// The gap between a layer row's stacked blend mode and opacity, either side of the row's middle. +const ROW_STACK_GAP: f32 = 1.0; +/// Width of a layer's colour tag beside the accent edge. +const TAG_WIDTH: f32 = 3.0; +/// Space between a layer's content and mask thumbnails, and the size of the empty mask slot. +const THUMBNAIL_SPACING: f32 = 4.0; +const MASK_SLOT_SIZE: f32 = 18.0; +/// Grays of a white or black mask before its thumbnail arrives. +const WHITE_MASK_GRAY: u8 = 225; +const BLACK_MASK_GRAY: u8 = 18; +/// A layer's name and subtitle font sizes, and their distance from the row's middle. +const LAYER_NAME_FONT_SIZE: f32 = 12.5; +const LAYER_SUBTITLE_FONT_SIZE: f32 = 10.0; +const NAME_LINE_GAP: f32 = 2.0; +/// Folder lines: their width, how faded they are, how far an indent must reach past one, and where the branch starts. +const FOLDER_LINE_WIDTH: f32 = 1.0; +const FOLDER_LINE_FADE: f32 = 0.6; +const FOLDER_LINE_CLEARANCE: f32 = 8.0; +const FOLDER_BRANCH_OFFSET: f32 = 15.0; +/// The share of a folder row's height, either side of its middle, where a drop goes inside it. +const FOLDER_DROP_ZONE: f32 = 0.25; +/// How far each alternating effect row shade goes from the panel towards the hover colour. +const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; +/// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. +const EFFECT_BLEND_WIDTH: f32 = 82.0; +const EFFECT_OPACITY_WIDTH: f32 = 36.0; /// Height of the "Content effects" / "Mask effects" header rows. const GROUP_HEADER_H: f32 = 20.0; @@ -292,7 +363,7 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - 7.0 - 22.0 - preview - 8.0 - 20.0 - 6.0).max(0.0)) + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -351,292 +422,280 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget false } +/// The row of `layer` at folder depth `depth`, the `index`th row of the stack (rows alternate shades). fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); let content_target = selected && targets_content(app); - let size = layer_preview_size(app); - let h = layer_row_height(size); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); - let p = ui.painter().clone(); - let bg = if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover + let preferred_size = layer_preview_size(app); + let row_height = layer_row_height(preferred_size); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); + + // Background, folder lines, the selected row's accent edge and the colour tag + let painter = ui.painter().clone(); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover } else { - row_shade(&tk, index) + row_shade(&tokens, index) }; - p.rect_filled(rect, 0.0, bg); - let (indent, size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), size); + painter.rect_filled(rect, 0.0, background); + let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); // Folder contents hang off lines down the left without crossing compact row controls - let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + let line = Stroke::new(FOLDER_LINE_WIDTH, tokens.button_border.gamma_multiply(FOLDER_LINE_FADE)); for level in 0..depth { - let x = level_x(rect.left(), level); - if level as f32 * INDENT + 8.0 < indent { - p.vline(x, rect.y_range(), line); + if level as f32 * INDENT + FOLDER_LINE_CLEARANCE < indent { + painter.vline(level_x(rect.left(), level), rect.y_range(), line); } } if depth > 0 && indent >= INDENT { - let x = rect.left() + 15.0 + indent - INDENT; - p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; + painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); } if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } - if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); + if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); } - let x0 = rect.left() + 7.0 + indent; - // Eye. - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); - p.text( + + // The eye + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + painter.text( eye.center(), egui::Align2::CENTER_CENTER, if layer.visible { ic::EYE } else { ic::EYE_SLASH }, - egui::FontId::proportional(13.0), - if layer.visible { tk.text } else { tk.text_dim }, + egui::FontId::proportional(LAYER_EYE_FONT_SIZE), + if layer.visible { tokens.text } else { tokens.text_dim }, ); - if eye_resp.clicked() { + if eye_response.clicked() { app.run("layer.visible", json!({"layer": layer.id.0})); } - // Group caret. - let mut x = x0 + 20.0; + + // A folder's caret + let mut x = content_left + LAYER_EYE_COLUMN_WIDTH; if let LayerKind::Group { collapsed, .. } = layer.kind { - let caret = Rect::from_center_size(pos2(x + 6.0, rect.center().y), vec2(14.0, 14.0)); - let cr = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); - p.text( + let caret = Rect::from_center_size(pos2(x + FOLDER_CARET_CENTER, rect.center().y), vec2(FOLDER_CARET_SIZE, FOLDER_CARET_SIZE)); + let caret_response = ui.interact(caret, ui.scope_id().with(("caret", layer.id.0)), Sense::click()).on_hover_text(tr("Expand or collapse the folder")); + painter.text( caret.center(), egui::Align2::CENTER_CENTER, if collapsed { ic::CARET_RIGHT } else { ic::CARET_DOWN }, - egui::FontId::proportional(11.0), - tk.text_dim, + egui::FontId::proportional(ROW_SMALL_FONT_SIZE), + tokens.text_dim, ); - if cr.clicked() - && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|l| &mut l.kind) + if caret_response.clicked() + && let Some(LayerKind::Group { collapsed, .. }) = app.session.doc.project.layers.get_mut(&layer.id).map(|edited| &mut edited.kind) { *collapsed = !*collapsed; } - x += 14.0; + x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel. - let ch = app.ui.layer_channel; - let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); - if !drawn { - content_glyph(&p, &tk, thumb, layer); + + // Content thumbnail: the layer's own result in the displayed channel + let channel = app.ui.layer_channel; + let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { + content_glyph(&painter, &tokens, thumbnail, layer); } - p.rect_stroke( - thumb, - 2.0, - Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); - if content_resp.clicked() { + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); + let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); } - x = thumb.right() + 4.0; - // An instance draws its source's content, blending and (unless it has its own) mask. + x = thumbnail.right() + THUMBNAIL_SPACING; + + // An instance draws its source's content, blending and (unless it has its own) mask let project = &app.session.doc.project; - let source = layer.instance_source().map(|src| { - let set = project.locate(src).and_then(|(ts, _, _)| project.texture_sets.get(ts)).map(|t| t.name.as_str()).unwrap_or("?"); - project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) + let source = layer.instance_source().map(|source| { + let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); + project.layers.get(&source).map_or_else(|| tr("missing source").to_string(), |source_layer| format!("{} · {set}", source_layer.name)) }); - let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); - // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); + let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); + + // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; - if let Some(m) = &mask { - let mask_sel = selected && !targets_content(app); - mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); - let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); - if !drawn { - p.rect_filled( - mask_rect, - 2.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + if let Some(mask) = &mask { + let mask_target = selected && !targets_content(app); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); + if !thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !mask.enabled) { + let white = mask.background == texturecraft_engine::core::MaskBackground::White; + painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); + if !mask.effects.is_empty() { + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); } } - p.rect_stroke( - mask_rect, - 2.0, - Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), - egui::StrokeKind::Outside, - ); - if !m.enabled { - p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); + if !mask.enabled { + painter.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.danger)); } - let mr = ui + let mask_response = ui .interact(mask_rect, ui.scope_id().with(("mask", layer.id.0)), Sense::click()) .on_hover_text(tr("Select the mask (Alt+click: show it in the viewport)")); - if mr.clicked() { + if mask_response.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": "mask"})); - if ui.input(|i| i.modifiers.alt) { + if ui.input(|input| input.modifiers.alt) { let showing = app.session.view == texturecraft_engine::ViewMode::Mask(layer.id); - let p = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; - app.run("viewport.view", p); + let view = if showing { json!({"mode": "material"}) } else { json!({"mode": "mask", "layer": layer.id.0}) }; + app.run("viewport.view", view); } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + painter.rect_stroke( + mask_rect.expand(HIGHLIGHT_OUTSET), + THUMBNAIL_ROUNDING, + Stroke::new(TARGET_BORDER_WIDTH, tokens.warning), + egui::StrokeKind::Outside, + ); } - x = mask_rect.right() + 8.0; } else { - // The empty slot adds a mask to this layer. - let slot_size = size.min(18.0); + // The empty slot adds a mask to this layer + let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + let slot_color = if slot.hovered() { tokens.accent } else { tokens.field_border }; + painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, slot_color), egui::StrokeKind::Inside); if slot.hovered() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); + painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); - x = mask_rect.right() + 8.0; } - // Blend mode and opacity of the displayed channel, stacked at the right. - let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); - // Name (or rename editor) with the quieter subtitle under it. + x = mask_rect.right() + THUMBNAIL_GAP; + + // Name (or rename editor) with the quieter subtitle under it let (name_rect, show_blend) = layer_name_layout(rect, x); - let show_name = name_rect.width() >= 20.0; + let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { - resp.clone().on_hover_text(&layer.name); + row.clone().on_hover_text(&layer.name); if app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0) { app.ui.rename = None; } } - let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); + let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == layer.id.0); if renaming { - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); - if let Some((_, buf)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. + let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + if let Some((_, text)) = app.ui.rename.as_mut() { + // Escape reaches us instead of just unfocusing the field, so it can cancel let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; - let r = child.add(egui::TextEdit::singleline(buf).desired_width(name_rect.width()).event_filter(filter)); - if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); + if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; - } else if r.lost_focus() { - // Enter or a click elsewhere. - let name = buf.trim().to_string(); + } else if editor.lost_focus() { + // Enter or a click elsewhere + let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { app.run("layer.rename", json!({"layer": layer.id.0, "name": name})); } - } else if !r.has_focus() { - // Only until the field has focus: requesting it every frame kept it from ever - // losing focus, which trapped the editor open and blocked every shortcut. - r.request_focus(); + } else if !editor.has_focus() { + // Only until the field has focus: asking every frame trapped the editor open and blocked every shortcut + editor.request_focus(); } } } else if show_name { - let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let name_color = if layer.visible { tokens.text_strong } else { tokens.text_dim }; + let galley = elided(&painter, layer.name.clone(), LAYER_NAME_FONT_SIZE, name_color, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y - NAME_LINE_GAP - galley.size().y), galley, tokens.text); let kind = tr(match &layer.kind { LayerKind::Paint => "Paint layer", LayerKind::Fill(_) => "Fill layer", LayerKind::Group { .. } => "Folder", LayerKind::Instance { .. } => "Instance", }); - let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |mask| mask.effects.len()); let subtitle = match (source, effects) { - (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (Some(source), _) => format!("{kind} · {} {source}", ic::LINK_SIMPLE), (None, 0) => kind.to_string(), (None, 1) => format!("{kind} · {}", tr("1 effect")), - (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), }; - let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); + let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width()); + painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); } - if let Some(b) = blend.filter(|_| show_blend) { - let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); - if br.hovered() { - p.rect_filled(blend_rect, 2.0, tk.row_hover); + + // Blend mode and opacity of the displayed channel, stacked at the right + let mode_rect = Rect::from_min_size( + pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), + vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), + ); + let opacity_rect = + Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); + if let Some(channel_blend) = blend.filter(|_| show_blend) { + let id = ui.scope_id().with(("blend", layer.id.0)); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (channel_blend.mode, channel_blend.opacity), tr("Blending mode of the displayed channel")); + if let Some(mode) = mode { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } - p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); - egui::Popup::menu(&br).show(|ui| { - ui.set_min_width(190.0); - for m in BlendMode::MENU { - match m { - Some(m) => { - if ui.selectable_label(m == b.mode, tr(m.label())).clicked() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "mode": format!("{m:?}")})); - ui.close(); - } - } - None => { - ui.separator(); - } - } - } - }); - let mut op = (b.opacity * 100.0).round(); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(op_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); - // As tall as its slot in the row (the style's fields are taller), in the row's small print. - child.spacing_mut().interact_size.y = op_rect.height(); - child.spacing_mut().button_padding = vec2(4.0, 0.0); - child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); - if r.changed() { - app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); + if let Some((opacity, merge)) = opacity { + app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "opacity": opacity, "merge": merge})); } } else if show_blend { - p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu. - let on_control = eye_resp.clicked() || content_resp.clicked(); - if resp.clicked() && !on_control && !renaming { + + // Interaction: select, rename, drag & drop, context menu + let on_control = eye_response.clicked() || content_response.clicked(); + if row.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !on_control && !renaming && show_name { + if row.double_clicked() && !on_control && !renaming && show_name { app.ui.rename = Some((layer.id.0, layer.name.clone())); } - if resp.drag_started() && !renaming { - resp.dnd_set_drag_payload(layer.id.0); + if row.drag_started() && !renaming { + row.dnd_set_drag_payload(layer.id.0); } - // Drops: a layer or a shelf material lands above this row (inside a folder when dropped on - // its middle); a shelf smart mask replaces this layer's mask. - let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25); - let shelf = resp.dnd_hover_payload::().map(|d| d.asset.clone()); - let moving = resp.dnd_hover_payload::().is_some_and(|src| *src != layer.id.0); + + // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + let inside = layer.is_group() + && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); + let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); if moving || shelf.as_ref().is_some_and(Asset::is_material) { if inside { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } else { - p.line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } } else if matches!(shelf, Some(Asset::SmartMask(_))) { - p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Outside); + painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { - p.rect_stroke(rect, 2.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } - if let Some(src) = dnd_release::(&resp) - && *src != layer.id.0 + if let Some(dragged) = dnd_release::(&row) + && *dragged != layer.id.0 { - app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside})); + app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); } - match dnd_release::(&resp).map(|d| d.asset.clone()) { - Some(Asset::Material(m)) => { - app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside})); + match dnd_release::(&row).map(|drag| drag.asset.clone()) { + Some(Asset::Material(material)) => { + app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); } Some(Asset::Library(path)) => { app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); } - Some(Asset::SmartMask(m)) => { - app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0})); + Some(Asset::SmartMask(smart_mask)) => { + app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); } - Some(Asset::Filter(f)) => { + Some(Asset::Filter(filter)) => { app.run("layer.select", json!({"layer": layer.id.0})); - app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"})); + app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); } Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {} } - resp.context_menu(|ui| layer_context_menu(app, ui, layer)); + row.context_menu(|ui| layer_context_menu(app, ui, layer)); +} + +/// The border of a content or mask thumbnail: the accent while it is the layer's target. +fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { + if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } } /// What a content thumbnail shows until its picture arrives (or where the layer has none). @@ -721,97 +780,194 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// A stack row's blend mode menu and opacity field (percent): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +fn blend_controls( + ui: &mut Ui, + id: egui::Id, + (mode_rect, opacity_rect): (Rect, Rect), + (mode, opacity): (BlendMode, f32), + hover: &str, +) -> (Option, Option<(f32, bool)>) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter().clone(); + + let mut picked = None; + let menu = ui.interact(mode_rect, id, Sense::click()).on_hover_text(hover); + if menu.hovered() { + painter.rect_filled(mode_rect, ROW_CONTROL_ROUNDING, tokens.row_hover); + } + let mode_font = egui::FontId::proportional(ROW_SMALL_FONT_SIZE); + painter.text(mode_rect.right_center() - vec2(CARET_WIDTH, 0.0), egui::Align2::RIGHT_CENTER, mode.short(), mode_font, tokens.text); + painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_FONT_SIZE), tokens.text_dim); + egui::Popup::menu(&menu).show(|ui| { + ui.set_min_width(BLEND_MENU_MIN_WIDTH); + for item in BlendMode::MENU { + match item { + Some(item) => { + if ui.selectable_label(item == mode, tr(item.label())).clicked() { + picked = Some(item); + ui.close(); + } + } + None => { + ui.separator(); + } + } + } + }); + + let mut percent = (opacity * 100.0).round(); + let mut field_ui = ui.new_child(egui::UiBuilder::new().max_rect(opacity_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); + // As tall as its slot in the row (the style's fields are taller), in the row's small print + field_ui.spacing_mut().interact_size.y = opacity_rect.height(); + field_ui.spacing_mut().button_padding = vec2(ROW_FIELD_PADDING, 0.0); + field_ui.style_mut().override_text_style = Some(egui::TextStyle::Small); + + // Plain text like the blend mode beside it: no field box, only the hover fill + let widgets = &mut field_ui.visuals_mut().widgets; + for state in [&mut widgets.inactive, &mut widgets.noninteractive] { + state.weak_bg_fill = Color32::TRANSPARENT; + state.bg_fill = Color32::TRANSPARENT; + state.bg_stroke = Stroke::NONE; + } + for state in [&mut widgets.hovered, &mut widgets.active] { + state.weak_bg_fill = tokens.row_hover; + state.bg_stroke = Stroke::NONE; + } + let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + (picked, field.changed().then_some((percent / 100.0, merge))) +} + +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. #[allow(clippy::too_many_arguments)] -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { - let tk = Tokens::get(ui.ctx()); - let (eid, visible) = (e.id, e.visible); - let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let size = effect_preview_size(layer_preview_size(app)); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); - let p = ui.painter().clone(); - p.rect_filled( - rect, - 0.0, - if selected { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }, - ); - let indent = effect_row_indent(rect.width(), level, size); - tree_lines(&p, &tk, rect, indent, trunks, !last); +fn effect_row( + app: &mut TextureCraftApp, + ui: &mut Ui, + layer: &Layer, + stack: &[Effect], + effect: &Effect, + level: usize, + trunks: &[usize], + last: bool, + in_mask: bool, +) { + let tokens = Tokens::get(ui.ctx()); + let (effect_id, visible) = (effect.id, effect.visible); + let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(effect_id); + let preview_size = effect_preview_size(layer_preview_size(app)); + let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &effect.name)); + + // Background, tree lines and the selected row's accent edge + let painter = ui.painter().clone(); + // Effect rows alternate two shades just above the panel, counted from the top of their list + let row_index = stack.iter().rev().position(|other| other.id == effect_id).unwrap_or(0); + let background = if selected { + tokens.row_selected + } else if row.hovered() { + tokens.row_hover + } else { + tokens.panel.lerp_to_gamma(tokens.row_hover, EFFECT_ROW_SHADES[row_index % EFFECT_ROW_SHADES.len()]) + }; + painter.rect_filled(rect, 0.0, background); + let indent = effect_row_indent(rect.width(), level, preview_size); + tree_lines(&painter, &tokens, rect, indent, trunks, !last); if selected { - p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, rect.height())), 0.0, tokens.accent); } - let x0 = rect.left() + 7.0 + indent; - let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); - let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - // The stack as it is up to and including this effect; a hidden one shows what it bypasses. - let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); - let ch = app.ui.layer_channel; - if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + + // The eye, then the stack as it is up to and including this effect (a hidden one shows what it bypasses) + let content_left = rect.left() + ROW_LEFT_PADDING + indent; + let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(EYE_SIZE, EYE_SIZE)); + let eye_response = ui.interact(eye, ui.scope_id().with(("eff_eye", effect_id.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); + let eye_glyph = if visible { ic::EYE } else { ic::EYE_SLASH }; + painter.text(eye.center(), egui::Align2::CENTER_CENTER, eye_glyph, egui::FontId::proportional(EYE_FONT_SIZE), tokens.text_dim); + let thumbnail = Rect::from_min_size(pos2(content_left + EYE_COLUMN_WIDTH, rect.center().y - preview_size * 0.5), vec2(preview_size, preview_size)); + let channel = app.ui.layer_channel; + if !thumb_box(ui, app, thumbnail, ThumbTarget::Stage { effect: effect_id, channel }, false) { let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; - p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + painter.text(thumbnail.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(preview_size * 0.5), tokens.text_dim); } - p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border), egui::StrokeKind::Outside); if !visible { - p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - let name_x = thumb.right() + 8.0; - let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); - p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); - if er.clicked() { - app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); - } else if resp.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); + + // The name, then the blend mode and opacity side by side at the right when the name keeps room to be read + let name_left = thumbnail.right() + THUMBNAIL_GAP; + let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_color = if visible { tokens.text } else { tokens.text_dim }; + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); + if show_blend { + let mode_width = EFFECT_BLEND_WIDTH - ROW_CONTROL_GAP - EFFECT_OPACITY_WIDTH; + let mode_rect = Rect::from_center_size(pos2(controls_left + mode_width * 0.5, rect.center().y), vec2(mode_width, ROW_CONTROL_HEIGHT)); + let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); + let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); + let id = ui.scope_id().with(("eff_blend", effect_id.0)); + let (mode, opacity) = blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), tr("Blending mode of the effect")); + if let Some(mode) = mode { + app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); + } + if let Some((opacity, merge)) = opacity { + app.run("effect.set", json!({"effect": effect_id.0, "opacity": opacity, "merge": merge})); + } } - // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half. - if resp.drag_started() { - resp.dnd_set_drag_payload(EffectDrag(eid.0)); + + if eye_response.clicked() { + app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if row.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); } - let pos = |id: u64| stack.iter().position(|x| x.id.0 == id); - let below = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| p.y > rect.center().y); - if resp.dnd_hover_payload::().is_some_and(|src| src.0 != eid.0 && pos(src.0).is_some()) { + + // Drag to reorder within the stack: a drop lands above this row, or below it from its lower half + if row.drag_started() { + row.dnd_set_drag_payload(EffectDrag(effect_id.0)); + } + let position = |id: u64| stack.iter().position(|other| other.id.0 == id); + let below = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| pointer.y > rect.center().y); + if row.dnd_hover_payload::().is_some_and(|dragged| dragged.0 != effect_id.0 && position(dragged.0).is_some()) { let y = if below { rect.bottom() } else { rect.top() }; - p.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(2.0, tk.accent)); + painter.line_segment([pos2(rect.left(), y), pos2(rect.right(), y)], Stroke::new(DROP_LINE_WIDTH, tokens.accent)); } - if let Some(src) = dnd_release::(&resp) - && let (Some(from), Some(to)) = (pos(src.0), pos(eid.0)) + if let Some(dragged) = dnd_release::(&row) + && let (Some(from), Some(to)) = (position(dragged.0), position(effect_id.0)) && from != to { - // Rows list the stack top first, so above this row is the next index up. + // Rows list the stack top first, so above this row is the next index up let index = match (from < to, below) { (true, false) | (false, true) => to, (true, true) => to - 1, (false, false) => to + 1, }; - app.run("effect.move", json!({"effect": src.0, "index": index})); + app.run("effect.move", json!({"effect": dragged.0, "index": index})); } - resp.context_menu(|ui| { + + row.context_menu(|ui| { let keymap = app.ui.keymap.clone(); - // The row is selected before the paste runs, so a copied effect is all it needs. + // The row is selected before the paste runs, so a copied effect is all it needs let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); - // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect. - for (label, id, keys, enabled) in [ + // The clipboard items show the layer clipboard's shortcuts, which act on a selected effect + for (label, command, keys, enabled) in [ (tr("Copy effect"), "effect.copy", Some("layer.copy"), true), (tr("Cut effect"), "effect.cut", Some("layer.cut"), true), (tr("Paste effect"), "effect.paste", Some("layer.paste"), paste), (tr("Duplicate effect"), "effect.duplicate", None, true), (tr("Remove effect"), "effect.remove", None, true), ] { - let mut b = egui::Button::new(label); - if let Some(sc) = keys.and_then(|k| crate::keymap::shortcut_of(&keymap, k)) { - b = b.shortcut_text(sc); + let mut button = egui::Button::new(label); + if let Some(shortcut) = keys.and_then(|key| crate::keymap::shortcut_of(&keymap, key)) { + button = button.shortcut_text(shortcut); } - if ui.add_enabled(enabled, b).clicked() { - // Selected first: a paste lands above it, a duplicate takes the selection. - app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); - app.run(id, json!({"effect": eid.0})); + if ui.add_enabled(enabled, button).clicked() { + // Selected first: a paste lands above it, a duplicate takes the selection + app.run("layer.select", json!({"layer": layer.id.0, "target": effect_id.0})); + app.run(command, json!({"effect": effect_id.0})); ui.close(); } } @@ -1069,7 +1225,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { } /// Menu items listing the image resources, then Import...: the image picked, if any. -fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { +pub(crate) fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { ui.label(caption(tr("Images"))); let mut picked = None; // Bounded, so Import... and the items after it stay on screen with many images. @@ -1092,7 +1248,7 @@ fn image_menu(app: &mut TextureCraftApp, ui: &mut Ui) -> Option { /// An image from the Assets panel dropped on `resp`, outlined while one hovers it. Other assets /// are left for the drop targets around it. -fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { +pub(crate) fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { if !resp.dnd_hover_payload::().is_some_and(|d| matches!(d.asset, Asset::Texture(_))) { return None; } @@ -1103,7 +1259,7 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(map: BakedMap) -> Color32 { +pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), @@ -1910,7 +2066,7 @@ fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { +pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { let p = &app.session.doc.project; let Some((ts, _, _)) = p.locate(reader) else { return Vec::new() }; p.walk(ts) @@ -1922,7 +2078,7 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .collect() } -fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { +pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } @@ -2221,30 +2377,16 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu } } -fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { - let tk = Tokens::get(ui.ctx()); - let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; +/// The properties of effect `effect_id` of `layer`: each kind's own settings. +fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let tokens = Tokens::get(ui.ctx()); + let Some(effect) = app.session.doc.project.effect(effect_id).map(|(_, effect)| effect.clone()) else { return }; - let id = eid.0; - ui.horizontal(|ui| { - ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { - for mode in BlendMode::all() { - if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); - } - } - }); - }); - let mut opacity = effect.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); - } - ui.separator(); + let id = effect_id.0; match &effect.kind { - EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), - EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, eid, levels), + EffectKind::Generator(generator) => crate::generator_panel::generator_properties(app, ui, layer.id, id, generator), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2280,12 +2422,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } }); - ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } _ => {} } if anchors.is_empty() { - ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); } } EffectKind::Material(fill) => { @@ -2297,27 +2439,27 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(caption(tr("Anchor point"))); ui.label( RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|content| content.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") }; - ui.label(RichText::new(hint).color(tk.text_dim)); + ui.label(RichText::new(hint).color(tokens.text_dim)); tool_properties(app, ui); } EffectKind::Path(paths) => { ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) - .color(tk.text_dim), + .color(tokens.text_dim), ); let editing = app.session.tool.path.editing; for index in 0..paths.len() { ui.horizontal(|ui| { - let selected = editing == Some((eid, index)); + let selected = editing == Some((effect_id, index)); if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { if selected { app.run("tool.path", json!({"clear": true})); @@ -2325,7 +2467,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: app.run("path.edit", json!({"effect": id, "index": index})); } } - if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { app.run("path.remove", json!({"effect": id, "index": index})); } }); @@ -2333,86 +2475,13 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: tool_properties(app, ui); } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), - EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance), other => { - ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); + ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); } } } -/// The settings of generator effect `id`. -fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { - for kind in GeneratorKind::ALL { - if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); - } - } - }); - - let (mut level, mut softness, mut noise, mut noise_scale, mut offset, mut invert) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset, generator.invert); - let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); - let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); - let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); - let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit).or(invert_edit) { - app.run( - "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "invert": invert, "merge": merge}), - ); - } - - if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { - curvature_detail_properties(app, ui, id, generator.detail.as_ref()); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); - } -} - -/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). -fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { - let tk = Tokens::get(ui.ctx()); - let shown = detail.cloned().unwrap_or_default(); - combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { - for mode in CurvatureMode::ALL { - if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { - app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); - } - } - }); - - ui.label(caption(tr("Detail sizes"))); - let mut weights = shown.weights; - let mut edit = None; - for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { - edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); - } - if detail.is_none() { - ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); - } -} - -/// The translated name of curvature mode `mode`. -fn curvature_mode_label(mode: CurvatureMode) -> &'static str { - match mode { - CurvatureMode::Edges => tr("Edges"), - CurvatureMode::Cavities => tr("Cavities"), - CurvatureMode::Both => tr("Edges and cavities"), - CurvatureMode::Raw => tr("Raw curvature"), - } -} - /// The filter slot and the parameters of filter effect `id` fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs new file mode 100644 index 00000000..99b93905 --- /dev/null +++ b/crates/ui-egui/src/generator_panel.rs @@ -0,0 +1,385 @@ +//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs. + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source}; + +use crate::TextureCraftApp; +use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::theme::{Tokens, caption}; +use crate::widgets::{combo, section, slider_edit}; + +/// Random seeds stay below this, short enough to read and type. +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. +const SEED_MIX: u32 = 2_654_435_761; + +/// Font size of the notes under a control. +const NOTE_FONT_SIZE: f32 = 10.5; + +/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. +const INPUT_TILE_SIZE: f32 = 32.0; +const INPUT_TILE_ROUNDING: f32 = 2.0; +const INPUT_TILE_ICON_SIZE: f32 = 16.0; + +/// Width of the names in the Attributes section, so their values line up. +const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; + +/// The settings of generator effect `id`. +pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { + let tokens = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Another kind starts from its own defaults: this effect is removed and one of that kind added + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind)); + section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution)); + section(ui, "generator_parameters", tr("Parameters"), true, |ui| { + global_adjustments(app, ui, id, generator); + ramp_parameters(app, ui, id, generator); + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + app.run("effect.set", defaults_of(id, generator.kind)); + } + }); + }); + }); + if !generator.kind.inputs().is_empty() { + section(ui, "generator_inputs", tr("Image inputs"), true, |ui| { + for map in generator.kind.inputs() { + input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some()); + } + }); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label( + RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning), + ); + } +} + +/// What a generator kind makes, its category and its tags (read only). +fn attributes(ui: &mut Ui, kind: GeneratorKind) { + let tokens = Tokens::get(ui.ctx()); + let (description, tags) = match kind { + GeneratorKind::EdgeWear => ( + tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::Dirt => ( + tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")], + ), + GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]), + GeneratorKind::Curvature => ( + tr("Convex edges, cavities or both from the curvature map, at several detail sizes."), + [tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")], + ), + GeneratorKind::AmbientOcclusion => { + (tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")]) + } + GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]), + GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]), + }; + + // Wrapped rows: a long line must not widen the panel past its edge + let tags = tags.join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to. +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) { + let tokens = Tokens::get(ui.ctx()); + combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if resolution.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() { + app.run("effect.set", json!({"effect": id, "customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() { + app.run("effect.set", json!({"effect": id, "resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.resolution) else { return }; + + let size = resolution.output_size(texture_set, texture_set); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(format!("{size} × {size}"))); + }) + .response + .on_hover_text(tr("A finer output than the texture set gives the same result as the texture set's resolution.")); +} + +/// The most powers of two a resolution factor scales by, either way. +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for. +fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// Global invert, blur, balance and contrast: what every generator applies to its finished value. +fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut invert, mut global) = (generator.invert, generator.global); + let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false); + let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2); + let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2); + let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2); + if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) { + app.run( + "effect.set", + json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}), + ); + } +} + +/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed. +fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let (mut level, mut softness, mut noise, mut noise_scale, mut offset) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}), + ); + } + seed_row(app, ui, id, generator.seed); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference. +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { + let typing_id = ui.make_persistent_id(("generator_seed_typing", id)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + // The later changes of one drag continue its first undo step + let merge = field.dragged() && !field.drag_started(); + app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() { + app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// A seed different from `current`, from the clock. +fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +/// The `effect.set` params that put generator effect `id` back to the defaults of its kind. +fn defaults_of(id: u64, kind: GeneratorKind) -> Value { + let defaults = Generator::new(kind); + let mut params = json!({ + "effect": id, + "level": defaults.level, + "softness": defaults.softness, + "noise": defaults.noise_amount, + "noiseScale": defaults.noise_scale, + "offset": defaults.offset, + "seed": defaults.seed, + "direction": defaults.direction, + "invert": defaults.invert, + "blur": defaults.global.blur, + "balance": defaults.global.balance, + "contrast": defaults.global.contrast, + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + if let Some(detail) = defaults.detail { + params["mode"] = json!(format!("{:?}", detail.mode)); + params["sizes"] = json!(detail.weights); + } + params +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tokens = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + +/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again. +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) { + let tokens = Tokens::get(ui.ctx()); + let input = map.id(); + let current = match source { + None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), + Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), + Some(Source::Uniform(_)) => tr("Uniform value").to_string(), + Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Procedural { .. }) => tr("Procedural").to_string(), + }; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + input_tile(app, ui, map, source); + ui.vertical(|ui| { + ui.label(RichText::new(tr(baked_map_label(map))).strong()); + ui.label(RichText::new(¤t).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + }); + }); + combo(ui, tr("Source"), current.clone(), |ui| { + let anchors = anchors_below(app, layer); + if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); + } + if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]})); + } + for (anchor, label) in &anchors { + if ui + .selectable_label( + matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor), + trf("Anchor: {name}", &[("name", label)]), + ) + .clicked() + { + app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0})); + } + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } + }); + if let Some(Source::Uniform(value)) = source { + let mut value = value[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge})); + } + } + if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) { + ui.label( + RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only.")) + .size(NOTE_FONT_SIZE) + .color(tokens.text_dim), + ); + } + }); + if let Some(name) = image_drop(ui, &group.response) { + app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name})); + } +} + +/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list). +fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) { + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover()); + let painter = ui.painter(); + let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + match source { + Some(Source::Image { name, .. }) => match app.session.images.get(name) { + Some(image) => { + let texture = app.thumbs.image(ui.ctx(), name, image); + painter.image(texture.id(), rect, whole, egui::Color32::WHITE); + } + None => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + } + }, + Some(Source::Uniform(value)) => { + painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8)); + } + Some(Source::Anchor { .. } | Source::Procedural { .. }) => { + let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND }; + painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button); + painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim); + } + None => { + let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map)); + painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button }); + } + } + painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..4dd0b5fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -20,6 +20,7 @@ pub mod export_templates; pub mod file_dialogs; mod filter_slot; pub mod fonts; +mod generator_panel; pub mod gpu; pub mod i18n; pub mod id_color_pick; diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 218eb0cc..156b6616 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack. +//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -12,16 +12,16 @@ fn id(v: Value, key: &str) -> u64 { } /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. -fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { - let start = h.get_by_label(from).rect().center(); - let r = h.get_by_label(to).rect(); - let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 }); - h.drag_at(start); - h.run_steps(2); - h.hover_at(end); - h.run_steps(2); - h.drop_at(end); - h.run_steps(3); +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { + let start = harness.get_by_label(from).rect().center(); + let row_rect = harness.get_by_label(to).rect(); + let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.0 }); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); } #[test] @@ -32,17 +32,54 @@ fn dragging_an_effect_row_reorders_its_stack() { |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); - assert_eq!(order(&h), [a, b, c]); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(order(&harness), [a, b, c]); // The rows list the top first: C, B, A. A dropped on C's upper half goes to the top. - drag(&mut h, "Effect A", "Effect C", false); - assert_eq!(order(&h), [b, c, a]); + drag(&mut harness, "Effect A", "Effect C", false); + assert_eq!(order(&harness), [b, c, a]); // A dropped on B's lower half goes back to the bottom. - drag(&mut h, "Effect A", "Effect B", true); - assert_eq!(order(&h), [a, b, c]); + drag(&mut harness, "Effect A", "Effect B", true); + assert_eq!(order(&harness), [a, b, c]); // C dropped on A's upper half lands between A and B. - drag(&mut h, "Effect C", "Effect A", false); - assert_eq!(order(&h), [a, c, b]); + drag(&mut harness, "Effect C", "Effect A", false); + assert_eq!(order(&harness), [a, c, b]); +} + +/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +#[test] +fn an_effect_row_sets_its_blend_mode_and_opacity() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect, effect_of(&harness).id.0); + + // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + let row = harness.get_by_label("Effect A").rect(); + let pair_right = row.right() - 4.0; + let pair_left = pair_right - 82.0; + let mode_at = egui::pos2(pair_left + 20.0, row.center().y); + harness.drag_at(mode_at); + harness.drop_at(mode_at); + harness.run_steps(2); + harness.get_by_label("Multiply").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + + let history = harness.state().session.history_labels().len(); + let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index a26ac303..469edeca 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -1,5 +1,4 @@ -//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged -//! or clicked to. +//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all). use egui::accesskit::Role; use egui_kittest::Harness; @@ -9,79 +8,82 @@ use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; /// The sample session with its first generator effect selected, and that effect's id. -fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { +fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session .doc .project .layers .values() - .find_map(|l| { - let mask = l.mask.iter().flat_map(|m| m.effects.iter()); - l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id)) + .find_map(|label_rect| { + let mask = label_rect.mask.iter().flat_map(|m| m.effects.iter()); + label_rect.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (label_rect.id, e.id)) }) .unwrap(); texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - (h, effect) + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + (harness, effect) } -fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { - h.state().session.doc.project.effect(effect).unwrap().1.opacity +fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.global.balance, + _ => panic!("a generator"), + } } /// The track under the slider labelled `label` (the row below the label). -fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { - let l = h.get_by_label(label).rect(); - egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0)) +fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect { + let label_rect = harness.get_by_label(label).rect(); + egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0)) } #[test] -fn dragging_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - assert_eq!(opacity(&h, effect), 1.0); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect)); +fn dragging_a_slider_applies_it() { + let (mut harness, effect) = selected_generator(); + assert_eq!(balance(&harness, effect), 0.5); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect)); } /// A generator slider applies while it is dragged (the texture follows the pointer), and the /// whole drag is one undo step. #[test] fn dragging_a_generator_slider_applies_live_as_one_undo_step() { - let (mut h, effect) = harness(); - let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind { + let (mut harness, effect) = selected_generator(); + let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { EffectKind::Generator(g) => g.level, _ => panic!("a generator"), }; - let steps = h.state().session.history_labels().len(); - let t = track(&h, "Level"); - let at = |x: f32| egui::pos2(t.left() + x, t.center().y); - h.drag_at(at(10.0)); - h.run_steps(2); + let steps = harness.state().session.history_labels().len(); + let track_rect = track(&harness, "Level"); + let at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y); + harness.drag_at(at(10.0)); + harness.run_steps(2); let mut last = 0.0; for x in [60.0, 160.0] { - h.hover_at(at(x)); - h.run_steps(2); - assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h)); - last = level(&h); + harness.hover_at(at(x)); + harness.run_steps(2); + assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness)); + last = level(&harness); } - h.drop_at(at(160.0)); - h.run_steps(3); - assert_eq!(level(&h), last); - assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + harness.drop_at(at(160.0)); + harness.run_steps(3); + assert_eq!(level(&harness), last); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } /// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Reset").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let row = harness.get_by_label("Reset").rect().center().y; + harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. @@ -90,102 +92,102 @@ fn content_levels_pick_the_histogram_channel() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&h).click(); - h.run_steps(2); - h.get_by_label("Roughness").click(); - h.run_steps(3); - assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays"); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); + channel_picker(&harness).click(); + harness.run_steps(2); + harness.get_by_label("Roughness").click(); + harness.run_steps(3); + assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); } #[test] -fn clicking_the_effect_opacity_applies_it() { - let (mut h, effect) = harness(); - let t = track(&h, "Opacity"); - let at = egui::pos2(t.left() + 20.0, t.center().y); - h.drag_at(at); - h.drop_at(at); - h.run_steps(3); - assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect)); +fn clicking_a_slider_track_applies_it() { + let (mut harness, effect) = selected_generator(); + let track_rect = track(&harness, "Global balance"); + let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } /// The number field in the row of the slider labelled `label`. -fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = h.get_by_label(label).rect().center().y; - h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() } -/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person. -fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { - number_field(h, "Opacity").focus(); - h.run_steps(2); - for k in keys { - h.key_press(*k); - h.run_steps(1); +/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person. +fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) { + number_field(harness, "Global balance").focus(); + harness.run_steps(2); + for key in keys { + harness.key_press(*key); + harness.run_steps(1); } - for c in text.chars() { - number_field(h, "Opacity").type_text(&c.to_string()); - h.run_steps(1); + for character in text.chars() { + number_field(harness, "Global balance").type_text(&character.to_string()); + harness.run_steps(1); } } #[test] fn a_value_typed_in_the_number_field_applies() { - let (mut h, effect) = harness(); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.25); - assert_eq!(h.state().session.history_labels().len(), steps + 1); + let (mut harness, effect) = selected_generator(); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.25); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); } /// Dragging the track while the number field has focus drops what was typed there: leaving the /// field afterwards does not undo the drag. #[test] fn a_track_drag_drops_text_typed_in_the_number_field() { - let (mut h, effect) = harness(); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5"); - let t = track(&h, "Opacity"); - h.drag_at(egui::pos2(t.right(), t.center().y)); - h.run_steps(2); - h.hover_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - h.drop_at(egui::pos2(t.left() + 20.0, t.center().y)); - h.run_steps(2); - let dragged = opacity(&h, effect); - assert!(dragged < 0.5, "the drag applies: {dragged}"); - // Leave whatever has focus: a click on empty space. - h.drag_at(egui::pos2(5.0, 1390.0)); - h.drop_at(egui::pos2(5.0, 1390.0)); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped"); + let (mut harness, effect) = selected_generator(); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5"); + let track_rect = track(&harness, "Global balance"); + harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y)); + harness.run_steps(2); + let dragged = balance(&harness, effect); + assert!(dragged < 0.25, "the drag applies: {dragged}"); + // Leave whatever has focus: a click on empty space + harness.drag_at(egui::pos2(5.0, 1390.0)); + harness.drop_at(egui::pos2(5.0, 1390.0)); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped"); } /// Leaving the number field without typing, or with Escape, keeps the value (not the rounded /// text the field shows) and makes no undo step. #[test] fn leaving_the_number_field_unchanged_keeps_the_value() { - let (mut h, effect) = harness(); - texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap(); - h.run_steps(2); - let steps = h.state().session.history_labels().len(); - type_opacity(&mut h, &[], ""); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333, "left without typing"); - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9"); - assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39")); - assert!(number_field(&h, "Opacity").is_focused()); - h.key_press(egui::Key::Escape); - h.run_steps(3); - assert_eq!(opacity(&h, effect), 0.333); - // Typing the value it already has is no edit either. - type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); - h.key_press(egui::Key::Enter); - h.run_steps(3); - assert_eq!(h.state().session.history_labels().len(), steps); + let (mut harness, effect) = selected_generator(); + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap(); + harness.run_steps(2); + let steps = harness.state().session.history_labels().len(); + type_balance(&mut harness, &[], ""); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333, "left without typing"); + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9"); + assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39")); + assert!(number_field(&harness, "Global balance").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(balance(&harness, effect), 0.333); + // Typing the value it already has is no edit either + type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(harness.state().session.history_labels().len(), steps); } diff --git a/crates/ui-egui/tests/it/generator_panel.rs b/crates/ui-egui/tests/it/generator_panel.rs new file mode 100644 index 00000000..c8afadc9 --- /dev/null +++ b/crates/ui-egui/tests/it/generator_panel.rs @@ -0,0 +1,128 @@ +//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel. +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Generator(generator) => generator.clone(), + _ => panic!("expected a generator"), + } +} + +/// Drags the track under slider `label` to the right. +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0); + let end = start + egui::vec2(120.0, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn global_blur_applies_as_one_undo_step() { + let (mut harness, effect) = harness(false); + let history = harness.state().session.history_labels().len(); + drag_slider(&mut harness, "Global blur"); + assert!(generator(&harness, effect).global.blur > 0.0); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + harness.state_mut().session.undo().unwrap(); + assert_eq!(generator(&harness, effect).global.blur, 0.0); +} + +#[test] +fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() { + let (mut harness, effect) = harness(false); + let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.run_steps(3); + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature)); +} + +#[test] +fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() { + let (mut harness, effect) = harness(false); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me(); + harness.run_steps(3); + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Uniform value").click(); + harness.run_steps(3); + assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_)))); + + harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); + harness.run_steps(2); + harness.get_by_label("Mesh map").click(); + harness.run_steps(3); + assert!(generator(&harness, effect).inputs.is_empty()); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn generator_panel_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, effect) = harness(true); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap(); + + for section in ["Attributes", "Resolution"] { + harness.get_by_label(section).click(); + harness.run_steps(3); + } + harness.run_steps(6); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(3); + harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + + let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap(); + + // The effect row with its blend mode and opacity, in the layer stack + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(12); + harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 7597d587..50e4458e 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -58,9 +58,9 @@ fn mask_and_content_thumbnails_select_their_own_target() { let at = thumb(&h, "Masked fill", false); click(&mut h, at); assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); - // Clicking an effect row still selects that effect. - let r = h.get_by_label("Effect A").rect(); - click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + // Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity) + let row = h.get_by_label("Effect A").rect(); + click(&mut h, row.center()); assert!(matches!(h.state().session.target, StackTarget::Effect(_))); } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..1b467ac7 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -14,6 +14,7 @@ mod file_dialogs; mod fill_channel_image; mod fill_projection_section; mod filter_picker; +mod generator_panel; mod history_panel; mod layer_clipboard; mod layer_rename; From f734b0b96d22f0fecb8cbf48f080913ccaf66f8a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 12 Nov 2026 04:46:54 +0000 Subject: [PATCH 03/22] Effect rows: an opacity drag's first change starts its undo step; the field is named after its row A drag can start without changing the value, so the first change of a drag, not its first frame, opens the undo step. The opacity field's accessible name is "Opacity of" the layer or effect. --- crates/ui-egui/src/dock.rs | 26 +++++++++++++++------ crates/ui-egui/tests/it/effect_rows.rs | 31 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e6ee88ac..00adf00c 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -628,8 +628,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y + ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT)); if let Some(channel_blend) = blend.filter(|_| show_blend) { let id = ui.scope_id().with(("blend", layer.id.0)); - let (mode, opacity) = - blend_controls(ui, id, (mode_rect, opacity_rect), (channel_blend.mode, channel_blend.opacity), tr("Blending mode of the displayed channel")); + let (mode, opacity) = blend_controls( + ui, + id, + (mode_rect, opacity_rect), + (channel_blend.mode, channel_blend.opacity), + (tr("Blending mode of the displayed channel"), &layer.name), + ); if let Some(mode) = mode { app.run("layer.blend", json!({"layer": layer.id.0, "channel": channel.id(), "mode": format!("{mode:?}")})); } @@ -780,13 +785,13 @@ fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, indent: f32, trunks: & /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// A stack row's blend mode menu and opacity field (percent): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. +/// A stack row's blend mode menu and opacity field (percent, named after row `row_name`): the mode picked, and the opacity (0..1) set this frame with whether it continues a drag. fn blend_controls( ui: &mut Ui, id: egui::Id, (mode_rect, opacity_rect): (Rect, Rect), (mode, opacity): (BlendMode, f32), - hover: &str, + (hover, row_name): (&str, &str), ) -> (Option, Option<(f32, bool)>) { let tokens = Tokens::get(ui.ctx()); let painter = ui.painter().clone(); @@ -835,9 +840,15 @@ fn blend_controls( state.bg_stroke = Stroke::NONE; } let field = field_ui.add(egui::DragValue::new(&mut percent).range(0.0..=100.0).speed(OPACITY_DRAG_SPEED).max_decimals(0).suffix("%")); + field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, true, trf("Opacity of {name}", &[("name", &row_name)]))); - // The later changes of one drag continue its first undo step - let merge = field.dragged() && !field.drag_started(); + // A drag's first change starts an undo step and its later changes continue it (a drag can start without a change) + let drag_changed_id = id.with("opacity_drag_changed"); + let drag_changed = !field.drag_started() && ui.data(|data| data.get_temp::(drag_changed_id)).unwrap_or(false); + let merge = field.dragged() && drag_changed; + if field.changed() || field.drag_started() { + ui.data_mut(|data| data.insert_temp(drag_changed_id, field.changed() && field.dragged())); + } (picked, field.changed().then_some((percent / 100.0, merge))) } @@ -910,7 +921,8 @@ fn effect_row( let opacity_center = pos2(mode_rect.right() + ROW_CONTROL_GAP + EFFECT_OPACITY_WIDTH * 0.5, rect.center().y); let opacity_rect = Rect::from_center_size(opacity_center, vec2(EFFECT_OPACITY_WIDTH, ROW_CONTROL_HEIGHT)); let id = ui.scope_id().with(("eff_blend", effect_id.0)); - let (mode, opacity) = blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), tr("Blending mode of the effect")); + let (mode, opacity) = + blend_controls(ui, id, (mode_rect, opacity_rect), (effect.blend, effect.opacity), (tr("Blending mode of the effect"), &effect.name)); if let Some(mode) = mode { app.run("effect.set", json!({"effect": effect_id.0, "blend": format!("{mode:?}")})); } diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 156b6616..9f0a87ff 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -83,3 +83,34 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } + +/// A drag whose first frame leaves the opacity unchanged still starts its own undo step: undo keeps the blend mode set before it +#[test] +fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + + let history = harness.state().session.history_labels().len(); + let opacity_at = harness.get_by_label("Opacity of Effect A").rect().center(); + // Equal right and down movement adds nothing to the value: the drag starts without a change + harness.drag_at(opacity_at); + harness.run_steps(2); + harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); + harness.run_steps(2); + assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(2); + harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); + harness.run_steps(3); + assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); + harness.state_mut().session.undo().unwrap(); + assert_eq!(effect_of(&harness).opacity, 1.0); + assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); +} From 4fd1b33c3c433f4d53484150df4e07d4a8cbd964 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 05:53:14 +0000 Subject: [PATCH 04/22] Use shared MaterialX parser and writer --- Cargo.lock | 37 ++- Cargo.toml | 17 +- crates/formats/Cargo.toml | 1 + crates/formats/src/materialx.rs | 143 ++------- crates/formats/src/materialx_read.rs | 427 +++++---------------------- 5 files changed, 135 insertions(+), 490 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..66ad4529 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +771,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,17 +799,26 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "egui", "serde", "serde_json", ] +[[package]] +name = "craft-materialx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +dependencies = [ + "craft-xml", + "thiserror 2.0.21", +] + [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "craft-keymap", "craft-quit", @@ -822,7 +831,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "dispatch2", "egui", @@ -833,7 +842,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -854,7 +863,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "chrono", "dunce", @@ -881,7 +890,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" dependencies = [ "egui", "objc2 0.6.5", @@ -889,6 +898,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +dependencies = [ + "quick-xml 0.41.0", + "thiserror 2.0.21", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4369,6 +4387,7 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-materialx", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index cb9745b5..5fa07cf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,20 +66,21 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 7b458a53..50654ab8 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true workspace = true [dependencies] +craft-materialx = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/materialx.rs b/crates/formats/src/materialx.rs index e7440328..9481ed13 100644 --- a/crates/formats/src/materialx.rs +++ b/crates/formats/src/materialx.rs @@ -1,20 +1,7 @@ -//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification -//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is -//! linked, and nothing is read from any other application. +//! TextureCraft's MaterialX export adapter. //! -//! [`write`] takes a material's name and the texture files an export produced, each tagged with -//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader -//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones -//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a -//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node -//! (OpenGL, +Y up, which is what that node expects). -//! -//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were -//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `` filename token MaterialX defines. -//! Texture file names are relative to the document. - -use std::collections::HashSet; -use std::fmt::Write as _; +//! The shared `craft-materialx` crate owns the MaterialX document writer. This module maps the +//! built-in preset's map names and TextureCraft color spaces to that format-level API. use texturecraft_texel::ColorSpace; @@ -51,7 +38,6 @@ pub const INPUTS: &[(&str, Kind)] = &[ ("height", Kind::Height), ]; -/// The file-name prefix of the built-in OpenPBR preset's maps. const PREFIX: &str = "$mesh_$textureSet_"; /// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`). @@ -59,14 +45,11 @@ const PREFIX: &str = "$mesh_$textureSet_"; pub struct Texture { pub input: String, pub file: String, - /// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...); - /// used for colour inputs only, data maps are always linear. + /// The MaterialX colour space of the file's values; used for color inputs only. pub colorspace: &'static str, } -/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no -/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the -/// specification, which 1.39 readers may not know. +/// The MaterialX colour space of colour maps written in `space`. pub fn colorspace_name(space: ColorSpace) -> &'static str { match space { ColorSpace::Srgb => "srgb_texture", @@ -76,116 +59,28 @@ pub fn colorspace_name(space: ColorSpace) -> &'static str { } } -/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` → -/// `base_color`), or None for templates this module has no place for. +/// The OpenPBR input a preset map's file template feeds, or None for unsupported templates. pub fn input_of_template(template: &str) -> Option<&'static str> { let suffix = template.strip_prefix(PREFIX)?; - INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n) -} - -fn kind_of(input: &str) -> Option { - INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k) + INPUTS.iter().find(|(name, _)| *name == suffix).map(|(name, _)| *name) } /// A MaterialX name: letters, digits and underscores, not starting with a digit. -pub fn node_name(s: &str) -> String { - let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); +pub fn node_name(name: &str) -> String { + let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) { out.insert(0, '_'); } out } -fn esc(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - for c in s.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - c if c.is_control() => out.push(' '), - c => out.push(c), - } - } - out -} - -fn image_name(input: &str) -> String { - format!("image_{}", node_name(input)) -} - -/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes -/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so -/// are repeats of one input (the first wins). +/// The text of a MaterialX OpenPBR document for `name` and the given texture files. pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String { - let base = node_name(name); - let mut seen = HashSet::new(); - let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect(); - let has = |i: &str| tex.iter().any(|(t, _)| t.input == i); - let mut x = String::new(); - let _ = writeln!(x, ""); - let _ = writeln!(x, ""); - - let shader = format!("OPBR_{base}"); - let _ = writeln!(x, " ", esc(&shader)); - for (t, kind) in &tex { - let (ty, node) = match kind { - Kind::Color => ("color3", image_name(&t.input)), - Kind::Float => ("float", image_name(&t.input)), - Kind::Normal => ("vector3", "normalmap".to_owned()), - Kind::Height => continue, - }; - let _ = writeln!(x, " ", t.input); - } - if has("emission_color") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - - for (t, kind) in &tex { - let (ty, space) = match kind { - Kind::Color => ("color3", Some(t.colorspace)), - Kind::Normal => ("vector3", None), - Kind::Float | Kind::Height => ("float", None), - }; - let node = image_name(&t.input); - let _ = writeln!(x, " "); - match space { - Some(space) => { - let _ = writeln!(x, " ", esc(&t.file)); - } - None => { - let _ = writeln!(x, " ", esc(&t.file)); - } - } - let _ = writeln!(x, " "); - } - if has("geometry_normal") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("geometry_normal")); - let _ = writeln!(x, " "); - } - if has("height") { - let _ = writeln!(x, " "); - let _ = writeln!(x, " ", image_name("height")); - let _ = writeln!(x, " "); - let _ = writeln!(x, " "); - } - - let doc = match physical_size_cm { - Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""), - _ => String::new(), - }; - let _ = writeln!(x, " ", esc(&base)); - let _ = writeln!(x, " ", esc(&shader)); - if has("height") { - let _ = writeln!(x, " "); - } - let _ = writeln!(x, " "); - let _ = writeln!(x, ""); - x + let textures: Vec = textures + .iter() + .map(|texture| craft_materialx::Texture { input: texture.input.clone(), file: texture.file.clone(), colorspace: texture.colorspace.to_owned() }) + .collect(); + craft_materialx::write_open_pbr(name, &textures, physical_size_cm) } #[cfg(test)] @@ -247,7 +142,7 @@ mod tests { assert!(x.contains(want), "missing {want}\n{x}"); } // Data textures carry no colour space, and height is not an OpenPBR input. - assert!(x.contains("value=\"stone_specular_roughness.png\" />")); + assert!(x.contains("value=\"stone_specular_roughness.png\"/>")); assert!(!x.contains("name=\"height\"")); } @@ -265,7 +160,7 @@ mod tests { fn colour_inputs_carry_their_files_space_and_data_inputs_none() { let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) }; let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None); - assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}"); + assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\"/>"), "{x}"); } #[test] @@ -292,7 +187,9 @@ mod tests { assert_eq!(node_name(""), "_"); let x = write("a&\"c", &[tex("base_color", "x\"&<'>..png")], Some([f32::NAN, 1.0])); assert!(balanced(&x.replace("<UDIM>", "UDIM")), "{x}"); - assert!(x.contains("value=\"x"&<'>.<UDIM>.png\"")); + let doc = craft_materialx::Document::parse(x.as_bytes()).unwrap(); + let material = doc.read_material(None).unwrap(); + assert!(material.inputs.iter().any(|(input, value)| input == "base_color" && value == &craft_materialx::Value::Image("x\"&<'>..png".into()))); assert!(!x.contains("doc="), "a non-finite size is left out"); assert!(x.contains("OPBR_a_b___c")); } diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index c8cd8b39..1b3da9ea 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -1,41 +1,16 @@ -//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF -//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure -//! Rust: no MaterialX library is linked. +//! MaterialX material import adapted to TextureCraft's channel model. //! -//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an -//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft -//! has a channel for into a literal value or an image file: -//! -//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted -//! to linear; a colour given for a scalar channel is averaged); -//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph` -//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and -//! `constant` nodes in between are passed through; -//! - the material's `displacementshader` becomes the height channel; -//! - `uvtiling` of the first tiled image is returned as the UV tiling. -//! -//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning -//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing -//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is. -//! -//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a -//! wiring loop stops at a depth limit, and every failure is an error, never a panic. +//! XML parsing, nodegraph traversal and shader input resolution live in `craft-materialx`. +//! This module maps those format-level values to TextureCraft's channels and color handling. -use std::collections::HashMap; - -use quick_xml::events::{BytesStart, Event}; -use texturecraft_core::Channel; +use texturecraft_core::{Channel, ChannelKind}; use texturecraft_texel::srgb_to_linear; use crate::{FormatError, Result, malformed}; const KIND: &str = "MaterialX document"; /// Largest document read, in bytes. -pub const MAX_BYTES: usize = 16 << 20; -const MAX_DEPTH: usize = 64; -const MAX_ELEMENTS: usize = 200_000; -/// Longest chain of nodes followed from one shader input. -const MAX_HOPS: usize = 16; +pub const MAX_BYTES: usize = craft_materialx::MAX_BYTES; /// What one channel is set from. #[derive(Clone, Debug, PartialEq)] @@ -58,259 +33,40 @@ pub struct Material { pub warnings: Vec, } -// --------------------------------------------------------------------------------------------- -// XML. - -#[derive(Default)] -struct El { - name: String, - attrs: Vec<(String, String)>, - children: Vec, +fn channel(shader: craft_materialx::Shader, input: &str) -> Option { + use craft_materialx::Shader::{GltfPbr, OpenPbr, StandardSurface}; + Some(match (shader, input) { + (OpenPbr, "base_color") | (StandardSurface, "base_color") | (GltfPbr, "base_color") => Channel::BaseColor, + (OpenPbr, "base_metalness") | (StandardSurface, "metalness") | (GltfPbr, "metallic") => Channel::Metallic, + (OpenPbr, "specular_roughness") | (StandardSurface, "specular_roughness") | (GltfPbr, "roughness") => Channel::Roughness, + (OpenPbr, "geometry_normal") | (StandardSurface, "normal") | (GltfPbr, "normal") => Channel::Normal, + (OpenPbr, "geometry_opacity") | (StandardSurface, "opacity") | (GltfPbr, "alpha") => Channel::Opacity, + (OpenPbr, "emission_color") | (StandardSurface, "emission_color") | (GltfPbr, "emission") => Channel::Emissive, + (OpenPbr, "coat_weight") | (StandardSurface, "coat") | (GltfPbr, "clearcoat") => Channel::CoatWeight, + (OpenPbr, "coat_roughness") | (StandardSurface, "coat_roughness") | (GltfPbr, "clearcoat_roughness") => Channel::CoatRoughness, + (OpenPbr, "geometry_coat_normal") | (StandardSurface, "coat_normal") | (GltfPbr, "clearcoat_normal") => Channel::CoatNormal, + (OpenPbr, "fuzz_weight") | (StandardSurface, "sheen") => Channel::SheenWeight, + (OpenPbr, "fuzz_color") | (StandardSurface, "sheen_color") | (GltfPbr, "sheen_color") => Channel::SheenColor, + (OpenPbr, "fuzz_roughness") | (StandardSurface, "sheen_roughness") | (GltfPbr, "sheen_roughness") => Channel::SheenRoughness, + (OpenPbr, "specular_roughness_anisotropy") | (StandardSurface, "specular_anisotropy") => Channel::AnisotropyLevel, + (OpenPbr, "transmission_weight") | (StandardSurface, "transmission") | (GltfPbr, "transmission") => Channel::Transmission, + (OpenPbr, "subsurface_weight") | (StandardSurface, "subsurface") => Channel::ScatterWeight, + (GltfPbr, "occlusion") => Channel::AmbientOcclusion, + _ => return None, + }) } -impl El { - fn attr(&self, k: &str) -> Option<&str> { - self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()) +fn constant(channel: Channel, values: &[f32], colorspace: Option<&str>) -> [f32; 3] { + let mut values = values.to_vec(); + if let Some(space) = colorspace + && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) + && values.len() >= 3 + { + values.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); } - - /// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it). - fn input(&self, name: &str) -> Option<&El> { - self.children.iter().find(|c| c.attr("name") == Some(name)) - } -} - -fn element(e: &BytesStart) -> El { - let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e - .attributes() - .with_checks(false) - .flatten() - .map(|a| { - (text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned())) - }) - .collect(); - El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() } -} - -fn parse_xml(bytes: &[u8]) -> Result { - let mut reader = quick_xml::Reader::from_reader(bytes); - let mut stack = vec![El::default()]; - let mut count = 0usize; - loop { - let event = reader.read_event().map_err(|e| malformed(KIND, e))?; - if matches!(event, Event::Start(_) | Event::Empty(_)) { - count += 1; - if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { - return Err(FormatError::TooLarge(format!( - "the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}" - ))); - } - } - match event { - Event::Start(e) => stack.push(element(&e)), - Event::Empty(e) => { - if let Some(parent) = stack.last_mut() { - parent.children.push(element(&e)); - } - } - Event::End(_) => { - let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?; - if let Some(parent) = stack.last_mut() { - parent.children.push(el); - } - } - Event::Eof => break, - _ => {} - } - } - match (stack.pop(), stack.is_empty()) { - (Some(root), true) => Ok(root), - _ => Err(malformed(KIND, "unclosed elements at the end of the document")), - } -} - -// --------------------------------------------------------------------------------------------- -// Shader input tables: (shader input, channel). `kind` says how to read the value. - -#[derive(Clone, Copy, PartialEq)] -enum Shader { - OpenPbr, - Standard, - Gltf, -} - -const OPEN_PBR: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("base_metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("geometry_normal", Channel::Normal), - ("geometry_opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat_weight", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("geometry_coat_normal", Channel::CoatNormal), - ("fuzz_weight", Channel::SheenWeight), - ("fuzz_color", Channel::SheenColor), - ("fuzz_roughness", Channel::SheenRoughness), - ("specular_roughness_anisotropy", Channel::AnisotropyLevel), - ("transmission_weight", Channel::Transmission), - ("subsurface_weight", Channel::ScatterWeight), -]; - -const STANDARD: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metalness", Channel::Metallic), - ("specular_roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("opacity", Channel::Opacity), - ("emission_color", Channel::Emissive), - ("coat", Channel::CoatWeight), - ("coat_roughness", Channel::CoatRoughness), - ("coat_normal", Channel::CoatNormal), - ("sheen", Channel::SheenWeight), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("specular_anisotropy", Channel::AnisotropyLevel), - ("transmission", Channel::Transmission), - ("subsurface", Channel::ScatterWeight), -]; - -const GLTF: &[(&str, Channel)] = &[ - ("base_color", Channel::BaseColor), - ("metallic", Channel::Metallic), - ("roughness", Channel::Roughness), - ("normal", Channel::Normal), - ("alpha", Channel::Opacity), - ("emission", Channel::Emissive), - ("occlusion", Channel::AmbientOcclusion), - ("clearcoat", Channel::CoatWeight), - ("clearcoat_roughness", Channel::CoatRoughness), - ("clearcoat_normal", Channel::CoatNormal), - ("sheen_color", Channel::SheenColor), - ("sheen_roughness", Channel::SheenRoughness), - ("transmission", Channel::Transmission), -]; - -// --------------------------------------------------------------------------------------------- -// Resolving what feeds an input. - -struct Doc<'a> { - root: &'a El, - /// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`). - nodes: HashMap, - /// Each nodegraph's outputs: `graph/output` to the node name inside (qualified). - outputs: HashMap, - tiling: Option<[f32; 2]>, - warnings: Vec, -} - -enum Found { - Constant(Vec), - Image(String), - None, -} - -fn numbers(text: &str) -> Option> { - let v: Option> = text.split(',').map(|p| p.trim().parse::().ok().filter(|f| f.is_finite())).collect(); - v.filter(|v| !v.is_empty() && v.len() <= 4) -} - -impl<'a> Doc<'a> { - fn new(root: &'a El) -> Doc<'a> { - let mut nodes = HashMap::new(); - let mut outputs = HashMap::new(); - for c in &root.children { - match (c.name.as_str(), c.attr("name")) { - ("nodegraph", Some(g)) => { - for n in &c.children { - let Some(name) = n.attr("name") else { continue }; - if n.name == "output" { - if let Some(from) = n.attr("nodename") { - outputs.insert(format!("{g}/{name}"), format!("{g}/{from}")); - } - } else { - nodes.insert(format!("{g}/{name}"), n); - } - } - } - (_, Some(name)) => { - nodes.insert(name.to_owned(), c); - } - _ => {} - } - } - Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() } - } - - /// What `input` (an `` element of a node) resolves to; `scope` is the nodegraph the - /// node lives in, if any. - fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found { - if hops > MAX_HOPS { - self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into()); - return Found::None; - } - if let Some(v) = input.attr("value") { - return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n))); - } - let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) { - (Some(g), out, _) => { - let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned))); - out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned()) - } - (None, _, Some(n)) => { - Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned())) - } - _ => None, - }; - let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None }; - let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned()); - let scope = scope.as_deref(); - match node.name.as_str() { - "tiledimage" | "image" => { - let Some(file) = node.input("file").and_then(|f| f.attr("value")) else { - self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or(""))); - return Found::None; - }; - let prefix = - [node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next(); - if self.tiling.is_none() - && let Some(t) = - node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0)) - { - // The range a fill's UV scale accepts (`layer.fill.projection`). - self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]); - } - Found::Image(format!("{}{file}", prefix.unwrap_or(""))) - } - "normalmap" | "convert" => match node.input("in") { - Some(i) => self.resolve(i, scope, hops + 1), - None => Found::None, - }, - "constant" => match node.input("value") { - Some(v) => self.resolve(v, scope, hops + 1), - None => Found::None, - }, - other => { - self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or(""))); - Found::None - } - } - } - - /// Literal values tagged with an sRGB colour space are converted to linear. - fn tag(&self, input: &El, mut n: Vec) -> Vec { - let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or(""); - if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 { - n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c)); - } - n - } -} - -fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { - match (channel.kind(), n) { + match (channel.kind(), values.as_slice()) { (_, [a]) => [*a; 3], - (texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], + (ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b], (_, [r, g, b, ..]) => { let mean = (r + g + b) / 3.0; [mean; 3] @@ -319,9 +75,11 @@ fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] { } } -/// The literal number of `input`, if it is one. -fn literal(shader: &El, name: &str) -> Option { - shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied()) +fn app_value(channel: Channel, value: craft_materialx::Value) -> Value { + match value { + craft_materialx::Value::Constant { values, colorspace } => Value::Constant(constant(channel, &values, colorspace.as_deref())), + craft_materialx::Value::Image(file) => Value::Image(file), + } } /// Read the material called `material` (default: the first) from a `.mtlx` document. @@ -330,79 +88,30 @@ pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result } fn read_inner(bytes: &[u8], material: Option<&str>) -> Result { - if bytes.len() > MAX_BYTES { - return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20))); - } - let top = parse_xml(bytes)?; - let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no element"))?; - let mut doc = Doc::new(root); - let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect(); - let mat = match material { - Some(name) => materials - .iter() - .copied() - .find(|m| m.attr("name") == Some(name)) - .ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?, - None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?, - }; - let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() }; - let shader = mat - .input("surfaceshader") - .and_then(|i| i.attr("nodename")) - .and_then(|n| doc.nodes.get(n).copied()) - .ok_or_else(|| malformed(KIND, "the material has no surface shader"))?; - let (kind, table) = match shader.name.as_str() { - "open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR), - "standard_surface" => (Shader::Standard, STANDARD), - "gltf_pbr" => (Shader::Gltf, GLTF), - other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))), - }; - // Emission is off by default in OpenPBR and standard_surface. - let emits = match kind { - Shader::OpenPbr => { - shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0)) - } - Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)), - Shader::Gltf => true, - }; - let weight = match kind { - Shader::OpenPbr => literal(shader, "base_weight"), - Shader::Standard => literal(shader, "base"), - Shader::Gltf => None, - }; - if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) { - doc.warnings.push("the base weight isn't 1; it was ignored".into()); - } - for &(input, channel) in table { - let Some(el) = shader.input(input) else { continue }; - if channel == Channel::Emissive && !emits && kind != Shader::Gltf { - doc.warnings.push(format!("{input} was skipped: the shader's emission is 0")); - continue; - } - match doc.resolve(el, None, 0) { - Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))), - Found::Image(f) => out.channels.push((channel, Value::Image(f))), - Found::None => {} + let document = craft_materialx::Document::parse(bytes).map_err(map_error)?; + let shared = document.read_material(material).map_err(map_error)?; + let mut channels = Vec::new(); + for (input, value) in shared.inputs { + if let Some(channel) = channel(shared.shader, &input) { + channels.push((channel, app_value(channel, value))); } } - // The displacement shader's `displacement` input is the height. - if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied()) - && let Some(i) = d.input("displacement") - { - match doc.resolve(i, None, 0) { - Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))), - Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))), - Found::None => {} - } + if let Some(value) = shared.displacement { + channels.push((Channel::Height, app_value(Channel::Height, value))); } - out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]); - out.warnings = doc.warnings; - Ok(out) + Ok(Material { name: shared.name, channels, uv_tiling: shared.uv_tiling, warnings: shared.warnings }) } -fn names(materials: &[&El]) -> String { - let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect(); - if n.is_empty() { "none".into() } else { n.join(", ") } +fn map_error(error: craft_materialx::Error) -> FormatError { + use craft_materialx::Error; + match error { + Error::Xml(xml) if xml.is_limit() => FormatError::TooLarge(xml.to_string()), + Error::MissingMaterial(name) => FormatError::Invalid(format!("no material named {name:?}")), + Error::Unsupported(message) => FormatError::Unsupported(message), + Error::Malformed(message) => malformed(KIND, message), + Error::Root => malformed(KIND, "no element"), + Error::Xml(other) => malformed(KIND, other), + } } #[cfg(test)] @@ -456,6 +165,24 @@ mod tests { assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale"); } + #[test] + fn nodegraph_input_without_output_uses_the_first_output() { + let xml = r#" + + + + + + + + +"#; + for _ in 0..50 { + let material = read_materialx(xml.as_bytes(), None).unwrap(); + assert_eq!(get(&material, Channel::BaseColor), Some(&Value::Image("first.png".into()))); + } + } + #[test] fn emission_is_off_unless_the_shader_emits() { let x = OPENPBR.replace(r#""#, ""); From bf25c1c5364260012c499e6b6f682c5d0eb3b739 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:33:26 +0000 Subject: [PATCH 05/22] Move TextureCraft STL parsing to craft-mesh --- Cargo.lock | 6 ++ Cargo.toml | 1 + crates/formats/Cargo.toml | 1 + crates/formats/src/mesh_import/stl.rs | 114 ++++++++++-------------- crates/formats/src/mesh_import/tests.rs | 17 ++++ 5 files changed, 73 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66ad4529..1efde862 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -828,6 +828,11 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748" + [[package]] name = "craft-quit" version = "0.1.0" @@ -4388,6 +4393,7 @@ version = "0.6.1" dependencies = [ "base64 0.22.1", "craft-materialx", + "craft-mesh", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 5fa07cf3..cc958885 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 50654ab8..d78d4d7a 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-materialx = { workspace = true } +craft-mesh = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index 9b39bf2c..fd288a27 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -1,78 +1,60 @@ -//! STL (binary and ascii). Facets keep their own corners, so shading is flat; there are no UVs. +//! STL (binary and ASCII), read by the shared bounded mesh importer. -use texturecraft_geom::glam::Vec3; +use texturecraft_geom::glam::{Vec3, Vec4}; use super::{RawMesh, check_triangles}; -use crate::{Result, malformed}; +use crate::{FormatError, Result}; const KIND: &str = "STL"; pub(crate) fn read(bytes: &[u8]) -> Result { - let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); - let binary_len = count.and_then(|c| c.checked_mul(50)).and_then(|n| n.checked_add(84)); - let looks_ascii = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i..i + 5)) == Some(b"solid".as_slice()); - let tris = match (count, binary_len) { - // Exact size wins: many binary files also start with "solid". - (Some(c), Some(len)) if len == bytes.len() => binary(bytes, c)?, - _ if looks_ascii => ascii(bytes)?, - (Some(c), Some(len)) if len < bytes.len() => binary(bytes, c)?, - _ => return Err(malformed(KIND, "neither a complete binary STL nor an ascii STL")), - }; + let scene = craft_mesh::stl::read(bytes, &craft_mesh::Limits::default()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); - check_triangles(0, tris.len())?; - let mut normals = Vec::with_capacity(tris.len() * 3); - for t in &tris { - let n = (t[1] - t[0]).cross(t[2] - t[0]).try_normalize().unwrap_or(Vec3::Y); - raw.positions.extend_from_slice(t); - normals.extend_from_slice(&[n; 3]); + raw.warnings = scene.warnings; + + let mut tri_count = 0; + let mut vertex_colors = Vec::new(); + let has_colors = !scene.materials.is_empty(); + for mesh in scene.meshes { + // The shared model groups colored facets into parts. Position indices still reflect + // source order, so merge the parts back into STL order for TextureCraft's raw mesh. + let mut triangles = Vec::new(); + for part in mesh.parts { + let material = part.material.and_then(|i| scene.materials.get(i)); + let color = material.map(|m| Vec4::from_array(m.base_color)); + for tri in part.triangles() { + let first_position = tri.iter().map(|c| c.position).min().unwrap_or(u32::MAX); + triangles.push((first_position, tri, color)); + } + } + triangles.sort_by_key(|(first_position, _, _)| *first_position); + for (_, tri, color) in triangles { + check_triangles(tri_count, 1)?; + tri_count += 1; + let mut points = [Vec3::ZERO; 3]; + for (i, corner) in tri.into_iter().enumerate() { + let p = mesh.positions.get(corner.position as usize).ok_or_else(|| FormatError::Invalid(format!("{KIND}: position index out of range")))?; + points[i] = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32); + } + // Recompute per-facet normals as TextureCraft's old importer did; stored STL + // normals are often zero or disagree with the vertex winding. + let normal = (points[1] - points[0]).cross(points[2] - points[0]).try_normalize().unwrap_or(Vec3::Y); + raw.positions.extend_from_slice(&points); + raw.normals.get_or_insert_with(Vec::new).extend_from_slice(&[normal; 3]); + if has_colors { + // The shared reader normalizes STL's color extensions to linear RGBA. + // Uncolored facets alongside colored ones receive its neutral gray material. + let color = color.unwrap_or(Vec4::new(0.6, 0.6, 0.6, 1.0)); + vertex_colors.extend_from_slice(&[color; 3]); + } + } + } + if raw.positions.is_empty() { + return Err(crate::malformed(KIND, "no facets")); + } + if has_colors { + raw.colors = Some(vertex_colors); } - raw.normals = Some(normals); raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } - -fn binary(bytes: &[u8], count: usize) -> Result> { - check_triangles(0, count)?; - let mut out = Vec::with_capacity(count); - for i in 0..count { - let f = |k: usize| -> Result { - let o = 84 + i * 50 + 12 + k * 4; - let b = bytes.get(o..o + 4).ok_or_else(|| malformed(KIND, "truncated facet"))?; - Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - }; - let v = |c: usize| -> Result { Ok(Vec3::new(f(c * 3)?, f(c * 3 + 1)?, f(c * 3 + 2)?)) }; - out.push([v(0)?, v(1)?, v(2)?]); - } - Ok(out) -} - -fn ascii(bytes: &[u8]) -> Result> { - let text = std::str::from_utf8(bytes).map_err(|_| malformed(KIND, "ascii STL is not text"))?; - let mut out = Vec::new(); - let mut facet: Vec = Vec::new(); - let mut words = text.split_whitespace(); - while let Some(w) = words.next() { - match w { - "vertex" => { - let mut c = [0.0f32; 3]; - for v in &mut c { - let tok = words.next().ok_or_else(|| malformed(KIND, "truncated vertex"))?; - *v = tok.parse().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")))?; - } - facet.push(Vec3::from(c)); - } - "endfacet" => { - for i in 1..facet.len().saturating_sub(1) { - check_triangles(out.len(), 1)?; - out.push([facet[0], facet[i], facet[i + 1]]); - } - facet.clear(); - } - _ => {} - } - } - if out.is_empty() { - return Err(malformed(KIND, "no facets")); - } - Ok(out) -} diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index e55f8eae..80078488 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -372,6 +372,23 @@ fn stl_ascii_and_binary() { assert_eq!(import_mesh_bytes("c.stl", &b).unwrap().mesh.triangle_count(), 2); } +#[test] +fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() { + let mut bytes = stl_binary(); + // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. + bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // Some exporters leave the header count at zero despite having facets. + bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); + let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); + assert_eq!(imported.mesh.triangle_count(), 2); + assert_eq!(imported.mesh.submeshes.len(), 1); + assert_eq!(imported.mesh.submeshes[0].name, "colored"); + assert_eq!(imported.mesh.positions.len(), 6); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 6]); + assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); + assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); +} + /// Every prefix and some corruptions of a valid file: errors, never panics (and never an /// error from the panic guard, which would mean a parser panicked). pub(crate) fn hammer(name: &str, good: &[u8]) { From 1bf3707aeca5a5ca902277f5dd61363811d56617 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 13 Nov 2026 06:41:49 +0000 Subject: [PATCH 06/22] Cover interleaved STL color part order --- crates/formats/src/mesh_import/tests.rs | 26 ++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 80078488..ef592129 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -377,14 +377,34 @@ fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() let mut bytes = stl_binary(); // VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14. bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes()); + // A third facet repeats that color after an uncolored facet. The shared reader groups its + // parts by color, so the adapter must restore the source facet order. + bytes.extend([0.0f32; 3].iter().flat_map(|v| v.to_le_bytes())); + for v in [[0.0f32, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]] { + bytes.extend(v.iter().flat_map(|x| x.to_le_bytes())); + } + bytes.extend(0xfc00u16.to_le_bytes()); // Some exporters leave the header count at zero despite having facets. bytes[80..84].copy_from_slice(&0u32.to_le_bytes()); let imported = import_mesh_bytes("colored.stl", &bytes).unwrap(); - assert_eq!(imported.mesh.triangle_count(), 2); + assert_eq!(imported.mesh.triangle_count(), 3); assert_eq!(imported.mesh.submeshes.len(), 1); assert_eq!(imported.mesh.submeshes[0].name, "colored"); - assert_eq!(imported.mesh.positions.len(), 6); - assert_eq!(imported.mesh.normals, vec![Vec3::Z; 6]); + assert_eq!( + imported.mesh.positions, + vec![ + Vec3::ZERO, + Vec3::X, + Vec3::new(1.0, 1.0, 0.0), + Vec3::ZERO, + Vec3::new(1.0, 1.0, 0.0), + Vec3::Y, + Vec3::Z, + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0) + ] + ); + assert_eq!(imported.mesh.normals, vec![Vec3::Z; 9]); assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01)); assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets"))); } From 75502053dbbb3577056d0f3e241a05d611f7ef7f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 04:18:22 -0500 Subject: [PATCH 07/22] formats: stop copying whole OBJ and glTF inputs before parsing (#503) * formats: stop copying whole OBJ and glTF inputs before parsing * formats: format the mesh-import copy changes --- crates/formats/src/mesh_import/gltf.rs | 8 ++++---- crates/formats/src/mesh_import/obj.rs | 11 ++++++++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 136e3e0c..92e52f72 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -28,9 +28,9 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { let (json, blob) = if bytes.starts_with(b"glTF") { let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?; let blob = glb.bin.take().map(std::borrow::Cow::into_owned); - (glb.json.into_owned(), blob) + (glb.json, blob) } else { - (bytes.to_vec(), None) + (std::borrow::Cow::Borrowed(bytes), None) }; let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?; if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) { @@ -40,8 +40,8 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option>)> { } } } - let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?; - let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?; + // Consume the DOM directly rather than serialising it back to a second full-size buffer. + let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?; let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?; Ok((document, blob)) } diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 2f284704..bf949625 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -1,5 +1,7 @@ //! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn. +use std::io::{BufReader, Read}; + use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::{RawMesh, check_triangles, check_vertices}; @@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result { } let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); - let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); + let prefix = "mtllib texturecraft-usemtl.mtl\n"; + + // Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a + // whole-file copy nor an extra string is needed before tobj parses it. + let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes())); // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; - let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; + let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); From e89799153365731247b21bd696fac733029d81fe Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 09:59:44 +0000 Subject: [PATCH 08/22] test: allow instrumented high-DPI preview to settle --- crates/ui-egui/tests/it/shelf_hover_preview.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c7ad071a..64a997e2 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -155,6 +155,11 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { check_high_dpi_orb_hover(1, "Steel Painted Worn"); } +// Coverage instrumentation makes the 512px software-rendered preview substantially slower. +fn high_dpi_worker_timeout() -> Duration { + if std::env::var_os("LLVM_PROFILE_FILE").is_some() { Duration::from_secs(600) } else { WORKER_TIMEOUT } +} + fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; @@ -166,7 +171,7 @@ fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { let expected = Some([MAX_PREVIEW_SIZE_PX; 2]); let started = Instant::now(); - while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < WORKER_TIMEOUT { + while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < high_dpi_worker_timeout() { harness.run_steps(1); std::thread::sleep(Duration::from_millis(20)); } From 5f008e72728849aab3573b69a9736e740862585a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:21:25 +0000 Subject: [PATCH 09/22] Preserve TextureCraft STL vertex limits --- crates/formats/src/mesh_import/stl.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index fd288a27..e087b711 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -2,13 +2,13 @@ use texturecraft_geom::glam::{Vec3, Vec4}; -use super::{RawMesh, check_triangles}; +use super::{MAX_VERTICES, RawMesh, check_triangles}; use crate::{FormatError, Result}; const KIND: &str = "STL"; pub(crate) fn read(bytes: &[u8]) -> Result { - let scene = craft_mesh::stl::read(bytes, &craft_mesh::Limits::default()).map_err(|e| FormatError::Invalid(e.to_string()))?; + let scene = craft_mesh::stl::read(bytes, &stl_limits()).map_err(|e| FormatError::Invalid(e.to_string()))?; let mut raw = RawMesh::default(); raw.warnings = scene.warnings; @@ -58,3 +58,18 @@ pub(crate) fn read(bytes: &[u8]) -> Result { raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); Ok(raw) } + +/// STL stores three positions per facet; retain the app's established triangle capacity. +fn stl_limits() -> craft_mesh::Limits { + craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() } +} + +#[cfg(test)] +mod tests { + #[test] + fn shared_reader_accepts_the_app_vertex_limit() { + let limits = super::stl_limits(); + assert_eq!(limits.max_vertices, super::MAX_VERTICES); + assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES); + } +} From d7e534a6575ca844ea332156c8d7d645ae3880c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 10:24:24 +0000 Subject: [PATCH 10/22] Recognize explicit coverage compiler flags --- crates/ui-egui/tests/it/shelf_hover_preview.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index 64a997e2..a18f3404 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -157,7 +157,11 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() { // Coverage instrumentation makes the 512px software-rendered preview substantially slower. fn high_dpi_worker_timeout() -> Duration { - if std::env::var_os("LLVM_PROFILE_FILE").is_some() { Duration::from_secs(600) } else { WORKER_TIMEOUT } + if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + WORKER_TIMEOUT + } } fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) { From 32380b0dc53b0791195b9f24d031ab3b1737b091 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:05:14 +0000 Subject: [PATCH 11/22] Preserve MaterialX displacement tiling --- Cargo.lock | 23 ++++++++++++----------- Cargo.toml | 18 +++++++++--------- crates/formats/src/materialx_read.rs | 13 +++++++++++++ 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1efde862..8368bc88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +771,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,7 +799,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "serde", @@ -809,7 +809,7 @@ dependencies = [ [[package]] name = "craft-materialx" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-xml", "thiserror 2.0.21", @@ -818,7 +818,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-keymap", "craft-quit", @@ -836,7 +836,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89 [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "dispatch2", "egui", @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -868,7 +868,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "chrono", "dunce", @@ -895,7 +895,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "egui", "objc2 0.6.5", @@ -906,9 +906,10 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b8f70b46ee0c5fbfd552cbe2a4dae68652519153#b8f70b46ee0c5fbfd552cbe2a4dae68652519153" +source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" dependencies = [ "quick-xml 0.41.0", + "serde", "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index cc958885..09fada6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,22 +66,22 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["serde"] } -craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } +craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). -craft-window = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "b8f70b46ee0c5fbfd552cbe2a4dae68652519153" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/crates/formats/src/materialx_read.rs b/crates/formats/src/materialx_read.rs index 1b3da9ea..4de6abce 100644 --- a/crates/formats/src/materialx_read.rs +++ b/crates/formats/src/materialx_read.rs @@ -148,6 +148,19 @@ mod tests { m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v) } + #[test] + fn displacement_only_image_supplies_uv_tiling() { + let xml = br#" + + + + + "#; + let material = read_materialx(xml, None).unwrap(); + assert_eq!(get(&material, Channel::Height), Some(&Value::Image("height.png".into()))); + assert_eq!(material.uv_tiling, [4.0, 2.0]); + } + #[test] fn open_pbr_inputs_become_channels() { let m = read_materialx(OPENPBR.as_bytes(), None).unwrap(); From 0d90953467314de4fd30baa10ab6a8a2869d064a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 11:44:04 +0000 Subject: [PATCH 12/22] Share portable materials and preserve SBS links --- Cargo.lock | 23 +++ Cargo.toml | 2 + crates/engine/src/link_cmds.rs | 58 ++++++- crates/engine/tests/it/materialcraft_link.rs | 44 ++++- crates/formats/Cargo.toml | 2 + crates/formats/src/mcmat.rs | 167 +++++++++---------- crates/ui-egui/src/dock.rs | 3 +- docs/architecture.md | 4 +- docs/control-protocol.md | 9 +- 9 files changed, 205 insertions(+), 107 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bcd091ae..63034cc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -806,6 +806,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-mcmat" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +dependencies = [ + "craft-zip", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-menu" version = "0.1.0" @@ -889,6 +900,16 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4369,6 +4390,8 @@ name = "texturecraft-formats" version = "0.6.1" dependencies = [ "base64 0.22.1", + "craft-mcmat", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index cb9745b5..86b75667 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr # MIT OR Apache-2.0, pinned to one rev. # Shared catalog lookup, pinned with the other Craft libraries. craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index e5122cd9..459d72e5 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { "Save MaterialCraft package", [], None, - "{layer?, path} — writes the MaterialCraft package (.mcraft) behind a material layer, to open in MaterialCraft", + "{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer", has_layer, save_source ), @@ -178,7 +178,9 @@ fn save_source(s: &mut Session, p: &Value) -> Result { const CMD: &str = "material.link.saveSource"; let id = layer_param(s, CMD, p)?; let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?; - let path = if path.to_ascii_lowercase().ends_with(&format!(".{MCRAFT_EXT}")) { path.to_string() } else { format!("{path}.{MCRAFT_EXT}") }; + let link = link_of(s, CMD, id)?; + let ext = source_extension(&link.package); + let path = if path.to_ascii_lowercase().ends_with(&format!(".{ext}")) { path.to_string() } else { format!("{path}.{ext}") }; let bytes = s.link_package(id)?; texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad(CMD, e.to_string()))?; Ok(json!({"path": path})) @@ -195,6 +197,10 @@ fn save_source(_: &mut Session, _: &Value) -> Result { pub struct LinkJob { pub layer: LayerId, pub package: Arc>, + /// The source package extension (`mcraft` or `sbs`). + pub source_ext: &'static str, + /// The named graph in a linked material; direct package imports use its default. + pub graph: Option, /// Pixels across (the texture set's resolution). pub size: u32, /// Every parameter's value, by id, in MaterialCraft's typed form. @@ -226,7 +232,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command { c } -/// Open `package` (a `.mcraft` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this +/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this /// program, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { @@ -236,6 +242,11 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { }) } +/// Source file extensions are chosen from the linked resource name, never an untrusted path. +pub fn source_extension(name: &str) -> &'static str { + if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT } +} + impl LinkJob { /// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). @@ -252,7 +263,8 @@ impl LinkJob { std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?; utf8(&p) }; - let src = write("source.mcraft", &self.package)?; + let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT }; + let src = write(&format!("source.{ext}"), &self.package)?; let mut inputs = Map::new(); for (i, (id, png)) in self.inputs.iter().enumerate() { inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?)); @@ -260,7 +272,19 @@ impl LinkJob { let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let run = quiet(&cli).arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()).output().map_err(|e| { + let mut command = quiet(&cli); + if let Some(graph) = &self.graph { + // Opening the source starts on its first graph; select the graph saved in the link. + let script = json!({"open": src, "steps": [ + {"id": "graph.open", "params": {"graph": graph}}, + {"id": "file.exportMaterial", "params": params}, + ]}); + let script_path = write("cook.json", script.to_string().as_bytes())?; + command.arg("batch").arg(script_path); + } else { + command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()); + } + let run = command.output().map_err(|e| { other(format!( "MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI", cli.display() @@ -301,7 +325,15 @@ impl Session { let bytes = if is_mcraft(bytes) { let ts = self.ts(); let size = self.doc.project.texture_set(ts)?.resolution; - let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes.to_vec()), size, values: Map::new(), inputs: Vec::new() }; + let job = LinkJob { + layer: LayerId(0), + package: Arc::new(bytes.to_vec()), + source_ext: MCRAFT_EXT, + graph: None, + size, + values: Map::new(), + inputs: Vec::new(), + }; cooked = job.run()?; cooked.as_slice() } else { @@ -316,7 +348,7 @@ impl Session { let (id, names) = self.edit(&label, |s| { let ts = s.ts(); let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name); - let package = unique(s, &format!("{stem}.{MCRAFT_EXT}")); + let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source))); s.doc.resources.insert(package.clone(), Arc::new(m.source.clone())); let link = MaterialLink { name: m.manifest.name.clone(), @@ -345,7 +377,7 @@ impl Session { Ok(id) } - /// The `.mcraft` package behind linked layer `id`. + /// The source package behind linked layer `id`. pub fn link_package(&self, id: LayerId) -> Result>> { let link = link_of(self, "material.link", id)?; self.doc.resources.get(&link.package).cloned().ok_or_else(|| EngineError::Other(format!("the package of {} is missing", link.name))) @@ -376,7 +408,15 @@ impl Session { // UDIM tiles share one cook at the texture set's base resolution let size = self.doc.project.texture_set(texture_set)?.resolution; - Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs }) + Ok(LinkJob { + layer: id, + package: self.link_package(id)?, + source_ext: source_extension(&link.package), + graph: Some(link.graph.clone()), + size, + values, + inputs, + }) } /// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with. diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index ac86d775..5dd63e02 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -21,9 +21,14 @@ fn session() -> Session { /// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`. fn mcmat(roughness: f32, wear: f32) -> Vec { + mcmat_version(roughness, wear, 1) +} + +fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec { + let source = if version == 2 { "source.sbs" } else { "source.mcraft" }; let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap(); let manifest = json!({ - "format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], + "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [ {"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}, {"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"}, @@ -42,7 +47,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { {"identifier": "bentNormal", "kind": "color"} ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], - "source": "source.mcraft" + "source": source }); let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -51,7 +56,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { ("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()), ("maps/roughness.png", gray(roughness)), ("maps/ambientOcclusion.png", gray(1.0)), - ("source.mcraft", b"package bytes".to_vec()), + (source, b"package bytes".to_vec()), ] { z.start_file(name, o).unwrap(); z.write_all(&bytes).unwrap(); @@ -81,6 +86,18 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String { } } +#[test] +fn version_two_preserves_the_sbs_source_for_future_cooks() { + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap(); + let linked = link(&session, id); + assert!(linked.package.ends_with(".sbs")); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.source_ext, "sbs"); + assert_eq!(job.graph.as_deref(), Some("Brick_wall")); + assert_eq!(job.package.as_slice(), b"package bytes"); +} + #[test] fn imports_as_a_linked_fill_with_its_maps() { let mut s = session(); @@ -199,7 +216,7 @@ fn cooks_through_materialcraft_cli_when_available() { let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let pkg = dir.join("bricks.mcraft"); - let ok = std::process::Command::new(&cli).args(["new", "bricks"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); + let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap(); assert!(ok.success()); let exposed = dir.join("exposed.mcraft"); let ok = std::process::Command::new(&cli) @@ -217,9 +234,24 @@ fn cooks_through_materialcraft_cli_when_available() { assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution"); assert!(link(&s, id).params.iter().any(|p| p.id == "wear")); execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap(); - assert_eq!(link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value, json!({"t": "float", "v": 0.8})); - let out = dir.join("back.mcraft"); + let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap(); + assert!((wear - 0.8).abs() < 1e-6); + let out = dir.join("back.sbs"); execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap(); assert!(std::fs::metadata(&out).unwrap().len() > 0); + + // The portable material can name a graph other than the first in the embedded source. + let multi = dir.join("multi.mcraft"); + let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap(); + assert!(ok.success()); + let portable = dir.join("second.mcmat"); + let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()}); + let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap(); + assert!(ok.success()); + let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap(); + let expected_graph = link(&s, second).graph; + let job = s.link_job(second, &serde_json::Map::new()).unwrap(); + let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap(); + assert_eq!(result.manifest.graph, expected_graph); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 7b458a53..040e6b84 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -9,6 +9,8 @@ license.workspace = true workspace = true [dependencies] +craft-mcmat = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 1976c73b..5040f320 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -1,11 +1,11 @@ //! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the //! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/.png` -//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the source -//! `.mcraft` package. TextureCraft keeps its own reader (the apps share the format, not code). +//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the +//! source package. The shared reader handles the portable container and manifest. //! //! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs. -use std::io::{Cursor, Read}; +use std::io::Cursor; use serde::Deserialize; use texturecraft_core::{LinkParam, LinkPreset}; @@ -16,8 +16,7 @@ use crate::{FormatError, Result}; pub const MCMAT_EXT: &str = "mcmat"; /// MaterialCraft's package extension. pub const MCRAFT_EXT: &str = "mcraft"; -const FORMAT: &str = "craft-material"; -const VERSION: u32 = 1; +const VERSION: u32 = 2; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; /// Most map entries one manifest may name (a material has at most nine usages). @@ -70,68 +69,76 @@ fn malformed(msg: impl Into) -> FormatError { FormatError::Malformed { kind: KIND, msg: msg.into() } } -fn read_entry(name: &str, entry: impl Read, total_bytes: &mut u64) -> Result> { - // Earlier maps remain live while the next entry is read - let remaining_bytes = MAX_TOTAL.saturating_sub(*total_bytes); - let entry_limit = MAX_ENTRY.min(remaining_bytes); - let mut bytes = Vec::new(); - entry.take(entry_limit + 1).read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?; - if bytes.len() as u64 > MAX_ENTRY { - return Err(FormatError::TooLarge(name.to_string())); +fn shared_error(error: craft_mcmat::Error) -> FormatError { + match error { + craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")), + craft_mcmat::Error::Limit(message) => malformed(message), + craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()), + other => malformed(other.to_string()), } - - let next_total = total_bytes.saturating_add(bytes.len() as u64); - if next_total > MAX_TOTAL { - return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)"))); - } - - // Keep spare read capacity from accumulating across retained map entries - bytes.shrink_to_fit(); - *total_bytes = next_total; - - Ok(bytes) } -/// Read `.mcmat` bytes. +/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits. pub fn read_mcmat(bytes: &[u8]) -> Result { - let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| malformed(error.to_string()))?; - let mut total_bytes = 0u64; - let mut read = |name: &str| -> Result> { - let entry = archive.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; - read_entry(name, entry, &mut total_bytes) + let limits = craft_mcmat::Limits { + min_version: 0, + max_version: VERSION, + max_entries: 100_000, + max_maps: MAX_MAPS, + max_manifest_bytes: MAX_ENTRY, + max_entry_bytes: MAX_ENTRY, + max_total_bytes: MAX_TOTAL, }; - - let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|error| malformed(format!("material.json: {error}")))?; - if manifest.format != FORMAT { - return Err(malformed(format!("format `{}`", manifest.format))); - } - - if manifest.version > VERSION { - return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); - } - - if manifest.maps.len() > MAX_MAPS { - return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len()))); - } - - let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), read(&map.file)?))).collect::>>()?; - let source = read(&manifest.source)?; - + let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?; + // Consume the JSON values rather than cloning the entire untrusted manifest into a second tree. + let parameters = std::mem::take(&mut archive.manifest.parameters) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let inputs = std::mem::take(&mut archive.manifest.inputs) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let presets = std::mem::take(&mut archive.manifest.presets) + .into_iter() + .map(serde_json::from_value) + .collect::>() + .map_err(|e| malformed(format!("material.json: {e}")))?; + let shared = &archive.manifest; + let manifest = Manifest { + format: shared.format.clone(), + version: shared.version, + name: shared.name.clone(), + graph: shared.graph.clone(), + size: shared.size, + maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(), + parameters, + inputs, + presets, + source: shared.source.clone(), + }; + let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::>>()?; + let source = archive.read_source().map_err(shared_error)?; Ok(PortableMaterial { manifest, maps, source }) } -/// Whether `bytes` are a zip holding `entry` (`material.json`: a portable material, -/// `package.json`: a MaterialCraft package). -fn zip_has(bytes: &[u8], entry: &str) -> bool { - zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(entry).is_ok()) -} - +/// Whether `bytes` contain a portable material manifest within the ZIP entry limit. pub fn is_mcmat(bytes: &[u8]) -> bool { - zip_has(bytes, "material.json") + craft_mcmat::is_material(bytes, 100_000) } pub fn is_mcraft(bytes: &[u8]) -> bool { - zip_has(bytes, "package.json") + let Ok(mut archive) = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 100_000, max_total_bytes: 0 }) else { return false }; + // A portable material may itself contain source.sbs, so it is not a source archive. + if archive.has_duplicate_names() || archive.contains("material.json") { + return false; + } + if archive.contains("package.json") { + return true; + } + (0..archive.len()).any(|i| archive.entry_name(i).ok().flatten().is_some_and(|name| !name.contains('/') && name.to_ascii_lowercase().ends_with(".sbs"))) } /// A baked mesh map (`components` floats per texel, 0..1, rows top first) as a 16-bit PNG @@ -161,13 +168,14 @@ mod tests { /// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`). pub(crate) fn sample(version: u32) -> Vec { + let source = if version >= 2 { "source.sbs" } else { "source.mcraft" }; let manifest = serde_json::json!({ "format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4], "maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}], "parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}], "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}], - "source": "source.mcraft", "futureField": true + "source": source, "futureField": true }); let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); let o = zip::write::SimpleFileOptions::default(); @@ -175,7 +183,7 @@ mod tests { z.write_all(manifest.to_string().as_bytes()).unwrap(); z.start_file("maps/baseColor.png", o).unwrap(); z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); - z.start_file("source.mcraft", o).unwrap(); + z.start_file(source, o).unwrap(); z.write_all(b"pkg").unwrap(); z.finish().unwrap().into_inner() } @@ -195,15 +203,29 @@ mod tests { assert_eq!(material.maps[0].0, "baseColor"); assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4); assert_eq!(material.source, b"pkg"); - assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_)))); + let current = read_mcmat(&sample(2)).unwrap(); + assert_eq!(current.manifest.source, "source.sbs"); + assert_eq!(current.source, b"pkg"); + assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_)))); assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() { + for entry in ["package.json", "package.sbs"] { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"source").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + assert!(is_mcraft(&bytes), "{entry}"); + } + assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too"); + } + #[test] fn an_unbounded_map_list_is_refused() { let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); - let manifest = - serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); let options = zip::write::SimpleFileOptions::default(); archive.start_file("material.json", options).unwrap(); @@ -218,31 +240,6 @@ mod tests { assert!(matches!(result, Err(FormatError::Malformed { .. }))); } - #[test] - fn entry_read_stops_at_the_remaining_payload_budget() { - let payload = vec![7u8; 1024]; - let mut input = Cursor::new(&payload); - let mut total_bytes = MAX_TOTAL - 8; - - let result = read_entry("maps/extra.png", &mut input, &mut total_bytes); - - assert!(matches!(result, Err(FormatError::TooLarge(_)))); - assert_eq!(input.position(), 9, "only one byte beyond the remaining budget is needed to reject the entry"); - assert_eq!(total_bytes, MAX_TOTAL - 8, "a rejected entry does not consume the payload budget"); - } - - #[test] - fn payload_budget_accepts_the_exact_limit_and_empty_entries() { - let mut total_bytes = MAX_TOTAL - 4; - - let bytes = read_entry("map.png", Cursor::new([1, 2, 3, 4]), &mut total_bytes).unwrap(); - - assert_eq!(bytes, [1, 2, 3, 4]); - assert_eq!(total_bytes, MAX_TOTAL); - assert!(read_entry("empty.mcraft", Cursor::new([]), &mut total_bytes).unwrap().is_empty()); - assert!(matches!(read_entry("extra.png", Cursor::new([1]), &mut total_bytes), Err(FormatError::TooLarge(_)))); - } - #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 1d266ee1..fcce9071 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1828,7 +1828,8 @@ fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: app.cook_link(layer); } if ui.button(tr("Open in MaterialCraft")).clicked() { - let path = std::env::temp_dir().join(format!("{}.mcraft", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); let opened = app .session .link_package(layer) diff --git a/docs/architecture.md b/docs/architecture.md index 2ddcd76b..8d5deb43 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -121,10 +121,10 @@ on the CPU by `render::displace` from the composited height. A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the -`.mcraft` package as a resource, and re-cooks by running `materialcraft-cli` with the link's +`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded -image cache never disagree. The apps share the file format and the command line, never code. +image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app. ## Commands and automation diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f255a509..0ead3445 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -325,8 +325,9 @@ of a second. A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the -graph's exposed inputs, presets and image inputs. The apps share the format and the command line, -not code. +graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container. +Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current +MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version. | Command | Params | |---|---| @@ -334,9 +335,9 @@ not code. | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | | `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | -| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` package, to open in MaterialCraft | +| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft | -Re-cooks run `materialcraft-cli run file.exportMaterial {path, size, values, inputs}`: +Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs: `$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, From f40dc84f72da5e1d23730db3222186b9967133f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:28:11 +0000 Subject: [PATCH 13/22] Use shared streaming project tile payloads --- Cargo.lock | 21 +++ Cargo.toml | 2 + crates/formats/Cargo.toml | 2 + .../formats/src/project_file/load_budget.rs | 14 +- crates/formats/src/project_file/mod.rs | 160 +++++------------- crates/formats/src/project_file/tests.rs | 10 +- 6 files changed, 81 insertions(+), 128 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8368bc88..16ef0634 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -844,6 +844,15 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-tcraft" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +dependencies = [ + "craft-zip", + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" @@ -913,6 +922,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -4395,6 +4414,8 @@ dependencies = [ "base64 0.22.1", "craft-materialx", "craft-mesh", + "craft-tcraft", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 09fada6a..a7682daa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,6 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index d78d4d7a..5569b475 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [dependencies] craft-materialx = { workspace = true } craft-mesh = { workspace = true } +craft-tcraft = { workspace = true } +craft-zip = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs index 284c4d64..a183336a 100644 --- a/crates/formats/src/project_file/load_budget.rs +++ b/crates/formats/src/project_file/load_budget.rs @@ -13,14 +13,18 @@ impl LoadBudget { self.limit_bytes - self.used_bytes } + pub(super) fn exceeded_message(&self) -> String { + format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + ) + } + /// Reserve bytes before retaining decoded data so entries share one allocation budget. pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { if bytes > self.remaining() { - return Err(format!( - "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", - self.limit_bytes, - self.limit_bytes as f64 / (1u64 << 30) as f64, - )); + return Err(self.exceeded_message()); } self.used_bytes += bytes; diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index ff7a7b3a..5862e436 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -43,9 +43,11 @@ pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_re pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; const KIND: &str = "project file"; +#[cfg(test)] const MAGIC: &[u8; 4] = b"TCTX"; -/// Version of the `.bin` layout. +#[cfg(test)] const BIN_VERSION: u32 = 1; +#[cfg(test)] const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; @@ -124,6 +126,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError { } } +#[cfg(test)] fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { let mut b = MAGIC.to_vec(); for v in [BIN_VERSION, w, h, comps as u32, count as u32] { @@ -132,19 +135,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec { b } -fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { - w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?; - let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8); - for (tx, ty) in img.allocated() { - buf.clear(); - buf.extend_from_slice(&tx.to_le_bytes()); - buf.extend_from_slice(&ty.to_le_bytes()); - for v in img.tile(tx, ty).unwrap_or_default() { - buf.extend_from_slice(&v.to_le_bytes()); - } - w.write_all(&buf)?; +fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error { + match error { + craft_tcraft::Error::Io(error) => error, + other => std::io::Error::other(other), } - Ok(()) +} + +fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> { + let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() }; + let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?; + let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default())); + craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error) } /// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension). @@ -169,18 +171,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -/// Floats converted to bytes at a time when a baked map streams into the compressor. +#[cfg(test)] const BAKED_CHUNK: usize = 1 << 16; fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { - w.write_all(&header(res, h, comps, 0))?; - let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); - for chunk in data.chunks(BAKED_CHUNK) { - buf.clear(); - buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); - w.write_all(&buf)?; - } - Ok(()) + let layout = craft_tcraft::Layout { width: res, height: h, components: comps }; + craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error) } /// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. @@ -304,110 +300,34 @@ fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &st Ok(out) } -/// Decode bounded chunks so a false header cannot allocate an entire missing map. -fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result> { - let mut values = Vec::new(); - let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4]; - let mut remaining = count; - while remaining > 0 { - let chunk_values = BAKED_CHUNK.min(remaining); - let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?; - read_exact(reader, chunk, what)?; - values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?; - values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); - remaining -= chunk_values; - } - - Ok(values) -} - -fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { - r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) -} - -fn u32_at(b: &[u8], i: usize) -> u32 { - b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0) -} - -/// Read and check a `.bin` header: returns (width, height, comps, count). -fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; BIN_HEADER_BYTES]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); - } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); - } - Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize)) -} - -/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC). -fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { - let mut b = [0u8; 1]; - match r.read(&mut b) { - Ok(0) => Ok(()), - Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))), - Err(e) => Err(malformed(KIND, format!("{what}: {e}"))), - } +/// Transfer the bytes charged by the shared codec to this project's one load budget. +fn codec_result(result: std::result::Result, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(shared.used()).map_err(FormatError::TooLarge)?; + result.map_err(|error| match error { + craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()), + craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")), + craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION }, + other => malformed(KIND, format!("{what}: {other}")), + }) } fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, count) = read_header(reader, what)?; - if (width, height) != size || stored_components != components { - return Err(malformed( - KIND, - format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1), - )); - } - - let mut image = TileImage::new(width, height, components); - if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) { - return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); - } - - let mut bytes = vec![0u8; TILE_AREA * components * 2]; - let mut position_bytes = [0u8; 8]; - for _ in 0..count { - budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?; - read_exact(reader, &mut position_bytes, what)?; - let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); - if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { - return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); - } - - read_exact(reader, &mut bytes, what)?; - let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); - image.set_tile(tx, ty, Some(Arc::new(data))); - } - - expect_end(reader, what)?; - - Ok(image) + let layout = craft_tcraft::Layout { width: size.0, height: size.1, components }; + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let mut image = None; + let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| { + image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values))); + Ok(()) + }); + codec_result(result, &shared, budget, what)?; + Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components))) } -/// A baked map: (width, height, data). fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { - budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; - let (width, height, stored_components, _) = read_header(reader, what)?; - if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { - return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); - } - - let value_count = u64::from(width) * u64::from(height) * components as u64; - let payload_bytes = value_count * 4; - if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes { - return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map"))); - } - - budget.take(payload_bytes).map_err(FormatError::TooLarge)?; - let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?; - let data = read_f32s(reader, value_count, what)?; - expect_end(reader, what)?; - - Ok((width, height, data)) + let mut shared = craft_zip::Budget::new("project", budget.remaining()); + let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared); + let (layout, values) = codec_result(result, &shared, budget, what)?; + Ok((layout.width, layout.height, values)) } /// Texture set holding a paint layer, a content effect or a mask effect id. diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 93a58a9a..b48f2a7c 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -803,13 +803,17 @@ fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { #[test] fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); - let bytes: Vec = values.iter().flat_map(|bits| bits.to_le_bytes()).collect(); + let mut bytes = header(values.len() as u32, 1, 1, 0); + bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes())); + let declared = bytes.len() as u64; let mut reader = Cursor::new(bytes); + let mut budget = LoadBudget::new(declared); - let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap(); + let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap(); assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); - assert_eq!(reader.position(), (values.len() * 4) as u64); + assert_eq!(reader.position(), declared); + assert_eq!(budget.remaining(), 0); } #[test] From 1d0f9665f99466a26008602fd99396d0af570ca6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:46:12 +0000 Subject: [PATCH 14/22] Use shared project version parser --- Cargo.lock | 6 ++++-- Cargo.toml | 4 ++-- crates/formats/src/project_file/mod.rs | 10 +++------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 16ef0634..acf9f9b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,9 +847,11 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" dependencies = [ "craft-zip", + "serde", + "serde_json", "thiserror 2.0.21", ] @@ -925,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=5f46c0ab25f067f6fdb863c7e1f9ff567712f394#5f46c0ab25f067f6fdb863c7e1f9ff567712f394" +source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a7682daa..0b3672a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "5f46c0ab25f067f6fdb863c7e1f9ff567712f394" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 5862e436..7cbacad0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -376,13 +376,9 @@ fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result check_archive(&mut zip, budget.remaining())?; let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; - #[derive(serde::Deserialize)] - struct Version { - format_version: u32, - } - let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; - if v.format_version > FORMAT_VERSION { - return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION }); + let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + if version > FORMAT_VERSION { + return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION }); } let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; From b02a3ab44a9adcc9bf857e1044ed3311bb25eee5 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:56:36 +0000 Subject: [PATCH 15/22] Exercise linked material cooks under coverage --- crates/engine/src/link_cmds.rs | 59 +++++++++++++++++++- crates/engine/tests/it/materialcraft_link.rs | 6 ++ crates/ui-egui/src/preview_worker.rs | 8 ++- 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 459d72e5..3a77ae50 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -252,6 +252,11 @@ impl LinkJob { /// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K). #[cfg(not(target_arch = "wasm32"))] pub fn run(&self) -> Result> { + self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI")) + } + + #[cfg(not(target_arch = "wasm32"))] + fn run_with_cli(&self, cli: &std::path::Path) -> Result> { let other = |e: String| EngineError::Other(e); let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id())); @@ -271,8 +276,7 @@ impl LinkJob { } let out = dir.join(format!("out.{MCMAT_EXT}")); let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs}); - let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"); - let mut command = quiet(&cli); + let mut command = quiet(cli); if let Some(graph) = &self.graph { // Opening the source starts on its first graph; select the graph saved in the link. let script = json!({"open": src, "steps": [ @@ -496,3 +500,54 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec, texturecraft } names } + +#[cfg(all(test, unix))] +mod subprocess_tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn cook_uses_the_saved_graph_and_source_type_without_global_environment() { + let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cli = dir.join("materialcraft-cli"); + let script = r#"#!/bin/sh +set -eu +case "$1" in + batch) + grep -F '"graph":"Second"' "$2" >/dev/null + grep -F '"id":"file.exportMaterial"' "$2" >/dev/null + test -f "$(dirname "$2")/source.sbs" + test -f "$(dirname "$2")/input0.png" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + run) + test "$(basename "$2")" = "source.mcraft" + cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat" + ;; + *) exit 1 ;; +esac +"#; + std::fs::write(&cli, script).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap(); + let mut job = LinkJob { + layer: LayerId(1), + package: Arc::new(b"source".to_vec()), + source_ext: "sbs", + graph: Some("Second".into()), + size: 64, + values: Map::new(), + inputs: vec![("curvature".into(), b"png".to_vec())], + }; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = None; + job.source_ext = "mcraft"; + assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked"); + job.graph = Some("wrong".into()); + assert!(job.run_with_cli(&cli).is_err()); + assert!(job.run_with_cli(&dir.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 5dd63e02..cbe75532 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -96,6 +96,12 @@ fn version_two_preserves_the_sbs_source_for_future_cooks() { assert_eq!(job.source_ext, "sbs"); assert_eq!(job.graph.as_deref(), Some("Brick_wall")); assert_eq!(job.package.as_slice(), b"package bytes"); + let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id())); + let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap(); + let path = saved["path"].as_str().unwrap(); + assert!(path.ends_with(".sbs")); + assert_eq!(std::fs::read(path).unwrap(), b"package bytes"); + let _ = std::fs::remove_file(path); } #[test] diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index c979e3e4..e58901b4 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -206,7 +206,13 @@ mod tests { let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { + // Instrumented orb baking can take several minutes on coverage runners. + let timeout = if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) { + Duration::from_secs(600) + } else { + Duration::from_secs(120) + }; + while answers.len() < requests_sent && start.elapsed() < timeout { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } From 4864fbbc78b48762a3dc8223f5f824928409fc78 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:01:22 +0000 Subject: [PATCH 16/22] Test shared schema against native project documents --- crates/formats/src/project_file/tests.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index b48f2a7c..95beac51 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,15 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn shared_project_schema_round_trips_the_app_document() { + let project = sample().pf.project; + let original = serde_json::to_value(&project).unwrap(); + let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap(); + assert_eq!(document.format_version, project.format_version); + assert_eq!(serde_json::to_value(document).unwrap(), original); +} + #[test] fn legacy_bakes_load_as_is_without_layout_conversion() { let mut sample = sample(); From 267eff5c1e3e0fe6f34a282525764172192e9481 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:08:27 +0000 Subject: [PATCH 17/22] Pin merged shared material format --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c45a767d..5a2b05d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,7 +818,7 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=26980ff331efa6ec2cb2b9093dc5a154a8f66bdb#26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" +source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index f0c79815..28c1404c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,8 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "26980ff331efa6ec2cb2b9093dc5a154a8f66bdb" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). From 6028051a400e3748ac046e20670f47623c0f90c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:44:48 +0000 Subject: [PATCH 18/22] Update shared project schema pin --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index acf9f9b8..111b6612 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" +source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b85e4b150#b85e4b150b7e427b1fd3c88b4ed9e6aba055053c" +source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 0b3672a6..2a45cfb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b85e4b150" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } From 0e218bd23ee0dd76283aeede29c4abf50d404419 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:51:20 +0000 Subject: [PATCH 19/22] Use shared seekable ZIP archive checks --- Cargo.lock | 4 +- Cargo.toml | 4 +- .../src/project_file/metadata_reader.rs | 81 ------------------- crates/formats/src/project_file/mod.rs | 35 +++----- crates/formats/src/project_file/tests.rs | 11 +-- 5 files changed, 17 insertions(+), 118 deletions(-) delete mode 100644 crates/formats/src/project_file/metadata_reader.rs diff --git a/Cargo.lock b/Cargo.lock index 111b6612..4b848b5c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -847,7 +847,7 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" +source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d2c1cac03#d2c1cac0324491bd67f6e3b583a5dffb18bf78eb" +source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2a45cfb2..e1284fde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,8 +69,8 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "d2c1cac03" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/crates/formats/src/project_file/metadata_reader.rs b/crates/formats/src/project_file/metadata_reader.rs deleted file mode 100644 index 7e82825c..00000000 --- a/crates/formats/src/project_file/metadata_reader.rs +++ /dev/null @@ -1,81 +0,0 @@ -use std::cell::Cell; -use std::io::{self, Read, Seek, SeekFrom}; - -/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access. -pub(super) struct MetadataReader<'a, R> { - reader: R, - metadata_only: &'a Cell, - metadata_start: u64, - remaining_bytes: u64, - position: u64, -} - -impl<'a, R: Read + Seek> MetadataReader<'a, R> { - pub(super) fn new(mut reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> io::Result { - let end = reader.seek(SeekFrom::End(0))?; - Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end }) - } -} - -impl Read for MetadataReader<'_, R> { - fn read(&mut self, bytes: &mut [u8]) -> io::Result { - if bytes.is_empty() { - return Ok(0); - } - - let metadata_only = self.metadata_only.get(); - if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) { - return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit")); - } - - let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() }; - let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?; - self.position = self.position.saturating_add(read as u64); - if metadata_only { - self.remaining_bytes -= read as u64; - } - - Ok(read) - } -} - -impl Seek for MetadataReader<'_, R> { - fn seek(&mut self, position: SeekFrom) -> io::Result { - self.position = self.reader.seek(position)?; - Ok(self.position) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Cursor; - - #[test] - fn indexing_cannot_read_payloads_outside_the_metadata_window() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap(); - reader.seek(SeekFrom::Start(91)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - reader.seek(SeekFrom::Start(92)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - - metadata_only.set(false); - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 100]).unwrap(); - } - - #[test] - fn repeated_metadata_scans_share_one_read_allowance() { - let metadata_only = Cell::new(true); - let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap(); - for _ in 0..2 { - reader.seek(SeekFrom::Start(0)).unwrap(); - reader.read_exact(&mut [0; 8]).unwrap(); - } - reader.seek(SeekFrom::Start(0)).unwrap(); - - assert!(reader.read(&mut [0; 1]).is_err()); - } -} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 7cbacad0..e1d98196 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,7 +18,6 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). -use std::cell::Cell; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; @@ -31,12 +30,10 @@ use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; use self::load_budget::LoadBudget; -use self::metadata_reader::MetadataReader; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; mod load_budget; -mod metadata_reader; mod project_open_limit; #[cfg(not(target_arch = "wasm32"))] pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; @@ -342,37 +339,25 @@ fn load(reader: R) -> Result { } fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { - if zip.len() > MAX_ENTRIES { - return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); - } - - // Count every declared payload, including ignored entries, before any decompression - let mut declared_budget = LoadBudget::new(limit_bytes); - for index in 0..zip.len() { - let entry = zip.by_index_raw(index).map_err(zip_err)?; - declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?; - } - - // Shared compressed ranges can amplify one payload into many apparent files - if zip.has_overlapping_entries().map_err(zip_err)? { - return Err(malformed(KIND, "overlapping ZIP entries are not supported")); - } - - Ok(()) + craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error { + craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")), + craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()), + craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"), + craft_zip::InspectError::Zip(error) => zip_err(error), + }) } -fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> Result>> { - let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?; +fn open_archive(reader: R, metadata_bytes: u64) -> Result>> { + let (reader, indexing) = craft_zip::MetadataReader::new(reader, metadata_bytes)?; // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; - metadata_only.set(false); + indexing.finish(); Ok(archive) } fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { - let metadata_only = Cell::new(true); - let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?; + let mut zip = open_archive(reader, MAX_ZIP_METADATA_BYTES)?; check_archive(&mut zip, budget.remaining())?; let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 95beac51..4fcc0aed 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -831,23 +831,19 @@ fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); writer.write_all(&vec![7; 1 << 20]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), 4096).unwrap(); let mut first_byte = [0; 1]; archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); assert_eq!(first_byte, [7]); - assert!(!metadata_only.get()); let mut writer = ZipWriter::new(Cursor::new(Vec::new())); writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); writer.write_all(&[7]).unwrap(); let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err()); - assert!(metadata_only.get(), "failed indexing must not enable payload access"); + assert!(open_archive(Cursor::new(bytes), 4096).is_err()); } #[test] @@ -858,9 +854,8 @@ fn zip64_entry_counts_remain_supported_and_bounded() { writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); } let bytes = writer.finish().unwrap().into_inner(); - let metadata_only = Cell::new(true); - let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap(); + let mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap(); let result = check_archive(&mut archive, 0); assert_eq!(archive.len(), count); From b1cdd044874623f78c39da3ed9912b50768f56c7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 15:47:19 +0000 Subject: [PATCH 20/22] Adopt shared ZIP64 entry-count guard fix --- Cargo.lock | 4 ++-- Cargo.toml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5a2b05d4..d63a2ff2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,7 +818,7 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "craft-zip", "serde", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 28c1404c..65ce6e99 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,8 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). From e1d4f99da1262d34b324808848602702f1846bdf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 16:48:44 +0000 Subject: [PATCH 21/22] Pin shared project codecs to merged craft-libs --- Cargo.lock | 22 ++++++---------------- Cargo.toml | 6 +++--- 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2f687131..ba685c21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -818,9 +818,9 @@ dependencies = [ [[package]] name = "craft-mcmat" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -858,9 +858,9 @@ dependencies = [ [[package]] name = "craft-tcraft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833)", + "craft-zip", "serde", "serde_json", "thiserror 2.0.21", @@ -938,17 +938,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833#2cf13ea7c6920f3674e0fd5c362852e77c5cf833" -dependencies = [ - "flate2", - "thiserror 2.0.21", - "zip", -] - -[[package]] -name = "craft-zip" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b6d9feed23ceae249b40593ed84a668343091627#b6d9feed23ceae249b40593ed84a668343091627" +source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83" dependencies = [ "flate2", "thiserror 2.0.21", @@ -4439,7 +4429,7 @@ dependencies = [ "craft-mcmat", "craft-mesh", "craft-tcraft", - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=2cf13ea7c6920f3674e0fd5c362852e77c5cf833)", + "craft-zip", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 9493c02b..3d25ee21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,10 +69,10 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "2cf13ea7c6920f3674e0fd5c362852e77c5cf833" } +craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } -craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "b6d9feed23ceae249b40593ed84a668343091627" } +craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). From 0d18d7afb71955e133a8c9b81b89cb8b64ab0b5d Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Sun, 15 Nov 2026 20:32:35 +0100 Subject: [PATCH 22/22] Add mesh replacement backend and reimport safeguards (#230) Add file.changeMesh for trusted local callers while preserving layers, remembered mesh paths, imported images and bake resources. Retain unchanged-layout paint preservation, cache/cage invalidation and stale-bake cancellation safeguards. The temporary Change mesh menu entry is removed. The Project Configuration 3D Mesh UI will follow separately. Contributor: @vangel76. Validated by fresh Ubuntu and Windows CI at the exact head-equivalent tree; QA confirmed the new dependency inputs and named backend/safety regressions. --- crates/engine/src/file_cmds.rs | 110 +++++++++++++++++++++++ crates/engine/src/preserve.rs | 67 +++++++++++++- crates/engine/tests/it/bake.rs | 39 ++++++++ crates/ui-egui/src/bake_job.rs | 2 + crates/ui-egui/src/lib.rs | 11 ++- crates/ui-egui/src/updates_ui.rs | 2 +- crates/ui-egui/tests/bake_preview.rs | 2 + crates/ui-egui/tests/it/bake_job_mesh.rs | 43 +++++++++ crates/ui-egui/tests/it/main.rs | 1 + docs/features.md | 3 +- 10 files changed, 275 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/tests/it/bake_job_mesh.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index a728fd6c..e4d17f53 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -37,6 +37,15 @@ pub fn specs() -> Vec { always, reimport ), + cmd!( + "file.changeMesh", + "Change mesh", + [], + None, + "{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index", + always, + change_mesh + ), cmd!( "file.exportTextures", "Export textures", @@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result { Ok(reply) } +#[cfg(not(target_arch = "wasm32"))] +fn change_mesh(s: &mut Session, p: &Value) -> Result { + let path = native::path_param(p, "path", "file.changeMesh")?; + let file = native::read_mesh("file.changeMesh", path)?; + let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?; + // Only after the swap succeeded: Reimport mesh and Save keep following the new file. + s.doc.project.mesh_path = native::absolute(path); + Ok(reply) +} + #[cfg(not(target_arch = "wasm32"))] impl Session { /// The file the mesh was imported from, when it is still there: what Reimport mesh reads again. @@ -471,6 +490,19 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.sync_images(); + // The high polys and the skew map stay. The cage is sampled by triangle index and + // barycentrics, so it stays only for an identical mesh; the low poly's base colours are + // read again from the new mesh. + next.bake_meshes = self.bake_meshes.clone(); + next.bake_meshes.low_base_color = Default::default(); + if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.bake_meshes.cage = None; + next.log.push("the cage mesh was dropped: the low-poly mesh changed".into()); + } + if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { + next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into()); + } next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -621,6 +653,8 @@ use unsupported as save_copy; #[cfg(target_arch = "wasm32")] use unsupported as reimport; #[cfg(target_arch = "wasm32")] +use unsupported as change_mesh; +#[cfg(target_arch = "wasm32")] use unsupported as export_textures; #[cfg(target_arch = "wasm32")] use unsupported as export_mesh; @@ -764,6 +798,82 @@ f 1/1 2/2 3/3 let _ = std::fs::remove_dir_all(&dir); } + /// A project built on one mesh moves to another mesh file with its layers intact, even when + /// it carries its own copy of the mesh (a plain reimport would only re-read that copy). + #[test] + fn change_mesh_swaps_the_mesh_and_keeps_the_layers() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let quad = dir.join("quad.obj"); + std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap(); + let tri = dir.join("tri.obj"); + std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layers = s.doc.project.layers.len(); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap(); + assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use"); + assert_eq!(s.doc.project.mesh_file, "tri.obj"); + assert_eq!(s.doc.project.layers.len(), layers, "the layers stay"); + std::fs::remove_dir_all(&dir).ok(); + } + + /// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B, + /// not A. A failed change leaves the remembered path alone. + #[test] + fn change_mesh_remembers_the_new_file_for_reimport() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"); + let (a, b) = (dir.join("a.obj"), dir.join("b.obj")); + std::fs::write(&a, obj(1.0)).unwrap(); + std::fs::write(&b, obj(2.0)).unwrap(); + let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max); + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap(); + let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap(); + // A failed change (unreadable file) keeps A. + let missing = dir.join("missing.obj"); + assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err()); + assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str())); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert_eq!(width(&s), 2.0); + let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered"); + assert_ne!(a_abs, b_abs); + // The remembered path survives save and reopen. + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str())); + // Edit B, then Reimport from the remembered path: B's edits arrive, not A. + std::fs::write(&b, obj(3.0)).unwrap(); + let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap(); + crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap(); + assert_eq!(width(&reopened), 3.0); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() { + let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let a = dir.join("a.obj"); + std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + // Same triangle count, other vertices. + let b = dir.join("b.obj"); + std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); + let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.bake_meshes.cage = Some(cage); + let _ = s.bake_meshes.low_base_color.set(Err("old".into())); + // The same mesh again keeps the cage but not the cached colours. + crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_some()); + assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); + assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + std::fs::remove_dir_all(&dir).ok(); + } + #[test] fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() { // A GLB quad whose mesh and node have no name: its one part is named after the file. diff --git a/crates/engine/src/preserve.rs b/crates/engine/src/preserve.rs index 38544edc..d68f20bc 100644 --- a/crates/engine/src/preserve.rs +++ b/crates/engine/src/preserve.rs @@ -16,8 +16,14 @@ use crate::Session; const REACH: f32 = 0.05; /// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s -/// document) from `old`'s UV layout. Returns how many texels found the old surface. +/// document) from `old`'s UV layout. Returns how many texels found the old surface; +/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the +/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already +/// sit where they belong, however far the mesh moved. pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { + if same_layout(&old.mesh, &next.mesh) { + return 0; + } let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius()); let mut found = 0; for ts in 0..next.set_count() { @@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { ((tx, ty), src) }) .collect(); - found += table.values().flatten().filter(|p| p[0].is_finite()).count(); + let matched = table.values().flatten().filter(|p| p[0].is_finite()).count(); + found += matched; + // No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is. + if matched == 0 { + continue; + } let map = |x: f32, y: f32| { let (xi, yi) = (x as u32, y as u32); table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1])) @@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize { found } +/// Same index buffer, same UVs per vertex and the same material ranges. +fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool { + let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::>(); + a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b) +} + #[cfg(test)] mod tests { use super::*; @@ -104,4 +121,50 @@ mod tests { } assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong"); } + + #[test] + fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..64 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout + // shortcut is not taken): nothing of the old surface is within reach. + let mut mesh = (*s.mesh).clone(); + for p in &mut mesh.positions { + p.x += 100.0; + } + for uv in &mut mesh.uvs { + *uv = Vec2::new(1.0 - uv.x, uv.y); + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there"); + } + + #[test] + fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() { + let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); + let id = s.doc.project.texture_sets[0].stack[0]; + let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128)); + for x in 0..128 { + img.set(x, 40, &[65535, 0, 0, 65535]); + } + // Slid along its own surface by a fraction of the plane: half of it still overlaps the old one. + let mut mesh = (*s.mesh).clone(); + let shift = mesh.radius() * 0.5; + for p in &mut mesh.positions { + p.x += shift; + } + let mut next = Session::new(s.doc.clone(), mesh, None).unwrap(); + assert_eq!(preserve_strokes(&s, &mut next), 0); + let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap(); + for x in 0..128 { + assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved"); + assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint"); + } + } } diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 85b0142c..62afeb63 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -612,3 +612,42 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.doc.baked, original.baked); assert_eq!(session.history_labels(), history); } + +/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, +/// the project counts as changed, and image resources are decoded in the new session. +#[test] +fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { + let mut s = plane_session(); + let plane = s.mesh.as_ref().clone(); + let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3])); + execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); + // 1x1 PNG as an image resource. + let png = [ + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, + 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, + 0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + ]; + s.import_resource_bytes("dot.png", png.to_vec()).unwrap(); + s.modified = false; + let mesh_id = s.mesh_id; + + let mut low = String::new(); + for p in &plane.positions { + low += &format!("v {} {} {}\n", p.x, p.y, p.z); + } + for uv in &plane.uvs { + low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y); + } + for t in plane.indices.as_chunks::<3>().0 { + low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1); + } + let low = temp_file("change_low.obj", &low); + execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); + + assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); + assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); + assert!(s.modified, "the project differs from the saved one"); + assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index f585d326..4b60f6f0 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -5,4 +5,6 @@ pub struct BakeJob { pub queue: Vec, pub current: Option, pub total: usize, + /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. + pub mesh_id: u64, } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 815ba793..b80b1790 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -327,7 +327,7 @@ impl TextureCraftApp { } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -393,6 +393,15 @@ impl TextureCraftApp { return; }; + if job.mesh_id != self.session.mesh_id { + // The mesh was swapped under the job: stop it and drop its result. + if let Some(running) = &job.current { + running.progress.cancel.store(true, Ordering::Relaxed); + } + self.bake = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(50)); if let Some(running) = &job.current { let set_index = running.set_index; diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index fa1e6c4b..20736bdd 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -263,7 +263,7 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 6860bdc4..1703abde 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { result_sender.send(Ok(output)).unwrap(); let app = harness.state_mut(); app.start_bake(vec![0]); + let mesh_id = app.session.mesh_id; app.bake = Some(BakeJob { queue: Vec::new(), total: 1, + mesh_id, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs new file mode 100644 index 00000000..60f6f03e --- /dev/null +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -0,0 +1,43 @@ +//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps +//! the mesh meanwhile, the job is cancelled and its result is dropped. + +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use egui_kittest::Harness; +use texturecraft_engine::bake::Progress; +use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; + +/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. +fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + let progress = Arc::new(Progress::new()); + let (tx, receiver) = std::sync::mpsc::channel(); + let (maps_tx, maps) = std::sync::mpsc::channel(); + let id = mesh_id(h.state().session.mesh_id); + // Leak the sender so the channel stays empty instead of closed. + std::mem::forget(tx); + std::mem::forget(maps_tx); + let running = + RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; + h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); + (h, progress) +} + +#[test] +fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() { + let (mut h, progress) = harness_with_job(|current| current + 1); + h.step(); + assert!(h.state().bake.is_none(), "the job is dropped"); + assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); +} + +#[test] +fn a_job_on_the_current_mesh_keeps_running() { + let (mut h, progress) = harness_with_job(|current| current); + h.step(); + assert!(h.state().bake.is_some(), "the job stays"); + assert!(!progress.cancel.load(Ordering::Relaxed)); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6f1c5092..00f1ba79 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,6 +1,7 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. +mod bake_job_mesh; mod bake_mode; mod brush_drag; mod brush_section_reset; diff --git a/docs/features.md b/docs/features.md index a51352da..a456a371 100644 --- a/docs/features.md +++ b/docs/features.md @@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. - Reimport a changed mesh and your painted strokes stay on the surface. + Reimport a changed mesh and your painted strokes stay on the surface. The + `file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers. - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`).