Auto: Preserve bake repairs and finish pending main merge

Finish integration of main at 7550205 with all saved bake review repairs and cleanup intact.
This commit is contained in:
chasse20 committed 2026-11-16 00:19:03 +00:00
commit a0905d8b4a
66 files changed
+2506 -555

No files matched your search

-1
View File
@@ -24,7 +24,6 @@ jobs:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
os: '["ubuntu-24.04","windows-latest"]'
toolchain: "1.96.0"
# xtask ci runs cargo test (including doctests), not cargo nextest.
tools: ""
packages: >-
+77
View File
@@ -0,0 +1,77 @@
# Code style
Style conventions for TextureCraft's Rust code.
Read alongside [AGENTS.md](AGENTS.md) for repository requirements.
## Naming and Rust conventions
- Use descriptive names that explain purpose; include units where useful. Avoid misleading names
and abbreviations whose meaning is unclear in context.
- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules;
`UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics.
- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`,
`args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them
longer.
- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`,
`examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language
syntax, not naming problems.
- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for
coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`.
Use more descriptive names when scope or ambiguity makes those hard to follow.
## Magic numbers
- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants
instead of leaving unexplained numeric literals in the code.
- Name constants for their purpose, with units where useful, rather than for their literal value.
Keep them in the narrowest useful scope.
- Reuse an existing constant when it represents the same concept. Equal numeric values alone do
not mean two concepts should share a constant.
- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment.
Use standard library constants for standard mathematical values.
- Keep literals inline when their role is clear, such as zero initialization, incrementing by one,
or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add
no meaning.
- Apply this guidance to tests too; clear fixture values and expected results can remain literal.
## Formatting and spacing
- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting.
Do not introduce a competing indentation or line-wrapping convention.
- Use one blank line between distinct logical steps: input preparation, validation, computation,
mutation, and result construction.
- Keep closely related statements together. Do not add a blank line after every declaration or
fragment a single operation with extra spacing.
- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before
the next statement.
- Put a blank line before a comment introducing a new step, with no blank line between the
comment and the code it explains.
- Keep documentation and attributes attached to their declarations.
- Separate function definitions with one blank line. Avoid extra empty lines just inside braces
or between every field, argument, or statement.
- In tests, separate preparation, action, and verification with blank lines when those phases
are distinct; keep related assertions together.
## Source organization
- Give each struct or enum its own source file, with its implementation beside it. Use the full
type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`.
- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and
`mod.rs`. Follow the command and node module placement required by `AGENTS.md`.
- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`.
Keep standard Rust directories and repository-mandated paths unchanged.
- Group related types into focused modules rather than collecting unrelated types in one large file.
- Apply these preferences to new types and source organization changes within scope. Do not
reorganize unrelated existing code to enforce them.
## Comments
- Explain intent or a non-obvious constraint rather than narrating the code.
- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation
comments; adjacent comment lines should each express a concise point.
- Do not add trailing punctuation to ordinary code comments.
- Preserve explanations of guards and invariants. Remove stale or redundant comments without
losing necessary rationale.
- API documentation, required license headers, and examples may use conventional multiline
formatting and punctuation.
- Apply the same comment guidance to production code and tests.
+7
View File
@@ -117,6 +117,13 @@ opt-level = 1
lto = "thin"
codegen-units = 1
# Fast optimized verification: each test executable otherwise repeats cross-crate LTO.
# `false` keeps thin LTO within each crate; release packaging keeps the profile above.
[profile.verify]
inherits = "release"
lto = false
codegen-units = 16
[profile.wasm-release]
inherits = "release"
opt-level = "s"
+24 -2
View File
@@ -1,12 +1,34 @@
//! Drives the `texturecraft-cli` binary.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use serde_json::Value;
// Nextest 0.9.130+ remaps this variable when an archive is extracted on another
// runner. Cargo's compile-time path still supports ordinary `cargo test`.
fn cli_binary() -> OsString {
cli_binary_path(std::env::var_os("CARGO_BIN_EXE_texturecraft-cli"))
}
fn cli_binary_path(runner_path: Option<OsString>) -> OsString {
runner_path.unwrap_or_else(|| env!("CARGO_BIN_EXE_texturecraft-cli").into())
}
#[test]
fn cli_binary_prefers_relocated_runner_path() {
let relocated = OsString::from("relocated archive/texturecraft-cli");
assert_eq!(cli_binary_path(Some(relocated.clone())), relocated);
}
#[test]
fn cli_binary_defaults_to_cargo_path() {
assert_eq!(cli_binary_path(None), OsString::from(env!("CARGO_BIN_EXE_texturecraft-cli")));
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap()
Command::new(cli_binary()).args(args).output().unwrap()
}
fn ok(args: &[&str]) -> String {
@@ -101,7 +123,7 @@ fn info_on_a_mesh_reports_uvs() {
fn serve_takes_the_automation_root_spelling_too() {
use std::io::Write as _;
let d = tmp("automation-root");
let mut child = Command::new(env!("CARGO_BIN_EXE_texturecraft-cli"))
let mut child = Command::new(cli_binary())
.args(["serve", "--automation-write-root", p(&d)])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
+25 -2
View File
@@ -26,6 +26,30 @@ impl CageShell {
/// The cage of `request`'s texture set, from the same ray starts the bake uses
pub fn new(request: &BakeRequest) -> Result<CageShell, BakeError> {
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
Self::build(request, ray_frame, || {
// Each scan drops other materials' edges before the next scan starts
let wire_edges = request.mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
let missing_seam_edges = request.mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
(wire_edges, missing_seam_edges)
})
}
/// Build a cage using edges already scanned for every material of the low mesh
pub fn new_with_edges(request: &BakeRequest, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result<CageShell, BakeError> {
let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?;
Self::build(request, ray_frame, || {
(
wire_edges.get(request.material).into_iter().flatten().copied().collect(),
missing_seam_edges.get(request.material).into_iter().flatten().copied().collect(),
)
})
}
fn build(
request: &BakeRequest,
ray_frame: RayFrame,
edge_sets: impl FnOnce() -> (HashSet<(u32, u32)>, HashSet<(u32, u32)>),
) -> Result<CageShell, BakeError> {
let (frame, mesh) = (&ray_frame, request.mesh);
let triangles: Vec<usize> = mesh.triangles_of(request.material).collect();
let (positions, starts): (Vec<Vec3>, Vec<RayStart>) = triangles
@@ -38,8 +62,7 @@ impl CageShell {
})
.unzip();
let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
let missing_seam_edges: HashSet<(u32, u32)> = mesh.missing_seam_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect();
let (wire_edges, missing_seam_edges) = edge_sets();
let (mut edge_corners, mut seam_corners) = (HashMap::new(), HashMap::new());
for (triangle_index, &triangle) in triangles.iter().enumerate() {
let Some(vertices) = mesh.tri(triangle) else { continue };
+39 -1
View File
@@ -136,7 +136,13 @@ fn the_cage_lists_its_hard_edges_without_a_uv_seam() {
cage_paint: None,
tiles: (1, 1),
};
CageShell::new(&request).unwrap()
let shell = CageShell::new(&request).unwrap();
let shared = CageShell::new_with_edges(&request, &low.wire_edges(), &low.missing_seam_edges()).unwrap();
assert_eq!(shared.positions, shell.positions);
assert_eq!(shared.corners(0.1), shell.corners(0.1));
assert_eq!(shared.edges, shell.edges);
assert_eq!(shared.missing_seams, shell.missing_seams);
shell
};
let smooth = quad_with_diagonal_normal(Vec3::Z);
@@ -152,3 +158,35 @@ fn the_cage_lists_its_hard_edges_without_a_uv_seam() {
assert_eq!(ends, diagonal, "the line runs along the hard diagonal");
}
}
#[test]
fn shared_edges_select_the_requested_material() {
let mut mesh = primitives::cube(1.0);
mesh.append(&primitives::cube(1.0));
let bvh = Bvh::new(&mesh);
let bake_settings = settings(16, &[BakedMap::Normal]);
let wire_edges = mesh.wire_edges();
let missing_seam_edges = mesh.missing_seam_edges();
for material in 0..mesh.materials.len() {
let request = BakeRequest {
low_base_color: &[],
mesh: &mesh,
bvh: &bvh,
material,
settings: &bake_settings,
high: None,
cage: None,
skew: None,
cage_paint: None,
tiles: (1, 1),
};
let direct = CageShell::new(&request).unwrap();
let shared = CageShell::new_with_edges(&request, &wire_edges, &missing_seam_edges).unwrap();
assert_eq!(shared.positions, direct.positions);
assert_eq!(shared.starts, direct.starts);
assert_eq!(shared.edges, direct.edges);
assert_eq!(shared.missing_seams, direct.missing_seams);
}
}
+113 -43
View File
@@ -10,10 +10,12 @@ use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_core::{BakedMap, Channel, EffectKind, Layer, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::held_fields::HeldFields;
use crate::image_identity::ImageIdentity;
use crate::store::{BakedMaps, ImageStore, PixelStore};
/// Default byte budget of a [`BelowCache`], per nesting level it holds (see
@@ -40,11 +42,28 @@ pub struct BelowCache {
/// Tiles of the whole pass a caller splits into several composites (0: each composite is a
/// pass). A pass larger than the cache records only what fits.
pub pass: usize,
/// Tiles the caller composites next in this pass, after those of the coming composite (empty: none, or a pass that is one
/// composite). A stack with neighbourhood filters then filters the coming tiles and these at once and keeps the result for
/// the composites that follow, instead of filtering each small chunk's surroundings again.
pub ahead: Vec<(u32, u32)>,
pub(crate) held: Option<HeldFields>,
}
impl Default for BelowCache {
fn default() -> Self {
BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), clock: 0, bytes: 0, budget: BELOW_BUDGET, levels: 1, pass: 0 }
BelowCache {
hot: None,
key: None,
tiles: HashMap::new(),
order: VecDeque::new(),
clock: 0,
bytes: 0,
budget: BELOW_BUDGET,
levels: 1,
pass: 0,
ahead: Vec::new(),
held: None,
}
}
}
@@ -78,48 +97,82 @@ pub struct StackKey {
layers: Vec<Layer>,
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, usize)>,
images: Vec<(String, ImageIdentity)>,
}
impl StackKey {
/// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects.
pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option<StackKey> {
StackKey::of_tree(project, pixels, baked, images, ts, roots.to_vec(), &project.render_tree(roots))
/// The key of `roots` (layers of a texture set, bottom → top) and their effects.
pub fn new(
project: &Project,
pixels: &PixelStore,
baked: &BakedMaps,
images: &ImageStore,
texture_set_index: usize,
roots: &[LayerId],
) -> Option<StackKey> {
StackKey::of_tree(project, pixels, baked, images, texture_set_index, roots.to_vec(), &project.render_tree(roots))
}
/// The key of the layers in `tree` (and their effects), drawn as `roots` arrange them.
/// The key of the layers in `render_tree` (and their effects), drawn as `roots` arrange them.
fn of_tree(
project: &Project,
pixels: &PixelStore,
baked: &BakedMaps,
images: &ImageStore,
ts: usize,
texture_set_index: usize,
roots: Vec<LayerId>,
tree: &BTreeSet<LayerId>,
render_tree: &BTreeSet<LayerId>,
) -> Option<StackKey> {
let mut set = project.texture_set(ts).ok()?.clone();
let mut set = project.texture_set(texture_set_index).ok()?.clone();
set.name.clear();
set.description.clear();
set.stack.clear();
set.bake = Default::default();
let effects: BTreeSet<LayerId> = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
let pixels = tree
let effect_ids: BTreeSet<LayerId> = render_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
let pixel_handles = render_tree
.iter()
.chain(&effects)
.chain(&effect_ids)
.flat_map(|id| {
let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone()))));
layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone()))))
let layer_channels =
Channel::ALL.into_iter().filter_map(move |channel| pixels.layer(*id, channel).map(|image| (*id, Some(channel), Shared(image.clone()))));
layer_channels.chain(pixels.masks.get(id).map(|image| (*id, None, Shared(image.clone()))))
})
.collect();
let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect();
images.sort();
let mut referenced_images = BTreeSet::new();
if !images.is_empty() {
let mut record_image_reference = |source: &Source| {
if let Source::Image { name, .. } = source
&& let Some((name, _)) = images.get_key_value(name)
{
referenced_images.insert(name);
}
};
for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) {
if let LayerKind::Fill(fill) = &layer.kind {
fill.sources.values().for_each(&mut record_image_reference);
}
for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) {
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
_ => {}
}
}
}
}
let image_identities =
referenced_images.into_iter().filter_map(|name| images.get(name).map(|image| (name.clone(), ImageIdentity::new(image)))).collect();
Some(StackKey {
set,
roots,
layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
pixels,
baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()),
images,
layers: render_tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
pixels: pixel_handles,
baked: (baked.resolution, baked.maps.iter().map(|(map, data)| (*map, Arc::as_ptr(data) as usize)).collect()),
images: image_identities,
})
}
}
@@ -173,23 +226,30 @@ impl BelowCache {
pub fn clear(&mut self) {
let tiles = std::mem::take(&mut self.tiles);
// Freeing a full cache (up to the byte budget in small bands) can take most of a
// second: a thread does it so the frame that switched the hot layer doesn't stall.
// Native builds free cached bands off-thread to avoid a frame stall
#[cfg(not(target_arch = "wasm32"))]
if !tiles.is_empty() {
let _ = std::thread::Builder::new().name("texturecraft-free".into()).spawn(move || drop(tiles));
}
#[cfg(target_arch = "wasm32")]
drop(tiles);
self.order.clear();
self.bytes = 0;
self.key = None;
self.held = None;
}
pub fn bytes(&self) -> usize {
self.bytes
}
/// Whether neighbourhood-filter fields are kept for the composites that follow (see [`BelowCache::ahead`]).
pub fn holds_fields(&self) -> bool {
self.held.is_some()
}
/// The byte limit: the budget for the top level and as much again for a hot layer nested in
/// folders (each tile then holds the stack at two or more levels).
pub fn limit(&self) -> usize {
@@ -256,43 +316,53 @@ impl BelowCache {
/// live stroke). Empties the cache when what the cached part reads changed.
pub(crate) fn prepare(&mut self, inp: &Inputs) -> Option<Vec<Level>> {
let hot = self.hot?;
let p = inp.project;
let set = p.texture_set(inp.ts).ok()?;
// Anchor readers depend on the stack below them.
if p.render_tree(&set.stack).iter().any(|id| p.layers.get(id).is_some_and(Layer::reads_anchor)) {
let project = inp.project;
let set = project.texture_set(inp.ts).ok()?;
// Anchor readers depend on the stack below them
if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) {
return None;
}
let levels = path(p, &set.stack, hot)?;
let rest: Vec<LayerId> = levels.iter().flat_map(|l| l.below.iter().chain(&l.above)).copied().collect();
if rest.is_empty() && levels.len() == 1 {
let levels = path(project, &set.stack, hot)?;
let off_path_roots: Vec<LayerId> = levels.iter().flat_map(|level| level.below.iter().chain(&level.above)).copied().collect();
if off_path_roots.is_empty() && levels.len() == 1 {
return None;
}
let mut tree = p.render_tree(&rest);
// Folders holding the hot layer (and the folders their instances draw) count with their
// own state only, not their children.
for l in levels.iter().take(levels.len() - 1) {
let mut id = Some(l.at);
let mut cached_tree = project.render_tree(&off_path_roots);
// Cache containing folders by state, without their children
for level in levels.iter().take(levels.len() - 1) {
let mut id = Some(level.at);
for _ in 0..=MAX_DEPTH {
let Some(i) = id.filter(|i| tree.insert(*i)) else { break };
id = p.layers.get(&i).and_then(Layer::instance_source);
let Some(instance_id) = id.filter(|instance_id| cached_tree.insert(*instance_id)) else { break };
id = project.layers.get(&instance_id).and_then(Layer::instance_source);
}
}
if tree.contains(&hot) {
// Repeated hot instances cannot share the off-path cache
if cached_tree.contains(&hot) {
return None;
}
if let Some(pv) = inp.preview {
let (PaintTarget::Layer(t) | PaintTarget::Mask(t)) = pv.target;
if tree.contains(&t) || tree.iter().filter_map(|id| p.layers.get(id)).flat_map(effect_ids).any(|e| e == t) {
if let Some(preview) = inp.preview {
let (PaintTarget::Layer(target) | PaintTarget::Mask(target)) = preview.target;
if cached_tree.contains(&target)
|| cached_tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).any(|effect_id| effect_id == target)
{
return None;
}
}
let roots = set.stack.iter().chain(levels.iter().map(|l| &l.at)).copied().collect();
let key = StackKey::of_tree(p, inp.pixels, inp.baked, inp.images, inp.ts, roots, &tree)?;
let roots = set.stack.iter().chain(levels.iter().map(|level| &level.at)).copied().collect();
let key = StackKey::of_tree(project, inp.pixels, inp.baked, inp.images, inp.ts, roots, &cached_tree)?;
self.levels = levels.len();
if self.key.as_ref() != Some(&key) {
self.clear();
self.key = Some(key);
}
Some(levels)
}
}
+40 -10
View File
@@ -125,8 +125,9 @@ fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes:
sizes
};
// One layout per curvature map, with the most recently used map at the end
cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature)));
// Keep distinct layouts: thumbnails and the viewport alternate on the same bake.
// Replacing only this variant prevents them from repeatedly rebuilding each other.
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()));
trim_cache(&mut cache, CACHE_BYTES);
@@ -338,6 +339,7 @@ mod tests {
#[test]
fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() {
let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect();
let scales = BlockScales::default();
let key = ((4, 4), (4, 4), (4, 4));
@@ -408,18 +410,46 @@ mod tests {
}
}
// Cache lifecycle tests must not evict each other's entries in parallel.
static CACHE_TESTS: Mutex<()> = Mutex::new(());
#[test]
fn a_new_layout_replaces_the_sizes_of_the_old_one() {
fn alternating_layouts_reuse_their_cached_sizes() {
let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let curvature = Arc::new(vec![0.5; 16]);
let scales = BlockScales::default();
let entries_for_curvature = || {
let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count()
};
let viewport_key = ((4, 4), (4, 4), (4, 4));
let thumbnail_key = ((4, 4), (4, 4), (2, 2));
let viewport = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() });
let thumbnail = store(&curvature, thumbnail_key, &scales, CurvatureSizes { levels: Vec::new() });
store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() });
store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() });
assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached");
assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "a thumbnail must not evict the viewport layout");
assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "both layouts stay reusable");
let mut set = texturecraft_core::TextureSet::new("Tiles", 0, 4);
set.uv_tiles = vec![1001, 1002];
set.tile_resolutions.insert(1002, 2);
let scaled = set.block_scales();
assert_ne!(scaled, scales);
assert!(cached(&curvature, viewport_key, &scaled).is_none(), "different tile scales cannot read the unscaled result");
let scaled_sizes = store(&curvature, viewport_key, &scaled, CurvatureSizes { levels: Vec::new() });
assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scaled).unwrap(), &scaled_sizes));
assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &viewport), "scale variants also coexist");
let replacement = store(&curvature, viewport_key, &scales, CurvatureSizes { levels: Vec::new() });
assert!(Arc::ptr_eq(&cached(&curvature, viewport_key, &scales).unwrap(), &replacement));
assert!(Arc::ptr_eq(&cached(&curvature, thumbnail_key, &scales).unwrap(), &thumbnail), "updating one layout keeps the other");
}
#[test]
fn layout_variants_obey_the_entry_limit() {
let _guard = CACHE_TESTS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let curvature = Arc::new(vec![0.5; 16]);
let scales = BlockScales::default();
let key = |size| ((4, 4), (4, 4), (size, size));
for size in 1..=CACHE_MAPS as u32 + 1 {
store(&curvature, key(size), &scales, CurvatureSizes { levels: Vec::new() });
}
assert!(cached(&curvature, key(1), &scales).is_none(), "layout variants cannot grow without bound");
assert!(cached(&curvature, key(CACHE_MAPS as u32 + 1), &scales).is_some(), "the newest layout stays cached");
}
#[test]
+276 -109
View File
@@ -18,8 +18,9 @@ use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
use crate::below::{Band, BelowCache, Level};
use crate::below::{Band, BelowCache, Level, StackKey};
use crate::curvature_sizes::CurvatureSizes;
use crate::held_fields::HeldFields;
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
@@ -434,15 +435,29 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3
/// the region it is computed in, so tiles composited in any grouping agree exactly.
const FIX: f64 = (1u64 << 24) as f64;
/// Texels one parallel task of a neighbourhood filter handles at least. Compositing in frame slices filters regions of a few tiles: split per texel,
/// handing that little work to every thread costs far more than the work itself. Each texel is computed on its own, so the split does not change results.
const MIN_PARALLEL_TEXELS: usize = 1 << 14;
/// How many lines of `length` texels make a parallel task of at least [`MIN_PARALLEL_TEXELS`].
fn lines_per_task(length: usize) -> usize {
(MIN_PARALLEL_TEXELS / length.max(1)).max(1)
}
/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel.
pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) {
let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
let mut fixed: Vec<i64> = data.par_iter().map(to_fixed).collect();
// Bound samples before fixed-point accumulation
const MAX_INPUT_MAGNITUDE: f32 = 1e6;
let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-MAX_INPUT_MAGNITUDE, MAX_INPUT_MAGNITUDE)) * FIX).round() as i64 } else { 0 };
let mut fixed: Vec<i64> = data.par_iter().with_min_len(MIN_PARALLEL_TEXELS).map(to_fixed).collect();
blur_rows(&mut fixed, width, radius);
let mut columns = transpose(&fixed, width, height);
blur_rows(&mut columns, height, radius);
data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32);
transpose_into(&columns, height, width, &mut fixed);
data.par_iter_mut().with_min_len(MIN_PARALLEL_TEXELS).zip(fixed).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32);
}
/// The box blurs `blur` runs along each axis
@@ -453,11 +468,12 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) {
if w == 0 {
return;
}
data.par_chunks_mut(w).for_each(|row| {
let mut tmp = vec![0i64; row.len()];
data.par_chunks_mut(w).with_min_len(lines_per_task(w)).for_each(|row| {
let mut scratch = vec![0i64; row.len()];
for _ in 0..BLUR_BOX_PASSES {
box_line(row, &mut tmp, r);
row.copy_from_slice(&tmp);
box_line(row, &mut scratch, r);
row.copy_from_slice(&scratch);
}
});
}
@@ -465,7 +481,8 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) {
/// One box blur of radius `r` of a line (texels past the ends count as 0).
fn box_line(src: &[i64], dst: &mut [i64], r: usize) {
let n = (2 * r + 1) as i64;
// Rounded division of a window sum.
// Rounded division of a window sum
let avg = |acc: i64| (2 * acc + n).div_euclid(2 * n);
let mut acc: i64 = src.iter().take(r + 1).sum();
for (i, d) in dst.iter_mut().enumerate() {
@@ -480,14 +497,18 @@ fn box_line(src: &[i64], dst: &mut [i64], r: usize) {
/// `src` (`w × h`, row-major) transposed to `h × w`.
fn transpose(src: &[i64], w: usize, h: usize) -> Vec<i64> {
let mut out = vec![0i64; src.len()];
transpose_into(src, w, h, &mut out);
out
}
fn transpose_into(src: &[i64], w: usize, h: usize, out: &mut [i64]) {
if h > 0 {
out.par_chunks_mut(h).enumerate().for_each(|(x, col)| {
out.par_chunks_mut(h).with_min_len(lines_per_task(h)).enumerate().for_each(|(x, col)| {
for (y, d) in col.iter_mut().enumerate() {
*d = src.get(y * w + x).copied().unwrap_or(0);
}
});
}
out
}
/// Covered texels of tile (tx, ty): (x, y, offset inside the tile).
@@ -607,9 +628,12 @@ fn filter_region(
(rx0, ry0, w, h): (u32, u32, u32, u32),
start: Option<(usize, &Field)>,
) -> Option<Field> {
// Tiny coverage sums make normalization unstable
const MIN_FILTER_WEIGHT: f32 = 1e-6;
let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height));
let comps = match job {
let component_count = match job {
Job::Mask(_) => 1,
Job::Content(_) => 4,
};
@@ -620,7 +644,7 @@ fn filter_region(
let parts: Vec<Vec<(u32, u32, [f32; 4])>> = region_tiles
.par_iter()
.map(|&(tx, ty)| {
let full = anchor_plan(inp, id, channels, tx, ty, Some(below));
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));
let mut mask = None;
let mut nodes = Vec::new();
@@ -634,22 +658,23 @@ fn filter_region(
}
Job::Content(channel) => {
nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below));
if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) {
chan.effects.truncate(index);
chan.start = start;
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)
.map(|(x, y, offset)| {
let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset));
if !full.is_empty() {
texel.anchors_below(&full, id);
if !anchor_nodes.is_empty() {
texel.anchors_below(&anchor_nodes, id);
}
let value = match (&mask, nodes.first()) {
(Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0],
(None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) {
Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov],
(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],
None => [0.0; 4],
},
(None, None) => [0.0; 4],
@@ -662,64 +687,77 @@ fn filter_region(
// Scatter into the region, a row of tiles at a time (the region is tile aligned)
let texel_count = (w * h) as usize;
let mut orig = vec![0.0f32; texel_count * comps];
let mut cover = vec![0.0f32; texel_count];
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;
orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| {
for &(x, y, value) in row.iter().flatten() {
let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize;
if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) {
*covered = 1.0;
pixel.copy_from_slice(&value[..comps]);
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]);
}
}
}
});
},
);
// High pass centers on the channel's mid value (0 for signed channels like height)
let mid = match job {
// Release scattered texels 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 {
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 res = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
let scaled_radius = neighbourhood_filters(effects, res)
let sampling_resolution = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
let scaled_radius = neighbourhood_filters(effects, sampling_resolution)
.find(|filter| filter.0 == index)
.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32);
if !is_box_blur(op) {
return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity);
return gather(op, &original_values, &coverage, component_count, (rx0, ry0, w, h), scaled_radius as f32, sampling_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 = cover.clone();
let mut weights = coverage.clone();
blur(&mut weights, width, height, blur_radius);
let mut data = orig.clone();
for component in 0..comps {
let mut sums: Vec<f32> = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect();
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(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| {
// Content is premultiplied, so the mid value is too (coverage itself is kept)
let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
if *weight > 1e-6
&& let Some(slot) = pixel.get_mut(component)
{
let (original, blurred) = (*slot, sum / weight);
let result = match op {
Op::Blur(Some(amount)) => original + amount * (original - blurred),
Op::HighPass if component < 3 => original - blurred + mid * cov,
// 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.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;
}
},
);
}
data
};
@@ -733,9 +771,9 @@ fn filter_region(
let mut data = filtered(first);
for &scale in rest {
let other = filtered(scale);
let row = w as usize * comps;
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(comps).zip(src.chunks(comps)).enumerate() {
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 {
target.copy_from_slice(source);
}
@@ -743,17 +781,20 @@ fn filter_region(
});
}
unpremultiply(&mut data, comps);
Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
unpremultiply(&mut data, component_count);
Some(Field { x0: rx0, y0: ry0, w, h, comps: component_count, data })
}
/// Clamp filtered masks to 0..1, and turn filtered content back into straight values.
fn unpremultiply(data: &mut [f32], comps: usize) {
data.par_chunks_mut(comps).for_each(|px| match px {
// Avoid amplifying rounding error near transparent texels
const MIN_COVERAGE: f32 = 1e-5;
data.par_chunks_mut(comps).with_min_len(MIN_PARALLEL_TEXELS).for_each(|px| match px {
[v] => *v = v.clamp(0.0, 1.0),
[r, g, b, cov] => {
*cov = cov.clamp(0.0, 1.0);
let inv = if *cov > 1e-5 { 1.0 / *cov } else { 0.0 };
let inv = if *cov > MIN_COVERAGE { 1.0 / *cov } else { 0.0 };
*r *= inv;
*g *= inv;
*b *= inv;
@@ -794,12 +835,14 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32
if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() {
continue;
}
for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) {
if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) {
out.insert(FieldKey::Content(id, *channel), filtered);
}
}
}
out
}
@@ -1661,7 +1704,7 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)])
}
/// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory).
const BLOCK: u32 = 16;
pub const BLOCK: u32 = 16;
/// [`composite_tiles`], serving everything but the hot layer from `below` where it can (and
/// filling it). Results are identical to [`composite_tiles`].
@@ -1670,9 +1713,10 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32,
if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) {
return;
}
let split = below.as_deref_mut().and_then(|b| b.prepare(inp));
// A pass over more tiles than the cache holds records only what fits: recording the rest
// would just evict it again. Tiles hold the stack per level plus a tape of varying size.
// Avoid caching tiles that would immediately evict each other
let levels = split.as_ref().map_or(1, Vec::len);
let estimate = TILE_AREA * levels * set.channel_list().iter().map(|c| c.components()).sum::<usize>() * std::mem::size_of::<f32>();
let tile_bytes = below.as_deref().and_then(BelowCache::tile_bytes).unwrap_or(estimate).max(1);
@@ -1681,14 +1725,66 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32,
for t in tiles {
blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t);
}
for block in blocks.values() {
let channels = set.channel_list();
let hot = split.as_deref().and_then(<[Level]>::last);
// A stroke preview is absent from StackKey, so it disables field retention
let retain_fields = below.is_some() && inp.preview.is_none() && has_neighbourhood(inp, &set.stack);
let key = if retain_fields { StackKey::new(inp.project, inp.pixels, inp.baked, inp.images, inp.ts, &set.stack).map(Arc::new) } else { None };
let size = (inp.gbuf.width, inp.gbuf.height);
// Release fields when a stroke or stack change disables retention
if key.is_none()
&& let Some(cache) = below.as_deref_mut()
{
cache.held = None;
}
for (block_index, block) in &blocks {
let uncached = |tile: &(u32, u32)| below.as_deref().zip(split.as_deref()).is_none_or(|(cache, _)| cache.tile(*tile).is_none());
let fresh: Vec<(u32, u32)> = block.iter().copied().filter(uncached).collect();
let held = below.as_deref().and_then(|cache| cache.held.as_ref()).filter(|held| {
key.as_ref().is_some_and(|key| **key == *held.key)
&& held.size == size
&& fresh.iter().all(|tile| held.stack_tiles.contains(tile))
&& block.iter().all(|tile| held.hot_tiles.contains(tile))
});
let ahead: Vec<(u32, u32)> = match (&key, below.as_deref()) {
(Some(_), Some(cache)) if held.is_none() => {
cache.ahead.iter().copied().filter(|tile| (tile.1 / BLOCK, tile.0 / BLOCK) == *block_index && !block.contains(tile)).collect()
}
_ => Vec::new(),
};
let fields: Arc<Fields> = match (held, &key) {
(Some(held), _) => held.fields.clone(),
(None, Some(key)) if !ahead.is_empty() => {
// Filter the current and following tiles as one run
let planned_tiles: Vec<(u32, u32)> = block.iter().chain(&ahead).copied().collect();
let uncached_planned_tiles: Vec<(u32, u32)> = planned_tiles.iter().copied().filter(uncached).collect();
let fields = Arc::new(block_fields(inp, &channels, &set.stack, hot, &uncached_planned_tiles, &planned_tiles));
let hot_tiles: std::collections::BTreeSet<(u32, u32)> = planned_tiles.iter().copied().collect();
let stack_tiles = if hot.is_some() && uncached_planned_tiles.len() < planned_tiles.len() {
uncached_planned_tiles.into_iter().collect()
} else {
hot_tiles.clone()
};
if let Some(cache) = below.as_deref_mut() {
cache.held = Some(HeldFields { key: key.clone(), size, stack_tiles, hot_tiles, fields: fields.clone() });
}
fields
}
_ => Arc::new(block_fields(inp, &channels, &set.stack, hot, &fresh, block)),
};
let quota = match below.as_deref() {
Some(_) if fits => usize::MAX,
Some(b) => b.limit().saturating_sub(b.bytes()) / tile_bytes,
None => 0,
};
let cached = below.as_deref().zip(split.as_deref());
let records = composite_block(inp, &set.stack, out, block, cached, quota);
let records = composite_block(inp, &set.stack, out, block, cached, quota, &fields);
if let Some(b) = below.as_deref_mut() {
for t in block {
b.touch(*t);
@@ -1698,6 +1794,35 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32,
}
}
}
// Release fields at the end of the pass
if let Some(cache) = below.filter(|cache| cache.ahead.is_empty()) {
cache.held = None;
}
}
/// Whether a layer drawn by `stack` has a neighbourhood filter in its mask or content effects.
fn has_neighbourhood(inp: &Inputs, stack: &[LayerId]) -> bool {
let working_width = inp.gbuf.width;
let mut order = Vec::new();
draw_order(inp.project, stack, 0, &mut order);
order.into_iter().any(|id| {
let masked = layer_mask(inp.project, id).is_some_and(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some());
masked || inp.project.content_layer(id).is_some_and(|layer| !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some())
})
}
/// The neighbourhood fields compositing `tiles` reads: those of every layer of `stack` over the tiles the cache lacks (`fresh`),
/// and off the path to the `hot` layer only there; the hot layer's over all of `tiles`.
fn block_fields(inp: &Inputs, channels: &[Channel], stack: &[LayerId], hot: Option<&Level>, fresh: &[(u32, u32)], tiles: &[(u32, u32)]) -> Fields {
match hot {
Some(hot) if fresh.len() < tiles.len() => {
let mut fields = fields_of(inp, channels, stack, fresh);
fields.extend(fields_of(inp, channels, &[hot.at], tiles));
fields
}
_ => fields_of(inp, channels, stack, tiles),
}
}
/// Rows of a tile composited as one parallel task.
@@ -1719,6 +1844,7 @@ fn composite_block(
tiles: &[(u32, u32)],
below: Option<(&BelowCache, &[Level])>,
quota: usize,
fields: &Fields,
) -> Vec<((u32, u32), Vec<Band>)> {
let channels: Vec<Channel> = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default();
let (w, h) = (out.resolution, out.height);
@@ -1726,20 +1852,12 @@ fn composite_block(
let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t));
let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect();
let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() };
// Off the path, layers are only evaluated on tiles the cache lacks.
let fields = match split.and_then(<[Level]>::last) {
Some(hot) if fresh.len() < tiles.len() => {
let mut fields = fields_of(inp, &channels, stack, &fresh);
fields.extend(fields_of(inp, &channels, &[hot.at], tiles));
fields
}
_ => fields_of(inp, &channels, stack, tiles),
};
let lanes: Vec<Lane> = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect();
let stride: usize = lanes.iter().map(|l| l.n).sum();
let nlev = split.map_or(0, <[Level]>::len);
let level_count = split.map_or(0, <[Level]>::len);
let defaults: Acc = Channel::ALL.map(Channel::default_value);
// Tiles split into bands of rows, so a handful of tiles still keeps every thread busy.
// Tiles split into bands of rows, so a handful of tiles still keeps every thread busy
let bands = TILE / BAND;
let tasks: Vec<((u32, u32), u32)> = tiles.iter().flat_map(|t| (0..bands).map(move |b| (*t, b))).collect();
let mut results: Vec<BandResult> = tasks
@@ -1747,20 +1865,20 @@ fn composite_block(
.map(|&((tx, ty), band)| {
let warm = cached((tx, ty)).and_then(|b| b.get(band as usize));
let record = warm.is_none() && recorded.contains(&(tx, ty));
let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some()));
let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() };
let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, fields, warm.is_some()));
let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(fields)) } else { Vec::new() };
let rows = (BAND * TILE) as usize;
let mut accs = vec![defaults; nlev];
let mut masks = vec![0.0f32; nlev];
let mut level_values = vec![defaults; level_count];
let mut masks = vec![0.0f32; level_count];
let mut tape = match warm {
Some(b) => Tape::Replay(b, 0),
None if record => Tape::Record(Vec::new()),
None => Tape::Off,
};
// The levels whose stack the band stores (its header): a level with nothing drawn
// before the path layer repeats the level above it.
// Empty lower stacks reuse the enclosing level instead of storing a duplicate
let stored: Vec<bool> = match (&levels, warm) {
(Some(_), Some(_)) => tape.take(nlev).iter().map(|v| *v > 0.0).collect(),
(Some(_), Some(_)) => tape.take(level_count).iter().map(|v| *v > 0.0).collect(),
(Some(levels), None) => levels.iter().map(|l| !l.below.is_empty()).collect(),
(None, _) => Vec::new(),
};
@@ -1769,7 +1887,7 @@ fn composite_block(
}
let slots = stored.iter().filter(|s| **s).count() * stride;
let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty));
let mut bufs: Vec<Vec<u16>> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect();
let mut channel_buffers: Vec<Vec<u16>> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect();
let mut anchors = Vec::new();
let mut any = false;
for ly in band * BAND..(band + 1) * BAND {
@@ -1782,20 +1900,20 @@ fn composite_block(
if x >= w {
break;
}
let gi = (y * w + x) as usize;
// Offset in the tile, and in this band.
let o = (ly * TILE + lx) as usize;
let ob = ((ly - band * BAND) * TILE + lx) as usize;
let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI);
let gbuffer_index = (y * w + x) as usize;
let tile_offset = (ly * TILE + lx) as usize;
let band_offset = ((ly - band * BAND) * TILE + lx) as usize;
let covered = inp.gbuf.tri.get(gbuffer_index).is_some_and(|t| *t != NO_TRI);
let mut acc = defaults;
if covered {
any = true;
let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o));
// Reuse one anchor buffer per band.
tex.anchors = std::mem::take(&mut anchors);
let mut texel = Texel::new(inp, x, y, tile_offset, stroke_at(preview_tile, tile_offset));
// Reuse one anchor buffer per band
texel.anchors = std::mem::take(&mut anchors);
match &levels {
Some(levels) => {
// The texel's stream starts with the stack at each level.
// The texel's stream starts with the stack at each level
let start = match &mut tape {
Tape::Record(t) => {
t.resize(t.len() + slots, 0.0);
@@ -1804,38 +1922,39 @@ fn composite_block(
_ => 0,
};
if warm.is_some() {
load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut accs);
load_levels(tape.take(slots), &lanes, stride, &stored, &defaults, &mut level_values);
}
acc = tex.eval_split(defaults, levels, &mut accs, &mut masks, warm.is_some(), &mut tape);
acc = texel.eval_split(defaults, levels, &mut level_values, &mut masks, warm.is_some(), &mut tape);
if let Tape::Record(t) = &mut tape
&& let Some(below) = t.get_mut(start..start + slots)
{
store_levels(below, &lanes, stride, &stored, &accs);
store_levels(below, &lanes, stride, &stored, &level_values);
}
}
None => {
tex.eval(&nodes, &mut acc);
texel.eval(&nodes, &mut acc);
}
}
anchors = tex.anchors;
anchors = texel.anchors;
anchors.clear();
}
for (l, buf) in lanes.iter().zip(&mut bufs) {
for (l, buf) in lanes.iter().zip(&mut channel_buffers) {
let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]);
for (k, x) in v.iter().take(l.n).enumerate() {
let enc = if l.signed { to_u16_signed(*x) } else { to_u16(*x) };
if let Some(slot) = buf.get_mut(ob * l.n + k) {
*slot = enc;
let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) };
if let Some(slot) = buf.get_mut(band_offset * l.n + k) {
*slot = encoded;
}
}
}
}
}
let cache = if let Tape::Record(t) = tape { Some(t) } else { None };
(bufs, cache, any)
(channel_buffers, cache, any)
})
.collect();
// Join the bands of each tile (in parallel; uncovered tiles are freed).
// Join the bands of each tile (in parallel; uncovered tiles are freed)
let joined: Vec<Joined> = results
.par_chunks(bands as usize)
.map(|parts| {
@@ -1861,7 +1980,8 @@ fn composite_block(
img.set_tile(tx, ty, d);
}
}
// Tiles without covered texels cost nothing to composite: not worth caching.
// Tiles without covered texels cost nothing to composite: not worth caching
if any && let Some(bands) = parts.iter_mut().map(|p| p.1.take()).collect::<Option<Vec<Band>>>() {
records.push(((tx, ty), bands));
}
@@ -2323,6 +2443,53 @@ mod tests {
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-4)
}
#[test]
fn retained_filter_buffers_release_after_the_last_tile() {
let mut fixture = fixture();
const RESOLUTION: u32 = 128;
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, RESOLUTION, RESOLUTION);
fixture.project.texture_sets[0] = TextureSet::new("Plane", 0, RESOLUTION);
let layer = fill_layer(&mut fixture.project, [0.4; 3], 0.5);
let mut mask = Mask::new(MaskBackground::White);
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 8.0 })));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let second_layer = fill_layer(&mut fixture.project, [0.2; 3], 0.7);
let mut second_mask = Mask::new(MaskBackground::White);
second_mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 4.0 })));
fixture.project.layer_mut(second_layer).unwrap().mask = Some(second_mask);
let images = ImageStore::default();
let input = Inputs {
project: &fixture.project,
ts: 0,
mesh: &fixture.mesh,
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: fixture.project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
};
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RESOLUTION);
let mut cache = BelowCache::default();
cache.ahead = vec![(1, 0), (0, 1), (1, 1)];
composite_tiles_cached(&input, &mut output, &[(0, 0)], Some(&mut cache));
let retained = cache.held.as_ref().expect("filter fields should be retained while tiles follow");
let field_bytes: usize = retained.fields.values().map(|field| field.data.capacity() * std::mem::size_of::<f32>()).sum();
let field_count = retained.fields.len();
let weak_fields = Arc::downgrade(&retained.fields);
assert_eq!(field_count, 2);
assert!(field_bytes > 0);
println!("retained fields: {field_count}, buffer capacity: {field_bytes} bytes");
cache.ahead.clear();
composite_tiles_cached(&input, &mut output, &[(1, 0)], Some(&mut cache));
assert!(weak_fields.upgrade().is_none(), "the last tile must release retained field buffers");
}
#[test]
fn histogram_samples_spread_over_every_column() {
assert_eq!(histogram_tiles(1024, 1024), all_tiles(1024, 1024), "small sets are read whole");
+24
View File
@@ -0,0 +1,24 @@
use std::collections::BTreeSet;
use std::sync::Arc;
use crate::below::StackKey;
use crate::eval::Fields;
/// Neighbourhood-filter fields kept between the composites of one pass.
pub(crate) struct HeldFields {
/// Everything the fields read.
pub key: Arc<StackKey>,
/// The working size they were built at.
pub size: (u32, u32),
/// The tiles every layer's fields hold.
pub stack_tiles: BTreeSet<(u32, u32)>,
/// The tiles the hot layer's fields hold (the same tiles when the stack was not split).
pub hot_tiles: BTreeSet<(u32, u32)>,
pub fields: Arc<Fields>,
}
impl std::fmt::Debug for HeldFields {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HeldFields").field("stack_tiles", &self.stack_tiles.len()).field("hot_tiles", &self.hot_tiles.len()).finish_non_exhaustive()
}
}
+19
View File
@@ -0,0 +1,19 @@
use std::sync::{Arc, Weak};
use crate::store::ImageRes;
/// Keeps an image's allocation identity stable without retaining pixels after resource removal.
#[derive(Debug)]
pub(crate) struct ImageIdentity(Weak<ImageRes>);
impl ImageIdentity {
pub(crate) fn new(image: &Arc<ImageRes>) -> Self {
Self(Arc::downgrade(image))
}
}
impl PartialEq for ImageIdentity {
fn eq(&self, other: &Self) -> bool {
self.0.ptr_eq(&other.0)
}
}
+4 -2
View File
@@ -13,6 +13,8 @@ mod curvature_size_level;
pub mod curvature_sizes;
pub mod display;
pub mod eval;
mod held_fields;
mod image_identity;
pub mod pattern;
pub mod store;
pub mod thumb;
@@ -20,8 +22,8 @@ pub mod thumb;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, tile_bytes};
pub use eval::{
Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer,
mask_at, mask_image, pad_tiles,
BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram,
flatten_layer, mask_at, mask_image, pad_tiles,
};
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+226
View File
@@ -573,3 +573,229 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
assert!(!check_cached(&f, 0, hot).is_empty());
}
}
/// Composite every tile in chunks of `chunk`, telling the cache the `ahead` tiles that follow each chunk, as a pass spread over frames does.
fn run_sliced(fixture: &Fixture, cache: &mut BelowCache, chunk: usize, ahead: usize) -> Composite {
let all = all_tiles(RES, RES);
let (images, baked) = (Default::default(), Default::default());
let mut out = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
for (index, tiles) in all.chunks(chunk).enumerate() {
let done = (index * chunk + tiles.len()).min(all.len());
cache.ahead = all.iter().skip(done).take(ahead).copied().collect();
composite_tiles_cached(&inputs(fixture, 0, &images, &baked), &mut out, tiles, Some(&mut *cache));
assert_eq!(cache.holds_fields(), !cache.ahead.is_empty(), "fields are kept exactly while tiles follow (chunk {chunk}, ahead {ahead})");
}
out
}
#[test]
fn filter_fields_kept_across_the_chunks_of_a_pass_composite_exactly() {
let mut fixture = fixture();
let top = heavy_stack(&mut fixture);
let blurred_fill = fixture.project.texture_sets[0].stack[1];
let expected = reference(&fixture, 0);
for hot in [None, Some(top), Some(blurred_fill)] {
// Exercise reuse within and recomputation beyond retained runs
for (chunk, ahead) in [(1, 1), (1, 5), (3, 4), (5, 16), (2, 0)] {
let mut cache = BelowCache::default();
cache.set_hot(hot);
assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a cold sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})");
// A warm hot-layer cache needs fewer fields
assert!(run_sliced(&fixture, &mut cache, chunk, ahead) == expected, "a warm sliced pass differs (hot {hot:?}, chunk {chunk}, ahead {ahead})");
}
}
// Evicted tiles need fields from every layer again
let mut full = BelowCache::default();
full.set_hot(Some(top));
run(&fixture, 0, &all_tiles(RES, RES), Some(&mut full));
let tile_bytes = full.tile_bytes().unwrap();
for tiles_held in [2, 5, 9] {
for (chunk, ahead) in [(1, 5), (3, 4), (2, 16)] {
let mut cache = BelowCache::default();
cache.budget = tiles_held * tile_bytes;
cache.set_hot(Some(top));
for pass in 0..3 {
assert!(
run_sliced(&fixture, &mut cache, chunk, ahead) == expected,
"pass {pass} differs with {tiles_held} cached tiles (chunk {chunk}, ahead {ahead})"
);
}
}
}
}
#[test]
fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() {
let mut fixture = fixture();
let top = heavy_stack(&mut fixture);
let all = all_tiles(RES, RES);
let (first, rest) = all.split_at(3);
let mut cache = BelowCache::default();
cache.set_hot(Some(top));
// Keep fields for the remaining tiles
cache.ahead = rest.to_vec();
let mut out = run(&fixture, 0, first, Some(&mut cache));
assert!(cache.holds_fields());
// Changing the hot mask must invalidate the retained fields
let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap();
mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 });
let (images, baked) = (Default::default(), Default::default());
cache.ahead = Vec::new();
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache));
assert!(out == reference(&fixture, 0), "fields kept from before an edit were used after it");
assert!(!cache.holds_fields());
// A live stroke must bypass retained fields
let preview = stroke(top);
cache.ahead = rest.to_vec();
let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview));
assert!(!cache.holds_fields());
let mut inp = inputs(&fixture, 0, &images, &baked);
inp.preview = Some(&preview);
composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache));
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a live stroke over a sliced pass differs");
}
/// Kept fields hold a layer off the hot path only over the tiles the cache lacked when they were built. A tile the cache drops
/// while they are in use needs that layer's fields again.
#[test]
fn tiles_the_cache_drops_during_a_kept_run_are_filtered_again() {
const SIZE: u32 = 512;
let mesh = primitives::sphere(1.0, 32, 16);
let gbuf = UvGBuffer::new(&mesh, 0, SIZE, SIZE);
let mut project = Project::new("t", "builtin:sphere");
project.texture_sets.push(TextureSet::new("A", 0, SIZE));
let mut fixture = Fixture { project, mesh, gbuf, pixels: PixelStore::default() };
add(&mut fixture, 0, fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9))]), None);
// Pattern detail exposes any missing blur field
let mut blurred = Mask::new(MaskBackground::Black);
blurred.effects.push(effect(&mut fixture, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
blurred.effects.push(effect(&mut fixture, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
add(&mut fixture, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(blurred));
// Keep the blurred layer visible under the hot layer
let hot = add(&mut fixture, 0, LayerKind::Paint, None);
paint_rect_at(&mut fixture, hot, SIZE, (10, 10), (40, 40), 0.2);
let mut all = all_tiles(SIZE, SIZE);
all.sort_by_key(|&(x, y)| (y, x));
let channels = fixture.project.texture_sets[0].channel_list();
let (images, baked) = (Default::default(), Default::default());
let mut expected = Composite::new(&channels, SIZE);
composite_tiles(&inputs(&fixture, 0, &images, &baked), &mut expected, &all);
// Prime the cache with only the two bottom rows
let rows = (SIZE / TILE) as usize;
let (above, bottom) = all.split_at(all.len() - 2 * rows);
let mut cache = BelowCache::default();
cache.set_hot(Some(hot));
let mut out = Composite::new(&channels, SIZE);
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, bottom, Some(&mut cache));
assert_eq!(cache.len(), bottom.len());
cache.budget = cache.bytes();
// Cache eviction during the run must rebuild missing lower-layer fields
let mut out = Composite::new(&channels, SIZE);
for (index, tile) in all.iter().enumerate() {
cache.ahead = all.iter().skip(index + 1).copied().collect();
composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &[*tile], Some(&mut cache));
if index == 0 {
assert!(cache.holds_fields());
}
}
assert!(above.len() > bottom.len());
assert!(out == expected, "a tile dropped from the cache was composited with fields that lack the layers off the hot path");
}
/// A stroke that starts while fields are kept must not leave them allocated for as long as it lasts, even though tiles still follow.
#[test]
fn a_live_stroke_releases_the_fields_kept_before_it_started() {
let mut fixture = fixture();
let top = heavy_stack(&mut fixture);
let all = all_tiles(RES, RES);
let (first, rest) = all.split_at(3);
let mut cache = BelowCache::default();
cache.set_hot(Some(top));
cache.ahead = rest.to_vec();
run(&fixture, 0, first, Some(&mut cache));
assert!(cache.holds_fields());
// A stroke must release fields even while tiles remain
let preview = stroke(top);
let mut live = run_with(&fixture, 0, first, Some(&mut cache), Some(&preview));
assert!(!cache.holds_fields(), "fields kept before the stroke stay allocated while it lasts");
let (images, baked) = (Default::default(), Default::default());
let mut inp = inputs(&fixture, 0, &images, &baked);
inp.preview = Some(&preview);
composite_tiles_cached(&inp, &mut live, rest, Some(&mut cache));
assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs");
}
#[test]
fn cached_stack_tracks_referenced_images_only() {
use std::sync::Arc;
use texturecraft_compose::{ImageRes, ImageStore};
let mut fixture = fixture();
let hot_layer = heavy_stack(&mut fixture);
let bottom_layer = fixture.project.texture_sets[0].stack[0];
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") };
fill.sources.insert(Channel::Roughness, Source::Image { name: "used".into(), normal_format: Default::default() });
let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let mut images = ImageStore::default();
let baked = Default::default();
let tiles = all_tiles(RES, RES);
let mut cache = BelowCache::default();
cache.set_hot(Some(hot_layer));
let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
let mut previous_image = None;
for stage in ["cold", "resolve", "unused1", "unused2", "unused3", "replace", "remove"] {
match stage {
"resolve" => {
let image = image_with_value(1.0);
previous_image = Some(Arc::downgrade(&image));
images.insert("used".into(), image);
}
"replace" => {
let replacement = image_with_value(0.4);
let replacement_weak = Arc::downgrade(&replacement);
images.insert("used".into(), replacement);
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain replaced image pixels");
previous_image = Some(replacement_weak);
}
"remove" => {
images.remove("used");
assert!(previous_image.as_ref().is_some_and(|old| old.upgrade().is_none()), "cached key must not retain removed image pixels");
}
"cold" => {}
_ => {
images.insert(stage.into(), image_with_value(0.5));
}
}
fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]);
let input = inputs(&fixture, 0, &images, &baked);
composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache));
assert!(!cache.is_empty(), "{stage}: first tile should be cached");
let retained = cache.len() - 1;
composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache));
assert_eq!(retained, if stage.starts_with("unused") { tiles.len() - 1 } else { 0 }, "{stage}");
let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES);
composite_tiles(&input, &mut expected, &tiles);
assert!(output == expected, "{stage}");
}
}
@@ -23,6 +23,16 @@ impl BakeCageInputs {
CageShell::new(&self.request())
}
/// Whether this set uses the session's shared low mesh
pub fn uses_mesh(&self, mesh: &Arc<Mesh>) -> bool {
Arc::ptr_eq(&self.mesh, mesh)
}
/// Build a cage from edges shared across sets using the same low mesh
pub fn cage_shell_with_edges(&self, wire_edges: &[Vec<(u32, u32)>], missing_seam_edges: &[Vec<(u32, u32)>]) -> Result<CageShell, BakeError> {
CageShell::new_with_edges(&self.request(), wire_edges, missing_seam_edges)
}
/// Where each high-poly vertex sits relative to the bake's transfer rays
pub fn high_poly_reach(&self) -> Result<HighPolyReach, BakeError> {
HighPolyReach::new(&self.request())
+1
View File
@@ -83,6 +83,7 @@ fn triangles_by_block(mesh: &Mesh, material: usize, grid: (u32, u32), baked_bloc
// Every block the triangle's UV bounds touch, so a triangle across a border counts in both
let (uv_min, uv_max) = uvs.iter().fold((Vec2::INFINITY, Vec2::NEG_INFINITY), |(uv_min, uv_max), uv| (uv_min.min(*uv), uv_max.max(*uv)));
// Capped at the grid: a stray huge UV must not walk billions of blocks
let columns = uv_min.x.floor().max(0.0) as u32..=((uv_max.x.ceil() as u32).saturating_sub(1)).min(grid.0 - 1);
let rows = uv_min.y.floor().max(0.0) as u32..=((uv_max.y.ceil() as u32).saturating_sub(1)).min(grid.1 - 1);
+62 -4
View File
@@ -195,16 +195,26 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Blen
}
/// A color: `[r, g, b]` (linear 0..1) or `"#rrggbb"` (sRGB hex, converted to linear).
pub(crate) fn color_param(p: &Value, key: &str) -> Option<[f32; 3]> {
color_of(p.get(key)?)
pub(crate) fn color_param(cmd: &str, p: &Value, key: &str) -> Result<Option<[f32; 3]>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))),
}
}
/// A color value (see [`color_param`]).
pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> {
match v {
Value::Array(a) if a.len() >= 3 => {
let v: Vec<f32> = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None }
let mut out = [0.0f32; 3];
for (i, x) in a.iter().take(3).enumerate() {
let f = x.as_f64()? as f32;
if !f.is_finite() {
return None;
}
out[i] = f;
}
Some(out)
}
Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()),
Value::String(s) => {
@@ -218,3 +228,51 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> {
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn color_param_accepts_valid_forms() {
let p = json!({
"hex": "#336699",
"hex_plain": "336699",
"rgb": [0.2, 0.4, 0.6],
"grey": 0.5,
});
assert!(color_param("cmd", &p, "hex").unwrap().is_some());
assert!(color_param("cmd", &p, "hex_plain").unwrap().is_some());
assert_eq!(color_param("cmd", &p, "rgb").unwrap(), Some([0.2, 0.4, 0.6]));
assert_eq!(color_param("cmd", &p, "grey").unwrap(), Some([0.5, 0.5, 0.5]));
assert_eq!(color_param("cmd", &p, "missing").unwrap(), None);
assert_eq!(color_param("cmd", &json!({"c": null}), "c").unwrap(), None);
}
#[test]
fn color_param_rejects_invalid_forms() {
let bad_cases = [
("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"),
];
for (input, expected_err) in bad_cases {
let p = json!({ "color": input });
let err = color_param("test.cmd", &p, "color").unwrap_err();
assert_eq!(err.to_string(), format!("`test.cmd`: {expected_err}"));
}
let bad_array = json!({ "color": ["a", "b", "c"] });
assert!(color_param("test.cmd", &bad_array, "color").is_err());
let short_array = json!({ "color": [0.5, 0.5] });
assert!(color_param("test.cmd", &short_array, "color").is_err());
let overflow_array = json!({ "color": [1e40, 0.0, 0.0] });
assert!(color_param("test.cmd", &overflow_array, "color").is_err());
let overflow_scalar = json!({ "color": 1e40 });
assert!(color_param("test.cmd", &overflow_scalar, "color").is_err());
}
}
+3 -4
View File
@@ -253,8 +253,8 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> {
}
Filter::ColorBalance { shadows, midtones, highlights } => {
for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] {
if p.get(key).is_some() {
let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?;
if let Some(val) = p.get(key).filter(|v| !v.is_null()) {
let v = color_of(val).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?;
*slot = v.map(|x| x.clamp(-1.0, 1.0));
}
}
@@ -305,8 +305,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> {
}
Filter::ReplaceColor { from, to, tolerance, softness } => {
for (key, slot) in [("from", from), ("to", to)] {
if p.get(key).is_some() {
let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")")))?;
if let Some(v) = color_param(cmd, p, key)? {
*slot = v.map(|x| x.clamp(0.0, 1.0));
}
}
+10 -6
View File
@@ -71,9 +71,9 @@ fn add_paint(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A uniform fill from the `color`, `roughness`, `metallic`, `height` and `opacity` params.
pub(crate) fn fill_from(p: &Value) -> Fill {
pub(crate) fn fill_from(cmd: &str, p: &Value) -> Result<Fill> {
let mut fill = Fill::default();
if let Some(c) = color_param(p, "color") {
if let Some(c) = color_param(cmd, p, "color")? {
fill.sources.insert(Channel::BaseColor, Source::Uniform(c));
}
for (key, ch) in [("roughness", Channel::Roughness), ("metallic", Channel::Metallic), ("height", Channel::Height), ("opacity", Channel::Opacity)] {
@@ -81,13 +81,13 @@ pub(crate) fn fill_from(p: &Value) -> Fill {
fill.sources.insert(ch, Source::Uniform([v; 3]));
}
}
fill
Ok(fill)
}
fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
let ts = s.ts();
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Fill layer"));
let fill = fill_from(p);
let fill = fill_from("layer.add.fill", p)?;
let id = s.edit("Add fill layer", |s| {
let id = s.doc.project.alloc_id();
insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &channels_of(s)))
@@ -316,6 +316,10 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let solo = boolp(p, "solo") == Some(true);
let enabled = if solo { Some(true) } else { boolp(p, "enabled") };
let normal_format = normal_format_param("layer.fill.set", p)?;
let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]);
let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]);
let color = color_param("layer.fill.set", p, "color")?;
let value = color_param("layer.fill.set", p, "value")?;
let source = if let Some(kind) = strp(p, "procedural") {
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?;
let mut pr = Procedural::new(kind);
@@ -332,8 +336,8 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
pr.balance = v.clamp(-1.0, 1.0);
}
pr.invert = boolp(p, "invert").unwrap_or(false);
Some(Source::Procedural { pattern: pr, low: color_param(p, "low").unwrap_or([0.0; 3]), high: color_param(p, "high").unwrap_or([1.0; 3]) })
} else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) {
Some(Source::Procedural { pattern: pr, low, high })
} else if let Some(c) = color.or(value) {
Some(Source::Uniform(c))
} else if let Some(name) = strp(p, "image") {
Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })
+27 -20
View File
@@ -383,38 +383,45 @@ impl Session {
/// With `merge`, this folds into the previous undo step when that was an edit of the same kind
/// (a parameter set while the cook ran).
pub fn apply_link_cook(&mut self, id: LayerId, bytes: &[u8], merge: bool) -> Result<()> {
let m = read_mcmat(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let maps = decoded_maps(&m)?;
let names = self.edit_merging(EDIT, merge, |s| {
let LayerKind::Fill(mut fill) = s.doc.project.layer(id)?.kind.clone() else {
let material = read_mcmat(bytes).map_err(|error| EngineError::Other(error.to_string()))?;
let maps = decoded_maps(&material)?;
let names = self.edit_merging(EDIT, merge, |session| {
let LayerKind::Fill(mut fill) = session.doc.project.layer(id)?.kind.clone() else {
return Err(EngineError::Other(format!("layer {} is not a fill", id.0)));
};
let link = fill.link.as_mut().ok_or_else(|| EngineError::Other(format!("layer {} is not a MaterialCraft material", id.0)))?;
for p in &mut link.params {
if let Some(cooked) = m.manifest.parameters.iter().find(|c| c.id == p.id) {
p.value = cooked.value.clone();
for parameter in &mut link.params {
if let Some(cooked) = material.manifest.parameters.iter().find(|candidate| candidate.id == parameter.id) {
parameter.value = cooked.value.clone();
}
}
link.size = m.manifest.size[0];
link.size = material.manifest.size[0];
let stem = texturecraft_formats::sanitize_resource_name(&link.name);
let old: Vec<String> =
fill.sources.values().filter_map(|src| if let Source::Image { name, .. } = src { Some(name.clone()) } else { None }).collect();
let names = put_maps(s, &stem, &maps, &mut fill);
s.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
// Old maps go unless another layer (a duplicate) still shows them.
let mut used = Vec::new();
for set in 0..s.doc.project.texture_sets.len() {
for root in s.doc.project.texture_sets.get(set).map(|t| t.stack.clone()).unwrap_or_default() {
crate::material_lib::images_used(&s.doc.project, root, &mut used, 0);
let old_names: Vec<String> =
fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect();
let names = put_maps(session, &stem, &maps, &mut fill);
session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
// Duplicated layers may still use the earlier maps
let mut used_names = Vec::new();
for set in 0..session.doc.project.texture_sets.len() {
for root in session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.stack.clone()).unwrap_or_default() {
crate::material_lib::images_used(&session.doc.project, root, &mut used_names, 0);
}
}
for name in old.iter().filter(|n| !used.contains(n)) {
s.doc.resources.remove(name);
for name in old_names.iter().filter(|name| !used_names.contains(name)) {
session.doc.resources.remove(name);
}
Ok(names)
})?;
self.sync_images();
// Reuse the validated maps before synchronization considers decoding missing images
self.cache_decoded(names, maps);
self.sync_images();
Ok(())
}
+3 -3
View File
@@ -141,7 +141,7 @@ fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result<Value> {
}
fn add_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let color = color_param(p, "color").unwrap_or([1.0, 0.0, 0.0]);
let color = color_param("mask.add.colorSelection", p, "color")?.unwrap_or([1.0, 0.0, 0.0]);
let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0);
with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| {
let eid = s.doc.project.alloc_id();
@@ -285,7 +285,7 @@ fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
let blend = blend_param("effect.add.fill", p, "blend")?.unwrap_or(BlendMode::Normal);
let id = layer_param(s, "effect.add.fill", p)?;
if content_target(p, "effect.add.fill")? {
let mut fill = crate::layer_cmds::fill_from(p);
let mut fill = crate::layer_cmds::fill_from("effect.add.fill", p)?;
if fill.sources.is_empty() {
fill.sources = s.doc.project.layer(id)?.channels.keys().map(|c| (*c, Source::uniform_of(*c))).collect();
}
@@ -337,7 +337,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
if let Some(invert) = boolp(params, "invert") {
generator.invert = invert;
}
if let Some(direction) = color_param(params, "direction") {
if let Some(direction) = color_param(command, params, "direction")? {
generator.direction = direction;
}
+1 -3
View File
@@ -343,9 +343,7 @@ impl Session {
let Some(cache) = self.caches.get_mut(active.ts) else { return };
let settings = &active.stroke.settings;
let pressure = pressure.clamp(0.0, 1.0);
let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 };
let radius = settings.size * 2.0 * size_scale;
let radius = settings.uv_stamp_radius(pressure);
let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP);
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down)
+49 -26
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add fill layer from image",
[],
None,
"{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}",
"{name (exact resource name with extension or unique stem), channel?: baseColor, projection?: uv|triplanar|planar, scale?}",
always,
add_image_fill
),
@@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
impl Session {
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX))
self.edit("Import resource", |session| session.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS))
}
/// Add an image within a decoded texel budget, inside the caller's edit
@@ -47,39 +47,38 @@ impl Session {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image");
let base = texturecraft_formats::sanitize_resource_name(leaf);
let mut name = base.clone();
let mut n = 2;
let mut duplicate_index = 2;
while self.doc.resources.contains_key(&name) {
name = format!("{n}_{base}");
n += 1;
name = format!("{duplicate_index}_{base}");
duplicate_index += 1;
}
self.doc.resources.insert(name.clone(), Arc::new(bytes));
self.images.insert(name.clone(), decoded(image));
Ok(name)
}
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
pub fn sync_images(&mut self) {
let keep: Vec<String> = self.doc.resources.keys().cloned().collect();
self.images.retain(|k, _| keep.contains(k));
// Linked materials' packages are resources too, not images.
let missing: Vec<(String, Arc<Vec<u8>>)> = self
.doc
.resources
.iter()
.filter(|(k, _)| !self.images.contains_key(*k) && !k.ends_with(&format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT)))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
for (k, bytes) in missing {
match texturecraft_formats::decode_image(&bytes) {
Ok(d) => {
self.images.insert(k, decoded(d));
self.images.retain(|name, _| self.doc.resources.contains_key(name));
// Linked material packages are resources but cannot be decoded as images
let package_suffix = format!(".{}", texturecraft_formats::mcmat::MCRAFT_EXT);
for (name, bytes) in &self.doc.resources {
if self.images.contains_key(name) || name.ends_with(&package_suffix) {
continue;
}
match texturecraft_formats::decode_image(bytes) {
Ok(image) => {
self.images.insert(name.clone(), decoded(image));
}
Err(e) => self.log.push(format!("resource {k}: {e}")),
Err(error) => self.log.push(format!("resource {name}: {error}")),
}
}
}
@@ -179,11 +178,35 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "removed": unused }))
}
fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string();
if !s.doc.resources.contains_key(&name) {
return Err(bad("layer.add.image", format!("no resource `{name}`")));
#[cfg(not(target_arch = "wasm32"))]
const IMPORT_HINT: &str = "resource.import";
#[cfg(target_arch = "wasm32")]
const IMPORT_HINT: &str = "File > Import resources";
/// Resolve an image resource by exact name or unique file stem.
fn resolve_resource_name(s: &Session, name: &str) -> Result<String> {
if s.images.contains_key(name) {
return Ok(name.to_string());
}
let matches: Vec<&String> = s.images.keys().filter(|k| std::path::Path::new(k).file_stem().and_then(|stem| stem.to_str()) == Some(name)).collect();
match matches.as_slice() {
[single] => Ok((*single).clone()),
[] => {
let available: Vec<&str> = s.images.keys().map(String::as_str).collect();
let hint =
if available.is_empty() { format!(" (no resources imported: use {IMPORT_HINT})") } else { format!(" (available: {})", available.join(", ")) };
Err(bad("layer.add.image", format!("no resource `{name}`{hint}")))
}
multiple => {
let matches_str = multiple.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", ");
Err(bad("layer.add.image", format!("ambiguous resource `{name}` matches {matches_str}: give the full name with extension")))
}
}
}
fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
let raw_name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?;
let name = resolve_resource_name(s, raw_name)?;
let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor);
let projection = crate::layer_cmds::projection_from(p, "layer.add.image", None)?;
let ts = s.ts();
+113 -48
View File
@@ -571,23 +571,55 @@ impl Session {
self.invalidate_changed(other);
}
/// Mark dirty every texture set whose composite differs between `other` and the current
/// Mark dirty every texture set whose composite differs between the previous and current
/// document (after an edit, undo or redo).
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
self.follow_uv_layouts(&other.project);
pub(crate) fn invalidate_changed(&mut self, previous_document: &Document) {
self.follow_uv_layouts(&previous_document.project);
self.sync_caches();
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
let all = resources(other) != resources(&self.doc);
let (empty, images) = (BakedMaps::default(), Default::default());
let key = |d: &Document, ts: usize| {
let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default();
StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack)
// Removed or replaced resources may change any set's rendered content
let removed_or_replaced_resource =
previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current)));
let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect();
let uses_added_resource = |texture_set_index: usize| {
use texturecraft_core::{EffectKind, Fill, Source};
let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name));
let uses_fill =
|fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package));
let project = &self.doc.project;
!added_resource_names.is_empty()
&& project.texture_sets.get(texture_set_index).is_some_and(|set| {
project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| {
matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill))
|| 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),
_ => false,
})
})
})
};
for ts in 0..self.caches.len() {
if (all || key(other, ts) != key(&self.doc, ts))
&& let Some(c) = self.caches.get_mut(ts)
let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default());
let stack_key = |document: &Document, texture_set_index: usize| {
let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default();
StackKey::new(
&document.project,
&document.pixels,
document.baked.get(&texture_set_index).unwrap_or(&empty_baked_maps),
&empty_images,
texture_set_index,
stack,
)
};
for texture_set_index in 0..self.caches.len() {
if (removed_or_replaced_resource
|| stack_key(previous_document, texture_set_index) != stack_key(&self.doc, texture_set_index)
|| uses_added_resource(texture_set_index))
&& let Some(cache) = self.caches.get_mut(texture_set_index)
{
c.invalidate_all();
cache.invalidate_all();
}
}
}
@@ -740,6 +772,10 @@ impl Session {
let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e));
self.target = if content { StackTarget::Content } else { StackTarget::Mask };
}
let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some());
if self.target == StackTarget::Mask && !has_mask {
self.target = StackTarget::Content;
}
}
// -----------------------------------------------------------------------------------------
@@ -759,22 +795,24 @@ impl Session {
/// of a finite budget, after the dirty ones.
pub fn update_for(&mut self, budget_ms: f64, clock: impl Fn() -> f64) -> bool {
let start = clock();
let first = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK };
// The layer being edited: everything else is cached per tile.
let hot = self.stroke.as_ref().and_then(|s| s.target).map(|t| self.paint_owner(t)).or_else(|| self.selected_layer());
let stroke_size = self.stroke.as_ref().and_then(|s| self.caches.get(s.ts)).map(|c| c.size);
let preview = self.stroke.as_ref().and_then(|s| {
let initial_chunk_size = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK };
// The layer being edited: everything else is cached per tile
let hot = self.stroke.as_ref().and_then(|stroke| stroke.target).map(|target| self.paint_owner(target)).or_else(|| self.selected_layer());
let stroke_size = self.stroke.as_ref().and_then(|stroke| self.caches.get(stroke.ts)).map(|cache| cache.size);
let preview = self.stroke.as_ref().and_then(|stroke| {
Some(StrokePreview {
target: s.target?,
alpha: s.canvas.alpha.clone(),
opacity: s.stroke.settings.opacity,
erase: s.erase,
values: s.values.clone(),
target: stroke.target?,
alpha: stroke.canvas.alpha.clone(),
opacity: stroke.stroke.settings.opacity,
erase: stroke.erase,
values: stroke.values.clone(),
mask_value: self.tool.mask_value,
stencil: s.stencil.clone(),
carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(),
stencil: stroke.stencil.clone(),
carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(),
})
});
let active = self.ts();
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
let mut changed = false;
@@ -782,24 +820,27 @@ impl Session {
let Some(cache) = self.caches.get_mut(ts) else { continue };
cache.below.set_hot(hot);
cache.below.pass = cache.dirty.len() + cache.settle.len();
// Instances in sets of the stroke's size show the live stroke too.
// Instances in sets of the stroke's size show the live stroke too
let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size);
// Start at the size that fit the budget last time: with a heavy stack (smart
// materials at 8K) one tile per thread alone would take several frames' budget.
let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first };
// Reuse the last affordable chunk size for heavy stacks
let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { initial_chunk_size };
loop {
if cache.dirty.is_empty() {
if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) {
break;
}
// Small chunks: the settle slice of the budget is short.
cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first)));
// Small chunks: the settle slice of the budget is short
cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(initial_chunk_size)));
}
let t0 = clock();
let chunk_started = clock();
let tiles = next_chunk(&mut cache.dirty, chunk);
for t in &tiles {
cache.settle.remove(t);
for tile in &tiles {
cache.settle.remove(tile);
}
let empty = BakedMaps::default();
let inputs = texturecraft_compose::Inputs {
project: &self.doc.project,
@@ -813,30 +854,39 @@ impl Session {
images: &self.images,
bounds: self.mesh.bounds(),
};
// Look ahead so sliced updates filter a run of tiles once
cache.below.ahead = if budget_ms.is_finite() { tiles_ahead(&cache.dirty, &tiles) } else { Vec::new() };
texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below));
// The composited tiles and the neighbours their padding reached change.
// The composited tiles and the neighbours their padding reached change
let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles);
cache.upload.extend(tiles.iter().copied().chain(padded));
cache.revision = cache.revision.wrapping_add(1);
changed = true;
let now = clock();
let left = budget_ms - (now - start);
// As many tiles as fit in what is left, at the pace of this chunk.
let per_tile = (now - t0) / tiles.len().max(1) as f64;
if budget_ms.is_finite() && per_tile > 0.0 {
// Never above one tile per thread: work can turn heavy from one frame to the next.
cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first);
let remaining_ms = budget_ms - (now - start);
// Estimate how many tiles fit in the remaining frame budget
let ms_per_tile = (now - chunk_started) / tiles.len().max(1) as f64;
if budget_ms.is_finite() && ms_per_tile > 0.0 {
// Never above one tile per thread: work can turn heavy from one frame to the next
cache.chunk = ((budget_ms / ms_per_tile) as usize).clamp(1, initial_chunk_size);
}
if left <= 0.0 {
if remaining_ms <= 0.0 {
return changed;
}
let fit = if per_tile > 0.0 { (left / per_tile) as usize } else { CHUNK };
if fit == 0 {
let fitting_tiles = if ms_per_tile > 0.0 { (remaining_ms / ms_per_tile) as usize } else { CHUNK };
if fitting_tiles == 0 {
return changed;
}
chunk = fit.min(CHUNK);
chunk = fitting_tiles.min(CHUNK);
}
}
changed
}
@@ -963,15 +1013,30 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> {
if dirty.len() <= n {
return std::mem::take(dirty).into_iter().collect();
}
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
tiles.sort_by_key(|&(x, y)| (y / 16, x / 16, y, x));
tiles.sort_by_key(|&(x, y)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK, y, x));
tiles.truncate(n);
for t in &tiles {
dirty.remove(t);
for tile in &tiles {
dirty.remove(tile);
}
tiles
}
/// Dirty tiles a neighbourhood filter runs over ahead of the chunk being composited.
const FILTER_AHEAD: usize = 64;
/// The dirty tiles composited after `chunk` in its 16 × 16 tile blocks, in the order [`next_chunk`] takes them, at most [`FILTER_AHEAD`].
fn tiles_ahead(dirty: &BTreeSet<(u32, u32)>, chunk: &[(u32, u32)]) -> Vec<(u32, u32)> {
let block = |&(x, y): &(u32, u32)| (y / texturecraft_compose::BLOCK, x / texturecraft_compose::BLOCK);
let blocks: BTreeSet<(u32, u32)> = chunk.iter().map(block).collect();
let mut ahead: Vec<(u32, u32)> = dirty.iter().copied().filter(|tile| blocks.contains(&block(tile))).collect();
ahead.sort_by_key(|tile| (block(tile), tile.1, tile.0));
ahead.truncate(FILTER_AHEAD);
ahead
}
/// Valid texture set resolutions: powers of two from 128 to 8192.
pub fn check_resolution(r: u32) -> Result<u32> {
if (128..=8192).contains(&r) && r.is_power_of_two() {
+1 -1
View File
@@ -100,7 +100,7 @@ fn add_text(s: &mut Session, p: &Value) -> Result<Value> {
let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?;
let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0);
let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?;
let rgb = color_param(p, "color").unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?;
// The resource is named after the text (its first line, shortened) unless a name is given.
let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect();
+11 -9
View File
@@ -6,7 +6,7 @@ use texturecraft_core::Channel;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_of, color_param, f32p, strp, vec3};
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, StackTarget, Tool};
@@ -285,11 +285,14 @@ pub(crate) fn brush_json(session: &Session) -> Value {
}
fn material(s: &mut Session, p: &Value) -> Result<Value> {
let channel = channel_param("tool.material", p, "channel")?;
let color = color_param("tool.material", p, "color")?;
let value = color_param("tool.material", p, "value")?;
if let Some(v) = f32p(p, "maskValue") {
s.tool.mask_value = v.clamp(0.0, 1.0);
}
if let Some(c) = channel_param("tool.material", p, "channel")? {
if let Some(v) = color_param(p, "color").or_else(|| color_param(p, "value")) {
if let Some(c) = channel {
if let Some(v) = color.or(value) {
let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) };
s.tool.values.insert(c, v);
s.tool.enabled.insert(c);
@@ -356,7 +359,7 @@ fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.stencil = Some(st);
}
let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(c) = color_param(p, "center").map(|c| [c[0], c[1]]).or_else(|| pair(p, "center")) {
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));
}
if let Some(v) = f32p(p, "scale") {
@@ -378,11 +381,10 @@ fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
/// A `[a, b]` param of two finite numbers.
fn pair(p: &Value, key: &str) -> Option<[f32; 2]> {
let a = p.get(key)?.as_array()?;
let v: Vec<f32> = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
match v.as_slice() {
[x, y] => Some([*x, *y]),
_ => None,
}
let [x, y] = a.as_slice() else { return None };
let x = x.as_f64()? as f32;
let y = y.as_f64()? as f32;
(x.is_finite() && y.is_finite()).then_some([x, y])
}
fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
+2 -1
View File
@@ -211,6 +211,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(e) = env.as_deref().filter(|e| !e.starts_with(texturecraft_core::project::ENV_RESOURCE_PREFIX) && !ENVIRONMENTS.contains(e)) {
return Err(bad("display.set", format!("unknown environment `{e}`: one of {}, or resource:<image>", ENVIRONMENTS.join(", "))));
}
let scatter_color = color_param("display.set", p, "scatterColor")?;
let d = &mut s.doc.project.display;
if let Some(e) = env {
d.environment = e;
@@ -236,7 +237,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(t) = tm {
d.tone_mapping = t;
}
if let Some(c) = color_param(p, "scatterColor") {
if let Some(c) = scatter_color {
d.scatter_color = c.map(|v| v.clamp(0.0, 1.0));
}
if let Some(b) = boolp(p, "shadows") {
+18 -9
View File
@@ -464,7 +464,8 @@ fn leaning_session(lean: bool) -> Session {
}
let high_text = obj(&mesh, 0.1, f32::MAX, [1.0; 3]);
let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap();
// A folder of its own per call: tests run in parallel, and another one removes the shared folder.
// Tests run in parallel, so each call needs its own folder
static CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let call = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("texturecraft-lean-test-{}-{call}", std::process::id()));
@@ -472,7 +473,8 @@ fn leaning_session(lean: bool) -> Session {
let high = dir.join("high.obj");
std::fs::write(&high, high_text).unwrap();
execute(&mut s, "bake.highPoly.add", &json!({ "path": high.display().to_string() })).unwrap();
// The mesh is parsed and kept on add, so the file can go.
// The imported mesh remains after its source file is removed
let _ = std::fs::remove_dir_all(&dir);
execute(
&mut s,
@@ -489,10 +491,12 @@ fn the_skew_map_is_saved_with_the_project() {
execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap();
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(back.doc.bake_paint, s.doc.bake_paint);
// No skew: none comes back.
// Clearing skew persists
execute(&mut s, "bake.skew.clear", &Value::Null).unwrap();
assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.bake_paint.is_empty());
// A map with a non-finite value is skipped with a log line, and the project still opens.
// Invalid saved skew is skipped without preventing project load
let mut pf = s.project_file();
pf.bake_paint.insert((0, texturecraft_core::BakePaintTarget::Skew), texturecraft_formats::BakePaintData { width: 1, height: 1, values: vec![f32::NAN] });
let opened = Session::from_project_file(pf).unwrap();
@@ -522,24 +526,28 @@ fn the_skew_map_steers_only_a_distance_cage_with_averaged_normals() {
#[test]
fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() {
let mut s = leaning_session(true);
// Painting with no map makes a black one at `size` and puts the dab in it.
// The first stroke creates a black map at the requested size
let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap();
assert_eq!(r["skew"]["width"], 64);
let map = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0));
let rev = s.revision;
// Erasing with value 0 brings it back down; the size stays.
// Erasing retains the map size
execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap();
let after = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
assert_eq!(after.width, 64);
assert!(after.values.iter().all(|v| *v < 0.01) && s.revision > rev);
// A constant map is widened, keeping its value where nothing is painted.
// Resizing preserves untouched constant values
execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap();
execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap();
let wide = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap();
assert_eq!(wide.width, 32);
assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]);
// Hostile input is an error and leaves the map alone.
// Invalid strokes leave the map unchanged
let before = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned();
for bad in [
json!({}),
@@ -556,7 +564,8 @@ fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() {
assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}");
}
assert_eq!(s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(), before);
// And the painted map is saved with the project.
// Painted skew survives a project round trip
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(back.doc.bake_paint, s.doc.bake_paint);
}
+1
View File
@@ -45,6 +45,7 @@ fn overlap_is_measured_at_the_same_detail_in_every_uv_tile() {
// Tiles 1001 and 1010 make a grid ten tiles wide; 512 texels across all ten would give each tile about 51
const TEXELS_PER_TILE: f32 = 512.0;
const SLIVER_TEXELS: f32 = 4.0;
// Inside tile 1010 (column 9), clear of the wide raster's texel centres
const SLIVER_LEFT_U: f32 = 9.1;
let (left, right) = (SLIVER_LEFT_U, SLIVER_LEFT_U + SLIVER_TEXELS / TEXELS_PER_TILE);
+47 -1
View File
@@ -2,7 +2,7 @@
//! frame-budgeted compositor, through engine commands.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId, LayerKind};
use texturecraft_engine::core::{Channel, Fill, LayerId, LayerKind, Source};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
@@ -206,6 +206,52 @@ fn edits_invalidate_only_the_sets_they_change() {
assert!((rough(&mut s, 0) - 0.4).abs() < 1e-3);
}
#[test]
fn importing_images_invalidates_only_sets_with_newly_resolved_references() {
use std::sync::Arc;
let mut session = session();
let referenced_layer = session.doc.project.texture_sets[1].stack[0];
session
.edit("Reference missing image", |session| {
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::image("later.png"));
session.doc.project.layer_mut(referenced_layer).unwrap().kind = LayerKind::Fill(fill);
Ok(())
})
.unwrap();
session.update();
let mut image_bytes = Vec::new();
let image = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
image.write_to(&mut std::io::Cursor::new(&mut image_bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes("later.png", image_bytes.clone()).unwrap();
assert!(session.caches[0].dirty.is_empty(), "unrelated set stays clean");
assert!(!session.caches[1].dirty.is_empty(), "newly resolved image invalidates its set");
session.update();
let (x, y) = covered(&session, 1);
assert!(session.caches[1].composite.value(Channel::BaseColor, x, y)[0] > 0.9);
let imported_image = Arc::downgrade(&session.images["later.png"]);
session.undo().unwrap();
assert!(!session.caches[0].dirty.is_empty(), "resource removal retains broad invalidation");
assert!(!session.caches[1].dirty.is_empty());
assert!(imported_image.upgrade().is_none(), "undo releases the decoded image even while encoded bytes remain in history");
session.update();
session.redo().unwrap();
assert!(session.caches[0].dirty.is_empty());
assert!(!session.caches[1].dirty.is_empty());
assert!(!imported_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "redo decodes a new image allocation");
session.update();
session.import_resource_bytes("unused.png", image_bytes).unwrap();
assert!(session.caches.iter().all(|cache| cache.dirty.is_empty()), "unused image leaves every set clean");
let resolved_image = Arc::downgrade(&session.images["later.png"]);
session.sync_images();
assert!(resolved_image.ptr_eq(&Arc::downgrade(&session.images["later.png"])), "sync reuses already decoded images");
}
#[test]
fn budgeted_updates_spread_work_and_end_identical() {
let mut s = session();
+39 -31
View File
@@ -108,47 +108,55 @@ fn imports_as_a_linked_fill_with_its_maps() {
/// An image marked DirectX keeps the mark when a re-cook replaces it.
#[test]
fn recooks_keep_the_normal_format_of_a_map() {
let mut s = session();
let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap();
s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap();
let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("a fill") };
let mut session = session();
let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
execute(&mut session, "layer.fill.set", &json!({"layer": id.0, "channel": "roughness", "normalFormat": "directX"})).unwrap();
session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap();
let LayerKind::Fill(fill) = &session.doc.project.layer(id).unwrap().kind else { panic!("a fill") };
assert!(matches!(fill.sources.get(&Channel::Roughness), Some(Source::Image { normal_format: NormalFormat::DirectX, .. })));
}
#[test]
fn parameters_are_checked_stored_and_recooked_in_one_undo_step() {
let mut s = session();
let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
let set = |s: &mut Session, p: Value| execute(s, "material.link.set", &p);
assert!(set(&mut s, json!({"id": "nope", "value": 1, "cook": false})).is_err());
assert!(set(&mut s, json!({"id": "wear", "value": "soft", "cook": false})).is_err());
assert!(set(&mut s, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err());
set(&mut s, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap();
assert_eq!(link(&s, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]}));
set(&mut s, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap();
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.9}));
let mut session = session();
let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap();
let set = |session: &mut Session, params: Value| execute(session, "material.link.set", &params);
assert!(set(&mut session, json!({"id": "nope", "value": 1, "cook": false})).is_err());
assert!(set(&mut session, json!({"id": "wear", "value": "soft", "cook": false})).is_err());
assert!(set(&mut session, json!({"id": "wear", "value": f64::NAN, "cook": false})).is_err());
set(&mut session, json!({"id": "tint", "value": "#ff0000", "cook": false})).unwrap();
assert_eq!(link(&session, id).params[1].value, json!({"t": "color", "v": [1.0, 0.0, 0.0, 1.0]}));
set(&mut session, json!({"id": "wear", "value": 0.9, "cook": false})).unwrap();
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.9}));
// Cooks follow the texture set resolution
let job = session.link_job(id, &serde_json::Map::new()).unwrap();
// The job carries every value and the texture set's resolution.
let job = s.link_job(id, &serde_json::Map::new()).unwrap();
assert_eq!(job.size, 128);
assert_eq!(job.values["wear"], json!({"t": "float", "v": 0.9}));
// What the job cooked (here: built by hand) replaces the maps, merged into the edit.
let old = map_name(&s, id, Channel::Roughness);
s.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap();
assert!((roughness(&mut s) - 0.75).abs() < 2e-3);
assert!(!s.doc.resources.contains_key(&old), "old maps are dropped");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!((roughness(&mut s) - 0.25).abs() < 2e-3, "undo restores the earlier maps");
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 0.5}));
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert!((roughness(&mut s) - 0.75).abs() < 2e-3);
// Merge the cooked maps into the parameter edit
let old = map_name(&session, id, Channel::Roughness);
session.apply_link_cook(id, &mcmat(0.75, 0.9), true).unwrap();
// Presets skip inputs the painter can't set; unknown presets are errors.
assert!(execute(&mut s, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err());
execute(&mut s, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap();
assert_eq!(link(&s, id).params[0].value, json!({"t": "float", "v": 1.0}));
assert!((roughness(&mut session) - 0.75).abs() < 2e-3);
assert!(!session.doc.resources.contains_key(&old), "old maps are dropped");
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert!((roughness(&mut session) - 0.25).abs() < 2e-3, "undo restores the earlier maps");
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 0.5}));
execute(&mut session, "edit.redo", &Value::Null).unwrap();
assert!((roughness(&mut session) - 0.75).abs() < 2e-3);
// Presets skip unsupported inputs and reject unknown names
assert!(execute(&mut session, "material.link.preset", &json!({"name": "Nope", "cook": false})).is_err());
execute(&mut session, "material.link.preset", &json!({"name": "Worn", "cook": false})).unwrap();
assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0}));
}
#[test]
+40
View File
@@ -397,3 +397,43 @@ fn bench_layer_thumbs_4k() {
}
eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len());
}
/// A full recomposite in one call against the same one spread over frames, as the UI runs it, with and without a blurred mask
/// in the stack: neighbourhood filters are what a frame slice pays for apart from its own tiles.
#[test]
#[ignore]
fn bench_sliced_filters_4k() {
for blur in [false, true] {
let mut session = Session::new_project("sliced", primitives::sphere(1.0, 64, 32), "builtin:sphere", None, 4096).unwrap();
session.viewport = Vec2::new(800.0, 800.0);
let run = |session: &mut Session, id: &str, params: Value| execute(session, id, &params).unwrap();
run(&mut session, "layer.add.fill", json!({"color": [0.6, 0.5, 0.4], "roughness": 0.6}));
run(&mut session, "layer.add.fill", json!({"color": [0.1, 0.3, 0.6]}));
run(&mut session, "mask.add.black", Value::Null);
run(&mut session, "effect.add.generator", json!({"generator": "position", "level": 0.5}));
if blur {
run(&mut session, "effect.add.filter", json!({"filter": "blur", "radius": 8}));
}
session.update();
session.caches[0].invalidate_all();
let started = Instant::now();
session.update();
let direct = started.elapsed();
session.caches[0].invalidate_all();
let clock = Instant::now();
let elapsed_ms = || clock.elapsed().as_secs_f64() * 1000.0;
let (mut frames, mut longest_frame) = (0, Duration::ZERO);
while session.pending_tiles() > 0 {
let started = Instant::now();
session.update_for(30.0, elapsed_ms);
longest_frame = longest_frame.max(started.elapsed());
frames += 1;
}
let label = if blur { "blurred mask" } else { "no filter" };
println!("[sliced 4096², {label}] one call {direct:.2?}; in 30 ms slices {frames} frames, worst {longest_frame:.2?}, total {:.2?}", clock.elapsed());
}
}
+51
View File
@@ -244,3 +244,54 @@ fn swap_mask_value_inverts_only_while_a_mask_is_the_target() {
assert_eq!(session.tool.mask_value, 0.0, "a mask effect paints the mask too");
}
#[test]
fn stroke_after_undoing_mask_is_paint_stroke() {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.3], "roughness": 0.7})).unwrap();
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
s.update();
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap();
execute(&mut s, "tool.paint", &Value::Null).unwrap();
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [0.9, 0.3, 0.9]})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[130, 130], [170, 150]]})).unwrap();
s.update();
execute(&mut s, "mask.add.white", &Value::Null).unwrap();
s.update();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
execute(&mut s, "tool.stroke", &json!({"points": [[167, 183], [207, 203]]})).unwrap();
s.update();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
s.update();
let settled = s.caches[0].composite.clone();
s.caches[0].below.clear();
s.caches[0].invalidate_all();
s.update();
assert_eq!(settled, s.caches[0].composite, "the composite after the stroke matches a full recomposite");
}
#[test]
fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:random", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "mask.add.white", &Value::Null).unwrap();
execute(&mut s, "layer.instance", &Value::Null).unwrap();
s.update();
s.target = StackTarget::Mask;
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 50, "opacity": 0.8})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[170, 180], [210, 200]]})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.target, StackTarget::Mask);
execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Mask stroke");
}
+110
View File
@@ -308,6 +308,67 @@ fn image_resources_fill_layers_and_round_trip() {
assert!(s.import_resource_bytes("bad.png", vec![1, 2, 3]).is_err());
}
#[test]
fn image_resource_lookup_accepts_extension_and_stem() {
let mut s = session();
// No resources imported yet
let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err();
assert!(err.to_string().contains("no resource `missing` (no resources imported: use resource.import)"));
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.import_resource_bytes("tile.png", png.clone()).unwrap();
// Lookup by stem
let r = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap();
assert!(r["layer"].as_u64().is_some());
// Lookup by full name
let r2 = execute(&mut s, "layer.add.image", &json!({"name": "tile.png"})).unwrap();
assert!(r2["layer"].as_u64().is_some());
// Missing resource lists available
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err();
assert!(err.to_string().contains("no resource `wood` (available: tile.png)"));
// Ambiguous stem resolution
s.import_resource_bytes("tile.jpg", png).unwrap();
let err = execute(&mut s, "layer.add.image", &json!({"name": "tile"})).unwrap_err();
assert!(err.to_string().contains("ambiguous resource `tile`"));
}
#[test]
fn image_resource_lookup_ignores_linked_packages() {
use std::sync::Arc;
use texturecraft_engine::core::{LayerId, LayerKind, Source};
let mut s = session();
s.doc.resources.insert("wood.mcraft".into(), Arc::new(b"package bytes".to_vec()));
s.sync_images();
assert!(!s.images.contains_key("wood.mcraft"));
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap_err();
assert!(err.to_string().contains("no resources imported"), "{err}");
let err = execute(&mut s, "layer.add.image", &json!({"name": "wood.mcraft"})).unwrap_err();
assert!(err.to_string().contains("no resource `wood.mcraft` (no resources imported"), "{err}");
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([0, 255, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
s.import_resource_bytes("wood.png", png).unwrap();
let err = execute(&mut s, "layer.add.image", &json!({"name": "missing"})).unwrap_err();
assert!(err.to_string().contains("no resource `missing` (available: wood.png)"), "{err}");
let res = execute(&mut s, "layer.add.image", &json!({"name": "wood"})).unwrap();
let id = LayerId(res["layer"].as_u64().unwrap());
let LayerKind::Fill(fill) = &s.doc.project.layer(id).unwrap().kind else { panic!("expected fill layer") };
assert_eq!(fill.sources.get(&Channel::BaseColor), Some(&Source::image("wood.png")));
}
#[test]
fn brush_presets_apply_save_and_load() {
let mut s = session();
@@ -524,3 +585,52 @@ fn curvature_generators_take_a_mode_and_detail_sizes() {
assert!(dirt.is_err(), "only curvature generators have a mode");
assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged");
}
#[test]
fn unparseable_color_param_returns_error() {
let mut s = session();
let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err();
assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err();
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")");
let rev_before = s.revision;
let exposure_before = s.doc.project.display.env_exposure;
let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(s.doc.project.display.env_exposure, exposure_before);
assert_eq!(s.revision, rev_before);
let mask_before = s.tool.mask_value;
let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(s.tool.mask_value, mask_before);
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err();
assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err();
assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(s.revision, rev_before);
let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err();
assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")");
assert_eq!(s.revision, rev_before);
assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err());
execute(&mut s, "tool.polygonFill", &Value::Null).unwrap();
let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err();
assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]");
}
+41 -16
View File
@@ -1,6 +1,6 @@
//! Decoding imported image resources (fills, alphas, stencils).
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result};
/// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay
/// sRGB-encoded; `srgb` says so), row-major, top row first.
@@ -15,33 +15,37 @@ pub struct DecodedImage {
/// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes.
pub fn decode_image(bytes: &[u8]) -> Result<DecodedImage> {
decode_image_within(bytes, u64::MAX)
decode_image_within(bytes, MAX_RESOURCE_TEXELS)
}
/// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the
/// header, before any pixel is decoded or allocated.
pub fn decode_image_within(bytes: &[u8], max_texels: u64) -> Result<DecodedImage> {
let mut reader =
image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?;
// TGA has no magic signature; its decoder validates the header when no format was recognized
let format = reader.format().unwrap_or(image::ImageFormat::Tga);
reader.set_format(format);
let (width, height) = reader.into_dimensions().map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() })?;
let (width, height) = reader.into_dimensions().map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })?;
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE {
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_IMAGE_SIZE})")));
}
if u64::from(width) * u64::from(height) > max_texels {
return Err(FormatError::TooLarge(format!("image is {width}x{height}, more than {max_texels} texels")));
}
let image =
crate::guard("image", || image::load_from_memory_with_format(bytes, format).map_err(|e| FormatError::Malformed { kind: "image", msg: e.to_string() }))?;
let image = crate::guard("image", || {
image::load_from_memory_with_format(bytes, format).map_err(|error| FormatError::Malformed { kind: "image", msg: error.to_string() })
})?;
let srgb = !matches!(image, image::DynamicImage::ImageRgb32F(_) | image::DynamicImage::ImageRgba32F(_));
let float_image = image.into_rgba32f();
let (width, height) = float_image.dimensions();
let rgba = float_image.pixels().map(|pixel| pixel.0).collect();
Ok(DecodedImage { width, height, rgba, srgb })
}
@@ -63,15 +67,19 @@ mod tests {
#[test]
fn decodes_png_and_rejects_garbage() {
let mut png = Vec::new();
let img = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255]));
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let d = decode_image(&png).unwrap();
assert_eq!((d.width, d.height), (4, 2));
assert!(d.srgb);
assert!((d.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
let image = image::RgbaImage::from_fn(4, 2, |x, _| image::Rgba([x as u8 * 60, 0, 0, 255]));
image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let decoded = decode_image(&png).unwrap();
assert_eq!((decoded.width, decoded.height), (4, 2));
assert!(decoded.srgb);
assert!((decoded.rgba[1][0] - 60.0 / 255.0).abs() < 1e-3);
assert!(decode_image(b"not an image").is_err());
assert!(decode_image(&png[..png.len() / 2]).is_err());
let text = decode_image(&coverage_png(2, 1, &[0, 255], [255; 3]).unwrap()).unwrap();
assert_eq!(text.rgba, vec![[1.0, 1.0, 1.0, 0.0], [1.0; 4]]);
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
}
@@ -80,11 +88,15 @@ mod tests {
fn tga_without_a_magic_signature_decodes_within_the_texel_budget() {
let mut bytes = Vec::new();
image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Tga).unwrap();
let image = decode_image_within(&bytes, 16).unwrap();
assert_eq!((image.width, image.height), (4, 4));
assert!((image.rgba[0][1] - 0.2).abs() < 1e-6);
assert!(image.srgb);
let header = &bytes[..18];
assert!(matches!(decode_image_within(header, 15), Err(FormatError::TooLarge(_))));
assert!(decode_image(header).is_err());
}
@@ -92,12 +104,25 @@ mod tests {
#[test]
fn decoding_within_a_texel_limit_refuses_big_images_from_the_header() {
let png = {
let mut b = Vec::new();
image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png).unwrap();
b
let mut bytes = Vec::new();
image::RgbImage::from_pixel(8, 8, image::Rgb([1, 2, 3])).write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
bytes
};
assert_eq!(decode_image_within(&png, 64).unwrap().width, 8);
assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_))));
assert!(decode_image(&png).is_ok());
}
#[test]
fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() {
// The edge limit permits 16384² but the default resource budget does not
let mut header = [0u8; 18];
header[2] = 2;
header[12..14].copy_from_slice(&16_384u16.to_le_bytes());
header[14..16].copy_from_slice(&16_384u16.to_le_bytes());
header[16] = 24;
assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_))));
}
}
+61 -8
View File
@@ -95,6 +95,10 @@ pub(crate) fn guard<T>(kind: &'static str, f: impl FnOnce() -> Result<T>) -> Res
/// Largest image edge accepted or produced anywhere in this crate.
pub const MAX_IMAGE_SIZE: u32 = 16_384;
/// Most texels an imported image resource may decode to by default (8192 × 8192).
/// Larger images are refused from their header before any pixels are decoded.
pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26;
/// Read a whole file, refusing files over `cap` bytes.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result<Vec<u8>> {
@@ -108,15 +112,64 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result<Vec<u8>> {
Ok(std::fs::read(path)?)
}
/// Write `bytes` to `path` atomically: `<path>.tmp` first, then rename over the target.
/// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> {
let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("out");
// Bound retries when stale files or concurrent writers occupy candidate names
const MAX_TEMP_ATTEMPTS: u32 = 100;
for attempt in 0..MAX_TEMP_ATTEMPTS {
let temporary_path = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id()));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&temporary_path) {
Ok(file) => return Ok((temporary_path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error.into()),
}
}
Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file")))
}
/// Write `bytes` to `path` atomically: a new temporary file first, then rename over the target.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> {
let mut tmp = path.as_os_str().to_owned();
tmp.push(".tmp");
let tmp = std::path::PathBuf::from(tmp);
let res = std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, path));
if res.is_err() {
let _ = std::fs::remove_file(&tmp);
use std::io::Write;
let (temporary_path, mut file) = create_temp(path)?;
let result = file.write_all(bytes).and_then(|_| file.sync_all());
drop(file);
let result = result.and_then(|_| std::fs::rename(&temporary_path, path));
if result.is_err() {
let _ = std::fs::remove_file(&temporary_path);
}
Ok(result?)
}
#[cfg(all(test, unix))]
mod atomic_tests {
use super::write_atomic;
#[test]
fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> {
let directory = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory)?;
let target = directory.join("out.png");
let victim = directory.join("victim.txt");
std::fs::write(&victim, b"safe")?;
std::os::unix::fs::symlink(&victim, directory.join("out.png.tmp"))?;
write_atomic(&target, b"new").map_err(std::io::Error::other)?;
assert_eq!(std::fs::read(&victim)?, b"safe");
assert_eq!(std::fs::read(&target)?, b"new");
let _ = std::fs::remove_dir_all(&directory);
Ok(())
}
Ok(res?)
}
+95 -19
View File
@@ -20,6 +20,10 @@ const FORMAT: &str = "craft-material";
const VERSION: u32 = 1;
/// Largest entry read (maps are at most 8192² × 16 bits, compressed).
const MAX_ENTRY: u64 = 512 << 20;
/// Most map entries one manifest may name (a material has at most nine usages).
const MAX_MAPS: usize = 64;
/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4).
const MAX_TOTAL: u64 = 1 << 30;
const KIND: &str = "MaterialCraft material";
#[derive(Clone, Debug, PartialEq, Deserialize)]
@@ -66,27 +70,53 @@ fn malformed(msg: impl Into<String>) -> FormatError {
FormatError::Malformed { kind: KIND, msg: msg.into() }
}
fn read_entry(name: &str, entry: impl Read, total_bytes: &mut u64) -> Result<Vec<u8>> {
// Earlier maps remain live while the next entry is read
let remaining_bytes = MAX_TOTAL.saturating_sub(*total_bytes);
let entry_limit = MAX_ENTRY.min(remaining_bytes);
let mut bytes = Vec::new();
entry.take(entry_limit + 1).read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?;
if bytes.len() as u64 > MAX_ENTRY {
return Err(FormatError::TooLarge(name.to_string()));
}
let next_total = total_bytes.saturating_add(bytes.len() as u64);
if next_total > MAX_TOTAL {
return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)")));
}
// Keep spare read capacity from accumulating across retained map entries
bytes.shrink_to_fit();
*total_bytes = next_total;
Ok(bytes)
}
/// Read `.mcmat` bytes.
pub fn read_mcmat(bytes: &[u8]) -> Result<PortableMaterial> {
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?;
let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| malformed(error.to_string()))?;
let mut total_bytes = 0u64;
let mut read = |name: &str| -> Result<Vec<u8>> {
let mut out = Vec::new();
let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?;
f.take(MAX_ENTRY + 1).read_to_end(&mut out).map_err(|e| malformed(format!("{name}: {e}")))?;
if out.len() as u64 > MAX_ENTRY {
return Err(FormatError::TooLarge(name.to_string()));
}
Ok(out)
let entry = archive.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?;
read_entry(name, entry, &mut total_bytes)
};
let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?;
let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|error| malformed(format!("material.json: {error}")))?;
if manifest.format != FORMAT {
return Err(malformed(format!("format `{}`", manifest.format)));
}
if manifest.version > VERSION {
return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version)));
}
let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::<Result<Vec<_>>>()?;
if manifest.maps.len() > MAX_MAPS {
return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len())));
}
let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), read(&map.file)?))).collect::<Result<Vec<_>>>()?;
let source = read(&manifest.source)?;
Ok(PortableMaterial { manifest, maps, source })
}
@@ -153,20 +183,66 @@ mod tests {
#[test]
fn reads_manifest_maps_and_source() {
let bytes = sample(1);
assert!(is_mcmat(&bytes) && !is_mcraft(&bytes));
let m = read_mcmat(&bytes).unwrap();
assert_eq!(m.manifest.graph, "Brick_wall");
assert_eq!(m.manifest.parameters[0].id, "wear");
assert_eq!(m.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25}));
assert_eq!(m.manifest.presets[0].name, "Worn");
assert_eq!(m.manifest.inputs[0].identifier, "curvature");
assert_eq!(m.maps[0].0, "baseColor");
assert_eq!(crate::decode_image(&m.maps[0].1).unwrap().width, 4);
assert_eq!(m.source, b"pkg");
let material = read_mcmat(&bytes).unwrap();
assert_eq!(material.manifest.graph, "Brick_wall");
assert_eq!(material.manifest.parameters[0].id, "wear");
assert_eq!(material.manifest.parameters[0].value, serde_json::json!({"t": "float", "v": 0.25}));
assert_eq!(material.manifest.presets[0].name, "Worn");
assert_eq!(material.manifest.inputs[0].identifier, "curvature");
assert_eq!(material.maps[0].0, "baseColor");
assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4);
assert_eq!(material.source, b"pkg");
assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_))));
assert!(read_mcmat(b"junk").is_err());
}
#[test]
fn an_unbounded_map_list_is_refused() {
let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect();
let manifest =
serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"});
let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
archive.start_file("material.json", options).unwrap();
archive.write_all(manifest.to_string().as_bytes()).unwrap();
archive.start_file("maps/baseColor.png", options).unwrap();
archive.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap();
archive.start_file("source.mcraft", options).unwrap();
archive.write_all(b"pkg").unwrap();
let result = read_mcmat(&archive.finish().unwrap().into_inner());
assert!(matches!(result, Err(FormatError::Malformed { .. })));
}
#[test]
fn entry_read_stops_at_the_remaining_payload_budget() {
let payload = vec![7u8; 1024];
let mut input = Cursor::new(&payload);
let mut total_bytes = MAX_TOTAL - 8;
let result = read_entry("maps/extra.png", &mut input, &mut total_bytes);
assert!(matches!(result, Err(FormatError::TooLarge(_))));
assert_eq!(input.position(), 9, "only one byte beyond the remaining budget is needed to reject the entry");
assert_eq!(total_bytes, MAX_TOTAL - 8, "a rejected entry does not consume the payload budget");
}
#[test]
fn payload_budget_accepts_the_exact_limit_and_empty_entries() {
let mut total_bytes = MAX_TOTAL - 4;
let bytes = read_entry("map.png", Cursor::new([1, 2, 3, 4]), &mut total_bytes).unwrap();
assert_eq!(bytes, [1, 2, 3, 4]);
assert_eq!(total_bytes, MAX_TOTAL);
assert!(read_entry("empty.mcraft", Cursor::new([]), &mut total_bytes).unwrap().is_empty());
assert!(matches!(read_entry("extra.png", Cursor::new([1]), &mut total_bytes), Err(FormatError::TooLarge(_))));
}
#[test]
fn mesh_maps_encode_as_16_bit() {
let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap();
+19 -7
View File
@@ -217,7 +217,7 @@ impl<'a> Ogawa<'a> {
let value_bytes = match property.pod {
0..=2 => 1,
3 | 4 => 2,
3 | 4 | 9 => 2,
5 | 6 | 10 => 4,
7 | 8 | 11 => 8,
other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))),
@@ -233,6 +233,7 @@ impl<'a> Ogawa<'a> {
6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(),
7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(),
8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(),
9 => raw.as_chunks::<2>().0.iter().map(|c| half::f16::from_bits(u16::from_le_bytes(*c)).to_f64()).collect(),
10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(),
_ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(),
})
@@ -280,19 +281,30 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) {
return Err(malformed(KIND, "the archive group does not have the Alembic layout"));
}
// Indexed metadata: a u8 length before each string.
let block = o.data(root[5])?;
let mut c = Cursor { b: block, pos: 0 };
while c.pos < block.len() {
let n = c.u8()? as usize;
o.indexed_meta.push(c.string(n)?);
}
read_indexed_meta(block, &mut o.indexed_meta)?;
let mut sink = PolygonSink::default();
let mut walk = Walk { o, sink: &mut sink, visits: 0 };
walk.object(root[2], Mat4::IDENTITY, "", 0)?;
Ok(sink.finish())
}
/// The most indexed metadata entries that can ever be used: objects and properties refer to one
/// with a single byte, and 0xff already means "stored inline", so only 0 to 254 are reachable.
const MAX_INDEXED_META: usize = 255;
/// Indexed metadata: a u8 length before each string. `out` starts with the empty entry 0. Reading
/// stops once `out` holds [`MAX_INDEXED_META`] entries, because no later entry can be referred to
/// and an empty one costs a whole `String` in memory for one byte of file.
fn read_indexed_meta(block: &[u8], out: &mut Vec<String>) -> Result<()> {
let mut c = Cursor { b: block, pos: 0 };
while c.pos < block.len() && out.len() < MAX_INDEXED_META {
let n = c.u8()? as usize;
out.push(c.string(n)?);
}
Ok(())
}
struct Walk<'a, 'b> {
o: Ogawa<'a>,
sink: &'b mut PolygonSink,
@@ -243,6 +243,38 @@ fn strip_alone_keeps_uvs_flipped_to_v_down() {
}
}
#[test]
fn half_float_uvs_import_without_losing_values() {
let mut a = Abc { w: Writer::new() };
let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.5, 1.0, 0.0, 1.0, 0.0, 0.0]));
let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2]));
let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3]));
let uv_bytes: Vec<u8> = [0u16, 0, 0x3800, 0x3c00, 0x3c00, 0].iter().flat_map(|x| x.to_le_bytes()).collect();
let uv = a.array("uv", "", 9, 2, &uv_bytes);
let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv]);
let mesh = a.object(vec![geom], &[]);
let top = a.object(vec![], &[("m", "", mesh)]);
let imported = crate::import_mesh_bytes("m.abc", &a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])).unwrap();
assert!(!imported.report.uvs_generated);
for (p, uv) in imported.mesh.positions.iter().zip(&imported.mesh.uvs) {
assert_eq!(*uv, texturecraft_geom::glam::Vec2::new(p.x, 1.0 - p.y));
}
}
#[test]
fn half_float_values_preserve_special_values() {
let mut a = Abc { w: Writer::new() };
let raw: Vec<u8> = [0xc000u16, 0x0001, 0x7c00, 0x7e00].iter().flat_map(|x| x.to_le_bytes()).collect();
let p = a.array("values", "", 9, 1, &raw);
let property = Prop { name: p.name.into(), meta: p.meta, kind: PropKind::Array, pod: 9, extent: 1, group: p.group };
let mut ogawa = Ogawa { b: &a.w.b, budget: MAX_DECODED_BYTES, indexed_meta: Vec::new() };
let values = ogawa.values(&property).unwrap();
assert_eq!(values[0], -2.0);
assert_eq!(values[1], 2f64.powi(-24));
assert_eq!(values[2], f64::INFINITY);
assert!(values[3].is_nan());
}
#[test]
fn hdf5_and_garbage_are_clear_errors() {
let e = read(b"\x89HDF\r\n\x1a\n rest of an hdf5 file").err().unwrap().to_string();
@@ -291,3 +323,29 @@ fn self_referencing_groups_are_bounded() {
let bytes = a.archive(at, &[]);
assert!(read(&bytes).is_err());
}
#[test]
fn indexed_metadata_stops_at_the_entries_a_byte_can_index() {
// One real entry followed by a million empty ones: a byte each in the file, a `String` each
// in memory, and no index past 254 can be used anyway.
let mut block = vec![3, b'a', b'b', b'c'];
block.extend(std::iter::repeat_n(0u8, 1_000_000));
let mut kept = vec![String::new()];
read_indexed_meta(&block, &mut kept).unwrap();
assert_eq!(kept.len(), MAX_INDEXED_META);
assert_eq!(kept.get(1).map(String::as_str), Some("abc"));
// The mesh schema comes from metadata index 1 even when the table has unreachable entries.
let mut a = Abc { w: Writer::new() };
let pp = a.array("P", "", F32, 3, &f32s(&[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]));
let fi = a.array(".faceIndices", "", I32, 1, &i32s(&[0, 1, 2]));
let fc = a.array(".faceCounts", "", I32, 1, &i32s(&[3]));
let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc]);
let mesh = a.object(vec![geom], &[]);
let top = a.object(vec![], &[("tri", "", mesh)]);
let mut metas = vec!["schema=AbcGeom_PolyMesh_v1"];
metas.extend(std::iter::repeat_n("", 5_000));
let raw = read(&a.archive(top, &metas)).unwrap();
assert_eq!(raw.positions, [Vec3::X, Vec3::Y, Vec3::ZERO]);
assert_eq!(raw.groups, vec![(DEFAULT_MATERIAL.into(), "tri".into(), vec![0, 1, 2])]);
}
+119 -4
View File
@@ -32,6 +32,8 @@ const MIN_VERSION: i64 = 6000;
const MAX_DEPTH: usize = 64;
/// Memory budget for parsed nodes and properties (arrays are held as f64).
const MAX_DECODED_BYTES: usize = 1 << 31;
/// Maximum control points transformed across all mesh instances in one import.
const MAX_INSTANCE_POINTS: usize = 200_000_000;
/// Approximate memory charged per node and per scalar property.
const NODE_COST: usize = 96;
const PROP_COST: usize = 32;
@@ -128,14 +130,15 @@ impl Node {
if let Some(a) = self.child("a") {
return a.arr();
}
Cow::Owned(self.props.iter().filter_map(Prop::num).collect())
Cow::Owned(self.props.iter().map(|p| p.num().unwrap_or(f64::NAN)).collect())
}
/// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or
/// Properties60 (`Property: name, type, flags, values`).
fn property(&self, name: &str) -> Option<Vec<f64>> {
let list = self.child("Properties70").or_else(|| self.child("Properties60"))?;
list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().filter_map(Prop::num).collect())
let first_value = if list.name == "Properties70" { 4 } else { 3 };
list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().skip(first_value).map(|v| v.num().unwrap_or(f64::NAN)).collect())
}
fn vec3(&self, name: &str, default: Vec3) -> Vec3 {
@@ -542,6 +545,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result<RawMesh> {
attribute_of.insert(parent, *a);
}
}
// Repeated connections describe the same instance; keep distinct model placements in order.
let mut seen_instances = HashSet::new();
instances.retain(|instance| seen_instances.insert(instance.clone()));
let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect();
let mut unplaced: Vec<String> = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect();
unplaced.sort_unstable();
@@ -550,6 +556,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result<RawMesh> {
let base_colors = base_colors(&materials, &textures, &videos, &connections, files);
let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings")));
let mut sink = PolygonSink::default();
let mut remaining_points = MAX_INSTANCE_POINTS;
let no_slots = Vec::new();
for (geom, model) in instances {
let Some(g) = geometries.get(&geom) else { continue };
@@ -564,12 +571,15 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result<RawMesh> {
}
};
let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots);
add_geometry(&mut sink, g, global * m, names)?;
add_geometry(&mut sink, g, global * m, names, &mut remaining_points)?;
}
let mut raw = sink.finish();
raw.base_colors = base_colors;
// In file order; FBX 6's built-in "Producer" views are not the scene's cameras.
for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) {
if raw.cameras.len() >= super::MAX_CAMERAS {
break;
}
let Some(id) = o.id_at(0) else { continue };
if let Ok(m) = world(&models, &parents, &id) {
raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m));
@@ -783,14 +793,25 @@ impl Layer<'_> {
}
}
fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> {
fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String], remaining_points: &mut usize) -> Result<()> {
let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default();
check_vertices(vertices.len() / 3)?;
*remaining_points = remaining_points
.checked_sub(vertices.len() / 3)
.ok_or_else(|| FormatError::TooLarge(format!("FBX instances exceed the {MAX_INSTANCE_POINTS} control-point work limit")))?;
let points: Vec<Vec3> = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect();
let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default();
let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex");
let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex");
let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", "");
if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite())
|| [&normals, &uvs, &materials]
.into_iter()
.flatten()
.any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite())))
{
return Err(malformed(KIND, "mesh array contains a non-numeric or non-finite value"));
}
let normal_transform = Mat3::from_mat4(transform).inverse().transpose();
let flip = transform.determinant() < 0.0;
let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize);
@@ -839,3 +860,97 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots:
Ok(())
}
#[cfg(test)]
mod instance_budget_tests {
use super::*;
#[test]
fn ascii_array_keeps_invalid_values_in_place() {
let (nodes, _) = parse_ascii(
br#"FBXHeaderExtension: { FBXVersion: 7400 }
Vertices: 1, 1.#INF, 3, "x", 5
"#,
)
.unwrap();
let values = nodes[1].arr();
assert_eq!(values.len(), 5);
assert!(values[1].is_nan() && values[3].is_nan());
assert_eq!((values[0], values[2], values[4]), (1.0, 3.0, 5.0));
}
#[test]
fn ascii_bad_vertex_is_rejected() {
let (nodes, _) = parse_ascii(
br#"FBXHeaderExtension: { FBXVersion: 7400 }
Geometry: { Vertices: 0, 0, 0, 1, -1.#IND, 0, 0, 1, 0
PolygonVertexIndex: 0, 1, -3 }
"#,
)
.unwrap();
let mut remaining = usize::MAX;
let result = add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining);
assert!(result.is_err());
}
#[test]
fn ascii_bad_index_and_uv_are_rejected() {
for payload in [
"PolygonVertexIndex: 0, oops, -3",
"PolygonVertexIndex: 0, 1, -3\nLayerElementUV: 0 { MappingInformationType: \"ByPolygonVertex\"\nReferenceInformationType: \"Direct\"\nUV: 0, 0, oops, 1, 1, 0 }",
] {
let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nGeometry: {{ Vertices: 0, 0, 0, 1, 0, 0, 0, 1, 0\n{payload} }}");
let (nodes, _) = parse_ascii(source.as_bytes()).unwrap();
let mut remaining = usize::MAX;
assert!(add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining).is_err());
}
}
#[test]
fn ascii_transform_metadata_does_not_shift_values() {
let (nodes, _) = parse_ascii(
br#"FBXHeaderExtension: { FBXVersion: 7400 }
Model: { Properties70: { P: "Lcl Translation", "Lcl Translation", "", "A", 1, 2, 3 } }
"#,
)
.unwrap();
assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0]));
let (nodes, _) = parse_ascii(
br#"FBXHeaderExtension: { FBXVersion: 7400 }
Model: { Properties60: { Property: "Lcl Translation", "Lcl Translation", "A", 1, 2, 3 } }
"#,
)
.unwrap();
assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0]));
}
#[test]
fn malformed_transform_value_keeps_its_position_in_both_property_formats() {
for (list, entry) in [
("Properties70", "P: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A\", 1, oops, 3"),
("Properties60", "Property: \"Lcl Translation\", \"Lcl Translation\", \"A\", 1, oops, 3"),
] {
let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nModel: {{ {list}: {{ {entry} }} }}");
let (nodes, _) = parse_ascii(source.as_bytes()).unwrap();
let values = nodes[1].property("Lcl Translation").unwrap();
assert_eq!(values.len(), 3);
assert_eq!((values[0], values[2]), (1.0, 3.0));
assert!(values[1].is_nan());
}
}
#[test]
fn instance_points_are_charged_before_transforming_each_copy() {
let geometry = Node {
name: "Geometry".into(),
props: vec![],
children: vec![Node { name: "Vertices".into(), props: vec![Prop::Arr(vec![0.0; 9])], children: vec![] }],
};
let mut sink = PolygonSink::default();
let mut remaining = 5;
add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining).unwrap();
assert_eq!(remaining, 2);
assert!(matches!(add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining), Err(FormatError::TooLarge(_))));
assert_eq!(remaining, 2);
}
}
+27 -1
View File
@@ -20,8 +20,34 @@ pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
crate::guard(KIND, || read_inner(bytes))
}
/// Loads and validates the document like `gltf::Gltf::from_slice`, except that a scene without a
/// `nodes` array is an empty scene. The `gltf` crate declares the field as required, but the
/// glTF 2.0 schema lists no required properties for a scene, and exporters write such scenes
/// for scenes that contain no objects.
fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option<Vec<u8>>)> {
let (json, blob) = if bytes.starts_with(b"glTF") {
let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?;
let blob = glb.bin.take().map(std::borrow::Cow::into_owned);
(glb.json, blob)
} else {
(std::borrow::Cow::Borrowed(bytes), None)
};
let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?;
if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) {
for scene in scenes {
if let Some(scene) = scene.as_object_mut() {
scene.entry("nodes").or_insert_with(|| serde_json::Value::Array(Vec::new()));
}
}
}
// Consume the DOM directly rather than serialising it back to a second full-size buffer.
let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?;
let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?;
Ok((document, blob))
}
fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
let gltf::Gltf { document, blob } = gltf::Gltf::from_slice(bytes).map_err(|e| malformed(KIND, e))?;
let (document, blob) = parse(bytes)?;
check_buffer_uris(&document)?;
let buffers = gltf::import_buffers(&document, None, blob).map_err(|e| match e {
gltf::Error::ExternalReferenceInSliceImport => FormatError::Unsupported(
+8 -3
View File
@@ -1,5 +1,7 @@
//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn.
use std::io::{BufReader, Read};
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use super::{RawMesh, check_triangles, check_vertices};
@@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
}
let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect();
let source = format!("mtllib texturecraft-usemtl.mtl\n{text}");
let prefix = "mtllib texturecraft-usemtl.mtl\n";
// Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a
// whole-file copy nor an extra string is needed before tobj parses it.
let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes()));
// Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates
let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true };
let (models, materials) =
tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let materials = materials.unwrap_or_default();
let mut raw = RawMesh::default();
+71 -2
View File
@@ -299,6 +299,18 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() {
}
/// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue.
#[test]
fn fbx_camera_models_are_capped_during_import() {
let mut nodes = scene(false);
let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap();
for id in 100..199 {
objects.children.push(n("Model", vec![P::L(id), P::S("Camera\\u{0}\\u{1}Model"), P::S("Camera")], vec![]));
}
let raw = fbx::read(&binary_fbx(&nodes, 7500, true)).unwrap();
assert_eq!(raw.cameras.len(), MAX_CAMERAS);
}
fn textured_scene(png: &[u8]) -> Vec<N> {
let mut nodes = scene(false);
let objects = nodes.iter_mut().find(|n| n.name == "Objects").unwrap();
@@ -415,6 +427,24 @@ fn fbx_ascii_and_z_up() {
check_fbx_scene(&import_mesh_bytes("z.fbx", &binary_fbx(&scene(true), 7700, true)).unwrap().mesh, true);
}
#[test]
fn fbx_duplicate_geometry_connections_do_not_duplicate_instances() {
let mut nodes = scene(false);
let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap();
for _ in 0..50 {
connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(21)], vec![]));
}
let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap();
assert_eq!(imported.report.triangles, 3);
let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap();
objects.children.push(n("Model", vec![P::L(22), P::S("Other\u{0}\u{1}Model"), P::S("Mesh")], vec![]));
let connections = nodes.iter_mut().find(|node| node.name == "Connections").unwrap();
connections.children.push(n("C", vec![P::S("OO"), P::L(10), P::L(22)], vec![]));
let imported = import_mesh_bytes("scene.fbx", ascii_fbx(&nodes).as_bytes()).unwrap();
assert_eq!(imported.report.triangles, 6, "a different model must remain a distinct instance");
}
/// The scene of [`scene`] (Y up) as FBX 6.1 writes it: geometry inside the Model, objects named
/// `Class::Name`, `Properties60`, `Connect` records, GlobalSettings inside Objects.
const FBX61: &str = r#"; FBX 6.1.0 project file
@@ -589,19 +619,55 @@ fn fbx_old_versions_and_garbage_are_errors() {
assert!(import_mesh_bytes("h.fbx", &huge).is_err());
}
// Keep these fixtures independently schedulable: one serial test took 24 minutes in
// instrumented coverage. Splitting cases keeps every mutation and assertion intact.
#[test]
fn malformed_fbx_and_dae_never_panic() {
fn malformed_fbx_and_dae_never_panic_binary_7400() {
hammer("x.fbx", &binary_fbx(&scene(false), 7400, false));
}
#[test]
fn malformed_fbx_and_dae_never_panic_binary_7500() {
hammer("x.fbx", &binary_fbx(&scene(true), 7500, true));
}
#[test]
fn malformed_fbx_and_dae_never_panic_ascii() {
hammer("x.fbx", ascii_fbx(&scene(false)).as_bytes());
}
#[test]
fn malformed_fbx_and_dae_never_panic_collada() {
hammer("x.dae", DAE.as_bytes());
}
#[test]
fn malformed_fbx_and_dae_never_panic_random_binary() {
random_scene_corruptions(0);
}
#[test]
fn malformed_fbx_and_dae_never_panic_random_ascii() {
random_scene_corruptions(1);
}
#[test]
fn malformed_fbx_and_dae_never_panic_random_collada() {
random_scene_corruptions(2);
}
fn random_scene_corruptions(selected_fixture: usize) {
// Random multi-byte corruptions (a fixed LCG keeps failures reproducible).
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = move || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize
};
for good in [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()] {
// Replay earlier mutations without parsing them so each fixture receives exactly
// its original LCG stream, not a fresh seed. Fixture sizes and all 1,500 cases
// per fixture stay unchanged; generating these bytes is cheap next to parsing.
let fixtures = [binary_fbx(&scene(false), 7500, true), ascii_fbx(&scene(true)).into_bytes(), DAE.as_bytes().to_vec()];
for (fixture, good) in fixtures.into_iter().enumerate().take(selected_fixture + 1) {
let name = if good.starts_with(b"<?xml") { "r.dae" } else { "r.fbx" };
for _ in 0..1500 {
let mut b = good.clone();
@@ -609,6 +675,9 @@ fn malformed_fbx_and_dae_never_panic() {
let i = next() % b.len();
b[i] = next() as u8;
}
if fixture != selected_fixture {
continue;
}
if let Err(e) = import_mesh_bytes(name, &b) {
assert!(!e.to_string().contains("parser failed"), "{name}: a parser panicked");
}
+42
View File
@@ -118,6 +118,48 @@ fn glb_two_materials_mirrored_node() {
m.validate().unwrap();
}
/// A scene without a `nodes` array is legal glTF (Blender writes one for a scene with no exported
/// objects); it must not stop the default scene from importing.
#[test]
fn gltf_scene_without_nodes_imports_the_default_scene() {
let mut json: serde_json::Value = serde_json::from_slice(&embedded_gltf()).unwrap();
json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]);
json["scene"] = 1.into();
let im = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap();
assert_eq!(im.report.triangles, 2);
// Only an empty scene: nothing to import, but a clear error rather than a parse failure.
json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }]);
json["scene"] = 0.into();
let err = import_mesh_bytes("scene.gltf", &serde_json::to_vec(&json).unwrap()).unwrap_err();
assert!(!err.to_string().contains("missing field"), "{err}");
}
#[test]
fn glb_scene_without_nodes_keeps_binary_mesh_in_default_scene() {
let original = glb(true, true);
let jlen = u32::from_le_bytes(original[12..16].try_into().unwrap()) as usize;
let mut json: serde_json::Value = serde_json::from_slice(&original[20..20 + jlen]).unwrap();
json["scenes"] = serde_json::json!([{ "name": "EmptyReviewScene" }, { "nodes": [0] }]);
json["scene"] = 1.into();
let mut js = serde_json::to_vec(&json).unwrap();
while !js.len().is_multiple_of(4) {
js.push(b' ');
}
let bin_chunk = &original[20 + jlen..];
let mut glb = Vec::new();
glb.extend(b"glTF");
glb.extend(2u32.to_le_bytes());
glb.extend(((20 + js.len() + bin_chunk.len()) as u32).to_le_bytes());
glb.extend((js.len() as u32).to_le_bytes());
glb.extend(b"JSON");
glb.extend(js);
glb.extend(bin_chunk);
let im = import_mesh_bytes("scene.glb", &glb).unwrap();
assert_eq!(im.report.triangles, 2);
assert_eq!(im.mesh.materials, ["Red", "Material_1"]);
assert_outward(&im.mesh);
}
#[test]
fn gltf_embedded_buffers_and_missing_attributes() {
let im = import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap();
+88 -34
View File
@@ -15,6 +15,9 @@ const MIN_VERSION: (u8, u8, u8) = (0, 4, 0);
const MAX_SECTIONS: usize = 64;
/// Items in one table or array.
const MAX_ITEMS: usize = 1 << 28;
/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a
/// materialised path, so it needs its own ceiling as well as the decoded-byte budget.
const MAX_PATHS: usize = 4_000_000;
/// Spec types.
const SPEC_ATTRIBUTE: i64 = 1;
@@ -242,58 +245,73 @@ impl<'a> Crate<'a> {
/// Paths are stored as a pre-order tree: element token (negative for properties) and a
/// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump).
fn read_paths(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> {
let total = s.count(0)?;
let n = s.count(0)?;
let index = s.ints(n, 4, budget)?;
let elements = s.ints(n, 4, budget)?;
let jumps = s.ints(n, 4, budget)?;
budget.take(total.saturating_mul(64))?;
self.paths = vec![None; total];
let mut work: Vec<(usize, Option<usize>)> = vec![(0, None)];
let mut steps = 0usize;
let bad = || malformed(KIND, "corrupt path table");
while let Some((mut i, mut parent)) = work.pop() {
fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> {
let path_count = section.count(0)?;
let encoded_count = section.count(0)?;
let path_indices = section.ints(encoded_count, 4, budget)?;
let elements = section.ints(encoded_count, 4, budget)?;
let jumps = section.ints(encoded_count, 4, budget)?;
if path_count > MAX_PATHS {
return Err(FormatError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})")));
}
// Charge slot storage before allocating the table
budget.take(path_count.saturating_mul(std::mem::size_of::<Option<PathEl>>()))?;
self.paths = vec![None; path_count];
let mut pending_branches: Vec<(usize, Option<usize>)> = vec![(0, None)];
let mut visited_count = 0usize;
let path_error = || malformed(KIND, "corrupt path table");
while let Some((mut cursor_index, mut parent)) = pending_branches.pop() {
loop {
steps += 1;
if steps > n {
return Err(bad());
visited_count += 1;
if visited_count > encoded_count {
return Err(path_error());
}
let this = i;
i += 1;
let at = index.get(this).map(|v| *v as u32 as usize).filter(|p| *p < total).ok_or_else(bad)?;
let el = match parent {
let node_index = cursor_index;
cursor_index += 1;
let path_index =
path_indices.get(node_index).map(|v| *v as u32 as usize).filter(|parent_index| *parent_index < path_count).ok_or_else(path_error)?;
let path_element = match parent {
None => PathEl { text: "/".into(), parent: None, name: String::new(), prop: false },
Some(p) => {
let e = *elements.get(this).ok_or_else(bad)?;
let name = self.token(e.unsigned_abs())?.to_string();
let base = self.paths.get(p).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(bad)?;
let text = match (e < 0, base) {
(true, _) => format!("{base}.{name}"),
(false, _) if name.starts_with('{') => format!("{base}{name}"),
Some(parent_index) => {
let element_token = *elements.get(node_index).ok_or_else(path_error)?;
let name = self.token(element_token.unsigned_abs())?;
let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?;
let separator_bytes = usize::from(element_token < 0 || (!name.starts_with('{') && parent_path != "/"));
let text_bytes = parent_path.len().saturating_add(name.len()).saturating_add(separator_bytes);
// Charge both retained strings before allocating either one
budget.take(text_bytes.saturating_add(name.len()))?;
let name = name.to_string();
let text = match (element_token < 0, parent_path) {
(true, _) => format!("{parent_path}.{name}"),
(false, _) if name.starts_with('{') => format!("{parent_path}{name}"),
(false, "/") => format!("/{name}"),
(false, _) => format!("{base}/{name}"),
(false, _) => format!("{parent_path}/{name}"),
};
budget.take(text.len())?;
PathEl { text, parent: Some(p), name, prop: e < 0 }
PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 }
}
};
if let Some(slot) = self.paths.get_mut(at) {
*slot = Some(el);
if let Some(slot) = self.paths.get_mut(path_index) {
*slot = Some(path_element);
}
let jump = *jumps.get(this).ok_or_else(bad)?;
let jump = *jumps.get(node_index).ok_or_else(path_error)?;
let (child, sibling) = (jump > 0 || jump == -1, jump >= 0);
if child {
if sibling {
work.push((this.checked_add(usize::try_from(jump).map_err(|_| bad())?).ok_or_else(bad)?, parent));
pending_branches.push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent));
}
parent = Some(at);
parent = Some(path_index);
}
if !child && !sibling {
break;
}
}
}
Ok(())
}
@@ -647,6 +665,42 @@ mod tests {
out.extend_from_slice(&comp);
}
#[test]
fn repeated_path_names_count_toward_the_decode_budget() {
let name = "long_name_reused";
let mut section = Vec::new();
section.extend_from_slice(&3u64.to_le_bytes());
section.extend_from_slice(&3u64.to_le_bytes());
compressed_ints(&mut section, &[0, 1, 2]);
compressed_ints(&mut section, &[0, 0, 0]);
compressed_ints(&mut section, &[-1, 0, -2]);
let mut crate_data = crate_over(&section, (0, 8, 0));
crate_data.tokens.push(name.into());
let decoded_arrays_bytes = 3 * 3 * std::mem::size_of::<i64>();
let path_slots_bytes = 3 * std::mem::size_of::<Option<PathEl>>();
let path_text_bytes = 2 * (1 + name.len());
let one_name_budget = decoded_arrays_bytes + path_slots_bytes + path_text_bytes + name.len();
let mut insufficient_budget = Budget(one_name_budget);
let rejected = crate_data.read_paths(Cur { b: &section, pos: 0 }, &mut insufficient_budget);
assert!(matches!(rejected, Err(FormatError::TooLarge(_))), "two path names cannot fit a one-name budget");
drop(crate_data);
let mut complete_budget = Budget(one_name_budget + name.len());
let mut crate_data = crate_over(&section, (0, 8, 0));
crate_data.tokens.push(name.into());
crate_data.read_paths(Cur { b: &section, pos: 0 }, &mut complete_budget).unwrap();
assert_eq!(complete_budget.0, 0);
assert_eq!(crate_data.path(1).unwrap().text, format!("/{name}"));
assert_eq!(crate_data.path(2).unwrap().text, format!("/{name}"));
let retained_name_bytes: usize = crate_data.paths.iter().filter_map(Option::as_ref).map(|path| path.name.capacity()).sum();
assert!(retained_name_bytes >= 2 * name.len());
println!("retained names: 2, buffer capacity: {retained_name_bytes} bytes");
}
#[test]
fn compressed_float_and_int_arrays() {
let n = 20usize;
+13 -13
View File
@@ -98,23 +98,23 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result<Vec<u8>> {
Ok(out.into_inner())
}
/// Save atomically: `<path>.tmp` first, then rename over `path`.
/// Save atomically through a newly created temporary file beside `path`.
#[cfg(not(target_arch = "wasm32"))]
pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> {
let mut tmp = path.as_os_str().to_owned();
tmp.push(".tmp");
let tmp = std::path::PathBuf::from(tmp);
let res = (|| -> Result<()> {
let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
write_project(&mut file, pf)?;
file.into_inner().map_err(|e| e.into_error())?.sync_all()?;
std::fs::rename(&tmp, path)?;
pub fn save_project(path: &std::path::Path, project_file: &ProjectFile) -> Result<()> {
let (temporary_path, file) = crate::create_temp(path)?;
let result = (|| -> Result<()> {
let mut file = std::io::BufWriter::new(file);
write_project(&mut file, project_file)?;
file.into_inner().map_err(|error| error.into_error())?.sync_all()?;
std::fs::rename(&temporary_path, path)?;
Ok(())
})();
if res.is_err() {
let _ = std::fs::remove_file(&tmp);
if result.is_err() {
let _ = std::fs::remove_file(&temporary_path);
}
res
result
}
fn zip_err(e: zip::result::ZipError) -> FormatError {
+3 -2
View File
@@ -82,7 +82,7 @@ impl UvGBuffer {
.zip(bary.par_chunks_mut(band_texels))
.enumerate()
.map(|(band_index, (band_tri, band_bary))| {
// Per texel: how many triangles cover it, and whether any has its center strictly inside, so the count doesn't depend on triangle order
// Keep cover counts and strict interiors independent of triangle order
let mut covers = vec![0u32; band_tri.len()];
let mut strict_cover = vec![false; band_tri.len()];
let first_row = band_index as u32 * BAND;
@@ -178,7 +178,7 @@ mod tests {
#[test]
fn half_triangle_covers_texels_with_centers_inside() {
// One triangle covering the lower-left half of UV space (v down: y = v·H).
// UV v increases down, so this triangle covers the lower-left half
let m =
Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0)], vec![0, 1, 2], "m")
.unwrap();
@@ -206,6 +206,7 @@ mod tests {
// The texel center (0.5, 0.5) lies inside the first triangle and on the diagonal the other two share
let uv = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.2), Vec2::new(0.2, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)];
let positions = vec![Vec3::ZERO; uv.len()];
// In either order: the inside cover first, or the two edge covers first
for indices in [vec![0, 1, 2, 0, 3, 4, 0, 5, 3], vec![0, 3, 4, 0, 5, 3, 0, 1, 2]] {
let m = Mesh::from_parts(positions.clone(), None, uv.clone(), indices.clone(), "m").unwrap();
+23 -18
View File
@@ -88,27 +88,27 @@ impl Mesh {
/// split it from its twin), per material in `0..materials.len().max(1)`.
pub fn wire_edges(&self) -> Vec<Vec<(u32, u32)>> {
(0..self.materials.len().max(1))
.map(|m| {
// Edge → (real in some triangle, triangles using it), in first-seen order.
.map(|material| {
// Keep first-seen edge order while counting its triangle uses
let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new();
let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
for t in self.triangles_of(m) {
let Some(v) = self.indices.get(t * 3..t * 3 + 3) else { continue };
let hidden = self.diagonals.get(t).copied().unwrap_or(0);
for (i, (a, b)) in [(v[0], v[1]), (v[1], v[2]), (v[2], v[0])].into_iter().enumerate() {
let key = (a.min(b), a.max(b));
let real = hidden >> i & 1 == 0;
let e = *at.entry(key).or_insert_with(|| {
let mut edge_indices: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new();
for triangle in self.triangles_of(material) {
let Some(vertices) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue };
let hidden = self.diagonals.get(triangle).copied().unwrap_or(0);
for (side, (from, to)) in [(vertices[0], vertices[1]), (vertices[1], vertices[2]), (vertices[2], vertices[0])].into_iter().enumerate() {
let key = (from.min(to), from.max(to));
let is_polygon_edge = hidden >> side & 1 == 0;
let edge_index = *edge_indices.entry(key).or_insert_with(|| {
edges.push((key, false, 0));
edges.len() - 1
});
if let Some((_, r, n)) = edges.get_mut(e) {
*r |= real;
*n = n.saturating_add(1);
if let Some((_, edge_is_polygon_side, triangle_count)) = edges.get_mut(edge_index) {
*edge_is_polygon_side |= is_polygon_edge;
*triangle_count = triangle_count.saturating_add(1);
}
}
}
edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect()
edges.into_iter().filter(|(_, is_polygon_edge, triangle_count)| *is_polygon_edge || *triangle_count == 1).map(|(edge, ..)| edge).collect()
})
.collect()
}
@@ -118,6 +118,7 @@ impl Mesh {
// Signed zero denotes the same position on either side of an imported seam
let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() });
let mut seams = vec![Vec::new(); self.materials.len().max(1)];
// Match across materials before grouping the lines for texture-set visibility
let mut sides: std::collections::HashMap<EdgePositions, Vec<(u32, u32, usize)>> = std::collections::HashMap::new();
for material in 0..seams.len() {
@@ -135,7 +136,8 @@ impl Mesh {
}
let uv = |index: u32| self.uvs.get(index as usize).copied();
// Directions only: imported normals need not be unit length, and two missing normals agree
// Imported normals need not be unit length; two missing normals agree
let direction = |index: u32| self.normals.get(index as usize).map_or(Vec3::ZERO, |normal| normal.normalize_or_zero());
let same_normal = |a: u32, b: u32| {
let (a, b) = (direction(a), direction(b));
@@ -482,14 +484,17 @@ mod tests {
fn wire_edges_leave_out_polygon_diagonals() {
let mut m = quad();
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge");
// Edge 2 of (0, 1, 2) and edge 0 of (0, 2, 3) split the quad.
// Hide the quad's shared diagonal
m.diagonals = vec![0b100, 0b001];
assert_eq!(m.wire_edges(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]);
// A diagonal whose twin a seam split off (vertex 4 copies vertex 0) stays.
// Keep the diagonal when a seam splits its twin
let mut seam = m.clone();
seam.indices[3] = 4;
assert_eq!(seam.wire_edges()[0].len(), 6);
// Appending keeps each side's diagonals on its own triangles.
// Appending preserves each side's own diagonals
let mut a = Mesh::from_parts(m.positions.clone(), None, m.uvs.clone(), vec![0, 1, 2], "A").unwrap();
a.append(&m);
assert_eq!(a.diagonals, vec![0, 0b100, 0b001]);
+16
View File
@@ -353,6 +353,13 @@ impl Default for BrushSettings {
}
impl BrushSettings {
/// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the
/// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it.
pub fn uv_stamp_radius(&self, pressure: f32) -> f32 {
let p = pressure.clamp(0.0, 1.0);
self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 }
}
/// Clamp every value into its valid range (input from UI, CLI or agents)
pub fn sanitized(&self) -> BrushSettings {
let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default };
@@ -392,6 +399,15 @@ impl BrushSettings {
#[cfg(test)]
mod tests {
#[test]
fn uv_stamp_radius_follows_pen_pressure() {
let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() };
assert!((b.uv_stamp_radius(1.0) - 0.2).abs() < 1e-6);
assert!((b.uv_stamp_radius(0.5) - 0.15).abs() < 1e-6);
assert!((b.uv_stamp_radius(0.0) - 0.1).abs() < 1e-6);
assert!((b.uv_stamp_radius(7.0) - 0.2).abs() < 1e-6, "pressure clamps to 1");
}
use super::*;
#[test]
+24 -18
View File
@@ -884,8 +884,10 @@ impl Renderer {
fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)),
],
);
// The display textures, the aux texture, the sampler
let textures = DisplayKind::ALL.len() as u32 + 1;
// Displacement reads the height (and the sampler) in the vertex shader
let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32;
let set_entries: Vec<_> = (0..textures)
@@ -922,7 +924,7 @@ impl Renderer {
attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2],
})];
// shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter
// RGBA8 fallback clips bright highlights and dark gradients
let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT };
let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend));
let always = || Some(depth_state(false, wgpu::CompareFunction::Always));
@@ -1259,6 +1261,7 @@ impl Renderer {
if self.mesh.as_ref().is_some_and(|m| m.id == id) {
return;
}
let verts = subdivide::vertices(mesh);
let mk = |label: &str, data: &[u8], usage: wgpu::BufferUsages| upload_buffer(device, queue, label, data, usage);
let mut idx_bytes = bytemuck::cast_slice::<u32, u8>(&mesh.indices).to_vec();
@@ -1266,7 +1269,8 @@ impl Renderer {
let vb = mk("tc_vb", bytemuck::cast_slice(&verts), wgpu::BufferUsages::VERTEX);
let ib = mk("tc_ib", &idx_bytes, wgpu::BufferUsages::INDEX);
let draws: Vec<(u32, u32, usize)> = mesh.submeshes.iter().map(|s| (s.start, s.count, s.material)).collect();
// Mesh edges per material (polygons, not their triangles), for the wireframes.
// Use polygon edges for each material's wireframe
let mut line_idx: Vec<u32> = Vec::new();
let mut line_draws = Vec::new();
for (m, edges) in mesh.wire_edges().into_iter().enumerate() {
@@ -1896,10 +1900,11 @@ impl Renderer {
if sample >= TAA_SAMPLES {
return;
}
let aspect = frame.size[0].max(1) as f32 / frame.size[1].max(1) as f32;
let mut vp = frame.camera.view_proj(aspect);
if sample > 0 {
// Sub-pixel jitter in clip space: a box filter over the pixel once averaged.
// Sub-pixel jitter averages into a box filter
let (jx, jy) = (halton(sample, 2) - 0.5, halton(sample, 3) - 0.5);
vp = Mat4::from_translation(Vec3::new(2.0 * jx / frame.size[0].max(1) as f32, 2.0 * jy / frame.size[1].max(1) as f32, 0.0)) * vp;
}
@@ -1911,13 +1916,13 @@ impl Renderer {
(1.0, [sx, sy, pan[0], pan[1]])
}
};
// Data views (channels, mesh maps, UV checker, the 2D view) show values as they are: no
// exposure, tone mapping, effects or shadows.
// Data views bypass exposure, tone mapping, effects and shadows
let data = uv_view > 0.5 || s.view_mode != 0;
let fx = |v: f32| if s.post_effects && !data { v.clamp(0.0, 1.0) } else { 0.0 };
let bloom = fx(s.bloom) > 0.0;
// The key light lives in the environment: turn it with it (the inverse of env_rotate in
// mesh.wgsl maps environment directions to world directions).
// Turn the key light with the environment
let (sin, cos) = s.env_rotation_deg.to_radians().sin_cos();
let [lx, ly, lz, lw] = s.light;
let light = Vec3::new(cos * lx + sin * lz, ly, cos * lz - sin * lx);
@@ -1926,19 +1931,19 @@ impl Renderer {
self.ensure_dense(device, queue);
}
let disp = match self.mesh.as_ref().filter(|_| displace) {
// Height-to-normal's slope: strength 1 tilts 45° for a height change of 1 over 1/16 of
// the UV square; the vertex shader samples the mip whose texels match the vertex spacing.
// A unit height across 1/16 of UV space tilts 45°; use the mip nearest vertex spacing
Some(m) => [1.0, m.world_per_uv / 16.0, 1.0 / (m.dense.as_ref().unwrap_or(&m.geo).triangles.max(1) as f32 * 0.5).sqrt(), 0.0],
None => [0.0; 4],
};
let shadow_disp = [disp[0], disp[1] * s.height_strength, disp[2], 0.0];
let shadow_vp = if !data && s.shadows && lw > 0.0 { self.update_shadow(device, queue, encoder, light, shadow_disp, &frame.visible) } else { None };
let radius = self.mesh.as_ref().map_or(1.0, |m| m.radius);
// Background rays come from a perspective camera even in orthographic views (an ortho
// ray grid would show a single flat environment color).
// Perspective background rays prevent flat color in orthographic views
let bg_vp = OrbitCamera { ortho: false, ..frame.camera }.view_proj(aspect);
let e = frame.camera.eye();
// Scene effects (3D material view; they need float targets for depths and signed light).
// Scene effects need float targets for depths and signed light
let scene_fx = !data && frame.kind == ViewKind::Scene && self.hdr_format == HDR_FORMAT && self.mesh.is_some();
let dof = s.dof.filter(|_| scene_fx);
let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0));
@@ -1947,7 +1952,8 @@ impl Renderer {
let cam = &frame.camera;
let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan();
let height = frame.size[1].max(1) as f32;
// Pixels per world unit at view depth z: k / z in perspective, k in orthographic views.
// Perspective pixels per world unit vary with depth
let k = if cam.ortho { height / (2.0 * cam.distance.max(1e-6) * half_h) } else { height / (2.0 * half_h) };
let ppw = |z: f32| if cam.ortho { k } else { k / z.max(1e-6) };
let dof_c = dof.map_or([0.0; 4], |[focus, aperture]| {
@@ -1967,7 +1973,7 @@ impl Renderer {
uv_xform,
light: [light.x, light.y, light.z, lw],
light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(),
// Normal offset: 1.5 shadow texels of the light frustum (2 × radius wide).
// Offset by 1.5 shadow texels to avoid self-shadowing
shadow: [if shadow_vp.is_some() { 1.0 } else { 0.0 }, 1.0 / SHADOW_SIZE as f32, radius * 3.0 / SHADOW_SIZE as f32, 0.0],
material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior],
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }],
@@ -2000,9 +2006,7 @@ impl Renderer {
}
let weight = 1.0 / f64::from(sample + 1);
match v.fx.as_ref().filter(|_| fx_on) {
// The effects run on every frame before it joins the average, so idle accumulation
// also smooths the depth of field's sampling pattern (turned each frame). Their
// G-buffer (unjittered) stays valid while the view accumulates.
// Effects run before averaging; the unjittered G-buffer remains valid
Some(f) => {
self.scene_pass(encoder, v, &v.hdr, globals_bg, frame);
if sample == 0 {
@@ -2138,7 +2142,8 @@ impl Renderer {
None => (&self.mesh_pipeline, frame.shade.wireframe_3d.then_some(&self.wire3d_pipeline)),
Some(_) => (&self.uv_pipeline, frame.shade.wireframe.then_some(&self.wire_pipeline)),
};
// Transmissive surfaces refract what the behind pass rendered this frame.
// Transmissive surfaces refract the current behind pass
let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg);
let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set));
self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr);
@@ -2260,6 +2265,7 @@ impl Renderer {
let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true);
let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref());
// The translucent faces first, then the wireframe over them
if bake.cage_surface.shown {
pass.set_pipeline(&self.cage_pipeline);
+9 -4
View File
@@ -124,7 +124,7 @@ fn fs_wire_cage_missing_seam(surface: BakeViewOut) -> @location(0) vec4<f32> {
return g.bake_missing_seam;
}
// The neutral material at the texture set's normal `n` (over the mesh normal `n_geo`) seen from direction `v`, darkened by its occlusion `ao_channel`, lit along the packed bent normal `packed_bent` when it is on
// Shade the neutral material using the texture set's normal, occlusion and optional bent normal
fn neutral_color(n: vec3<f32>, n_geo: vec3<f32>, v: vec3<f32>, world_position: vec3<f32>, ao_channel: f32, packed_bent: vec3<f32>) -> vec4<f32> {
let albedo = g.bake_neutral_color.rgb;
let rough = clamp(g.bake_neutral.x, MIN_NEUTRAL_ROUGHNESS, 1.0);
@@ -140,6 +140,7 @@ fn neutral_color(n: vec3<f32>, n_geo: vec3<f32>, v: vec3<f32>, world_position: v
let diffuse = sh_irradiance(normalize(mix(n, bent, g.bake_bent_normal.x)), vec3<f32>(0.0)) * diffuse_col * ao;
let r = reflect(-v, n);
let horizon = clamp(1.0 + HORIZON_FADE * dot(r, n_geo), 0.0, 1.0);
// Reflections pointing away from the open direction are occluded
let bent_occlusion = mix(1.0, smoothstep(BENT_OCCLUSION_START, BENT_OCCLUSION_END, dot(bent, r)), g.bake_bent_normal.y);
let spec = sampled_reflection(n, v, rough, f0, nov) * ao * bent_occlusion * horizon * horizon;
@@ -159,7 +160,7 @@ fn neutral_color(n: vec3<f32>, n_geo: vec3<f32>, v: vec3<f32>, world_position: v
return vec4<f32>(select(color, vec3<f32>(0.0), any(color != color)), 1.0);
}
// The environment's GGX reflection at normal `n`, importance sampled with this frame's share of the neutral material's quality; each accumulated frame takes other samples
// Importance sample the environment's GGX reflection with a new sequence each frame
fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov: f32) -> vec3<f32> {
let count = max(u32(g.bake_neutral_color.w), 1u);
let a = rough * rough;
@@ -170,6 +171,7 @@ fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov
let tangent = normalize(cross(side, n));
let bitangent = cross(n, tangent);
let frame_offset = u32(g.material.z) * count;
// Schlick-GGX geometry term at k = a / 2
let k = a * 0.5;
let view_visibility = nov / (nov * (1.0 - k) + k);
@@ -178,7 +180,8 @@ fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov
for (var index = 0u; index < count; index++) {
let xi = vec2<f32>(fract((f32(index) + 0.5) / f32(count) + f32(g.material.z) * GOLDEN_RATIO_FRACTION), radical_inverse(index + frame_offset));
let phi = 2.0 * PI * xi.x;
// Clamped: near roughness 0 the ratio rounds a hair past 1, and the sine's square root would be NaN (a black pixel once frames accumulate)
// Clamp cosine before computing its sine to avoid NaN near zero roughness
let cos_theta = clamp(sqrt((1.0 - xi.y) / (1.0 + (a2 - 1.0) * xi.y)), 0.0, 1.0);
let sin_theta = sqrt(1.0 - cos_theta * cos_theta);
let h = normalize(tangent * (cos(phi) * sin_theta) + bitangent * (sin(phi) * sin_theta) + n * cos_theta);
@@ -193,13 +196,15 @@ fn sampled_reflection(n: vec3<f32>, v: vec3<f32>, rough: f32, f0: vec3<f32>, nov
let voh = clamp(dot(v, h), MIN_COSINE, 1.0);
let denominator = max(noh * noh * (a2 - 1.0) + 1.0, MIN_GGX_DENOMINATOR);
let pdf = a2 / (PI * denominator * denominator) * noh / (4.0 * voh);
// Filtered importance sampling: each sample reads the mip that covers its share of the lobe
let lod = clamp(0.5 * log2(1.0 / (f32(count) * pdf * texel_solid_angle)) + FILTERED_SAMPLING_LOD_BIAS, 0.0, g.env.y);
let light = textureSampleLevel(env_tex, env_samp, env_uv(l), lod).rgb;
let fresnel = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
let visibility = view_visibility * nol / (nol * (1.0 - k) + k);
let contribution = light * fresnel * (visibility * voh / (noh * nov));
// A sample that still came out NaN (x != x) is dropped: the frame average would carry it, and post effects spread it over the image
// Drop NaN samples before they contaminate the frame average
sum += select(contribution, vec3<f32>(0.0), any(contribution != contribution));
}
return sum / f32(count);
+24 -19
View File
@@ -411,8 +411,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
let hu = textureSample(t_height, samp, uv - vec2<f32>(0.0, ts.y)).r;
let hd = textureSample(t_height, samp, uv + vec2<f32>(0.0, ts.y)).r;
// Tangent-space normal: height gradient (+Y = up the image) combined with the normal channel.
// Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width.
// Match export: a unit height over 1/16 of the width tilts 45°
// Combine the height gradient with the tangent-space normal
let k = g.mode.z * dims.x / 16.0 * tile_scale(uv);
let n_height = normalize(vec3<f32>(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0));
var n_detail = snorm8(nrm_s);
@@ -426,6 +426,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
if (ch >= 11) {
return unlit(lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a, extra));
}
switch ch {
case 0: { return unlit(data_out(base_s.rgb)); }
case 1: { return unlit(data_out(vec3<f32>(orm.b))); }
@@ -443,6 +444,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
if (mode == 2) {
return unlit(raw_out(aux.rgb));
}
if (mode == 3) {
let c = floor(uv * 32.0);
let chk = (c.x + c.y) - 2.0 * floor((c.x + c.y) * 0.5);
@@ -458,7 +460,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
return Shaded(neutral_color(n, n_geo, v, i.wpos, orm.r, aux.rgb), vec3<f32>(0.0));
}
// Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out).
// Change the alpha dither each frame so accumulation smooths it
if (base_s.a < hash12(i.clip.xy + g.material.z * vec2<f32>(17.0, 59.0))) {
discard;
}
@@ -471,25 +473,27 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
var f0 = mix(vec3<f32>(0.08 * orm.a), albedo, metal);
var diffuse_col = albedo * (1.0 - metal);
if (g.material.x > 0.5) {
// Specular/glossiness: the Specular color is F0 and base color the diffuse color, with
// the energy the specular takes removed (roughness already is 1 - glossiness).
// Specular color gives F0; remove its energy from diffuse
f0 = hgt.gba;
diffuse_col = albedo * (1.0 - max(f0.r, max(f0.g, f0.b)));
}
// Transmission: that part of the dielectric base refracts instead of reflecting diffusely.
// Transmission removes energy from the dielectric diffuse base
let trans = extra.b * (1.0 - metal);
diffuse_col *= 1.0 - trans;
// The extra lobes; their defaults (weights 0) leave the base shading as it is.
// Zero lobe weights preserve the base shading
let coat_w = lobes.r;
let coat_rough = clamp(lobes.g, 0.045, 1.0);
let aniso = lobes.b;
let sheen_col = sheen_t.rgb * sheen_t.a;
let sheen_max = max3(sheen_col);
let sheen_rough = clamp(nrm_t.a, 0.07, 1.0);
// Subsurface scattering: wrapped diffuse, wider for the channels the scatter color carries further.
// Scatter color controls each channel's diffuse wrap
let wrap = emis_t.a * g.scatter.xyz;
// Anisotropy: GGX roughness stretched along the mesh tangent turned by the angle (0..1 → 0..π).
// Stretch GGX along the tangent rotated by 0..π
let a = rough * rough;
let at = max(a * (1.0 + aniso), 0.002);
let ab = max(a * (1.0 - aniso), 0.002);
@@ -498,8 +502,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
let ta1 = ta0 - n * dot(n, ta0);
let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8));
let ba = cross(n, ta);
// The clear coat follows the mesh normal (not the normal and height channels), turned by the
// coat normal channel where it is painted (the flat default keeps the mesh normal exactly).
// Coat normals perturb the geometric normal independently of base detail
var n_c = n_geo;
let cn = coat_normal_ts(extra);
if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) {
@@ -507,7 +511,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
}
let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0);
let coat_t = 1.0 - coat_w * schlick(0.04, nov_c);
// What reaches the layers below: the coat's transmission and the sheen albedo scaling.
// Coat transmission and sheen albedo limit energy reaching the base
var base_scale = coat_t;
var sheen_e = 0.0;
if (sheen_max > 0.0) {
@@ -518,12 +523,13 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
let diffuse = sh_irradiance(n, wrap) * diffuse_col * ao;
var r = reflect(-v, n);
if (aniso > 0.0) {
// Bent reflection vector: the standard real-time approximation of anisotropic IBL.
// Bend the reflection to approximate anisotropic IBL
let bent = cross(cross(ba, v), ba);
r = reflect(-v, normalize(mix(n, bent, aniso * clamp(5.0 * rough, 0.0, 1.0))));
}
let pre = textureSampleLevel(env_tex, env_samp, env_uv(r), rough * g.env.y).rgb;
// Horizon fading: reflections that point below the geometric surface are dimmed.
// Fade reflections below the geometric surface
let horizon = clamp(1.0 + 1.3 * dot(r, n_geo), 0.0, 1.0);
let spec = pre * env_brdf(f0, rough, nov) * ao * horizon * horizon;
var layers = vec3<f32>(0.0);
@@ -537,16 +543,14 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
}
if (trans > 0.0) {
// shortcut: one refraction interface (no exit); the path tracer refracts through the
// whole mesh.
// Approximate one refraction interface; the path tracer also handles the exit
var td = refract(-v, n, 1.0 / max(g.material.w, 1.0));
if (dot(td, td) < 1e-6) {
td = reflect(-v, n);
}
var behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb;
if (g.refr.x > 0.5) {
// Screen-space refraction: the opaque scene where the refracted ray lands on screen,
// over the environment where that shows nothing (or the ray leaves the view).
// Composite the refracted screen sample over the environment fallback
let p = g.view_proj * vec4<f32>(i.wpos + td * g.refr.z, 1.0);
let s = p.xy / max(p.w, 1e-6);
let suv = vec2<f32>(s.x * 0.5 + 0.5, 0.5 - s.y * 0.5);
@@ -575,7 +579,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded {
dv = ggx_dv(a, nov, nol, noh);
}
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
// Energy-conserving wrapped Lambert (plain Lambert where nothing scatters).
// Normalize wrapped Lambert to conserve energy
let diff_nol = max((nol_raw + wrap) / ((1.0 + wrap) * (1.0 + wrap)), vec3<f32>(0.0));
direct_diffuse = (vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol * (g.light.w * base_scale);
direct = ((vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol + dv * f * nol) * (g.light.w * base_scale);
+3 -1
View File
@@ -265,7 +265,7 @@ fn bake_neutral_material_shades_the_low_poly_in_its_settings() {
#[test]
fn bake_neutral_material_looks_the_same_moving_as_still() {
// A moving view only ever shows its first frame; with the whole quality in it, it stays close to the settled image (one sample a frame was 6.6 levels off)
// Full quality keeps the first frame near settled; one sample missed by 6.6 levels
const MAX_MEAN_LEVELS: f32 = 4.0;
let Some((mut h, frame)) = setup() else { return };
@@ -280,6 +280,7 @@ fn bake_neutral_material_looks_the_same_moving_as_still() {
render(&mut h, &still, "bake_neutral_settling");
}
let settled = render(&mut h, &still, "bake_neutral_settled");
// Compared on the ball in the middle of the view, where the reflections are
let (width, height) = (frame.size[0], frame.size[1]);
let ball = (width * 3 / 8..width * 5 / 8).flat_map(|x| (height / 4..height / 2).map(move |y| (x, y)));
@@ -424,6 +425,7 @@ fn oversized_bake_high_poly_leaves_the_view_renderable() {
let high = primitives::sphere(0.5, 16, 8);
headless.renderer.set_bake_high(&headless.device, &headless.queue, Some(&high), 1).unwrap();
let limit = headless.device.limits().max_buffer_size;
// The viewport vertex contains position, normal, tangent and UV: twelve f32 values
let vertex_count = limit as usize / (12 * std::mem::size_of::<f32>()) + 1;
let oversized = texturecraft_geom::Mesh { positions: vec![Vec3::ZERO; vertex_count], ..Default::default() };
@@ -48,6 +48,7 @@ pub(crate) fn bake_warnings(app: &TextureCraftApp, ctx: &egui::Context, viewport
pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc<Vec<String>> {
let id = egui::Id::unique("bake_check_warnings");
let key = inputs_key(session);
// A handle, not an address: a rebuilt high poly could reuse a dropped one's address
let high = session.bake_meshes.merged_high().map_or_else(Weak::new, |high| Arc::downgrade(&high.mesh));
if let Some((cached_key, cached_high, cached)) = ctx.data(|data| data.get_temp::<(String, Weak<Mesh>, Arc<Vec<String>>)>(id))
@@ -45,6 +45,7 @@ pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view:
// Its own backing, so the panel reads in every theme over whatever the 3D view shows
egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| {
ui.set_width(PANEL_WIDTH);
// Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over
let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true);
if header(ui, toggles, collapsing_state.is_open()).clicked() {
@@ -132,6 +133,7 @@ fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, rese
ui.set_min_height(EYE_BUTTON_SIZE);
let text = egui::RichText::new(format!("{} {title}", section_chevron(ui, collapsing_state.is_open()).text())).strong().color(tokens.text_strong);
let header = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click()));
// Dimmed while the section is closed, as the reference draws it
let reset = resettable.then(|| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+1
View File
@@ -50,6 +50,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() {
app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled }));
}
// The name takes the room the resolution leaves, so it only shortens when the row is too narrow
let resolution_text = format!("{resolution}x{resolution}");
let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0);
@@ -65,7 +65,7 @@ impl BakeSceneLink {
}
self.reach.sync(session, self.high_id, visualization.only_set, out);
} else if self.high_sent {
// A hidden high poly leaves the GPU; showing it again sends it and its colours under the same id, so its reach is not worked out again
// Drop the hidden GPU mesh but keep its id so its reach can be reused
out.bake_high = Some((None, self.high_id));
self.high_sent = false;
self.reach.resend();
@@ -90,6 +90,7 @@ impl BakeSceneLink {
}
self.cages.truncate(set_count);
self.cages.resize_with(set_count, || None);
let mut shared_edges = None;
for (texture_set, link) in self.cages.iter_mut().enumerate() {
let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue };
@@ -100,11 +101,26 @@ impl BakeSceneLink {
if link.max_frontal == max_frontal {
continue;
}
link.max_frontal = max_frontal;
}
_ => {
self.next_topology += 1;
let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new);
let shell = session
.bake_cage_inputs(texture_set)
.ok()
.flatten()
.and_then(|inputs| {
let result = if inputs.uses_mesh(&session.mesh) {
let (wire_edges, missing_seam_edges) =
shared_edges.get_or_insert_with(|| (session.mesh.wire_edges(), session.mesh.missing_seam_edges()));
inputs.cage_shell_with_edges(wire_edges, missing_seam_edges)
} else {
inputs.cage_shell()
};
result.ok()
})
.map(Arc::new);
*link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal });
}
}
@@ -199,6 +215,7 @@ mod tests {
texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap();
let rebuilt = sync(&mut link, &session, everything());
assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage");
// The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts
red_share(&mut link, &session, everything());
+32 -2
View File
@@ -64,7 +64,11 @@ impl ReachLink {
.enumerate()
.map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone())))
.collect();
if keys != self.keys || high_id != self.high_id {
// The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild
self.reach.clear();
let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect();
self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || {
inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect()
@@ -99,8 +103,31 @@ mod tests {
use texturecraft_engine::core::BakePaintTarget;
use texturecraft_engine::geom::primitives;
#[test]
fn rebuilding_reach_releases_previous_vertex_arrays_before_starting_work() {
const PREVIOUS_SET_COUNT: usize = 2;
const PREVIOUS_VERTEX_COUNT: usize = 64;
let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
let mut link = ReachLink {
reach: (0..PREVIOUS_SET_COUNT).map(|_| Some(HighPolyReach { vertices: vec![None; PREVIOUS_VERTEX_COUNT], ..Default::default() })).collect(),
..Default::default()
};
let mut out = SceneSync::default();
link.sync(&session, 1, None, &mut out);
let retained_slots: usize = link.reach.iter().flatten().map(|reach| reach.vertices.capacity()).sum();
assert_eq!(retained_slots, 0, "obsolete CPU arrays must not overlap their replacements");
assert!(out.bake_high_missed.is_none(), "the GPU keeps its displayed colors until the replacement arrives");
}
#[test]
fn input_changes_wait_for_the_running_reach_then_use_the_latest_inputs() {
const WAIT_FRAMES: usize = 2000;
const WAIT_FRAME_PAUSE: Duration = Duration::from_millis(5);
let mut session = Session::new_project("Reach", primitives::plane(1.0, 1), "plane", None, 128).unwrap();
session.add_high_poly_bytes("high.obj", b"v 0 0.1 0\nv 0.1 0.1 0\nv 0 0.1 0.1\nf 1 2 3\n".to_vec()).unwrap();
let (sender, receiver) = mpsc::channel();
@@ -113,6 +140,7 @@ mod tests {
link.sync(&session, 2, None, &mut out);
assert!(out.bake_high_missed.is_none());
}
assert!(sender.send(Vec::new()).is_ok(), "input changes must keep the running job's receiver");
link.poll();
@@ -123,13 +151,15 @@ mod tests {
assert!(link.busy());
assert!(out.bake_high_missed.is_none());
for _ in 0..2000 {
for _ in 0..WAIT_FRAMES {
link.poll();
if !link.busy() {
break;
}
std::thread::sleep(Duration::from_millis(5));
std::thread::sleep(WAIT_FRAME_PAUSE);
}
assert!(!link.busy(), "the latest reach must finish");
link.sync(&session, 2, None, &mut out);
let (high_id, missed) = out.bake_high_missed.unwrap();
+1
View File
@@ -388,6 +388,7 @@ impl CallbackTrait for ViewCallback {
reports.memory.push(texture_set);
}
}
// This frame's report drain already ran: the next frame shows the toast
gpu.ctx.request_repaint();
}
+2 -2
View File
@@ -551,7 +551,7 @@ fn spawn_worker<T: Send + 'static>(name: &str, f: impl FnOnce() -> T + Send + 's
let _ = tx.send(f());
});
if let Err(e) = spawned {
// The receiver reports a stopped worker.
// The receiver reports a stopped worker
log::warn!("could not start {name}: {e}");
}
rx
@@ -559,7 +559,7 @@ fn spawn_worker<T: Send + 'static>(name: &str, f: impl FnOnce() -> T + Send + 's
#[cfg(target_arch = "wasm32")]
fn spawn_worker<T: Send + 'static>(_name: &str, f: impl FnOnce() -> T + Send + 'static) -> std::sync::mpsc::Receiver<T> {
// shortcut: no threads on the web; the work runs on the UI thread (the window pauses).
// Web builds run the work synchronously because threads are unavailable
let (tx, rx) = std::sync::mpsc::channel();
let _ = tx.send(f());
rx
+51 -8
View File
@@ -85,6 +85,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
let divider_x = split_divider_x(app, ui, full);
let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y));
let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max);
// Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour
let clip = ui.clip_rect();
ui.set_clip_rect(left.intersect(clip));
@@ -372,14 +373,16 @@ const VIEW_HEADER_TOP_GAP: f32 = 8.0;
/// Width of each of the two pickers
const VIEW_PICKER_WIDTH: f32 = 130.0;
/// Where `view_header` draws its pickers in a view of `rect`; `None` when the view is too narrow.
fn view_header_rect(rect: Rect) -> Option<Rect> {
(rect.width() >= VIEW_HEADER_WIDTH).then(|| {
Rect::from_min_size(rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP), vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT))
})
}
/// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them
fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
if rect.width() < VIEW_HEADER_WIDTH {
return;
}
let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP);
let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT));
let Some(header) = view_header_rect(rect) else { return };
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center)));
let current = texturecraft_engine::camera_cmds::current(&app.session);
@@ -1558,8 +1561,11 @@ fn brush_drag_button(resp: &egui::Response) -> Option<bool> {
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.
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
// Keep the values clear of the pointer and the brush cursor at its press origin
if ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| resp.rect.contains(p)) {
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)
@@ -1824,6 +1830,27 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
}
}
// Match the 3D view's stamp size and hardness
let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held;
let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p));
if cursor_mode
&& !path_tool
&& brush_tool(app.session.tool.tool)
&& !response.dragged_by(PointerButton::Middle)
// Egui keeps hover during drags; adjustment may continue outside the view
&& (adjusting || pointer_in_view)
// Keep the brush outline at the press origin while adjusting
&& let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) }
// Header pickers need the normal pointer
&& !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(hp))
{
// Match the pressure-scaled radius used by continue_stroke_uv
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);
if pointer_in_view {
ui.ctx().set_cursor_icon(egui::CursorIcon::None);
}
brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness);
}
brush_readout(app, ui, &response, adjusting);
view_header(app, ui, rect, "v2d");
axis_gizmo(ui, rect, app, true);
@@ -1831,6 +1858,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), 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
})
.collect();
p.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0));
}
p.circle_filled(c, 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.
fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) {
let pressure = pen_pressure(ui);
+143
View File
@@ -0,0 +1,143 @@
//! The 2D view hides the system pointer and draws the brush outline under it while painting.
use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase};
use egui_kittest::Harness;
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
}
fn cursor(h: &Harness<'_, TextureCraftApp>) -> CursorIcon {
h.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");
}
#[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);
}
/// 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>) {
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),
_ => {}
}
}
let mut out = Vec::new();
h.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, c, &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 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
});
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");
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());
}
#[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);
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);
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 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);
}
#[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 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);
}
+6
View File
@@ -483,6 +483,7 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() {
let mut harness = harness(None);
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
// Without a high poly everything that needs one shows greyed, as in the reference
for needs_high in ["Match", "Max Frontal Distance", "Edge Protection"] {
assert!(harness.get_by_label(needs_high).accesskit_node().is_disabled(), "{needs_high} is greyed");
@@ -576,8 +577,10 @@ fn texture_set_names_show_in_full_beside_their_resolution() {
harness.state_mut().session.doc.project.texture_sets[0].name = "LowerTorso".into();
harness.state_mut().ui.dock.focus(Panel::TextureSetList);
harness.run_steps(3);
// "LowerTorso" is about 75 points wide; cut short it collapses to an ellipsis of about 20
const FULL_NAME_MIN_WIDTH: f32 = 60.0;
// The breadcrumb names the set too; the list row is the top-most
let row = harness.get_all_by_label("LowerTorso").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap();
let width = row.rect().width();
@@ -612,6 +615,7 @@ fn the_eye_greys_the_baking_meshes_and_holds_the_project_mesh() {
assert!(harness.get_by_label(greyed).accesskit_node().is_disabled(), "{greyed} is greyed");
}
assert!(harness.state().ui.bake_visualization.project_mesh.shown);
// The header, not its "Reset Project Mesh (LP)" button further right
let header = harness.get_all_by_label_contains("Project Mesh (LP)").min_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap();
header.click();
@@ -625,9 +629,11 @@ fn picking_material_while_painting_keeps_bake_modes_neutral_material() {
let mut harness = harness(None);
harness.state_mut().ui.mode = Mode::Painting;
harness.run_steps(3);
// Painting mode shows the 3D and 2D views, each with a view menu; the 3D view's comes first
harness.get_all_by_value("Material").next().unwrap().click();
harness.run_steps(3);
// The menu entry, not the dropdown that shows the same word
let entry = harness.get_all_by_label("Material").find(|node| node.accesskit_node().role() != Role::ComboBox).unwrap();
entry.click();
+1
View File
@@ -28,6 +28,7 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() {
let mut h = harness();
h.get_by_label("Skew Correction");
assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on);
// Off: a drag in the view paints nothing
h.drag_at(STROKE_START);
h.hover_at(STROKE_END);
+2 -34
View File
@@ -8,7 +8,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi
- Review-only requests call for findings; requests to fix or improve also authorize focused local edits
- A review may conclude that no changes are needed. If the PR meets the applicable standards and no actionable issues are found, leave it unchanged. Do not invent findings, add unnecessary tests, or make edits merely to produce a diff. Report what was checked and any remaining validation limits
- Apply all review standards across the entire affected method, including existing code and relevant tests
- Complete naming, spacing, and comment cleanup throughout it
- Read and apply [CODE_STYLE.md](../CODE_STYLE.md) throughout that scope
- Make additional correctness or performance changes when supported by evidence and appropriate validation
- Separate substantial changes that address an independent problem, explaining why
- Apply the same scope to standalone functions and inspect relevant callers when verifying behavior
@@ -27,6 +27,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi
## Optimization and simplicity
- Prefer the smallest complete solution that is efficient and easy to understand
- Keep control flow direct and share repeated logic when it makes the code simpler
- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access
- For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions
- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost
@@ -35,39 +36,6 @@ Use these preferences when reviewing and improving a PR. Follow repository requi
- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations
- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity
## Clarity, naming, and spacing
- Clean up the functions or methods being changed and their relevant tests within the scope above
- Use descriptive names that explain purpose; include units where useful
- Avoid cryptic abbreviations, misleading names, and unexplained production constants
- Keep control flow direct and share repeated logic when it makes the code simpler
- Use a single blank line to separate logical steps, such as input preparation, validation, computation, mutation, and result construction, when those steps are distinct
- Keep closely related statements together; avoid spacing that fragments a single operation or inserts a blank line after every declaration
- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before the next statement
- Keep comments attached to the code they explain; put a blank line before a comment introducing a new step, with no blank line between the comment and that step
- Keep documentation and attributes attached to their declarations
- Separate function definitions with one blank line; avoid extra empty lines immediately inside braces or between every field, argument, or statement
- Group tests into preparation, action, and verification with blank lines where those phases are distinct; keep related assertions together
- Apply this spacing consistently throughout affected functions, methods, and tests, and follow the repository's formatter for mechanical formatting
## Source organization
- Keep each class, enum, or struct in its own source file, with its implementation beside it
- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust
- Use singular folder names, such as `map`, `setting`, or `tracing`
- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file
- Apply these preferences to new types and source organization changes within scope; follow mandatory repository layout rules and leave unrelated existing structure alone
## Comments
- Use short, single-line comments; adjacent comment lines should each express a concise point
- Avoid block comments and wrapped prose in ordinary implementation comments
- Explain intent or a non-obvious constraint rather than narrating the code
- No trailing punctuation on ordinary code comments
- Preserve explanations of guards and invariants; remove stale or redundant comments without losing necessary rationale
- API documentation, required license headers, and examples may use their conventional multiline formatting and punctuation
- Apply these standards to both production code and tests
## Validation and reporting
- Run relevant tests and required repository checks with the project's expected toolchain
+25
View File
@@ -12,6 +12,31 @@ Run a feature module with a test-name filter, for example:
cargo test -p texturecraft-engine --test it bake::
```
For faster optimized local verification, run the same workspace tests and doctests
with the `verify` profile:
```sh
cargo test --workspace --profile verify
```
`verify` inherits the release profile's optimization level and runtime checks, but
uses 16 codegen units and `lto = false`. Cargo retains thin LTO within each crate
without repeating cross-crate LTO for every test executable. The existing test
selection and ignore attributes still apply. Keep the target directory between
runs so Cargo can reuse unchanged build artifacts.
To compile the normal application binaries alongside the test binaries before
running them:
```sh
cargo build --workspace --bins --tests --profile verify
cargo test --workspace --profile verify
```
This profile is for local verification. Use `--release` for release validation and
performance measurements; its compiler settings remain unchanged. The regular
debug test profile and CI gates also remain unchanged.
The standalone engine `session` target and UI `ui_snapshots` target remain
available for the commands in `AGENTS.md`. Existing ignore attributes are
unchanged. Tests in the shared executable can run concurrently across modules;
+3 -2
View File
@@ -15,7 +15,7 @@ usage: cargo xtask <command>
commands:
layers enforce the crate dependency layering (xtask/src/layers.rs)
wasm cargo check --target wasm32-unknown-unknown for the wasm crates and the web app
ci fmt --check, clippy -D warnings, test, layers, wasm (stops at the first failure)
ci fmt --check, layers, clippy -D warnings, test, wasm (stops at the first failure)
version [set X.Y.Z[-pre]]
print the workspace version, or set it (Cargo.toml + Cargo.lock)
ico <out.ico> <in.png>...
@@ -154,11 +154,12 @@ fn cmd_ci() -> Result<(), String> {
}
};
type Step = (&'static str, Box<dyn Fn() -> Result<(), String>>);
// Reject invalid dependency layering before spending time compiling and running the workspace.
let steps: Vec<Step> = vec![
("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))),
("layers", Box::new(cmd_layers)),
("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))),
("test", Box::new(cargo_step(&["test", "--workspace"]))),
("layers", Box::new(cmd_layers)),
("wasm", Box::new(cmd_wasm)),
];
for (i, (name, step)) in steps.iter().enumerate() {