Merge main into refactor/shared-ply-rows

This commit is contained in:
FredApps committed 2026-11-16 06:47:44 +01:00
commit ebb4bc8673
84 files changed
+16911 -1942

No files matched your search

Generated
+34 -2
View File
@@ -755,6 +755,15 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=272a095b61257917693da3d09f2f8ecccd7f0295#272a095b61257917693da3d09f2f8ecccd7f0295"
dependencies = [
"md-5",
"rayon",
]
[[package]]
name = "craft-dialogs"
version = "0.1.0"
@@ -818,7 +827,7 @@ dependencies = [
[[package]]
name = "craft-mcmat"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"craft-zip",
"serde",
@@ -855,6 +864,17 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-tcraft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -927,7 +947,7 @@ dependencies = [
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -2499,6 +2519,16 @@ version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
@@ -4414,9 +4444,11 @@ name = "texturecraft-formats"
version = "0.6.1"
dependencies = [
"base64 0.22.1",
"craft-cms",
"craft-materialx",
"craft-mcmat",
"craft-mesh",
"craft-tcraft",
"craft-zip",
"exr",
"flate2",
+3 -2
View File
@@ -69,9 +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 = "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", "ply"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" }
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).
+1 -1
View File
@@ -14,7 +14,7 @@ end to end today (engine + UI + automation + tests), not what is planned.
| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) |
| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — |
| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog |
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) |
| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's |
| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay |
| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing |
+2 -1
View File
@@ -157,6 +157,7 @@ impl StackKey {
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
_ => {}
}
}
@@ -279,7 +280,7 @@ impl BelowCache {
self.clock += 1;
*stamp = self.clock;
self.order.push_back((t, self.clock));
// Drop superseded uses once they outnumber the tiles.
// Drop superseded uses once they outnumber the tiles
if self.order.len() > 2 * self.tiles.len() + 64 {
let tiles = &self.tiles;
self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s));
+2 -3
View File
@@ -125,8 +125,7 @@ fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes:
sizes
};
// Keep distinct layouts: thumbnails and the viewport alternate on the same bake.
// Replacing only this variant prevents them from repeatedly rebuilding each other.
// Keep layout variants so thumbnails and the viewport reuse their own levels
cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales));
let sizes = Arc::new(sizes);
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
@@ -410,7 +409,7 @@ mod tests {
}
}
// Cache lifecycle tests must not evict each other's entries in parallel.
// Cache lifecycle tests must not evict each other's entries in parallel
static CACHE_TESTS: Mutex<()> = Mutex::new(());
#[test]
+397 -124
View File
@@ -279,12 +279,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<Item = (usize, f32, Op)> + '_ {
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 }))
@@ -298,6 +310,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (
EffectKind::Filter(Filter::Bevel { width }) => 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 }))
}
@@ -618,63 +634,74 @@ 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<Field> {
// Tiny coverage sums make normalization unstable
const MIN_FILTER_WEIGHT: f32 = 1e-6;
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));
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 component_count = match job {
// Generator stages keep their ramp beside the mask stack below
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<Vec<(u32, u32, [f32; 4])>> = region_tiles
.par_iter()
.map(|&(tx, ty)| {
let anchor_nodes = 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));
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));
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],
(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, alpha)) => [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha],
Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage],
None => [0.0; 4],
},
(None, None) => [0.0; 4],
@@ -686,103 +713,214 @@ 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 original_values = vec![0.0f32; texel_count * component_count];
let mut coverage = vec![0.0f32; texel_count];
let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize;
let band = (TILE * w) as usize;
original_values.par_chunks_mut(band * component_count).zip(coverage.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(
|((original_values, coverage), 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)) = (coverage.get_mut(texel), original_values.get_mut(texel * component_count..(texel + 1) * component_count))
{
*covered = 1.0;
pixel.copy_from_slice(&value[..component_count]);
}
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 = (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 - 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[..components]);
}
},
);
}
});
// Release scattered texels before allocating filter buffers
// Release tile scatter data before allocating filter buffers
drop(parts);
// High pass centers on the channel's midpoint value (0 for signed channels like height)
let midpoint = 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<f32> {
let sampling_resolution = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
let scaled_radius = neighbourhood_filters(effects, sampling_resolution)
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, &original_values, &coverage, component_count, (rx0, ry0, w, h), scaled_radius as f32, sampling_resolution, 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 mut weights = coverage.clone();
blur(&mut weights, width, height, blur_radius);
let mut data = original_values.clone();
for component in 0..component_count {
let mut sums: Vec<f32> = original_values
.par_chunks(component_count)
.with_min_len(MIN_PARALLEL_TEXELS)
.map(|pixel| pixel.get(component).copied().unwrap_or(0.0))
.collect();
blur(&mut sums, width, height, blur_radius);
data.par_chunks_mut(component_count).with_min_len(MIN_PARALLEL_TEXELS).zip(sums.par_iter()).zip(weights.par_iter()).for_each(
|((pixel, sum), weight)| {
// Content is premultiplied, so the midpoint value is too (coverage itself is kept)
let alpha = if component_count == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
if *weight > MIN_FILTER_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 + midpoint * alpha,
// 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,
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
_ => blurred,
};
*slot = original + (result - original) * opacity;
}
},
);
let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize);
let mut weights = cover.clone();
blur(&mut weights, columns, rows, blur_radius);
let mut filtered_values = stack_values.clone();
for component in 0..components {
let mut sums: Vec<f32> = 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 + 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,
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
_ => blurred,
};
*slot = original + (result - original) * opacity;
}
});
}
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<f32> =
(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<f32> = (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 * component_count;
data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| {
for (x, (target, source)) in dst.chunks_mut(component_count).zip(src.chunks(component_count)).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, component_count);
Some(Field { x0: rx0, y0: ry0, w, h, comps: component_count, 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<f32> {
let (columns, rows) = (width as usize, height as usize);
let mut ramps: Vec<f32> = 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<f32> = 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<f32> {
// 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<Option<f32>> = (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<f32> {
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.
@@ -1259,15 +1397,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,
};
@@ -1284,12 +1428,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<f32> {
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>) -> f32 {
let combine = |edges: f32, cavities: f32| match detail.mode {
CurvatureMode::Edges => edges,
CurvatureMode::Cavities => cavities,
@@ -1298,7 +1459,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];
@@ -2392,7 +2553,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 {
@@ -2731,42 +2892,154 @@ 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<f32> = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect();
let ridge: Vec<f32> = (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<f32> {
(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<Effect>, xs: std::ops::Range<u32>) -> Vec<f32> {
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::<Vec<_>>()).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 effect = generator_effect(&mut fixture, generator);
mask_row(&mut fixture, layer, vec![effect], 120..137)
};
// The sampled ridge is index 8; five texels to its left is index 3
let (ridge, five_texels_away) = (8, 3);
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 sampled row crosses a checker edge; indices below 30 are outside the blur
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)
};
// At one eighth resolution, each cell spans eight 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) }))];
// Tile and whole-set resolutions must select the same generator stage
let at_tile: Vec<usize> = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect();
let at_set_width: Vec<usize> = 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>| -> 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);
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::<Vec<_>>()).unwrap()
run(fixture, None).value(Channel::BaseColor, 20, 20)[0]
};
// 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]);
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:?}");
// Dark occlusion reveals dirt while the baked white map stays clear
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]
+35 -2
View File
@@ -6,8 +6,8 @@ use std::collections::BTreeMap;
use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached};
use texturecraft_core::{
BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural,
ProceduralKind, Project, Projection, Source, TextureSet,
BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, TileImage, to_u16};
@@ -799,3 +799,36 @@ fn cached_stack_tracks_referenced_images_only() {
assert!(output == expected, "{stage}");
}
}
#[test]
fn generator_input_image_changes_invalidate_stack_key() {
use std::sync::Arc;
use texturecraft_compose::{ImageRes, ImageStore, StackKey};
let mut fixture = fixture();
heavy_stack(&mut fixture);
let generated_layer = fixture.project.texture_sets[0].stack[1];
let mask = fixture.project.layer_mut(generated_layer).unwrap().mask.as_mut().unwrap();
let EffectKind::Generator(generator) = &mut mask.effects[0].kind else { panic!("expected generator") };
*generator = Generator::new(GeneratorKind::Dirt);
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used"));
let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let mut images = ImageStore::default();
images.insert("used".into(), image(0.1));
let baked = Default::default();
let roots = &fixture.project.texture_sets[0].stack;
let key = |images: &ImageStore| StackKey::new(&fixture.project, &fixture.pixels, &baked, images, 0, roots).unwrap();
let original = key(&images);
images.insert("unrelated".into(), image(0.5));
assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged");
let old_image = Arc::downgrade(&images["used"]);
images.insert("used".into(), image(0.9));
assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels");
assert!(key(&images) != original, "replacing a generator input must invalidate the cache");
images.remove("used");
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
}
+108 -4
View File
@@ -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<GeneratorKind> {
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<CurvatureDetail>,
/// 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<BakedMap, Source>,
}
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,46 @@ 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, material or generator input).
pub fn images_read(&self) -> impl Iterator<Item = &str> {
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::Image { name, .. } => Some(name.as_str()),
_ => None,
})
}
}
impl Layer {
@@ -1080,6 +1159,15 @@ impl Effect {
mod tests {
use super::*;
#[test]
fn material_effect_images_are_reported_as_used() {
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::image("material.png"));
let effect = EffectKind::Material(fill);
assert_eq!(effect.images_read().collect::<Vec<_>>(), vec!["material.png"]);
}
#[test]
fn generator_offset_shifts_the_mask_value() {
let mut g = Generator::new(GeneratorKind::Position);
@@ -1115,6 +1203,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 };
+96
View File
@@ -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);
}
}
+120
View File
@@ -0,0 +1,120 @@
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<i8> = -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 };
// Hostile tile sizes can make the minimum exceed the supported maximum
let minimum = (uv_tile / OutputResolution::MAX_CELL).clamp(1, OutputResolution::MAX_SIZE);
scaled.clamp(minimum, 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);
}
#[test]
fn hostile_uv_tile_size_does_not_panic() {
let resolution = OutputResolution::default();
assert_eq!(resolution.output_size(u32::MAX, 2048), OutputResolution::MAX_SIZE);
}
}
+32
View File
@@ -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<ResolutionMode> {
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))
}
}
+3 -3
View File
@@ -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,
+56 -45
View File
@@ -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<Value> {
Ok(json!({ "cut": eid }))
}
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
fn paste(session: &mut Session, params: &Value) -> Result<Value> {
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,54 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
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 }))
}
+10 -3
View File
@@ -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(), source_json(source))).collect::<serde_json::Map<_, _>>().into();
}
if let Some(detail) = &generator.detail {
out["mode"] = json!(format!("{:?}", detail.mode));
out["sizes"] = json!(detail.weights);
@@ -105,7 +112,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
v["geometryMask"] = json!(parts);
}
if matches!(l.kind, LayerKind::Paint) {
// Sorted: the store is a hash map, and inspect output must be stable.
// Sort the hash map entries for stable inspection output
let mut painted: Vec<(&str, usize)> =
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
painted.sort_unstable();
+2 -1
View File
@@ -41,7 +41,7 @@ mod path_draft;
pub mod path_tool;
mod polygon_fill;
mod polygon_fill_drag;
// Mesh reimport reads files: native only.
// Mesh reimport reads files on native targets only
#[cfg(not(target_arch = "wasm32"))]
mod preserve;
pub mod preset_cmds;
@@ -55,6 +55,7 @@ pub mod smart_masks;
pub mod template_cmds;
pub mod text_cmds;
pub mod thumbs;
mod tool_availability;
pub mod tool_cmds;
mod triangle_partition;
mod uv_stroke_state;
+89 -8
View File
@@ -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<CommandSpec> {
"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<CommandSpec> {
"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), generator?: kind (a generator effect only: changes kind 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
),
@@ -242,7 +242,7 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -
let label = format!("Add {}", kind.name().to_ascii_lowercase());
let eid = with_mask(s, p, "effect.add", &label, |s, id| {
let eid = s.doc.project.alloc_id();
// An instance's content and (unless it has its own) mask belong to its source.
// An instance's content and inherited mask belong to its source
let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) };
let l = s.doc.project.layer_mut(id)?;
let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
@@ -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(command, 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<Option<(BakedMap, Option<Source>)>> {
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.images.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<Value> {
let kind = match strp(params, "generator") {
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
@@ -458,6 +507,13 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.set";
let effect = effect_id(session, params, CMD)?;
let blend = blend_param(CMD, params, "blend")?;
let generator_kind = params
.get("generator")
.map(|value| {
let name = value.as_str().ok_or_else(|| bad(CMD, "`generator` must be a string"))?;
GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))
})
.transpose()?;
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
let anchor = match session.doc.project.effect(effect) {
@@ -475,6 +531,12 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
_ => 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 +570,26 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
}
match &mut edited.kind {
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
EffectKind::Generator(generator) => {
if let Some(kind) = generator_kind
&& kind != generator.kind
{
generator.kind = kind;
generator.detail = Generator::new(kind).detail;
generator.inputs.retain(|map, _| kind.inputs().contains(map));
}
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),
};
}
}
_ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")),
EffectKind::Levels(levels) => levels_from(params, levels),
// The swapped filter was built with the parameters already
EffectKind::Filter(_) if swaps_filter => {}
+13 -14
View File
@@ -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<String>, depth: usize) {
/// Image resources a layer subtree uses (fill sources and mask or content effects).
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, 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()).chain(&layer.content_effects) {
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);
}
}
+14 -12
View File
@@ -1,5 +1,5 @@
//! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill
//! and the color picker. The UI, CLI and agents all go through these.
//! and the material picker. The UI, CLI and agents all go through these.
use std::collections::{BTreeMap, BTreeSet};
@@ -553,20 +553,22 @@ impl Session {
Ok(())
}
/// Color picker: copy the material under the cursor into the tool's paint values.
/// Material picker: copy the material under the cursor into the tool's paint values
pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result<BTreeMap<Channel, [f32; 3]>> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let (w, h) = (cache.size.0 as f32, cache.size.1 as f32);
let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32);
let mut out = BTreeMap::new();
for c in cache.composite.channels.keys() {
let v = cache.composite.value(*c, x, y);
self.tool.values.insert(*c, v);
out.insert(*c, v);
let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts());
let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
let mut picked = BTreeMap::new();
for channel in cache.composite.channels.keys() {
let value = cache.composite.value(*channel, x, y);
self.tool.values.insert(*channel, value);
picked.insert(*channel, value);
}
Ok(out)
Ok(picked)
}
/// The stroke canvas alpha of the active stroke (for overlays and tests).
+70 -27
View File
@@ -12,7 +12,7 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use texturecraft_compose::{PaintTarget, PixelStore};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{OrbitCamera, surface_at};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
@@ -368,6 +368,10 @@ impl Session {
/// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool
pub fn commit_path(&mut self, viewport: Vec2) -> Result<Value> {
if self.quick_mask.editing {
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
}
if let Some((effect, index)) = self.tool.path.editing
&& self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored))
{
@@ -396,20 +400,20 @@ impl Session {
let shape = self.path_shape(self.camera, viewport);
let editing = self.tool.path.editing;
let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1));
let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| {
let (eid, index) = match editing {
let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| {
let (effect_id, index) = match editing {
Some(at) => at,
None => (s.path_effect()?, usize::MAX),
None => (session.path_effect()?, usize::MAX),
};
s.put_path(eid, index, shape)
session.put_path(effect_id, index, shape)
})?;
if let Some(eid) = out.get("effect").and_then(Value::as_u64) {
self.target = StackTarget::Effect(LayerId(eid));
if let Some(effect_id) = report.get("effect").and_then(Value::as_u64) {
self.target = StackTarget::Effect(LayerId(effect_id));
}
self.tool.path.clear();
Ok(out)
Ok(report)
}
/// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame
@@ -429,9 +433,13 @@ impl Session {
/// Preview a command's points in its supplied viewport, or the UI's current viewport
fn path_live_in_view(&mut self, viewport: Vec2) -> Result<bool> {
if self.quick_mask.editing {
return Ok(false);
}
let stored = match self.tool.path.editing {
Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() {
Some(shape) => Some((eid, index, shape)),
Some((effect_id, index)) => match self.paths(effect_id).and_then(|paths| paths.get(index)).cloned() {
Some(shape) => Some((effect_id, index, shape)),
None => {
self.stop_path_edit();
return Ok(false);
@@ -661,6 +669,11 @@ impl Session {
let from = if back { &self.path_steps.0 } else { &self.path_steps.1 };
let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) };
// Returning false here would let undo/redo consume document history instead.
if self.quick_mask.editing {
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
}
let path = &mut self.tool.path;
let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() });
if let Err(error) = self.path_live() {
@@ -706,33 +719,40 @@ impl Session {
self.path_steps = Default::default();
}
/// The selected path sublayer, or a new one on the selected layer's content or mask
/// (whichever is selected).
/// The selected path sublayer, or a new one on the selected paint layer's content or mask
fn path_effect(&mut self) -> Result<LayerId> {
let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?;
let p = &self.doc.project;
if self.quick_mask.editing {
return Err(EngineError::Other("paths can't edit the quick mask: stop editing it first".into()));
}
let selected = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to add the path to".into()))?;
let project = &self.doc.project;
let mask = match self.target {
StackTarget::Effect(e) => match p.effect(e) {
Some((_, x)) if matches!(x.kind, EffectKind::Path(_)) => return Ok(e),
Some((owner, _)) => !p.layer(owner)?.content_effects.iter().any(|x| x.id == e),
StackTarget::Effect(effect) => match project.effect(effect) {
// Paths saved in a fill layer before paths there were removed stay editable
Some((_, found)) if matches!(found.kind, EffectKind::Path(_)) => return Ok(effect),
Some((owner, _)) => !project.layer(owner)?.content_effects.iter().any(|candidate| candidate.id == effect),
None => false,
},
StackTarget::Mask => true,
StackTarget::Content => false,
};
// An instance's content and (unless it has its own) mask belong to its source.
let owner = if mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) };
let eid = self.doc.project.alloc_id();
let l = self.doc.project.layer_mut(owner)?;
let e = Effect::new(eid, EffectKind::Path(Vec::new()));
// An instance's content and (unless it has its own) mask belong to its source
let owner = if mask { project.mask_owner(selected) } else { project.content_layer(selected).map_or(selected, |layer| layer.id) };
let path_id = self.doc.project.alloc_id();
let layer = self.doc.project.layer_mut(owner)?;
let path = Effect::new(path_id, EffectKind::Path(Vec::new()));
if mask {
l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(e);
} else if l.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", l.name)));
layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black)).effects.push(path);
} else if layer.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: add the path to a layer or a mask", layer.name)));
} else if matches!(layer.kind, LayerKind::Paint) {
layer.content_effects.push(path);
} else {
l.content_effects.push(e);
return Err(EngineError::Other(format!("\"{}\" is not a paint layer: add the path to a paint layer or a mask", layer.name)));
}
Ok(eid)
Ok(path_id)
}
/// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before
@@ -1071,6 +1091,29 @@ mod tests {
assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new());
}
#[test]
fn quick_mask_preserves_pending_path_undo_and_redo() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap();
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap();
session.path_checkpoint();
session.tool.path.points[0].y = 0.3;
session.path_live().unwrap();
for back in [true, false] {
let curve = session.tool.path.clone();
let steps = (session.path_steps.0.len(), session.path_steps.1.len());
let history = (session.history_labels(), session.redo_labels());
let pixels = session.doc.pixels.clone();
session.quick_mask.editing = true;
assert!(if back { session.undo() } else { session.redo() }.is_err());
assert!(curve.same_curve(&session.tool.path));
assert_eq!(steps, (session.path_steps.0.len(), session.path_steps.1.len()));
assert_eq!(history, (session.history_labels(), session.redo_labels()));
assert_eq!(format!("{:?}", pixels), format!("{:?}", session.doc.pixels));
session.quick_mask.editing = false;
if back { session.undo() } else { session.redo() }.unwrap();
}
}
#[test]
fn point_checkpoints_skip_noops_and_bound_retained_points() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap();
+32 -23
View File
@@ -35,44 +35,53 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit quick mask",
["Viewport"],
Some("U"),
"{editing?: bool} — toggles when omitted; editing enables the mask",
always,
"{editing?: bool} — toggles when omitted; needs the quick mask enabled",
mask_enabled,
edit
),
cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert),
cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", mask_enabled, invert),
]
}
fn state(s: &Session) -> Value {
let q = &s.quick_mask;
fn mask_enabled(session: &Session) -> std::result::Result<(), String> {
if session.quick_mask.enabled { Ok(()) } else { Err("enable the quick mask first".into()) }
}
fn state(session: &Session) -> Value {
let mask = &session.quick_mask;
json!({
"enabled": q.enabled, "editing": q.editing, "inverted": q.inverted,
"paintedTiles": q.masks.get(&s.ts()).map(TileImage::allocated_count).unwrap_or(0),
"enabled": mask.enabled, "editing": mask.editing, "inverted": mask.inverted,
"paintedTiles": mask.masks.get(&session.ts()).map(TileImage::allocated_count).unwrap_or(0),
})
}
fn changed(s: &mut Session) -> Result<Value> {
s.quick_mask.revision = s.quick_mask.revision.wrapping_add(1);
s.revision = s.revision.wrapping_add(1);
Ok(state(s))
fn changed(session: &mut Session) -> Result<Value> {
session.quick_mask.revision = session.quick_mask.revision.wrapping_add(1);
session.revision = session.revision.wrapping_add(1);
Ok(state(session))
}
fn enable(s: &mut Session, p: &Value) -> Result<Value> {
s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled);
changed(s)
fn enable(session: &mut Session, params: &Value) -> Result<Value> {
let enabled = boolp(params, "enabled").unwrap_or(!session.quick_mask.enabled);
if !enabled && session.quick_mask.editing {
session.cancel_stroke();
session.quick_mask.editing = false;
}
session.quick_mask.enabled = enabled;
changed(session)
}
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
s.cancel_stroke();
let q = &mut s.quick_mask;
q.editing = boolp(p, "editing").unwrap_or(!q.editing);
q.enabled |= q.editing;
changed(s)
fn edit(session: &mut Session, params: &Value) -> Result<Value> {
session.cancel_stroke();
let quick_mask = &mut session.quick_mask;
quick_mask.editing = boolp(params, "editing").unwrap_or(!quick_mask.editing);
changed(session)
}
fn invert(s: &mut Session, _: &Value) -> Result<Value> {
s.quick_mask.inverted = !s.quick_mask.inverted;
changed(s)
fn invert(session: &mut Session, _: &Value) -> Result<Value> {
session.quick_mask.inverted = !session.quick_mask.inverted;
changed(session)
}
impl Session {
+15 -5
View File
@@ -109,7 +109,7 @@ impl Tool {
Tool::PolygonFill => "Polygon fill",
Tool::Smudge => "Smudge",
Tool::Clone => "Clone",
Tool::ColorPicker => "Color picker",
Tool::ColorPicker => "Material picker",
Tool::Path => "Path",
Tool::GeometryMask => "Geometry mask",
}
@@ -595,6 +595,7 @@ impl Session {
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind {
EffectKind::Fill { source, .. } => uses_source(source),
EffectKind::Material(fill) => uses_fill(fill),
EffectKind::Generator(generator) => generator.inputs.values().any(uses_source),
_ => false,
})
})
@@ -764,7 +765,8 @@ impl Session {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away: select the stack it was in.
// An undone add or duplicate takes the selected effect away
if let StackTarget::Effect(e) = self.target
&& self.doc.project.effect(e).is_none()
{
@@ -1009,14 +1011,22 @@ pub const SETTLE_BUDGET_MS: f64 = 6.0;
/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
/// evaluate compact regions.
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> {
if dirty.len() <= n {
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, max_tiles: usize) -> Vec<(u32, u32)> {
// A zero-sized request cannot select a pivot
if max_tiles == 0 {
return Vec::new();
}
if dirty.len() <= max_tiles {
return std::mem::take(dirty).into_iter().collect();
}
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
// Partition by block order so only the requested chunk needs sorting
tiles.select_nth_unstable_by_key(max_tiles - 1, |&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
tiles.truncate(max_tiles);
tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
tiles.truncate(n);
for tile in &tiles {
dirty.remove(tile);
}
+46
View File
@@ -0,0 +1,46 @@
//! Which tools can act on the current selection: the tool shelf and its shortcuts grey the rest
use texturecraft_core::{EffectKind, LayerKind};
use crate::{Session, StackTarget, Tool};
impl Session {
/// Whether `tool` can act on the selection (or on the quick mask while it is being edited)
pub fn tool_usable(&self, tool: Tool) -> bool {
match tool {
// The picker reads the composite under the cursor, whatever is selected
Tool::ColorPicker => return true,
Tool::GeometryMask => return self.selected_layer().is_some(),
_ => {}
}
// Brushes paint the quick mask whatever is selected; paths can't edit it
if self.quick_mask.editing {
return tool != Tool::Path;
}
let project = &self.doc.project;
let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false };
// Smudge and Clone read layer content, so they can't yet paint mask values
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match self.target {
StackTarget::Content => matches!(layer.kind, LayerKind::Paint),
StackTarget::Mask => !reads_content,
StackTarget::Effect(effect) => {
let Some((owner, found)) = project.effect(effect) else { return false };
let Some(owner_layer) = project.layers.get(&owner) else { return false };
let in_content = owner_layer.content_effects.iter().any(|candidate| candidate.id == effect);
let in_fill_content = in_content && matches!(owner_layer.kind, LayerKind::Fill(_));
match found.kind {
// Paths saved in a fill layer before paths there were removed stay editable
EffectKind::Path(_) => tool == Tool::Path,
EffectKind::Paint if tool == Tool::Path => !in_fill_content,
EffectKind::Paint => in_content || !reads_content,
_ => false,
}
}
}
}
}
+30 -25
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)),
cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)),
cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)),
cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)),
cmd!("tool.colorPicker", "Material picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)),
cmd!(
"tool.geometryMask",
"Geometry mask",
@@ -105,7 +105,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Tool click",
[],
None,
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
"{x, y, viewport?: [w,h]} — polygon fill / material picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
always,
click
),
@@ -115,6 +115,7 @@ pub fn specs() -> Vec<CommandSpec> {
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
session.cancel_stroke();
// A box fill under way keeps what it filled as one undo step
session.end_polygon_fill_box();
session.tool.tool = tool;
@@ -342,40 +343,44 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "maskValue": session.tool.mask_value }))
}
fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "clear") == Some(true) {
s.tool.stencil = None;
fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
if boolp(params, "clear") == Some(true) {
session.tool.stencil = None;
return Ok(Value::Null);
}
if let Some(name) = strp(p, "image") {
if !s.doc.resources.contains_key(name) {
if let Some(name) = strp(params, "image") {
if !session.doc.resources.contains_key(name) {
return Err(bad("tool.stencil", format!("no resource `{name}` (import it first)")));
}
let keep = s.tool.stencil.take();
let mut st = crate::session::StencilState::new(name);
if let Some(k) = keep {
st = crate::session::StencilState { image: name.to_string(), ..k };
let previous_stencil = session.tool.stencil.take();
let mut stencil_state = crate::session::StencilState::new(name);
if let Some(previous_stencil) = previous_stencil {
stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil };
}
s.tool.stencil = Some(st);
session.tool.stencil = Some(stencil_state);
}
let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(c) = pair(p, "center").or_else(|| p.get("center").and_then(color_of).map(|c| [c[0], c[1]])) {
st.center = c.map(|v| v.clamp(-4.0, 4.0));
let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) {
stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0));
}
if let Some(v) = f32p(p, "scale") {
st.scale = v.clamp(0.01, 10.0);
if let Some(scale) = f32p(params, "scale") {
stencil_state.scale = scale.clamp(0.01, 10.0);
}
if let Some(v) = f32p(p, "rotation") {
st.rotation = v.rem_euclid(360.0);
if let Some(rotation) = f32p(params, "rotation") {
stencil_state.rotation = rotation.rem_euclid(360.0);
}
if let Some(v) = boolp(p, "tile") {
st.tile = v;
if let Some(tile) = boolp(params, "tile") {
stencil_state.tile = tile;
}
if let Some(v) = f32p(p, "opacity") {
st.opacity = v.clamp(0.0, 1.0);
if let Some(opacity) = f32p(params, "opacity") {
stencil_state.opacity = opacity.clamp(0.0, 1.0);
}
s.revision = s.revision.wrapping_add(1);
Ok(serde_json::to_value(&s.tool.stencil).unwrap_or(Value::Null))
session.revision = session.revision.wrapping_add(1);
Ok(serde_json::to_value(&session.tool.stencil).unwrap_or(Value::Null))
}
/// A `[a, b]` param of two finite numbers.
+132
View File
@@ -0,0 +1,132 @@
//! Generator inputs that read an anchor point or an image, through engine commands.
use serde_json::{Value, json};
use std::sync::Arc;
use texturecraft_engine::core::{BakedMap, Channel, EffectKind, Source};
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");
}
#[test]
fn removing_unused_resources_keeps_an_image_read_by_a_content_effect() {
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("content.png", bytes).unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": "content"})).unwrap(), "effect");
execute(&mut session, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "image": name})).unwrap();
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert!(session.doc.resources.contains_key(&name), "the content effect still reads the image");
}
#[test]
fn generator_input_rejects_a_resource_that_is_not_an_image() {
let mut session = session();
session.doc.resources.insert("linked.mcmat".into(), Arc::new(vec![1, 2, 3]));
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");
let result = execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": "linked.mcmat"}));
assert!(result.is_err(), "a package resource has no image pixels for the generator to sample");
}
#[test]
fn importing_a_missing_generator_input_invalidates_the_composite() {
let mut session = session();
execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let effect = id(execute(&mut session, "effect.add.generator", &json!({"generator": "ambientOcclusion"})).unwrap(), "effect");
session
.edit("Reference an absent image", |session| {
let effect = session.doc.project.effect_mut(texturecraft_engine::core::LayerId(effect)).unwrap();
let EffectKind::Generator(generator) = &mut effect.kind else { panic!("expected generator") };
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("later.png"));
Ok(())
})
.unwrap();
let before = center(&mut session, Channel::BaseColor)[0];
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes("later.png", bytes).unwrap();
let after = center(&mut session, Channel::BaseColor)[0];
assert!((after - before).abs() > 0.2, "the new image must update the generator's composited mask: {before} -> {after}");
}
+2
View File
@@ -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;
@@ -24,6 +25,7 @@ mod polygon_fill;
mod project_recovery;
mod sample;
mod thumbs;
mod tool_availability;
mod tools;
mod udim;
mod uv_strokes;
+336
View File
@@ -0,0 +1,336 @@
//! Which tools can act on each selection, and that every usable tool acts there in both views
mod selection;
use selection::Selection;
use serde_json::{Value, json};
use texturecraft_engine::core::{Effect, EffectKind, LayerId};
use texturecraft_engine::geom::glam::{Vec2, Vec3};
use texturecraft_engine::{Session, StackTarget, Tool, execute};
/// Two triangles side by side, each a mesh part with its own corner of the UV square
const PARTS_OBJ: &str = "o Lid\nv 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 0.5 0\nvt 0 0.5\nf 1/1 2/2 3/3\n\
o Body\nv 2 2 0\nv 4 2 0\nv 2 4 0\nvt 0.5 0.5\nvt 1 0.5\nvt 0.5 1\nf 4/4 5/5 6/6\n";
const VIEWPORT_PIXELS: f32 = 400.0;
fn stencil_png() -> Vec<u8> {
let mut out = Vec::new();
let green = image::RgbaImage::from_fn(8, 8, |_, _| image::Rgba([0, 255, 0, 255]));
green.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
out
}
fn base_session() -> Session {
let mut session = Session::from_mesh_bytes("parts.obj", PARTS_OBJ.as_bytes(), 256, "parts").unwrap();
session.viewport = Vec2::splat(VIEWPORT_PIXELS);
(session.camera.yaw, session.camera.pitch) = (0.0, 0.0);
let (low, high) = session.mesh.bounds();
session.camera.frame(low, high);
session.update();
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap();
let stencil = session.import_resource_bytes("stencil.png", stencil_png()).unwrap();
execute(&mut session, "tool.stencil", &json!({"image": stencil})).unwrap();
session
}
fn screen(session: &Session, point: [f32; 3]) -> Vec2 {
let ndc = session.camera.project(Vec3::from(point), 1.0).unwrap();
Vec2::new((ndc.x + 1.0) * VIEWPORT_PIXELS / 2.0, (1.0 - ndc.y) * VIEWPORT_PIXELS / 2.0)
}
fn add_layer(session: &mut Session, command: &str) -> u64 {
execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap()
}
fn select(session: &mut Session, layer: u64, target: Value) {
execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap();
}
fn select_nothing(session: &mut Session) {
let set = session.ts();
session.selected.remove(&set);
session.target = StackTarget::Content;
}
/// Adds an effect with `command` to the layer's content or mask and selects it
fn select_new_effect(session: &mut Session, layer: u64, mask: bool, command: &str, effect_params: Value) {
if mask {
execute(session, "mask.add.black", &json!({"layer": layer})).unwrap();
}
let target = if mask { "mask" } else { "content" };
let mut params = effect_params;
params["layer"] = json!(layer);
params["target"] = json!(target);
execute(session, command, &params).unwrap();
let owner = session.doc.project.layer(LayerId(layer)).unwrap();
let effects = if mask { &owner.mask.as_ref().unwrap().effects } else { &owner.content_effects };
let effect = effects.last().unwrap().id.0;
select(session, layer, json!(effect));
}
fn select_new_mask(session: &mut Session, layer: u64) {
execute(session, "mask.add.black", &json!({"layer": layer})).unwrap();
select(session, layer, json!("mask"));
}
fn session_with(selection: Selection) -> Session {
let mut session = base_session();
match selection {
Selection::PaintContent => {
let layer = add_layer(&mut session, "layer.add.paint");
select(&mut session, layer, json!("content"));
}
Selection::FillContent => {
let layer = add_layer(&mut session, "layer.add.fill");
select(&mut session, layer, json!("content"));
}
Selection::PaintMask => {
let layer = add_layer(&mut session, "layer.add.paint");
select_new_mask(&mut session, layer);
}
Selection::FillMask => {
let layer = add_layer(&mut session, "layer.add.fill");
select_new_mask(&mut session, layer);
}
Selection::FolderMask => {
let folder = add_layer(&mut session, "layer.add.group");
select_new_mask(&mut session, folder);
}
Selection::InstanceOwnMask => {
let source = add_layer(&mut session, "layer.add.paint");
let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap();
select_new_mask(&mut session, instance);
}
Selection::PaintSublayer => {
let layer = add_layer(&mut session, "layer.add.paint");
select_new_effect(&mut session, layer, false, "effect.add.paint", json!({}));
}
Selection::PaintSublayerInMask => {
let layer = add_layer(&mut session, "layer.add.paint");
select_new_effect(&mut session, layer, true, "effect.add.paint", json!({}));
}
Selection::PaintSublayerInFill => {
let layer = add_layer(&mut session, "layer.add.fill");
select_new_effect(&mut session, layer, false, "effect.add.paint", json!({}));
}
Selection::PathSublayer => {
let layer = add_layer(&mut session, "layer.add.paint");
select(&mut session, layer, json!("content"));
let (start, end) = (screen(&session, [0.2, 0.2, 0.0]), screen(&session, [1.0, 0.4, 0.0]));
execute(&mut session, "tool.path", &json!({"points": [[start.x, start.y], [end.x, end.y]]})).unwrap();
execute(&mut session, "tool.path", &json!({"commit": true})).unwrap();
let path = session.doc.project.layer(LayerId(layer)).unwrap().content_effects.last().unwrap().id.0;
select(&mut session, layer, json!(path));
}
Selection::FilterInPaint | Selection::FilterInFill | Selection::FilterInMask => {
let command = if selection == Selection::FilterInFill { "layer.add.fill" } else { "layer.add.paint" };
let layer = add_layer(&mut session, command);
select_new_effect(&mut session, layer, selection == Selection::FilterInMask, "effect.add.filter", json!({"filter": "invert"}));
}
Selection::FillEffectInPaint => {
let layer = add_layer(&mut session, "layer.add.paint");
select_new_effect(&mut session, layer, false, "effect.add.fill", json!({}));
}
Selection::GeneratorInFillMask => {
let layer = add_layer(&mut session, "layer.add.fill");
select_new_effect(&mut session, layer, true, "effect.add.generator", json!({}));
}
Selection::FolderContent => {
let folder = add_layer(&mut session, "layer.add.group");
select(&mut session, folder, json!("content"));
}
Selection::InstanceOfPaint | Selection::InstanceOfFill => {
let command = if selection == Selection::InstanceOfFill { "layer.add.fill" } else { "layer.add.paint" };
let source = add_layer(&mut session, command);
let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap();
select(&mut session, instance, json!("content"));
}
Selection::Nothing => select_nothing(&mut session),
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill => {
let command = if selection == Selection::QuickMaskOverFill { "layer.add.fill" } else { "layer.add.paint" };
let layer = add_layer(&mut session, command);
select(&mut session, layer, json!("content"));
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
}
Selection::QuickMaskOverNothing => {
select_nothing(&mut session);
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
}
}
session
}
/// Uses `tool` once the way the viewport does: a stroke, a click or a committed path
fn use_tool(session: &mut Session, tool: Tool, in_2d_view: bool) -> texturecraft_engine::Result<()> {
session.tool.tool = tool;
if tool == Tool::Clone {
let source = screen(session, [1.2, 0.3, 0.0]);
execute(session, "tool.cloneSource", &json!({"x": source.x, "y": source.y}))?;
}
let points = [screen(session, [0.3, 0.3, 0.0]), screen(session, [0.6, 0.4, 0.0]), screen(session, [0.9, 0.5, 0.0])];
let uv_points = [Vec2::new(0.05, 0.95), Vec2::new(0.1, 0.92), Vec2::new(0.15, 0.9)];
if tool == Tool::Path {
let params = if in_2d_view {
json!({"uvPoints": uv_points.iter().map(|uv| [uv.x, uv.y]).collect::<Vec<_>>()})
} else {
json!({"points": points.iter().map(|point| [point.x, point.y]).collect::<Vec<_>>()})
};
execute(session, "tool.path", &params)?;
execute(session, "tool.path", &json!({"commit": true}))?;
return Ok(());
}
let single_click = matches!(tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask);
let viewport = session.viewport;
if in_2d_view {
session.begin_stroke_uv(uv_points[0], 1.0)?;
} else {
session.begin_stroke(points[0], viewport, 1.0)?;
}
if single_click {
return Ok(());
}
for (point, uv) in points.iter().zip(&uv_points).skip(1) {
if in_2d_view {
session.continue_stroke_uv(*uv, 1.0);
} else {
session.continue_stroke(*point, 1.0);
}
}
session.end_stroke()
}
#[test]
fn every_selection_offers_the_tools_that_can_act_on_it() {
let mut wrong = Vec::new();
for selection in Selection::ALL {
let session = session_with(selection);
for tool in Tool::ALL {
let usable = session.tool_usable(tool);
if usable != selection.offers(tool) {
wrong.push(format!("{selection:?} {tool:?}: usable {usable}"));
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn every_usable_tool_acts_in_both_views() {
let mut wrong = Vec::new();
for in_2d_view in [false, true] {
for selection in Selection::ALL {
for tool in Tool::ALL {
// The picker and the geometry mask read the 3D view only, whatever is selected
if in_2d_view && matches!(tool, Tool::ColorPicker | Tool::GeometryMask) {
continue;
}
let mut session = session_with(selection);
let usable = session.tool_usable(tool);
let result = use_tool(&mut session, tool, in_2d_view);
let view = if in_2d_view { "2D" } else { "3D" };
match result {
Err(error) if usable => wrong.push(format!("{view} {selection:?} {tool:?}: usable but {error}")),
Ok(()) if !usable && !selection.scripts_still_paint() => wrong.push(format!("{view} {selection:?} {tool:?}: greyed but acts")),
_ => {}
}
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
fn commit_path(session: &mut Session) -> texturecraft_engine::Result<Value> {
execute(session, "tool.path", &json!({"uvPoints": [[0.05, 0.95], [0.15, 0.9]], "commit": true}))
}
fn path_count(session: &Session, path_sublayer: LayerId) -> usize {
match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
Some(EffectKind::Path(paths)) => paths.len(),
_ => 0,
}
}
#[test]
fn paths_are_refused_on_fill_layers_and_the_quick_mask_but_saved_ones_stay_editable() {
let mut session = session_with(Selection::FillContent);
let fill = session.selected_layer().unwrap();
assert!(commit_path(&mut session).is_err(), "no new paths in a fill layer");
assert!(session.doc.project.layer(fill).unwrap().content_effects.is_empty());
let mut session = session_with(Selection::QuickMaskOverPaint);
assert!(commit_path(&mut session).is_err(), "paths can't edit the quick mask");
// A project saved while paths could go into fill layers
let mut session = session_with(Selection::FillContent);
let fill = session.selected_layer().unwrap();
let saved_path = session.doc.project.alloc_id();
session.doc.project.layer_mut(fill).unwrap().content_effects.push(Effect::new(saved_path, EffectKind::Path(Vec::new())));
select(&mut session, fill.0, json!(saved_path.0));
assert!(session.tool_usable(Tool::Path));
commit_path(&mut session).unwrap();
assert_eq!(path_count(&session, saved_path), 1, "the saved path sublayer takes the new path");
}
#[test]
fn quick_mask_edit_and_invert_need_the_mask_on() {
let mut session = base_session();
assert!(execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).is_err());
assert!(execute(&mut session, "viewport.quickMask.invert", &json!({})).is_err());
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap();
assert!(!session.quick_mask.editing, "turning the mask off stops editing it");
}
#[test]
fn a_saved_path_cannot_be_committed_while_editing_the_quick_mask() {
let mut session = session_with(Selection::PaintContent);
commit_path(&mut session).unwrap();
let StackTarget::Effect(path_sublayer) = session.target else { panic!("the committed path is not selected") };
let points_before = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
Some(EffectKind::Path(paths)) => paths[0].points.clone(),
_ => panic!("the committed path is missing"),
};
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
execute(&mut session, "path.edit", &json!({"effect": path_sublayer.0, "index": 0})).unwrap();
assert!(!session.tool_usable(Tool::Path));
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.3, 0.7]]})).unwrap();
assert!(!session.path_live().unwrap(), "live preview must leave the stored path alone");
let result = execute(&mut session, "tool.path", &json!({"commit": true}));
assert!(result.is_err(), "a greyed Path tool must not commit a stored path into the quick mask edit state");
let points_after = match session.doc.project.effect(path_sublayer).map(|(_, effect)| &effect.kind) {
Some(EffectKind::Path(paths)) => paths[0].points.clone(),
_ => panic!("the stored path is missing"),
};
assert_eq!(points_after, points_before);
}
@@ -0,0 +1,83 @@
//! Selection cases for the tool availability tests
use texturecraft_engine::Tool;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Selection {
PaintContent,
FillContent,
PaintMask,
FillMask,
FolderMask,
InstanceOwnMask,
PaintSublayer,
PaintSublayerInMask,
PaintSublayerInFill,
PathSublayer,
FilterInPaint,
FilterInFill,
FilterInMask,
FillEffectInPaint,
GeneratorInFillMask,
FolderContent,
InstanceOfPaint,
InstanceOfFill,
Nothing,
QuickMaskOverPaint,
QuickMaskOverFill,
QuickMaskOverNothing,
}
impl Selection {
pub(super) const ALL: [Selection; 22] = [
Selection::PaintContent,
Selection::FillContent,
Selection::PaintMask,
Selection::FillMask,
Selection::FolderMask,
Selection::InstanceOwnMask,
Selection::PaintSublayer,
Selection::PaintSublayerInMask,
Selection::PaintSublayerInFill,
Selection::PathSublayer,
Selection::FilterInPaint,
Selection::FilterInFill,
Selection::FilterInMask,
Selection::FillEffectInPaint,
Selection::GeneratorInFillMask,
Selection::FolderContent,
Selection::InstanceOfPaint,
Selection::InstanceOfFill,
Selection::Nothing,
Selection::QuickMaskOverPaint,
Selection::QuickMaskOverFill,
Selection::QuickMaskOverNothing,
];
/// Whether the shelf offers `tool` for this selection
pub(super) fn offers(self, tool: Tool) -> bool {
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match tool {
Tool::ColorPicker => true,
Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing),
_ => match self {
Selection::PaintContent | Selection::PaintSublayer => true,
Selection::PaintSublayerInFill => tool != Tool::Path,
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => {
!reads_content
}
Selection::PathSublayer => tool == Tool::Path,
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path,
_ => false,
},
}
}
/// Greyed in the shelf, but scripts still paint here: below the effect, or the instance's source
pub(super) fn scripts_still_paint(self) -> bool {
matches!(
self,
Selection::FilterInPaint | Selection::FillEffectInPaint | Selection::FilterInMask | Selection::GeneratorInFillMask | Selection::InstanceOfPaint
)
}
}
+30 -23
View File
@@ -153,32 +153,39 @@ fn library_alphas_shape_the_stamp() {
#[test]
fn quick_mask_limits_painting() {
let mut s = session();
paint_red(&mut s, 20.0);
let r = execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap();
assert_eq!(r["editing"], json!(true));
assert_eq!(r["enabled"], json!(true), "editing enables the mask");
let undo = s.history_labels().len();
dab(&mut s, 150.0, 200.0);
assert!(!red(color_at(&s, 150.0, 200.0)), "mask strokes do not paint the layer");
assert_eq!(s.history_labels().len(), undo, "mask strokes stay out of the history");
assert!(s.quick_mask_rgba(0, 64).is_some_and(|v| v.len() == 64 * 64 * 4));
execute(&mut s, "viewport.quickMask.edit", &Value::Null).unwrap();
let mut session = session();
paint_red(&mut session, 20.0);
execute(&mut session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
dab(&mut s, 150.0, 200.0);
dab(&mut s, 250.0, 200.0);
assert!(red(color_at(&s, 150.0, 200.0)), "inside the mask");
assert!(!red(color_at(&s, 250.0, 200.0)), "outside the mask");
let state = execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap();
let undo = session.history_labels().len();
dab(&mut session, 150.0, 200.0);
execute(&mut s, "viewport.quickMask.invert", &Value::Null).unwrap();
dab(&mut s, 250.0, 200.0);
assert!(red(color_at(&s, 250.0, 200.0)), "inverted: outside is open");
assert_eq!(state["editing"], json!(true));
assert!(!red(color_at(&session, 150.0, 200.0)), "mask strokes do not paint the layer");
assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history");
let overlay_size: u32 = 64;
let rgba_bytes = (overlay_size * overlay_size * 4) as usize;
assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size");
execute(&mut s, "viewport.quickMask", &json!({"enabled": false})).unwrap();
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap();
dab(&mut s, 150.0, 200.0);
assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open");
execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap();
dab(&mut session, 150.0, 200.0);
dab(&mut session, 250.0, 200.0);
assert!(red(color_at(&session, 150.0, 200.0)), "inside the mask");
assert!(!red(color_at(&session, 250.0, 200.0)), "outside the mask");
execute(&mut session, "viewport.quickMask.invert", &Value::Null).unwrap();
dab(&mut session, 250.0, 200.0);
assert!(red(color_at(&session, 250.0, 200.0)), "inverted: outside is open");
execute(&mut session, "viewport.quickMask", &json!({"enabled": false})).unwrap();
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap();
dab(&mut session, 150.0, 200.0);
assert!(color_at(&session, 150.0, 200.0)[1] > 0.85, "disabled: everything is open");
}
/// How much redder than green a texel must be to count as painted (faded edges included)
+66
View File
@@ -586,6 +586,72 @@ fn curvature_generators_take_a_mode_and_detail_sizes() {
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}");
}
#[test]
fn changing_generator_kind_keeps_the_effect_identity_and_settings() {
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"].as_u64().unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "name": "Keep me", "opacity": 0.4, "level": 0.2})).unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap();
let later = execute(&mut state, "effect.add.generator", &json!({"generator": "position"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap();
let (owner, edited) = state.doc.project.effect(texturecraft_core::LayerId(effect)).unwrap();
assert!(matches!(&edited.kind, texturecraft_core::EffectKind::Generator(generator)
if generator.kind == texturecraft_core::GeneratorKind::AmbientOcclusion
&& generator.level == 0.2
&& matches!(generator.inputs.get(&texturecraft_core::BakedMap::AmbientOcclusion), Some(texturecraft_core::Source::Uniform([0.25, 0.25, 0.25])))));
assert_eq!(edited.name, "Keep me");
assert_eq!(edited.opacity, 0.4);
let layer = state.doc.project.layer(owner).unwrap();
let ids: Vec<u64> = layer.mask.as_ref().unwrap().effects.iter().map(|item| item.id.0).collect();
assert_eq!(ids, vec![effect, later]);
}
#[test]
fn unparseable_color_param_returns_error() {
let mut s = session();
+3
View File
@@ -9,9 +9,12 @@ license.workspace = true
workspace = true
[dependencies]
# ICC v2 serialization prerequisite: craft-libs#1735; app colour policy stays local.
craft-cms-icc-v2 = { package = "craft-cms", version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "272a095b61257917693da3d09f2f8ecccd7f0295" }
craft-materialx = { workspace = true }
craft-mesh = { workspace = true }
craft-mcmat = { workspace = true }
craft-tcraft = { workspace = true }
craft-zip = { workspace = true }
texturecraft-core = { workspace = true }
texturecraft-texel = { workspace = true }
+31 -110
View File
@@ -1,63 +1,7 @@
//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small
//! (about 1.2 KiB) and readable by every colour-managed viewer and editor.
//!
//! The colorants come from the space's primaries adapted to the D50 profile connection space
//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear
//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied
//! from a colour-management library or from another profile.
//! ICC v2.1 export policy; byte serialization is shared with craft-cms.
use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile};
use texturecraft_texel::{ColorSpace, srgb_to_linear};
/// Samples of the sRGB curve table.
const CURVE_POINTS: usize = 1024;
/// The D50 white of the profile connection space.
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
fn s15f16(v: f64) -> [u8; 4] {
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
}
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
let mut b = b"XYZ \0\0\0\0".to_vec();
for c in v {
b.extend_from_slice(&s15f16(c));
}
b
}
fn text_tag(text: &str) -> Vec<u8> {
let mut b = b"text\0\0\0\0".to_vec();
b.extend_from_slice(text.as_bytes());
b.push(0);
b
}
/// `textDescriptionType` with the ASCII description only.
fn desc_tag(text: &str) -> Vec<u8> {
let mut b = b"desc\0\0\0\0".to_vec();
b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
b.extend_from_slice(text.as_bytes());
b.push(0);
// No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler.
b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]);
b
}
fn curve_tag(space: ColorSpace) -> Vec<u8> {
let mut b = b"curv\0\0\0\0".to_vec();
if space == ColorSpace::Srgb {
b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes());
for i in 0..CURVE_POINTS {
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
}
} else {
// One entry is a gamma, u8Fixed8: 1.0 is linear.
b.extend_from_slice(&1u32.to_be_bytes());
b.extend_from_slice(&0x0100u16.to_be_bytes());
}
b
}
fn description(space: ColorSpace) -> &'static str {
match space {
@@ -68,64 +12,41 @@ fn description(space: ColorSpace) -> &'static str {
}
}
/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones).
/// The ICC profile of `space`, or None if its primaries are degenerate.
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
let m = space.to_xyz_d50()?;
let column = |c: usize| [m[0][c], m[1][c], m[2][c]];
let curve = curve_tag(space);
// The green and blue curves are the red one's entry.
let tags: [(&[u8; 4], Vec<u8>); 9] = [
(b"desc", desc_tag(description(space))),
(b"cprt", text_tag("No copyright, generated by TextureCraft")),
(b"wtpt", xyz_tag(D50_XYZ)),
(b"rXYZ", xyz_tag(column(0))),
(b"gXYZ", xyz_tag(column(1))),
(b"bXYZ", xyz_tag(column(2))),
(b"rTRC", curve.clone()),
(b"gTRC", curve.clone()),
(b"bTRC", curve),
];
// Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes.
let table_end = 128 + 4 + 12 * tags.len();
let mut offsets = Vec::new();
let mut data: Vec<u8> = Vec::new();
for (i, (_, bytes)) in tags.iter().enumerate() {
let shared = i >= 7;
let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() };
offsets.push(at);
if !shared {
data.extend_from_slice(bytes);
while !data.len().is_multiple_of(4) {
data.push(0);
}
}
}
let total = table_end + data.len();
let mut out = vec![0u8; 128];
out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes());
out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0
out.get_mut(12..16)?.copy_from_slice(b"mntr");
out.get_mut(16..20)?.copy_from_slice(b"RGB ");
out.get_mut(20..24)?.copy_from_slice(b"XYZ ");
// A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes.
out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
out.get_mut(36..40)?.copy_from_slice(b"acsp");
for (k, v) in D50_XYZ.iter().enumerate() {
out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v));
}
out.extend_from_slice(&(tags.len() as u32).to_be_bytes());
for ((sig, bytes), at) in tags.iter().zip(&offsets) {
out.extend_from_slice(*sig);
out.extend_from_slice(&(*at as u32).to_be_bytes());
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
}
out.extend_from_slice(&data);
Some(out)
let matrix = space.to_xyz_d50()?;
let samples: Vec<u16> = if space == ColorSpace::Srgb {
(0..CURVE_POINTS)
.map(|i| {
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
(v * 65535.0).round().clamp(0.0, 65535.0) as u16
})
.collect()
} else {
Vec::new()
};
matrix_profile(&MatrixProfile {
matrix,
curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) },
description: description(space),
copyright: "No copyright, generated by TextureCraft",
date: [2026, 1, 1, 0, 0, 0],
})
}
#[cfg(test)]
#[path = "icc_legacy_test.rs"]
mod legacy;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn all_spaces_match_legacy_wire_bytes() {
for space in ColorSpace::ALL {
assert_eq!(profile(space), legacy::profile(space), "{space:?}");
}
}
fn u32_at(b: &[u8], i: usize) -> u32 {
u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
+124
View File
@@ -0,0 +1,124 @@
//! ICC profiles for the export colour spaces: a version 2.1 matrix/curve display profile, small
//! (about 1.2 KiB) and readable by every colour-managed viewer and editor.
//!
//! The colorants come from the space's primaries adapted to the D50 profile connection space
//! (see `ColorSpace::to_xyz_d50`). sRGB carries its transfer curve as a sampled table; the linear
//! spaces carry a gamma of 1. Written from the ICC.1:2001-04 specification; nothing is copied
//! from a colour-management library or from another profile.
use texturecraft_texel::{ColorSpace, srgb_to_linear};
/// Samples of the sRGB curve table.
const CURVE_POINTS: usize = 1024;
/// The D50 white of the profile connection space.
const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249];
fn s15f16(v: f64) -> [u8; 4] {
((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes()
}
fn xyz_tag(v: [f64; 3]) -> Vec<u8> {
let mut b = b"XYZ \0\0\0\0".to_vec();
for c in v {
b.extend_from_slice(&s15f16(c));
}
b
}
fn text_tag(text: &str) -> Vec<u8> {
let mut b = b"text\0\0\0\0".to_vec();
b.extend_from_slice(text.as_bytes());
b.push(0);
b
}
/// `textDescriptionType` with the ASCII description only.
fn desc_tag(text: &str) -> Vec<u8> {
let mut b = b"desc\0\0\0\0".to_vec();
b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes());
b.extend_from_slice(text.as_bytes());
b.push(0);
// No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler.
b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]);
b
}
fn curve_tag(space: ColorSpace) -> Vec<u8> {
let mut b = b"curv\0\0\0\0".to_vec();
if space == ColorSpace::Srgb {
b.extend_from_slice(&(CURVE_POINTS as u32).to_be_bytes());
for i in 0..CURVE_POINTS {
let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
b.extend_from_slice(&((v * 65535.0).round().clamp(0.0, 65535.0) as u16).to_be_bytes());
}
} else {
// One entry is a gamma, u8Fixed8: 1.0 is linear.
b.extend_from_slice(&1u32.to_be_bytes());
b.extend_from_slice(&0x0100u16.to_be_bytes());
}
b
}
fn description(space: ColorSpace) -> &'static str {
match space {
ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)",
ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)",
ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)",
ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)",
}
}
/// The ICC profile of `space`, or None if its primaries are degenerate (never for the built-in ones).
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
let m = space.to_xyz_d50()?;
let column = |c: usize| [m[0][c], m[1][c], m[2][c]];
let curve = curve_tag(space);
// The green and blue curves are the red one's entry.
let tags: [(&[u8; 4], Vec<u8>); 9] = [
(b"desc", desc_tag(description(space))),
(b"cprt", text_tag("No copyright, generated by TextureCraft")),
(b"wtpt", xyz_tag(D50_XYZ)),
(b"rXYZ", xyz_tag(column(0))),
(b"gXYZ", xyz_tag(column(1))),
(b"bXYZ", xyz_tag(column(2))),
(b"rTRC", curve.clone()),
(b"gTRC", curve.clone()),
(b"bTRC", curve),
];
// Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes.
let table_end = 128 + 4 + 12 * tags.len();
let mut offsets = Vec::new();
let mut data: Vec<u8> = Vec::new();
for (i, (_, bytes)) in tags.iter().enumerate() {
let shared = i >= 7;
let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() };
offsets.push(at);
if !shared {
data.extend_from_slice(bytes);
while !data.len().is_multiple_of(4) {
data.push(0);
}
}
}
let total = table_end + data.len();
let mut out = vec![0u8; 128];
out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes());
out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0
out.get_mut(12..16)?.copy_from_slice(b"mntr");
out.get_mut(16..20)?.copy_from_slice(b"RGB ");
out.get_mut(20..24)?.copy_from_slice(b"XYZ ");
// A fixed date (2026-01-01 00:00:00), so a space always gives the same bytes.
out.get_mut(24..36)?.copy_from_slice(&[0x07, 0xEA, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]);
out.get_mut(36..40)?.copy_from_slice(b"acsp");
for (k, v) in D50_XYZ.iter().enumerate() {
out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v));
}
out.extend_from_slice(&(tags.len() as u32).to_be_bytes());
for ((sig, bytes), at) in tags.iter().zip(&offsets) {
out.extend_from_slice(*sig);
out.extend_from_slice(&(*at as u32).to_be_bytes());
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
}
out.extend_from_slice(&data);
Some(out)
}
@@ -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;
@@ -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<bool>,
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<bool>, metadata_bytes: u64) -> io::Result<Self> {
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<R: Read> Read for MetadataReader<'_, R> {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
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<R: Seek> Seek for MetadataReader<'_, R> {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
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());
}
}
+53 -152
View File
@@ -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,21 +30,21 @@ 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};
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 +123,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError {
}
}
#[cfg(test)]
fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
let mut b = MAGIC.to_vec();
for v in [BIN_VERSION, w, h, comps as u32, count as u32] {
@@ -132,19 +132,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
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 +168,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet<String>) -> 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 +297,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<Vec<f32>> {
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<T>(result: std::result::Result<T, craft_tcraft::Error>, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result<T> {
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<TileImage> {
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<u16> = 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<f32>)> {
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.
@@ -422,47 +339,31 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
}
fn check_archive<R: Read + Seek>(zip: &mut ZipArchive<R>, 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<bool>, metadata_bytes: u64) -> Result<ZipArchive<MetadataReader<'a, R>>> {
let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?;
fn open_archive<R: Read + Seek>(reader: R, metadata_bytes: u64) -> Result<ZipArchive<craft_zip::MetadataReader<R>>> {
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<R: Read + Seek>(reader: R, mut budget: LoadBudget) -> Result<ProjectFile> {
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")?;
#[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}")))?;
+19 -11
View File
@@ -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();
@@ -803,13 +812,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<u32> = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect();
let bytes: Vec<u8> = 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::<Vec<_>>(), values);
assert_eq!(reader.position(), (values.len() * 4) as u64);
assert_eq!(reader.position(), declared);
assert_eq!(budget.remaining(), 0);
}
#[test]
@@ -818,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]
@@ -845,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);
+7 -1
View File
@@ -13,7 +13,7 @@ use std::path::PathBuf;
/// has a download budget: of the CJK faces only the Japanese one, ~4.5 MB).
const MANIFESTS: &[(&str, Faces, Faces)] = &[
("fonts/manifest.txt", &[("BIZ UDPGothic", "Regular"), ("Noto Sans CJK SC", "Regular"), ARABIC], &[("BIZ UDPGothic", "Regular"), ARABIC]),
// The interface font, regular and semibold (0.8 MB).
// The interface font has regular and semibold faces
(LATIN_MANIFEST, LATIN, LATIN),
];
/// The Arabic face (0.8 MB, so the web build has it too).
@@ -38,6 +38,7 @@ fn main() {
Err(e) => println!("cargo::warning=building without craft-fonts: CRAFT_FONTS_DIR={}: {e}", dir.display()),
}
}
src.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs");
if let Err(e) = std::fs::write(&out, src) {
@@ -52,6 +53,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
if rel == LATIN_MANIFEST && !manifest.exists() {
return Ok(String::new());
}
let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?;
let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32");
let wanted = if wasm { web } else { desktop };
@@ -61,9 +63,11 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
let [family, style, file, scripts, ..] = f.as_slice() else {
return Err(format!("malformed manifest line: {line}"));
};
if !wanted.contains(&(*family, *style)) {
continue;
}
let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?;
println!("cargo::rerun-if-changed={}", path.display());
if rel == LATIN_MANIFEST {
@@ -72,6 +76,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
std::fs::write(&out, without_private_use(&bytes).map_err(|e| format!("{file}: {e}"))?).map_err(|e| format!("{}: {e}", out.display()))?;
path = out;
}
let scripts: Vec<String> = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect();
let _ = writeln!(
out,
@@ -80,6 +85,7 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web:
path.display().to_string(),
);
}
Ok(out)
}
+11 -3
View File
@@ -13,9 +13,11 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
source.push_str("];\n");
return Ok(source);
};
if !dir.is_absolute() {
return Err("CRAFT_I18N_DIR must be an absolute path".into());
}
let locales = dir.join("locales");
let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?;
println!("cargo::rerun-if-changed={}", locales.display());
@@ -26,23 +28,26 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
paths.push(entry.path());
}
}
paths.sort();
let mut count = 0;
let mut catalogs = Vec::new();
for path in paths {
// Watch directories too: adding/removing an app catalog must rebuild the embedding.
// Watch directories so adding or removing an app catalog rebuilds the embedding
println!("cargo::rerun-if-changed={}", path.display());
let app = path.join("texturecraft.tsv");
if !app.is_file() {
continue;
}
let locale = path.file_name().and_then(|n| n.to_str()).ok_or("non-UTF-8 locale")?;
let common = path.join("common.tsv");
let embed = |file: &Path| -> Result<(String, &'static str), String> {
let text = std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
let name = file.to_str().ok_or("non-UTF-8 catalog path")?;
println!("cargo::rerun-if-changed={name}");
// The shared runtime requires static inputs; this short-lived build process owns them.
// The shared runtime needs static inputs for this short-lived build process
Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str())))
};
let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") };
@@ -55,12 +60,14 @@ pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
if required && count == 0 {
return Err("no TextureCraft translation catalogs found".into());
}
// Reject the same rows the runtime would skip, before required builds can ship English fallbacks.
// Reject rows the runtime would skip before required builds can ship English fallbacks
let (runtime, mut problems) = craft_i18n::I18n::new(Box::leak(catalogs.into_boxed_slice()), &[]);
problems.extend(runtime.check_all());
if !problems.is_empty() {
return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; ")));
}
source.push_str("];\n");
Ok(source)
}
@@ -83,6 +90,7 @@ pub fn embed() {
"pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into()
}
};
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs");
if let Err(error) = std::fs::write(&out, source) {
println!("cargo::error=writing {}: {error}", out.display());
+138
View File
@@ -0,0 +1,138 @@
//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab
use egui::Ui;
use serde_json::json;
use std::path::Path;
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
use crate::TextureCraftApp;
use crate::i18n::tr;
/// The preset name field's width in points
const NAME_WIDTH: f32 = 110.0;
/// A name field and a button that saves the current brush under that name
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) {
let dir = crate::user_dir("brushes");
let name_id = ui.make_persistent_id("brush_preset_name");
let confirm_id = ui.make_persistent_id("brush_preset_overwrite");
let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default();
let mut pending_path: Option<std::path::PathBuf> = ui.data_mut(|data| data.get_temp(confirm_id));
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH));
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim())));
match std::fs::symlink_metadata(&path) {
Ok(_) => pending_path = Some(path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if save_brush(app, &dir, &path) {
new_name.clear();
}
}
Err(_) => pending_path = Some(path),
}
}
});
if let Some(path) = pending_path.clone() {
let mut replace = false;
let mut cancel = false;
egui::Window::new(tr("Replace"))
.id(ui.make_persistent_id("brush_preset_replace_dialog"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ui.ctx(), |ui| {
ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default());
ui.horizontal(|ui| {
replace = ui.button(tr("Replace")).clicked();
cancel = ui.button(tr("Cancel")).clicked();
});
});
if replace {
if save_brush(app, &dir, &path) {
new_name.clear();
}
pending_path = None;
} else if cancel {
pending_path = None;
}
}
ui.data_mut(|data| {
data.insert_temp(name_id, new_name);
data.insert_temp(confirm_id, pending_path);
});
}
/// Preserve Unicode names and encode filename punctuation without collisions
fn preset_file_stem(name: &str) -> String {
let mut stem = String::new();
// Six digits cover every Unicode scalar and separate adjacent escapes
for character in name.chars() {
if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' {
stem.push(character);
} else {
stem.push_str(&format!("~{:06X}", character as u32));
}
}
let uppercase = stem.to_ascii_uppercase();
if matches!(
uppercase.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
) {
stem.insert_str(0, "brush-");
}
stem
}
/// Save a preset and invalidate cached tiles only when the write succeeds
fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool {
// A folder that cannot be made is reported by the save command
let _ = std::fs::create_dir_all(dir);
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() {
return false;
}
app.brushes = None;
app.thumbs.forget_saved_files();
true
}
#[cfg(test)]
mod tests {
use super::preset_file_stem;
#[test]
fn distinct_unicode_brush_names_have_distinct_safe_file_stems() {
assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画"));
assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb"));
assert_eq!(preset_file_stem("水彩"), "水彩");
assert!(!preset_file_stem("a/b").contains('/'));
assert_eq!(preset_file_stem("CON"), "brush-CON");
}
}
+557 -420
View File
File diff suppressed because it is too large. Load diff
+55 -28
View File
@@ -133,17 +133,28 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node<Panel>, second: Node<Pane
Node::Split { axis, size, first: Box::new(first), second: Box::new(second) }
}
/// The default: assets left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties; ratios fit 1600x960
/// The default: assets (4 tile columns at 1920 px) left of the viewport, then texture sets, layers (tabbed with texture set settings) and properties
pub fn default_workspace() -> Workspace {
use Panel::*;
// The Assets split keeps four tiles visible at the reference window width
const ASSETS_SPLIT_RATIO: f32 = 0.16;
const VIEWPORT_SPLIT_RATIO: f32 = 0.80;
const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125;
const LAYERS_SPLIT_RATIO: f32 = 0.57;
let column = split(
SplitAxis::Vertical,
SplitSize::Ratio(0.125),
SplitSize::Ratio(TEXTURE_SET_SPLIT_RATIO),
tabs(&[TextureSetList]),
split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
split(SplitAxis::Vertical, SplitSize::Ratio(LAYERS_SPLIT_RATIO), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])),
);
let root = split(
SplitAxis::Horizontal,
SplitSize::Ratio(ASSETS_SPLIT_RATIO),
tabs(&[Assets]),
split(SplitAxis::Horizontal, SplitSize::Ratio(VIEWPORT_SPLIT_RATIO), tabs(&[Viewport]), column),
);
let root =
split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column));
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
for panel in Panel::ALL {
@@ -215,6 +226,9 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> {
// ---------------------------------------------------------------------------------------------
// The live dock
/// Height of a panel group's tab strip, in points
pub(crate) const TAB_HEIGHT: f32 = 30.0;
/// Width of the bake layout's texture set and mesh map bakers column, in points
const BAKERS_COLUMN_WIDTH: f32 = 200.0;
/// Width of the bake layout's common and mesh map settings column, in points
@@ -367,29 +381,42 @@ fn area_id() -> Id {
Id::unique("texturecraft-docking")
}
/// The dock look: every panel group is a card on the window's frame colour, its tab strip
/// without hard lines, the shown tab a pill.
fn style(ui: &Ui, t: &Tokens) -> DockStyle {
let mut s = DockStyle::from_ui(ui);
s.gap = f32::from(crate::theme::GUTTER);
// Smallest panel extent a divider drag leaves.
s.min_pane = 60.0;
s.background = t.panel;
s.tab_background = t.panel;
s.active_background = t.button;
s.text = t.text_strong;
s.inactive_text = t.text_dim;
s.border = egui::Stroke::NONE;
s.accent = t.accent;
s.floating_background = t.panel;
s.floating_stroke = egui::Stroke::new(1.0, t.button_border);
s.font = egui::FontId::proportional(12.5);
s.min_tab_width = 54.0;
s.tab_height = 30.0;
// Panels arrange in a split tree around the viewport; floating title bars only move windows.
s.new_dock_zones = false;
s.title_bar_docks = false;
s
/// Smallest panel extent a divider drag leaves, in points
const MIN_PANE_EXTENT: f32 = 60.0;
/// Border width of a floating panel, in points
const FLOATING_BORDER_WIDTH: f32 = 1.0;
/// Text size of the panel tabs, in points
const TAB_TEXT_SIZE: f32 = 12.5;
/// Narrowest panel tab, in points
const MIN_TAB_WIDTH: f32 = 54.0;
/// The dock look: each panel group a card on the window's frame colour, tab strips without hard lines, the shown tab a pill
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
let mut dock_style = DockStyle::from_ui(ui);
dock_style.gap = f32::from(crate::theme::GUTTER);
dock_style.min_pane = MIN_PANE_EXTENT;
dock_style.background = tokens.panel;
dock_style.tab_background = tokens.panel;
dock_style.active_background = tokens.button;
dock_style.text = tokens.text_strong;
dock_style.inactive_text = tokens.text_dim;
dock_style.border = egui::Stroke::NONE;
dock_style.accent = tokens.accent;
dock_style.floating_background = tokens.panel;
dock_style.floating_stroke = egui::Stroke::new(FLOATING_BORDER_WIDTH, tokens.button_border);
dock_style.font = egui::FontId::proportional(TAB_TEXT_SIZE);
dock_style.min_tab_width = MIN_TAB_WIDTH;
dock_style.tab_height = TAB_HEIGHT;
// Panels arrange in a split tree around the viewport; floating title bars only move windows
dock_style.new_dock_zones = false;
dock_style.title_bar_docks = false;
dock_style
}
/// Whether a modal layer or update dialog holds the input, so the panels, floating ones included,
+394
View File
@@ -0,0 +1,394 @@
//! 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() && kind != generator.kind {
app.run("effect.set", json!({"effect": id, "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()) else { return };
let (smallest, largest) = texture_set
.uv_tiles
.iter()
.map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution))
.fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size)));
let (smallest, largest) = if largest == 0 {
let size = resolution.output_size(texture_set.resolution, texture_set.resolution);
(size, size)
} else {
(smallest, largest)
};
let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") };
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(size_label));
})
.response
.on_hover_text(tr("An output finer than a UV tile gives the same result as that tile'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::<bool>(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(&current).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);
}
+9
View File
@@ -0,0 +1,9 @@
//! A grid tile's measurements in the shelf's small, medium and large views
/// A grid tile's size and its thumbnail's size and center below the tile's top, in points
pub(crate) struct GridTile {
pub(crate) width: f32,
pub(crate) height: f32,
pub(crate) thumbnail_size: f32,
pub(crate) thumbnail_center_y: f32,
}
+39 -36
View File
@@ -158,35 +158,36 @@ mod tests {
fn catalog_keys() -> Vec<&'static str> {
use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind};
use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params};
let mut k: Vec<&'static str> = Vec::new();
k.extend(crate::menus::TOP);
for i in crate::menus::CATALOG.iter().filter(|i| i.label != "-") {
k.push(i.label);
k.extend(i.sub);
let mut keys: Vec<&'static str> = Vec::new();
keys.extend(crate::menus::TOP);
for item in crate::menus::CATALOG.iter().filter(|item| item.label != "-") {
keys.push(item.label);
keys.extend(item.sub);
}
k.extend(crate::docking::VIEWS.iter().map(|(_, p)| p.name()));
for b in crate::keymap::bindings() {
k.push(b.label);
k.push(b.group);
keys.extend(crate::docking::VIEWS.iter().map(|(_, panel)| panel.name()));
for binding in crate::keymap::bindings() {
keys.push(binding.label);
keys.push(binding.group);
}
k.extend(crate::shelf::TABS.iter().map(|t| t.2));
k.extend(Channel::ALL.iter().flat_map(|c| [c.label(), c.short()]));
k.extend(BlendMode::all().map(|m| m.label()));
k.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|m| m.label()));
k.extend(texturecraft_engine::Tool::ALL.iter().map(|t| t.label()));
k.extend(ProceduralKind::ALL.iter().map(|p| p.label()));
k.extend(GeneratorKind::ALL.iter().map(|g| g.label()));
k.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|a| a.label()));
k.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, l)| *l));
for f in FILTERS {
k.extend([f.label, f.group]);
if let Ok(EffectKind::Filter(x)) = build(f.id, &serde_json::Value::Null) {
k.push(x.label());
k.extend(scalar_params(&x).into_iter().map(|p| p.1));
keys.extend(crate::shelf::TABS.iter().map(|tab| tab.2));
keys.extend(Channel::ALL.iter().flat_map(|channel| [channel.label(), channel.short()]));
keys.extend(BlendMode::all().map(|mode| mode.label()));
keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label()));
keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label()));
keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label()));
keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label()));
keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label()));
keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label));
for filter in FILTERS {
keys.extend([filter.label, filter.group]);
if let Ok(EffectKind::Filter(effect)) = build(filter.id, &serde_json::Value::Null) {
keys.push(effect.label());
keys.extend(scalar_params(&effect).into_iter().map(|parameter| parameter.1));
}
}
// Effect, view and camera names the engine gives.
k.extend([
// Include effect, view and camera names supplied by the engine
keys.extend([
"Paint",
"Path",
"Fill",
@@ -199,8 +200,8 @@ mod tests {
texturecraft_engine::camera_cmds::DEFAULT_CAMERA,
crate::dock::SOLO_HINT,
]);
k.retain(|s| !s.is_empty() && !UNTRANSLATED.contains(s));
k
keys.retain(|key| !key.is_empty() && !UNTRANSLATED.contains(key));
keys
}
/// String literals passed straight to `tr(` or `trf(` in `src`.
@@ -254,7 +255,8 @@ mod tests",
for &(locale, common, app) in CRAFT_I18N {
let Some(lang) = I18N.from_code(locale) else { continue };
let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect();
// Decode TSV escapes for comparison with the literal source strings.
// Decode TSV escapes to compare with literal source strings
let mut rows = HashMap::new();
for text in [common, app] {
for line in text.lines().filter(|l| !l.starts_with('#')) {
@@ -335,17 +337,18 @@ mod tests",
let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let keys = keys();
set_language("ja");
let t = std::time::Instant::now();
let mut n = 0usize;
let started = std::time::Instant::now();
let mut total_chars = 0usize;
for _ in 0..100 {
for k in &keys {
n += tr(k).len();
for key in &keys {
total_chars += tr(key).len();
}
}
let per = t.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64;
let ns_per_lookup = started.elapsed().as_secs_f64() * 1e9 / (100 * keys.len()) as f64;
set_language("en");
assert!(n > 0);
// A frame looks up a few hundred strings: well under a microsecond each.
assert!(per < 1000.0, "{per:.0} ns per lookup");
assert!(total_chars > 0);
// A frame looks up a few hundred strings, each expected below one microsecond
assert!(ns_per_lookup < 1000.0, "{ns_per_lookup:.0} ns per lookup");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+12
View File
@@ -10,6 +10,8 @@
mod bake_job;
pub mod bake_mode;
mod bake_scene;
#[cfg(not(target_arch = "wasm32"))]
mod brush_preset_save;
mod color_selection_editor;
pub mod control;
mod decal_drop;
@@ -20,7 +22,9 @@ pub mod export_templates;
pub mod file_dialogs;
mod filter_slot;
pub mod fonts;
mod generator_panel;
pub mod gpu;
mod grid_tile;
pub mod i18n;
pub mod id_color_pick;
pub mod keymap;
@@ -46,8 +50,15 @@ pub mod render_mode;
mod resource_picker;
mod resource_picker_item;
mod running_bake;
pub mod saved_search;
pub mod shelf;
mod shelf_entry;
mod shelf_folders;
pub mod shelf_panes;
pub mod shelf_preview;
mod shelf_tabs;
mod shelf_toolbar;
pub mod shelf_view;
mod soft_box;
pub mod state;
pub mod symmetry;
@@ -682,6 +693,7 @@ impl eframe::App for TextureCraftApp {
self.poll_bake(ctx);
self.poll_resize(ctx);
self.poll_link_cooks(ctx);
self.thumbs.sync_images(&self.session.images, self.session.revision);
// The library shelf rescans when the window comes back (MaterialCraft may have sent a material)
let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true);
if focused && !self.focused {
+10 -2
View File
@@ -4,6 +4,7 @@
use egui::{Key, Modifiers};
use serde_json::{Value, json};
use texturecraft_engine::Tool;
use crate::TextureCraftApp;
use crate::i18n::tr;
@@ -110,7 +111,7 @@ fn is_ui(id: &str) -> bool {
id.starts_with("ui.")
}
/// Whether an item can run now.
/// Whether an item can run now
pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
if let Some(panel) = crate::docking::view_panel(id) {
return panel.available_in(app.ui.mode);
@@ -123,7 +124,14 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
if is_ui(id) {
return true;
}
texturecraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok())
// Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act
let tool = id.strip_prefix("tool.").and_then(|tool_id| Tool::ALL.into_iter().find(|tool| tool.id() == tool_id));
if tool.is_some_and(|tool| !app.session.tool_usable(tool)) {
return false;
}
texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok())
}
/// Whether an id is implemented at all (parity report).
+64 -24
View File
@@ -153,44 +153,84 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage {
preview
}
/// Preview the brush along an S curve in an `n`-pixel square
pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage {
let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image);
let radius = n as f32 * 0.11;
let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius);
let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin()));
let mut cover = vec![0f32; n * n];
// Stable jitter keeps the preview reproducible
let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32;
let step = (b.spacing * 2.0 * radius).max(0.5);
/// Preview the brush along an S curve in a `size_px` square
pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage {
// Leave room around the S curve and cap work for a single preview
const STROKE_RADIUS_FRACTION: f32 = 0.11;
const CURVE_SAMPLE_STEP: f32 = 0.002;
const MIN_STAMP_SPACING_PX: f32 = 0.5;
const MAX_STAMPS: u32 = 2000;
const CURVE_HORIZONTAL_INSET: f32 = 0.15;
const CURVE_HORIZONTAL_SPAN: f32 = 0.7;
const CURVE_WAVE_AMPLITUDE: f32 = 0.22;
let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image);
let radius = size_px as f32 * STROKE_RADIUS_FRACTION;
let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius);
// The horizontal inset and vertical wave keep the S curve inside the swatch
let curve = |t: f32| {
(
size_px as f32 * (CURVE_HORIZONTAL_INSET + CURVE_HORIZONTAL_SPAN * t),
size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()),
)
};
let mut cover = vec![0f32; size_px * size_px];
// Odd multipliers decorrelate reproducible jitter across stamps and channels
let jitter_sample = |stamp_index: u32, channel: u32| {
(stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32
};
let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX);
let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32);
let mut last = curve(0.0);
while t <= 1.0 && i < 2000 {
while t <= 1.0 && i < MAX_STAMPS {
let p = curve(t);
travelled += (p.0 - last.0).hypot(p.1 - last.1);
last = p;
t += 0.002;
t += CURVE_SAMPLE_STEP;
if travelled < step {
continue;
}
travelled = 0.0;
i += 1;
let r = radius * (1.0 - b.jitter_size * rnd(i, 1));
let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 };
let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2);
let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0));
let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5));
let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1));
let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 };
let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2);
let (cx, cy) = (
p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0),
p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0),
);
let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5));
let (sin, cos) = angle.sin_cos();
let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n));
let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n));
let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px));
let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px));
for y in y0..y1 {
for x in x0..x1 {
let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r);
let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow;
let c = &mut cover[y * n + x];
*c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0));
let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius);
let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow;
let coverage = &mut cover[y * size_px + x];
*coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0));
}
}
}
ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect())
ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect())
}
/// Environment `name`'s panorama across a `size²` swatch, transparent above and below
pub fn environment_image(name: &str, size: usize) -> ColorImage {
let panorama = texturecraft_render::ibl::environment(name, u32::try_from(size).unwrap_or(u32::MAX));
let (width, height) = (panorama.width as usize, panorama.height as usize);
let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT);
let top = size.saturating_sub(height) / 2;
for (y, row) in panorama.data.chunks(width.max(1)).enumerate() {
for (x, linear) in row.iter().enumerate().take(size) {
let Some(pixel) = image.pixels.get_mut((top + y) * size + x) else { continue };
let [r, g, b] = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8);
*pixel = Color32::from_rgb(r, g, b);
}
}
image
}
+12
View File
@@ -0,0 +1,12 @@
//! A shelf query the user saved in the Saved searches pane
use serde::{Deserialize, Serialize};
/// The search text, tab and library folder of a saved shelf query, under the name it lists as
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SavedSearch {
pub name: String,
pub filter: String,
pub tab: usize,
pub path: Vec<String>,
}
+295 -329
View File
@@ -1,40 +1,49 @@
//! The asset shelf (the Assets dock tab): tabs (materials, smart materials, smart
//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural.
//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas
//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties
//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu
//! The Assets panel: built-in, saved and project assets in one grid by type, library and search, dragged onto the layer stack, the views or the brush
use egui::{Color32, RichText, Sense, Stroke, Ui, vec2};
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::filter_lib::FILTERS;
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_engine::formats::mcmat::MCMAT_EXT;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::materials::MATERIALS;
use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX;
use texturecraft_engine::paint::alphas;
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::SMART_MASKS;
use texturecraft_render::ibl::ENVIRONMENTS;
use crate::TextureCraftApp;
use crate::decal_drop::DecalDrop;
use crate::i18n::{tr, trf};
use crate::shelf_entry::ShelfEntry;
use crate::shelf_preview::ShelfPreview;
use crate::shelf_view::ShelfView;
use crate::theme::Tokens;
use crate::thumbs::Thumbs;
use crate::widgets::{dnd_release, icon_button};
use crate::widgets::dnd_release;
/// A shelf tile's size in points
const TILE_WIDTH: f32 = 72.0;
const TILE_HEIGHT: f32 = 86.0;
/// The gap between tiles in points (their sizes are [`ShelfView`]'s)
const TILE_GAP: f32 = 2.0;
/// The gap after a grid or a list of rows, in points
const SECTION_GAP: f32 = 6.0;
/// The gap between the type row and asset grid, in points
const TYPE_GRID_GAP: f32 = 4.0;
/// The saved material hint's font size, in points
#[cfg(not(target_arch = "wasm32"))]
const HINT_SIZE: f32 = 10.0;
/// The name of a saved material whose file name isn't text
const SAVED_MATERIAL_NAME: &str = "material";
/// Corner radius of a tile's hover and selection highlights, in points
const TILE_ROUNDING: f32 = 3.0;
/// The thumbnail's size in a tile and its center below the tile's top, in points
const THUMBNAIL_SIZE: f32 = 56.0;
const THUMBNAIL_CENTER_Y: f32 = 32.0;
/// The last clicked or right-clicked tile's [`ShelfEntry::identity`], kept in egui's memory under this id
const SELECTED_TILE: &str = "shelf_selected_tile";
/// The outline widths of the selected tile and of the one in use (the brush's alpha, the shown environment), in points
const SELECTED_OUTLINE_WIDTH: f32 = 1.5;
const IN_USE_OUTLINE_WIDTH: f32 = 1.0;
/// The randomness badge's dot radius, dot spacing and inset from the thumbnail's corner, in points
const BADGE_DOT_RADIUS: f32 = 1.3;
const BADGE_DOT_SPACING: f32 = 3.6;
const BADGE_INSET: f32 = 2.5;
/// The randomness badge's dot colour and its rim's width (points) and colour
const BADGE_DOT_FILL: Color32 = Color32::from_gray(205);
const BADGE_DOT_RIM: f32 = 0.8;
const BADGE_DOT_RIM_COLOR: Color32 = Color32::from_black_alpha(170);
/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color
const LOADING_ICON_SCALE: f32 = 0.9;
const LOADING_ICON_OPACITY: f32 = 0.5;
@@ -56,22 +65,21 @@ pub(crate) enum Tab {
Filters,
Brushes,
Alphas,
Procedurals,
Environments,
/// Procedural patterns and the project's images
Textures,
Environments,
}
/// The shelf tabs: icon and (English, translated where shown) name.
pub(crate) const TABS: [(Tab, &str, &str); 9] = [
/// The shelf tabs: icon and (English, translated where shown) name
pub(crate) const TABS: [(Tab, &str, &str); 8] = [
(Tab::Materials, ic::SPHERE, "Materials"),
(Tab::Smart, ic::STACK, "Smart materials"),
(Tab::Masks, ic::CIRCLE_HALF, "Smart masks"),
(Tab::Filters, ic::FUNNEL, "Filters"),
(Tab::Brushes, ic::PAINT_BRUSH_BROAD, "Brushes"),
(Tab::Alphas, ic::SHAPES, "Alphas"),
(Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"),
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
(Tab::Textures, ic::IMAGE, "Textures"),
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
];
/// A shelf asset: built in (by id), a saved smart material (file path) or an image resource.
@@ -117,7 +125,7 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) {
&& content
&& let Some(name) = unpainted_paint_layer(app)
{
// Otherwise the filter seems to do nothing: it has nothing to change yet.
// Otherwise the filter seems to do nothing: it has nothing to change yet
app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false);
}
return;
@@ -223,55 +231,106 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response
/// The Assets panel body (a dock tab)
pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let ctx = ui.ctx().clone();
let mut tab = app.ui.shelf_tab.min(TABS.len() - 1);
let searching = !app.ui.shelf_filter.is_empty();
let filter = app.ui.shelf_filter.to_lowercase();
scan_library(app);
scan_brushes(app);
let all = ShelfEntry::all(app);
let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all));
ui.horizontal_wrapped(|ui| {
let button_size = ui.spacing().interact_size.y;
ui.spacing_mut().item_spacing = vec2(2.0, 2.0);
for (i, (_, icon, label)) in TABS.iter().enumerate() {
if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() {
tab = i;
app.ui.shelf_filter.clear();
}
// A folder that is gone (its last image removed) shows everything again
if !paths.iter().any(|path| path.starts_with(&app.ui.shelf_path)) {
app.ui.shelf_path.clear();
}
let folder = app.ui.shelf_path.clone();
let picked_tab = app.ui.shelf_tab;
let searched: Vec<ShelfEntry> = all.into_iter().filter(|entry| entry.matches(&filter)).collect();
let mut applicable = crate::shelf_folders::paths(searched.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab())));
let matching: Vec<ShelfEntry> = searched.into_iter().filter(|entry| entry.in_folder(&folder)).collect();
let mut counts: Vec<usize> = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect();
// Saved smart materials list under the grid rather than as tiles, so they count apart
let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER);
let saved_materials_matching = saved_materials_matching(app, &filter);
if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) {
*smart += saved_materials_matching;
}
if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) {
applicable.push(vec![crate::shelf_entry::USER.to_string()]);
}
crate::shelf_folders::breadcrumb(app, ui, &paths);
search_field(app, ui);
crate::shelf_tabs::row(app, ui, &counts, crate::shelf_view::menu);
ui.add_space(TYPE_GRID_GAP);
let tab = app.ui.shelf_tab;
let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown);
let mut entries: Vec<ShelfEntry> = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect();
entries.sort_by_cached_key(|entry| entry.label().to_lowercase());
// The toolbar has its own strip at the panel's bottom, so nothing above it can push it out
let area = ui.available_rect_before_wrap();
let toolbar_top = (area.bottom() - crate::shelf_toolbar::height(ui)).max(area.top());
let grid_rect = egui::Rect::from_min_max(area.min, egui::pos2(area.right(), toolbar_top));
let toolbar_rect = egui::Rect::from_min_max(egui::pos2(area.left(), toolbar_top), area.max);
ui.scope_builder(egui::UiBuilder::new().max_rect(grid_rect).layout(egui::Layout::left_to_right(egui::Align::Min)), |ui| {
if let Some(width) = crate::shelf_panes::column_width(app, ui.available_width()) {
ui.allocate_ui_with_layout(vec2(width, grid_rect.height()), egui::Layout::top_down(egui::Align::Min), |ui| {
ui.set_min_size(vec2(width, grid_rect.height()));
crate::shelf_panes::column(app, ui, &paths, &applicable);
});
ui.separator();
}
});
app.ui.shelf_tab = tab;
// Saved smart materials are files in the user's library, without folders of their own
let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart);
grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter);
});
ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui));
drag_preview(&ctx);
}
/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials`
fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) {
let view = app.ui.shelf_view;
let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE)));
egui::ScrollArea::vertical()
.id_salt("shelf_scroll")
.auto_shrink([false, false])
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
.max_height(height)
.show(ui, |ui| {
tiles(ui, |ui| {
for entry in entries {
let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str()));
entry_tile(app, ui, ctx, entry, view, is_selected);
}
});
if saved_materials {
library(app, ui, filter);
}
});
}
/// How many of the user's saved smart materials match `filter` (none until the library is read)
fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize {
app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count()
}
/// The search field: a live filter on names (and categories) with a clear button while it has text
fn search_field(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim));
ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY));
});
ui.add_space(4.0);
let filter = app.ui.shelf_filter.to_lowercase();
egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| {
// Searching shows matches from every tab, each under its tab's name
for (i, (t, _, title)) in TABS.iter().enumerate() {
if filter.is_empty() && i != tab {
continue;
}
let title = tr(title);
match t {
Tab::Materials => materials(app, ui, &ctx, &filter, false, title),
Tab::Smart => {
materials(app, ui, &ctx, &filter, true, title);
library(app, ui, &filter);
}
Tab::Masks => smart_masks(app, ui, &ctx, &filter, title),
Tab::Filters => filters(app, ui, &ctx, &filter, title),
Tab::Brushes => brushes(app, ui, &ctx, &filter, title),
Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title),
Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title),
Tab::Environments => environments(app, ui, &filter, title),
Tab::Textures => textures(app, ui, &ctx, &filter, title),
}
let clear_width = if app.ui.shelf_filter.is_empty() { 0.0 } else { ui.spacing().interact_size.y + ui.spacing().item_spacing.x };
let field = egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search")).desired_width(ui.available_width() - clear_width);
ui.add(field);
if !app.ui.shelf_filter.is_empty() && ui.add(egui::Button::new(ic::X).frame(false)).on_hover_text(tr("Clear")).clicked() {
app.ui.shelf_filter.clear();
}
});
drag_preview(&ctx);
}
/// The dragged asset's name next to the pointer.
@@ -290,11 +349,6 @@ pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool {
filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter))
}
fn title(ui: &mut Ui, text: &str) {
let tk = Tokens::get(ui.ctx());
ui.label(RichText::new(text).strong().color(tk.text_strong));
}
pub(crate) fn header(ui: &mut Ui, text: &str) {
let tk = Tokens::get(ui.ctx());
ui.add_space(2.0);
@@ -303,10 +357,10 @@ pub(crate) fn header(ui: &mut Ui, text: &str) {
pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
ui.spacing_mut().item_spacing = vec2(TILE_GAP, TILE_GAP);
body(ui);
});
ui.add_space(6.0);
ui.add_space(SECTION_GAP);
}
/// The distinct categories of `items`, in order of first appearance.
@@ -320,46 +374,38 @@ pub(crate) fn categories<T>(items: &[T], category: impl Fn(&T) -> &'static str)
out
}
/// Built-in materials or smart materials, grouped by category
fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) {
let shown: Vec<_> =
MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect();
if shown.is_empty() {
/// Read the user's saved smart materials (desktop library folder) unless they are already listed
#[cfg(not(target_arch = "wasm32"))]
fn scan_library(app: &mut TextureCraftApp) {
if app.library.is_some() {
return;
}
title(ui, name);
for category in categories(&shown, |material| material.category) {
header(ui, category);
tiles(ui, |ui| {
for material in shown.iter().filter(|material| material.category == category) {
let texture = app.thumbs.material(ctx, material.id);
let asset = Asset::Material(material.id);
if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT);
let mut files: Vec<std::path::PathBuf> =
std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_material).collect()).unwrap_or_default();
files.sort();
app.library = Some(files);
}
/// The user's saved smart materials (desktop library folder).
#[cfg(target_arch = "wasm32")]
fn scan_library(_: &mut TextureCraftApp) {}
/// A saved smart material's name: its file name without the extension
fn saved_material_name(path: &std::path::Path) -> &str {
path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME)
}
/// The user's saved smart materials matching `filter`, as rows under the grid
#[cfg(not(target_arch = "wasm32"))]
fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
let tk = Tokens::get(ui.ctx());
if app.library.is_none() {
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(crate::library_dir())
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tcmat" || x == MCMAT_EXT)).collect())
.unwrap_or_default();
files.sort();
app.library = Some(files);
}
let tokens = Tokens::get(ui.ctx());
let files = app.library.clone().unwrap_or_default();
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("material").to_string();
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect();
if !filter.is_empty() && shown.is_empty() {
return;
}
ui.horizontal(|ui| {
header(ui, tr("My smart materials"));
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
@@ -367,276 +413,174 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
}
});
if files.is_empty() {
ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(10.0).color(tk.text_dim));
ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim));
}
for f in shown {
let (label, asset) = (name(f), Asset::Library(f.display().to_string()));
// MaterialCraft materials (sent from MaterialCraft) show a graph.
let glyph = if f.extension().is_some_and(|x| x == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE };
let r = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| {
for path in shown {
let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string()));
// MaterialCraft materials (sent from MaterialCraft) show a graph
let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE };
let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| {
ui.label(crate::i18n::trf(
"{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)",
&[("file", &f.display())],
&[("file", &path.display())],
));
});
if r.drag_started() {
r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label });
if response.drag_started() {
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label });
}
if r.clicked() {
if response.clicked() {
apply(app, &asset);
}
}
ui.add_space(6.0);
ui.add_space(SECTION_GAP);
}
#[cfg(target_arch = "wasm32")]
fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<_> = SMART_MASKS.iter().filter(|m| matches(filter, &[m.label, m.id])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
tiles(ui, |ui| {
for m in shown {
let tex = app.thumbs.smart_mask(ctx, m.id);
let asset = Asset::SmartMask(m.id);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
/// The filter library, grouped: a click adds the filter to the selected layer's content (or its
/// mask when the mask is selected), a drop onto a layer to that layer's content.
fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id, tr(f.label), tr(f.group)])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
for group in categories(&shown, |f| f.group) {
header(ui, tr(group));
tiles(ui, |ui| {
for f in shown.iter().filter(|f| f.group == group) {
let tex = app.thumbs.filter(ctx, f.id);
let asset = Asset::Filter(f.id);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() {
apply(app, &asset);
}
}
});
}
}
/// Brush presets, grouped by category, then the user's own: a click sets the brush's stroke
/// (alpha, spacing, flow, jitters…) and keeps its size.
fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<&BrushPreset> = PRESETS.iter().filter(|p| matches(filter, &[p.label, p.category, p.id])).collect();
if !shown.is_empty() {
title(ui, name);
for cat in categories(&shown, |p| p.category) {
header(ui, cat);
tiles(ui, |ui| {
for p in shown.iter().filter(|p| p.category == cat) {
let tex = app.thumbs.brush_preset(ctx, p);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() {
app.run("brush.preset.apply", json!({"preset": p.id}));
}
}
});
}
}
my_brushes(app, ui, filter);
}
/// The user's saved brush presets (desktop brushes folder) and saving the current brush there.
/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed
#[cfg(not(target_arch = "wasm32"))]
fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
fn scan_brushes(app: &mut TextureCraftApp) {
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
let dir = crate::user_dir("brushes");
if app.brushes.is_none() {
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect())
.unwrap_or_default();
files.sort();
app.brushes = Some(files);
}
let files = app.brushes.clone().unwrap_or_default();
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string();
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
if !filter.is_empty() && shown.is_empty() {
if app.brushes.is_some() {
return;
}
ui.horizontal(|ui| {
header(ui, tr("My brushes"));
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
app.brushes = None;
}
});
for f in shown {
if ui
.add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f))))
.on_hover_text(tr("Use this brush (keeps its size)"))
.clicked()
{
app.run("brush.preset.load", json!({"path": f.display().to_string()}));
}
}
ui.horizontal(|ui| {
let id = ui.make_persistent_id("brush_preset_name");
let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default();
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0));
let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim());
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
let path = dir.join(format!("{file}.{BRUSH_EXT}"));
// A folder that can't be made fails the save, which reports it.
let _ = std::fs::create_dir_all(&dir);
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() {
new_name.clear();
app.brushes = None;
}
}
ui.data_mut(|d| d.insert_temp(id, new_name));
});
ui.add_space(6.0);
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(crate::user_dir("brushes"))
.map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect())
.unwrap_or_default();
files.sort();
app.brushes = Some(files);
}
#[cfg(target_arch = "wasm32")]
fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
fn scan_brushes(_: &mut TextureCraftApp) {}
/// The built-in alpha library, grouped by category; the brush's alpha is outlined.
fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let tk = Tokens::get(ctx);
let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect();
if shown.is_empty() {
/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu
fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) {
// An image removed this frame has nothing to show
if let ShelfEntry::Image(name) = entry
&& !app.session.images.contains_key(name)
{
return;
}
title(ui, name);
let brush = &app.session.tool.brush;
let current = if brush.alpha_image.is_none() { brush.alpha_library.clone() } else { None };
for cat in categories(&shown, |a| a.category) {
header(ui, cat);
tiles(ui, |ui| {
for &a in shown.iter().filter(|a| a.category == cat) {
let tex = app.thumbs.alpha(ctx, a);
let asset = Asset::Alpha(&a.id);
let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset));
if current.as_deref() == Some(a.id.as_str()) {
ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
if r.clicked() {
apply(app, &asset);
}
let texture = entry.thumbnail(app, ctx);
let asset = entry.asset();
let session = &app.session;
let response = tile_in_view(
ui,
&mut app.thumbs,
texture.as_ref(),
|thumbs| match entry {
ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)),
_ => entry.preview(session),
},
entry.label(),
asset.as_ref(),
view,
);
if selected || entry.in_use(app) {
let tokens = Tokens::get(ctx);
let width = if selected { SELECTED_OUTLINE_WIDTH } else { IN_USE_OUTLINE_WIDTH };
ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(width, tokens.accent), egui::StrokeKind::Inside);
}
if entry.includes_randomness() {
randomness_badge(ui.painter(), view.thumbnail_rect(response.rect));
}
if response.clicked() || response.secondary_clicked() {
let (kind, id) = entry.identity();
ctx.data_mut(|data| data.insert_temp(egui::Id::unique(SELECTED_TILE), (kind.to_string(), id.to_string())));
}
if response.clicked() {
entry.activate(app);
}
if let ShelfEntry::Image(name) = entry {
response.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
}
fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let shown: Vec<ProceduralKind> = ProceduralKind::ALL.into_iter().filter(|k| matches(filter, &[k.label(), tr(k.label())])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
tiles(ui, |ui| {
for k in shown {
let tex = app.thumbs.procedural(ctx, k);
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() {
app.run("layer.add.fill", json!({"name": k.label()}));
app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]}));
}
}
});
}
fn environments(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, name: &str) {
let shown: Vec<&&str> = ENVIRONMENTS.iter().filter(|e| matches(filter, &[e])).collect();
if shown.is_empty() {
return;
}
title(ui, name);
for env in shown {
let on = app.session.doc.project.display.environment == **env;
if ui.selectable_label(on, format!("{} {env}", ic::SUN_HORIZON)).clicked() {
app.run("display.set", json!({"environment": env}));
}
}
ui.add_space(6.0);
}
fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
let tk = Tokens::get(ctx);
let names: Vec<String> = app.session.doc.resources.keys().filter(|n| matches(filter, &[n])).cloned().collect();
if !filter.is_empty() && names.is_empty() {
return;
}
ui.horizontal(|ui| {
title(ui, name);
if ui.small_button(tr("Import...")).clicked() {
crate::menus::invoke(app, ctx, "resource.import");
}
});
if names.is_empty() {
ui.label(RichText::new(tr("Import images to use them in fills and masks")).size(10.0).color(tk.text_dim));
}
tiles(ui, |ui| {
for name in names {
let Some(img) = app.session.images.get(&name).cloned() else { continue };
let tex = app.thumbs.image(ctx, &name, &img);
let asset = Asset::Texture(name.clone());
let preview = || ShelfPreview::Image(name.clone(), img);
let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset));
if r.clicked() {
apply(app, &asset);
}
r.context_menu(|ui| {
if ui.button(tr("Add as decal (view center)")).clicked() {
app.run("layer.add.decal", json!({"image": name}));
ui.close();
}
if ui.button(tr("Remove resource")).clicked() {
app.run("resource.remove", json!({"name": name}));
ui.close();
}
});
}
});
}
/// Asset tile with optional dragging and a larger hover preview
/// Asset tile with optional dragging and a larger hover preview, at the medium size
pub(crate) fn tile(
ui: &mut Ui,
thumbs: &mut Thumbs,
tex: Option<&egui::TextureHandle>,
texture: Option<&egui::TextureHandle>,
preview: impl FnOnce() -> ShelfPreview,
label: &str,
drag: Option<&Asset>,
) -> egui::Response {
let tk = Tokens::get(ui.ctx());
tile_in_view(ui, thumbs, texture, |_| Some(preview()), label, drag, ShelfView::Medium)
}
/// [`tile`] at `view`'s size: a grid tile with the name under the thumbnail, or a list row with it beside; `preview` runs on hover
fn tile_in_view(
ui: &mut Ui,
thumbs: &mut Thumbs,
texture: Option<&egui::TextureHandle>,
preview: impl FnOnce(&mut Thumbs) -> Option<ShelfPreview>,
label: &str,
drag: Option<&Asset>,
view: ShelfView,
) -> egui::Response {
let tokens = Tokens::get(ui.ctx());
let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() };
let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense);
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));
if let Some(asset) = drag
&& resp.drag_started()
&& response.drag_started()
{
resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
}
let painter = ui.painter();
if resp.hovered() || resp.dragged() {
painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover);
if response.hovered() || response.dragged() {
painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover);
}
let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
thumbnail(painter, tex, image_rect, &tk);
let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN);
painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text);
let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None };
resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label))
let image_rect = view.thumbnail_rect(rect);
thumbnail(painter, texture, image_rect, &tokens);
if view.name_beside() {
let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP;
let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text));
painter.galley(egui::pos2(left, rect.center().y - galley.size().y * 0.5), galley, tokens.text);
} else {
let galley = painter.layout_job(one_line(label, rect.width() - LABEL_MARGIN, tokens.text));
painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tokens.text);
}
let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None };
response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label))
}
/// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness
fn randomness_badge(painter: &egui::Painter, thumbnail: egui::Rect) {
let corner = thumbnail.right_bottom() - vec2(BADGE_INSET, BADGE_INSET);
for offset in [vec2(0.0, 0.0), vec2(-BADGE_DOT_SPACING, 0.0), vec2(-BADGE_DOT_SPACING * 0.5, -BADGE_DOT_SPACING)] {
painter.circle(corner + offset, BADGE_DOT_RADIUS, BADGE_DOT_FILL, Stroke::new(BADGE_DOT_RIM, BADGE_DOT_RIM_COLOR));
}
}
/// A tile label on one line, cut with "…" past `width` points (the hover popup shows the whole name)
fn one_line(label: &str, width: f32, color: Color32) -> egui::text::LayoutJob {
let mut job = egui::text::LayoutJob::single_section(label.to_string(), egui::TextFormat::simple(egui::FontId::proportional(LABEL_FONT_SIZE), color));
job.wrap = egui::text::TextWrapping::truncate_at_width(width);
job
}
/// Start rendering during the popup delay once the pointer rests
@@ -689,3 +633,25 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&
ui.label(label);
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_long_label_stays_on_one_line_ending_in_an_ellipsis() {
let width = 60.0;
let mut laid_out = None;
let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| {
laid_out = Some(ui.painter().layout_job(one_line("Steel Painted Rust Leaks Extra", width, Color32::WHITE)));
});
// The font atlas upload is not under test
output.textures_delta.clear();
let galley = laid_out.unwrap();
assert_eq!(galley.rows.len(), 1);
assert!(galley.size().x <= width);
assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…'));
}
}
+270
View File
@@ -0,0 +1,270 @@
//! One asset on the shelf: its name, the tab it belongs to, and how it previews, drags and applies
use std::path::PathBuf;
use serde_json::json;
use texturecraft_engine::Session;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::core::project::ENVIRONMENTS;
use texturecraft_engine::filter_lib::{FILTERS, FilterDef};
use texturecraft_engine::materials::{MATERIALS, SmartMaterial};
use texturecraft_engine::paint::alphas::{self, LibraryAlpha};
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
use texturecraft_engine::smart_masks::{SMART_MASKS, SmartMask};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf::{Asset, Tab, apply};
use crate::shelf_preview::ShelfPreview;
/// The name of a saved brush whose file name isn't text
const SAVED_BRUSH_NAME: &str = "brush";
/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines
const SEED_PROBES: usize = 4;
const SEED_PROBE_OFFSET: f32 = 0.13;
/// A smaller difference between the two seeds' samples is rounding
const SEED_TOLERANCE: f32 = 1e-4;
/// The libraries' ids: the open project's images, the built-in assets, the user's saved assets
pub(crate) const PROJECT: &str = "project";
pub(crate) const STARTER: &str = "starter";
pub(crate) const USER: &str = "user";
/// The libraries in the picker's order: id and (English, translated where shown) name
pub(crate) const LIBRARIES: [(&str, &str); 3] = [(PROJECT, "Project"), (STARTER, "Starter assets"), (USER, "Your assets")];
/// A shelf tile's asset
pub(crate) enum ShelfEntry {
Material(&'static SmartMaterial),
SmartMask(&'static SmartMask),
Filter(&'static FilterDef),
Brush(&'static BrushPreset),
/// A brush preset file the user saved
SavedBrush(PathBuf),
Alpha(&'static LibraryAlpha),
Procedural(ProceduralKind),
/// A built-in lighting environment, by name
Environment(&'static str),
/// An image resource of the project, by name
Image(String),
}
impl ShelfEntry {
/// Every built-in asset, the user's saved brushes and the project's images
pub(crate) fn all(app: &TextureCraftApp) -> Vec<ShelfEntry> {
let built_in = MATERIALS
.iter()
.map(ShelfEntry::Material)
.chain(SMART_MASKS.iter().map(ShelfEntry::SmartMask))
.chain(FILTERS.iter().map(ShelfEntry::Filter))
.chain(PRESETS.iter().map(ShelfEntry::Brush))
.chain(alphas::library().iter().map(ShelfEntry::Alpha))
.chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural))
.chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment));
let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush);
let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image);
built_in.chain(saved).chain(images).collect()
}
/// The tab that lists the asset
pub(crate) fn tab(&self) -> Tab {
match self {
ShelfEntry::Material(material) if material.smart => Tab::Smart,
ShelfEntry::Material(_) => Tab::Materials,
ShelfEntry::SmartMask(_) => Tab::Masks,
ShelfEntry::Filter(_) => Tab::Filters,
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes,
ShelfEntry::Alpha(_) => Tab::Alphas,
ShelfEntry::Procedural(_) => Tab::Textures,
ShelfEntry::Environment(_) => Tab::Environments,
ShelfEntry::Image(_) => Tab::Textures,
}
}
/// The asset's identity across frames: its kind and id
pub(crate) fn identity(&self) -> (&'static str, &str) {
match self {
ShelfEntry::Material(material) => ("material", material.id),
ShelfEntry::SmartMask(mask) => ("mask", mask.id),
ShelfEntry::Filter(filter) => ("filter", filter.id),
ShelfEntry::Brush(preset) => ("brush", preset.id),
ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()),
ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id),
ShelfEntry::Procedural(kind) => ("procedural", kind.label()),
ShelfEntry::Environment(name) => ("environment", name),
ShelfEntry::Image(name) => ("image", name),
}
}
/// Where the asset lives: its library id ([`LIBRARIES`]), its type's folder, then its category if it has one (names in English, shown through `tr`)
pub(crate) fn path(&self) -> Vec<&str> {
let (library, folder, category) = match self {
ShelfEntry::Material(material) if material.smart => (STARTER, "Smart materials", Some(material.category)),
ShelfEntry::Material(material) => (STARTER, "Materials", Some(material.category)),
ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None),
ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)),
ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)),
ShelfEntry::SavedBrush(_) => (USER, "Brushes", None),
ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)),
ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None),
ShelfEntry::Environment(_) => (STARTER, "Environments", None),
ShelfEntry::Image(_) => (PROJECT, "Textures", None),
};
[library, folder].into_iter().chain(category).collect()
}
/// Whether the asset is in folder `path` (a library id, then folder names) or below it
pub(crate) fn in_folder(&self, path: &[String]) -> bool {
let own = self.path();
path.len() <= own.len() && path.iter().zip(own).all(|(wanted, have)| wanted == have)
}
/// The name under the tile, translated where the asset's name is
pub(crate) fn label(&self) -> &str {
match self {
ShelfEntry::Material(material) => material.label,
ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME),
ShelfEntry::SmartMask(mask) => mask.label,
ShelfEntry::Filter(filter) => tr(filter.label),
ShelfEntry::Brush(preset) => preset.label,
ShelfEntry::Alpha(alpha) => &alpha.label,
ShelfEntry::Procedural(kind) => tr(kind.label()),
ShelfEntry::Environment(name) => name,
ShelfEntry::Image(name) => name,
}
}
/// Whether `filter` (lowercase) matches the asset's name, id or category, in English or translated
pub(crate) fn matches(&self, filter: &str) -> bool {
let texts: &[&str] = match self {
ShelfEntry::Material(material) => &[material.label, material.category, material.id],
ShelfEntry::SavedBrush(_) => &[self.label()],
ShelfEntry::SmartMask(mask) => &[mask.label, mask.id],
ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)],
ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id],
ShelfEntry::Alpha(alpha) => &[&alpha.label, alpha.category, &alpha.id],
ShelfEntry::Procedural(kind) => &[kind.label(), tr(kind.label())],
ShelfEntry::Environment(name) => &[name],
ShelfEntry::Image(name) => &[name],
};
crate::shelf::matches(filter, texts)
}
/// The thumbnail, or None while it renders
pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option<egui::TextureHandle> {
match self {
ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id),
ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id),
ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id),
ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset),
ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images),
ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha),
ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind),
ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name),
ShelfEntry::Image(name) => {
let image = app.session.images.get(name).cloned()?;
Some(app.thumbs.image(ctx, name, &image))
}
}
}
/// What the hover popup renders; None for an image that is gone
pub(crate) fn preview(&self, session: &Session) -> Option<ShelfPreview> {
Some(match self {
ShelfEntry::Material(material) => ShelfPreview::material(material.id),
ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id),
ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id),
ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset),
ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images),
ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha),
ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind),
ShelfEntry::Environment(name) => ShelfPreview::Environment(name),
ShelfEntry::Image(name) => ShelfPreview::Image(name.clone(), session.images.get(name).cloned()?),
})
}
/// The drag payload's asset; brushes and procedurals don't drag
pub(crate) fn asset(&self) -> Option<Asset> {
match self {
ShelfEntry::Material(material) => Some(Asset::Material(material.id)),
ShelfEntry::SmartMask(mask) => Some(Asset::SmartMask(mask.id)),
ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)),
ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)),
ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())),
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None,
}
}
/// Whether the tile is outlined as in use: the brush's library alpha, the shown environment
pub(crate) fn in_use(&self, app: &TextureCraftApp) -> bool {
match self {
ShelfEntry::Alpha(alpha) => {
let brush = &app.session.tool.brush;
brush.alpha_image.is_none() && brush.alpha_library.as_deref() == Some(alpha.id.as_str())
}
ShelfEntry::Environment(name) => app.session.doc.project.display.environment == *name,
_ => false,
}
}
/// Whether applying the asset gives a different result per random seed (the tile's dots badge)
pub(crate) fn includes_randomness(&self) -> bool {
match self {
ShelfEntry::Procedural(kind) => SEEDED_PROCEDURALS.contains(kind),
_ => false,
}
}
/// What a click on the tile does
pub(crate) fn activate(&self, app: &mut TextureCraftApp) {
match self {
ShelfEntry::Brush(preset) => {
app.run("brush.preset.apply", json!({"preset": preset.id}));
}
ShelfEntry::SavedBrush(path) => {
app.run("brush.preset.load", json!({"path": path.display().to_string()}));
}
ShelfEntry::Procedural(kind) => {
app.run("layer.add.fill", json!({"name": kind.label()}));
app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": kind.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]}));
}
ShelfEntry::Environment(name) => {
app.run("display.set", json!({"environment": name}));
}
entry => {
if let Some(asset) = entry.asset() {
apply(app, &asset);
}
}
}
}
}
/// The procedurals whose pattern depends on the seed, worked out once
static SEEDED_PROCEDURALS: std::sync::LazyLock<Vec<ProceduralKind>> =
std::sync::LazyLock::new(|| ProceduralKind::ALL.into_iter().filter(|kind| seed_changes(*kind)).collect());
/// Whether procedural `kind` samples differently under two seeds
fn seed_changes(kind: ProceduralKind) -> bool {
use texturecraft_engine::compose::pattern::{Coords, procedural};
use texturecraft_engine::core::{Procedural, Projection};
use texturecraft_engine::geom::glam::{Vec2, Vec3};
let sample = |seed: u32, i: usize| {
let uv = Vec2::new((i % SEED_PROBES) as f32 / SEED_PROBES as f32, (i / SEED_PROBES) as f32 / SEED_PROBES as f32) + SEED_PROBE_OFFSET;
procedural(&Procedural { seed, ..Procedural::new(kind) }, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y })
};
(0..SEED_PROBES * SEED_PROBES).any(|i| (sample(1, i) - sample(2, i)).abs() > SEED_TOLERANCE)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_seeded_procedurals_include_randomness() {
let seeded = &*SEEDED_PROCEDURALS;
assert!(seeded.contains(&ProceduralKind::Clouds), "{seeded:?}");
assert!(!seeded.contains(&ProceduralKind::Checker), "{seeded:?}");
}
}
+95
View File
@@ -0,0 +1,95 @@
//! The shelf's library folders ([`ShelfEntry::path`]) for the breadcrumb above the search and the Filter by path tree
use std::collections::BTreeSet;
use egui::{RichText, Ui};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf_entry::{LIBRARIES, ShelfEntry};
use crate::theme::Tokens;
use crate::widgets::icon_button;
/// The breadcrumb arrows' size relative to an icon button
const ARROW_SCALE: f32 = 0.8;
/// The folder paths of `entries`, each a library id then folder names
pub(crate) fn paths<'a>(entries: impl IntoIterator<Item = &'a ShelfEntry>) -> Vec<Vec<String>> {
let unique_paths: BTreeSet<Vec<&str>> = entries.into_iter().map(ShelfEntry::path).collect();
unique_paths.into_iter().map(|segments| segments.into_iter().map(str::to_string).collect()).collect()
}
/// `paths` and every library, even one with nothing in it (the picker always lists them all)
pub(crate) fn with_every_library(mut paths: Vec<Vec<String>>) -> Vec<Vec<String>> {
paths.extend(LIBRARIES.iter().map(|(id, _)| vec![id.to_string()]));
paths.sort();
paths.dedup();
paths
}
/// The folders right below `prefix` (libraries in their usual order, folders by name)
pub(crate) fn children(paths: &[Vec<String>], prefix: &[String]) -> Vec<String> {
let mut children = Vec::new();
for path in paths.iter().filter(|path| path.len() > prefix.len() && path.starts_with(prefix)) {
if let Some(child) = path.get(prefix.len())
&& !children.contains(child)
{
children.push(child.clone());
}
}
if prefix.is_empty() {
children.sort_by_key(|library| LIBRARIES.iter().position(|(id, _)| id == library));
}
children
}
/// A folder's shown name: libraries by their name, folders (type and category names) translated
pub(crate) fn name(level: usize, segment: &str) -> &str {
match LIBRARIES.iter().find(|(id, _)| *id == segment) {
Some((_, library)) if level == 0 => tr(library),
_ => tr(segment),
}
}
/// "› All libraries › …": each arrow lists the folders at its level, the names are plain text, a last arrow lists the folders inside
pub(crate) fn breadcrumb(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>]) {
let tokens = Tokens::get(ui.ctx());
let size = ui.spacing().interact_size.y * ARROW_SCALE;
let mut picked: Option<Vec<String>> = None;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = ui.spacing().item_spacing.x * 0.5;
let path = app.ui.shelf_path.clone();
for level in 0..=path.len() {
let options = children(paths, &path[..level]);
if level > 0 && options.is_empty() {
break;
}
let current = path.get(level);
let response = icon_button(ui, egui_phosphor::regular::CARET_RIGHT, tr("Browse folders"), false, size);
egui::Popup::menu(&response).show(|ui| {
if level == 0 && ui.selectable_label(current.is_none(), tr("All libraries")).clicked() {
picked = Some(Vec::new());
}
for option in &options {
if ui.selectable_label(current == Some(option), name(level, option)).clicked() {
picked = Some(path[..level].iter().cloned().chain([option.clone()]).collect());
}
}
});
let shown = match current {
Some(segment) => name(level, segment),
None if level == 0 => tr("All libraries"),
None => continue,
};
ui.label(RichText::new(shown).strong().color(tokens.text_strong));
}
});
if let Some(path) = picked {
app.ui.shelf_path = path;
}
}
+175
View File
@@ -0,0 +1,175 @@
//! The shelf's side panes left of the grid, toggled from the toolbar: saved searches and the folder tree
use egui::{RichText, Ui};
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::saved_search::SavedSearch;
use crate::shelf::TABS;
use crate::theme::Tokens;
use crate::widgets::icon_button;
/// The panes' column width as a fraction of the panel, and its least width in points
const COLUMN_FRACTION: f32 = 0.45;
const COLUMN_MIN_WIDTH: f32 = 110.0;
/// Maximum share of the column used by saved searches while both panes are open
const SAVED_SEARCHES_HEIGHT_FRACTION: f32 = 0.45;
/// The pane header's caption size in points
const HEADER_SIZE: f32 = 10.0;
/// Which side panes are open
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShelfPanes {
pub saved_searches: bool,
pub filter_by_path: bool,
/// Filter by path lists only the folders with assets matching the search and tab
pub hide_non_applicable: bool,
}
/// The toolbar's buttons that open and close the panes
pub(crate) fn toggles(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let panes = &mut app.ui.shelf_panes;
if icon_button(ui, ic::BOOKMARKS_SIMPLE, tr("Saved searches"), panes.saved_searches, size).clicked() {
panes.saved_searches = !panes.saved_searches;
}
if icon_button(ui, ic::TREE_STRUCTURE, tr("Filter by path"), panes.filter_by_path, size).clicked() {
panes.filter_by_path = !panes.filter_by_path;
}
}
/// The width of the panes' column in a panel `width` wide, or None while no pane is open
pub(crate) fn column_width(app: &TextureCraftApp, width: f32) -> Option<f32> {
let panes = &app.ui.shelf_panes;
(panes.saved_searches || panes.filter_by_path).then(|| (width * COLUMN_FRACTION).max(COLUMN_MIN_WIDTH).min(width))
}
/// The open panes, top to bottom; the tree shows `paths`, or `applicable` while it hides folders with nothing matching
pub(crate) fn column(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>], applicable: &[Vec<String>]) {
// Names past the narrow column end in "…" rather than breaking mid-word
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
if app.ui.shelf_panes.saved_searches {
saved_searches(app, ui);
}
if app.ui.shelf_panes.filter_by_path {
if app.ui.shelf_panes.saved_searches {
ui.separator();
}
let shown = if app.ui.shelf_panes.hide_non_applicable { applicable } else { paths };
filter_by_path(app, ui, shown);
}
}
/// "All libraries", then each library's folders as a tree; a click shows that folder
fn filter_by_path(app: &mut TextureCraftApp, ui: &mut Ui, paths: &[Vec<String>]) {
let size = ui.spacing().interact_size.y;
header(ui, tr("Filter by path"), |ui| {
let hiding = app.ui.shelf_panes.hide_non_applicable;
if icon_button(ui, ic::EYE_SLASH, tr("Hide non-applicable folders"), hiding, size).clicked() {
app.ui.shelf_panes.hide_non_applicable = !hiding;
}
});
let mut picked = None;
egui::ScrollArea::vertical().id_salt("shelf_path_tree").auto_shrink([false, true]).show(ui, |ui| {
if ui.selectable_label(app.ui.shelf_path.is_empty(), tr("All libraries")).clicked() {
picked = Some(Vec::new());
}
folders(ui, paths, &[], &app.ui.shelf_path, &mut picked);
});
if let Some(path) = picked {
app.ui.shelf_path = path;
}
}
/// The folders below `prefix`: one with folders inside opens and closes, a click on a name picks it
fn folders(ui: &mut Ui, paths: &[Vec<String>], prefix: &[String], current: &[String], picked: &mut Option<Vec<String>>) {
for child in crate::shelf_folders::children(paths, prefix) {
let path: Vec<String> = prefix.iter().cloned().chain([child.clone()]).collect();
let name = crate::shelf_folders::name(prefix.len(), &child);
let selected = current == path.as_slice();
if crate::shelf_folders::children(paths, &path).is_empty() {
ui.indent(("shelf_path_leaf", &path), |ui| {
if ui.selectable_label(selected, name).clicked() {
*picked = Some(path.clone());
}
});
continue;
}
let id = ui.make_persistent_id(("shelf_path", &path));
let open_by_default = current.starts_with(&path);
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, open_by_default)
.show_header(ui, |ui| {
if ui.selectable_label(selected, name).clicked() {
*picked = Some(path.clone());
}
})
.body(|ui| folders(ui, paths, &path, current, picked));
}
}
/// A pane's caption with a button at its right
fn header(ui: &mut Ui, title: &str, button: impl FnOnce(&mut Ui)) {
let tokens = Tokens::get(ui.ctx());
ui.horizontal(|ui| {
ui.label(RichText::new(title.to_uppercase()).size(HEADER_SIZE).color(tokens.text_dim));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), button);
});
}
/// "All", then the saved queries; the header's button saves the current one, a right-click deletes one
fn saved_searches(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
let current = current_query(app);
header(ui, tr("Saved searches"), |ui| {
if icon_button(ui, ic::FLOPPY_DISK, tr("Save the current search"), false, size).clicked() && !app.ui.shelf_saved_searches.contains(&current) {
app.ui.shelf_saved_searches.push(current.clone());
}
});
let everything = current.filter.is_empty() && current.path.is_empty() && current.tab == crate::shelf_tabs::NO_TYPE;
if ui.selectable_label(everything, tr("All")).clicked() {
crate::shelf_toolbar::reset_query(app);
}
let mut deleted = None;
let max_height = if app.ui.shelf_panes.filter_by_path { ui.available_height() * SAVED_SEARCHES_HEIGHT_FRACTION } else { ui.available_height() };
let row_height = ui.spacing().interact_size.y;
let total_rows = app.ui.shelf_saved_searches.len();
egui::ScrollArea::vertical().id_salt("shelf_saved_searches").max_height(max_height).show_rows(ui, row_height, total_rows, |ui, visible_rows| {
for i in visible_rows {
let Some(saved) = app.ui.shelf_saved_searches.get(i) else { continue };
let same = saved.filter == current.filter && saved.tab == current.tab && saved.path == current.path;
let response = ui.selectable_label(same, &saved.name);
if response.clicked() {
(app.ui.shelf_filter, app.ui.shelf_tab, app.ui.shelf_path) = (saved.filter.clone(), saved.tab, saved.path.clone());
}
response.context_menu(|ui| {
if ui.button(tr("Delete")).clicked() {
deleted = Some(i);
ui.close();
}
});
}
});
if let Some(i) = deleted {
app.ui.shelf_saved_searches.remove(i);
}
}
/// The shelf's query, named after its search text, else its folder, else its tab
fn current_query(app: &TextureCraftApp) -> SavedSearch {
let (filter, tab, path) = (app.ui.shelf_filter.clone(), app.ui.shelf_tab, app.ui.shelf_path.clone());
let name = if !filter.is_empty() {
filter.clone()
} else if let Some(folder) = path.last() {
crate::shelf_folders::name(path.len() - 1, folder).to_string()
} else {
TABS.get(tab).map_or(tr("All"), |(_, _, label)| tr(label)).to_string()
};
SavedSearch { name, filter, tab, path }
}
+61 -2
View File
@@ -1,9 +1,11 @@
//! Shelf assets and their preview renderers
use std::path::PathBuf;
use std::sync::Arc;
use egui::ColorImage;
use texturecraft_engine::compose::ImageRes;
use texturecraft_engine::compose::ImageStore;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::materials;
use texturecraft_engine::paint::BrushSettings;
@@ -11,9 +13,14 @@ use texturecraft_engine::paint::alphas::LibraryAlpha;
use texturecraft_engine::paint::presets::BrushPreset;
use texturecraft_engine::preview;
use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview};
use crate::preview_image::{alpha_image, environment_image, image_preview, procedural_image, sphere_image, stroke_preview};
/// Larger brush preset files aren't read (the `brush.preset.load` command's limit)
#[cfg(not(target_arch = "wasm32"))]
const MAX_SAVED_BRUSH_BYTES: u64 = 1 << 20;
/// The asset a shelf tile previews
#[derive(Clone)]
pub enum ShelfPreview {
/// A built-in plain material on a sphere
Material(&'static str),
@@ -29,11 +36,22 @@ pub enum ShelfPreview {
Alpha(&'static LibraryAlpha),
/// A brush preset's stroke along an S curve
Brush(&'static BrushPreset),
/// A brush preset file the user saved, its stroke along an S curve
SavedBrush { path: PathBuf, settings: Option<BrushSettings>, image: Option<Arc<ImageRes>> },
/// An image resource by name
Image(String, Arc<ImageRes>),
/// A built-in lighting environment's panorama
Environment(&'static str),
}
impl ShelfPreview {
/// Resolve a saved brush's image alpha while the project images are available
pub fn saved_brush(path: &std::path::Path, images: &ImageStore) -> Self {
let settings = read_saved_brush(path);
let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name)).cloned();
ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image }
}
/// Smart materials preview on the orb, plain materials on a sphere
pub fn material(id: &'static str) -> ShelfPreview {
match materials::find(id) {
@@ -52,7 +70,9 @@ impl ShelfPreview {
ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"),
ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id),
ShelfPreview::Brush(preset) => format!("brush:{}", preset.id),
ShelfPreview::SavedBrush { path, .. } => format!("saved-brush:{}", path.display()),
ShelfPreview::Image(name, _) => format!("image:{name}"),
ShelfPreview::Environment(name) => format!("environment:{name}"),
}
}
@@ -65,12 +85,39 @@ impl ShelfPreview {
ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)),
ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)),
ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)),
ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)),
ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)),
ShelfPreview::SavedBrush { settings, image, .. } => {
let settings = settings.as_ref()?;
if settings.alpha_image.is_some() && image.is_none() {
return None;
}
Some(stroke_preview(settings, size, image.as_deref()))
}
ShelfPreview::Image(_, image) => Some(image_preview(image, size)),
ShelfPreview::Environment(name) => Some(environment_image(name, size)),
}
}
}
/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files)
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option<BrushSettings> {
use std::io::Read as _;
let mut bytes = Vec::new();
std::fs::File::open(path).and_then(|file| file.take(MAX_SAVED_BRUSH_BYTES + 1).read_to_end(&mut bytes)).ok()?;
if bytes.len() as u64 > MAX_SAVED_BRUSH_BYTES {
return None;
}
serde_json::from_slice::<BrushSettings>(&bytes).ok().map(|settings| settings.sanitized())
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn read_saved_brush(_: &std::path::Path) -> Option<BrushSettings> {
None
}
#[cfg(test)]
mod tests {
use texturecraft_engine::filter_lib::FILTERS;
@@ -93,6 +140,7 @@ mod tests {
ShelfPreview::Alpha(&alphas::library()[0]),
ShelfPreview::Brush(&PRESETS[0]),
ShelfPreview::Image("image".into(), Arc::new(image)),
ShelfPreview::Environment(texturecraft_engine::core::project::ENVIRONMENTS[0]),
];
for preview in previews {
let key = preview.key();
@@ -117,4 +165,15 @@ mod tests {
assert_eq!(on_the_orb, material.smart, "{}", material.id);
}
}
#[test]
fn saved_brush_preview_uses_its_project_image_alpha() {
let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() };
let transparent = Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[1.0, 1.0, 1.0, 0.0]; 4], srgb: false });
let preview = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings.clone()), image: Some(transparent) };
assert!(preview.image(64).is_some_and(|image| image.pixels.iter().all(|pixel| pixel.r() == 0)));
let missing = ShelfPreview::SavedBrush { path: PathBuf::from("brush.tcbrush"), settings: Some(settings), image: None };
assert!(missing.image(64).is_none());
}
}
+72
View File
@@ -0,0 +1,72 @@
//! The shelf's type row: one icon per type (none picked shows every type), greyed without matches, one dropdown when narrow
use egui::{Ui, vec2};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::shelf::{TABS, Tab};
use crate::widgets::{icon_button, icon_dropdown_button};
/// The gap between the row's icons in points
const ICON_GAP: f32 = 2.0;
/// The size of the dot that marks the collapsed row's dropdown while a type is picked, in points
const FILTER_DOT_RADIUS: f32 = 2.5;
/// `app.ui.shelf_tab` while no type is picked: every type shows
pub(crate) const NO_TYPE: usize = TABS.len();
/// The row, then `trailing` at its right end; `counts[i]` is how many assets of `TABS[i]` match the search
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui, counts: &[usize], trailing: impl FnOnce(&mut TextureCraftApp, &mut Ui, f32)) {
let size = ui.spacing().interact_size.y;
// The type icons and one icon after them
let row_width = (TABS.len() + 1) as f32 * (size + ICON_GAP);
let mut picked = app.ui.shelf_tab.min(NO_TYPE);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing = vec2(ICON_GAP, ICON_GAP);
if ui.available_width() >= row_width {
for (i, (_, icon, label)) in TABS.iter().enumerate() {
// The picked type stays clickable so it can be unpicked
let empty = i != picked && counts.get(i).is_none_or(|count| *count == 0);
if ui.add_enabled_ui(!empty, |ui| icon_button(ui, icon, tr(label), i == picked, size)).inner.clicked() {
picked = if i == picked { NO_TYPE } else { i };
}
}
} else {
collapsed(ui, &mut picked, counts, size);
}
let rest = ui.available_width() - size;
ui.add_space(rest.max(0.0));
trailing(app, ui, size);
});
app.ui.shelf_tab = picked;
}
/// One dropdown listing the types, dotted while one is picked
fn collapsed(ui: &mut Ui, picked: &mut usize, counts: &[usize], size: f32) {
let filtering = *picked != NO_TYPE;
let response = icon_dropdown_button(ui, egui_phosphor::regular::FUNNEL_SIMPLE, tr("Filter by type"), filtering, size);
let response = response.on_hover_text(tr("Filter by type"));
if filtering {
let tokens = crate::theme::Tokens::get(ui.ctx());
let dot = response.rect.left_top() + vec2(size - FILTER_DOT_RADIUS, FILTER_DOT_RADIUS);
ui.painter().circle_filled(dot, FILTER_DOT_RADIUS, tokens.accent);
}
egui::Popup::menu(&response).show(|ui| {
for (i, (_, icon, label)) in TABS.iter().enumerate() {
let empty = i != *picked && counts.get(i).is_none_or(|count| *count == 0);
if ui.add_enabled(!empty, egui::Button::selectable(i == *picked, format!("{icon} {}", tr(label)))).clicked() {
*picked = if i == *picked { NO_TYPE } else { i };
ui.close();
}
}
});
}
/// Whether `tab` (an index into [`TABS`], or [`NO_TYPE`]) shows assets of type `kind`
pub(crate) fn shows(tab: usize, kind: Tab) -> bool {
TABS.get(tab).is_none_or(|(shown, _, _)| *shown == kind)
}
+50
View File
@@ -0,0 +1,50 @@
//! The shelf's bottom toolbar: the side pane toggles on the left; refresh, reset query and import on the right
use egui::Ui;
use egui_phosphor::regular as ic;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::widgets::icon_button;
/// The gap above the toolbar in points
const GAP_ABOVE: f32 = 4.0;
/// The toolbar's height for a `ui` (one icon button and the gap above it)
pub(crate) fn height(ui: &Ui) -> f32 {
ui.spacing().interact_size.y + GAP_ABOVE
}
/// The toolbar
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) {
let size = ui.spacing().interact_size.y;
ui.add_space(GAP_ABOVE);
ui.horizontal(|ui| {
crate::shelf_panes::toggles(app, ui, size);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if icon_button(ui, ic::PLUS, tr("Import resources..."), false, size).clicked() {
crate::menus::invoke(app, &ui.ctx().clone(), "resource.import");
}
if icon_button(ui, ic::X_CIRCLE, tr("Reset query"), false, size).clicked() {
reset_query(app);
}
if icon_button(ui, ic::ARROWS_CLOCKWISE, tr("Refresh"), false, size).clicked() {
refresh(app);
}
});
});
}
/// Show every asset again: no search, no type picked, all libraries
pub(crate) fn reset_query(app: &mut TextureCraftApp) {
app.ui.shelf_filter.clear();
app.ui.shelf_tab = crate::shelf_tabs::NO_TYPE;
app.ui.shelf_path.clear();
}
/// Read the user's saved assets from disk again and redraw their thumbnails
fn refresh(app: &mut TextureCraftApp) {
app.library = None;
app.brushes = None;
app.thumbs.forget_saved_files();
}
+83
View File
@@ -0,0 +1,83 @@
//! How the shelf shows its assets: small, medium or large tiles, or a list (the menu at the type row's end)
use egui::{Rect, Ui, Vec2, vec2};
use egui_phosphor::regular as ic;
use serde::{Deserialize, Serialize};
use crate::TextureCraftApp;
use crate::grid_tile::GridTile;
use crate::i18n::tr;
use crate::widgets::icon_button;
/// A list row's height and its thumbnail's size, in points
const LIST_ROW_HEIGHT: f32 = 30.0;
const LIST_THUMBNAIL_SIZE: f32 = 26.0;
/// The gap between a list row's thumbnail and its name, in points
pub(crate) const LIST_NAME_GAP: f32 = 6.0;
/// The shelf's tile size, or the list
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ShelfView {
Small,
/// A 68 x 78 grid step, as in the reference
#[default]
Medium,
Large,
List,
}
/// The views in the menu's order: icon and (English, translated where shown) name
const VIEWS: [(ShelfView, &str, &str); 4] = [
(ShelfView::Small, ic::GRID_NINE, "Small"),
(ShelfView::Medium, ic::GRID_FOUR, "Medium"),
(ShelfView::Large, ic::SQUARE, "Large"),
(ShelfView::List, ic::LIST, "List"),
];
impl ShelfView {
/// A grid tile's measurements; None for the list
fn grid(self) -> Option<GridTile> {
match self {
ShelfView::Small => Some(GridTile { width: 50.0, height: 58.0, thumbnail_size: 44.0, thumbnail_center_y: 23.0 }),
ShelfView::Medium => Some(GridTile { width: 66.0, height: 76.0, thumbnail_size: 60.0, thumbnail_center_y: 31.0 }),
ShelfView::Large => Some(GridTile { width: 88.0, height: 100.0, thumbnail_size: 82.0, thumbnail_center_y: 42.0 }),
ShelfView::List => None,
}
}
/// A tile's size in a grid `width` points wide (a list row spans it)
pub(crate) fn tile_size(self, width: f32) -> Vec2 {
match self.grid() {
Some(tile) => vec2(tile.width, tile.height),
None => vec2(width.max(LIST_ROW_HEIGHT), LIST_ROW_HEIGHT),
}
}
/// Where the thumbnail goes in the tile `rect`
pub(crate) fn thumbnail_rect(self, rect: Rect) -> Rect {
match self.grid() {
Some(tile) => Rect::from_center_size(rect.center_top() + vec2(0.0, tile.thumbnail_center_y), vec2(tile.thumbnail_size, tile.thumbnail_size)),
None => Rect::from_center_size(rect.left_center() + vec2(LIST_ROW_HEIGHT * 0.5, 0.0), vec2(LIST_THUMBNAIL_SIZE, LIST_THUMBNAIL_SIZE)),
}
}
/// Whether the name sits right of the thumbnail (a list) rather than under it
pub(crate) fn name_beside(self) -> bool {
self == ShelfView::List
}
}
/// The view menu button: its icon is the current view's
pub(crate) fn menu(app: &mut TextureCraftApp, ui: &mut Ui, size: f32) {
let current = app.ui.shelf_view;
let icon = VIEWS.iter().find(|(view, _, _)| *view == current).map_or(ic::GRID_FOUR, |(_, icon, _)| icon);
let response = icon_button(ui, icon, tr("Thumbnail size"), false, size);
egui::Popup::menu(&response).show(|ui| {
for (view, icon, label) in VIEWS {
if ui.selectable_label(view == current, format!("{icon} {}", tr(label))).clicked() {
app.ui.shelf_view = view;
ui.close();
}
}
});
}
+41 -4
View File
@@ -5,6 +5,9 @@ use texturecraft_engine::core::{BakedMap, Channel, NormalFormat};
use crate::docking::Dock;
use crate::keymap::Keymap;
use crate::saved_search::SavedSearch;
use crate::shelf_panes::ShelfPanes;
use crate::shelf_view::ShelfView;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Mode {
@@ -297,9 +300,21 @@ pub struct UiState {
/// Channel whose blending the layer rows show.
pub layer_channel: Channel,
pub shelf_filter: String,
/// The asset shelf's open tab.
/// The asset shelf's picked type: an index into the shelf's types, or past them for every type
#[serde(default)]
pub shelf_tab: usize,
/// The asset shelf's library folder: a library id, then folder names (empty: all libraries)
#[serde(default)]
pub shelf_path: Vec<String>,
/// The asset shelf's tile size, or its list
#[serde(default)]
pub shelf_view: ShelfView,
/// The asset shelf's open side panes
#[serde(default)]
pub shelf_panes: ShelfPanes,
/// The asset shelf's saved queries, in the order they were saved
#[serde(default)]
pub shelf_saved_searches: Vec<SavedSearch>,
pub props_tab: PropsTab,
#[serde(default)]
pub text: TextUi,
@@ -357,17 +372,21 @@ impl UiState {
self.bake_layout_version = BAKE_LAYOUT_VERSION;
}
/// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export
/// settings and recent files.
/// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query
pub fn adopt_layout(&mut self, layout: UiState) {
let keep = std::mem::replace(self, layout);
self.new_project = keep.new_project;
self.export = keep.export;
self.recent = keep.recent;
self.shelf_filter = keep.shelf_filter;
self.prefs = keep.prefs;
self.keymap = keep.keymap;
self.rename = None;
// The shelf's search, type and folder are one query, and saved searches are the user's own
self.shelf_filter = keep.shelf_filter;
self.shelf_tab = keep.shelf_tab;
self.shelf_path = keep.shelf_path;
self.shelf_saved_searches = keep.shelf_saved_searches;
}
}
@@ -390,6 +409,10 @@ impl Default for UiState {
layer_channel: Channel::BaseColor,
shelf_filter: String::new(),
shelf_tab: 0,
shelf_path: Vec::new(),
shelf_view: ShelfView::default(),
shelf_panes: ShelfPanes::default(),
shelf_saved_searches: Vec::new(),
props_tab: PropsTab::Brush,
text: TextUi::default(),
rename: None,
@@ -419,13 +442,27 @@ mod tests {
ui.keymap.insert("file.save".into(), "F5".into());
let mut layout = UiState::default();
layout.dock.close(crate::docking::Panel::Assets);
ui.adopt_layout(layout);
assert!(!ui.dock.is_open(crate::docking::Panel::Assets));
assert_eq!(ui.recent, vec!["a.tcraft".to_string()]);
assert_eq!(ui.export.preset, "Mine");
assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5"));
}
#[test]
fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() {
let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] };
let mut ui = UiState { shelf_filter: "rust".into(), shelf_tab: 2, shelf_path: vec!["starter".into()], ..UiState::default() };
ui.shelf_saved_searches.push(saved.clone());
ui.adopt_layout(UiState::default());
assert_eq!((ui.shelf_filter.as_str(), ui.shelf_tab, ui.shelf_path.as_slice()), ("rust", 2, ["starter".to_string()].as_slice()));
assert_eq!(ui.shelf_saved_searches, [saved]);
}
#[test]
fn the_data_folder_is_an_absolute_choice_or_documents_texturecraft() {
let default = crate::data_folder("");
+3 -2
View File
@@ -29,9 +29,10 @@ pub(crate) fn applies_to(tool: Tool) -> bool {
matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path)
}
/// Whether the 3D view shows symmetry now
/// Whether the 3D view shows symmetry now: not while the active tool can't act on the selection
pub(crate) fn shown(app: &TextureCraftApp) -> bool {
app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any()
let tool = app.session.tool.tool;
app.ui.mode == crate::state::Mode::Painting && applies_to(tool) && app.session.tool_usable(tool) && app.session.tool.brush.symmetry.any()
}
/// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled
+312 -29
View File
@@ -3,11 +3,14 @@
//! Smart masks, smart materials and hover previews use [`PreviewWorker`]
use std::collections::{HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Weak};
use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions};
use texturecraft_engine::compose::{ImageRes, ImageStore};
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::paint::presets::BrushPreset;
use texturecraft_engine::paint::{BrushAlpha, alphas};
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::texel::linear_to_srgb;
use crate::preview_image::{aces, image_preview, shade};
@@ -21,20 +24,32 @@ const PER_FRAME: usize = 2;
/// Shelf sphere and smart mask thumbnail size in pixels
const SPHERE_PX: usize = 72;
/// Shelf procedural swatch size in pixels
const PROCEDURAL_PX: usize = 56;
const PROCEDURAL_PX: usize = 64;
/// Shelf alpha and brush stroke swatch size in pixels
const SWATCH_PX: usize = 64;
/// Image resource preview size in pixels
const IMAGE_PX: usize = 64;
/// The [`ShelfPreview::key`] prefix of the user's saved files
const SAVED_FILE_KEY_PREFIX: &str = "saved-";
/// Largest stencil preview dimension in pixels
const STENCIL_MAX_SIZE_PX: f32 = 1024.0;
/// Big hover previews kept at most (the least recently shown go first)
const BIG_PREVIEWS_KEPT: usize = 32;
/// Parsed settings, weak image identity and preview revision for a saved brush
type SavedBrushCacheEntry = (Option<BrushSettings>, Option<Weak<ImageRes>>, u64);
/// The shelf's and the brush panel's preview textures
#[derive(Default)]
pub struct Thumbs {
/// Shelf thumbnails by [`ShelfPreview::key`]
shelf: HashMap<String, TextureHandle>,
images: HashMap<String, TextureHandle>,
/// Parsed settings, weak image identity and preview revision for each saved brush
saved_brush_previews: HashMap<PathBuf, SavedBrushCacheEntry>,
/// Refresh generation; queued results from earlier generations must not match new requests
saved_files_epoch: u64,
images: HashMap<String, (Weak<ImageRes>, TextureHandle)>,
images_revision: Option<u64>,
/// (frame, thumbnails rendered in it)
budget: (u64, usize),
/// Renders the orb thumbnails and the big previews
@@ -49,34 +64,57 @@ pub struct Thumbs {
impl Thumbs {
/// A larger cached texture of an image resource for the stencil overlay (up to 1024 px)
pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle {
pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc<ImageRes>) -> TextureHandle {
let key = format!("stencil:{name}");
if let Some(t) = self.images.get(&key) {
return t.clone();
if let Some((cached_image, texture)) = self.images.get(&key)
&& cached_image.ptr_eq(&Arc::downgrade(image))
{
return texture.clone();
}
let scale = (1024.0 / img.width.max(img.height).max(1) as f32).min(1.0);
let (w, h) = (((img.width as f32 * scale) as usize).max(1), ((img.height as f32 * scale) as usize).max(1));
let mut ci = ColorImage::filled([w, h], Color32::TRANSPARENT);
let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0);
let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1));
let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT);
for y in 0..h {
for x in 0..w {
let s = img.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 };
ci.pixels[y * w + x] = Color32::from_rgba_unmultiplied(enc(s[0]), enc(s[1]), enc(s[2]), (s[3].clamp(0.0, 1.0) * 255.0) as u8);
let sample = image.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
let encode = |value: f32| {
if image.srgb { (value.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(value) * 255.0) as u8 }
};
color_image.pixels[y * w + x] =
Color32::from_rgba_unmultiplied(encode(sample[0]), encode(sample[1]), encode(sample[2]), (sample[3].clamp(0.0, 1.0) * 255.0) as u8);
}
}
let t = ctx.load_texture(key.clone(), ci, TextureOptions::LINEAR);
self.images.insert(key, t.clone());
t
let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR);
self.images.insert(key, (Arc::downgrade(image), texture.clone()));
texture
}
/// Cached preview of an image resource (64 px, letterboxed)
pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle {
if let Some(t) = self.images.get(name) {
return t.clone();
pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc<ImageRes>) -> TextureHandle {
if let Some((cached_image, texture)) = self.images.get(name)
&& cached_image.ptr_eq(&Arc::downgrade(image))
{
return texture.clone();
}
let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR);
self.images.insert(name.to_string(), t.clone());
t
let texture = ctx.load_texture(format!("res_{name}"), image_preview(image, IMAGE_PX), TextureOptions::LINEAR);
self.images.insert(name.to_string(), (Arc::downgrade(image), texture.clone()));
texture
}
/// Release previews for deleted or replaced resources after a session change
pub fn sync_images(&mut self, images: &ImageStore, revision: u64) {
if self.images_revision == Some(revision) {
return;
}
self.images_revision = Some(revision);
self.images.retain(|key, (cached_image, _)| {
let name = key.strip_prefix("stencil:").unwrap_or(key);
images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image)))
});
}
/// Render within the frame budget; deferred thumbnails request a repaint
@@ -117,7 +155,7 @@ impl Thumbs {
fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option<TextureHandle> {
self.receive(ctx);
let key = worker_key(&preview, size_px);
let key = self.worker_key(&preview, size_px);
if !self.rendered.contains_key(&key) && self.may_request(ctx) {
let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover });
self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed });
@@ -166,7 +204,7 @@ impl Thumbs {
/// Request a hover preview and evict the least recently shown beyond the cache limit
pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option<TextureHandle> {
let key = worker_key(&preview, size_px);
let key = self.worker_key(&preview, size_px);
self.big_shown.retain(|k| *k != key);
self.big_shown.push_back(key);
while self.big_shown.len() > BIG_PREVIEWS_KEPT {
@@ -181,7 +219,7 @@ impl Thumbs {
/// The big preview of `preview` if the worker already rendered it (requests nothing)
pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option<TextureHandle> {
self.receive(ctx);
self.ready(&worker_key(preview, size_px))
self.ready(&self.worker_key(preview, size_px))
}
/// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres
@@ -192,6 +230,16 @@ impl Thumbs {
}
}
/// Drop the thumbnails and hover previews of the user's saved files, which may have changed on disk
pub fn forget_saved_files(&mut self) {
self.saved_files_epoch = self.saved_files_epoch.wrapping_add(1);
let current = |key: &String| !key.starts_with(SAVED_FILE_KEY_PREFIX);
self.shelf.retain(|key, _| current(key));
self.rendered.retain(|key, _| current(key));
self.big_shown.retain(current);
self.saved_brush_previews.clear();
}
/// Smart mask thumbnail; None until the worker returns it
pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option<TextureHandle> {
self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false)
@@ -212,17 +260,69 @@ impl Thumbs {
self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX)
}
/// A lighting environment's panorama
pub fn environment(&mut self, ctx: &egui::Context, name: &'static str) -> Option<TextureHandle> {
self.shelf(ctx, ShelfPreview::Environment(name), SWATCH_PX)
}
/// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable
pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option<TextureHandle> {
let key = format!("saved-brush:{}", path.display());
let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images));
if let Some(texture) = self.shelf.get(&key) {
return Some(texture.clone());
}
if !self.spend_budget(ctx, 1) {
return None;
}
let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images));
let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT));
let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR);
self.shelf.insert(key, texture.clone());
Some(texture)
}
/// Reuse parsed settings until refresh; rebuild previews when their project image changes
pub fn saved_brush_preview(&mut self, path: &Path, images: &ImageStore) -> ShelfPreview {
let cached = self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (crate::shelf_preview::read_saved_brush(path), None, 0));
let (settings, previous_image, revision) = cached;
let image = settings.as_ref().and_then(|brush| brush.alpha_image.as_ref()).and_then(|name| images.get(name));
let image_changed = match (previous_image.as_ref(), image) {
(Some(previous), Some(current)) => previous.upgrade().is_none_or(|previous| !Arc::ptr_eq(&previous, current)),
(None, None) => false,
_ => true,
};
*previous_image = image.map(Arc::downgrade);
if image_changed {
*revision = revision.wrapping_add(1);
let key = format!("saved-brush:{}", path.display());
let rendered_prefix = format!("{key}@");
self.shelf.remove(&key);
self.rendered.retain(|rendered, _| !rendered.starts_with(&rendered_prefix));
self.big_shown.retain(|rendered| !rendered.starts_with(&rendered_prefix));
}
ShelfPreview::SavedBrush { path: path.to_path_buf(), settings: settings.clone(), image: image.cloned() }
}
/// A saved-brush key also identifies the refresh and image version of its request
fn worker_key(&self, preview: &ShelfPreview, size_px: usize) -> String {
let key = format!("{}@{size_px}", preview.key());
if let ShelfPreview::SavedBrush { path, .. } = preview {
let revision = self.saved_brush_previews.get(path).map_or(0, |(_, _, revision)| *revision);
format!("{key}#{}:{revision}", self.saved_files_epoch)
} else {
key
}
}
/// A brush preset's stroke along an S curve
pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option<TextureHandle> {
self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX)
}
}
/// The key of a worker-rendered preview: one per asset and size
fn worker_key(preview: &ShelfPreview, size_px: usize) -> String {
format!("{}@{size_px}", preview.key())
}
/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews).
pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) {
let mut mesh = egui::Mesh::default();
@@ -276,3 +376,186 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::orb_shape::OrbShape;
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
#[test]
fn saved_brush_refresh_discards_old_worker_result() {
let ctx = egui::Context::default();
let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() };
let preview = ShelfPreview::SavedBrush { path: PathBuf::from("refreshed.tcbrush"), settings: None, image: None };
assert!(thumbs.big(&ctx, preview.clone(), 8).is_none());
thumbs.forget_saved_files();
assert!(thumbs.big(&ctx, preview.clone(), 8).is_none());
let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") };
let old_key = results[0].0.clone();
let current_key = results[1].0.clone();
*results = vec![(current_key, None), (old_key, Some(ColorImage::filled([8, 8], Color32::RED)))];
let mut output = ctx.run_pass(Default::default(), |_| {});
output.textures_delta.clear();
assert!(thumbs.rendered_big(&ctx, &preview, 8).is_none(), "an old completion must not replace the current failed result");
}
#[test]
fn saved_brush_image_replacement_preserves_current_worker_result() {
let ctx = egui::Context::default();
let mut thumbs = Thumbs { worker: PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }, ..Thumbs::default() };
let path = PathBuf::from("changed-alpha.tcbrush");
let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() };
thumbs.saved_brush_previews.insert(path.clone(), (Some(settings), None, 0));
let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false });
let mut images: ImageStore = [("alpha.png".into(), image(0.2))].into();
let old_preview = thumbs.saved_brush_preview(&path, &images);
assert!(thumbs.big(&ctx, old_preview, 8).is_none());
images.insert("alpha.png".into(), image(0.8));
let current_preview = thumbs.saved_brush_preview(&path, &images);
assert!(thumbs.big(&ctx, current_preview.clone(), 8).is_none());
let PreviewWorker::Inline { results, .. } = &mut thumbs.worker else { panic!("test worker must render inline") };
let old_key = results[0].0.clone();
let current_key = results[1].0.clone();
*results = vec![(current_key, Some(ColorImage::filled([8, 8], Color32::RED))), (old_key, None)];
let mut output = ctx.run_pass(Default::default(), |_| {});
output.textures_delta.clear();
assert!(thumbs.rendered_big(&ctx, &current_preview, 8).is_some(), "the current completion must survive an old failure");
}
#[test]
fn saved_brush_file_read_waits_for_the_thumbnail_budget() {
let path = std::env::temp_dir().join(format!("texturecraft-brush-budget-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap();
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME);
assert!(thumbs.saved_brush(&context, &path, &ImageStore::new()).is_none());
assert!(thumbs.saved_brush_previews.is_empty(), "a deferred thumbnail has not read its file");
std::fs::remove_file(&path).unwrap();
}
#[test]
fn saved_brush_settings_are_read_once_until_refresh() {
let path =
std::env::temp_dir().join(format!("texturecraft-brush-preview-{}-{}.tcbrush", std::process::id(), NEXT_FILE.fetch_add(1, Ordering::Relaxed)));
std::fs::write(&path, serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap();
let mut thumbs = Thumbs::default();
let images = ImageStore::new();
assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }));
std::fs::remove_file(&path).unwrap();
assert!(
matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: Some(_), .. }),
"cached settings avoid a second file read"
);
thumbs.forget_saved_files();
assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again");
}
#[test]
fn saved_brush_cache_releases_old_images_on_change_and_refresh() {
const IMAGE_SIDE: u32 = 512;
const IMAGE_TEXELS: usize = IMAGE_SIDE as usize * IMAGE_SIDE as usize;
const IMAGE_BYTES: usize = IMAGE_TEXELS * std::mem::size_of::<[f32; 4]>();
let mut thumbs = Thumbs::default();
let first_path = PathBuf::from("first.tcbrush");
let second_path = PathBuf::from("second.tcbrush");
let settings = BrushSettings { alpha_image: Some("alpha.png".into()), ..BrushSettings::default() };
let old_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[1.0; 4]; IMAGE_TEXELS], srgb: false });
let other_image = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.5; 4]; IMAGE_TEXELS], srgb: false });
let old_weak = Arc::downgrade(&old_image);
let other_weak = Arc::downgrade(&other_image);
assert!(old_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::<f32>() > 0.0);
assert!(other_image.rgba.iter().map(|pixel| std::hint::black_box(pixel[0])).sum::<f32>() > 0.0);
thumbs.saved_brush_previews.insert(first_path.clone(), (Some(settings.clone()), None, 0));
thumbs.saved_brush_previews.insert(second_path.clone(), (Some(settings), None, 0));
let mut images: ImageStore = [("alpha.png".into(), old_image.clone())].into();
drop(thumbs.saved_brush_preview(&first_path, &images));
images.insert("alpha.png".into(), other_image.clone());
drop(thumbs.saved_brush_preview(&second_path, &images));
drop(old_image);
drop(other_image);
assert!(old_weak.upgrade().is_none(), "cached settings do not retain a replaced image");
assert!(other_weak.upgrade().is_some(), "the project still owns its current image");
eprintln!(
"saved brush cache after first replacement: 0 of {IMAGE_BYTES} old image bytes retained, {} current image strong owners",
Arc::strong_count(&images["alpha.png"])
);
let replacement = Arc::new(ImageRes { width: IMAGE_SIDE, height: IMAGE_SIDE, rgba: vec![[0.0; 4]; IMAGE_TEXELS], srgb: false });
images.insert("alpha.png".into(), replacement);
drop(thumbs.saved_brush_preview(&first_path, &images));
assert!(other_weak.upgrade().is_none(), "another saved brush does not retain the old project image");
eprintln!("saved brush cache after second replacement: 0 of {IMAGE_BYTES} previous image bytes retained");
thumbs.forget_saved_files();
assert!(thumbs.saved_brush_previews.is_empty(), "refresh releases parsed brush settings");
}
#[test]
fn replacing_an_image_rebuilds_its_preview() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false });
let first_image = image(0.2);
let replacement_image = image(0.8);
let first = thumbs.image(&context, "sample.png", &first_image);
let second = thumbs.image(&context, "sample.png", &replacement_image);
assert_ne!(first.id(), second.id(), "a replaced resource must update its preview");
}
#[test]
fn removing_resources_releases_their_previews() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
let mut images = ImageStore::new();
for index in 0..3 {
let name = format!("image-{index}");
images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false }));
}
for (name, image) in &images {
drop(thumbs.image(&context, name, image));
}
let cached_pixel_bytes = |thumbs: &Thumbs| thumbs.images.values().map(|(_, texture)| texture.size()[0] * texture.size()[1] * 4).sum::<usize>();
let before_count = thumbs.images.len();
let before_pixel_bytes = cached_pixel_bytes(&thumbs);
images.remove("image-0");
images.remove("image-1");
thumbs.sync_images(&images, 1);
let after_count = thumbs.images.len();
let after_pixel_bytes = cached_pixel_bytes(&thumbs);
eprintln!("cached previews: {before_count} -> {after_count}; texture pixel bytes: {before_pixel_bytes} -> {after_pixel_bytes}");
assert_eq!((before_count, after_count), (3, 1));
assert!(after_pixel_bytes < before_pixel_bytes);
assert!(thumbs.images.contains_key("image-2"));
images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false }));
drop(thumbs.image(&context, "image-3", &images["image-3"]));
thumbs.sync_images(&images, 2);
assert_eq!(thumbs.images.len(), 2);
images.clear();
thumbs.sync_images(&images, 3);
eprintln!("cached previews after clearing resources: {}", thumbs.images.len());
assert!(thumbs.images.is_empty());
}
}
+100 -36
View File
@@ -17,29 +17,36 @@ const BAR_SPACING: f32 = 10.0;
const COMPACT_BAR_SPACING: f32 = 4.0;
const BAR_SEPARATOR_WIDTH: f32 = 6.0;
pub fn tool_icon(t: Tool) -> &'static str {
match t {
/// Height of the top bar, in points
const BAR_HEIGHT: f32 = 40.0;
/// Padding inside the top bar card on its left and right, in points
const BAR_PADDING: egui::Margin = egui::Margin::symmetric(8, 0);
pub fn tool_icon(tool: Tool) -> &'static str {
match tool {
Tool::Paint => ic::PAINT_BRUSH,
Tool::Eraser => ic::ERASER,
Tool::Projection => ic::PROJECTOR_SCREEN,
Tool::Projection => ic::CUBE_FOCUS,
Tool::PolygonFill => ic::POLYGON,
Tool::Smudge => ic::FINGERPRINT,
Tool::Clone => ic::STAMP,
Tool::ColorPicker => ic::EYEDROPPER,
Tool::Path => ic::PATH,
Tool::GeometryMask => ic::CUBE_FOCUS,
Tool::Path => ic::PEN_NIB_STRAIGHT,
Tool::GeometryMask => ic::SELECTION_SLASH,
}
}
/// Keep mode buttons visible, with painting controls scrolling as space runs out
pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
let tokens = Tokens::get(ui.ctx());
egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| {
card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| {
egui::Panel::top("paint_bar").exact_size(BAR_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| {
card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, BAR_PADDING, |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let button_size = ui.spacing().interact_size.y;
let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING;
let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING;
// Leave room for both scroll arrows and at least one button of content
let minimum_strip_width = 3.0 * button_size + 2.0 * BAR_SPACING;
let scroll_views =
@@ -54,7 +61,9 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
if !scroll_views {
view_buttons(app, ui);
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
if app.session.tool_usable(app.session.tool.tool) {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
}
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
@@ -183,9 +192,15 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens:
scroll_area.show(ui, |ui| {
ui.scroll_with_delta(vec2(scroll_delta, 0.0));
ui.horizontal_centered(|ui| {
tool_controls(app, ui, tokens);
// A tool that can't act on the selection leaves the bar, as the shelf greys it
let tool_usable = app.session.tool_usable(app.session.tool.tool);
if tool_usable {
tool_controls(app, ui, tokens);
}
if scroll_views {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
if tool_usable {
ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH));
}
let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height());
ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui));
}
@@ -344,41 +359,90 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
}
}
/// Shelf order of the tools; their shortcut keys follow `Tool::ALL`
const SHELF_TOOLS: [Tool; 9] =
[Tool::Paint, Tool::Eraser, Tool::Path, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::GeometryMask];
/// The tools Baking keeps on its shelf, greyed
const BAKING_SHELF_TOOLS: [Tool; 3] = [Tool::Paint, Tool::Eraser, Tool::PolygonFill];
/// Width of the tool shelf, in points
const SHELF_WIDTH: f32 = 40.0;
/// Size of a shelf button, in points
const SHELF_BUTTON_SIZE: f32 = 28.0;
/// Vertical gap between shelf buttons, in points
const SHELF_BUTTON_SPACING: f32 = 3.0;
/// Space on each side of the lines between shelf groups, in points
const SHELF_GROUP_GAP: f32 = 6.0;
/// Padding inside the shelf card around its buttons, in points (sides, then top and bottom)
const SHELF_PADDING: egui::Margin = egui::Margin::symmetric(3, 6);
pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
let tokens = Tokens::get(ui.ctx());
egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| {
card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| {
ui.spacing_mut().item_spacing.y = 3.0;
ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| {
for tool in Tool::ALL {
let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool;
let hint = tip(&app.ui.keymap, tr(tool.label()), &format!("tool.{}", tool.id()));
if icon_button(ui, tool_icon(tool), &hint, selected, 28.0).clicked() {
egui::Panel::left("tool_shelf").resizable(false).exact_size(SHELF_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| {
// The tools start level with the panels' contents, below their tab strips
let top = GUTTER + crate::docking::TAB_HEIGHT as i8;
card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top, bottom: GUTTER }, SHELF_PADDING, |ui| {
ui.spacing_mut().item_spacing.y = SHELF_BUTTON_SPACING;
// Rendering has nothing to paint, so its shelf keeps only the buttons below the tools
let tools: &[Tool] = match app.ui.mode {
Mode::Painting => &SHELF_TOOLS,
Mode::Baking => &BAKING_SHELF_TOOLS,
Mode::Rendering => &[],
};
if !tools.is_empty() {
for &tool in tools {
let command = format!("tool.{}", tool.id());
let hint = tip(&app.ui.keymap, tr(tool.label()), &command);
let (usable, selected) = match app.ui.mode {
// In bake mode Paint is the cage or skew brush while one of them is being painted
Mode::Baking => {
let bake_brush = tool == Tool::Paint && app.ui.bake_paint_brush.on;
(bake_brush, bake_brush)
}
// A greyed tool never shows as selected, even while it stays equipped
_ => {
let usable = crate::menus::enabled(app, &command);
(usable, usable && app.session.tool.tool == tool)
}
};
let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner;
if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting {
app.run("tool.select", json!({"tool": tool.id()}));
}
}
ui.add_space(6.0);
ui.add_space(SHELF_GROUP_GAP);
ui.separator();
ui.add_space(6.0);
let quick_mask = &app.session.quick_mask;
for (command, icon, label, selected) in [
("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled),
("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing),
("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted),
] {
if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), selected, 28.0).clicked() {
app.run(command, json!({}));
}
}
ui.add_space(SHELF_GROUP_GAP);
}
ui.add_space(6.0);
ui.separator();
ui.add_space(6.0);
if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() {
app.ui.dock.focus(Panel::Assets);
let quick_mask = &app.session.quick_mask;
for (command, icon, label, selected) in [
("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled),
("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing),
("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted),
] {
let hint = tip(&app.ui.keymap, label, command);
let button = ui.add_enabled_ui(crate::menus::enabled(app, command), |ui| icon_button(ui, icon, &hint, selected, SHELF_BUTTON_SIZE)).inner;
if button.on_disabled_hover_text(label).clicked() {
app.run(command, json!({}));
}
});
}
ui.add_space(SHELF_GROUP_GAP);
ui.separator();
ui.add_space(SHELF_GROUP_GAP);
let painting = app.ui.mode == Mode::Painting;
if ui.add_enabled_ui(painting, |ui| icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, SHELF_BUTTON_SIZE)).inner.clicked()
{
app.ui.dock.focus(Panel::Assets);
}
});
});
}
+66 -3
View File
@@ -13,6 +13,9 @@ const STORAGE_STEM: &str = "ui";
/// eframe storage key under which earlier builds kept the UI state, as RON
const RON_STORAGE_KEY: &str = "ui";
/// Textures moved from index 8 to index 6 when procedurals joined that type
const LEGACY_TEXTURES_TAB: usize = 8;
const TEXTURES_TAB: usize = 6;
/// Maximum encoded UI state size for both reads and writes; typical states are a few kilobytes
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
@@ -65,7 +68,7 @@ impl UiStateStore {
return None;
}
let ui = serde_json::from_slice::<UiState>(&bytes).ok();
let ui = decode_json_ui(&bytes);
if !ui.as_ref().is_some_and(fully_read) {
self.unreadable = Some((bytes, "json"));
}
@@ -75,7 +78,10 @@ impl UiStateStore {
/// Preserve the original RON when decoding loses either dock, even if other settings load
fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option<UiState> {
let text = storage.get_string(RON_STORAGE_KEY)?;
let ui = eframe::get_value::<UiState>(storage, RON_STORAGE_KEY);
let mut ui = eframe::get_value::<UiState>(storage, RON_STORAGE_KEY);
if let Some(ui) = &mut ui {
migrate_shelf_tab(ui, ron_has_shelf_path(&text));
}
if !ui.as_ref().is_some_and(fully_read) {
self.unreadable = Some((text.into_bytes(), "ron"));
}
@@ -158,9 +164,52 @@ impl UiStateStore {
}
}
/// Old saved states have no shelf path, so their former Textures index needs remapping
fn migrate_shelf_tab(ui: &mut UiState, has_shelf_path: bool) {
if ui.shelf_tab == LEGACY_TEXTURES_TAB && !has_shelf_path {
ui.shelf_tab = TEXTURES_TAB;
}
}
/// Decode JSON settings and map the old Textures index only when its new fields are absent
fn decode_json_ui(bytes: &[u8]) -> Option<UiState> {
let mut ui = serde_json::from_slice::<UiState>(bytes).ok()?;
if ui.shelf_tab == LEGACY_TEXTURES_TAB {
let has_shelf_path = serde_json::from_slice::<serde_json::Value>(bytes)
.ok()
.and_then(|state| state.as_object().map(|fields| fields.contains_key("shelf_path")))
.unwrap_or(true);
migrate_shelf_tab(&mut ui, has_shelf_path);
}
Some(ui)
}
/// Ignore user text while looking for the field in legacy RON settings
fn ron_has_shelf_path(text: &str) -> bool {
let bytes = text.as_bytes();
let mut quoted = false;
let mut escaped = false;
for (index, byte) in bytes.iter().enumerate() {
if quoted {
if escaped {
escaped = false;
} else if *byte == b'\\' {
escaped = true;
} else if *byte == b'"' {
quoted = false;
}
} else if *byte == b'"' {
quoted = true;
} else if bytes[index..].starts_with(b"shelf_path:") && (index == 0 || matches!(bytes[index - 1], b',' | b'(' | b' ' | b'\n')) {
return true;
}
}
false
}
/// The UI state saved in `file`, if it reads
pub fn read(file: &Path) -> Option<UiState> {
serde_json::from_slice(&read_bytes(file).ok()?).ok()
decode_json_ui(&read_bytes(file).ok()?)
}
/// eframe's browser storage reports write failures only through logging, so verify before discarding old settings
@@ -311,6 +360,20 @@ pub(crate) mod tests {
assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded);
}
#[test]
fn legacy_ron_textures_index_migrates_to_the_combined_type() {
let mut storage = MemoryStorage::default();
let legacy = include_str!("../tests/fixture/ui_state_before_json.ron")
.replace("shelf_tab:0", "shelf_tab:8")
.replace("shelf_filter:\"\"", "shelf_filter:\"shelf_path:\"");
assert!(legacy.contains("shelf_tab:8") && !ron_has_shelf_path(&legacy));
storage.values.insert(RON_STORAGE_KEY.into(), legacy);
let loaded = UiStateStore::default().load(Some(&storage)).expect("the legacy state loads");
assert_eq!(loaded.shelf_tab, TEXTURES_TAB);
}
#[test]
fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() {
let folder = test_folder("unreadable");
+212 -97
View File
@@ -54,6 +54,18 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
crate::toolbar::paint_bar(app, ui);
}
let stroke_end = ui.scope_id().with("paint_2d_stroke_end");
// A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture.
let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) {
ui.data_mut(|data| {
let endpoint = data.get_temp(stroke_end);
data.remove::<crate::uv_paint_point::UvPaintPoint>(stroke_end);
endpoint
})
} else {
None
};
finish_unavailable_tool_gestures(app, pending_2d_endpoint);
crate::id_color_pick::IdColorPick::end_when_stale(app);
let tokens = Tokens::get(ui.ctx());
let aux_view = match app.session.view {
@@ -178,9 +190,30 @@ const RUBBER_BAND_GAP: f32 = 4.0;
/// Opacity of the UV tile outlines in the 2D view
const UV_TILE_OUTLINE_ALPHA: u8 = 40;
/// Width of the UV tile outlines, in points
const UV_TILE_OUTLINE_WIDTH: f32 = 1.0;
/// The texture set name in the 2D view's bottom-right corner: its inset from the corner and its text size, in points
const SET_NAME_INSET: egui::Vec2 = vec2(10.0, 10.0);
const SET_NAME_TEXT_SIZE: f32 = 11.0;
/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible
const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0;
/// The bake brush cursor's outline: width in points and white alpha
const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0;
const BAKE_PAINT_CURSOR_ALPHA: u8 = 200;
/// A UDIM tile label: its offset from the tile's top-left corner and its text size, in points
const UV_TILE_LABEL_OFFSET: egui::Vec2 = vec2(6.0, 4.0);
const UV_TILE_LABEL_SIZE: f32 = 11.0;
/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points
const STENCIL_OUTLINE_STROKE: f32 = 1.0;
const STENCIL_OUTLINE_ALPHA: u8 = 120;
const STENCIL_OUTLINE_DASH: f32 = 5.0;
const STENCIL_OUTLINE_GAP: f32 = 4.0;
/// The 2D view's width when the split divider is at `divider_x`
fn uv_view_width(full: Rect, divider_x: f32) -> f32 {
(full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0)
@@ -219,18 +252,25 @@ fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) {
ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal);
}
/// The shader's view modes (`Shade::view_mode`): the material, one channel, the aux texture (mesh map, mask or quick mask), the UV checker
const VIEW_MODE_MATERIAL: u32 = 0;
const VIEW_MODE_CHANNEL: u32 = 1;
const VIEW_MODE_AUX_TEXTURE: u32 = 2;
const VIEW_MODE_UV_CHECKER: u32 = 3;
fn shade(app: &TextureCraftApp) -> Shade {
let (view_mode, channel) = match app.session.view {
_ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (2, 0),
ViewMode::Material => (0, 0),
ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32),
ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0),
ViewMode::UvChecker => (3, 0),
_ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (VIEW_MODE_AUX_TEXTURE, 0),
ViewMode::Material => (VIEW_MODE_MATERIAL, 0),
ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32),
ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0),
ViewMode::UvChecker => (VIEW_MODE_UV_CHECKER, 0),
};
let set_index = app.session.ts();
let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0);
// Polygon fill shows the polygons it fills without changing the saved wireframe toggles
let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill;
let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill;
Shade {
height_strength,
view_mode,
@@ -490,7 +530,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
// Navigation; S + drag moves the projection stencil instead, below
let delta = ui.input(|input| input.pointer.delta());
let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input();
let stencil_drag = s_held && app.session.tool.stencil.is_some();
// Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise
let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection;
let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some();
if stencil_drag || adjusting {
// The stencil or the brush changes instead of the camera
} else if response.dragged_by(PointerButton::Middle) {
@@ -512,8 +555,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
if scroll != 0.0 {
if shift && app.ui.mode == crate::state::Mode::Painting {
let brush = &mut app.session.tool.brush;
brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
// A tool that can't act keeps its size: its controls are hidden
if tool_acts(app) {
let brush = &mut app.session.tool.brush;
brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
}
} else {
app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT);
}
@@ -539,7 +585,10 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
// Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it
if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() {
if s_held
&& stencil_moves
&& let Some(stencil) = app.session.tool.stencil.as_mut()
{
if response.dragged_by(PointerButton::Primary) {
stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0);
} else if response.dragged_by(PointerButton::Secondary) {
@@ -638,7 +687,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect);
// Painting
let painting = app.ui.mode == crate::state::Mode::Painting
let painting = tool_acts(app)
&& !popup
&& !alt
&& !adjusting
@@ -718,7 +767,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
// Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began
let mut symmetry_cursor = None;
if app.ui.mode == crate::state::Mode::Painting
if tool_acts(app)
&& !navigating
&& response.hovered()
&& brush_tool(app.session.tool.tool)
@@ -748,7 +797,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
}
if app.ui.mode == crate::state::Mode::Painting && path_tool {
if tool_acts(app) && path_tool {
path_overlay(app, ui, rect, &response, false, show);
}
crate::symmetry::overlay(app, ui, rect, symmetry_cursor);
@@ -1010,12 +1059,13 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
/// Draw the projection stencil in Paint Mode
fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Projection {
if !tool_acts(app) || app.session.tool.tool != Tool::Projection {
return;
}
let Some(stencil) = app.session.tool.stencil.clone() else { return };
let Some(image) = app.session.images.get(&stencil.image).cloned() else { return };
// Where the stencil's corners land on screen
let texture = app.thumbs.stencil(ui.ctx(), &stencil.image, &image);
let aspect = rect.width() / rect.height().max(1.0);
let (center, half_size, rotation) = stencil.placement(image.width as f32 / image.height.max(1) as f32, aspect);
@@ -1025,7 +1075,8 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
let (x, y) = (x * half_size[0], y * half_size[1]);
to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine)
};
let tint = Color32::from_white_alpha((stencil.opacity * 255.0) as u8);
let tint = Color32::from_white_alpha((stencil.opacity * f32::from(u8::MAX)) as u8);
let mut mesh = egui::Mesh::with_texture(texture.id());
for (x, y, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] {
mesh.vertices.push(egui::epaint::Vertex { pos: corner(x, y), uv: pos2(u, v), color: tint });
@@ -1033,8 +1084,10 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);
let painter = ui.painter_at(rect);
painter.add(egui::Shape::mesh(mesh));
let outline = vec![corner(-1.0, 1.0), corner(1.0, 1.0), corner(1.0, -1.0), corner(-1.0, -1.0), corner(-1.0, 1.0)];
painter.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0));
let outline_stroke = Stroke::new(STENCIL_OUTLINE_STROKE, Color32::from_white_alpha(STENCIL_OUTLINE_ALPHA));
painter.add(egui::Shape::dashed_line(&outline, outline_stroke, STENCIL_OUTLINE_DASH, STENCIL_OUTLINE_GAP));
}
/// A world point on screen in the 3D view `rect` (None behind the camera)
@@ -1082,19 +1135,16 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) {
return;
}
if app.ui.mode != crate::state::Mode::Painting
|| app.session.tool.tool != Tool::Path
|| app.session.tool.path.points.is_empty()
|| ui.ctx().egui_wants_keyboard_input()
{
if !tool_acts(app) || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() || ui.ctx().egui_wants_keyboard_input() {
return;
}
let (enter, back) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::Enter), i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)));
let (enter, backspace) =
ui.input_mut(|input| (input.consume_key(egui::Modifiers::NONE, egui::Key::Enter), input.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)));
if enter {
app.run("tool.path", json!({"commit": true}));
}
if back {
if backspace {
app.session.remove_selected_path_point();
}
}
@@ -1484,23 +1534,43 @@ fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option<Rect>) {
ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside);
}
/// V held with the Clone tool in painting mode: clicks set the clone source.
/// V held with the Clone tool in painting mode: clicks set the clone source
fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool {
app.ui.mode == crate::state::Mode::Painting
&& app.session.tool.tool == Tool::Clone
&& ui.input(|i| i.key_down(egui::Key::V))
&& !ui.ctx().egui_wants_keyboard_input()
tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(egui::Key::V)) && !ui.ctx().egui_wants_keyboard_input()
}
/// Crosshair where the Clone tool reads from.
fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) {
let tk = Tokens::get(ui.ctx());
let Some(c) = project(app, rect, pos) else { return };
let p = ui.painter_at(rect);
for (w, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tk.viewport_accent)] {
p.circle_stroke(c, 7.0, Stroke::new(w, color));
p.line_segment([c - vec2(11.0, 0.0), c + vec2(11.0, 0.0)], Stroke::new(w, color));
p.line_segment([c - vec2(0.0, 11.0), c + vec2(0.0, 11.0)], Stroke::new(w, color));
let tokens = Tokens::get(ui.ctx());
let Some(center) = project(app, rect, pos) else { return };
let painter = ui.painter_at(rect);
for (stroke_width, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tokens.viewport_accent)] {
painter.circle_stroke(center, 7.0, Stroke::new(stroke_width, color));
painter.line_segment([center - vec2(11.0, 0.0), center + vec2(11.0, 0.0)], Stroke::new(stroke_width, color));
painter.line_segment([center - vec2(0.0, 11.0), center + vec2(0.0, 11.0)], Stroke::new(stroke_width, color));
}
}
/// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views
fn tool_acts(app: &TextureCraftApp) -> bool {
app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool)
}
/// Both views must close gestures even when the selection disables their input handlers.
fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp, pending_2d_endpoint: Option<crate::uv_paint_point::UvPaintPoint>) {
if !tool_acts(app) {
if app.session.stroke_active() {
match app.session.end_stroke() {
Ok(()) => {
if let Some(endpoint) = pending_2d_endpoint {
app.last_paint_uv = Some(endpoint);
}
}
Err(error) => app.toast(error.to_string(), true),
}
}
app.session.end_polygon_fill_box();
}
}
@@ -1509,15 +1579,13 @@ fn brush_tool(t: Tool) -> bool {
matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path)
}
/// Ctrl (Cmd on macOS) + drag in a view changes the brush instead of painting or navigating: a
/// right drag its size (left/right) and hardness (up/down), a left drag its flow and angle. True
/// while Ctrl is held with a brush tool and no stroke is under way.
fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response) -> bool {
let held =
app.ui.mode == crate::state::Mode::Painting && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|i| i.modifiers.command);
if held && let Some(right) = brush_drag_button(resp) {
adjust_brush(&mut app.session.tool.brush, right, ui.input(|i| i.pointer.delta()));
/// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`)
fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool {
let held = tool_acts(app) && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|input| input.modifiers.command);
if held && let Some(right) = brush_drag_button(response) {
adjust_brush(&mut app.session.tool.brush, right, ui.input(|input| input.pointer.delta()));
}
held
}
@@ -1529,25 +1597,28 @@ fn brush_drag_button(resp: &egui::Response) -> Option<bool> {
/// While a Ctrl+drag changes the brush, its values beside where the drag began (drawn over the
/// view; the tool bar and Properties show them too).
fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjusting: bool) {
let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return };
let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return };
// The pointer would cover the values; the brush cursor stays where the drag began.
if ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| resp.rect.contains(p)) {
fn brush_readout(app: &TextureCraftApp, ui: &Ui, response: &egui::Response, adjusting: bool) {
let Some(right_drag) = brush_drag_button(response).filter(|_| adjusting) else { return };
let Some(press_origin) = ui.input(|input| input.pointer.press_origin()) else { return };
// Keep the brush cursor at the drag origin so the pointer does not cover the values
if ui.input(|input| input.pointer.latest_pos()).is_some_and(|pointer| response.rect.contains(pointer)) {
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
}
let b = &app.session.tool.brush;
let text = if right {
format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0)
let brush = &app.session.tool.brush;
let text = if right_drag {
format!("{} {:.1} {} {:.0}", tr("Size"), brush.size / 0.25 * 100.0, tr("Hardness"), brush.hardness * 100.0)
} else {
format!("{} {:.0} {} {:.0}°", tr("Flow"), b.flow * 100.0, tr("Angle"), b.angle)
format!("{} {:.0} {} {:.0}°", tr("Flow"), brush.flow * 100.0, tr("Angle"), brush.angle)
};
let tk = Tokens::get(ui.ctx());
let p = ui.painter_at(resp.rect);
let g = p.layout_no_wrap(text, egui::FontId::proportional(12.0), tk.text_strong);
let r = Rect::from_min_size(at + vec2(18.0, -30.0), g.size()).expand2(vec2(6.0, 3.0));
p.rect_filled(r, 3.0, tk.panel);
p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong);
let tokens = Tokens::get(ui.ctx());
let painter = ui.painter_at(response.rect);
let galley = painter.layout_no_wrap(text, egui::FontId::proportional(12.0), tokens.text_strong);
let readout_rect = Rect::from_min_size(press_origin + vec2(18.0, -30.0), galley.size()).expand2(vec2(6.0, 3.0));
painter.rect_filled(readout_rect, 3.0, tokens.panel);
painter.galley(readout_rect.min + vec2(6.0, 3.0), galley, tokens.text_strong);
}
/// Size fraction, hardness and flow change per point of a Ctrl+drag
@@ -1623,9 +1694,9 @@ fn pen_pressure(ui: &Ui) -> f32 {
ui.data_mut(|d| d.insert_temp(id, f));
f
}
// A pen lifts with no pressure, and a tap paints on that frame: keep its contact pressure.
// A pen lifts with no pressure, so keep its contact pressure for a tap
Some((egui::TouchPhase::End, None)) => ui.data(|d| d.get_temp(id)).unwrap_or(1.0),
// A touch without pressure (a finger) must not inherit an earlier pen's.
// A finger must not inherit an earlier pen's pressure
Some((egui::TouchPhase::Start, None)) => {
ui.data_mut(|d| d.remove_temp::<f32>(id));
1.0
@@ -1664,8 +1735,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
// Conversions between the view's points and the texture set's UV space
let ts = app.session.ts();
let set = app.session.doc.project.texture_sets.get(ts);
let texture_set_index = app.session.ts();
let set = app.session.doc.project.texture_sets.get(texture_set_index);
let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size()));
let pan = app.ui.uv_pan;
let to_uv = |pointer: egui::Pos2| {
@@ -1712,7 +1783,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
// Painting in UV space
let painting = app.ui.mode == crate::state::Mode::Painting
let painting = tool_acts(app)
&& app.properties_popup.is_none()
&& !crate::rail_popup::blocks_paint_input(app, ui.ctx())
&& !alt
@@ -1742,7 +1813,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let frame = Frame {
view_id: VIEW_2D,
size: frame_size_in_pixels(ui, rect),
kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan },
kind: ViewKind::Uv { ts: texture_set_index, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan },
camera: app.session.camera,
shade: shade(app),
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
@@ -1754,8 +1825,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
// The UV tile outlines (numbered for UDIM sets) and the path being edited
let painter = ui.painter_at(rect);
let set = app.session.doc.project.texture_sets.get(ts);
let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside);
let set = app.session.doc.project.texture_sets.get(texture_set_index);
let outline = |tile: Rect| {
painter.rect_stroke(tile, 0.0, Stroke::new(UV_TILE_OUTLINE_WIDTH, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside)
};
match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) {
Some((texture_set, grid)) => {
for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) {
@@ -1765,10 +1838,10 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32));
outline(tile);
painter.text(
tile.left_top() + vec2(6.0, 4.0),
tile.left_top() + UV_TILE_LABEL_OFFSET,
egui::Align2::LEFT_TOP,
udim.to_string(),
egui::FontId::proportional(11.0),
egui::FontId::proportional(UV_TILE_LABEL_SIZE),
tokens.viewport_text,
);
}
@@ -1777,7 +1850,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0)));
}
}
if app.ui.mode == crate::state::Mode::Painting && path_tool {
if tool_acts(app) && path_tool {
path_overlay(app, ui, rect, &response, true, show);
}
@@ -1796,54 +1869,63 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0));
if bake_paint_on && let Some(hover) = response.hover_pos() {
let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS);
painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200)));
painter.circle_stroke(hover, radius, Stroke::new(BAKE_PAINT_CURSOR_STROKE, Color32::from_white_alpha(BAKE_PAINT_CURSOR_ALPHA)));
}
}
// Brush cursor: the stamp's size and hardness at the pointer, as in the 3D view.
let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held;
// Brush cursor shows the stamp's size and hardness at the pointer
let show_brush_cursor = tool_acts(app) && !alt && !v_held;
let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p));
if cursor_mode
if show_brush_cursor
&& !path_tool
&& brush_tool(app.session.tool.tool)
&& !response.dragged_by(PointerButton::Middle)
// During a drag egui keeps reporting a hover position after the pointer left the view:
// the system pointer is hidden only while the pointer is really over it. A Ctrl+drag that
// changes the brush keeps its outline at the press origin wherever the pointer goes.
// A drag can retain stale hover while the pointer is outside the view
&& (adjusting || pointer_in_view)
// While a Ctrl+drag changes the brush, its cursor stays where the drag began.
&& let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) }
// The view header's pickers keep the normal pointer.
&& !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(hp))
// Ctrl+drag keeps the brush outline at the press origin
&& let Some(cursor_center) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) }
// View header pickers keep the normal pointer
&& !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(cursor_center))
{
// The stamp's radius as `continue_stroke_uv` paints it, including a light pen's smaller footprint.
let r = (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5);
// Match the stamp radius used by `continue_stroke_uv`, including pen pressure
let radius_points =
(to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(BRUSH_CURSOR_MIN_RADIUS_POINTS);
if pointer_in_view {
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
}
brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness);
brush_cursor_2d(&painter, cursor_center, radius_points, app.session.tool.brush.hardness);
}
brush_readout(app, ui, &response, adjusting);
view_header(app, ui, rect, "v2d");
axis_gizmo(ui, rect, app, true);
let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default();
ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text);
let name = app.session.doc.project.texture_sets.get(texture_set_index).map(|texture_set| texture_set.name.clone()).unwrap_or_default();
let name_position = rect.right_bottom() - SET_NAME_INSET;
ui.painter().text(name_position, egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(SET_NAME_TEXT_SIZE), tokens.viewport_text);
}
/// The brush outline (and its hardness ring) as screen circles around `c`, radius `r` in points.
fn brush_cursor_2d(p: &egui::Painter, c: egui::Pos2, r: f32, hardness: f32) {
p.circle_stroke(c, r, Stroke::new(2.5, Color32::from_black_alpha(140)));
p.circle_stroke(c, r, Stroke::new(1.2, Color32::from_white_alpha(230)));
if hardness > 0.05 {
let inner: Vec<egui::Pos2> = (0..=48)
.map(|k| {
let a = k as f32 / 48.0 * std::f32::consts::TAU;
c + vec2(a.cos(), a.sin()) * r * hardness
/// Smallest visible 2D brush outline, in points
const BRUSH_CURSOR_MIN_RADIUS_POINTS: f32 = 1.5;
/// Hardness ring segments, balancing smoothness and per-frame shape work
const BRUSH_CURSOR_RING_SEGMENTS: usize = 48;
/// Smaller hardness rings overlap the center dot
const BRUSH_CURSOR_MIN_RING_HARDNESS: f32 = 0.05;
/// The brush outline and hardness ring around `center`, with `radius_points` in screen points
fn brush_cursor_2d(painter: &egui::Painter, center: egui::Pos2, radius_points: f32, hardness: f32) {
painter.circle_stroke(center, radius_points, Stroke::new(2.5, Color32::from_black_alpha(140)));
painter.circle_stroke(center, radius_points, Stroke::new(1.2, Color32::from_white_alpha(230)));
if hardness > BRUSH_CURSOR_MIN_RING_HARDNESS {
let inner_ring: Vec<egui::Pos2> = (0..=BRUSH_CURSOR_RING_SEGMENTS)
.map(|point_index| {
let angle = point_index as f32 / BRUSH_CURSOR_RING_SEGMENTS as f32 * std::f32::consts::TAU;
center + vec2(angle.cos(), angle.sin()) * radius_points * hardness
})
.collect();
p.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0));
painter.add(egui::Shape::dashed_line(&inner_ring, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0));
}
p.circle_filled(c, 1.5, Color32::WHITE);
painter.circle_filled(center, 1.5, Color32::WHITE);
}
/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke.
@@ -1880,7 +1962,13 @@ fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response,
if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) {
let finishing = app.session.stroke_active();
match app.session.end_stroke() {
Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)),
Ok(()) if finishing => {
app.last_paint_uv = ui.data_mut(|data| {
let endpoint = data.get_temp(stroke_end);
data.remove::<crate::uv_paint_point::UvPaintPoint>(stroke_end);
endpoint
});
}
Ok(()) => {}
Err(error) => app.toast(error.to_string(), true),
}
@@ -1943,6 +2031,33 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t
mod tests {
use super::*;
#[test]
fn unavailable_tools_finish_strokes_and_box_fills() {
use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives};
for tool in [Tool::Paint, Tool::PolygonFill] {
let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session));
let app = harness.state_mut();
app.session.tool.tool = tool;
let history = app.session.history_labels().len();
if tool == Tool::Paint {
app.session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap();
assert!(app.session.stroke_active());
} else {
assert!(app.session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0);
}
app.session.target = StackTarget::Effect(LayerId(u64::MAX));
assert!(!tool_acts(app));
finish_unavailable_tool_gestures(app, None);
assert!(!app.session.stroke_active());
assert_eq!(app.session.history_labels().len(), history + 1);
assert_eq!(app.session.end_polygon_fill_box(), 0, "the interrupted box is already closed");
finish_unavailable_tool_gestures(app, None);
assert_eq!(app.session.history_labels().len(), history + 1, "cleanup records the gesture only once");
}
}
#[test]
fn stored_surfaces_release_after_a_frame_without_paths() {
use texturecraft_engine::{core::EffectKind, execute, geom::primitives};
+104 -89
View File
@@ -2,142 +2,157 @@
use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase};
use egui_kittest::Harness;
use serde_json::json;
use texturecraft_engine::execute;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::state::{Mode, ViewLayout};
fn harness() -> Harness<'static, TextureCraftApp> {
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.state_mut().ui.layout = ViewLayout::Only2D;
h.run_steps(4);
h
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.layout = ViewLayout::Only2D;
harness.run_steps(4);
harness
}
fn cursor(h: &Harness<'_, TextureCraftApp>) -> CursorIcon {
h.output().platform_output.cursor_icon
fn cursor(harness: &Harness<'_, TextureCraftApp>) -> CursorIcon {
harness.output().platform_output.cursor_icon
}
#[test]
fn painting_in_the_2d_view_replaces_the_pointer_with_the_brush_outline() {
let mut h = harness();
let c = egui::pos2(800.0, 480.0);
h.hover_at(c);
h.run_steps(3);
assert_eq!(cursor(&h), CursorIcon::None, "the brush outline replaces the pointer");
h.hover_at(egui::pos2(2.0, 2.0));
h.run_steps(3);
assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is back");
let mut harness = harness();
let center = egui::pos2(800.0, 480.0);
harness.hover_at(center);
harness.run_steps(3);
assert_eq!(cursor(&harness), CursorIcon::None, "the brush outline replaces the pointer");
harness.hover_at(egui::pos2(2.0, 2.0));
harness.run_steps(3);
assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is back");
}
#[test]
fn outside_painting_the_2d_view_keeps_the_normal_pointer() {
let mut h = harness();
h.state_mut().ui.mode = Mode::Baking;
h.run_steps(3);
let c = egui::pos2(800.0, 480.0);
h.hover_at(c);
h.run_steps(3);
assert_ne!(cursor(&h), CursorIcon::None);
let mut harness = harness();
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(3);
let center = egui::pos2(800.0, 480.0);
harness.hover_at(center);
harness.run_steps(3);
assert_ne!(cursor(&harness), CursorIcon::None);
}
/// Radii of the white brush-outline rings (stroke 1.2) around `c` in the last frame.
fn rings_at(h: &Harness<'_, TextureCraftApp>, c: Pos2) -> Vec<f32> {
fn walk(shape: &Shape, c: Pos2, out: &mut Vec<f32>) {
#[test]
fn unavailable_paint_tool_keeps_the_pointer_and_hides_the_2d_brush_outline() {
let mut harness = harness();
let fill = execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill, "target": "content"})).unwrap();
let pointer = egui::pos2(800.0, 480.0);
harness.hover_at(pointer);
harness.run_steps(3);
assert_ne!(cursor(&harness), CursorIcon::None, "a fill layer cannot take the paint tool");
assert!(rings_at(&harness, pointer).is_empty(), "an unavailable brush has no outline");
}
/// Radii of the white brush-outline rings (stroke 1.2) around `center` in the last frame.
fn rings_at(harness: &Harness<'_, TextureCraftApp>, center: Pos2) -> Vec<f32> {
fn walk(shape: &Shape, center: Pos2, out: &mut Vec<f32>) {
match shape {
Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, c, out)),
Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(c) < 0.5 => out.push(circle.radius),
Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, center, out)),
Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(center) < 0.5 => out.push(circle.radius),
_ => {}
}
}
let mut out = Vec::new();
h.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, c, &mut out));
harness.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, center, &mut out));
out
}
#[test]
fn the_view_header_keeps_the_normal_pointer_and_gets_no_brush_outline() {
let mut h = harness();
// The view's top edge is where the brush outline first replaces the pointer; the header is
// centred 8 points below it and 22 high.
let mut harness = harness();
// The header starts 8 points below the view edge and is 22 points high
let view_top = (0..200).map(|y| y as f32).find(|&y| {
h.hover_at(egui::pos2(300.0, y));
h.run_steps(2);
cursor(&h) == CursorIcon::None
harness.hover_at(egui::pos2(300.0, y));
harness.run_steps(2);
cursor(&harness) == CursorIcon::None
});
let top = view_top.expect("the view has a top edge");
let header = egui::pos2(800.0, top + 8.0 + 11.0);
h.hover_at(header);
h.run_steps(3);
assert_ne!(cursor(&h), CursorIcon::None, "over the pickers the pointer stays");
assert!(rings_at(&h, header).is_empty(), "no brush outline over the pickers");
harness.hover_at(header);
harness.run_steps(3);
assert_ne!(cursor(&harness), CursorIcon::None, "over the pickers the pointer stays");
assert!(rings_at(&harness, header).is_empty(), "no brush outline over the pickers");
let below = egui::pos2(800.0, top + 120.0);
h.hover_at(below);
h.run_steps(3);
assert_eq!(cursor(&h), CursorIcon::None, "below the header the brush outline is back");
assert!(!rings_at(&h, below).is_empty());
harness.hover_at(below);
harness.run_steps(3);
assert_eq!(cursor(&harness), CursorIcon::None, "below the header the brush outline is back");
assert!(!rings_at(&harness, below).is_empty());
}
#[test]
fn a_light_pen_shows_the_smaller_footprint_it_paints() {
let mut h = harness();
h.state_mut().session.tool.brush.size = 0.05;
h.state_mut().session.tool.brush.min_size = 0.5;
let c = egui::pos2(800.0, 600.0);
h.hover_at(c);
h.run_steps(3);
let full = rings_at(&h, c);
let mut harness = harness();
harness.state_mut().session.tool.brush.size = 0.05;
harness.state_mut().session.tool.brush.min_size = 0.5;
let center = egui::pos2(800.0, 600.0);
harness.hover_at(center);
harness.run_steps(3);
let full = rings_at(&harness, center);
assert_eq!(full.len(), 1, "one outline at full pressure");
// A pen sample at half pressure: stamp radius is min + (1 - min) * p = 0.75 of full.
let events = &mut h.input_mut().events;
events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: c, force: Some(0.5) });
events.push(Event::PointerMoved(c));
h.step();
let light = rings_at(&h, c);
// Half pressure gives 0.75 of the full radius with this minimum size
let events = &mut harness.input_mut().events;
events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: center, force: Some(0.5) });
events.push(Event::PointerMoved(center));
harness.step();
let light = rings_at(&harness, center);
assert_eq!(light.len(), 1);
assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]);
}
#[test]
fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() {
let mut h = harness();
let c = egui::pos2(800.0, 480.0);
h.hover_at(c);
h.run_steps(3);
assert_eq!(cursor(&h), CursorIcon::None, "inside the view the brush outline replaces the pointer");
// Press inside the view, then carry the pointer out of the view (top-left corner) with the button held.
h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(2);
assert_eq!(cursor(&h), CursorIcon::None, "still inside while dragging");
let mut harness = harness();
let center = egui::pos2(800.0, 480.0);
harness.hover_at(center);
harness.run_steps(3);
assert_eq!(cursor(&harness), CursorIcon::None, "inside the view the brush outline replaces the pointer");
// Drag from the view to its upper-left outside corner
harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
harness.run_steps(2);
assert_eq!(cursor(&harness), CursorIcon::None, "still inside while dragging");
let outside = egui::pos2(2.0, 2.0);
h.hover_at(outside);
h.run_steps(3);
assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible even during a drag");
assert!(rings_at(&h, outside).is_empty(), "no brush outline outside the view");
h.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(2);
harness.hover_at(outside);
harness.run_steps(3);
assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible even during a drag");
assert!(rings_at(&harness, outside).is_empty(), "no brush outline outside the view");
harness.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
harness.run_steps(2);
}
#[test]
fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() {
let mut h = harness();
let c = egui::pos2(800.0, 480.0);
let mut harness = harness();
let center = egui::pos2(800.0, 480.0);
let ctrl = egui::Modifiers::COMMAND;
h.hover_at(c);
h.run_steps(2);
h.event(Event::ModifiersChanged(ctrl));
h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl });
h.run_steps(2);
// Drag a little inside the view: the outline is anchored and the pointer hidden.
h.hover_at(c + egui::vec2(10.0, 0.0));
h.run_steps(3);
assert_eq!(rings_at(&h, c).len(), 1, "anchored outline while the pointer is in the view");
assert_eq!(cursor(&h), CursorIcon::None);
// Carry the pointer out of the view: the outline stays at the anchor, the system pointer is back.
h.hover_at(egui::pos2(2.0, 2.0));
h.run_steps(3);
assert_eq!(rings_at(&h, c).len(), 1, "the outline stays at the press origin outside the view");
assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible");
h.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl });
h.event(Event::ModifiersChanged(egui::Modifiers::NONE));
h.run_steps(2);
harness.hover_at(center);
harness.run_steps(2);
harness.event(Event::ModifiersChanged(ctrl));
harness.event(Event::PointerButton { pos: center, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl });
harness.run_steps(2);
// The outline stays anchored while the pointer is hidden inside the view
harness.hover_at(center + egui::vec2(10.0, 0.0));
harness.run_steps(3);
assert_eq!(rings_at(&harness, center).len(), 1, "anchored outline while the pointer is in the view");
assert_eq!(cursor(&harness), CursorIcon::None);
// Outside the view, the outline stays anchored and the system pointer returns
harness.hover_at(egui::pos2(2.0, 2.0));
harness.run_steps(3);
assert_eq!(rings_at(&harness, center).len(), 1, "the outline stays at the press origin outside the view");
assert_ne!(cursor(&harness), CursorIcon::None, "outside the view the pointer is visible");
harness.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl });
harness.event(Event::ModifiersChanged(egui::Modifiers::NONE));
harness.run_steps(2);
}
@@ -272,8 +272,11 @@ fn color_selection_snapshots_and_quick_mask_pick() {
let center = harness.state().viewport_rect.center();
harness.hover_at(center + egui::vec2(80.0, 0.0));
let expected = save(&mut harness, "color-selection-picking");
execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap();
execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap();
let with_quick_mask = save(&mut harness, "color-selection-picking-quick-mask");
assert_eq!(
with_quick_mask.get_pixel(center.x as u32, center.y as u32),
expected.get_pixel(center.x as u32, center.y as u32),
@@ -281,14 +284,18 @@ fn color_selection_snapshots_and_quick_mask_pick() {
);
click_at(&mut harness, center);
assert!(harness.state().session.quick_mask.editing, "picking preserves quick-mask editing");
save(&mut harness, "color-selection-quick-mask-restored");
execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap();
harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D;
harness.get_by_label(&pick_color_label()).click();
save(&mut harness, "color-selection-picking-2d");
click_at(&mut harness, center);
assert!(harness.state().picking_id_color.is_none());
execute(&mut harness.state_mut().session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap();
save(&mut harness, "color-selection-no-id-map");
}
+95 -24
View File
@@ -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,88 @@ 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::<Vec<_>>();
assert_eq!(order(&h), [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]);
// 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]);
// 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]);
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::<Vec<_>>();
assert_eq!(order(&harness), [a, b, c]);
// Rows show C, B, A; dropping A above C moves it to the top
drag(&mut harness, "Effect A", "Effect C", false);
assert_eq!(order(&harness), [b, c, a]);
// Dropping A below B returns it to the bottom
drag(&mut harness, "Effect A", "Effect B", true);
assert_eq!(order(&harness), [a, b, c]);
// Dropping C above A places it between A and 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");
}
/// 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");
}
+118 -116
View File
@@ -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(|layer| {
let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter());
layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.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 {
EffectKind::Generator(g) => g.level,
let (mut harness, effect) = selected_generator();
let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Generator(generator) => generator.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 point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y);
harness.drag_at(point_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(point_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(point_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(|node| (node.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);
}
+141
View File
@@ -0,0 +1,141 @@
//! 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 changing_kind_in_the_panel_preserves_the_effect() {
let (mut harness, effect) = harness(false);
let history = harness.state().session.history_labels().len();
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click();
harness.run_steps(2);
harness.get_by_label("Dirt").click();
harness.run_steps(3);
assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt);
assert_eq!(harness.state().session.history_labels().len(), history + 1);
}
#[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();
}
+3 -3
View File
@@ -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(_)));
}
+3
View File
@@ -15,6 +15,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;
@@ -30,11 +31,13 @@ mod properties_popup;
mod rail;
mod shelf_drop;
mod shelf_hover_preview;
mod shelf_panel;
mod shift_lines_2d;
mod shortcut_keys;
mod skew_paint;
mod split_divider;
mod start_window;
mod tool_availability;
mod toolbar;
mod symmetry;
@@ -20,20 +20,22 @@ const REST: f32 = 0.1;
/// Real time the worker gets to render
const WORKER_TIMEOUT: Duration = Duration::from_secs(60);
/// Open the Materials tab and find two labels unique to shelf tiles
/// Open the Materials tab and find the first two labels (the grid is sorted by name) unique to shelf tiles
fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder()
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_step_dt(step_seconds)
.with_pixels_per_point(pixels_per_point)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.shelf_tab = MATERIALS_TAB;
h.run_steps(4);
harness.state_mut().ui.shelf_tab = MATERIALS_TAB;
harness.run_steps(4);
let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect();
let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect();
plain.sort_by_key(|material| material.label.to_lowercase());
let unique: Vec<_> = plain.into_iter().filter(|material| harness.query_all_by_label(material.label).count() == 1).take(2).collect();
assert_eq!(unique.len(), 2, "two materials with unique names");
(h, unique)
(harness, unique)
}
/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points
+316
View File
@@ -0,0 +1,316 @@
//! The Assets panel's layout: columns at the reference width, type row, size menu, breadcrumb, side panes and toolbar
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::core::project::ENVIRONMENTS;
use texturecraft_engine::materials::{MATERIALS, SmartMaterial};
use texturecraft_engine::smart_masks::SMART_MASKS;
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::saved_search::SavedSearch;
use texturecraft_ui_egui::shelf_view::ShelfView;
/// The reference's capture window: its Assets panel shows four columns there
const REFERENCE_WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0);
/// A window whose default Assets panel is too narrow for the full type row
const NARROW_WINDOW: egui::Vec2 = egui::vec2(1100.0, 1032.0);
/// The types' positions in the shelf's type row (its table is crate-private)
const MATERIALS_TYPE: usize = 0;
const SMART_MASKS_TYPE: usize = 2;
const BRUSHES_TYPE: usize = 4;
const TEXTURES_TYPE: usize = 6;
const ENVIRONMENTS_TYPE: usize = 7;
/// How far the saved brush's spacing differs from the current brush's, so loading it shows
const SAVED_SPACING_CHANGE: f32 = 0.25;
/// Tile columns the reference shows at its panel width
const REFERENCE_COLUMNS: usize = 4;
/// The sample project with the shelf on the Materials type
fn shelf(size: egui::Vec2) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.shelf_tab = MATERIALS_TYPE;
harness.run_steps(4);
harness
}
/// The plain materials in the grid's order (by name)
fn plain_materials() -> Vec<&'static SmartMaterial> {
let mut plain: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect();
plain.sort_by_key(|material| material.label.to_lowercase());
plain
}
/// A clickable node labelled `label` (its tooltip, once shown, has the same label)
fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> {
harness.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}"))
}
#[test]
fn the_default_panel_shows_the_reference_column_count() {
let harness = shelf(REFERENCE_WINDOW);
let tops: Vec<f32> = plain_materials().iter().take(REFERENCE_COLUMNS + 1).map(|material| harness.get_by_label(material.label).rect().top()).collect();
assert!(tops[..REFERENCE_COLUMNS].iter().all(|top| *top == tops[0]), "the first {REFERENCE_COLUMNS} tiles share a row: {tops:?}");
assert!(tops[REFERENCE_COLUMNS] > tops[0], "the next tile starts a row: {tops:?}");
}
#[test]
fn a_click_on_the_picked_type_shows_every_type() {
let mut harness = shelf(REFERENCE_WINDOW);
let mask = SMART_MASKS[0].label;
assert!(harness.query_by_label(mask).is_none(), "the Materials type hides smart masks");
button(&harness, "Materials").click();
harness.run_steps(3);
assert!(harness.query_by_label(mask).is_some(), "no type picked shows smart masks too");
}
#[test]
fn the_search_narrows_the_picked_type_and_greys_types_without_matches() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials().into_iter().find(|material| material.label.to_lowercase().contains("rust")).unwrap();
let mask = SMART_MASKS.iter().find(|mask| mask.label.to_lowercase().contains("rust")).unwrap();
harness.state_mut().ui.shelf_filter = "rust".into();
harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE;
harness.run_steps(3);
assert!(harness.query_by_label(mask.label).is_some(), "the matching mask shows");
assert!(harness.query_by_label(material.label).is_none(), "a matching material of another type does not");
assert!(button(&harness, "Environments").accesskit_node().is_disabled(), "no environment matches");
assert!(!button(&harness, "Materials").accesskit_node().is_disabled());
button(&harness, "Materials").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_filter, "rust", "picking a type keeps the search");
assert!(harness.query_by_label(material.label).is_some());
}
#[test]
fn unavailable_project_images_do_not_make_textures_match() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().session.doc.resources.insert("unavailable-preview.png".into(), vec![0].into());
harness.state_mut().ui.shelf_filter = "unavailable-preview.png".into();
harness.run_steps(3);
assert!(button(&harness, "Textures").accesskit_node().is_disabled());
assert!(harness.query_by_label("unavailable-preview.png").is_none());
}
#[test]
fn the_breadcrumb_arrow_picks_a_library() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials()[0].label;
button(&harness, "Browse folders").click();
harness.run_steps(2);
for library in ["Project", "Starter assets", "Your assets"] {
assert!(harness.query_by_label(library).is_some(), "the list offers {library}");
}
harness.get_by_label("Project").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_path, ["project"]);
assert!(harness.query_by_label(material).is_none(), "built-in materials are not in the project");
}
#[test]
fn the_thumbnail_size_menu_switches_to_the_list() {
let mut harness = shelf(REFERENCE_WINDOW);
let material = plain_materials()[0].label;
let tile_width = harness.get_by_label(material).rect().width();
button(&harness, "Thumbnail size").click();
harness.run_steps(2);
harness.get_by_label_contains("List").click();
harness.run_steps(3);
assert_eq!(harness.state().ui.shelf_view, ShelfView::List);
assert!(harness.get_by_label(material).rect().width() > tile_width * 2.0, "a list row spans the panel");
}
#[test]
fn reset_query_shows_every_asset_again() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_filter = "rust".into();
harness.state_mut().ui.shelf_path = vec!["starter".into()];
harness.run_steps(2);
button(&harness, "Reset query").click();
harness.run_steps(3);
let ui = &harness.state().ui;
assert!(ui.shelf_filter.is_empty() && ui.shelf_path.is_empty());
assert!(harness.query_by_label(SMART_MASKS[0].label).is_some(), "every type shows");
}
#[test]
fn refresh_reads_the_saved_brushes_again() {
let mut harness = shelf(REFERENCE_WINDOW);
let stale = vec![std::path::PathBuf::from("gone.tcbrush")];
harness.state_mut().brushes = Some(stale.clone());
harness.run_steps(1);
button(&harness, "Refresh").click();
harness.run_steps(3);
assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again");
assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button");
}
#[test]
fn a_saved_search_restores_its_query() {
let mut harness = shelf(REFERENCE_WINDOW);
button(&harness, "Saved searches").click();
harness.state_mut().ui.shelf_filter = "rust".into();
harness.run_steps(3);
button(&harness, "Save the current search").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_saved_searches.len(), 1);
harness.state_mut().ui.shelf_filter.clear();
harness.run_steps(2);
harness.get_by_label("rust").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_filter, "rust");
harness.get_by_label("rust").click_secondary();
harness.run_steps(2);
// The context menu opens last, so its Delete is the newest node with that label
harness.get_all_by_label("Delete").last().unwrap().click();
harness.run_steps(2);
assert!(harness.state().ui.shelf_saved_searches.is_empty());
}
#[test]
fn filter_by_path_picks_a_folder() {
let mut harness = shelf(REFERENCE_WINDOW);
button(&harness, "Filter by path").click();
harness.run_steps(3);
harness.get_by_label("Starter assets").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_path, ["starter"]);
}
#[test]
fn many_saved_searches_keep_the_path_filter_reachable() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.state_mut().ui.shelf_saved_searches = (0..100)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.collect();
harness.run_steps(3);
let heading = harness.get_by_label("FILTER BY PATH").rect();
assert!(heading.bottom() < NARROW_WINDOW.y, "the path pane heading stays on screen: {heading:?}");
assert!(harness.query_by_label("Starter assets").is_some(), "the folder tree remains reachable");
}
#[test]
fn a_long_saved_search_list_can_select_the_last_query() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_saved_searches = (0..1000)
.map(|index| SavedSearch { name: format!("search {index}"), filter: format!("filter {index}"), tab: MATERIALS_TYPE, path: Vec::new() })
.collect();
harness.run_steps(3);
assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows");
harness.get_by_label("search 0").hover();
harness.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, -50_000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Wheel,
modifiers: egui::Modifiers::NONE,
});
harness.run_steps(3);
harness.get_by_label("search 999").click();
harness.run_steps(2);
assert_eq!(harness.state().ui.shelf_filter, "filter 999");
}
#[test]
fn a_narrow_panel_keeps_the_toolbar_and_folds_the_type_row() {
let mut harness = shelf(NARROW_WINDOW);
harness.state_mut().ui.shelf_panes.saved_searches = true;
harness.state_mut().ui.shelf_panes.filter_by_path = true;
harness.run_steps(3);
for label in ["Refresh", "Reset query", "Import resources...", "Saved searches", "Filter by path"] {
let rect = button(&harness, label).rect();
assert!(rect.bottom() <= NARROW_WINDOW.y, "{label} is inside the window: {rect:?}");
}
assert!(harness.query_by_label("Filter by type").is_some(), "the type row folds into one dropdown");
assert!(harness.query_by_label("Environments").is_none());
}
#[test]
fn an_environment_tile_switches_the_lighting() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_tab = ENVIRONMENTS_TYPE;
harness.run_steps(3);
let shown = harness.state().session.doc.project.display.environment.clone();
let other = ENVIRONMENTS.iter().find(|name| **name != shown).unwrap();
harness.get_by_label(other).click();
harness.run_steps(2);
assert_eq!(harness.state().session.doc.project.display.environment, *other);
}
#[test]
fn a_saved_brush_is_a_tile_that_loads_the_preset() {
let mut harness = shelf(REFERENCE_WINDOW);
let mut saved = harness.state().session.tool.brush.clone();
saved.spacing += SAVED_SPACING_CHANGE;
let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id()));
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
harness.state_mut().brushes = Some(vec![path.clone()]);
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click();
harness.run_steps(2);
std::fs::remove_file(&path).unwrap();
assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke");
}
#[test]
fn saved_smart_materials_keep_their_type_pickable_in_your_assets() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().library = Some(vec![std::path::PathBuf::from("Mine.tcmat")]);
harness.state_mut().ui.shelf_path = vec!["user".into()];
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
assert!(!button(&harness, "Smart materials").accesskit_node().is_disabled(), "a saved smart material is in Your assets");
assert!(button(&harness, "Materials").accesskit_node().is_disabled(), "no plain material is");
}
#[test]
fn saved_smart_materials_are_read_whatever_the_type_and_after_a_refresh() {
let mut harness = shelf(REFERENCE_WINDOW);
assert!(harness.state().library.is_some(), "read on the Materials type");
button(&harness, "Refresh").click();
harness.run_steps(2);
assert!(harness.state().library.is_some(), "read again after a refresh");
}
#[test]
fn procedurals_are_in_the_textures_type() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().ui.shelf_tab = TEXTURES_TYPE;
harness.run_steps(3);
assert!(harness.query_by_label(ProceduralKind::ALL[0].label()).is_some());
}
+37
View File
@@ -5,6 +5,7 @@ use egui_kittest::Harness;
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::{StackTarget, core::LayerId};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::state::ViewLayout;
@@ -179,6 +180,42 @@ fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() {
assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO));
}
#[test]
fn a_forced_2d_completion_moves_the_next_line_start() {
let mut harness = uv_view_app();
click(&mut harness, FIRST_CLICK, false);
harness.hover_at(CANCELLED_DRAG_FROM);
harness.run_steps(1);
harness.event(Event::PointerButton { pos: CANCELLED_DRAG_FROM, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
harness.run_steps(1);
harness.hover_at(CANCELLED_DRAG_TO);
harness.run_steps(2);
assert!(harness.state().session.stroke_active(), "the 2D drag is still active");
harness.state_mut().session.target = StackTarget::Effect(LayerId(u64::MAX));
harness.run_steps(1);
assert!(!harness.state().session.stroke_active(), "the unavailable tool finishes the drag");
harness.state_mut().session.target = StackTarget::Content;
harness.event(Event::PointerButton { pos: CANCELLED_DRAG_TO, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
harness.run_steps(2);
let (before_line, width) = alpha(&harness);
click(&mut harness, SECOND_CLICK, true);
let (after_line, _) = alpha(&harness);
let line = added(&before_line, &after_line);
let dab_centre = |point| {
let mut reference = uv_view_app();
let (blank, width) = alpha(&reference);
click(&mut reference, point, false);
let (painted, _) = alpha(&reference);
centre(&added(&blank, &painted), width)
};
let expected_middle = (dab_centre(CANCELLED_DRAG_TO) + dab_centre(SECOND_CLICK)) * 0.5;
assert!(painted_at(&line, width, expected_middle), "Shift+click starts at the forced completion endpoint");
}
#[test]
fn a_new_project_does_not_reuse_the_previous_projects_line_start() {
let mut harness = uv_view_app();
+20
View File
@@ -157,6 +157,26 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() {
assert_eq!(restored.split_ratio, 0.5);
}
#[test]
fn old_textures_tab_index_migrates_without_changing_new_all_types() {
let mut storage = MemoryStorage::default();
let mut state = UiState::default();
state.shelf_tab = 8;
UiStateStore::default().save(&state, &mut storage);
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(8));
let mut legacy: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap();
legacy.as_object_mut().unwrap().remove("shelf_path");
legacy.as_object_mut().unwrap().insert("shelf_filter".into(), "shelf_path".into());
storage.0.insert("ui.json".into(), legacy.to_string());
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(6));
state.shelf_tab = 0;
UiStateStore::default().save(&state, &mut storage);
assert_eq!(UiStateStore::default().load(Some(&storage)).map(|ui| ui.shelf_tab), Some(0));
}
#[test]
fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() {
// Zoomed in, a 2D sliver needs a zoom far past the one the view starts with
@@ -0,0 +1,270 @@
//! The shelf greys tools that can't act on the selection; the top bar and Properties follow it
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use texturecraft_engine::{Session, StackTarget, Tool, execute};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::state::Mode;
use texturecraft_ui_egui::theme::Brightness;
fn add_layer(session: &mut Session, command: &str) -> u64 {
execute(session, command, &json!({})).unwrap()["layer"].as_u64().unwrap()
}
fn select(session: &mut Session, layer: u64, target: Value) {
execute(session, "layer.select", &json!({"layer": layer, "target": target})).unwrap();
}
fn select_nothing(session: &mut Session) {
let set = session.ts();
session.selected.remove(&set);
session.target = StackTarget::Content;
}
fn app_harness() -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
harness
}
/// Selects a new fill layer's content with `tool` equipped
fn select_fill_content(harness: &mut Harness<'_, TextureCraftApp>, tool: Tool) {
let session = &mut harness.state_mut().session;
let fill = add_layer(session, "layer.add.fill");
select(session, fill, json!("content"));
session.tool.tool = tool;
harness.run_steps(4);
}
fn shelf_button_disabled(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool {
harness.get_by_label(label).accesskit_node().is_disabled()
}
fn shelf_button_selected(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool {
harness.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)
}
fn shows_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool {
harness.output().shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(found) if found.galley.text() == text))
}
#[test]
fn a_fill_layer_greys_the_paint_tools_and_shows_its_own_properties() {
let mut harness = app_harness();
let session = &mut harness.state_mut().session;
let paint = add_layer(session, "layer.add.paint");
select(session, paint, json!("content"));
harness.run_steps(4);
assert!(!shelf_button_disabled(&harness, "Paint (1)"));
assert!(shelf_button_selected(&harness, "Paint (1)"));
assert!(shows_text(&harness, "Size"), "the brush controls are in the top bar");
select_fill_content(&mut harness, Tool::PolygonFill);
assert!(shelf_button_disabled(&harness, "Paint (1)"));
assert!(shelf_button_disabled(&harness, "Polygon fill (4)"));
assert!(!shelf_button_selected(&harness, "Polygon fill (4)"), "the equipped tool doesn't show as selected while greyed");
assert!(!shelf_button_disabled(&harness, "Geometry mask (8)"));
assert!(shows_text(&harness, "Properties - Fill"), "a fill layer shows its fill whatever the tool");
assert!(!shows_text(&harness, "Size"), "a tool that can't act leaves the top bar");
}
#[test]
fn shortcuts_skip_the_tools_the_shelf_greys() {
let mut harness = app_harness();
select_fill_content(&mut harness, Tool::Paint);
harness.key_press(egui::Key::Num2);
harness.run_steps(2);
assert_eq!(harness.state().session.tool.tool, Tool::Paint, "Eraser can't act on a fill layer");
harness.key_press(egui::Key::P);
harness.run_steps(2);
assert_eq!(harness.state().session.tool.tool, Tool::ColorPicker);
}
/// Drag with the left button across the middle of the 3D view, as a stroke would
fn drag_across_the_view(harness: &mut Harness<'_, TextureCraftApp>) {
const STEPS: usize = 4;
const STEP_POINTS: f32 = 15.0;
let center = harness.state().viewport_rect.center();
let modifiers = egui::Modifiers::NONE;
harness.hover_at(center);
harness.event(egui::Event::PointerButton { pos: center, button: egui::PointerButton::Primary, pressed: true, modifiers });
harness.run_steps(2);
for step in 1..=STEPS {
harness.hover_at(center + egui::vec2(STEP_POINTS * step as f32, 0.0));
harness.run_steps(1);
}
let end = center + egui::vec2(STEP_POINTS * STEPS as f32, 0.0);
harness.event(egui::Event::PointerButton { pos: end, button: egui::PointerButton::Primary, pressed: false, modifiers });
harness.run_steps(3);
}
#[test]
fn a_tool_that_cant_act_ignores_the_view() {
let mut harness = app_harness();
let session = &mut harness.state_mut().session;
let paint = add_layer(session, "layer.add.paint");
select(session, paint, json!("content"));
harness.run_steps(4);
let steps_before = harness.state().session.history_labels().len();
drag_across_the_view(&mut harness);
assert!(harness.state().session.history_labels().len() > steps_before, "the drag reaches the mesh and paints a paint layer");
for tool in [Tool::Paint, Tool::PolygonFill, Tool::Path] {
select_fill_content(&mut harness, tool);
let steps_before = harness.state().session.history_labels().len();
drag_across_the_view(&mut harness);
let state = harness.state();
assert!(state.toasts.is_empty(), "{tool:?} on a fill layer: no error toast, got {:?}", state.toasts.first().map(|toast| &toast.text));
assert_eq!(state.session.history_labels().len(), steps_before, "{tool:?} on a fill layer changes nothing");
assert!(state.session.tool.path.points.is_empty(), "{tool:?} places no path points");
}
}
#[test]
fn bake_painting_turns_on_the_shelf_paint_tool() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
assert!(shelf_button_disabled(&harness, "Paint (1)"), "nothing is being painted yet");
harness.state_mut().ui.bake_paint_brush.on = true;
harness.run_steps(4);
assert!(harness.state().ui.bake_paint_brush.on, "the high poly allows bake painting");
assert!(!shelf_button_disabled(&harness, "Paint (1)"), "Paint is the bake brush while it paints");
assert!(shelf_button_disabled(&harness, "Eraser (2)"));
assert!(shelf_button_disabled(&harness, "Polygon fill (4)"));
}
#[test]
fn nothing_selected_asks_for_a_layer() {
let mut harness = app_harness();
select_nothing(&mut harness.state_mut().session);
harness.run_steps(4);
assert!(shows_text(&harness, "Select a layer to paint on"));
assert!(shelf_button_disabled(&harness, "Geometry mask (8)"));
}
#[test]
fn baking_keeps_three_greyed_tools_and_rendering_none() {
let mut harness = app_harness();
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
for label in ["Paint (1)", "Eraser (2)", "Polygon fill (4)"] {
assert!(shelf_button_disabled(&harness, label), "{label}");
}
assert!(harness.query_by_label("Path (7)").is_none());
harness.state_mut().ui.mode = Mode::Rendering;
harness.run_steps(4);
assert!(harness.query_by_label("Paint (1)").is_none());
}
#[test]
#[ignore = "offscreen GPU snapshots; set TC_UI_SNAPSHOTS to an output directory"]
fn tool_availability_snapshots() {
let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else {
return;
};
std::fs::create_dir_all(&directory).unwrap();
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session));
let save = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| {
for (brightness, suffix) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] {
harness.state_mut().ui.prefs.brightness = brightness;
harness.run_steps(8);
harness.render().unwrap().save(directory.join(format!("{name}-{suffix}.png"))).unwrap();
}
};
let session = &mut harness.state_mut().session;
let paint = add_layer(session, "layer.add.paint");
select(session, paint, json!("content"));
session.tool.tool = Tool::Paint;
save(&mut harness, "paint-layer");
let session = &mut harness.state_mut().session;
let fill = add_layer(session, "layer.add.fill");
select(session, fill, json!("content"));
session.tool.tool = Tool::PolygonFill;
save(&mut harness, "fill-content-polygon-fill");
let session = &mut harness.state_mut().session;
execute(session, "effect.add.filter", &json!({"layer": paint, "target": "content", "filter": "blur"})).unwrap();
let filter = session.doc.project.layer(texturecraft_engine::core::LayerId(paint)).unwrap().content_effects.last().unwrap().id.0;
select(session, paint, json!(filter));
session.tool.tool = Tool::Paint;
save(&mut harness, "filter");
let session = &mut harness.state_mut().session;
execute(session, "mask.add.black", &json!({"layer": paint})).unwrap();
select(session, paint, json!("mask"));
session.tool.tool = Tool::Smudge;
save(&mut harness, "mask-smudge");
let session = &mut harness.state_mut().session;
let folder = add_layer(session, "layer.add.group");
select(session, folder, json!("content"));
session.tool.tool = Tool::Paint;
save(&mut harness, "folder");
select_nothing(&mut harness.state_mut().session);
save(&mut harness, "nothing-selected");
harness.state_mut().ui.mode = Mode::Baking;
save(&mut harness, "baking");
harness.state_mut().ui.mode = Mode::Rendering;
save(&mut harness, "rendering");
}
#[test]
fn unavailable_effect_tools_hide_their_properties() {
for path in [false, true] {
let mut harness = app_harness();
let session = &mut harness.state_mut().session;
let layer = add_layer(session, "layer.add.paint");
select(session, layer, json!("content"));
let (effect, usable, blocked) = if path {
let result = execute(session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
(result["committed"]["effect"].as_u64().unwrap(), Tool::Path, Tool::Paint)
} else {
execute(session, "mask.add.black", &json!({"layer": layer})).unwrap();
let result = execute(session, "effect.add.paint", &json!({"layer": layer, "target": "mask"})).unwrap();
(result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Smudge)
};
select(session, layer, json!(effect));
session.tool.tool = usable;
harness.run_steps(4);
assert!(shows_text(&harness, "Size"));
harness.state_mut().session.tool.tool = blocked;
harness.run_steps(4);
assert!(!shows_text(&harness, "Size"), "unavailable effect tools hide brush controls");
if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") {
let directory = std::path::PathBuf::from(directory);
std::fs::create_dir_all(&directory).unwrap();
let name = if path { "unavailable-path-effect.png" } else { "unavailable-mask-paint-effect.png" };
harness.render().unwrap().save(directory.join(name)).unwrap();
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
stroke and keep the size; save your own brushes there too.
- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the
stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a
**particle brush**, **smudge**, **clone** (V + click sets the source), color picker, Shift+click
**particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click
straight lines, and painting directly in the **2D UV view**.
- **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays
an editable fill layer.