From 795d798deffaedb9b1f86f5de9dfb2cbe8242001 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:11:13 -0800 Subject: [PATCH] craft-mesh-ops: the crate is the TextureCraft geometry code moved as it is Replace the crate's sources with TextureCraft crates/geom at 386630e and MaterialCraft Mesh::subdivided at 3133062, with their tests, so this pull request is the move alone. The crate keeps the sources' dependencies and behavior; rustfmt is applied at this repository's 150 columns. Fixes to the moved code go in separate pull requests. --- NOTICE | 3 - README.md | 3 +- crates/mesh-ops/Cargo.toml | 14 +- crates/mesh-ops/README.md | 145 +- crates/mesh-ops/src/bvh.rs | 360 +---- crates/mesh-ops/src/camera.rs | 179 +-- crates/mesh-ops/src/gbuffer.rs | 608 +------- crates/mesh-ops/src/lib.rs | 184 +-- crates/mesh-ops/src/mesh.rs | 2246 +++-------------------------- crates/mesh-ops/src/primitives.rs | 385 +---- crates/mesh-ops/src/unwrap.rs | 944 ++---------- 11 files changed, 555 insertions(+), 4516 deletions(-) diff --git a/NOTICE b/NOTICE index 033755c349..e496aee57e 100644 --- a/NOTICE +++ b/NOTICE @@ -242,9 +242,6 @@ The mesh operations in crates/mesh-ops are moved from: 3133062968b8a1566eda12a357cb06062db16687. https://github.com/storytold/materialcraft Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors. - The index check before tangent generation and its two tests are from TextureCraft pull - request #386 by simonhull, revision faa4548a6f34bb61d43f56b3500edb73dd71981b - (https://github.com/storytold/texturecraft/pull/386). All licensed MIT OR Apache-2.0. The image-based lighting in crates/pbr (craft-pbr) is adapted from: diff --git a/README.md b/README.md index 286ecc92ec..2302266be6 100644 --- a/README.md +++ b/README.md @@ -320,8 +320,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft. - [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a - BVH for ray casts (feature `bvh`), with slice functions checked against `Limits`. From - TextureCraft and MaterialCraft. + BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft. - [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and 2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per quarter note. From SoundCraft. diff --git a/crates/mesh-ops/Cargo.toml b/crates/mesh-ops/Cargo.toml index fc68669c2d..441abc88c1 100644 --- a/crates/mesh-ops/Cargo.toml +++ b/crates/mesh-ops/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-mesh-ops" -description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a BVH, bounded on hostile input" +description = "Triangle mesh operations: smooth normals, MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs, a BVH and an orbit camera" version.workspace = true edition.workspace = true license.workspace = true @@ -10,17 +10,11 @@ repository.workspace = true [lints] workspace = true -[features] -default = [] -bvh = [] -parallel = ["dep:rayon"] -serde = ["dep:serde", "glam/serde"] - [dependencies] -glam = "0.30" +glam = { version = "0.30", features = ["serde"] } # MIT OR Apache-2.0; its src/generated.rs also carries the zlib-style notice of the C original, # reproduced in ATTRIBUTION.md. mikktspace = { version = "0.3", default-features = false, features = ["glam"] } -rayon = { workspace = true, optional = true } -serde = { workspace = true, optional = true } +rayon = { workspace = true } +serde = { workspace = true } thiserror = { workspace = true } diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 39062fb4ab..d7b1852d6a 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -4,104 +4,26 @@ Operations on triangle meshes, for apps that paint, bake or preview materials on crate has no UI, does no file or network I/O and has no `unsafe` code. File formats stay in [`craft-mesh`](../mesh/README.md). -- **Slice functions.** `bounds`, `smooth_normals`, `tangents`, `weld` and `unwrap_uvs` at the crate - root, `UvGBuffer::from_slices` and `Bvh::from_slices` take plain slices: positions and normals - as `[f32; 3]`, UVs as `[f32; 2]`, triangle indices as `u32`. They check the counts against - `Limits`, every index and every value (finite) before any work, and return a `MeshOpsError`. - Values are `f32`; a caller that holds `f64` converts first and rejects values outside the `f32` - range. +- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes + and polygon-diagonal flags, with `validate`, `append`, `subdivided`, `normalize_to`, wireframe + and UV-seam edges, and UV-tile helpers. - **Normals and tangents.** Smooth normals are area weighted. Tangents come from MikkTSpace, which glTF 2.0 recommends for meshes without tangents - (): `w` holds the bitangent sign, and - UVs have `(0, 0)` at the upper-left corner with `v` increasing downward. A mesh MikkTSpace - cannot handle (every triangle degenerate, no UV area, more than - `mesh::MAX_MIKKTSPACE_VALENCE` (2,048) triangles around one vertex, or so many corners at one - position that welding them would take more than `mesh::MAX_MIKKTSPACE_WELD_WORK` (2^27) - comparisons) gets per-vertex tangents, with `w` set as MikkTSpace sets it. - MikkTSpace gives each triangle corner its own frame: `Mesh::compute_tangents` splits a vertex - whose corners get different frames (UVs mirrored across it), and `tangents` returns an - `Invalid` error for such a vertex, since it returns one tangent per input vertex. When the - largest coordinate is above 1e6 or below 1e-6 in magnitude, normals and tangents are computed - from the positions divided by it, and finite input gives finite output. UVs passed to - `tangents` are divided the same way, and normals when their largest component is above 2 or - below 0.5. Normals are unit vectors, as glTF 2.0 stores them. -- **UV unwrapping.** `unwrap_uvs` and `unwrap::auto_unwrap` make a non-overlapping layout per - material, splitting vertices where charts meet. A face joins a chart only when its projection - onto the chart's plane does not overlap the chart's other faces, and every chart is packed at - a scale above zero. The charts are projected, measured and packed in `f64` from the positions - as given, so a small chart far from the origin keeps its shape. A mesh whose submeshes put one - triangle in two materials is an `Invalid` error. `weld` - gives vertices at the same position (on a grid of 1e-6 of the bounding diagonal) the same id, - numbered in order of first appearance. + (): `w` holds the bitangent sign. +- **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting + vertices where charts meet. - **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle and barycentrics under the texel center; `surface_at` turns them into a position, normal and - tangent frame. A triangle with a corner more than 1e18 texels from the UV origin is skipped. - A texel center counts as inside a triangle when it is no more than 1e-6 texel outside each - edge, plus the `f64` rounding of the edge function at the triangle's coordinates, and at most - 1e-3 of the triangle's smallest height. -- **Primitives.** `sphere`, `rounded_box`, `cube`, `cylinder`, `torus` and `plane`, and the - built-in scenes in `primitives::BUILTINS`, all with UVs and tangents. The `try_` forms return an - error for a non-finite or non-positive size, a size so large that a coordinate overflows `f32`, - or a segment count over `Limits::max_segments`; the other forms clamp the segment count and - return an empty mesh for an invalid size. -- **BVH** (feature `bvh`). Binned SAH on all three axes, with a median split on the widest - centroid axis when no split beats a leaf. Closest-hit, any-hit and filtered ray casts, the - nearest point within a distance, and box queries. Triangles with a non-finite corner are left - out of the tree. A ray with a non-finite origin or direction, a zero direction or a NaN - distance, a NaN box and a negative or NaN search distance find nothing. Ray casts find hits on - triangles with coordinates between about 1e-12 and 1e12; outside that range the products in - the triangle test overflow or underflow `f32`. The nearest-point - search does not find a point more than about 1.8e19 away, where the squared distance overflows - `f32`. -- **`Mesh`.** Positions, normals, tangents, UVs, vertex colors, indices, per-material submeshes - and polygon-diagonal flags, with `validate`, `append` and `try_append`, `subdivided` and - `try_subdivided`, wireframe and UV-seam edges, and UV-tile helpers. `OrbitCamera` and `Ray` - give an orbit view and picking rays; `OrbitCamera::frame` ignores a box whose center or framing - distance is not finite, and `OrbitCamera::zoom` ignores a distance at which the eye rounds to - the target. `OrbitCamera::ray` unprojects in `f64`. + tangent frame. +- **Primitives.** Sphere, rounded box, cube, cylinder, torus and plane with UVs and tangents, and + the built-in scenes in `primitives::BUILTINS`. +- **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a + leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box + queries. +- **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays. -Triangulation with holes, extrusion of 2D outlines and conversion from `craft_mesh::Mesh` are not -in the crate yet. - -## Cargo features - -No default features. - -| Feature | Provides | Pulls in | -|---|---|---| -| `bvh` | `Bvh`, `Hit` | nothing | -| `parallel` | the UV G-buffer rasterizes bands of rows on several threads; the result is the same | `rayon` | -| `serde` | `Serialize` and `Deserialize` for `OrbitCamera` | `serde`, `glam/serde` | - -Without `parallel` the crate builds for `wasm32-unknown-unknown`. - -## Limits - -| Field | Default | Checked by | -|---|---|---| -| `max_vertices` | 20,000,000 | every slice function, `try_subdivided`, the `try_` primitives (also after their tangents split vertices), `UvGBuffer::try_new`, `unwrap::auto_unwrap` (input and output), `Mesh::map_material_uvs` (the mesh's vertices and the copies of the vertices it shares with other materials) | -| `max_triangles` | 20,000,000 | the same except `auto_unwrap`, and `Bvh::from_slices`; the UV G-buffer also counts a triangle again each time another submesh of the material lists it; `Mesh::wire_edges`, `Mesh::uv_seam_edges`, `Mesh::uv_tiles` and `Mesh::map_material_uvs` count the triangles the submeshes list in the same way | -| `max_segments` | 2,048 | the `try_` primitives (segments, rings or subdivisions along one direction, after a count under the primitive's minimum is raised to it; a box face has 12, or 22 with a bevel) | -| `max_gbuffer_side` | 8,192 | `UvGBuffer::try_new`, `UvGBuffer::from_slices`; `UvGBuffer::new` clamps each side to `1..=8192` | -| `max_gbuffer_texels` | 2^26 (8,192 × 8,192) | the same | -| `max_gbuffer_work` | 2^32 | the same: the texels the rasterizer visits, summed over each triangle's bounding box clipped to the buffer | -| `max_gbuffer_bin_entries` | 2^26 | the same: one entry per triangle for each band of 32 rows its clipped box reaches | -| `max_unwrap_triangles` | 4,000,000 | `unwrap_uvs` and `unwrap::auto_unwrap`, for the mesh's triangles and for the triangles its submeshes list | - -A BVH holds at most `bvh::MAX_BVH_TRIANGLES` (2^31 − 1) triangles. - -`Bvh::from_slices`, `Bvh::try_new`, `UvGBuffer::try_new` and `UvGBuffer::from_slices` reserve all -their memory before using it. The other slice functions, `weld`, `Mesh::try_compute_normals`, -`Mesh::try_compute_tangents`, `Mesh::try_subdivided`, the `try_` primitives, `unwrap::weld_ids` -and the unwrap functions reserve their working memory and their results as they grow. Each -returns `MeshOpsError::OutOfMemory` when a reservation fails. `Bvh::new` then returns an empty -tree, `UvGBuffer::new` a 1 × 1 uncovered buffer, and `compute_normals` and `compute_tangents` -leave the mesh unchanged. `UvGBuffer::new` also returns that buffer when the input is over a -default limit. The UV G-buffer checks its work and band entries in a first pass over the -triangles, before it reserves its band lists (in one piece) or its texel buffers, so a request -over those limits returns `MeshOpsError::TooLarge`. The working memory of the `mikktspace` crate -is allocated inside it and is not reserved this way; it is a fixed multiple of the input the -limits allow. +`GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde` +serializes `OrbitCamera`; both are always on. ## Origin @@ -109,8 +31,6 @@ limits allow. |---|---| | `mesh.rs`, `bvh.rs`, `primitives.rs`, `gbuffer.rs`, `unwrap.rs`, `camera.rs` and their tests | TextureCraft `crates/geom` at [386630e](https://github.com/storytold/texturecraft/commit/386630ee85cb22679295b24013575d1aecb39ad2) | | `Mesh::subdivided` and `subdivision_shares_edge_midpoints` | MaterialCraft `crates/geom/src/mesh.rs` at [3133062](https://github.com/storytold/materialcraft/commit/3133062968b8a1566eda12a357cb06062db16687) | -| The index check in `Mesh::from_parts` and `compute_tangents`, and its two tests | TextureCraft [#386](https://github.com/storytold/texturecraft/pull/386) by simonhull, at `faa4548a` | -| `Limits`, `MeshOpsError::TooLarge` and `OutOfMemory`, the slice functions, the `try_` forms, the finite-value and overflow checks, the `bvh`, `parallel` and `serde` features | written here | MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md](ATTRIBUTION.md). @@ -120,38 +40,3 @@ MikkTSpace comes from the `mikktspace` crate; its notice is in [ATTRIBUTION.md]( |---|---| | TextureCraft | `texturecraft-geom` is the source. The app switches to this crate in its own pull request. | | MaterialCraft | `materialcraft-geom` is the source of `subdivided`. The app switches in its own pull request. | - -For both apps: - -| `*-geom` | craft-mesh-ops | -| --- | --- | -| `GeomError::Invalid` | `MeshOpsError::Invalid`, plus `TooLarge` and `OutOfMemory` | -| `BaseColor` | not moved; it stays in the app | -| `Bvh`, `Hit` always built | the `bvh` feature | -| `rayon` and `serde` always on | the `parallel` and `serde` features | -| `Mesh::bounds` with a NaN position | NaN positions are left out of the box | -| `Mesh::append` with a mismatched attribute | the missing normals, UVs or tangents are filled in; `try_append` returns an error on overflow or a bad index | -| `Mesh::append` with submeshes and no material list on either side | that side gets one unnamed material | -| `Mesh::validate` | also rejects a submesh that does not start and end on a triangle, and a non-finite normal, UV, tangent or color | -| `Mesh::subdivided` with an invalid mesh | returns a copy; `try_subdivided` returns the error | -| `primitives::*` with a NaN or negative size | an empty mesh; the `try_` forms return the error | -| `auto_unwrap` with a non-finite position, normal or color, a bad submesh or colors for some vertices only | an error, with the mesh unchanged | -| `Bvh::nearest` skips a point exactly `max_dist` away | the point is found | -| Rays miss a triangle whose two edge lengths multiply to under 1e-12 | the cutoff follows the triangle's size, so the ray hits | -| `Mesh::normalize_to` with a radius that overflows a coordinate | the mesh is unchanged | -| `Mesh::normalize_to` leaves a mesh with a radius under 1e-4 too small | the mesh gets the requested radius | -| `weld_ids` on a grid of 1e-12 when the bounding diagonal is under 1e-6 | a grid of 1e-6 of the diagonal at every size | -| `OrbitCamera::frame` with a box whose center or distance is not finite | the camera is unchanged | -| `OrbitCamera::project` in orthographic mode returns points behind the camera | it returns `None` for them | -| The orthographic projection and `pan` use the field of view as it is | they clamp it to 5° to 150°, as the perspective projection does | -| `Mesh::compute_tangents` keeps the last corner's frame at a shared vertex | the vertex is split where its corners' frames differ | -| The per-vertex tangent fallback always sets `w` to +1 | `w` is -1 where the UVs are mirrored, as MikkTSpace sets it | -| `auto_unwrap` packs a triangle that submeshes of two materials list with only the last one | an `Invalid` error, with the mesh unchanged | -| `OrbitCamera::zoom` close to a target far from the origin gives a view that is not finite | the camera is unchanged | -| `Bvh::nearest` misses points inside very thin triangles and near a triangle with a zero-length edge | the nearest point is found | -| `Bvh::nodes` with no triangles lists one node | it lists none | -| `surface_at` and the rounded box replace a vector whose squared length overflows `f32` with a fallback direction | they keep its direction | -| The cylinder's side UVs shrink for a profile shorter than 1e-6, and a profile longer than `f32::MAX` is an error | the side UVs are the same at every size | -| `auto_unwrap` joins faces whose projections overlap into one chart | such a face starts another chart | -| `auto_unwrap` accepts a layout that fits only at scale zero | the packing square grows until the charts fit at a positive scale | -| `weld_ids` returns the ids | it returns `Result`, with `OutOfMemory` when the ids or the grid cannot be reserved | diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 81fd885736..9b01c84155 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -1,18 +1,9 @@ //! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and //! box queries (used by picking, baking and brush stamps). -//! -//! The tree is built by binned SAH on all three axes, falling back to a median split on the -//! widest centroid axis when no SAH split beats a leaf. Triangles with a non-finite corner are -//! left out, and a query with a non-finite origin, direction or point, a zero direction, a NaN -//! distance or a NaN box finds nothing. -//! -//! Ray casts find hits on triangles with coordinates between about 1e-12 and 1e12. Outside that -//! range the products in the triangle test overflow or underflow `f32`, and a ray can miss a -//! triangle it crosses. -use glam::{DVec3, Vec3, Vec3A}; +use glam::{Vec3, Vec3A}; -use crate::{Limits, Mesh, MeshOpsError, Result, check_limit, try_vec}; +use crate::Mesh; #[derive(Clone, Copy, Debug)] struct Node { @@ -44,9 +35,6 @@ pub struct Bvh { const LEAF: usize = 4; -/// Most triangles one tree holds: its node indices (up to twice the triangle count) are `u32`. -pub const MAX_BVH_TRIANGLES: usize = (u32::MAX / 2) as usize; - /// Traversal stack of (node, entry distance): inline for typical depths (no allocation per /// ray), spilling to the heap for degenerate trees. struct Stack { @@ -91,79 +79,22 @@ fn area(lo: Vec3, hi: Vec3) -> f32 { d.x * d.y + d.y * d.z + d.z * d.x } -/// The centroid of a triangle; thirds first when the sum would overflow. -fn centroid(t: &[Vec3; 3]) -> Vec3 { - let c = (t[0] + t[1] + t[2]) / 3.0; - if c.is_finite() { c } else { t[0] / 3.0 + t[1] / 3.0 + t[2] / 3.0 } -} - impl Bvh { - /// The tree over a mesh's triangles. Triangles with a non-finite corner or an index out of - /// range are left out, as is every triangle past [`MAX_BVH_TRIANGLES`]. When the memory for - /// the tree cannot be reserved, the tree is empty. pub fn new(mesh: &Mesh) -> Bvh { - Bvh::try_new(mesh).unwrap_or(Bvh { nodes: Vec::new(), tris: Vec::new(), order: Vec::new() }) - } - - /// [`Bvh::new`], or `OutOfMemory` when the memory for the tree cannot be reserved. - pub fn try_new(mesh: &Mesh) -> Result { - let triangle_count = mesh.triangle_count().min(MAX_BVH_TRIANGLES); - let mut tris = try_vec(triangle_count, "BVH triangles")?; - let mut ids = try_vec(triangle_count, "BVH triangles")?; + let triangle_count = mesh.triangle_count(); + let mut tris = Vec::with_capacity(triangle_count); for triangle in 0..triangle_count { let Some([a, b, c]) = mesh.tri(triangle) else { continue }; - let (Some(a), Some(b), Some(c)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue }; - if a.is_finite() && b.is_finite() && c.is_finite() { - tris.push([*a, *b, *c]); - ids.push(triangle as u32); - } + let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + tris.push([position(a), position(b), position(c)]); } - Bvh::build(tris, ids) - } - /// The tree over the triangles of `indices`, after checking the counts against `limits` - /// and [`MAX_BVH_TRIANGLES`], every index and every position (finite). - pub fn from_slices(positions: &[[f32; 3]], indices: &[u32], limits: &Limits) -> Result { - check_limit("vertex count", positions.len(), limits.max_vertices)?; - if !indices.len().is_multiple_of(3) { - return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into())); - } - let triangles = indices.len() / 3; - check_limit("triangle count", triangles, limits.max_triangles.min(MAX_BVH_TRIANGLES))?; - if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len()))); - } - if !positions.iter().flatten().all(|v| v.is_finite()) { - return Err(MeshOpsError::Invalid("non-finite position".into())); - } - let mut tris = try_vec(triangles, "BVH triangles")?; - let mut ids = try_vec(triangles, "BVH triangles")?; - for (t, &[a, b, c]) in indices.as_chunks::<3>().0.iter().enumerate() { - let p = |i: u32| positions.get(i as usize).map_or(Vec3::ZERO, |p| Vec3::from_array(*p)); - tris.push([p(a), p(b), p(c)]); - ids.push(t as u32); - } - Bvh::build(tris, ids) - } + let mut order: Vec = (0..tris.len() as u32).collect(); + let centroids: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); - /// Build over `tris`, whose original triangle indices are `ids`; at most - /// [`MAX_BVH_TRIANGLES`] finite triangles. Every list reserves its memory before it grows. - /// Without triangles the tree has no nodes. - fn build(tris: Vec<[Vec3; 3]>, ids: Vec) -> Result { - if tris.is_empty() { - return Ok(Bvh { nodes: Vec::new(), tris, order: Vec::new() }); - } - let out_of_memory = |_| MeshOpsError::OutOfMemory("BVH nodes"); - let mut order: Vec = try_vec(tris.len(), "BVH triangles")?; - order.extend(0..tris.len() as u32); - let mut centroids: Vec = try_vec(tris.len(), "BVH triangles")?; - centroids.extend(tris.iter().map(centroid)); - - let mut nodes = try_vec(1, "BVH nodes")?; - nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }); - let mut stack = try_vec(1, "BVH nodes")?; - stack.push(0usize); + let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; + let mut stack = vec![0usize]; while let Some(node_index) = stack.pop() { let Node { first, count, .. } = nodes[node_index]; @@ -280,8 +211,6 @@ impl Bvh { continue; } - nodes.try_reserve(2).map_err(out_of_memory)?; - stack.try_reserve(2).map_err(out_of_memory)?; let left_child = nodes.len(); nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first, count: left_count as u32 }); nodes.push(Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: first + left_count as u32, count: (count - left_count) as u32 }); @@ -293,13 +222,8 @@ impl Bvh { stack.push(left_child + 1); } - let mut sorted = try_vec(order.len(), "BVH triangles")?; - sorted.extend(order.iter().map(|t| tris[*t as usize])); - // The triangle indices replace the positions in `order` one by one. - for t in &mut order { - *t = ids[*t as usize]; - } - Ok(Bvh { nodes, tris: sorted, order }) + let tris = order.iter().map(|t| tris[*t as usize]).collect(); + Bvh { nodes, tris, order } } pub fn is_empty(&self) -> bool { @@ -308,7 +232,7 @@ impl Bvh { /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children - /// `first` and `first + 1`. A tree without triangles has no nodes. + /// `first` and `first + 1`. pub fn nodes(&self) -> impl ExactSizeIterator + '_ { self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) } @@ -326,9 +250,7 @@ impl Bvh { let open = t0.is_nan_mask() | t1.is_nan_mask(); let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); - // A box whose entry distance is +∞ (where 1/d overflows) is not reached, even when `tmax` - // is unbounded; no triangle can be hit at that distance. - (tn <= tf && tn.is_finite()).then_some(tn) + (tn <= tf).then_some(tn) } /// Möller–Trumbore, double sided. @@ -337,10 +259,7 @@ impl Bvh { let e2 = t[2] - t[0]; let p = d.cross(e2); let det = e1.dot(p); - // A ray in the triangle's plane, or a triangle without area. The determinant is the - // product of the two edge lengths, the direction's length and the sines of the angles - // between them, so the cutoff shrinks with that product for small triangles. - if det.abs() < 1e-12 && (det == 0.0 || det.abs() < 1e-12 * (e1.length() * e2.length() * d.length()).min(1.0)) { + if det.abs() < 1e-12 { return None; } let inv = 1.0 / det; @@ -362,9 +281,6 @@ impl Bvh { } fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { - if !o.is_finite() || !d.is_finite() || d == Vec3::ZERO || tmax.is_nan() { - return None; - } let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); let mut best = None; @@ -426,14 +342,9 @@ impl Bvh { self.traverse(o, d, tmax, true, &|_| true).is_some() } - /// The point nearest to `p` at most `max_dist` (zero or more) away on a triangle accepted by - /// `filter` (original index): a [`Hit`] with the distance in `t` and the barycentrics of - /// vertices 1 and 2. A point whose squared distance overflows `f32` (a distance above about - /// 1.8e19) is not found. + /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { - if max_dist.is_nan() || max_dist < 0.0 { - return None; - } let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; let pa = Vec3A::from(p); let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); @@ -450,9 +361,7 @@ impl Bvh { } let (q, u, v) = closest_on_triangle(p, tri); let dd = (q - p).length_squared(); - // The first point found may lie exactly at `max_dist`. A squared distance that - // overflows is not comparable with a squared `max_dist` that overflows too. - if dd.is_finite() && (dd < best_d2 || (best.is_none() && dd <= best_d2)) { + if dd < best_d2 { best_d2 = dd; best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); } @@ -469,12 +378,8 @@ impl Bvh { best } - /// Call `f` with every triangle (original index) whose bounds overlap the box. A box with a - /// NaN coordinate, or a lower corner past the upper corner on any axis, overlaps nothing. + /// Call `f` with every triangle (original index) whose bounds overlap the box. pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { - if lo.is_nan() || hi.is_nan() || lo.cmpgt(hi).any() { - return; - } let mut stack = vec![0u32]; while let Some(i) = stack.pop() { let Some(n) = self.nodes.get(i as usize) else { continue }; @@ -499,16 +404,10 @@ impl Bvh { } /// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), -/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5), in `f64`: in `f32` the -/// region tests round to zero inside thin triangles. A triangle without area is measured as the -/// point or segment it is, and can be the nearest. An edge of zero length is skipped: the -/// denominator of its parameter is its squared length. +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give +/// a non-finite distance and are never nearest. fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { - let (q, v, w) = closest_on_triangle_f64(p.as_dvec3(), t.map(|c| c.as_dvec3())); - (q.as_vec3(), v as f32, w as f32) -} - -fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64) { + let [a, b, c] = *t; let (ab, ac, ap) = (b - a, c - a, p - a); let (d1, d2) = (ab.dot(ap), ac.dot(ap)); if d1 <= 0.0 && d2 <= 0.0 { @@ -519,9 +418,8 @@ fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64) if d3 >= 0.0 && d4 <= d3 { return (b, 1.0, 0.0); } - // d1 - d3 = |ab|², d2 - d6 = |ac|² and (d4 - d3) + (d5 - d6) = |bc|². let vc = d1 * d4 - d3 * d2; - if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 && d1 - d3 > 0.0 { + if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { let v = d1 / (d1 - d3); return (a + ab * v, v, 0.0); } @@ -531,36 +429,18 @@ fn closest_on_triangle_f64(p: DVec3, [a, b, c]: [DVec3; 3]) -> (DVec3, f64, f64) return (c, 0.0, 1.0); } let vb = d5 * d2 - d1 * d6; - if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 && d2 - d6 > 0.0 { + if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { let w = d2 / (d2 - d6); return (a + ac * w, 0.0, w); } let va = d3 * d6 - d5 * d4; - if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 && (d4 - d3) + (d5 - d6) > 0.0 { + if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); return (b + (c - b) * w, 1.0 - w, w); } - let sum = va + vb + vc; - if sum > 0.0 { - let (v, w) = (vb / sum, vc / sum); - // Project p onto the plane instead of rebuilding a + ab v + ac w, whose rounding moves a - // point that lies on the plane off it. A point whose height above the plane is 0 stays p. - let n = ab.cross(ac); - let nn = n.length_squared(); - let q = if nn > 0.0 { p - n * (n.dot(ap) / nn) } else { a + ab * v + ac * w }; - return (q, v, w); - } - // No area and no region matched: the nearest of the three edges. - let on_edge = |from: DVec3, to: DVec3| { - let d = to - from; - let s = if d.length_squared() > 0.0 { ((p - from).dot(d) / d.length_squared()).clamp(0.0, 1.0) } else { 0.0 }; - (from + d * s, s) - }; - let ((qab, s), (qac, r), (qbc, k)) = (on_edge(a, b), on_edge(a, c), on_edge(b, c)); - [(qab, s, 0.0), (qac, 0.0, r), (qbc, 1.0 - k, k)] - .into_iter() - .min_by(|x, y| (x.0 - p).length_squared().total_cmp(&(y.0 - p).length_squared())) - .unwrap_or((a, 0.0, 0.0)) + let denom = 1.0 / (va + vb + vc); + let (v, w) = (vb * denom, vc * denom); + (a + ab * v + ac * w, v, w) } #[cfg(test)] @@ -568,24 +448,6 @@ mod tests { use super::*; use crate::primitives; - #[test] - fn a_box_first_reached_at_infinity_is_missed() { - let (lo, hi) = (Vec3A::ZERO, Vec3A::ONE); - // 1/d overflows on every axis: x, where the direction is subnormal, as well as y and z. - for d in [Vec3A::new(1e-39, 0.0, 0.0), Vec3A::new(1e-39, -0.0, -0.0)] { - let inv = Vec3A::ONE / d; - for o in [Vec3A::new(0.5, -1.0, 0.5), Vec3A::new(0.5, 2.0, 0.5), Vec3A::new(-1.0, 0.5, 0.5)] { - assert_eq!(Bvh::slab(lo, hi, o, inv, f32::INFINITY), None, "d {d}, origin {o}"); - } - assert_eq!(Bvh::slab(lo, hi, Vec3A::splat(0.5), inv, f32::INFINITY), Some(0.0), "d {d}, inside"); - } - // A ray parallel to a slab outside it, with a finite exit on another axis. - let inv = Vec3A::ONE / Vec3A::new(1.0, 0.0, 0.0); - assert_eq!(Bvh::slab(lo, hi, Vec3A::new(0.5, -1.0, 0.5), inv, f32::INFINITY), None); - assert_eq!(Bvh::slab(lo, hi, Vec3A::new(-1.0, 0.5, 0.5), inv, f32::INFINITY), Some(1.0)); - assert_eq!(Bvh::slab(lo, hi, Vec3A::new(0.5, 0.0, 0.5), inv, f32::INFINITY), Some(0.0), "in the plane"); - } - #[test] fn nearest_point_matches_brute_force() { let m = primitives::builtin("torus").unwrap(); @@ -613,61 +475,6 @@ mod tests { assert!(bvh.nearest(Vec3::ZERO, f32::MAX, &|_| false).is_none(), "filtered out"); } - #[test] - fn nearest_finds_a_point_inside_a_thin_triangle() { - let l = Limits::default(); - let bvh = Bvh::from_slices(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1e-4, 0.0]], &[0, 1, 2], &l).unwrap(); - // p = a + 0.5 (b - a) + 0.25 (c - a) lies on the triangle. - let p = Vec3::new(0.75, 2.5e-5, 0.0); - let hit = bvh.nearest(p, 0.0, &|_| true).unwrap(); - assert_eq!(hit.t, 0.0); - assert!((hit.u - 0.5).abs() < 1e-4 && (hit.v - 0.25).abs() < 1e-4, "{hit:?}"); - } - - #[test] - fn nearest_finds_a_coplanar_point_inside_a_triangle_at_distance_zero() { - let l = Limits::default(); - let bvh = Bvh::from_slices(&[[-1.0, -1.0, 0.0], [2.0, 0.0, 0.0], [0.0, 3.0, 0.0]], &[0, 1, 2], &l).unwrap(); - // The origin is a + 3/11 (b - a) + 2/11 (c - a); rebuilding it from those weights in - // floating point gives x of about -5.6e-17 instead of 0. - let hit = bvh.nearest(Vec3::ZERO, 0.0, &|_| true).unwrap(); - assert_eq!(hit.t, 0.0); - assert!((hit.u - 3.0 / 11.0).abs() < 1e-6 && (hit.v - 2.0 / 11.0).abs() < 1e-6, "{hit:?}"); - } - - #[test] - fn nearest_measures_a_triangle_with_a_collapsed_edge() { - let l = Limits::default(); - let p = Vec3::new(0.5, 1.0, 0.0); - let (o, x) = ([0.0, 0.0, 0.0], [1.0, 0.0, 0.0]); - // The surviving segment runs from the origin to +X; its point nearest p is (0.5, 0, 0). - for (positions, indices) in [(vec![o, o, x], vec![0, 1, 2]), (vec![x, x, o], vec![0, 1, 2]), (vec![o, x], vec![0, 0, 1])] { - let bvh = Bvh::from_slices(&positions, &indices, &l).unwrap(); - let hit = bvh.nearest(p, 10.0, &|_| true); - let hit = hit.unwrap_or_else(|| panic!("{positions:?} {indices:?}: no point found")); - assert!((hit.t - 1.0).abs() < 1e-6, "{positions:?} {indices:?}: {hit:?}"); - let [a, b, c] = [0, 1, 2].map(|k| Vec3::from_array(positions[indices[k] as usize])); - let q = a * (1.0 - hit.u - hit.v) + b * hit.u + c * hit.v; - assert!((q - Vec3::new(0.5, 0.0, 0.0)).length() < 1e-6, "{positions:?} {indices:?}: {q}"); - } - } - - #[test] - fn a_tree_without_triangles_has_no_nodes() { - let l = Limits::default(); - assert_eq!(Bvh::from_slices(&[], &[], &l).unwrap().nodes().len(), 0); - // Every triangle is left out: one corner is not finite. - let rejected = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(f32::NAN, 0.0, 0.0)], indices: vec![0, 1, 2], ..Mesh::default() }; - let bvh = Bvh::try_new(&rejected).unwrap(); - assert_eq!(bvh.nodes().len(), 0); - assert!(bvh.is_empty()); - assert!(bvh.closest(Vec3::Z, Vec3::NEG_Z, 10.0).is_none()); - assert!(bvh.nearest(Vec3::ZERO, 10.0, &|_| true).is_none()); - let mut found = 0; - bvh.query_box(Vec3::splat(-1.0), Vec3::ONE, |_| found += 1); - assert_eq!(found, 0); - } - #[test] fn traversal_stack_spills_in_lifo_order() { let mut st = Stack::default(); @@ -868,115 +675,4 @@ mod tests { assert_eq!(hit.tri, 500); assert_eq!(hit.t, 10.0); } - - #[test] - fn bvh_rejects_non_finite_queries_without_callbacks() { - let m = primitives::plane(2.0, 4); - let bvh = Bvh::new(&m); - let mut calls = 0; - bvh.query_box(Vec3::new(f32::NAN, -1.0, -1.0), Vec3::ONE, |_| calls += 1); - bvh.query_box(Vec3::splat(-1.0), Vec3::new(1.0, f32::NAN, 1.0), |_| calls += 1); - // A box whose lower corner is past its upper corner on one axis is empty, even where a - // triangle spans both values. - bvh.query_box(Vec3::new(0.3, -1.0, -1.0), Vec3::new(0.2, 1.0, 1.0), |_| calls += 1); - bvh.query_box(Vec3::new(-1.0, -1.0, 0.3), Vec3::new(1.0, 1.0, 0.2), |_| calls += 1); - assert_eq!(calls, 0); - // An infinite box is a valid query and finds everything. - bvh.query_box(Vec3::NEG_INFINITY, Vec3::INFINITY, |_| calls += 1); - assert_eq!(calls, m.triangle_count()); - - let (o, d) = (Vec3::new(0.0, 1.0, 0.0), Vec3::NEG_Y); - assert!(bvh.closest(o, d, 10.0).is_some()); - let counted = std::cell::Cell::new(0); - let filter = |_: u32| { - counted.set(counted.get() + 1); - true - }; - for (o, d, tmax) in - [(Vec3::NAN, d, 10.0), (o, Vec3::new(0.0, f32::NAN, 0.0), 10.0), (o, Vec3::ZERO, 10.0), (o, Vec3::NEG_INFINITY, 10.0), (o, d, f32::NAN)] - { - assert!(bvh.closest_filtered(o, d, tmax, &filter).is_none(), "{o} {d} {tmax}"); - assert!(!bvh.occluded(o, d, tmax)); - } - assert_eq!(counted.get(), 0); - - // A negative or NaN distance finds nothing, not the points within its magnitude. - assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), 1.0, &|_| true).is_some()); - assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), -1.0, &|_| true).is_none()); - assert!(bvh.nearest(Vec3::new(0.0, 0.5, 0.0), f32::NAN, &|_| true).is_none()); - } - - #[test] - fn ray_hits_do_not_depend_on_the_size_of_the_triangle() { - for exponent in [-10, -7, -3, 0, 3, 7, 10] { - let s = 10f32.powi(exponent); - let bvh = Bvh::from_slices(&[[0.0, 0.0, 0.0], [s, 0.0, 0.0], [0.0, 0.0, s]], &[0, 1, 2], &Limits::default()).unwrap(); - // Straight down onto the triangle, from one triangle size above it. - let o = Vec3::new(0.25 * s, s, 0.25 * s); - let hit = bvh.closest(o, Vec3::NEG_Y, f32::MAX).unwrap_or_else(|| panic!("no hit at 1e{exponent}")); - assert!((hit.t / s - 1.0).abs() < 1e-4, "1e{exponent}: {hit:?}"); - assert!((hit.u - 0.25).abs() < 1e-4 && (hit.v - 0.25).abs() < 1e-4, "1e{exponent}: {hit:?}"); - assert!(bvh.occluded(o, Vec3::NEG_Y, 2.0 * s), "1e{exponent}"); - // Beside the triangle, and along its plane. - assert!(bvh.closest(Vec3::new(0.75 * s, s, 0.75 * s), Vec3::NEG_Y, f32::MAX).is_none(), "1e{exponent}"); - assert!(bvh.closest(Vec3::new(-s, 0.0, 0.25 * s), Vec3::X, f32::MAX).is_none(), "1e{exponent}"); - } - } - - #[test] - fn nearest_includes_points_exactly_at_the_distance() { - let m = primitives::plane(2.0, 4); - let bvh = Bvh::new(&m); - // A vertex of the plane, and a point 0.5 above it. - let corner = m.positions[6]; - assert_eq!(bvh.nearest(corner, 0.0, &|_| true).map(|h| h.t), Some(0.0)); - let above = corner + Vec3::new(0.0, 0.5, 0.0); - assert_eq!(bvh.nearest(above, 0.5, &|_| true).map(|h| h.t), Some(0.5)); - assert!(bvh.nearest(above, 0.499, &|_| true).is_none()); - // A triangle 1e30 away is outside a distance of 1e20, though both squares overflow. - let far = Mesh { - positions: vec![Vec3::new(1e30, 0.0, 0.0), Vec3::new(1e30, 1.0, 0.0), Vec3::new(1e30, 0.0, 1.0)], - indices: vec![0, 1, 2], - ..Mesh::default() - }; - assert!(Bvh::new(&far).nearest(Vec3::ZERO, 1e20, &|_| true).is_none()); - } - - #[test] - fn bvh_leaves_out_non_finite_triangles() { - let mut m = primitives::plane(2.0, 4); - // Vertex 0 is the corner of one triangle only. - m.positions[0] = Vec3::new(f32::NAN, 0.0, 0.0); - m.positions[24] = Vec3::new(0.0, f32::INFINITY, 0.0); - let affected = m.indices.chunks(3).filter(|t| t.contains(&0) || t.contains(&24)).count(); - let bvh = Bvh::new(&m); - let mut found = Vec::new(); - bvh.query_box(Vec3::splat(-10.0), Vec3::splat(10.0), |t| found.push(t)); - assert_eq!(found.len(), m.triangle_count() - affected); - for (lo, hi, _, _) in bvh.nodes() { - assert!(lo.is_finite() && hi.is_finite(), "{lo} {hi}"); - } - let (_, order) = bvh.triangles(); - assert!(order.iter().all(|t| m.tri(*t as usize).is_some_and(|c| !c.contains(&0) && !c.contains(&24)))); - } - - #[test] - fn bvh_slices_check_limits_indices_and_positions() { - let m = primitives::plane(2.0, 4); - let positions: Vec<[f32; 3]> = m.positions.iter().map(|p| p.to_array()).collect(); - let l = Limits::default(); - let bvh = Bvh::from_slices(&positions, &m.indices, &l).unwrap(); - assert_eq!(bvh.triangles().1.len(), m.triangle_count()); - let hit = bvh.closest(Vec3::new(0.3, 1.0, 0.2), Vec3::NEG_Y, 10.0).unwrap(); - assert_eq!(Some(hit), Bvh::new(&m).closest(Vec3::new(0.3, 1.0, 0.2), Vec3::NEG_Y, 10.0)); - assert_eq!(Bvh::try_new(&m).unwrap().triangles(), bvh.triangles()); - let few = Limits { max_triangles: m.triangle_count() - 1, ..l }; - assert!(matches!(Bvh::from_slices(&positions, &m.indices, &few), Err(MeshOpsError::TooLarge { .. }))); - assert!(Bvh::from_slices(&positions, &[0, 1, positions.len() as u32], &l).is_err()); - assert!(Bvh::from_slices(&positions, &[0, 1], &l).is_err()); - let mut nan = positions.clone(); - nan[3][2] = f32::NAN; - assert!(Bvh::from_slices(&nan, &m.indices, &l).is_err()); - assert!(Bvh::from_slices(&[], &[], &l).unwrap().is_empty()); - } } diff --git a/crates/mesh-ops/src/camera.rs b/crates/mesh-ops/src/camera.rs index 0ad5b8443a..1f4156c93e 100644 --- a/crates/mesh-ops/src/camera.rs +++ b/crates/mesh-ops/src/camera.rs @@ -1,9 +1,9 @@ //! Orbit camera (texture painting navigation) and picking rays. -use glam::{DVec4, Mat4, Vec2, Vec3}; +use glam::{Mat4, Vec2, Vec3, Vec4}; +use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct OrbitCamera { pub target: Vec3, /// Radians around Y. @@ -16,7 +16,7 @@ pub struct OrbitCamera { /// Scene radius (sets the clip planes). pub scene_radius: f32, /// Orthographic projection instead of perspective. - #[cfg_attr(feature = "serde", serde(default))] + #[serde(default)] pub ortho: bool, } @@ -48,22 +48,16 @@ impl OrbitCamera { Mat4::look_at_rh(self.eye(), self.target, Vec3::Y) } - /// The vertical field of view in radians, with `fov` clamped to 5° to 150°. Perspective and - /// orthographic projection, [`OrbitCamera::pan`] and [`OrbitCamera::frame`] all use it. - fn fov_radians(&self) -> f32 { - self.fov.clamp(5.0, 150.0).to_radians() - } - pub fn proj(&self, aspect: f32) -> Mat4 { let r = self.scene_radius.max(1e-3); let near = (self.distance - r * 4.0).max(r * 0.01).max(1e-4); let far = self.distance + r * 50.0; let aspect = if aspect.is_finite() && aspect > 1e-4 { aspect } else { 1.0 }; if self.ortho { - let h = self.distance * (self.fov_radians() * 0.5).tan(); + let h = self.distance * (self.fov.to_radians() * 0.5).tan(); Mat4::orthographic_rh(-h * aspect, h * aspect, -h, h, near.min(0.01), far) } else { - Mat4::perspective_rh(self.fov_radians(), aspect, near, far) + Mat4::perspective_rh(self.fov.clamp(5.0, 150.0).to_radians(), aspect, near, far) } } @@ -71,20 +65,12 @@ impl OrbitCamera { self.proj(aspect) * self.view() } - /// Frame a bounding box, keeping the current angles. A box whose center or framing distance - /// is not finite, or whose framed view-projection at aspect 1 is not finite (an eye that - /// rounds to the target, or terms past the `f32` range), leaves the camera unchanged. + /// Frame a bounding box, keeping the current angles. pub fn frame(&mut self, lo: Vec3, hi: Vec3) { - let target = lo * 0.5 + hi * 0.5; + self.target = (lo + hi) * 0.5; let r = ((hi - lo).length() * 0.5).max(1e-3); - let distance = r / (self.fov_radians() * 0.5).sin() * 1.1; - if !(target.is_finite() && distance.is_finite()) { - return; - } - let framed = OrbitCamera { target, scene_radius: r, distance, ..*self }; - if framed.view_proj(1.0).is_finite() { - *self = framed; - } + self.scene_radius = r; + self.distance = r / (self.fov.clamp(5.0, 150.0).to_radians() * 0.5).sin() * 1.1; } pub fn orbit(&mut self, dx: f32, dy: f32) { @@ -97,46 +83,28 @@ impl OrbitCamera { let f = self.forward(); let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); let up = right.cross(f); - let scale = self.distance * (self.fov_radians() * 0.5).tan() * 2.0; + let scale = self.distance * (self.fov.to_radians() * 0.5).tan() * 2.0; self.target += (-right * dx + up * dy) * scale; } - /// Dolly by a factor exponent (positive zooms in). A distance whose view-projection at aspect 1 - /// is not finite (an eye that rounds to a target far from the origin) leaves the camera - /// unchanged. + /// Dolly by a factor exponent (positive zooms in). pub fn zoom(&mut self, amount: f32) { let r = self.scene_radius.max(1e-3); - let distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); - let zoomed = OrbitCamera { distance, ..*self }; - if zoomed.eye() != zoomed.target && zoomed.view_proj(1.0).is_finite() { - *self = zoomed; - } + self.distance = (self.distance * (-amount).exp()).clamp(r * 0.05, r * 200.0); } - /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). It - /// starts on the near plane: [`OrbitCamera::proj`] has a depth range of 0 to 1. The - /// view-projection is inverted and the points unprojected in `f64`, where the determinant of - /// a large scene's matrix and the squared length of the ray do not leave the range. + /// Ray through a viewport point given in normalized device coordinates (-1..1, y up). pub fn ray(&self, ndc: Vec2, aspect: f32) -> Ray { - let inv = self.view_proj(aspect).as_dmat4().inverse(); - let (x, y) = (f64::from(ndc.x), f64::from(ndc.y)); - let a = inv * DVec4::new(x, y, 0.0, 1.0); - let b = inv * DVec4::new(x, y, 1.0, 1.0); + let inv = self.view_proj(aspect).inverse(); + let a = inv * Vec4::new(ndc.x, ndc.y, 0.0, 1.0); + let b = inv * Vec4::new(ndc.x, ndc.y, 1.0, 1.0); let (a, b) = (a.truncate() / a.w, b.truncate() / b.w); - let origin = a.as_vec3(); - let dir = (b - a).try_normalize().map(|d| d.as_vec3()).filter(|d| d.is_finite()).unwrap_or(self.forward()); - Ray { origin, dir } + Ray { origin: a, dir: (b - a).try_normalize().unwrap_or(self.forward()) } } - /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera, in - /// both projections: the point's depth in front of the eye must be over 1e-6. + /// Project a world point to NDC (x, y in -1..1, y up; z depth). None behind the camera. pub fn project(&self, p: Vec3, aspect: f32) -> Option { - let in_view = self.view() * p.extend(1.0); - // The view looks down -Z. - if -in_view.z <= 1e-6 { - return None; - } - let c = self.proj(aspect) * in_view; + let c = self.view_proj(aspect) * p.extend(1.0); (c.w > 1e-6).then(|| c.truncate() / c.w) } } @@ -169,111 +137,4 @@ mod tests { assert!(c.distance > 0.0 && c.distance.is_finite()); let _ = c.proj(f32::NAN); } - - #[test] - fn orthographic_projection_finds_nothing_behind_the_camera() { - for ortho in [false, true] { - let c = OrbitCamera { ortho, ..OrbitCamera::default() }; - assert!(c.project(c.eye() - c.forward(), 1.5).is_none(), "ortho {ortho}"); - assert!(c.project(c.eye() - c.forward() * 1e-3, 1.5).is_none(), "ortho {ortho}"); - assert!(c.project(c.target, 1.5).is_some(), "ortho {ortho}"); - } - } - - #[test] - fn field_of_view_is_clamped_the_same_way_in_every_mode() { - for fov in [0.0, -10.0, 1.0, 179.0, 500.0] { - let c = OrbitCamera { fov, ortho: true, ..OrbitCamera::default() }; - let clamped = OrbitCamera { fov: fov.clamp(5.0, 150.0), ..c }; - assert!(c.proj(1.5).to_cols_array().iter().all(|v| v.is_finite()), "fov {fov}"); - assert_eq!(c.proj(1.5), clamped.proj(1.5), "fov {fov}"); - let (mut panned, mut expected) = (c, clamped); - panned.pan(0.25, -0.5); - expected.pan(0.25, -0.5); - assert_eq!(panned.target, expected.target, "fov {fov}"); - assert_ne!(panned.target, c.target, "fov {fov}"); - } - } - - #[test] - fn frame_leaves_the_camera_unchanged_for_a_box_it_cannot_frame() { - let mut c = OrbitCamera::default(); - c.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); - let framed = c; - for (lo, hi) in [ - (Vec3::new(f32::NAN, 0.0, 0.0), Vec3::ONE), - (Vec3::ZERO, Vec3::new(1.0, f32::INFINITY, 1.0)), - (Vec3::NEG_INFINITY, Vec3::INFINITY), - (Vec3::splat(-3e38), Vec3::splat(3e38)), - ] { - c.frame(lo, hi); - assert_eq!(c, framed, "{lo} {hi}"); - } - } - - #[test] - fn frame_keeps_the_view_finite() { - let mut c = OrbitCamera::default(); - c.frame(Vec3::splat(-1e15), Vec3::splat(1e15)); - assert!(c.view_proj(1.0).is_finite()); - assert!((c.scene_radius / (1e15 * 3f32.sqrt()) - 1.0).abs() < 1e-4, "{}", c.scene_radius); - let framed = c; - for (lo, hi) in [ - // A finite center and distance, with an eye whose distance from the target squares - // past the f32 range. - (Vec3::splat(-5e18), Vec3::splat(5e18)), - // An eye that rounds to a target this far out. - (Vec3::splat(1e30), Vec3::splat(1e30)), - // Corners whose sum overflows f32. - (Vec3::new(1.7e38, -1.0, -1.0), Vec3::new(1.8e38, 1.0, 1.0)), - ] { - c.frame(lo, hi); - assert_eq!(c, framed, "{lo} {hi}"); - assert!(c.view_proj(1.0).is_finite(), "{lo} {hi}"); - } - } - - #[test] - fn zoom_keeps_the_view_finite_near_a_far_target() { - // At the closest zoom the eye is 0.69 from the target, where coordinates of 1e8 are 8 apart. - let mut c = OrbitCamera::default(); - c.frame(Vec3::splat(1e8 - 8.0), Vec3::splat(1e8 + 8.0)); - assert!(c.view().is_finite()); - c.zoom(10.0); - assert!(c.view().is_finite(), "distance {}", c.distance); - assert_ne!(c.eye(), c.target); - // Zooming out from there works as before. - let before = c.distance; - c.zoom(-1.0); - assert!(c.distance > before); - } - - #[test] - fn orthographic_rays_of_a_large_scene_are_finite() { - // The view-projection of this scene has a determinant that underflows f32. - let mut c = OrbitCamera { ortho: true, ..OrbitCamera::default() }; - c.frame(Vec3::splat(-1e15), Vec3::splat(1e15)); - let r = c.ray(Vec2::ZERO, 1.0); - assert!(r.origin.is_finite() && r.dir.is_finite(), "{r:?}"); - assert!((r.dir - c.forward()).length() < 1e-4, "{r:?}"); - let p = Vec3::new(3e14, -2e14, 1e14); - let ndc = c.project(p, 1.0).unwrap(); - let r = c.ray(ndc.truncate(), 1.0); - // The ray passes the point within a millionth of the scene's size. - let to_p = p - r.origin; - assert!((to_p - r.dir * to_p.dot(r.dir)).length() < 1e9, "{r:?}"); - } - - #[test] - fn off_center_rays_of_a_large_scene_leave_the_center() { - // The near and far points are finite, while the square of their distance overflows f32. - let mut c = OrbitCamera { pitch: 0.0, ..OrbitCamera::default() }; - c.frame(Vec3::splat(-1e18), Vec3::splat(1e18)); - let r = c.ray(Vec2::new(0.5, 0.0), 1.0); - assert!(r.origin.is_finite() && r.dir.is_finite(), "{r:?}"); - assert!((r.dir.length() - 1.0).abs() < 1e-5, "{r:?}"); - assert!(r.dir.dot(c.forward()) < 0.999, "{r:?}"); - let ndc = c.project(r.origin + r.dir * c.distance, 1.0).unwrap(); - assert!((ndc.x - 0.5).abs() < 1e-3 && ndc.y.abs() < 1e-3, "{ndc}"); - } } diff --git a/crates/mesh-ops/src/gbuffer.rs b/crates/mesh-ops/src/gbuffer.rs index 9001a30de3..560b42f15e 100644 --- a/crates/mesh-ops/src/gbuffer.rs +++ b/crates/mesh-ops/src/gbuffer.rs @@ -2,22 +2,16 @@ //! to. Painting, compositing, baking and padding all work from this one buffer, so they agree //! on which texel is which surface point. -use glam::{DVec2, Vec2, Vec3, Vec4}; -#[cfg(feature = "parallel")] +use glam::{Vec2, Vec3, Vec4}; use rayon::prelude::*; -use crate::mesh::unit; -use crate::{Limits, Mesh, MeshOpsError, Result, check_limit, try_vec}; +use crate::Mesh; /// Texel not covered by any triangle. pub const NO_TRI: u32 = u32::MAX; const BAND: u32 = 32; -/// A triangle with a corner farther than this many texels from the UV origin is not rasterized: -/// within it, the products of two texel coordinates in the edge functions stay finite. -const MAX_TEXEL_COORDINATE: f32 = 1e18; - #[derive(Clone, Debug, PartialEq)] pub struct UvGBuffer { pub width: u32, @@ -26,8 +20,7 @@ pub struct UvGBuffer { pub tri: Vec, /// Barycentric weights of the triangle's second and third vertices. pub bary: Vec<[f32; 2]>, - /// Texels written by more than one triangle (overlapping UVs). A texel whose center lies on - /// an edge two triangles share is written by both and counts; the later triangle keeps it. + /// Texels written by more than one triangle (overlapping UVs). pub overlaps: u32, } @@ -44,110 +37,78 @@ pub struct Surface { pub tri: u32, } -/// The edge function of `a → b` at `p`, `(b - a) × (p - a)`, rounded once from the exact value -/// of its six products. Each product is split into its rounded value and its rounding error, -/// and the twelve parts are added with Neumaier's compensation, so corners far from `p` do not -/// cancel the digits that place `p` against the edge. -fn edge(a: DVec2, b: DVec2, p: DVec2) -> f64 { - let products = [(b.x, p.y), (-b.x, a.y), (-a.x, p.y), (-b.y, p.x), (b.y, a.x), (a.y, p.x)]; - let (mut sum, mut compensation) = (0.0f64, 0.0f64); - for (x, y) in products { - let high = x * y; - for part in [high, x.mul_add(y, -high)] { - let next = sum + part; - compensation += if sum.abs() >= part.abs() { (sum - next) + part } else { (part - next) + sum }; - sum = next; - } - } - sum + compensation -} - -/// Vertex indices of triangle `t` of an index buffer. -fn corners(indices: &[u32], t: usize) -> Option<[usize; 3]> { - let start = t.checked_mul(3)?; - let i = indices.get(start..start.checked_add(3)?)?; - Some([i[0] as usize, i[1] as usize, i[2] as usize]) -} - -/// Texel count of a `width × height` buffer, checked against `limits`. A count whose -/// barycentric array would be over `isize::MAX` bytes, which no allocation can hold, is -/// `OutOfMemory`. -fn texels(width: u32, height: u32, limits: &Limits) -> Result { - if width == 0 || height == 0 { - return Err(MeshOpsError::Invalid(format!("G-buffer size {width} × {height} is empty"))); - } - let side = limits.max_gbuffer_side as usize; - check_limit("G-buffer width", width as usize, side)?; - check_limit("G-buffer height", height as usize, side)?; - let n = u64::from(width) * u64::from(height); - if n > limits.max_gbuffer_texels { - return Err(MeshOpsError::TooLarge { what: "G-buffer texel count", got: n, limit: limits.max_gbuffer_texels }); - } - let n = usize::try_from(n).map_err(|_| MeshOpsError::TooLarge { what: "G-buffer texel count", got: n, limit: usize::MAX as u64 })?; - match n.checked_mul(size_of::<[f32; 2]>()) { - Some(bytes) if bytes <= isize::MAX as usize => Ok(n), - _ => Err(MeshOpsError::OutOfMemory("G-buffer")), - } +fn edge(a: Vec2, b: Vec2, p: Vec2) -> f32 { + (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) } impl UvGBuffer { - /// Rasterize the triangles of material `material` at `width × height`, each side clamped to - /// `1..=8192` (the default [`Limits::max_gbuffer_side`]). When the mesh is over another - /// default [`Limits`] field or the memory for that size cannot be reserved, the buffer is - /// 1 × 1 and uncovered. + /// Rasterize the triangles of material `material` at `width × height`. pub fn new(mesh: &Mesh, material: usize, width: u32, height: u32) -> UvGBuffer { - let side = Limits::default().max_gbuffer_side; - let (w, h) = (width.clamp(1, side), height.clamp(1, side)); - UvGBuffer::try_new(mesh, material, w, h, &Limits::default()).unwrap_or_else(|_| UvGBuffer { - width: 1, - height: 1, - tri: vec![NO_TRI], - bary: vec![[0.0; 2]], - overlaps: 0, - }) - } - - /// [`UvGBuffer::new`] with the size checked against `limits` instead of clamped: a zero - /// side is an error. The mesh's vertex and triangle counts and the rasterizer's work and band - /// lists are checked before the texel buffers are reserved. - pub fn try_new(mesh: &Mesh, material: usize, width: u32, height: u32, limits: &Limits) -> Result { - let n = texels(width, height, limits)?; - check_limit("vertex count", mesh.positions.len(), limits.max_vertices)?; - check_limit("triangle count", mesh.triangle_count(), limits.max_triangles)?; - let bins = Bins::new(&mesh.uvs, &mesh.indices, || mesh.triangles_of(material), (width, height), limits)?; - UvGBuffer::rasterize(&mesh.uvs, &mesh.indices, &bins, (width, height), n) - } - - /// Rasterize every triangle of `indices` over `uvs` at `width × height`. The size, the - /// triangle count, every index and every UV (finite) are checked first, and the - /// rasterizer's work and band lists before the texel buffers are reserved. - pub fn from_slices(uvs: &[[f32; 2]], indices: &[u32], width: u32, height: u32, limits: &Limits) -> Result { - let n = texels(width, height, limits)?; - check_limit("vertex count", uvs.len(), limits.max_vertices)?; - if !indices.len().is_multiple_of(3) { - return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into())); + let (w, h) = (width.max(1), height.max(1)); + let size = Vec2::new(w as f32, h as f32); + let bands = h.div_ceil(BAND) as usize; + let mut bins: Vec> = vec![Vec::new(); bands]; + for t in mesh.triangles_of(material) { + let Some([a, b, c]) = mesh.tri(t) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let y0 = (ua.y.min(ub.y).min(uc.y) * size.y).floor().max(0.0) as i64; + let y1 = (ua.y.max(ub.y).max(uc.y) * size.y).ceil().min(size.y) as i64; + if y1 <= y0 || !ua.is_finite() || !ub.is_finite() || !uc.is_finite() { + continue; + } + let (b0, b1) = ((y0 / BAND as i64) as usize, ((y1 - 1).max(0) / BAND as i64) as usize); + for bin in bins.iter_mut().take(b1 + 1).skip(b0) { + bin.push(t as u32); + } } - check_limit("triangle count", indices.len() / 3, limits.max_triangles)?; - if let Some(bad) = indices.iter().find(|&&i| i as usize >= uvs.len()) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", uvs.len()))); - } - if !uvs.iter().flatten().all(|v| v.is_finite()) { - return Err(MeshOpsError::Invalid("non-finite UV".into())); - } - let mut points = try_vec(uvs.len(), "UVs")?; - points.extend(uvs.iter().map(|uv| Vec2::from_array(*uv))); - let bins = Bins::new(&points, indices, || 0..indices.len() / 3, (width, height), limits)?; - UvGBuffer::rasterize(&points, indices, &bins, (width, height), n) - } - - /// Reserve the `n` texels of a `width × height` buffer and draw the triangles that `bins` - /// lists. - fn rasterize(uvs: &[Vec2], indices: &[u32], bins: &Bins, (width, height): (u32, u32), n: usize) -> Result { - let (mut tri, mut bary) = (try_vec(n, "G-buffer")?, try_vec(n, "G-buffer")?); - tri.resize(n, NO_TRI); - bary.resize(n, [0.0f32; 2]); - let overlaps = bins.draw(uvs, indices, (width, height), &mut tri, &mut bary); - Ok(UvGBuffer { width, height, tri, bary, overlaps }) + let n = w as usize * h as usize; + let mut tri = vec![NO_TRI; n]; + let mut bary = vec![[0.0f32; 2]; n]; + let band_len = (BAND * w) as usize; + let overlaps: u32 = tri + .par_chunks_mut(band_len) + .zip(bary.par_chunks_mut(band_len)) + .enumerate() + .map(|(bi, (tri, bary))| { + let mut overlaps = 0u32; + let row0 = bi as u32 * BAND; + let rows = (tri.len() as u32) / w; + for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { + let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; + let (Some(&ua), Some(&ub), Some(&uc)) = (mesh.uvs.get(a), mesh.uvs.get(b), mesh.uvs.get(c)) else { continue }; + let (pa, pb, pc) = (ua * size, ub * size, uc * size); + let area = edge(pa, pb, pc); + if area.abs() < 1e-12 { + continue; + } + let eps = -1e-6 * area.abs(); + let x0 = pa.x.min(pb.x).min(pc.x).floor().max(0.0) as u32; + let x1 = (pa.x.max(pb.x).max(pc.x).ceil().min(w as f32) as u32).min(w); + let y0 = (pa.y.min(pb.y).min(pc.y).floor().max(row0 as f32) as u32).max(row0); + let y1 = (pa.y.max(pb.y).max(pc.y).ceil() as u32).min(row0 + rows); + for y in y0..y1 { + for x in x0..x1 { + let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let (w0, w1, w2) = (edge(pb, pc, p) * area.signum(), edge(pc, pa, p) * area.signum(), edge(pa, pb, p) * area.signum()); + if w0 < eps || w1 < eps || w2 < eps { + continue; + } + let i = ((y - row0) * w + x) as usize; + if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { + if *slot != NO_TRI { + overlaps += 1; + } + *slot = t; + let inv = 1.0 / area.abs(); + *bw = [w1 * inv, w2 * inv]; + } + } + } + } + overlaps + }) + .sum(); + UvGBuffer { width: w, height: h, tri, bary, overlaps } } pub fn covered(&self, i: usize) -> bool { @@ -173,199 +134,18 @@ impl UvGBuffer { } } -/// `total + add`, or `TooLarge` naming `what` when that is over `limit` (`got` is `u64::MAX` -/// when the sum overflows). -fn add_within(what: &'static str, total: u64, add: u64, limit: u64) -> Result { - let got = total.saturating_add(add); - if got > limit { Err(MeshOpsError::TooLarge { what, got, limit }) } else { Ok(got) } -} - -/// Triangle `t` in the texels of a `size` buffer: its corners (in `f64`), its signed doubled -/// area and its bounding box clipped to the buffer as `[x0, x1, y0, y1]` (ends exclusive). -/// `None` when a corner is missing, not finite or farther than [`MAX_TEXEL_COORDINATE`], when -/// the triangle has no area or when the clipped box is empty. -fn texel_triangle(uvs: &[Vec2], indices: &[u32], t: usize, size: Vec2) -> Option<([DVec2; 3], f64, [u32; 4])> { - let [a, b, c] = corners(indices, t)?; - let p = [*uvs.get(a)? * size, *uvs.get(b)? * size, *uvs.get(c)? * size]; - if !p.iter().all(|q| q.is_finite() && q.abs().max_element() <= MAX_TEXEL_COORDINATE) { - return None; - } - let corners = p.map(|q| q.as_dvec2()); - let area = edge(corners[0], corners[1], corners[2]); - if area.abs() < 1e-12 { - return None; - } - let lo = p[0].min(p[1]).min(p[2]).floor().clamp(Vec2::ZERO, size); - let hi = p[0].max(p[1]).max(p[2]).ceil().clamp(Vec2::ZERO, size); - let [x0, x1, y0, y1] = [lo.x as u32, hi.x as u32, lo.y as u32, hi.y as u32]; - (x1 > x0 && y1 > y0).then_some((corners, area, [x0, x1, y0, y1])) -} - -/// The bands of rows of a G-buffer (each [`BAND`] rows high), each with the triangles whose -/// clipped boxes reach it, in triangle order. -struct Bins { - /// Band `b`'s triangles are `ids[offsets[b]..offsets[b + 1]]`. - offsets: Vec, - ids: Vec, -} - -impl Bins { - /// Bin the triangles that `triangles` returns (the same ones on every call) for a `w × h` - /// buffer. A first pass checks the triangles visited against [`Limits::max_triangles`], the - /// box texels against [`Limits::max_gbuffer_work`] and the band entries against - /// [`Limits::max_gbuffer_bin_entries`] and reserves nothing. A second pass counts each band's - /// entries, so the lists are reserved in one piece before a third pass fills them. - fn new>(uvs: &[Vec2], indices: &[u32], triangles: impl Fn() -> I, (w, h): (u32, u32), limits: &Limits) -> Result { - let size = Vec2::new(w as f32, h as f32); - let bands = h.div_ceil(BAND) as usize; - // NO_TRI marks an uncovered texel, so it cannot name a triangle. - let triangles = || triangles().take_while(|t| *t < NO_TRI as usize); - let band_range = |y0: u32, y1: u32| (y0 / BAND) as usize..=((y1 - 1) / BAND) as usize; - let (mut visited, mut work, mut entries) = (0usize, 0u64, 0u64); - // Every entry count and offset below then fits in a usize. - let entry_limit = limits.max_gbuffer_bin_entries.min(usize::MAX as u64); - for t in triangles() { - visited = visited.saturating_add(1); - check_limit("triangle count", visited, limits.max_triangles)?; - let Some((_, _, [x0, x1, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue }; - work = add_within("G-buffer work", work, u64::from(x1 - x0) * u64::from(y1 - y0), limits.max_gbuffer_work)?; - let reach = band_range(y0, y1); - entries = add_within("G-buffer band entries", entries, (reach.end() - reach.start() + 1) as u64, entry_limit)?; - } - // offsets[b + 1] counts band b's entries, then becomes the end of its run in `ids`. - let mut offsets = try_vec(bands + 1, "G-buffer bands")?; - offsets.resize(bands + 1, 0usize); - for t in triangles() { - let Some((_, _, [_, _, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue }; - for b in band_range(y0, y1) { - if let Some(n) = offsets.get_mut(b + 1) { - *n += 1; - } - } - } - let mut run = 0; - for n in &mut offsets { - run += *n; - *n = run; - } - let entries = usize::try_from(entries).map_err(|_| MeshOpsError::OutOfMemory("G-buffer bands"))?; - let mut ids = try_vec(entries, "G-buffer bands")?; - ids.resize(entries, NO_TRI); - let mut next = try_vec(offsets.len(), "G-buffer bands")?; - next.extend_from_slice(&offsets); - for t in triangles() { - let Some((_, _, [_, _, y0, y1])) = texel_triangle(uvs, indices, t, size) else { continue }; - for b in band_range(y0, y1) { - if let Some(at) = next.get_mut(b) { - if let Some(id) = ids.get_mut(*at) { - *id = t as u32; - } - *at += 1; - } - } - } - Ok(Bins { offsets, ids }) - } - - /// Write the triangle and barycentrics under each texel center of `w × h` buffers (`tri` - /// and `bary` hold `w × h` entries) for the binned triangles; returns the overlap count. - fn draw(&self, uvs: &[Vec2], indices: &[u32], (w, h): (u32, u32), tri: &mut [u32], bary: &mut [[f32; 2]]) -> u32 { - let size = Vec2::new(w as f32, h as f32); - let band_len = band_texels(w, tri.len()); - let band = |(bi, (tri, bary)): (usize, (&mut [u32], &mut [[f32; 2]]))| { - let mut overlaps = 0u32; - let row0 = bi as u32 * BAND; - let rows = (tri.len() / w as usize) as u32; - let list = match (self.offsets.get(bi), self.offsets.get(bi + 1)) { - (Some(&start), Some(&end)) => self.ids.get(start..end).unwrap_or(&[]), - _ => &[], - }; - for &t in list { - let Some(([pa, pb, pc], area, [x0, x1, y0, y1])) = texel_triangle(uvs, indices, t as usize, size) else { continue }; - let (y0, y1) = (y0.max(row0), y1.min(row0 + rows)); - if y0 >= y1 { - continue; - } - // Each edge function is taken in full at the first texel center of the box and - // stepped from there along its gradient, so its rounding at the other centers is - // a few `f64` steps of the box's size rather than of the corners' coordinates. - // Each edge function is its distance times the edge's length. A texel center - // within 1e-6 texel of an edge, plus that rounding, counts as inside: both - // triangles that share the edge write it. The slack is at most 1e-3 of the - // triangle's smallest height, so a thin triangle is not widened. - let start = DVec2::new(f64::from(x0) + 0.5, f64::from(y0) + 0.5); - let edges = [(pb, pc), (pc, pa), (pa, pb)]; - let base = edges.map(|(a, b)| edge(a, b, start) * area.signum()); - let step = edges.map(|(a, b)| DVec2::new(a.y - b.y, b.x - a.x) * area.signum()); - let lengths = edges.map(|(a, b)| (b - a).length()); - let lowest = area.abs() / lengths.iter().copied().fold(0.0, f64::max); - let slack = (1e-6 + 8.0 * f64::EPSILON * f64::from(size.max_element())).min(1e-3 * lowest); - let eps = lengths.map(|length| -slack * length); - for y in y0..y1 { - for x in x0..x1 { - let d = DVec2::new(f64::from(x - x0), f64::from(y - y0)); - let [w0, w1, w2] = [0, 1, 2].map(|i| base[i] + (step[i].x * d.x + step[i].y * d.y)); - if w0 < eps[0] || w1 < eps[1] || w2 < eps[2] { - continue; - } - let i = (y - row0) as usize * w as usize + x as usize; - if let (Some(slot), Some(bw)) = (tri.get_mut(i), bary.get_mut(i)) { - if *slot != NO_TRI { - overlaps = overlaps.saturating_add(1); - } - *slot = t; - let inv = 1.0 / area.abs(); - *bw = [(w1 * inv) as f32, (w2 * inv) as f32]; - } - } - } - } - overlaps - }; - each_band(tri, bary, band_len, band) - } -} - -/// Texels in one [`BAND`] of a `width`-wide buffer of `texels` texels, at most `texels` and at -/// least 1. The product is taken in `u64` and capped at `texels`, so a band of a wide buffer fits -/// a 32-bit `usize`. -fn band_texels(width: u32, texels: usize) -> usize { - let band = u64::from(BAND) * u64::from(width); - usize::try_from(band).map_or(texels, |band| band.min(texels)).max(1) -} - -/// Run `band` on each band of `len` texels (on several threads with `parallel`) and add up the -/// overlap counts. -#[cfg(feature = "parallel")] -fn each_band(tri: &mut [u32], bary: &mut [[f32; 2]], len: usize, band: impl Fn((usize, (&mut [u32], &mut [[f32; 2]]))) -> u32 + Sync + Send) -> u32 { - tri.par_chunks_mut(len).zip(bary.par_chunks_mut(len)).enumerate().map(band).reduce(|| 0, u32::saturating_add) -} - -/// Run `band` on each band of `len` texels (on several threads with `parallel`) and add up the -/// overlap counts. -#[cfg(not(feature = "parallel"))] -fn each_band(tri: &mut [u32], bary: &mut [[f32; 2]], len: usize, band: impl Fn((usize, (&mut [u32], &mut [[f32; 2]]))) -> u32) -> u32 { - tri.chunks_mut(len).zip(bary.chunks_mut(len)).enumerate().map(band).fold(0, u32::saturating_add) -} - -/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). The tangent keeps the -/// direction of the interpolated vertex tangents and is not made perpendicular to the -/// interpolated normal: MikkTSpace bakers and shaders use the interpolated vectors as they are. -/// The bitangent sign is the one of the triangle's first vertex. +/// Interpolate triangle `t` at barycentrics (weights of vertices 1 and 2). pub fn surface_at(mesh: &Mesh, t: u32, b1: f32, b2: f32) -> Option { let [a, b, c] = mesh.tri(t as usize)?; let b0 = 1.0 - b1 - b2; let p = |v: &[Vec3]| -> Option { Some(*v.get(a)? * b0 + *v.get(b)? * b1 + *v.get(c)? * b2) }; let pos = p(&mesh.positions)?; - // `unit` divides by the largest component first, so a long finite vector keeps its direction. - let nrm = unit(p(&mesh.normals)?).unwrap_or(Vec3::Y); - let (pa, pb, pc) = (mesh.positions.get(a)?.as_dvec3(), mesh.positions.get(b)?.as_dvec3(), mesh.positions.get(c)?.as_dvec3()); - // The edges and their cross product are taken in `f64`, where the difference and the cross - // product of any two finite `f32` positions neither overflow nor round to zero. - let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().map_or(nrm, |n| n.as_vec3()); + let nrm = p(&mesh.normals)?.try_normalize().unwrap_or(Vec3::Y); + let (pa, pb, pc) = (*mesh.positions.get(a)?, *mesh.positions.get(b)?, *mesh.positions.get(c)?); + let geo_nrm = (pb - pa).cross(pc - pa).try_normalize().unwrap_or(nrm); let tan = *mesh.tangents.get(a)? * b0 + *mesh.tangents.get(b)? * b1 + *mesh.tangents.get(c)? * b2; let uv = *mesh.uvs.get(a)? * b0 + *mesh.uvs.get(b)? * b1 + *mesh.uvs.get(c)? * b2; - let tdir = unit(tan.truncate()).unwrap_or_else(|| nrm.any_orthonormal_vector()); + let tdir = tan.truncate().try_normalize().unwrap_or_else(|| nrm.any_orthonormal_vector()); let w = mesh.tangents.get(a).map(|t| if t.w < 0.0 { -1.0 } else { 1.0 }).unwrap_or(1.0); Some(Surface { pos, nrm, geo_nrm, tangent: tdir.extend(w), uv, tri: t }) } @@ -417,242 +197,4 @@ mod tests { } } } - - #[test] - fn surface_keeps_the_direction_of_long_finite_vectors() { - // Squaring 1e30 overflows f32: the normal, the tangent and the face normal come out along - // the vectors all the same. - let s = 1e30; - let m = Mesh { - positions: vec![Vec3::ZERO, Vec3::X * s, Vec3::Y * s], - normals: vec![Vec3::X * s; 3], - tangents: vec![Vec4::new(0.0, s, 0.0, -1.0); 3], - uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y], - indices: vec![0, 1, 2], - ..Mesh::default() - }; - let surface = surface_at(&m, 0, 0.25, 0.25).unwrap(); - assert!((surface.nrm - Vec3::X).length() < 1e-6, "{}", surface.nrm); - assert!((surface.tangent - Vec4::new(0.0, 1.0, 0.0, -1.0)).length() < 1e-6, "{}", surface.tangent); - assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm); - } - - #[test] - fn surface_face_normal_of_corners_whose_differences_overflow_f32() { - // pb - pa is 6e38, past f32::MAX: the face normal is still +Z, not the +Y shading normal. - let m = Mesh { - positions: vec![Vec3::new(-3e38, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0), Vec3::new(0.0, 3e38, 0.0)], - normals: vec![Vec3::Y; 3], - tangents: vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 3], - uvs: vec![Vec2::ZERO, Vec2::X, Vec2::Y], - indices: vec![0, 1, 2], - ..Mesh::default() - }; - m.validate().unwrap(); - let surface = surface_at(&m, 0, 0.25, 0.25).unwrap(); - assert!((surface.nrm - Vec3::Y).length() < 1e-6, "{}", surface.nrm); - assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm); - // A triangle one subnormal step wide keeps its face normal too. - let tiny = f32::from_bits(1); - let m = Mesh { positions: vec![Vec3::ZERO, Vec3::X * tiny, Vec3::Y * tiny], ..m }; - let surface = surface_at(&m, 0, 0.25, 0.25).unwrap(); - assert!((surface.geo_nrm - Vec3::Z).length() < 1e-6, "{}", surface.geo_nrm); - } - - #[test] - fn gbuffer_rejects_huge_dimensions() { - let m = primitives::plane(1.0, 2); - let l = Limits::default(); - for (w, h) in [(u32::MAX, u32::MAX), (l.max_gbuffer_side + 1, 1), (1, 0), (0, 1)] { - assert!(UvGBuffer::try_new(&m, 0, w, h, &l).is_err(), "{w} × {h}"); - assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1, 2], w, h, &l).is_err(), "{w} × {h}"); - } - let few = Limits { max_gbuffer_texels: 63, ..l }; - assert!(UvGBuffer::try_new(&m, 0, 8, 8, &few).is_err()); - // The infallible form clamps each side. - let g = UvGBuffer::new(&m, 0, u32::MAX, 0); - assert_eq!((g.width, g.height, g.tri.len()), (l.max_gbuffer_side, 1, l.max_gbuffer_side as usize)); - // The checked forms rasterize as the clamped one does. - assert_eq!(UvGBuffer::try_new(&m, 0, 16, 16, &l).unwrap(), UvGBuffer::new(&m, 0, 16, 16)); - let uvs: Vec<[f32; 2]> = m.uvs.iter().map(|uv| uv.to_array()).collect(); - assert_eq!(UvGBuffer::from_slices(&uvs, &m.indices, 16, 16, &l).unwrap(), UvGBuffer::new(&m, 0, 16, 16)); - } - - #[test] - fn gbuffer_band_stays_within_the_buffer() { - assert_eq!(band_texels(8, 8 * 100), BAND as usize * 8); - // A buffer shorter than a band is one band, even when 32 rows of its width would not fit a - // 32-bit usize (custom limits allow a side of 1 << 27). - assert_eq!(band_texels(1 << 27, 1 << 27), 1 << 27); - assert_eq!(band_texels(u32::MAX, u32::MAX as usize), u32::MAX as usize); - assert_eq!(band_texels(4, 3), 3); - // A wide one-row buffer is drawn as one band; the triangle covers its left half. - let l = Limits { max_gbuffer_side: 1 << 12, ..Limits::default() }; - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - let g = UvGBuffer::from_slices(&uvs, &[0, 1, 2], 1 << 12, 1, &l).unwrap(); - assert_eq!(g.covered_count(), 1 << 11); - } - - #[test] - fn gbuffer_slices_reject_bad_indices_and_uvs() { - let l = Limits::default(); - assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1, 3], 4, 4, &l).is_err()); - assert!(UvGBuffer::from_slices(&[[0.0, 0.0]; 3], &[0, 1], 4, 4, &l).is_err()); - assert!(UvGBuffer::from_slices(&[[0.0, 0.0], [f32::NAN, 0.0], [0.0, 1.0]], &[0, 1, 2], 4, 4, &l).is_err()); - let empty = UvGBuffer::from_slices(&[], &[], 4, 4, &l).unwrap(); - assert_eq!((empty.covered_count(), empty.overlaps), (0, 0)); - } - - #[test] - fn gbuffer_skips_triangles_whose_texel_coordinates_overflow() { - let l = Limits::default(); - // Corners that become infinite in texels, and corners whose products overflow. - for far in [1e38f32, 1e30] { - let g = UvGBuffer::from_slices(&[[far, 0.0], [-far, 0.0], [0.0, far]], &[0, 1, 2], 8, 8, &l).unwrap(); - assert_eq!(g.covered_count(), 0, "{far}"); - assert!(g.bary.iter().flatten().all(|w| w.is_finite()), "{far}"); - } - // A large triangle within reach covers every texel with weights that add up to one. - let g = UvGBuffer::from_slices(&[[-1e6, -1e6], [1e6, -1e6], [0.0, 1e6]], &[0, 1, 2], 8, 8, &l).unwrap(); - assert_eq!(g.covered_count(), 64); - assert!(g.bary.iter().all(|[b1, b2]| (0.0..=1.0).contains(b1) && (0.0..=1.0).contains(b2) && b1 + b2 <= 1.0 + 1e-6), "{:?}", g.bary); - } - - #[test] - fn gbuffer_edge_tolerance_is_a_texel_distance() { - // The triangle covers u + v <= 0, so no texel center is inside it, while its box covers - // every texel of the buffer and its area is about 2.8e14 square texels. - let m = 1_048_576.0; - let g = UvGBuffer::from_slices(&[[-m, -m], [m, -m], [-m, m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 0); - // A sliver 0.1 texel high whose corners lie 8e14 texels to either side: the rounding at - // those coordinates does not widen it to the texel centers at y = 0.5. - let g = UvGBuffer::from_slices(&[[-1e14, 0.0], [1e14, 0.0], [0.0, 0.0125]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 0); - // The same triangle mirrored to cover u + v >= 0 covers every texel center. - let g = UvGBuffer::from_slices(&[[m, m], [-m, m], [m, -m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 64); - // The same triangles with corners up to 1e18 texels away, the farthest that is drawn. - for m in [1e15_f32, 1.25e17] { - let g = UvGBuffer::from_slices(&[[-m, -m], [m, -m], [-m, m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 0, "{m}"); - let g = UvGBuffer::from_slices(&[[m, m], [-m, m], [m, -m]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 64, "{m}"); - assert!(g.bary.iter().all(|[b1, b2]| (0.0..=1.0).contains(b1) && (0.0..=1.0).contains(b2)), "{m}: {:?}", g.bary); - let g = UvGBuffer::from_slices(&[[-m, 0.0], [m, 0.0], [0.0, 0.0125]], &[0, 1, 2], 8, 8, &Limits::default()).unwrap(); - assert_eq!(g.covered_count(), 0, "{m}"); - } - } - - /// The `what`, `got` and `limit` of a `TooLarge` error, `None` for any other result. - fn too_large(r: Result) -> Option<(&'static str, u64, u64)> { - match r { - Err(MeshOpsError::TooLarge { what, got, limit }) => Some((what, got, limit)), - _ => None, - } - } - - #[test] - fn gbuffer_rejects_overlapping_box_work_before_rasterization() { - // Five triangles whose boxes each cover the whole 8 × 8 buffer: 320 texel visits. - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - let indices = [0, 1, 2].repeat(5); - let l = Limits::default(); - let four = Limits { max_gbuffer_work: 4 * 64, ..l }; - assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &four)), Some(("G-buffer work", 320, 256))); - let five = Limits { max_gbuffer_work: 5 * 64, ..l }; - assert_eq!(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &five).unwrap(), UvGBuffer::from_slices(&uvs, &indices, 8, 8, &l).unwrap()); - } - - #[test] - fn gbuffer_rejects_excess_band_entries() { - // Three triangles that each reach the four bands of a 128-row buffer: 12 entries. - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - let indices = [0, 1, 2].repeat(3); - let l = Limits::default(); - let under = Limits { max_gbuffer_bin_entries: 11, ..l }; - assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 16, 128, &under)), Some(("G-buffer band entries", 12, 11))); - let exact = Limits { max_gbuffer_bin_entries: 12, ..l }; - let g = UvGBuffer::from_slices(&uvs, &indices, 16, 128, &exact).unwrap(); - assert_eq!(g, UvGBuffer::from_slices(&uvs, &indices, 16, 128, &l).unwrap()); - // Every band draws the triangles in order: the last one keeps each texel. - let covered = g.covered_count(); - assert!(covered > 16 * 128 / 3, "{covered}"); - assert!(g.tri.iter().all(|t| *t == 2 || *t == NO_TRI)); - assert_eq!(g.overlaps as usize, 2 * covered); - } - - #[test] - fn gbuffer_mesh_constructor_respects_count_limits() { - let m = primitives::plane(1.0, 2); - let l = Limits::default(); - let (v, t) = (m.vertex_count(), m.triangle_count()); - let few_triangles = Limits { max_triangles: t - 1, ..l }; - assert_eq!(too_large(UvGBuffer::try_new(&m, 0, 16, 16, &few_triangles)), Some(("triangle count", t as u64, t as u64 - 1))); - let few_vertices = Limits { max_vertices: v - 1, ..l }; - assert_eq!(too_large(UvGBuffer::try_new(&m, 0, 16, 16, &few_vertices)), Some(("vertex count", v as u64, v as u64 - 1))); - let exact = Limits { max_vertices: v, max_triangles: t, ..l }; - assert_eq!(UvGBuffer::try_new(&m, 0, 16, 16, &exact).unwrap(), UvGBuffer::new(&m, 0, 16, 16)); - // Submeshes that list the same triangles again count every time they are visited. - let mut twice = m.clone(); - twice.submeshes.push(twice.submeshes[0].clone()); - assert_eq!(too_large(UvGBuffer::try_new(&twice, 0, 16, 16, &exact)), Some(("triangle count", t as u64 + 1, t as u64))); - } - - #[test] - fn gbuffer_work_counts_clipped_boxes_and_skips_off_image() { - let uvs = [ - // A 2 × 2 texel box. - [0.5, 0.5], - [0.75, 0.5], - [0.5, 0.75], - // Entirely past the right and bottom edges. - [2.0, 2.0], - [3.0, 2.0], - [2.0, 3.0], - // Infinite once scaled to texels. - [1e38, 0.0], - [-1e38, 0.0], - [0.0, 1e38], - // A triangle over the whole image whose box is clipped to its 64 texels. - [-1.0, -1.0], - [3.0, -1.0], - [-1.0, 3.0], - ]; - let indices: Vec = (0..12).collect(); - let l = Limits::default(); - let under = Limits { max_gbuffer_work: 67, ..l }; - assert_eq!(too_large(UvGBuffer::from_slices(&uvs, &indices, 8, 8, &under)), Some(("G-buffer work", 68, 67))); - let exact = Limits { max_gbuffer_work: 68, ..l }; - let g = UvGBuffer::from_slices(&uvs, &indices, 8, 8, &exact).unwrap(); - assert_eq!(g, UvGBuffer::from_slices(&uvs, &indices, 8, 8, &l).unwrap()); - // The small triangle covers 3 texels, which the large one draws over. - assert_eq!((g.covered_count(), g.overlaps), (64, 3)); - } - - /// Texel buffers of `2^28 × 2^28` (2^58 and 2^59 bytes) are past every 64-bit address space, - /// so their reservation fails, and a work or band-entry rejection shows that the budgets are - /// checked first. - #[cfg(target_pointer_width = "64")] - #[test] - fn gbuffer_budgets_are_checked_before_the_texels_are_reserved() { - let huge = Limits { max_gbuffer_side: u32::MAX, max_gbuffer_texels: u64::MAX, max_gbuffer_work: u64::MAX, ..Limits::default() }; - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - let m = primitives::plane(1.0, 2); - let side = 1 << 28; - let cases = - [(Limits { max_gbuffer_work: 0, ..huge }, "G-buffer work"), (Limits { max_gbuffer_bin_entries: 0, ..huge }, "G-buffer band entries")]; - for (limits, what) in cases { - let slices = too_large(UvGBuffer::from_slices(&uvs, &[0, 1, 2], side, side, &limits)); - assert_eq!(slices.map(|(w, _, l)| (w, l)), Some((what, 0))); - let mesh = too_large(UvGBuffer::try_new(&m, 0, side, side, &limits)); - assert_eq!(mesh.map(|(w, _, l)| (w, l)), Some((what, 0))); - } - // A size whose texel arrays no allocation can hold is refused before the band lists are - // reserved, even with no triangles. - for (w, h) in [(u32::MAX, u32::MAX), (1 << 31, 1 << 30)] { - assert!(matches!(UvGBuffer::from_slices(&[], &[], w, h, &huge), Err(MeshOpsError::OutOfMemory("G-buffer"))), "{w} × {h}"); - assert!(matches!(UvGBuffer::try_new(&m, 0, w, h, &huge), Err(MeshOpsError::OutOfMemory("G-buffer"))), "{w} × {h}"); - } - } } diff --git a/crates/mesh-ops/src/lib.rs b/crates/mesh-ops/src/lib.rs index 56f63f9fde..1152aad8f2 100644 --- a/crates/mesh-ops/src/lib.rs +++ b/crates/mesh-ops/src/lib.rs @@ -1,19 +1,11 @@ //! # craft-mesh-ops //! -//! Operations on triangle meshes: area-weighted smooth normals, MikkTSpace tangents, welding, -//! automatic UV unwrapping, the UV-space [`UvGBuffer`] that maps texels to surface points, -//! built-in [`primitives`] with UVs, a [`Bvh`] for ray casts and box queries (feature `bvh`) and -//! the [`OrbitCamera`]. -//! -//! The functions at the crate root take plain slices: positions and normals as `[f32; 3]`, UVs as -//! `[f32; 2]` in the glTF convention (origin top-left, v down), tangents as `[f32; 4]` with the -//! bitangent sign in `w`, and triangle indices as `u32`. They check the input against -//! [`Limits`] and reject a non-finite value or an index past the last vertex before any work. -//! The [`Mesh`] type holds the same arrays for callers that keep several materials together. +//! Triangle mesh operations: the [`Mesh`] type with normals and MikkTSpace tangents, built-in +//! [`primitives`] (material ball, sphere, cube, …), a [`Bvh`] for ray casts and box queries, +//! the UV-space [`UvGBuffer`] that maps texels to surface points, and the [`OrbitCamera`]. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -#[cfg(feature = "bvh")] pub mod bvh; pub mod camera; pub mod gbuffer; @@ -21,180 +13,16 @@ pub mod mesh; pub mod primitives; pub mod unwrap; -#[cfg(feature = "bvh")] pub use bvh::{Bvh, Hit}; pub use camera::{OrbitCamera, Ray}; pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; -pub use mesh::{MAX_TRIANGLES, Mesh, SubMesh}; +pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; -use glam::Vec3; - -/// Why an operation did not run. #[derive(Debug, thiserror::Error, Clone, PartialEq)] -pub enum MeshOpsError { - /// The input is malformed: mismatched array lengths, an index out of range, a non-finite - /// value or an invalid parameter. +pub enum GeomError { #[error("invalid mesh: {0}")] Invalid(String), - /// A count is over its [`Limits`] field. - #[error("{what} {got} is over the limit of {limit}")] - TooLarge { what: &'static str, got: u64, limit: u64 }, - /// Memory for the result could not be reserved. - #[error("out of memory for {0}")] - OutOfMemory(&'static str), } -pub type Result = std::result::Result; - -/// Caps on the work one call does. Every slice function and `try_` constructor checks its input -/// against these before allocating. A UV G-buffer has three budgets: the texels it outputs, the -/// texels its rasterizer visits and the entries of its per-band triangle lists. The defaults -/// follow `craft-mesh` for whole meshes and are this crate's own values for the rest. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Limits { - /// Vertices in one input or output mesh. Default 20,000,000. - pub max_vertices: usize, - /// Triangles in one input or output mesh. Default 20,000,000. - pub max_triangles: usize, - /// Segments, rings or subdivisions along one direction of a primitive. Default 2,048. - pub max_segments: usize, - /// Width or height of a UV G-buffer. Default 8,192. - pub max_gbuffer_side: u32, - /// Texels in a UV G-buffer. Default 2^26 (8,192 × 8,192). - pub max_gbuffer_texels: u64, - /// Texels a UV G-buffer's rasterizer visits: the sum over its triangles of the texels in - /// each one's bounding box clipped to the buffer, covered or not. Default 2^32. - pub max_gbuffer_work: u64, - /// Entries in a UV G-buffer's per-band triangle lists: one per band of 32 rows that a - /// triangle's clipped bounding box reaches. Default 2^26; a value over `usize::MAX` counts - /// as `usize::MAX`. - pub max_gbuffer_bin_entries: u64, - /// Triangles one UV unwrap processes. Default 4,000,000. - pub max_unwrap_triangles: usize, -} - -impl Default for Limits { - fn default() -> Self { - Limits { - max_vertices: 20_000_000, - max_triangles: 20_000_000, - max_segments: 2_048, - max_gbuffer_side: 8_192, - max_gbuffer_texels: 1 << 26, - max_gbuffer_work: 1 << 32, - max_gbuffer_bin_entries: 1 << 26, - max_unwrap_triangles: 4_000_000, - } - } -} - -/// `Err(TooLarge)` when `got` is over `limit`. -pub(crate) fn check_limit(what: &'static str, got: usize, limit: usize) -> Result<()> { - if got > limit { Err(MeshOpsError::TooLarge { what, got: got as u64, limit: limit as u64 }) } else { Ok(()) } -} - -/// An empty vector with room for `len` elements, or `OutOfMemory`. -pub(crate) fn try_vec(len: usize, what: &'static str) -> Result> { - let mut v = Vec::new(); - v.try_reserve_exact(len).map_err(|_| MeshOpsError::OutOfMemory(what))?; - Ok(v) -} - -/// `len` copies of `value`, or `OutOfMemory`. -pub(crate) fn try_filled(len: usize, value: T, what: &'static str) -> Result> { - let mut v = try_vec(len, what)?; - v.resize(len, value); - Ok(v) -} - -/// `OutOfMemory` for `what` in place of a failed reservation. -pub(crate) fn reserved(r: std::result::Result<(), std::collections::TryReserveError>, what: &'static str) -> Result<()> { - r.map_err(|_| MeshOpsError::OutOfMemory(what)) -} - -/// The result of [`unwrap_uvs`]: vertices are split where charts meet, so the output has its own -/// vertex list. -#[derive(Clone, Debug, PartialEq)] -pub struct Unwrapped { - /// The input vertex each output vertex copies. - pub source: Vec, - /// One UV per output vertex, in 0..1. - pub uvs: Vec<[f32; 2]>, - /// Triangles over the output vertices, in the input's triangle order. - pub indices: Vec, - /// Number of charts. - pub charts: usize, -} - -/// Axis-aligned bounds of `positions`, or `None` when there are none. A non-finite coordinate is -/// an error. -pub fn bounds(positions: &[[f32; 3]]) -> Result> { - let mut found: Option<(Vec3, Vec3)> = None; - for p in positions { - let p = Vec3::from_array(*p); - if !p.is_finite() { - return Err(MeshOpsError::Invalid("non-finite position".into())); - } - found = Some(found.map_or((p, p), |(lo, hi)| (lo.min(p), hi.max(p)))); - } - Ok(found.map(|(lo, hi)| (lo.to_array(), hi.to_array()))) -} - -/// Area-weighted smooth normals, one per vertex. A vertex no triangle uses gets +Y. -pub fn smooth_normals(positions: &[[f32; 3]], indices: &[u32], limits: &Limits) -> Result> { - let mut mesh = Mesh::from_slices(positions, None, None, indices, limits)?; - mesh.try_compute_normals()?; - let mut out = try_vec(mesh.normals.len(), "normals")?; - out.extend(mesh.normals.iter().map(|n| n.to_array())); - Ok(out) -} - -/// MikkTSpace tangents, one per vertex: xyz tangent and the bitangent sign in `w`, so that -/// `cross(normal, tangent) * w` points up the image (glTF 2.0). Meshes MikkTSpace cannot handle -/// (every triangle degenerate, no UV area, more than [`mesh::MAX_MIKKTSPACE_VALENCE`] triangles -/// around one vertex, corners at one position whose welding would take more than -/// [`mesh::MAX_MIKKTSPACE_WELD_WORK`] comparisons) get per-vertex tangents instead, with `w` set -/// the same way. The normals are unit vectors, as glTF -/// 2.0 stores them: each tangent is made perpendicular to its normal with a projection that is -/// exact only at unit length. -/// -/// A vertex whose triangles need different tangent frames (UVs mirrored across it) cannot have -/// one tangent: that is an `Invalid` error naming the vertex. [`Mesh::compute_tangents`] splits -/// such vertices instead. -pub fn tangents(positions: &[[f32; 3]], normals: &[[f32; 3]], uvs: &[[f32; 2]], indices: &[u32], limits: &Limits) -> Result> { - let mut mesh = Mesh::from_slices(positions, Some(normals), Some(uvs), indices, limits)?; - mesh.try_compute_tangents_splitting(mesh::Split::Refuse)?; - let mut out = try_vec(mesh.tangents.len(), "tangents")?; - out.extend(mesh.tangents.iter().map(|t| t.to_array())); - Ok(out) -} - -/// Welded vertex id per vertex, as [`unwrap::weld_ids`] gives it, for finite positions. -pub fn weld(positions: &[[f32; 3]], limits: &Limits) -> Result> { - check_limit("vertex count", positions.len(), limits.max_vertices)?; - let mut p = try_vec(positions.len(), "positions")?; - for q in positions { - let q = Vec3::from_array(*q); - if !q.is_finite() { - return Err(MeshOpsError::Invalid("non-finite position".into())); - } - p.push(q); - } - unwrap::weld_ids(&p) -} - -/// An automatic non-overlapping UV layout for one material, as [`unwrap::auto_unwrap`] makes it. -/// The vertex limit applies to the input and to the output, which has more vertices where -/// charts meet. A padding that is not finite is an error; one under 1 texel counts as 1. -pub fn unwrap_uvs(positions: &[[f32; 3]], indices: &[u32], padding_texels: f32, resolution: u32, limits: &Limits) -> Result { - if !padding_texels.is_finite() { - return Err(MeshOpsError::Invalid(format!("padding {padding_texels} is not finite"))); - } - check_limit("triangle count", indices.len() / 3, limits.max_unwrap_triangles)?; - let mut mesh = Mesh::from_slices(positions, None, None, indices, limits)?; - let (charts, source) = unwrap::unwrap_core(&mut mesh, padding_texels, resolution, limits)?; - let mut uvs = try_vec(mesh.uvs.len(), "UVs")?; - uvs.extend(mesh.uvs.iter().map(|uv| uv.to_array())); - Ok(Unwrapped { source, uvs, indices: mesh.indices, charts }) -} +pub type Result = std::result::Result; diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 2eed6a0d2b..77c993d3c6 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -1,8 +1,8 @@ //! The internal triangle mesh. -use glam::{DVec3, Vec2, Vec3, Vec4}; +use glam::{Vec2, Vec3, Vec4}; -use crate::{Limits, MeshOpsError, Result, check_limit, reserved, try_filled, try_vec}; +use crate::{GeomError, Result}; /// An edge by the bits of its two end positions, the lower one first type EdgePositions = ([u32; 3], [u32; 3]); @@ -17,6 +17,18 @@ pub struct SubMesh { pub count: u32, } +/// A material's base color (what a color-map bake transfers): `factor` (linear RGBA) times an +/// optional texture sampled at the mesh UVs. +#[derive(Clone, Debug, PartialEq)] +pub struct BaseColor { + pub factor: Vec4, + pub width: u32, + pub height: u32, + /// `width × height` RGBA8 texels (color sRGB-encoded, alpha linear), rows top → bottom like + /// the UVs' v; empty without a texture. + pub texels: Vec<[u8; 4]>, +} + /// Triangle mesh in world space. UVs use the glTF convention (origin top-left, v down). #[derive(Clone, Debug, Default, PartialEq)] pub struct Mesh { @@ -39,183 +51,6 @@ pub struct Mesh { /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; -/// Positions and UVs whose largest magnitude lies between the reciprocal of this and this go -/// into normal, tangent and unwrap arithmetic as they are. Others are divided by the largest -/// magnitude first, so edge lengths, cross products, their products with UVs and the squares of -/// those neither overflow nor underflow. The results depend only on directions, which a uniform -/// scale keeps. -const SAFE_MAGNITUDE: f32 = 1e6; - -/// The smallest value [`Mesh::radius`] returns. -const MIN_RADIUS: f32 = 1e-4; - -/// Normals whose largest component lies between the reciprocal of this and this go to MikkTSpace -/// as they are: every unit vector does. MikkTSpace multiplies a normal twice into products of -/// positions and UVs, so longer normals are divided first. -const SAFE_NORMAL_MAGNITUDE: f32 = 2.0; - -/// Most triangles around one vertex (as MikkTSpace welds vertices) for which tangents come from -/// MikkTSpace. It visits the triangles around a vertex recursively, one call per triangle, so a -/// larger fan could exhaust the stack; such meshes get the per-vertex fallback. This crate's own -/// value, the same as the default [`Limits::max_segments`]. -pub const MAX_MIKKTSPACE_VALENCE: usize = 2_048; - -/// Most comparisons MikkTSpace may make welding corners, for which tangents come from it. It -/// compares each corner with the corners before it at the same position until one has the same -/// normal and UV, so `k` corners at one position can cost about `k²` comparisons; the sum of `k²` -/// over the positions stays within this. This crate's own value: the 6,144 corners at the pole of -/// a sphere with 2,048 segments take about 3.8e7. -pub const MAX_MIKKTSPACE_WELD_WORK: u64 = 1 << 27; - -/// The vertex copies [`Mesh::try_compute_tangents_splitting`] may make for different tangent -/// frames. -#[derive(Clone, Copy, Debug)] -pub(crate) enum Split { - /// Copies while the vertex count stays within this; a copy past it is `TooLarge`. - UpTo(usize), - /// No copies: a vertex that needs one is an `Invalid` error naming it. - Refuse, -} - -/// `v` at unit length, also when its squared length overflows or rounds to zero. `None` for a -/// zero or non-finite vector. -pub(crate) fn unit(v: Vec3) -> Option { - v.try_normalize().or_else(|| (v / v.abs().max_element()).try_normalize()) -} - -/// The largest absolute value, or `None` when a value is not finite. -pub(crate) fn largest_abs(values: impl IntoIterator) -> Option { - let mut largest = 0.0f32; - for v in values { - if !v.is_finite() { - return None; - } - largest = largest.max(v.abs()); - } - Some(largest) -} - -/// The divisor that brings positions or UVs of magnitude `largest` into the safe range: 1 when -/// they are already in it, are all zero or are not finite. -pub(crate) fn safe_divisor(largest: Option) -> f32 { - divisor_into(largest, SAFE_MAGNITUDE) -} - -/// The divisor that brings values of magnitude `largest` to between `1 / limit` and `limit`: 1 -/// when they are already there, are all zero or are not finite. -fn divisor_into(largest: Option, limit: f32) -> f32 { - match largest { - Some(m) if m > limit || (m > 0.0 && m < 1.0 / limit) => m, - _ => 1.0, - } -} - -/// The index range of a submesh, when it starts and ends on a triangle boundary inside `len` -/// indices. -fn submesh_range(s: &SubMesh, len: usize) -> Option> { - let end = u64::from(s.start) + u64::from(s.count); - (s.start.is_multiple_of(3) && s.count.is_multiple_of(3) && end <= len as u64).then_some(s.start as usize..end as usize) -} - -/// `listed + add` triangle visits, or `TooLarge` when that is over [`Limits::max_triangles`] -/// (`got` is `u64::MAX` when the sum overflows). -fn within_triangle_limit(listed: u64, add: usize, limits: &Limits) -> Result { - let (got, limit) = (listed.saturating_add(add as u64), limits.max_triangles as u64); - if got > limit { Err(MeshOpsError::TooLarge { what: "triangle count", got, limit }) } else { Ok(got) } -} - -/// The parts of each of `ranges` that no earlier one holds: in the order of `ranges`, and -/// ascending within each, so every value the ranges hold comes once, from the first range that -/// holds it. Memory and time grow with the number of ranges, not with their lengths. -fn first_listings(ranges: &[std::ops::Range]) -> Result>> { - use std::cmp::Reverse; - let what = "wire edges"; - // Range starts in ascending order, and every start and end once, ascending. - let mut starts = try_vec(ranges.len(), what)?; - let mut points = try_vec(ranges.len().saturating_mul(2), what)?; - for (i, r) in ranges.iter().enumerate().filter(|(_, r)| r.start < r.end) { - starts.push((r.start, i)); - points.extend([r.start, r.end]); - } - starts.sort_unstable(); - points.sort_unstable(); - points.dedup(); - - // Sweep the points, keeping the ranges that hold the current point with the earliest on top. - let mut active = std::collections::BinaryHeap::new(); - reserved(active.try_reserve(starts.len()), what)?; - let mut parts: Vec<(usize, std::ops::Range)> = Vec::new(); - let mut next = starts.iter().peekable(); - for (k, &p) in points.iter().enumerate() { - while let Some(&(_, i)) = next.next_if(|(s, _)| *s == p) { - active.push(Reverse(i)); - } - while active.peek().is_some_and(|Reverse(i)| ranges.get(*i).is_none_or(|r| r.end <= p)) { - active.pop(); - } - let (Some(&Reverse(owner)), Some(&end)) = (active.peek(), points.get(k + 1)) else { continue }; - match parts.last_mut() { - Some((last, part)) if *last == owner && part.end == p => part.end = end, - _ => { - reserved(parts.try_reserve(1), what)?; - parts.push((owner, p..end)); - } - } - } - parts.sort_unstable_by_key(|(owner, part)| (*owner, part.start)); - let mut out = try_vec(parts.len(), what)?; - out.extend(parts.into_iter().map(|(_, part)| part)); - Ok(out) -} - -/// Whether an array of `len` entries has one per vertex of a mesh with `n` vertices. A mesh -/// without vertices has no attributes to pass on to a mesh it is appended to. -fn per_vertex(len: usize, n: usize) -> bool { - n > 0 && len == n -} - -/// The centroid of a triangle's three UVs, summed in f64: the centroid of finite UVs is finite -/// even when their f32 sum would overflow. -fn uv_centroid(uvs: [Vec2; 3]) -> Vec2 { - (uvs.iter().map(Vec2::as_dvec2).sum::() / 3.0).as_vec2() -} - -/// A copy of `from` in a reserved array, or `OutOfMemory` naming `what`. Copying a `Copy` element -/// does not allocate; [`try_names`] and [`try_submeshes`] copy elements that own a string. -fn try_copy(from: &[T], what: &'static str) -> Result> { - let mut v = try_vec(from.len(), what)?; - v.extend_from_slice(from); - Ok(v) -} - -/// A copy of `name` in a reserved string, or `OutOfMemory` naming `what`. -fn try_name(name: &str, what: &'static str) -> Result { - let mut s = String::new(); - reserved(s.try_reserve_exact(name.len()), what)?; - #[cfg(test)] - tests::name_copy(what)?; - s.push_str(name); - Ok(s) -} - -/// Copies of `names`, each in a reserved string, or `OutOfMemory` naming `what`. -fn try_names(names: &[String], what: &'static str) -> Result> { - let mut v = try_vec(names.len(), what)?; - for name in names { - v.push(try_name(name, what)?); - } - Ok(v) -} - -/// Copies of `submeshes` with their names in reserved strings, or `OutOfMemory` naming `what`. -fn try_submeshes(submeshes: &[SubMesh], what: &'static str) -> Result> { - let mut v = try_vec(submeshes.len(), what)?; - for s in submeshes { - v.push(SubMesh { name: try_name(&s.name, what)?, material: s.material, start: s.start, count: s.count }); - } - Ok(v) -} - impl Mesh { pub fn triangle_count(&self) -> usize { self.indices.len() / 3 @@ -225,91 +60,65 @@ impl Mesh { self.positions.len() } - /// Axis-aligned bounds of the finite positions (zero box when there are none). Non-finite - /// positions are left out, so one cannot turn the box into NaN or hide a coordinate. + /// Axis-aligned bounds (zero box for an empty mesh). pub fn bounds(&self) -> (Vec3, Vec3) { - self.positions - .iter() - .filter(|p| p.is_finite()) - .fold(None, |b: Option<(Vec3, Vec3)>, p| Some(b.map_or((*p, *p), |(lo, hi)| (lo.min(*p), hi.max(*p))))) - .unwrap_or((Vec3::ZERO, Vec3::ZERO)) + if self.positions.is_empty() { + return (Vec3::ZERO, Vec3::ZERO); + } + self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) } - /// Bounding-sphere radius around the bounds center, at least 1e-4. Bounds wider than - /// `f32::MAX` give `f32::MAX`. + /// Bounding-sphere radius around the bounds center (at least a small epsilon). pub fn radius(&self) -> f32 { let (lo, hi) = self.bounds(); - let half = hi * 0.5 - lo * 0.5; - let largest = half.abs().max_element(); - let length = if largest > SAFE_MAGNITUDE { (half / largest).length() * largest } else { (hi - lo).length() * 0.5 }; - length.clamp(MIN_RADIUS, f32::MAX) + ((hi - lo).length() * 0.5).max(1e-4) } /// Vertex indices of triangle `t`. pub fn tri(&self, t: usize) -> Option<[usize; 3]> { - let start = t.checked_mul(3)?; - let i = self.indices.get(start..start.checked_add(3)?)?; + let i = self.indices.get(t * 3..t * 3 + 3)?; Some([i[0] as usize, i[1] as usize, i[2] as usize]) } /// The edges wireframes draw: each vertex pair once (smaller index first), leaving out /// polygon diagonals ([`Mesh::diagonals`]) unless only one triangle has the edge (a UV seam - /// split it from its twin), per material in `0..materials.len().max(1)`. A triangle that - /// several submeshes of one material list counts once for an edge. The triangles the - /// submeshes list (a triangle counts again for each submesh that lists it) over - /// [`Limits::max_triangles`] are `TooLarge`. - pub fn wire_edges(&self, limits: &Limits) -> Result>> { - let groups = self.ranges_by_material(limits)?; - let mut out = try_vec(groups.len(), "wire edges")?; - for ranges in &groups { - // Edge → (real in some triangle, triangles using it), in first-seen order. - let mut edges: Vec<((u32, u32), bool, u8)> = Vec::new(); - let mut at: std::collections::HashMap<(u32, u32), usize> = std::collections::HashMap::new(); - // Each listed triangle once, where its first submesh lists it. - for r in first_listings(ranges)? { - for t in r { + /// split it from its twin), per material in `0..materials.len().max(1)`. + pub fn wire_edges(&self) -> Vec> { + (0..self.materials.len().max(1)) + .map(|m| { + // Edge → (real in some triangle, triangles using it), in first-seen order. + 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 = match at.get(&key) { - Some(&e) => e, - None => { - reserved(edges.try_reserve(1), "wire edges")?; - reserved(at.try_reserve(1), "wire edges")?; - edges.push((key, false, 0)); - at.insert(key, edges.len() - 1); - edges.len() - 1 - } - }; + let e = *at.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); } } } - } - let mut kept = try_vec(edges.len(), "wire edges")?; - kept.extend(edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k)); - out.push(kept); - } - Ok(out) + edges.into_iter().filter(|(_, real, n)| *real || *n == 1).map(|(k, ..)| k).collect() + }) + .collect() } - /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per - /// material in `0..materials.len().max(1)`. The triangles the submeshes list (a triangle - /// counts again for each submesh that lists it) over [`Limits::max_triangles`] are - /// `TooLarge`. - pub fn uv_seam_edges(&self, limits: &Limits) -> Result>> { + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { // 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 groups = self.ranges_by_material(limits)?; - let mut seams: Vec> = try_filled(groups.len(), Vec::new(), "UV seams")?; + 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> = std::collections::HashMap::new(); - for (material, ranges) in groups.iter().enumerate() { - for triangle in ranges.iter().cloned().flatten() { + for material in 0..seams.len() { + for triangle in self.triangles_of(material) { let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { @@ -319,10 +128,7 @@ impl Mesh { let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; - reserved(sides.try_reserve(1), "UV seams")?; - let list = sides.entry(edge).or_default(); - reserved(list.try_reserve(1), "UV seams")?; - list.push((pair.0, pair.1, material)); + sides.entry(edge).or_default().push((pair.0, pair.1, material)); } } } @@ -334,7 +140,6 @@ impl Mesh { if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { for (from, to, material) in pairs { if let Some(edges) = seams.get_mut(material) { - reserved(edges.try_reserve(1), "UV seams")?; edges.push((from.min(to), from.max(to))); } } @@ -345,97 +150,25 @@ impl Mesh { edges.dedup(); } - Ok(seams) + seams } /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { - let idx = u64::try_from(t.checked_mul(3)?).ok()?; - self.submeshes.iter().find(|s| idx >= u64::from(s.start) && idx < u64::from(s.start) + u64::from(s.count)).map(|s| s.material) + let idx = (t * 3) as u32; + self.submeshes.iter().find(|s| idx >= s.start && idx < s.start.saturating_add(s.count)).map(|s| s.material) } - /// Triangle index range belonging to material `m` (all submeshes of that material), within - /// the index buffer. + /// Triangle index range belonging to material `m` (all submeshes of that material). pub fn triangles_of(&self, m: usize) -> impl Iterator + '_ { - self.submeshes.iter().filter(move |s| s.material == m).flat_map(move |s| self.listed(s)) + self.submeshes.iter().filter(move |s| s.material == m).flat_map(|s| (s.start / 3) as usize..((s.start + s.count) / 3) as usize) } - /// The triangles of submesh `s` within the index buffer, as [`Mesh::triangles_of`] visits - /// them. - fn listed(&self, s: &SubMesh) -> std::ops::Range { - let end = (u64::from(s.start) + u64::from(s.count)).min(self.indices.len() as u64); - (s.start / 3) as usize..(end / 3) as usize - } - - /// How many triangles [`Mesh::triangles_of`] visits for material `m` (a triangle counts again - /// for each submesh that lists it), or `TooLarge` when that is over [`Limits::max_triangles`]. - fn listed_of(&self, m: usize, limits: &Limits) -> Result { - let mut listed = 0u64; - for s in self.submeshes.iter().filter(|s| s.material == m) { - listed = within_triangle_limit(listed, self.listed(s).len(), limits)?; - } - // At most `max_triangles`, a usize. - Ok(listed as usize) - } - - /// Whether a submesh of a material other than `m` lists a triangle that a submesh of `m` - /// lists. The memory used grows with the number of `m`'s submeshes, not with the mesh. - fn listed_by_other(&self, m: usize) -> Result { - let mut own = Vec::new(); - for s in self.submeshes.iter().filter(|s| s.material == m) { - let r = self.listed(s); - if r.start < r.end { - reserved(own.try_reserve(1), "material triangles")?; - own.push(r); - } - } - if own.is_empty() { - return Ok(false); - } - own.sort_unstable_by_key(|r| r.start); - // Merge overlapping and touching ranges, so the ends ascend with the starts. - let mut merged: Vec> = try_vec(own.len(), "material triangles")?; - for r in own { - match merged.last_mut() { - Some(last) if r.start <= last.end => last.end = last.end.max(r.end), - _ => merged.push(r), - } - } - Ok(self.submeshes.iter().filter(|s| s.material != m).any(|s| { - let r = self.listed(s); - // The first merged range that ends after `r` starts overlaps `r` when it starts before `r` ends. - let i = merged.partition_point(|x| x.end <= r.start); - r.start < r.end && merged.get(i).is_some_and(|x| x.start < r.end) - })) - } - - /// The triangle ranges of each material in `0..materials.len().max(1)`, in submesh order, - /// from one pass over the submeshes. The triangles they list (a triangle counts again for - /// each submesh that lists it) over [`Limits::max_triangles`] are `TooLarge`, before any - /// memory is reserved. - fn ranges_by_material(&self, limits: &Limits) -> Result>>> { - let materials = self.materials.len().max(1); - let mut listed = 0u64; - for s in self.submeshes.iter().filter(|s| s.material < materials) { - listed = within_triangle_limit(listed, self.listed(s).len(), limits)?; - } - let mut groups = try_vec(materials, "submesh ranges")?; - groups.resize_with(materials, Vec::new); - for s in &self.submeshes { - if let Some(group) = groups.get_mut(s.material) { - reserved(group.try_reserve(1), "submesh ranges")?; - group.push(self.listed(s)); - } - } - Ok(groups) - } - - /// Check that attribute arrays agree, every value is finite, every index is in range and - /// every submesh covers whole triangles inside the index buffer. + /// Check that attribute arrays agree and every index is in range. pub fn validate(&self) -> Result<()> { let n = self.positions.len(); if self.normals.len() != n || self.uvs.len() != n || self.tangents.len() != n { - return Err(MeshOpsError::Invalid(format!( + return Err(GeomError::Invalid(format!( "attribute counts differ: {} positions, {} normals, {} uvs, {} tangents", n, self.normals.len(), @@ -444,323 +177,136 @@ impl Mesh { ))); } if !self.colors.is_empty() && self.colors.len() != n { - return Err(MeshOpsError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); + return Err(GeomError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); } if !self.indices.len().is_multiple_of(3) { - return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into())); + return Err(GeomError::Invalid("index count is not a multiple of 3".into())); } if self.triangle_count() > MAX_TRIANGLES { - return Err(MeshOpsError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); + return Err(GeomError::Invalid(format!("mesh has more than {MAX_TRIANGLES} triangles"))); } if let Some(bad) = self.indices.iter().find(|i| **i as usize >= n) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({n} vertices)"))); + return Err(GeomError::Invalid(format!("index {bad} out of range ({n} vertices)"))); } if self.positions.iter().any(|p| !p.is_finite()) { - return Err(MeshOpsError::Invalid("mesh has non-finite positions".into())); - } - if self.normals.iter().any(|v| !v.is_finite()) - || self.uvs.iter().any(|v| !v.is_finite()) - || self.tangents.iter().any(|v| !v.is_finite()) - || self.colors.iter().any(|v| !v.is_finite()) - { - return Err(MeshOpsError::Invalid("mesh has non-finite normals, UVs, tangents or colors".into())); + return Err(GeomError::Invalid("mesh has non-finite positions".into())); } for s in &self.submeshes { - if submesh_range(s, self.indices.len()).is_none() || s.material >= self.materials.len().max(1) { - return Err(MeshOpsError::Invalid(format!("submesh {} is out of range", s.name))); + if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); } } Ok(()) } - /// Area-weighted smooth normals over the index buffer. Leaves the normals unchanged when the - /// memory for them cannot be reserved. + /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { - let _ = self.try_compute_normals(); - } - - /// [`Mesh::compute_normals`], or `OutOfMemory` with the mesh unchanged. - pub fn try_compute_normals(&mut self) -> Result<()> { - self.normals = self.smooth_normals()?; - Ok(()) - } - - /// The normals [`Mesh::compute_normals`] stores. The face products are summed in `f64`, where - /// the cross product of any two `f32` edges neither overflows nor rounds to zero, so a small - /// face far from the origin keeps its normal. - pub(crate) fn smooth_normals(&self) -> Result> { - let mut sums = try_filled(self.positions.len(), DVec3::ZERO, "normals")?; + let mut normals = vec![Vec3::ZERO; self.positions.len()]; for &[a, b, c] in self.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; - let (pa, pb, pc) = (pa.as_dvec3(), pb.as_dvec3(), pc.as_dvec3()); - let face = (pb - pa).cross(pc - pa); + let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { - if let Some(x) = sums.get_mut(v) { + if let Some(x) = normals.get_mut(v) { *x += face; } } } - let mut normals = try_vec(sums.len(), "normals")?; - normals.extend(sums.into_iter().map(|v| v.try_normalize().map_or(Vec3::Y, |n| n.as_vec3()))); - Ok(normals) + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } - /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). A mesh with - /// an index out of range, a non-finite position, normal or UV, only degenerate triangles, - /// more than [`MAX_MIKKTSPACE_VALENCE`] triangles around one vertex or corners whose welding - /// would take more than [`MAX_MIKKTSPACE_WELD_WORK`] comparisons does not go to MikkTSpace. - /// Missing normals are computed and missing UVs are zero. - /// - /// MikkTSpace gives each triangle corner its own tangent frame. A vertex whose corners get - /// different frames (UVs mirrored across it) is split: every further frame gets a copy of - /// the vertex, and the corners with that frame use the copy. A copy whose index would not - /// fit in `u32` is not made, and those corners keep the first frame. - /// - /// Leaves the mesh unchanged when the memory for the result cannot be reserved. + /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). pub fn compute_tangents(&mut self) { - let _ = self.try_compute_tangents(); - } - - /// [`Mesh::compute_tangents`], or `OutOfMemory` with the mesh unchanged. MikkTSpace's own - /// working memory is not reserved this way. - pub fn try_compute_tangents(&mut self) -> Result<()> { - self.try_compute_tangents_splitting(Split::UpTo(usize::MAX)) - } - - /// [`Mesh::try_compute_tangents`] with `split` deciding what happens at the first copy a - /// split would make that `split` does not allow. The error comes before that copy is - /// reserved, with the mesh unchanged. - pub(crate) fn try_compute_tangents_splitting(&mut self, split: Split) -> Result<()> { - let n = self.positions.len(); - let computed_normals = if self.normals.len() != n { Some(self.smooth_normals()?) } else { None }; - let zero_uvs = if self.uvs.len() != n { Some(try_filled(n, Vec2::ZERO, "UVs")?) } else { None }; - let normals = computed_normals.as_deref().unwrap_or(&self.normals); - let uvs = zero_uvs.as_deref().unwrap_or(&self.uvs); - let scales = Scales::of(&self.positions, normals, uvs); - let mut corners = try_filled(self.indices.len(), Vec4::ZERO, "tangents")?; - - // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. It - // reads the divided positions, so the check does too. Its callbacks read a missing vertex - // as the origin, which the degenerate check cannot see, so an index past the last vertex - // skips it too. - let mut usable = - scales.finite && self.indices.iter().all(|&i| (i as usize) < n) && !self.all_triangles_degenerate_divided_by(scales.position); - let mut g = Mikk { positions: &self.positions, normals, uvs, indices: &self.indices, scales, corners: &mut corners }; - usable = usable && g.affordable()?; + self.tangents = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); self.positions.len()]; + if self.normals.len() != self.positions.len() { + self.compute_normals(); + } + if self.uvs.len() != self.positions.len() { + self.uvs = vec![Vec2::ZERO; self.positions.len()]; + } + // mikktspace crashes (out-of-bounds) when every triangle is degenerate; skip it then. + let usable = !crate::unwrap::all_triangles_degenerate(self); + let mut g = Mikk { mesh: self }; if !usable || !mikktspace::generate_tangents(&mut g) { - let per_vertex = simple_tangents(&self.positions, normals, uvs, &self.indices, scales)?; - for (corner, v) in corners.iter_mut().zip(&self.indices) { - *corner = per_vertex.get(*v as usize).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0)); - } + self.simple_tangents(); } - // Orthonormalize a tangent against the normal of vertex `v`; repair degenerate results. - let frame = |v: usize, t: Vec4| { - let n = normals.get(v).copied().unwrap_or(Vec3::Y); - // Normals outside the safe range are brought to unit length first, so the projection - // below stays finite. A normal that is not finite counts as +Y. - let n = if scales.normal == 1.0 && n.is_finite() { n } else { (n / scales.normal).try_normalize().unwrap_or(Vec3::Y) }; - let d = t.truncate(); - let o = (d - n * n.dot(d)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); - o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }) - }; - for (t, v) in corners.iter_mut().zip(&self.indices) { - *t = frame(*v as usize, *t); + for (t, n) in self.tangents.iter_mut().zip(&self.normals) { + // Orthonormalize against the normal; repair degenerate results. + let v = t.truncate(); + let o = (v - *n * n.dot(v)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()); + *t = o.extend(if t.w < 0.0 { -1.0 } else { 1.0 }); } - - // One tangent per vertex: the first corner's frame, and a copy of the vertex for each - // other frame its corners have. Corners that share a frame get bit-identical tangents. - let bits = |t: Vec4| t.to_array().map(f32::to_bits); - let mut tangents = try_filled(n, None::, "tangents")?; - let mut copies: Vec<(u32, Vec4)> = Vec::new(); - let mut copy_of: std::collections::HashMap<(u32, [u32; 4]), u32> = std::collections::HashMap::new(); - let mut indices = try_vec(self.indices.len(), "indices")?; - for (&v, &t) in self.indices.iter().zip(&corners) { - let slot = tangents.get_mut(v as usize); - let index = match slot { - Some(slot @ None) => { - *slot = Some(t); - v - } - Some(Some(first)) if bits(*first) == bits(t) => v, - Some(Some(_)) => match copy_of.get(&(v, bits(t))) { - Some(©) => copy, - None => match u32::try_from(n + copies.len()) { - Ok(copy) => { - match split { - Split::UpTo(max_vertices) => check_limit("vertex count", (copy as usize).saturating_add(1), max_vertices)?, - Split::Refuse => { - return Err(MeshOpsError::Invalid(format!("vertex {v} is shared by triangles with different tangent frames"))); - } - } - reserved(copies.try_reserve(1), "tangents")?; - reserved(copy_of.try_reserve(1), "tangents")?; - copies.push((v, t)); - copy_of.insert((v, bits(t)), copy); - copy - } - // No index for another copy: the corner keeps the first frame. - Err(_) => v, - }, - }, - None => v, - }; - indices.push(index); - } - - // Reserve every array before changing any of them: reserving leaves their contents as - // they are. - let extra = copies.len(); - let mut out = try_vec(n + extra, "tangents")?; - // A vertex no triangle uses gets +X made perpendicular to its normal. - out.extend(tangents.iter().enumerate().map(|(v, t)| t.unwrap_or_else(|| frame(v, Vec4::new(1.0, 0.0, 0.0, 1.0))))); - out.extend(copies.iter().map(|(_, t)| *t)); - let (mut normals, mut uvs) = (computed_normals, zero_uvs); - let has_colors = self.colors.len() == n; - let reserve = |r| reserved(r, "tangents"); - reserve(self.positions.try_reserve(extra))?; - reserve(normals.as_mut().unwrap_or(&mut self.normals).try_reserve(extra))?; - reserve(uvs.as_mut().unwrap_or(&mut self.uvs).try_reserve(extra))?; - if has_colors { - reserve(self.colors.try_reserve(extra))?; - } - - if let Some(normals) = normals.take() { - self.normals = normals; - } - if let Some(uvs) = uvs.take() { - self.uvs = uvs; - } - for &(v, _) in &copies { - let v = v as usize; - self.positions.push(self.positions.get(v).copied().unwrap_or_default()); - self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); - self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); - if has_colors { - self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); - } - } - self.tangents = out; - self.indices = indices; - Ok(()) } - /// True when the mesh has triangles and every one of them has two corners at the same - /// position after the positions are divided by `divisor`. - fn all_triangles_degenerate_divided_by(&self, divisor: f32) -> bool { - let p = |i: &u32| self.positions.get(*i as usize).map(|p| *p / divisor); - !self.indices.is_empty() - && self.indices.chunks(3).all(|t| match t { - [a, b, c] => p(a) == p(b) || p(a) == p(c) || p(b) == p(c), - _ => true, - }) + fn simple_tangents(&mut self) { + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; + let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; + let (e1, e2) = (*pb - *pa, *pc - *pa); + let (d1, d2) = (*ub - *ua, *uc - *ua); + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { + continue; + } + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; + for v in [a, b, c] { + if let Some(x) = tangents.get_mut(v) { + *x += tangent; + } + } + } + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), - /// ascending. Non-finite UVs are skipped. The triangles the material's submeshes list (a - /// triangle counts again for each submesh that lists it) over [`Limits::max_triangles`] are - /// `TooLarge`. - pub fn uv_tiles(&self, m: usize, limits: &Limits) -> Result> { - self.listed_of(m, limits)?; - Ok(self - .triangles_of(m) + /// ascending. Non-finite UVs are skipped. + pub fn uv_tiles(&self, m: usize) -> std::collections::BTreeSet<(i32, i32)> { + self.triangles_of(m) .filter_map(|t| { let [a, b, c] = self.tri(t)?; - let uv = uv_centroid([*self.uvs.get(a)?, *self.uvs.get(b)?, *self.uvs.get(c)?]); + let uv = (*self.uvs.get(a)? + *self.uvs.get(b)? + *self.uvs.get(c)?) / 3.0; uv.is_finite().then(|| (uv.x.floor() as i32, uv.y.floor() as i32)) }) - .collect()) + .collect() } /// Remap the UVs of material `m`'s triangles with `f`. Vertices they share with other - /// materials are duplicated first, so the other triangles keep their UVs. Errors as - /// [`Mesh::map_material_uvs_with`]. - pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2, limits: &Limits) -> Result<()> { - self.map_material_uvs_with(m, |_, uv| f(uv), limits) + /// materials are duplicated first, so the other triangles keep their UVs. + pub fn map_material_uvs(&mut self, m: usize, f: impl Fn(Vec2) -> Vec2) { + self.map_material_uvs_with(m, |_, uv| f(uv)); } /// [`Mesh::map_material_uvs`] where `f` also gets the UV centroid of the first of the /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then /// place a vertex on a tile border with its own triangle's tile. - /// - /// The triangles the material's submeshes list (a triangle counts again for each submesh that - /// lists it) over [`Limits::max_triangles`] are `TooLarge`, as are the mesh's vertices and - /// the copies of its shared ones over [`Limits::max_vertices`]. A triangle that a submesh of - /// another material also lists is `Invalid`, and a reservation that fails is `OutOfMemory`. - /// Every error leaves the mesh unchanged and does not call `f`. - pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2, limits: &Limits) -> Result<()> { - let listed = self.listed_of(m, limits)?; - let n = self.positions.len(); - check_limit("vertex count", n, limits.max_vertices)?; - if self.listed_by_other(m)? { - return Err(MeshOpsError::Invalid("triangle belongs to more than one material".into())); - } - let mut material_triangles = try_vec(listed, "material triangles")?; - material_triangles.extend(self.triangles_of(m)); - let mut in_material = try_filled(self.triangle_count(), false, "material triangles")?; + pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; for t in &material_triangles { if let Some(x) = in_material.get_mut(*t) { *x = true; } } - // (vertex, place of its triangle's first corner, centroid of its triangle), three per - // triangle. Reserved before the mesh changes, and sorted in place without allocating. - let mut vertices = try_vec(listed.saturating_mul(3), "material vertices")?; - // Per vertex: NOT_SHARED, SHARED with a triangle outside the material, or COPIED when it - // is shared and a triangle of the material uses it, so it gets one copy. - const NOT_SHARED: u8 = 0; - const SHARED: u8 = 1; - const COPIED: u8 = 2; - let what = "material vertices"; - let mut shared = try_filled(n, NOT_SHARED, what)?; + let mut shared = vec![false; self.positions.len()]; for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { - *s = SHARED; + *s = true; } } } - let mut copied = 0usize; - for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { - if let Some(s) = self.indices.get(k).and_then(|v| shared.get_mut(*v as usize)) - && *s == SHARED - { - *s = COPIED; - copied += 1; - } - } - // The vertices with their copies over `max_vertices` are `TooLarge`. The copies' storage - // is reserved before the mesh changes; only the copies whose index fits in u32 are made. - check_limit("vertex count", n.saturating_add(copied), limits.max_vertices)?; - let copies = copied.min(usize::try_from(u64::from(u32::MAX) + 1).unwrap_or(usize::MAX).saturating_sub(n)); - reserved(self.positions.try_reserve(copies), what)?; - if self.normals.len() == n { - reserved(self.normals.try_reserve(copies), what)?; - } - if self.tangents.len() == n { - reserved(self.tangents.try_reserve(copies), what)?; - } - if self.uvs.len() == n { - reserved(self.uvs.try_reserve(copies), what)?; - } - if self.colors.len() == n { - reserved(self.colors.try_reserve(copies), what)?; - } let mut duplicates = std::collections::HashMap::new(); - reserved(duplicates.try_reserve(copies), what)?; for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { let Some(&v) = self.indices.get(k) else { continue }; - let v = if shared.get(v as usize) == Some(&COPIED) { - match duplicates.get(&v) { - Some(©) => copy, - // A vertex past u32::MAX cannot be indexed: the triangle keeps the shared one. - None => match self.duplicate_vertex(v as usize) { - Some(copy) => *duplicates.entry(v).or_insert(copy), - None => v, - }, - } + let v = if shared.get(v as usize).copied().unwrap_or(false) { + *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; @@ -769,283 +315,120 @@ impl Mesh { } } + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); for t in &material_triangles { let Some(tri) = self.tri(*t) else { continue }; - let centroid = uv_centroid(tri.map(|v| self.uvs.get(v).copied().unwrap_or_default())); - let place = vertices.len(); - vertices.extend(tri.map(|v| (v, place, centroid))); + let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; + vertices.extend(tri.map(|v| (v, centroid))); } - // Each vertex once, with the centroid of the first triangle using it. - vertices.sort_unstable_by_key(|&(v, place, _)| (v, place)); - vertices.dedup_by_key(|(v, _, _)| *v); - for (v, _, centroid) in vertices { + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { if let Some(uv) = self.uvs.get_mut(v) { *uv = f(centroid, *uv); } } - Ok(()) } - /// Append a copy of vertex `v`; returns its index, or `None` when the new index would not - /// fit in `u32`. Normals, tangents, UVs and colors are copied where the mesh has one per - /// vertex; an array without one per vertex is left as it is. - fn duplicate_vertex(&mut self, v: usize) -> Option { - let n = self.positions.len(); - let i = u32::try_from(n).ok()?; + /// Append a copy of vertex `v`; returns its index. + fn duplicate_vertex(&mut self, v: usize) -> u32 { + let i = self.positions.len() as u32; self.positions.push(self.positions.get(v).copied().unwrap_or_default()); - if self.normals.len() == n { - self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); - } - if self.tangents.len() == n { - self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); - } - if self.uvs.len() == n { - self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); - } - if self.colors.len() == n { + self.normals.push(self.normals.get(v).copied().unwrap_or(Vec3::Y)); + self.tangents.push(self.tangents.get(v).copied().unwrap_or(Vec4::new(1.0, 0.0, 0.0, 1.0))); + self.uvs.push(self.uvs.get(v).copied().unwrap_or_default()); + if !self.colors.is_empty() { self.colors.push(self.colors.get(v).copied().unwrap_or(Vec4::ONE)); } - Some(i) + i } /// Append `other`, offsetting indices; its submeshes keep their material indices shifted by - /// this mesh's material count. Leaves this mesh unchanged when [`Mesh::try_append`] fails. + /// this mesh's material count. pub fn append(&mut self, other: &Mesh) { - let _ = self.try_append(other); - } - - /// [`Mesh::append`], or an error when an index of `other` is out of range or a rebased - /// index or submesh range would not fit in `u32`. When only one side has normals, UVs or - /// tangents for every vertex, the other side gets them (computed normals and tangents, zero - /// UVs), so the attribute arrays stay as long as the positions; computing tangents can split - /// vertices ([`Mesh::compute_tangents`]). A side with submeshes and no material list gets - /// one unnamed material. A reservation that fails is `OutOfMemory`. Every error leaves this - /// mesh unchanged. - pub fn try_append(&mut self, other: &Mesh) -> Result<()> { - if let Some(bad) = other.indices.iter().find(|&&i| i as usize >= other.positions.len()) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", other.positions.len()))); - } - let too_large = |what| MeshOpsError::Invalid(format!("the appended {what} do not fit in u32")); - u32::try_from(self.positions.len()).map_err(|_| too_large("vertices"))?; - // Splitting adds at most one vertex per triangle corner of a side whose tangents are - // computed here. - let split = |m: &Mesh, computed: bool| if computed { m.indices.len() } else { 0 }; - let tangents_needed = |m: &Mesh| !per_vertex(m.tangents.len(), m.positions.len()); - let any_tangents = per_vertex(self.tangents.len(), self.positions.len()) || per_vertex(other.tangents.len(), other.positions.len()); - let vertices = [ - self.positions.len(), - other.positions.len(), - split(self, any_tangents && tangents_needed(self)), - split(other, any_tangents && tangents_needed(other)), - ] - .into_iter() - .try_fold(0usize, usize::checked_add) - .ok_or(too_large("vertices"))?; - // The last vertex index is `vertices - 1`. - if vertices > 0 && u32::try_from(vertices - 1).is_err() { - return Err(too_large("vertices")); - } - let ibase = u32::try_from(self.indices.len()).map_err(|_| too_large("indices"))?; - let index_count = self.indices.len().checked_add(other.indices.len()).ok_or(too_large("indices"))?; - u32::try_from(index_count).map_err(|_| too_large("indices"))?; - // Submeshes of a mesh without a material list use material 0, which gets an unnamed entry - // so that it stays apart from the other mesh's materials. - let unnamed = |m: &Mesh| m.materials.is_empty() && !m.submeshes.is_empty(); - let (self_unnamed, other_unnamed) = (unnamed(self), unnamed(other)); - let mbase = self.materials.len() + usize::from(self_unnamed); - let mut submeshes = try_vec(other.submeshes.len(), "submeshes")?; - for s in &other.submeshes { - let start = s.start.checked_add(ibase).ok_or(too_large("submeshes"))?; - start.checked_add(s.count).ok_or(too_large("submeshes"))?; - let material = s.material.checked_add(mbase).ok_or(too_large("submeshes"))?; - submeshes.push(SubMesh { name: try_name(&s.name, "submeshes")?, material, start, count: s.count }); - } - let names = try_names(&other.materials, "materials")?; - - let complete = |m: &Mesh| { - ( - per_vertex(m.normals.len(), m.positions.len()), - per_vertex(m.uvs.len(), m.positions.len()), - per_vertex(m.tangents.len(), m.positions.len()), - ) - }; - let ((sn, su, st), (on, ou, ot)) = (complete(self), complete(other)); - let need_tangents = st || ot; - let (need_normals, need_uvs) = (sn || on || need_tangents, su || ou || need_tangents); - // A side that lacks an attribute the result needs is filled in on a copy of its vertex - // arrays, so an error leaves both meshes unchanged. - let filled = |m: &Mesh, (has_normals, has_uvs, has_tangents): (bool, bool, bool)| -> Result> { - if (has_normals || !need_normals) && (has_uvs || !need_uvs) && (has_tangents || !need_tangents) { - return Ok(None); - } - let mut w = m.vertex_copy()?; - if need_normals && !has_normals { - w.try_compute_normals()?; - } - if need_uvs && !has_uvs { - w.uvs = try_filled(w.positions.len(), Vec2::ZERO, "UVs")?; - } - if need_tangents && !has_tangents { - w.try_compute_tangents()?; - } - Ok(Some(w)) - }; - let other_filled = filled(other, (on, ou, ot))?; - let mut self_filled = filled(self, (sn, su, st))?; - let o = other_filled.as_ref().unwrap_or(other); - // Computing tangents can split vertices, so the base is taken now (checked to fit above). - let base = self_filled.as_ref().map_or(self.positions.len(), |w| w.positions.len()); - let has_colors = !(self.colors.is_empty() && other.colors.is_empty()); - let has_diagonals = !(self.diagonals.is_empty() && other.diagonals.is_empty()); - - // Reserve every array before changing any of them: reserving leaves their contents as - // they are. - let wanted = |on: bool, len: usize| if on { len } else { 0 }; - let diagonals = wanted(has_diagonals, (ibase as usize / 3 + other.triangle_count()).saturating_sub(self.diagonals.len())); - reserved(self.diagonals.try_reserve(diagonals), "diagonals")?; - let materials = other.materials.len() + usize::from(self_unnamed) + usize::from(other_unnamed); - reserved(self.materials.try_reserve(materials), "materials")?; - reserved(self.submeshes.try_reserve(submeshes.len()), "submeshes")?; - let target: &mut Mesh = match self_filled.as_mut() { - Some(w) => w, - None => self, - }; - reserved(target.positions.try_reserve(o.positions.len()), "positions")?; - reserved(target.normals.try_reserve(wanted(need_normals, o.normals.len())), "normals")?; - reserved(target.tangents.try_reserve(wanted(need_tangents, o.tangents.len())), "tangents")?; - reserved(target.uvs.try_reserve(wanted(need_uvs, o.uvs.len())), "UVs")?; - let colors = wanted(has_colors, (base + o.positions.len()).saturating_sub(target.colors.len())); - reserved(target.colors.try_reserve(colors), "colors")?; - reserved(target.indices.try_reserve(o.indices.len()), "indices")?; - - if let Some(w) = self_filled { - self.positions = w.positions; - self.normals = w.normals; - self.tangents = w.tangents; - self.uvs = w.uvs; - self.colors = w.colors; - self.indices = w.indices; - } - let base = base as u32; - self.positions.extend_from_slice(&o.positions); - if need_normals { - self.normals.extend_from_slice(&o.normals); - } else { - self.normals.clear(); - } - if need_tangents { - self.tangents.extend_from_slice(&o.tangents); - } else { - self.tangents.clear(); - } - if need_uvs { - self.uvs.extend_from_slice(&o.uvs); - } else { - self.uvs.clear(); - } - if has_colors { + let base = self.positions.len() as u32; + let ibase = self.indices.len() as u32; + let mbase = self.materials.len(); + self.positions.extend_from_slice(&other.positions); + self.normals.extend_from_slice(&other.normals); + self.tangents.extend_from_slice(&other.tangents); + self.uvs.extend_from_slice(&other.uvs); + if !(self.colors.is_empty() && other.colors.is_empty()) { // Vertices of the side without colors become white. self.colors.resize(base as usize, Vec4::ONE); - self.colors.extend(o.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(o.positions.len())); + self.colors.extend(other.colors.iter().copied().chain(std::iter::repeat(Vec4::ONE)).take(other.positions.len())); } - if has_diagonals { + if !(self.diagonals.is_empty() && other.diagonals.is_empty()) { self.diagonals.resize(ibase as usize / 3, 0); self.diagonals.extend(other.diagonals.iter().copied().chain(std::iter::repeat(0)).take(other.triangle_count())); } - self.indices.extend(o.indices.iter().map(|i| i + base)); - if self_unnamed { - self.materials.push(String::new()); - } - self.materials.extend(names); - if other_unnamed { - self.materials.push(String::new()); - } - self.submeshes.extend(submeshes); - Ok(()) + self.indices.extend(other.indices.iter().map(|i| i + base)); + self.materials.extend(other.materials.iter().cloned()); + self.submeshes.extend(other.submeshes.iter().map(|s| SubMesh { + name: s.name.clone(), + material: s.material + mbase, + start: s.start + ibase, + count: s.count, + })); } - /// A mesh holding reserved copies of this mesh's vertex attributes and indices, and nothing - /// else, or `OutOfMemory`. - fn vertex_copy(&self) -> Result { - Ok(Mesh { - positions: try_copy(&self.positions, "positions")?, - normals: try_copy(&self.normals, "normals")?, - tangents: try_copy(&self.tangents, "tangents")?, - uvs: try_copy(&self.uvs, "UVs")?, - colors: try_copy(&self.colors, "colors")?, - indices: try_copy(&self.indices, "indices")?, - ..Mesh::default() - }) + /// Each triangle split into four at its edge midpoints (shared edges share their midpoint); + /// attributes are interpolated and submesh ranges keep their triangles. + pub fn subdivided(&self) -> Mesh { + let mut m = Mesh { indices: Vec::with_capacity(self.indices.len() * 4), ..self.clone() }; + let has = |len: usize| len == self.positions.len(); + let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len())); + let mut mids = std::collections::HashMap::new(); + let mut mid = |m: &mut Mesh, a: u32, b: u32| -> u32 { + *mids.entry((a.min(b), a.max(b))).or_insert_with(|| { + let (i, j) = (a as usize, b as usize); + m.positions.push((self.positions[i] + self.positions[j]) * 0.5); + if has_n { + m.normals.push((self.normals[i] + self.normals[j]).normalize_or_zero()); + } + if has_t { + let (ti, tj) = (self.tangents[i], self.tangents[j]); + m.tangents.push((ti.truncate() + tj.truncate()).normalize_or_zero().extend(ti.w)); + } + if has_uv { + m.uvs.push((self.uvs[i] + self.uvs[j]) * 0.5); + } + if has_c { + m.colors.push((self.colors[i] + self.colors[j]) * 0.5); + } + (m.positions.len() - 1) as u32 + }) + }; + for t in self.indices.as_chunks::<3>().0 { + if t.iter().any(|&i| i as usize >= self.positions.len()) { + continue; + } + let (a, b, c) = (t[0], t[1], t[2]); + let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a)); + m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); + } + for s in &mut m.submeshes { + s.start *= 4; + s.count *= 4; + } + m } - /// Uniformly scale and translate so the mesh is centered with the given bounding radius. A - /// radius that is not a finite positive number, or is so large that a corner of the bounds - /// would pass `f32::MAX`, leaves the mesh unchanged. + /// Uniformly scale and translate so the mesh is centered with the given bounding radius. pub fn normalize_to(&mut self, radius: f32) { - if !(radius.is_finite() && radius > 0.0) { - return; - } let (lo, hi) = self.bounds(); - // `Mesh::radius` is the real radius above its floor; a smaller mesh, or a scale past - // f32::MAX, takes the second form. - let r = self.radius(); - let s = radius / r; - if lo.abs().max(hi.abs()).max_element() <= SAFE_MAGNITUDE && r > MIN_RADIUS && s.is_finite() { - let c = (lo + hi) * 0.5; - if !(((lo - c) * s).is_finite() && ((hi - c) * s).is_finite()) { - return; - } - for p in &mut self.positions { - *p = (*p - c) * s; - } - return; - } - // Half-sums and a divided length keep every intermediate value finite near f32::MAX and - // nonzero for a mesh far smaller than the floor. - let c = lo * 0.5 + hi * 0.5; - let half = hi * 0.5 - lo * 0.5; - let largest = half.abs().max_element(); - if largest == 0.0 { - // Every finite position is the center. - for p in &mut self.positions { - *p = *p * 0.5 - c * 0.5; - } - return; - } - let s = radius / (half / largest).length(); - let moved = |p: Vec3| (p * 0.5 - c * 0.5) / largest * s * 2.0; - if !(moved(lo).is_finite() && moved(hi).is_finite()) { - return; - } + let c = (lo + hi) * 0.5; + let s = radius / self.radius(); for p in &mut self.positions { - *p = moved(*p); + *p = (*p - c) * s; } } /// A single-material mesh from raw attributes; computes missing normals and tangents. pub fn from_parts(positions: Vec, normals: Option>, uvs: Vec, indices: Vec, material: &str) -> Result { - Self::from_parts_capped(positions, normals, uvs, indices, material, MAX_TRIANGLES) - } - - /// [`Mesh::from_parts`] with the triangle cap as a parameter, so a test can reach it with a - /// small mesh. - fn from_parts_capped( - positions: Vec, - normals: Option>, - uvs: Vec, - indices: Vec, - material: &str, - max_triangles: usize, - ) -> Result { - if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len()))); - } - let count = u32::try_from(indices.len()).map_err(|_| MeshOpsError::Invalid("index count does not fit in u32".into()))?; - // The triangle cap of `validate`, checked before the normals and tangents are computed. - if indices.len() / 3 > max_triangles { - return Err(MeshOpsError::Invalid(format!("mesh has more than {max_triangles} triangles"))); - } + let count = indices.len() as u32; let mut m = Mesh { normals: normals.unwrap_or_default(), uvs, @@ -1058,332 +441,46 @@ impl Mesh { diagonals: Vec::new(), }; if m.normals.len() != m.positions.len() { - m.try_compute_normals()?; + m.compute_normals(); } - m.try_compute_tangents()?; + m.compute_tangents(); m.validate()?; Ok(m) } - - /// A single-material mesh from plain slices, checked against `limits`: the counts, every - /// index, every value finite, and normals and UVs (when given) one per position. Leaves - /// normals, UVs and tangents empty when they are not given. - pub fn from_slices( - positions: &[[f32; 3]], - normals: Option<&[[f32; 3]]>, - uvs: Option<&[[f32; 2]]>, - indices: &[u32], - limits: &Limits, - ) -> Result { - check_limit("vertex count", positions.len(), limits.max_vertices)?; - if !indices.len().is_multiple_of(3) { - return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into())); - } - check_limit("triangle count", indices.len() / 3, limits.max_triangles)?; - let count = u32::try_from(indices.len()).map_err(|_| MeshOpsError::Invalid("index count does not fit in u32".into()))?; - if let Some(bad) = indices.iter().find(|&&i| i as usize >= positions.len()) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({} vertices)", positions.len()))); - } - let n = positions.len(); - for (what, len) in [("normals", normals.map(<[_]>::len)), ("UVs", uvs.map(<[_]>::len))] { - if let Some(len) = len.filter(|len| *len != n) { - return Err(MeshOpsError::Invalid(format!("{len} {what} for {n} vertices"))); - } - } - let finite = |v: &[f32]| v.iter().all(|x| x.is_finite()); - if !positions.iter().all(|p| finite(p)) { - return Err(MeshOpsError::Invalid("non-finite position".into())); - } - if !normals.unwrap_or_default().iter().all(|p| finite(p)) { - return Err(MeshOpsError::Invalid("non-finite normal".into())); - } - if !uvs.unwrap_or_default().iter().all(|p| finite(p)) { - return Err(MeshOpsError::Invalid("non-finite UV".into())); - } - - let mut mesh = Mesh { - submeshes: vec![SubMesh { name: "default".into(), material: 0, start: 0, count }], - materials: vec!["default".into()], - ..Mesh::default() - }; - mesh.positions = try_vec(n, "positions")?; - mesh.positions.extend(positions.iter().map(|p| Vec3::from_array(*p))); - if let Some(normals) = normals { - mesh.normals = try_vec(n, "normals")?; - mesh.normals.extend(normals.iter().map(|p| Vec3::from_array(*p))); - } - if let Some(uvs) = uvs { - mesh.uvs = try_vec(n, "UVs")?; - mesh.uvs.extend(uvs.iter().map(|p| Vec2::from_array(*p))); - } - mesh.indices = try_vec(indices.len(), "indices")?; - mesh.indices.extend_from_slice(indices); - Ok(mesh) - } - - /// Each triangle split into four at its edge midpoints, shared between neighbors. Leaves an - /// unchanged copy when [`Mesh::try_subdivided`] fails. - pub fn subdivided(&self) -> Mesh { - self.try_subdivided(&Limits::default()).unwrap_or_else(|_| self.clone()) - } - - /// [`Mesh::subdivided`] for a mesh that passes the index and submesh checks of - /// [`Mesh::validate`], with the result checked against `limits`. Normals, tangents, UVs and - /// colors are interpolated when the mesh has one per vertex; submeshes keep their triangles - /// and polygon diagonals stay hidden on the halves of their edges. - pub fn try_subdivided(&self, limits: &Limits) -> Result { - let n = self.positions.len(); - if !self.indices.len().is_multiple_of(3) { - return Err(MeshOpsError::Invalid("index count is not a multiple of 3".into())); - } - if let Some(bad) = self.indices.iter().find(|&&i| i as usize >= n) { - return Err(MeshOpsError::Invalid(format!("index {bad} out of range ({n} vertices)"))); - } - for s in &self.submeshes { - if submesh_range(s, self.indices.len()).is_none() || s.material >= self.materials.len().max(1) { - return Err(MeshOpsError::Invalid(format!("submesh {} is out of range", s.name))); - } - } - let triangles = self.triangle_count(); - let out_triangles = triangles.checked_mul(4).ok_or(MeshOpsError::Invalid("too many triangles".into()))?; - check_limit("triangle count", out_triangles, limits.max_triangles)?; - check_limit("vertex count", n, limits.max_vertices)?; - // Each triangle adds at most three midpoints; shared edges add fewer. - let most_vertices = n.saturating_add(triangles.saturating_mul(3)); - let out_indices = out_triangles.checked_mul(3).ok_or(MeshOpsError::Invalid("too many indices".into()))?; - let fits = |count: usize| u32::try_from(count).is_ok(); - if !fits(out_indices) || !fits(most_vertices) { - return Err(MeshOpsError::Invalid("the subdivided mesh does not fit in u32 indices".into())); - } - - // Diagonals stay empty here and are built below when the input has them. The loop below - // reserves room for each triangle's midpoints before adding them. - let mut m = Mesh { - positions: try_copy(&self.positions, "positions")?, - normals: try_copy(&self.normals, "normals")?, - tangents: try_copy(&self.tangents, "tangents")?, - uvs: try_copy(&self.uvs, "UVs")?, - colors: try_copy(&self.colors, "colors")?, - indices: try_vec(out_indices, "indices")?, - submeshes: try_submeshes(&self.submeshes, "submeshes")?, - materials: try_names(&self.materials, "materials")?, - diagonals: Vec::new(), - }; - let has = |len: usize| len == n; - let (has_n, has_t, has_uv, has_c) = (has(self.normals.len()), has(self.tangents.len()), has(self.uvs.len()), has(self.colors.len())); - let mut mids: std::collections::HashMap<(u32, u32), u32> = std::collections::HashMap::new(); - // Half-sums: (a + b) * 0.5 overflows for coordinates near f32::MAX. - let mid = |m: &mut Mesh, mids: &mut std::collections::HashMap<(u32, u32), u32>, a: u32, b: u32| -> u32 { - *mids.entry((a.min(b), a.max(b))).or_insert_with(|| { - let (i, j) = (a as usize, b as usize); - let half = |x: Vec3, y: Vec3| x * 0.5 + y * 0.5; - m.positions.push(half(self.positions[i], self.positions[j])); - if has_n { - m.normals.push(unit(half(self.normals[i], self.normals[j])).unwrap_or(Vec3::ZERO)); - } - if has_t { - let (ti, tj) = (self.tangents[i], self.tangents[j]); - m.tangents.push(unit(half(ti.truncate(), tj.truncate())).unwrap_or(Vec3::ZERO).extend(ti.w)); - } - if has_uv { - m.uvs.push(self.uvs[i] * 0.5 + self.uvs[j] * 0.5); - } - if has_c { - m.colors.push(self.colors[i] * 0.5 + self.colors[j] * 0.5); - } - // At most n + 3 × triangles vertices, checked to fit above. - (m.positions.len() - 1) as u32 - }) - }; - let oom = |_| MeshOpsError::OutOfMemory("subdivided vertices"); - for &[a, b, c] in self.indices.as_chunks::<3>().0 { - // A triangle adds at most three midpoints. - mids.try_reserve(3).map_err(oom)?; - m.positions.try_reserve(3).map_err(oom)?; - if has_n { - m.normals.try_reserve(3).map_err(oom)?; - } - if has_t { - m.tangents.try_reserve(3).map_err(oom)?; - } - if has_uv { - m.uvs.try_reserve(3).map_err(oom)?; - } - if has_c { - m.colors.try_reserve(3).map_err(oom)?; - } - let (ab, bc, ca) = (mid(&mut m, &mut mids, a, b), mid(&mut m, &mut mids, b, c), mid(&mut m, &mut mids, c, a)); - // Checked per triangle, so the result stops growing at most three vertices past the limit. - check_limit("vertex count", m.positions.len(), limits.max_vertices)?; - m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); - } - // Children 0 to 2 keep the halves of the parent's edges; child 3 and the edges between - // children are new, real edges. - if !self.diagonals.is_empty() { - m.diagonals = try_vec(out_triangles, "diagonals")?; - for t in 0..triangles { - let d = self.diagonals.get(t).copied().unwrap_or(0); - m.diagonals.extend_from_slice(&[d & 0b101, d & 0b011, d & 0b110, 0]); - } - } - for s in &mut m.submeshes { - // Validated above: whole triangles inside an index buffer that fits in u32 after × 4. - s.start *= 4; - s.count *= 4; - } - Ok(m) - } } -/// The divisors that bring a mesh's positions, normals and UVs into the safe range, and whether -/// all of them are finite. -#[derive(Clone, Copy)] -struct Scales { - position: f32, - normal: f32, - uv: f32, - finite: bool, -} - -impl Scales { - fn of(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2]) -> Scales { - let positions = largest_abs(positions.iter().flat_map(|p| p.to_array())); - let normals = largest_abs(normals.iter().flat_map(|p| p.to_array())); - let uvs = largest_abs(uvs.iter().flat_map(|p| p.to_array())); - Scales { - position: safe_divisor(positions), - normal: divisor_into(normals, SAFE_NORMAL_MAGNITUDE), - uv: safe_divisor(uvs), - finite: positions.is_some() && normals.is_some() && uvs.is_some(), - } - } -} - -/// Per-vertex tangents from the UV gradients of the triangles around each vertex: the fallback -/// when MikkTSpace does not run or fails. `w` is -1 where the summed direction up the image -/// (toward smaller v) lies against `cross(normal, tangent)`, and +1 otherwise, as MikkTSpace -/// sets it. Edges, UV differences and sums are taken in `f64`, so an edge too small to survive -/// division by the position scale in `f32` still sets the direction. -fn simple_tangents(positions: &[Vec3], normals: &[Vec3], uvs: &[Vec2], indices: &[u32], scales: Scales) -> Result> { - let mut sums = try_filled(positions.len(), (DVec3::ZERO, DVec3::ZERO), "tangents")?; - let (position_scale, uv_scale) = (f64::from(scales.position), f64::from(scales.uv)); - for &[a, b, c] in indices.as_chunks::<3>().0 { - let (a, b, c) = (a as usize, b as usize, c as usize); - let (Some(pa), Some(pb), Some(pc)) = (positions.get(a), positions.get(b), positions.get(c)) else { continue }; - let (Some(ua), Some(ub), Some(uc)) = (uvs.get(a), uvs.get(b), uvs.get(c)) else { continue }; - let (pa, pb, pc) = (pa.as_dvec3(), pb.as_dvec3(), pc.as_dvec3()); - let (ua, ub, uc) = (ua.as_dvec2(), ub.as_dvec2(), uc.as_dvec2()); - let (e1, e2) = ((pb - pa) / position_scale, (pc - pa) / position_scale); - let (d1, d2) = ((ub - ua) / uv_scale, (uc - ua) / uv_scale); - let determinant = d1.x * d2.y - d2.x * d1.y; - if determinant.abs() < 1e-12 { - continue; - } - - let tangent = (e1 * d2.y - e2 * d1.y) / determinant; - // The direction in which v shrinks, which is up the image. - let up = (e1 * d2.x - e2 * d1.x) / determinant; - for v in [a, b, c] { - if let Some((t, u)) = sums.get_mut(v) { - *t += tangent; - *u += up; - } - } - } - - let mut tangents = try_vec(sums.len(), "tangents")?; - tangents.extend(sums.into_iter().enumerate().map(|(v, (t, up))| { - let t = t.try_normalize().map(|t| t.as_vec3()).and_then(unit).unwrap_or(Vec3::X); - let up = up.try_normalize().map(|up| up.as_vec3()).unwrap_or(Vec3::ZERO); - let n = normals.get(v).copied().and_then(unit).unwrap_or(Vec3::Y); - let w = if n.cross(t).dot(up) < 0.0 { -1.0 } else { 1.0 }; - t.extend(w) - })); - Ok(tangents) -} - -/// The arrays MikkTSpace reads, and the tangent of every triangle corner it writes. struct Mikk<'a> { - positions: &'a [Vec3], - normals: &'a [Vec3], - uvs: &'a [Vec2], - indices: &'a [u32], - scales: Scales, - corners: &'a mut [Vec4], + mesh: &'a mut Mesh, } impl Mikk<'_> { fn vi(&self, face: usize, vert: usize) -> usize { - self.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize - } - - /// Whether MikkTSpace's work on this input stays bounded: at most - /// [`MAX_MIKKTSPACE_VALENCE`] triangles around one vertex, which it visits recursively, one - /// call per triangle, and at most [`MAX_MIKKTSPACE_WELD_WORK`] for welding. - fn affordable(&self) -> Result { - let (valence, weld_work) = self.welding()?; - Ok(valence <= MAX_MIKKTSPACE_VALENCE && weld_work <= MAX_MIKKTSPACE_WELD_WORK) - } - - /// The most triangles that share one vertex as MikkTSpace sees it, and the sum of the squared - /// corner counts of its positions. It welds corners whose position, normal and UV, as this - /// type passes them, are equal (0 and -0 alike). - fn welding(&self) -> Result<(usize, u64)> { - use mikktspace::Geometry; - let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; - let room = self.positions.len().min(self.indices.len()); - let mut count: std::collections::HashMap<[u32; 8], usize> = std::collections::HashMap::new(); - let mut at_position: std::collections::HashMap<[u32; 3], u64> = std::collections::HashMap::new(); - reserved(count.try_reserve(room), "tangents")?; - reserved(at_position.try_reserve(room), "tangents")?; - let (mut most, mut work) = (0, 0u64); - for face in 0..self.num_faces() { - for vert in 0..3 { - let ([px, py, pz], [nx, ny, nz], [u, v]) = (self.position(face, vert), self.normal(face, vert), self.tex_coord(face, vert)); - let key = [px, py, pz, nx, ny, nz, u, v].map(bits); - if !count.contains_key(&key) { - reserved(count.try_reserve(1), "tangents")?; - } - let c = count.entry(key).or_insert(0); - *c += 1; - most = most.max(*c); - let position = [px, py, pz].map(bits); - if !at_position.contains_key(&position) { - reserved(at_position.try_reserve(1), "tangents")?; - } - // k² grows by 2k + 1 with the (k + 1)th corner. - let k = at_position.entry(position).or_insert(0); - work = work.saturating_add(k.saturating_mul(2).saturating_add(1)); - *k += 1; - } - } - Ok((most, work)) + self.mesh.indices.get(face * 3 + vert).copied().unwrap_or(0) as usize } } impl mikktspace::Geometry for Mikk<'_> { fn num_faces(&self) -> usize { - self.indices.len() / 3 + self.mesh.indices.len() / 3 } fn num_vertices_of_face(&self, _face: usize) -> usize { 3 } fn position(&self, face: usize, vert: usize) -> [f32; 3] { - (self.positions.get(self.vi(face, vert)).copied().unwrap_or_default() / self.scales.position).to_array() + self.mesh.positions.get(self.vi(face, vert)).copied().unwrap_or_default().to_array() } fn normal(&self, face: usize, vert: usize) -> [f32; 3] { - (self.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y) / self.scales.normal).to_array() + self.mesh.normals.get(self.vi(face, vert)).copied().unwrap_or(Vec3::Y).to_array() } fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] { // MikkTSpace expects OpenGL texture coordinates (v up); our UVs are glTF (v down). With - // v negated, the bitangent `cross(N, T) * w` points up the image, as glTF requires. - // Negating keeps differences in v that `1 - v` would round away. - let uv = self.uvs.get(self.vi(face, vert)).copied().unwrap_or_default() / self.scales.uv; - [uv.x, -uv.y] + // v flipped, the bitangent `cross(N, T) * w` points up the image, as glTF requires. + let uv = self.mesh.uvs.get(self.vi(face, vert)).copied().unwrap_or_default(); + [uv.x, 1.0 - uv.y] } fn set_tangent_encoded(&mut self, tangent: [f32; 4], face: usize, vert: usize) { - // One tangent per corner: corners of a vertex can get different frames. - if let Some(t) = self.corners.get_mut(face * 3 + vert) { + let i = self.vi(face, vert); + if let Some(t) = self.mesh.tangents.get_mut(i) { *t = Vec4::from_array(tangent); } } @@ -1393,32 +490,6 @@ impl mikktspace::Geometry for Mikk<'_> { mod tests { use super::*; - thread_local! { - /// Name copies that succeed before the next one fails as out of memory; `None` lets every - /// copy succeed. - static NAME_COPIES_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; - } - - /// Let `copies` name copies on this thread succeed and fail the next one, or none with `None`. - fn fail_name_copy_after(copies: Option) { - NAME_COPIES_LEFT.with(|left| left.set(copies)); - } - - /// `OutOfMemory` naming `what` when [`fail_name_copy_after`] says this name copy fails. - pub(super) fn name_copy(what: &'static str) -> Result<()> { - NAME_COPIES_LEFT.with(|left| match left.get() { - Some(0) => { - left.set(None); - Err(MeshOpsError::OutOfMemory(what)) - } - Some(k) => { - left.set(Some(k - 1)); - Ok(()) - } - None => Ok(()), - }) - } - fn quad() -> Mesh { Mesh::from_parts( vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(0.0, 1.0, 0.0)], @@ -1445,28 +516,26 @@ mod tests { #[test] fn wire_edges_leave_out_polygon_diagonals() { - let l = Limits::default(); let mut m = quad(); - assert_eq!(m.wire_edges(&l).unwrap(), vec![vec![(0, 1), (1, 2), (0, 2), (2, 3), (0, 3)]], "triangles show every edge"); + 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. m.diagonals = vec![0b100, 0b001]; - assert_eq!(m.wire_edges(&l).unwrap(), vec![vec![(0, 1), (1, 2), (2, 3), (0, 3)]]); + 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. let mut seam = m.clone(); seam.indices[3] = 4; - assert_eq!(seam.wire_edges(&l).unwrap()[0].len(), 6); + assert_eq!(seam.wire_edges()[0].len(), 6); // Appending keeps each side's diagonals on its own triangles. 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]); - assert_eq!(crate::primitives::plane(1.0, 2).wire_edges(&l).unwrap()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } #[test] fn uv_seams_are_where_the_uv_layout_splits() { - let l = Limits::default(); let mesh = quad(); - assert_eq!(mesh.uv_seam_edges(&l).unwrap(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut let mut seam = mesh.clone(); @@ -1475,12 +544,12 @@ mod tests { seam.tangents.push(seam.tangents[0]); seam.uvs.push(Vec2::new(0.9, 0.9)); seam.indices[3] = 4; - assert_eq!(seam.uv_seam_edges(&l).unwrap(), vec![vec![(0, 2), (2, 4)]]); + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); // The same split with the same UV is a hard edge, not a seam let mut hard = seam.clone(); hard.uvs[4] = hard.uvs[0]; - assert_eq!(hard.uv_seam_edges(&l).unwrap(), vec![Vec::<(u32, u32)>::new()]); + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); } #[test] @@ -1492,7 +561,7 @@ mod tests { mesh.uvs.push(Vec2::new(0.9, 0.9)); mesh.indices[3] = 4; assert_eq!(mesh.positions[0], mesh.positions[4]); - assert_eq!(mesh.uv_seam_edges(&Limits::default()).unwrap(), vec![vec![(0, 2), (2, 4)]]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); } #[test] @@ -1507,25 +576,19 @@ mod tests { mesh.submeshes[0].count = 3; mesh.submeshes.push(SubMesh { name: "second".into(), material: 1, start: 3, count: 3 }); - let l = Limits::default(); - assert_eq!(mesh.uv_seam_edges(&l).unwrap(), vec![vec![(0, 2)], vec![(2, 4)]]); + assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2)], vec![(2, 4)]]); mesh.uvs[4] = mesh.uvs[0]; - assert_eq!(mesh.uv_seam_edges(&l).unwrap(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new(); 2], "a material boundary alone is not a UV seam"); } #[test] - fn material_uvs_leave_absent_attributes_absent() { - // UVs only, two materials sharing the diagonal's vertices 0 and 2. - let uvs = [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; - let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]; - let mut m = Mesh::from_slices(&positions, None, Some(&uvs), &[0, 1, 2, 0, 2, 3], &Limits::default()).unwrap(); - m.materials = vec!["a".into(), "b".into()]; - m.submeshes = - vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; - m.map_material_uvs(1, |uv| uv * 0.5, &Limits::default()).unwrap(); - assert_eq!(m.positions.len(), 6, "vertices 0 and 2 are copied for material 1"); - assert_eq!(m.uvs.len(), 6); - assert!(m.normals.is_empty() && m.tangents.is_empty() && m.colors.is_empty(), "{m:?}"); + fn subdivision_shares_edge_midpoints() { + let m = quad().subdivided(); + // 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles. + assert_eq!((m.positions.len(), m.triangle_count()), (9, 8)); + assert_eq!(m.uvs.len(), 9); + assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24)); + m.validate().unwrap(); } #[test] @@ -1568,8 +631,7 @@ mod tests { m.submeshes = vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; let before = m.clone(); - let l = Limits::default(); - m.map_material_uvs(1, |uv| uv + Vec2::X, &l).unwrap(); + m.map_material_uvs(1, |uv| uv + Vec2::X); m.validate().unwrap(); assert_eq!(m.vertex_count(), 6, "the two shared vertices are split"); assert_eq!(&m.indices[..3], &before.indices[..3]); @@ -1579,859 +641,7 @@ mod tests { let (old, new) = (before.indices[3 + k] as usize, m.indices[3 + k] as usize); assert_eq!((m.uvs[new], m.positions[new]), (before.uvs[old] + Vec2::X, before.positions[old])); } - assert_eq!(m.uv_tiles(1, &l).unwrap().into_iter().collect::>(), vec![(1, 0)]); - assert_eq!(m.uv_tiles(0, &l).unwrap().into_iter().collect::>(), vec![(0, 0)]); - } - - #[test] - fn material_uvs_pass_each_vertex_the_centroid_of_its_first_triangle() { - // A fan of triangles t = (0, t + 1, t + 2): vertex 0 is in every triangle, and vertex - // v >= 2 is first in triangle v - 2. - let fan = 40u32; - let positions = (0..=fan + 1).map(|i| Vec3::new(i as f32, (i * i) as f32, 0.0)).collect(); - let uvs: Vec = (0..=fan + 1).map(|i| Vec2::new(i as f32, 0.5 * i as f32 + 0.25)).collect(); - let indices = (0..fan).flat_map(|t| [0, t + 1, t + 2]).collect(); - let mut m = Mesh::from_parts(positions, None, uvs.clone(), indices, "a").unwrap(); - let centroid = |t: u32| (uvs[0] + uvs[t as usize + 1] + uvs[t as usize + 2]) / 3.0; - m.map_material_uvs_with(0, |c, _| c, &Limits::default()).unwrap(); - assert_eq!((m.uvs[0], m.uvs[1]), (centroid(0), centroid(0))); - for v in 2..=fan + 1 { - assert_eq!(m.uvs[v as usize], centroid(v - 2), "vertex {v}"); - } - } - - #[test] - fn uv_centroids_of_large_finite_uvs_stay_finite() { - // Three UVs of 1.5e38 sum past f32::MAX; their centroid is 1.5e38. - let big = Vec2::splat(1.5e38); - let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![big; 3], vec![0, 1, 2], "a").unwrap(); - let l = Limits::default(); - assert_eq!(m.uv_tiles(0, &l).unwrap().into_iter().collect::>(), vec![(i32::MAX, i32::MAX)]); - m.map_material_uvs_with(0, |c, _| c, &l).unwrap(); - assert_eq!(m.uvs, vec![big; 3]); - } - - /// One triangle in UV tile (0, 0) that `listings` submeshes of material 0 all list. - fn listed_triangle(listings: usize) -> Mesh { - let uvs = vec![Vec2::new(0.1, 0.1), Vec2::new(0.9, 0.1), Vec2::new(0.1, 0.9)]; - let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, uvs, vec![0, 1, 2], "a").unwrap(); - m.submeshes = vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }; listings]; - m - } - - fn at_most(triangles: usize) -> Limits { - Limits { max_triangles: triangles, ..Limits::default() } - } - - fn too_many(got: u64, limit: u64) -> MeshOpsError { - MeshOpsError::TooLarge { what: "triangle count", got, limit } - } - - #[test] - fn listed_triangles_bound_wire_edges() { - let m = listed_triangle(5); - m.validate().unwrap(); - assert_eq!(m.wire_edges(&at_most(4)), Err(too_many(5, 4))); - assert_eq!(too_many(5, 4).to_string(), "triangle count 5 is over the limit of 4"); - assert_eq!(m.wire_edges(&at_most(5)).unwrap(), vec![vec![(0, 1), (1, 2), (0, 2)]]); - } - - #[test] - fn listed_triangles_bound_uv_seams() { - let m = listed_triangle(5); - assert_eq!(m.uv_seam_edges(&at_most(4)), Err(too_many(5, 4))); - assert_eq!(m.uv_seam_edges(&at_most(5)).unwrap(), vec![Vec::<(u32, u32)>::new()]); - } - - #[test] - fn listed_triangles_bound_uv_tiles() { - let m = listed_triangle(5); - assert_eq!(m.uv_tiles(0, &at_most(4)), Err(too_many(5, 4))); - assert_eq!(m.uv_tiles(0, &at_most(5)).unwrap().into_iter().collect::>(), vec![(0, 0)]); - } - - #[test] - fn material_mapping_bounds_split_vertices() { - // quad(): the second triangle in its own material shares two vertices with the first. - let mut m = quad(); - m.materials = vec!["a".into(), "b".into()]; - m.submeshes = - vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; - let before = m.clone(); - let calls = std::cell::Cell::new(0); - let f = |uv: Vec2| { - calls.set(calls.get() + 1); - uv + Vec2::X - }; - let vertices = |max_vertices| Limits { max_vertices, ..Limits::default() }; - for limit in [4, 5] { - let too_large = MeshOpsError::TooLarge { what: "vertex count", got: 6, limit: limit as u64 }; - assert_eq!(m.map_material_uvs(1, f, &vertices(limit)), Err(too_large)); - assert_eq!((calls.get(), &m), (0, &before), "nothing is mapped or changed"); - } - m.map_material_uvs(1, f, &vertices(6)).unwrap(); - assert_eq!((calls.get(), m.vertex_count()), (3, 6)); - m.validate().unwrap(); - - // A mesh over the limit without any shared vertex. - let mut one = listed_triangle(1); - let before = one.clone(); - assert_eq!(one.map_material_uvs(0, f, &vertices(2)), Err(MeshOpsError::TooLarge { what: "vertex count", got: 3, limit: 2 })); - assert_eq!((calls.get(), &one), (3, &before)); - one.map_material_uvs(0, f, &vertices(3)).unwrap(); - assert_eq!((calls.get(), one.vertex_count()), (6, 3)); - } - - #[test] - fn listed_triangles_bound_material_mapping() { - let mut m = listed_triangle(5); - let before = m.clone(); - let calls = std::cell::Cell::new(0); - let f = |uv: Vec2| { - calls.set(calls.get() + 1); - uv + Vec2::X - }; - assert_eq!(m.map_material_uvs(0, f, &at_most(4)), Err(too_many(5, 4))); - assert_eq!((calls.get(), &m), (0, &before), "nothing is mapped or changed"); - m.map_material_uvs(0, f, &at_most(5)).unwrap(); - assert_eq!(calls.get(), 3, "each vertex is mapped once"); - m.validate().unwrap(); - assert_eq!(m.uvs, before.uvs.iter().map(|uv| *uv + Vec2::X).collect::>()); - } - - #[test] - fn repeated_listing_keeps_single_hidden_edge() { - let mut once = listed_triangle(1); - once.diagonals = vec![0b001]; - let mut twice = once.clone(); - twice.submeshes.push(twice.submeshes[0].clone()); - let edges = once.wire_edges(&at_most(1)).unwrap(); - assert_eq!(edges, vec![vec![(0, 1), (1, 2), (0, 2)]], "a hidden edge with one triangle stays"); - assert_eq!(twice.wire_edges(&at_most(2)).unwrap(), edges); - - // A quad whose diagonal a seam split (vertex 4 copies vertex 0): each half keeps its - // diagonal, also when a second submesh lists the second half again. - let mut seam = quad(); - seam.positions.push(seam.positions[0]); - seam.normals.push(seam.normals[0]); - seam.tangents.push(seam.tangents[0]); - seam.uvs.push(seam.uvs[0]); - seam.indices[3] = 4; - seam.diagonals = vec![0b100, 0b001]; - let edges = seam.wire_edges(&at_most(2)).unwrap(); - assert_eq!(edges[0].len(), 6, "{edges:?}"); - seam.submeshes.push(SubMesh { name: "again".into(), material: 0, start: 3, count: 3 }); - assert_eq!(seam.wire_edges(&at_most(3)).unwrap(), edges); - } - - #[test] - fn first_listings_of_overlapping_ranges() { - // A repeated range, the gaps around and between earlier ranges, a range touching an - // earlier one, a range over all of them and an empty range. - let ranges = [10..20, 10..20, 30..40, 5..45, 45..50, 0..60, 7..7]; - assert_eq!(first_listings(&ranges).unwrap(), vec![10..20, 30..40, 5..10, 20..30, 40..45, 45..50, 0..5, 50..60]); - // A later range inside an earlier one adds nothing; an earlier range inside a later one - // splits it. - assert_eq!(first_listings(&[0..10, 2..4]).unwrap(), vec![0..10]); - assert_eq!(first_listings(&[2..4, 0..10]).unwrap(), vec![2..4, 0..2, 4..10]); - assert_eq!(first_listings(&[]).unwrap(), Vec::>::new()); - } - - #[test] - fn mapping_rejects_cross_material_triangle_overlap() { - let mut m = listed_triangle(1); - m.materials.push("b".into()); - m.submeshes.push(SubMesh { name: "b".into(), material: 1, start: 0, count: 3 }); - m.validate().unwrap(); - let before = m.clone(); - let calls = std::cell::Cell::new(0); - let result = m.map_material_uvs( - 0, - |uv| { - calls.set(calls.get() + 1); - uv - }, - &Limits::default(), - ); - assert_eq!(result, Err(MeshOpsError::Invalid("triangle belongs to more than one material".into()))); - assert_eq!((calls.get(), &m), (0, &before), "nothing is mapped or changed"); - - // Material a lists both triangles of a quad; b lists the second one, after a range of a - // that ends where b starts. - let mut quad2 = quad(); - quad2.materials = vec!["a".into(), "b".into()]; - let sub = |material, start| SubMesh { name: String::new(), material, start, count: 3 }; - quad2.submeshes = vec![sub(0, 0), sub(1, 3)]; - assert_eq!(quad2.listed_by_other(0), Ok(false), "adjacent ranges do not overlap"); - quad2.submeshes.push(sub(0, 3)); - let invalid = Err(MeshOpsError::Invalid("triangle belongs to more than one material".into())); - assert_eq!(quad2.map_material_uvs(0, |uv| uv, &Limits::default()), invalid); - assert_eq!(quad2.map_material_uvs(1, |uv| uv, &Limits::default()), invalid); - } - - #[test] - fn edges_group_submesh_ranges_by_material_in_order() { - // Material b lists triangle 1, then triangle 0; material c lists none. - let mut m = quad(); - m.materials = vec!["a".into(), "b".into(), "c".into()]; - m.submeshes = vec![ - SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }, - SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, - SubMesh { name: "b".into(), material: 1, start: 0, count: 3 }, - ]; - assert_eq!(m.ranges_by_material(&at_most(3)).unwrap(), vec![vec![0..1], vec![1..2, 0..1], vec![]]); - assert_eq!(m.ranges_by_material(&at_most(2)), Err(too_many(3, 2))); - assert_eq!(m.wire_edges(&at_most(3)).unwrap(), vec![vec![(0, 1), (1, 2), (0, 2)], vec![(0, 2), (2, 3), (0, 3), (0, 1), (1, 2)], vec![]]); - assert_eq!(m.uv_seam_edges(&at_most(3)).unwrap(), vec![Vec::<(u32, u32)>::new(); 3]); - } - - #[test] - fn subdivision_shares_edge_midpoints() { - let m = quad().subdivided(); - // 4 corners + 5 edge midpoints (the diagonal is shared), 8 triangles. - assert_eq!((m.positions.len(), m.triangle_count()), (9, 8)); - assert_eq!(m.uvs.len(), 9); - assert_eq!((m.submeshes[0].start, m.submeshes[0].count), (0, 24)); - m.validate().unwrap(); - } - - /// An index past the last vertex reads as the origin in MikkTSpace's callbacks. With two - /// positions at the origin and one missing, the degenerate-mesh guard (which sees the missing - /// vertex as different) let it through while MikkTSpace saw every triangle as degenerate and - /// underflowed: a panic in debug builds, an out-of-bounds walk in release. - #[test] - fn from_parts_refuses_an_out_of_range_index_without_crashing() { - let positions = vec![Vec3::ZERO, Vec3::X]; - let uvs = vec![Vec2::ZERO, Vec2::X]; - let e = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2], "M").unwrap_err(); - assert!(e.to_string().contains("out of range"), "{e}"); - } - - /// `from_parts` refuses a mesh over its triangle cap before it computes normals and tangents. - /// With a cap of one triangle, a two-triangle mesh is refused, though `validate` passes it. - #[test] - fn from_parts_checks_the_triangle_cap_before_computing_attributes() { - let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::ONE]; - let uvs = vec![Vec2::ZERO, Vec2::X, Vec2::Y, Vec2::ONE]; - let e = Mesh::from_parts_capped(positions, None, uvs, vec![0, 1, 2, 1, 3, 2], "M", 1).unwrap_err(); - assert!(e.to_string().contains("more than 1 triangles"), "{e}"); - } - - #[test] - fn tangents_of_a_mesh_with_an_out_of_range_index_fall_back_without_crashing() { - for indices in [vec![0, 1, 2], vec![0, 0, 2], vec![0, 1, 5, 0, 1, 1]] { - let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, vec![Vec2::ZERO, Vec2::X, Vec2::Y], vec![0, 1, 2], "M").unwrap(); - m.positions.truncate(2); - m.normals.truncate(2); - m.uvs.truncate(2); - m.indices = indices; - m.compute_tangents(); - assert_eq!(m.tangents.len(), 2); - assert!(m.tangents.iter().all(|t| t.is_finite()), "{:?}", m.tangents); - } - } - - #[test] - fn submesh_ranges_and_append_reject_overflow() { - // A submesh whose end passes u32::MAX: no triangles, and no overflow. - let mut m = quad(); - m.submeshes[0] = SubMesh { name: "far".into(), material: 0, start: u32::MAX - 2, count: 6 }; - assert_eq!(m.triangles_of(0).count(), 0); - assert_eq!(m.material_of(1), None); - - // Rebasing a submesh past u32::MAX is an error that leaves the mesh as it was. - let mut far = quad(); - far.submeshes[0].start = u32::MAX - 5; - let mut a = quad(); - let before = a.clone(); - assert!(a.try_append(&far).is_err()); - a.append(&far); - assert_eq!(a, before); - } - - #[test] - fn tangents_reject_non_finite_and_survive_extreme_positions() { - let quad_at = |s: f32| [[0.0, 0.0, 0.0], [s, 0.0, 0.0], [s, s, 0.0], [0.0, s, 0.0]]; - let normals = [[0.0, 0.0, 1.0]; 4]; - let uvs = [[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; - let indices = [0, 1, 2, 0, 2, 3]; - let limits = Limits::default(); - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let mut positions = quad_at(1.0); - positions[2][1] = bad; - assert!(crate::tangents(&positions, &normals, &uvs, &indices, &limits).is_err(), "{bad}"); - let mut normal = normals; - normal[1][0] = bad; - assert!(crate::tangents(&quad_at(1.0), &normal, &uvs, &indices, &limits).is_err(), "normal {bad}"); - let mut uv = uvs; - uv[3][1] = bad; - assert!(crate::tangents(&quad_at(1.0), &normals, &uv, &indices, &limits).is_err(), "uv {bad}"); - // The Mesh form falls back instead of handing the value to MikkTSpace. - let mut m = Mesh { positions: positions.iter().map(|p| Vec3::from_array(*p)).collect(), indices: indices.to_vec(), ..Mesh::default() }; - m.compute_tangents(); - assert_eq!(m.tangents.len(), 4); - } - // Near f32::MAX the edge products overflow unless the positions are scaled first. - for s in [3e38f32, 1e30, 1e9, 1e6, 1e-6, 1e-9, 1e-30] { - let t = crate::tangents(&quad_at(s), &normals, &uvs, &indices, &limits).unwrap(); - for t in &t { - assert!((Vec4::from_array(*t) - Vec4::new(1.0, 0.0, 0.0, 1.0)).length() < 1e-4, "scale {s}: {t:?}"); - } - let n = crate::smooth_normals(&quad_at(s), &indices, &limits).unwrap(); - assert!(n.iter().all(|n| (Vec3::from_array(*n) - Vec3::Z).length() < 1e-5), "scale {s}: {n:?}"); - } - let large_uvs = uvs.map(|uv| [uv[0] * 3e38, uv[1] * 3e38]); - let t = crate::tangents(&quad_at(1.0), &normals, &large_uvs, &indices, &limits).unwrap(); - assert!(t.iter().all(|t| (Vec4::from_array(*t) - Vec4::new(1.0, 0.0, 0.0, 1.0)).length() < 1e-4), "{t:?}"); - // The largest positions and UVs that are not divided first. - let edge_uvs = uvs.map(|uv| [uv[0] * 1e6, uv[1] * 1e6]); - let t = crate::tangents(&quad_at(1e6), &normals, &edge_uvs, &indices, &limits).unwrap(); - assert!(t.iter().all(|t| (Vec4::from_array(*t) - Vec4::new(1.0, 0.0, 0.0, 1.0)).length() < 1e-4), "{t:?}"); - } - - #[test] - fn tangents_stay_finite_beside_a_non_finite_normal() { - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - let mut m = quad(); - m.normals[1] = Vec3::new(bad, 0.0, 1.0); - m.compute_tangents(); - assert_eq!(m.tangents.len(), 4, "{bad}"); - for (v, t) in m.tangents.iter().enumerate() { - assert!(t.is_finite() && t.w.abs() == 1.0, "{bad}, vertex {v}: {t:?}"); - assert!((t.truncate().length() - 1.0).abs() < 1e-5, "{bad}, vertex {v}: {t:?}"); - } - } - } - - #[test] - fn normals_of_many_large_triangles_at_one_vertex_do_not_overflow() { - // Twenty copies of one triangle: the summed face normal at each corner is 2e19 long, and - // its square is past f32::MAX. - let positions = [[0.0, 0.0, 0.0], [1e9, 0.0, 0.0], [0.0, 1e9, 0.0]]; - let indices = [0u32, 1, 2].repeat(20); - let n = crate::smooth_normals(&positions, &indices, &Limits::default()).unwrap(); - assert!(n.iter().all(|n| (Vec3::from_array(*n) - Vec3::Z).length() < 1e-6), "{n:?}"); - // The same sum normalizes without the division, as it does for a vector whose square - // rounds to zero. - assert_eq!(unit(Vec3::new(0.0, 0.0, 2e19)), Some(Vec3::Z)); - assert_eq!(unit(Vec3::new(-1e-25, 0.0, 0.0)), Some(Vec3::NEG_X)); - assert_eq!((unit(Vec3::ZERO), unit(Vec3::new(f32::NAN, 0.0, 0.0)), unit(Vec3::new(f32::INFINITY, 0.0, 0.0))), (None, None, None)); - } - - #[test] - fn bounds_reject_non_finite_positions() { - let mut m = quad(); - m.positions[1] = Vec3::new(f32::NAN, 5.0, 0.0); - m.positions[2] = Vec3::new(9.0, f32::INFINITY, 0.0); - assert_eq!(m.bounds(), (Vec3::ZERO, Vec3::new(0.0, 1.0, 0.0)), "only the finite corners count"); - assert!(crate::bounds(&[[0.0, 0.0, 0.0], [f32::NAN, 1.0, 1.0]]).is_err()); - assert!(crate::bounds(&[[0.0, 0.0, 0.0], [1.0, f32::INFINITY, 1.0]]).is_err()); - assert_eq!(crate::bounds(&[[1.0, -2.0, 3.0], [-1.0, 2.0, 0.0]]).unwrap(), Some(([-1.0, -2.0, 0.0], [1.0, 2.0, 3.0]))); - assert_eq!(crate::bounds(&[]).unwrap(), None); - } - - #[test] - fn validate_rejects_unaligned_and_overflowing_submeshes() { - for (start, count) in [(1, 3), (0, 4), (u32::MAX - 2, 6), (u32::MAX, u32::MAX), (3, 6)] { - let mut m = quad(); - m.submeshes[0].start = start; - m.submeshes[0].count = count; - assert!(m.validate().is_err(), "start {start}, count {count}"); - } - let mut m = quad(); - m.normals[0] = Vec3::NAN; - assert!(m.validate().is_err(), "non-finite normal"); - let mut m = quad(); - m.uvs[0] = Vec2::new(0.0, f32::INFINITY); - assert!(m.validate().is_err(), "non-finite UV"); - } - - #[test] - fn append_keeps_attributes_aligned() { - // A mesh without tangents gets them; one without normals or UVs gets computed normals - // and zero UVs. - let mut bare = quad(); - bare.tangents.clear(); - let mut a = quad(); - a.append(&bare); - a.validate().unwrap(); - assert_eq!((a.positions.len(), a.tangents.len()), (8, 8)); - let mut bare = quad(); - bare.normals.clear(); - bare.uvs.clear(); - bare.tangents.clear(); - let mut b = quad(); - b.append(&bare); - b.validate().unwrap(); - assert_eq!(b.uvs[4..], [Vec2::ZERO; 4]); - assert!((b.normals[5] - Vec3::Z).length() < 1e-5); - // Neither side has tangents: the result has none either. - let mut c = quad(); - c.tangents.clear(); - c.append(&bare); - assert_eq!((c.positions.len(), c.normals.len(), c.uvs.len(), c.tangents.len()), (8, 8, 8, 0)); - // An empty mesh has no attributes to pass on: appending it to a mesh without tangents - // leaves the mesh as it was, and the other way round the result has no tangents either. - let mut d = quad(); - d.tangents.clear(); - let before = d.clone(); - d.append(&Mesh::default()); - assert_eq!(d, before); - let mut e = Mesh::default(); - e.append(&before); - assert_eq!((e.positions.len(), e.normals.len(), e.uvs.len(), e.tangents.len()), (4, 4, 4, 0)); - // An index past the other mesh's vertices would point into this one after rebasing. - let mut broken = quad(); - broken.indices[0] = 4; - assert!(quad().try_append(&broken).is_err()); - } - - #[test] - fn append_fills_in_this_mesh_when_its_tangents_split_vertices() { - // UVs mirrored across the diagonal: computing this mesh's tangents splits the shared - // vertices, and the copies keep their colors. - let mut a = quad(); - a.normals.clear(); - a.tangents.clear(); - a.uvs[3] = Vec2::new(1.0, 1.0); - a.colors = vec![Vec4::new(1.0, 0.0, 0.0, 1.0); 4]; - a.diagonals = vec![0b100, 0]; - let other = quad(); - a.try_append(&other).unwrap(); - a.validate().unwrap(); - let n = a.positions.len(); - assert!(n > 8, "{n} vertices"); - assert_eq!((a.normals.len(), a.uvs.len(), a.tangents.len(), a.colors.len()), (n, n, n, n)); - assert!(a.colors[..n - 4].iter().all(|&c| c == Vec4::new(1.0, 0.0, 0.0, 1.0)), "{:?}", a.colors); - assert_eq!(a.colors[n - 4..], [Vec4::ONE; 4]); - assert_eq!(a.diagonals, vec![0b100, 0, 0, 0]); - let base = (n - 4) as u32; - assert_eq!(a.indices[6..], other.indices.iter().map(|i| i + base).collect::>()[..]); - } - - #[test] - fn append_keeps_unnamed_materials_apart() { - // A submesh may use material 0 of an empty material list. - let mut unnamed = quad(); - unnamed.materials.clear(); - unnamed.validate().unwrap(); - let mut a = unnamed.clone(); - a.append(&quad()); - a.validate().unwrap(); - assert_eq!(a.materials, vec![String::new(), "Default".to_string()]); - assert_eq!((a.submeshes[0].material, a.submeshes[1].material), (0, 1)); - let mut b = quad(); - b.append(&unnamed); - b.validate().unwrap(); - assert_eq!(b.materials, vec!["Default".to_string(), String::new()]); - assert_eq!((b.submeshes[0].material, b.submeshes[1].material), (0, 1)); - } - - /// A quad whose two triangles are submeshes named `c` and `d`, with materials `a` and `b`. - fn named_quad(a: String, b: String, c: String, d: String) -> Mesh { - let mut m = quad(); - m.materials = vec![a, b]; - m.submeshes = vec![SubMesh { name: c, material: 1, start: 0, count: 3 }, SubMesh { name: d, material: 0, start: 3, count: 3 }]; - m - } - - #[test] - fn append_copies_long_names_in_order() { - let long = |c: char| c.to_string().repeat(4096); - let other = named_quad(long('a'), long('b'), long('c'), long('d')); - let mut m = quad(); - m.materials.clear(); - m.try_append(&other).unwrap(); - m.validate().unwrap(); - assert_eq!(m.materials, vec![String::new(), long('a'), long('b')]); - let submeshes = m.submeshes.iter().map(|s| (s.name.clone(), s.material, s.start, s.count)).collect::>(); - assert_eq!(submeshes[1..], [(long('c'), 2, 6, 3), (long('d'), 1, 9, 3)]); - } - - #[test] - fn append_leaves_the_mesh_unchanged_when_a_name_copy_fails() { - let other = named_quad("a".into(), "b".into(), "c".into(), "d".into()); - let mut m = quad(); - let before = m.clone(); - // The two submesh names are copied first, then the two material names. - for (copies, what) in [(0, "submeshes"), (1, "submeshes"), (2, "materials"), (3, "materials")] { - fail_name_copy_after(Some(copies)); - assert_eq!(m.try_append(&other), Err(MeshOpsError::OutOfMemory(what)), "after {copies} copies"); - assert_eq!(m, before, "after {copies} copies"); - } - fail_name_copy_after(None); - m.try_append(&other).unwrap(); - assert_eq!(m.materials, ["Default", "a", "b"]); - } - - #[test] - fn subdivision_reports_a_failed_name_copy() { - let m = named_quad("a".into(), "b".into(), "c".into(), "d".into()); - // Both submesh names are copied before the material names. - for (copies, what) in [(0, "submeshes"), (1, "submeshes"), (2, "materials"), (3, "materials")] { - fail_name_copy_after(Some(copies)); - assert_eq!(m.try_subdivided(&Limits::default()), Err(MeshOpsError::OutOfMemory(what)), "after {copies} copies"); - } - fail_name_copy_after(None); - let s = m.try_subdivided(&Limits::default()).unwrap(); - assert_eq!((s.materials, s.submeshes.iter().map(|s| s.name.as_str()).collect::>()), (m.materials, vec!["c", "d"])); - } - - #[test] - fn subdivision_preserves_large_finite_midpoints() { - let mut m = quad(); - m.positions = vec![Vec3::new(3e38, 0.0, 0.0), Vec3::new(3e38, 3e38, 0.0), Vec3::new(-3e38, 3e38, 0.0), Vec3::new(-3e38, -3e38, 0.0)]; - m.uvs = vec![Vec2::new(3e38, 0.0), Vec2::new(3e38, 3e38), Vec2::ZERO, Vec2::ZERO]; - let s = m.try_subdivided(&Limits::default()).unwrap(); - assert!(s.positions.iter().all(|p| p.is_finite()), "{:?}", s.positions); - assert!(s.uvs.iter().all(|p| p.is_finite()), "{:?}", s.uvs); - assert!(s.positions.contains(&Vec3::new(3e38, 1.5e38, 0.0))); - } - - #[test] - fn subdivision_keeps_midpoint_normals_and_tangents_of_long_vectors() { - let mut m = quad(); - // Edge 0-1: the sum's squared length overflows; edge 2-3: the sum itself overflows. - m.normals = vec![Vec3::new(1e20, 0.0, 0.0), Vec3::new(1e20, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0)]; - m.tangents = vec![Vec4::new(1e20, 0.0, 0.0, 1.0); 4]; - let s = m.try_subdivided(&Limits::default()).unwrap(); - assert_eq!(s.positions.len(), 9); - for n in &s.normals[4..] { - assert!((*n - Vec3::X).length() < 1e-6, "{:?}", s.normals); - } - for t in &s.tangents[4..] { - assert!((*t - Vec4::new(1.0, 0.0, 0.0, 1.0)).length() < 1e-6, "{:?}", s.tangents); - } - } - - #[test] - fn subdivision_keeps_the_input_vertices_and_materials() { - let mut m = quad(); - m.colors = vec![Vec4::X, Vec4::Y, Vec4::Z, Vec4::W]; - let s = m.try_subdivided(&Limits::default()).unwrap(); - let n = m.positions.len(); - assert_eq!(s.positions[..n], m.positions[..]); - assert_eq!(s.normals[..n], m.normals[..]); - assert_eq!(s.tangents[..n], m.tangents[..]); - assert_eq!(s.uvs[..n], m.uvs[..]); - assert_eq!(s.colors[..n], m.colors[..]); - assert_eq!(s.colors.len(), s.positions.len()); - assert_eq!(s.materials, m.materials); - assert_eq!(s.submeshes.iter().map(|s| (&s.name, s.material)).collect::>(), vec![(&m.submeshes[0].name, 0)]); - // An input with no diagonals gives a result with none. - assert!(m.diagonals.is_empty() && s.diagonals.is_empty()); - } - - #[test] - fn subdivision_checks_submeshes_and_diagonals() { - // Two materials, one triangle each: each keeps its own four children. - let mut m = quad(); - m.materials = vec!["a".into(), "b".into()]; - m.submeshes = - vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 3 }, SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }]; - m.diagonals = vec![0b100, 0b001]; - let s = m.try_subdivided(&Limits::default()).unwrap(); - s.validate().unwrap(); - assert_eq!(s.triangles_of(0).collect::>(), vec![0, 1, 2, 3]); - assert_eq!(s.triangles_of(1).collect::>(), vec![4, 5, 6, 7]); - assert_eq!(s.diagonals.len(), s.triangle_count()); - // The diagonal (0, 2) splits at vertex 6; both halves stay hidden. A subdivided quad has - // 16 edges. - let whole = - Mesh { materials: vec!["a".into()], submeshes: vec![SubMesh { name: "a".into(), material: 0, start: 0, count: 24 }], ..s.clone() }; - let edges = &whole.wire_edges(&Limits::default()).unwrap()[0]; - assert!(!edges.contains(&(0, 6)) && !edges.contains(&(2, 6)), "{edges:?}"); - assert_eq!(edges.len(), 16 - 2, "{edges:?}"); - - // A submesh that splits a triangle, ends past the indices or overflows is an error. - for (start, count) in [(1, 3), (0, 9), (u32::MAX - 2, 6)] { - let mut bad = quad(); - bad.submeshes[0].start = start; - bad.submeshes[0].count = count; - assert!(bad.try_subdivided(&Limits::default()).is_err(), "start {start}, count {count}"); - assert_eq!(bad.subdivided(), bad, "the infallible form leaves the mesh unchanged"); - } - let mut bad = quad(); - bad.indices[1] = 9; - assert!(bad.try_subdivided(&Limits::default()).is_err()); - // A submesh naming a material the mesh lacks fails, as it fails validate. - let mut bad = quad(); - bad.submeshes[0].material = bad.materials.len().max(1); - assert!(bad.validate().is_err()); - assert!(matches!(bad.try_subdivided(&Limits::default()), Err(MeshOpsError::Invalid(_)))); - assert_eq!(bad.subdivided(), bad); - let small = Limits { max_triangles: 7, ..Limits::default() }; - assert!(quad().try_subdivided(&small).is_err()); - // The quad's two triangles share one of their six midpoints: 9 vertices, not 10. - let exact = Limits { max_vertices: 9, ..Limits::default() }; - assert_eq!(quad().try_subdivided(&exact).unwrap().positions.len(), 9); - let under = Limits { max_vertices: 8, ..Limits::default() }; - assert!(matches!(quad().try_subdivided(&under), Err(MeshOpsError::TooLarge { .. }))); - } - - #[test] - fn tri_rejects_overflowing_triangle_index() { - let m = quad(); - assert_eq!(m.tri(usize::MAX), None); - assert_eq!(m.tri(usize::MAX / 3 + 1), None); - assert_eq!(m.material_of(usize::MAX), None); - } - - #[test] - fn normalize_large_finite_meshes() { - let mut m = quad(); - m.positions = vec![Vec3::new(-3e38, -3e38, 0.0), Vec3::new(3e38, -3e38, 0.0), Vec3::new(3e38, 3e38, 0.0), Vec3::new(-3e38, 3e38, 0.0)]; - assert!(m.radius().is_finite()); - m.normalize_to(2.0); - assert!(m.positions.iter().all(|p| p.is_finite()), "{:?}", m.positions); - assert!((m.radius() - 2.0).abs() < 1e-4, "{}", m.radius()); - assert!((m.positions[2] - Vec3::new(2.0, 2.0, 0.0).normalize() * 2.0).length() < 1e-4, "{:?}", m.positions); - let before = m.clone(); - m.normalize_to(f32::NAN); - m.normalize_to(-1.0); - assert_eq!(m, before); - // One vertex far from the origin moves to the center. - let mut point = Mesh { positions: vec![Vec3::splat(3e38)], ..Mesh::default() }; - point.normalize_to(2.0); - assert_eq!(point.positions, vec![Vec3::ZERO]); - } - - #[test] - fn normalize_handles_the_largest_radii_and_the_smallest_meshes() { - // The unit quad has a radius of about 0.707, so f32::MAX divided by it passes f32::MAX; - // its corners still fit. - let mut unit = quad(); - unit.normalize_to(f32::MAX); - let corner = unit.positions[2] / f32::MAX; - assert!((corner - Vec3::new(1.0, 1.0, 0.0).normalize()).length() < 1e-4, "{:?}", unit.positions); - unit.normalize_to(1e30); - assert!(unit.positions.iter().all(|p| p.is_finite()), "{:?}", unit.positions); - assert!((unit.radius() / 1e30 - 1.0).abs() < 1e-4, "{}", unit.radius()); - // A mesh smaller than the floor of `radius` reaches the requested radius too. - for size in [1e-5f32, 1e-30] { - let mut small = crate::primitives::plane(1.0, 2); - for p in &mut small.positions { - *p *= size; - } - small.normalize_to(1.0); - assert!((small.radius() - 1.0).abs() < 1e-4, "{size}: {}", small.radius()); - } - // A plane spanning ±0.001 is above the floor, and 1e38 divided by its radius passes - // f32::MAX; its corners still fit. - let mut tiny = crate::primitives::plane(0.002, 2); - tiny.normalize_to(1e38); - assert!(tiny.positions.iter().all(|p| p.is_finite()), "{:?}", tiny.positions); - assert!((tiny.radius() / 1e38 - 1.0).abs() < 1e-4, "{}", tiny.radius()); - // A mesh already near f32::MAX reaches the largest radius: its corners fit. - let mut wide = quad(); - wide.positions = vec![Vec3::new(-3e38, -3e38, 0.0), Vec3::new(3e38, -3e38, 0.0), Vec3::new(3e38, 3e38, 0.0), Vec3::new(-3e38, 3e38, 0.0)]; - wide.normalize_to(f32::MAX); - let corner = wide.positions[2] / f32::MAX; - assert!((corner - Vec3::new(1.0, 1.0, 0.0).normalize()).length() < 1e-4, "{:?}", wide.positions); - } - - #[test] - fn tangents_skip_mikktspace_when_dividing_makes_every_triangle_degenerate() { - // Two different x coordinates near f32::MAX with the same quotient by the largest one. - let largest = 3.1e38f32; - let mut a = 1.6e38f32; - let mut b = f32::from_bits(a.to_bits() + 1); - for _ in 0..1000 { - if a / largest == b / largest { - break; - } - a = b; - b = f32::from_bits(a.to_bits() + 1); - } - assert!(a != b && a / largest == b / largest, "{a} {b}"); - let positions = [[a, 0.0, 0.0], [b, 0.0, 0.0], [0.0, largest, 0.0]]; - let uvs = [[0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]; - let t = crate::tangents(&positions, &[[0.0, 0.0, 1.0]; 3], &uvs, &[0, 1, 2], &Limits::default()).unwrap(); - assert_eq!(t.len(), 3); - assert!(t.iter().flatten().all(|v| v.is_finite()), "{t:?}"); - } - - #[test] - fn tangents_stay_perpendicular_to_very_long_normals() { - let direction = Vec3::new(1.0, 0.0, 3.0).normalize(); - let expected = (Vec3::X - direction * direction.x).normalize().extend(1.0); - // Normals near f32::MAX on a unit quad, and normals about 1e9 long on the largest quad - // and UVs that are not divided: MikkTSpace multiplies the normal twice into their product. - for (length, size) in [(1e38f32, 1.0f32), (3e8, 1e6)] { - let positions = [[0.0, 0.0, 0.0], [size, 0.0, 0.0], [size, size, 0.0], [0.0, size, 0.0]]; - let uvs = [[0.0, size], [size, size], [size, 0.0], [0.0, 0.0]]; - let normal = [length, 0.0, 3.0 * length]; - let t = crate::tangents(&positions, &[normal; 4], &uvs, &[0, 1, 2, 0, 2, 3], &Limits::default()).unwrap(); - for t in &t { - assert!((Vec4::from_array(*t) - expected).length() < 1e-3, "{length} {size}: {t:?}"); - } - } - } - - #[test] - fn a_small_triangle_far_from_the_origin_keeps_its_normal_and_tangent() { - // Unit edges along y and z at x = 1e24: divided by 1e24, their cross product underflows. - let positions = [[1e24, 0.0, 0.0], [1e24, 1.0, 0.0], [1e24, 0.0, 1.0]]; - let l = Limits::default(); - for n in crate::smooth_normals(&positions, &[0, 1, 2], &l).unwrap() { - assert_eq!(n, [1.0, 0.0, 0.0]); - } - // u grows along +y and v along +z: the bitangent points up the image, along -z, and - // cross(+x, +y) = +z, so w is -1. - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; - for t in crate::tangents(&positions, &[[1.0, 0.0, 0.0]; 3], &uvs, &[0, 1, 2], &l).unwrap() { - assert!((Vec4::from_array(t) - Vec4::new(0.0, 1.0, 0.0, -1.0)).length() < 1e-5, "{t:?}"); - } - } - - #[test] - fn fallback_tangents_keep_edges_that_vanish_when_divided() { - // Edges of 1e-10 at x = 1e38: divided by 1e38 in f32 they underflow to zero, so the - // triangle counts as degenerate and the fallback computes its tangent. - let positions = [[1e38, 0.0, 0.0], [1e38, 1e-10, 0.0], [1e38, 0.0, 1e-10]]; - // u grows along +z and v along +y: the tangent is +z, the bitangent points along -y, and - // cross(+x, +z) = -y, so w is +1. - let uvs = [[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]]; - for t in crate::tangents(&positions, &[[1.0, 0.0, 0.0]; 3], &uvs, &[0, 1, 2], &Limits::default()).unwrap() { - assert!((Vec4::from_array(t) - Vec4::new(0.0, 0.0, 1.0, 1.0)).length() < 1e-5, "{t:?}"); - } - } - - /// Positions, normals, UVs and indices. - type Slices = ([[f32; 3]; 4], [[f32; 3]; 4], [[f32; 2]; 4], [u32; 6]); - - /// Two triangles on vertices 0 and 1 whose UVs run in opposite directions: v grows toward +Y - /// on the first and toward -Y on the second. Bitangents point up the image (glTF 2.0), so the - /// first triangle's tangent frame has w = -1 and the second's w = +1. - fn opposite_handedness() -> Slices { - let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]; - let uvs = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 1.0]]; - (positions, [[0.0, 0.0, 1.0]; 4], uvs, [0, 1, 2, 1, 0, 3]) - } - - #[test] - fn tangents_split_vertices_shared_by_opposite_frames() { - let (positions, normals, uvs, indices) = opposite_handedness(); - let mut m = Mesh::from_slices(&positions, Some(&normals), Some(&uvs), &indices, &Limits::default()).unwrap(); - m.compute_tangents(); - m.validate().unwrap(); - // Vertices 0 and 1 get a copy each for the second triangle. - assert_eq!(m.positions.len(), 6); - for (t, w) in [(0, -1.0), (1, 1.0)] { - for (k, v) in m.tri(t).unwrap().into_iter().enumerate() { - let tangent = m.tangents[v]; - assert!((tangent - Vec3::X.extend(w)).length() < 1e-5, "triangle {t}, vertex {v}: {tangent}"); - let original = indices[t * 3 + k] as usize; - assert_eq!((m.positions[v], m.uvs[v]), (Vec3::from_array(positions[original]), Vec2::from_array(uvs[original]))); - } - } - // The slice form returns one tangent per input vertex, which cannot hold both frames. - assert!(matches!(crate::tangents(&positions, &normals, &uvs, &indices, &Limits::default()), Err(MeshOpsError::Invalid(_)))); - } - - #[test] - fn tangent_splits_stop_at_the_first_copy_they_may_not_make() { - let (positions, normals, uvs, indices) = opposite_handedness(); - // The second triangle's first corner, vertex 1, is the first to need a copy. - let e = crate::tangents(&positions, &normals, &uvs, &indices, &Limits::default()).unwrap_err(); - assert_eq!(e.to_string(), "invalid mesh: vertex 1 is shared by triangles with different tangent frames"); - let mesh = Mesh::from_slices(&positions, Some(&normals), Some(&uvs), &indices, &Limits::default()).unwrap(); - // Room for one of the two copies: the second is `TooLarge` and the mesh stays as it was. - let mut m = mesh.clone(); - let r = m.try_compute_tangents_splitting(Split::UpTo(5)); - assert!(matches!(r, Err(MeshOpsError::TooLarge { what: "vertex count", got: 6, limit: 5 })), "{r:?}"); - assert_eq!(m, mesh); - let mut m = mesh.clone(); - m.try_compute_tangents_splitting(Split::UpTo(6)).unwrap(); - assert_eq!(m.positions.len(), 6); - } - - #[test] - fn tangents_of_a_fan_around_one_vertex_do_not_exhaust_the_stack() { - // Every triangle shares vertex 0 with the same normal and UV; MikkTSpace would visit - // the fan recursively, one call per triangle. - let n = 200_000u32; - let mut positions = vec![[0.0f32, 0.0, 0.0]]; - for i in 0..=n { - let a = i as f32 / n as f32 * 6.0; - positions.push([a.cos(), a.sin(), 0.0]); - } - let indices: Vec = (0..n).flat_map(|i| [0, i + 1, i + 2]).collect(); - let normals = vec![[0.0, 0.0, 1.0]; positions.len()]; - // With v growing down the image along -y the bitangent points along +y and w is +1; with - // v mirrored to grow along +y, w is -1. - for (v_along_y, w) in [(-0.5f32, 1.0f32), (0.5, -1.0)] { - let uvs: Vec<[f32; 2]> = positions.iter().map(|p| [p[0] * 0.5 + 0.5, 0.5 + p[1] * v_along_y]).collect(); - let t = crate::tangents(&positions, &normals, &uvs, &indices, &Limits::default()).unwrap(); - assert_eq!(t.len(), positions.len()); - for t in &t { - assert!((Vec4::from_array(*t) - Vec4::new(1.0, 0.0, 0.0, w)).length() < 1e-2, "w {w}: {t:?}"); - } - } - } - - #[test] - fn fallback_tangents_have_the_handedness_mikktspace_gives() { - // Small fans go to MikkTSpace; past the valence limit the same frames come from the - // fallback, mirrored UVs included. - let fan = |n: u32, v_along_y: f32| { - let mut positions = vec![[0.0f32, 0.0, 0.0]]; - for i in 0..=n { - let a = i as f32 / n as f32 * 6.0; - positions.push([a.cos(), a.sin(), 0.0]); - } - let uvs: Vec<[f32; 2]> = positions.iter().map(|p| [0.5 - p[1] * 0.5, 0.5 + p[0] * v_along_y]).collect(); - let indices: Vec = (0..n).flat_map(|i| [0, i + 1, i + 2]).collect(); - let normals = vec![[0.0, 0.0, 1.0]; positions.len()]; - crate::tangents(&positions, &normals, &uvs, &indices, &Limits::default()).unwrap() - }; - for v_along_y in [0.5, -0.5] { - let (mikk, fallback) = (fan(16, v_along_y), fan(MAX_MIKKTSPACE_VALENCE as u32 + 1, v_along_y)); - let w = mikk[0][3]; - assert!(mikk.iter().chain(&fallback).all(|t| t[3] == w), "{v_along_y}: {:?} {:?}", mikk[0], fallback[0]); - assert!((Vec4::from_array(fallback[0]) - Vec4::from_array(mikk[0])).length() < 1e-2, "{:?} {:?}", fallback[0], mikk[0]); - } - } - - #[test] - fn tangents_keep_uv_differences_far_below_one() { - // V differs by 1e-8 between two corners: 1 - v rounds both to 1, and u grows along +y. - let m = Mesh::from_parts( - vec![Vec3::ZERO, Vec3::X, Vec3::Y], - Some(vec![Vec3::Z; 3]), - vec![Vec2::new(0.0, 0.0), Vec2::new(0.0, 1e-8), Vec2::new(1.0, 0.0)], - vec![0, 1, 2], - "m", - ) - .unwrap(); - for t in &m.tangents { - assert!((t.truncate() - Vec3::Y).length() < 1e-5, "{t}"); - } - } - - #[test] - fn coincident_copies_with_different_uvs_skip_mikktspace() { - // MikkTSpace compares the corners at one position with each other: this many copies of - // one triangle at the same place would cost it about 3 × 7,000² / 2 comparisons. - let copies = 7_000u32; - let positions = [Vec3::ZERO, Vec3::X, Vec3::Y].repeat(copies as usize); - let uvs: Vec = (0..copies).flat_map(|i| [Vec2::ZERO, Vec2::X, Vec2::Y].map(|uv| uv + Vec2::splat(i as f32))).collect(); - let indices: Vec = (0..copies * 3).collect(); - let normals = vec![Vec3::Z; positions.len()]; - let scales = Scales::of(&positions, &normals, &uvs); - let mut corners = vec![Vec4::ZERO; indices.len()]; - let g = Mikk { positions: &positions, normals: &normals, uvs: &uvs, indices: &indices, scales, corners: &mut corners }; - assert!(!g.affordable().unwrap()); - // The corners at the pole of a sphere at the segment limit share one position, and their - // UVs differ: MikkTSpace still gets them. - let pole = crate::primitives::try_sphere(1.0, MAX_MIKKTSPACE_VALENCE, 2, &Limits::default()).unwrap(); - let scales = Scales::of(&pole.positions, &pole.normals, &pole.uvs); - let mut corners = vec![Vec4::ZERO; pole.indices.len()]; - let g = Mikk { positions: &pole.positions, normals: &pole.normals, uvs: &pole.uvs, indices: &pole.indices, scales, corners: &mut corners }; - assert!(g.affordable().unwrap()); - // The fallback gives the copies their own frames: +X, with v growing down the image. - let mut m = Mesh { positions, normals, uvs, indices, ..Mesh::default() }; - m.try_compute_tangents().unwrap(); - assert!(m.tangents.iter().all(|t| (*t - Vec4::new(1.0, 0.0, 0.0, -1.0)).length() < 1e-5)); + assert_eq!(m.uv_tiles(1).into_iter().collect::>(), vec![(1, 0)]); + assert_eq!(m.uv_tiles(0).into_iter().collect::>(), vec![(0, 0)]); } } diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 74968d1e81..43a9f29684 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -1,17 +1,11 @@ //! Built-in meshes with clean, non-overlapping UVs: material ball, sphere, (rounded) cube, //! cylinder, torus and plane. Y is up; triangles are counter-clockwise seen from outside. -//! -//! Each `try_` builder checks its sizes (finite and positive) and its segment counts against -//! [`Limits`] and returns an error instead of building. A size so large that a coordinate -//! overflows `f32` is an error too. The builders without `try_` clamp the segment counts to the -//! default [`Limits::max_segments`] and return an empty mesh for an invalid size. use std::f32::consts::{PI, TAU}; -use glam::{DVec2, Vec2, Vec3}; +use glam::{Vec2, Vec3}; -use crate::mesh::{Mesh, Split, SubMesh, unit}; -use crate::{Limits, MeshOpsError, Result}; +use crate::mesh::{Mesh, SubMesh}; /// A UV-space rectangle: origin and size. #[derive(Clone, Copy, Debug)] @@ -38,42 +32,9 @@ struct Builder { idx: Vec, /// Per triangle: its [`Mesh::diagonals`] bits. diag: Vec, - limits: Limits, - /// Set when a part would pass the limits; later parts are skipped. - error: Option, } impl Builder { - fn new(limits: &Limits) -> Builder { - Builder { limits: *limits, ..Builder::default() } - } - - /// Whether `vertices` and `triangles` more fit the limits and `u32` indices, with the memory - /// for them reserved; records the error when they do not. - fn room(&mut self, vertices: Option, triangles: Option) -> bool { - if self.error.is_some() { - return false; - } - let total_vertices = vertices.and_then(|v| v.checked_add(self.p.len())).unwrap_or(usize::MAX); - let total_triangles = triangles.and_then(|t| t.checked_add(self.idx.len() / 3)).unwrap_or(usize::MAX); - let error = if total_vertices > self.limits.max_vertices || u32::try_from(total_vertices).is_err() { - Some(MeshOpsError::TooLarge { what: "vertex count", got: total_vertices as u64, limit: self.limits.max_vertices as u64 }) - } else if total_triangles > self.limits.max_triangles || total_triangles.checked_mul(3).and_then(|i| u32::try_from(i).ok()).is_none() { - Some(MeshOpsError::TooLarge { what: "triangle count", got: total_triangles as u64, limit: self.limits.max_triangles as u64 }) - } else { - // Both counts fit the limits, so they and three times the triangles are finite. - let (v, t) = (vertices.unwrap_or(0), triangles.unwrap_or(0)); - let reserved = self.p.try_reserve(v).is_ok() - && self.n.try_reserve(v).is_ok() - && self.uv.try_reserve(v).is_ok() - && self.idx.try_reserve(t * 3).is_ok() - && self.diag.try_reserve(t).is_ok(); - (!reserved).then_some(MeshOpsError::OutOfMemory("primitive")) - }; - self.error = error; - self.error.is_none() - } - fn vert(&mut self, p: Vec3, n: Vec3, uv: Vec2) -> u32 { self.p.push(p); self.n.push(n.try_normalize().unwrap_or(Vec3::Y)); @@ -83,10 +44,6 @@ impl Builder { /// A grid of (rows+1)×(cols+1) vertices from `f(row, col)`, rows going "down" the texture. fn grid(&mut self, rows: usize, cols: usize, mut f: impl FnMut(usize, usize) -> (Vec3, Vec3, Vec2)) { - let vertices = rows.checked_add(1).zip(cols.checked_add(1)).and_then(|(r, c)| r.checked_mul(c)); - if !self.room(vertices, rows.checked_mul(cols).and_then(|q| q.checked_mul(2))) { - return; - } let base = self.p.len() as u32; for i in 0..=rows { for j in 0..=cols { @@ -106,26 +63,17 @@ impl Builder { } } - /// The mesh of one material, with tangents. Computing them can split vertices; a copy that - /// would take the vertex count over the limit is `TooLarge` before it is made. - fn finish(self, material: &str) -> Result { - let max_vertices = self.limits.max_vertices; - let mut m = self.into_mesh(material)?; - m.try_compute_tangents_splitting(Split::UpTo(max_vertices))?; - Ok(m) + /// The mesh of one material, with tangents. + fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m } /// The mesh of one material, without tangents. - fn into_mesh(self, material: &str) -> Result { - if let Some(e) = self.error { - return Err(e); - } - // A finite size near f32::MAX can overflow where the builders add or scale coordinates. - if !(self.p.iter().all(|p| p.is_finite()) && self.n.iter().all(|n| n.is_finite()) && self.uv.iter().all(|uv| uv.is_finite())) { - return Err(MeshOpsError::Invalid("the primitive's coordinates overflow f32".into())); - } + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - Ok(Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -135,49 +83,14 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }) + } } } -/// A mesh of one material with no vertices: what the builders without `try_` return for an -/// invalid size. -fn empty(material: &str) -> Mesh { - Mesh { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count: 0 }], materials: vec![material.into()], ..Mesh::default() } -} - -/// `value` when it is finite and greater than zero. -fn positive(what: &str, value: f32) -> Result { - if value.is_finite() && value > 0.0 { Ok(value) } else { Err(MeshOpsError::Invalid(format!("{what} {value} is not a finite positive number"))) } -} - -/// `count`, raised to `min`, when the raised count is within the segment limit. -fn segments(what: &'static str, count: usize, min: usize, limits: &Limits) -> Result { - let count = count.max(min); - crate::check_limit(what, count, limits.max_segments)?; - Ok(count) -} - -/// Segments along one axis of a box face: in each of the two bevels, and between them. -fn box_segments(bevel: f32) -> (usize, usize) { - if bevel > 0.0 { (6, 10) } else { (0, 12) } -} - -/// A segment count clamped to the default limit, for the builders without `try_`. -fn clamped(count: usize) -> usize { - count.min(Limits::default().max_segments) -} - -/// UV sphere of `radius` around the origin. +/// UV sphere of `radius` centred at `center`. pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { - try_sphere(radius, clamped(segments), clamped(rings), &Limits::default()).unwrap_or_else(|_| empty("Sphere")) -} - -/// [`sphere`] with its parameters checked. -pub fn try_sphere(radius: f32, segs: usize, rings: usize, limits: &Limits) -> Result { - let radius = positive("sphere radius", radius)?; - let (segs, rings) = (segments("sphere segments", segs, 3, limits)?, segments("sphere rings", rings, 2, limits)?); - let mut b = Builder::new(limits); - sphere_into(&mut b, Vec3::ZERO, radius, segs, rings, UvRect::FULL); + let mut b = Builder::default(); + sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); b.finish("Sphere") } @@ -193,39 +106,19 @@ fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: u /// A box with rounded edges (`bevel` = edge radius; 0 gives a plain cube). Faces are laid out /// in a 3×2 UV atlas. pub fn rounded_box(half: Vec3, bevel: f32) -> Mesh { - try_rounded_box(half, bevel, &Limits::default()).unwrap_or_else(|_| empty("Box")) -} - -/// [`rounded_box`] with its parameters checked: every half size finite and positive, the bevel -/// finite (it is clamped to 0..0.95 of the smallest half size). A face has 12 segments along -/// each axis, or 22 with a bevel, which [`Limits::max_segments`] has to allow. -pub fn try_rounded_box(half: Vec3, bevel: f32, limits: &Limits) -> Result { - for v in half.to_array() { - positive("box half size", v)?; - } - if !bevel.is_finite() { - return Err(MeshOpsError::Invalid(format!("box bevel {bevel} is not finite"))); - } - let (in_bevel, between) = box_segments(bevel); - crate::check_limit("box segments", 2 * in_bevel + between, limits.max_segments)?; - let mut b = Builder::new(limits); + let mut b = Builder::default(); rounded_box_into(&mut b, Vec3::ZERO, half, bevel, UvRect::FULL); b.finish("Box") } /// The cube primitive (sharp edges). pub fn cube(size: f32) -> Mesh { - try_cube(size, &Limits::default()).unwrap_or_else(|_| empty("Cube")) -} - -/// [`cube`] with its size checked. -pub fn try_cube(size: f32, limits: &Limits) -> Result { - let mut m = try_rounded_box(Vec3::splat(positive("cube size", size)? * 0.5), 0.0, limits)?; + let mut m = rounded_box(Vec3::splat(size * 0.5), 0.0); m.materials = vec!["Cube".into()]; if let Some(s) = m.submeshes.first_mut() { s.name = "Cube".into(); } - Ok(m) + m } fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: UvRect) { @@ -239,7 +132,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv (Vec3::Y, Vec3::X, Vec3::Z), (-Vec3::Y, Vec3::X, -Vec3::Z), ]; - let (kb, kc) = box_segments(bevel); + let (kb, kc) = if bevel > 0.0 { (6usize, 10usize) } else { (0, 12) }; // Coordinates along one face axis from -h to h, dense in the bevels. let coords = |h: f32| -> Vec { let inner = h - bevel; @@ -265,9 +158,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv let (a, c) = (cu[j], cv[i]); let q = *n * hn + *u * a + *v * c; let clamped = q.clamp(-inner, inner); - // `unit` gives the same direction where the squared offset overflows, so faces that - // share a bevel edge place its vertices at the same positions. - let dir = unit(q - clamped).unwrap_or(*n); + let dir = (q - clamped).try_normalize().unwrap_or(*n); let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; let nn = if bevel > 0.0 { dir } else { *n }; (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) @@ -281,30 +172,26 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize if profile.len() < 2 { return; } - // Arc lengths and profile directions in `f64`, where the steps between finite `f32` points - // and their squares neither overflow nor round to zero, whatever the radius and height. - let point = |(r, y): (f32, f32)| DVec2::new(f64::from(r), f64::from(y)); - let mut len = vec![0.0f64]; + let mut len = vec![0.0f32]; for w in profile.windows(2) { - let d = (point(w[1]) - point(w[0])).length(); + let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length(); len.push(len.last().copied().unwrap_or(0.0) + d); } - // A profile of zero length maps every row to the top of `r`. - let total = len.last().copied().filter(|t| *t > 0.0 && t.is_finite()).unwrap_or(1.0); + let total = len.last().copied().unwrap_or(1.0).max(1e-6); let rows = profile.len() - 1; b.grid(rows, segs, |i, j| { let (rad, y) = profile[i]; // Profile tangent (downwards) → outward normal in the (r, y) plane. let prev = profile[i.saturating_sub(1)]; let next = profile[(i + 1).min(rows)]; - let t = (point(next) - point(prev)).try_normalize().map_or(Vec2::NEG_Y, |t| t.as_vec2()); + let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); let n2 = Vec2::new(-t.y, t.x); let u = j as f32 / segs as f32; let phi = u * TAU + PI * 1.5; let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); let p = center + dir * rad + Vec3::Y * y; let n = dir * n2.x + Vec3::Y * n2.y; - (p, n, r.map(u, (len[i] / total) as f32)) + (p, n, r.map(u, len[i] / total)) }); } @@ -349,7 +236,7 @@ pub fn preview_orb() -> Mesh { profile.push((0.0, -BASE_HALF_HEIGHT)); lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); - let Ok(mut m) = b.into_mesh("Preview") else { return empty("Preview") }; + let mut m = b.into_mesh("Preview"); // Normals from the triangles: the panel walls are too steep for the sphere's directions m.compute_normals(); // Body and base both run U around the vertical axis, so the tangent is that direction (a @@ -366,7 +253,7 @@ pub fn preview_orb() -> Mesh { m } -/// Distance from the center of the [`preview_orb`] body along unit direction `d`. +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. fn preview_orb_radius(d: Vec3) -> f32 { // Rim blends: the sharp faces, and the softly blended left face const SHARP_BLEND: f32 = 0.035; @@ -375,7 +262,7 @@ fn preview_orb_radius(d: Vec3) -> f32 { const PANEL_DEPTH: f32 = 0.11; const PANEL_BULGE: f32 = 0.04; const LEFT_PANEL_SCALE: f32 = 0.9; - // Slot around the middle: center height, half-width, edge rounding, depth; it fades out over + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over // this fraction of the left panel's rim const SLOT_Y: f32 = -0.03; const SLOT_HALF_WIDTH: f32 = 0.05; @@ -437,9 +324,6 @@ fn preview_orb_radius(d: Vec3) -> f32 { /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { - if !b.room(segs.checked_add(1), Some(segs)) { - return; - } let n = if up { Vec3::Y } else { Vec3::NEG_Y }; let c = b.vert(center, n, r.map(0.5, 0.5)); let first = b.p.len() as u32; @@ -463,31 +347,18 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, /// A capped cylinder along Y. pub fn cylinder(radius: f32, height: f32, segs: usize) -> Mesh { - try_cylinder(radius, height, clamped(segs), &Limits::default()).unwrap_or_else(|_| empty("Cylinder")) -} - -/// [`cylinder`] with its parameters checked. -pub fn try_cylinder(radius: f32, height: f32, segs: usize, limits: &Limits) -> Result { - let (radius, height) = (positive("cylinder radius", radius)?, positive("cylinder height", height)?); - let segs = segments("cylinder segments", segs, 3, limits)?; - let mut b = Builder::new(limits); + let mut b = Builder::default(); let h = height * 0.5; - lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); - disk_into(&mut b, Vec3::Y * h, radius, true, segs, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); - disk_into(&mut b, -Vec3::Y * h, radius, false, segs, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + lathe_into(&mut b, Vec3::ZERO, &[(radius, h), (radius, -h)], segs.max(3), UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); + disk_into(&mut b, Vec3::Y * h, radius, true, segs.max(3), UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); + disk_into(&mut b, -Vec3::Y * h, radius, false, segs.max(3), UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); b.finish("Cylinder") } /// A torus around Y. pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { - try_torus(major, minor, clamped(segs), clamped(sides), &Limits::default()).unwrap_or_else(|_| empty("Torus")) -} - -/// [`torus`] with its parameters checked. -pub fn try_torus(major: f32, minor: f32, segs: usize, sides: usize, limits: &Limits) -> Result { - let (major, minor) = (positive("torus major radius", major)?, positive("torus minor radius", minor)?); - let (segs, sides) = (segments("torus segments", segs, 3, limits)?, segments("torus sides", sides, 3, limits)?); - let mut b = Builder::new(limits); + let mut b = Builder::default(); + let (segs, sides) = (segs.max(3), sides.max(3)); b.grid(sides, segs, |i, j| { let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); let phi = u * TAU + PI * 1.5; @@ -501,14 +372,8 @@ pub fn try_torus(major: f32, minor: f32, segs: usize, sides: usize, limits: &Lim /// A subdivided plane facing +Y. pub fn plane(size: f32, subdivisions: usize) -> Mesh { - try_plane(size, clamped(subdivisions), &Limits::default()).unwrap_or_else(|_| empty("Plane")) -} - -/// [`plane`] with its parameters checked. -pub fn try_plane(size: f32, subdivisions: usize, limits: &Limits) -> Result { - let size = positive("plane size", size)?; - let s = segments("plane subdivisions", subdivisions, 1, limits)?; - let mut b = Builder::new(limits); + let mut b = Builder::default(); + let s = subdivisions.max(1); b.grid(s, s, |i, j| { let (u, v) = (j as f32 / s as f32, i as f32 / s as f32); (Vec3::new((u - 0.5) * size, 0.0, (v - 0.5) * size), Vec3::Y, Vec2::new(u, v)) @@ -543,7 +408,7 @@ pub fn udim_plane() -> Mesh { pub fn material_ball() -> Mesh { let mut ball = Builder::default(); sphere_into(&mut ball, Vec3::new(0.0, 1.32, 0.0), 1.0, 128, 64, UvRect::FULL); - let Ok(mut ball) = ball.finish("Ball") else { return empty("Ball") }; + let mut ball = ball.finish("Ball"); let mut base = Builder::default(); let (r, top, bot, bev) = (1.05f32, 0.32f32, 0.0f32, 0.07f32); @@ -566,7 +431,7 @@ pub fn material_ball() -> Mesh { lathe_into(&mut base, Vec3::ZERO, &profile, 128, UvRect { o: Vec2::ZERO, s: Vec2::new(1.0, 0.5) }.inset(0.01)); disk_into(&mut base, Vec3::new(0.0, top + 0.06, 0.0), 0.42, true, 128, UvRect { o: Vec2::new(0.0, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); disk_into(&mut base, Vec3::new(0.0, bot, 0.0), r - bev, false, 128, UvRect { o: Vec2::new(0.5, 0.5), s: Vec2::splat(0.5) }.inset(0.01)); - let Ok(base) = base.finish("Base") else { return ball }; + let base = base.finish("Base"); ball.append(&base); ball } @@ -576,12 +441,10 @@ pub fn material_ball() -> Mesh { pub fn crate_scene() -> Mesh { let mut body = Builder::default(); rounded_box_into(&mut body, Vec3::new(0.0, 0.8, 0.0), Vec3::new(1.2, 0.8, 0.8), 0.12, UvRect::FULL); - let Ok(mut m) = body.finish("Crate") else { return empty("Crate") }; + let mut m = body.finish("Crate"); let mut lid = Builder::default(); rounded_box_into(&mut lid, Vec3::new(0.0, 1.72, 0.0), Vec3::new(1.28, 0.12, 0.88), 0.08, UvRect::FULL); - if let Ok(lid) = lid.finish("Lid") { - m.append(&lid); - } + m.append(&lid.finish("Lid")); let mut handle = torus(0.32, 0.07, 64, 24); for p in &mut handle.positions { *p = Vec3::new(p.x, p.z, -p.y) + Vec3::new(0.0, 1.84, 0.0); @@ -665,7 +528,7 @@ mod tests { check(&m, if id == "udim_plane" { 2.0 } else { 1.0 }); } assert!(builtin("nope").is_none()); - assert_eq!(udim_plane().uv_tiles(0, &Limits::default()).unwrap().into_iter().collect::>(), vec![(0, 0), (1, 0)]); + assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } #[test] @@ -690,174 +553,4 @@ mod tests { assert_eq!(m.materials, vec!["Ball".to_string(), "Base".to_string()]); assert!(m.triangles_of(0).count() > 0 && m.triangles_of(1).count() > 0); } - - #[test] - fn primitives_reject_non_finite_parameters() { - let l = Limits::default(); - for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert!(try_sphere(bad, 16, 8, &l).is_err(), "sphere {bad}"); - assert!(try_rounded_box(Vec3::new(1.0, bad, 1.0), 0.1, &l).is_err(), "box {bad}"); - assert!(try_rounded_box(Vec3::ONE, bad, &l).is_err(), "bevel {bad}"); - assert!(try_cube(bad, &l).is_err(), "cube {bad}"); - assert!(try_cylinder(bad, 1.0, 16, &l).is_err() && try_cylinder(1.0, bad, 16, &l).is_err(), "cylinder {bad}"); - assert!(try_torus(bad, 0.3, 16, 8, &l).is_err() && try_torus(1.0, bad, 16, 8, &l).is_err(), "torus {bad}"); - assert!(try_plane(bad, 4, &l).is_err(), "plane {bad}"); - for m in [sphere(bad, 16, 8), cube(bad), cylinder(1.0, bad, 16), torus(bad, 0.3, 16, 8), plane(bad, 4)] { - assert_eq!(m.triangle_count(), 0); - m.validate().unwrap(); - } - } - } - - #[test] - fn box_rejects_negative_nan_and_zero_half_size() { - let l = Limits::default(); - for half in [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, 1.0, f32::NAN), Vec3::ZERO, Vec3::new(1.0, 0.0, 1.0)] { - assert!(try_rounded_box(half, 0.0, &l).is_err(), "{half}"); - assert!(try_rounded_box(half, 0.2, &l).is_err(), "{half}"); - let m = rounded_box(half, 0.2); - assert_eq!(m.triangle_count(), 0, "{half}"); - } - for size in [-2.0, 0.0] { - assert!(try_cube(size, &l).is_err(), "{size}"); - assert!(cube(size).uvs.iter().all(|uv| uv.is_finite())); - } - // A negative bevel is clamped to none, as before. - assert_eq!(try_rounded_box(Vec3::ONE, -1.0, &l).unwrap(), try_rounded_box(Vec3::ONE, 0.0, &l).unwrap()); - } - - #[test] - fn primitives_reject_sizes_that_overflow() { - let l = Limits::default(); - // The torus's two radii and the box's doubled half size pass f32::MAX. - assert!(try_torus(3e38, 3e38, 16, 8, &l).is_err()); - assert!(try_rounded_box(Vec3::splat(3e38), 0.0, &l).is_err()); - assert_eq!(torus(3e38, 3e38, 16, 8).triangle_count(), 0); - // The cylinder's profile length is measured on the divided profile, so a height whose - // length alone would pass f32::MAX builds. - let tall = try_cylinder(1.0, 3e38, 16, &l).unwrap(); - tall.validate().unwrap(); - assert!(tall.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); - // Large sizes that stay finite build. - let large = [ - try_sphere(1e30, 16, 8, &l).unwrap(), - try_cylinder(1e18, 1e18, 16, &l).unwrap(), - try_cube(1e30, &l).unwrap(), - try_torus(1e30, 1e29, 16, 8, &l).unwrap(), - try_plane(1e30, 4, &l).unwrap(), - ]; - for m in large { - assert!(m.triangle_count() > 0); - m.validate().unwrap(); - } - } - - #[test] - fn a_scaled_primitive_is_the_unit_primitive_scaled() { - let l = Limits::default(); - let close = |a: &Mesh, b: &Mesh, scale: f32| { - assert_eq!(a.positions.len(), b.positions.len()); - for (i, (p, q)) in a.positions.iter().zip(&b.positions).enumerate() { - assert!((*p / scale - *q).length() < 1e-5, "position {i}: {} vs {q}", *p / scale); - } - for (i, (u, v)) in a.uvs.iter().zip(&b.uvs).enumerate() { - assert!((*u - *v).length() < 1e-5, "UV {i}: {u} vs {v}"); - } - }; - // Squared bevel offsets overflow at this size: adjacent faces still meet. - close(&try_rounded_box(Vec3::splat(1e30), 1e29, &l).unwrap(), &try_rounded_box(Vec3::ONE, 0.1, &l).unwrap(), 1e30); - // A profile far shorter than 1e-6 keeps its share of the UV height. - close(&try_cylinder(1e-8, 1e-8, 16, &l).unwrap(), &try_cylinder(1.0, 1.0, 16, &l).unwrap(), 1e-8); - close(&try_cylinder(1e-30, 2e-30, 16, &l).unwrap(), &try_cylinder(1.0, 2.0, 16, &l).unwrap(), 1e-30); - } - - #[test] - fn primitives_reject_oversized_segment_counts() { - let l = Limits::default(); - assert!(try_sphere(1.0, l.max_segments + 1, 8, &l).is_err()); - assert!(try_sphere(1.0, 8, usize::MAX, &l).is_err()); - assert!(try_torus(1.0, 0.3, usize::MAX, 8, &l).is_err()); - assert!(try_cylinder(1.0, 1.0, usize::MAX, &l).is_err()); - assert!(try_plane(1.0, usize::MAX, &l).is_err()); - // Within the segment limit, the vertex limit still applies. - let few = Limits { max_vertices: 100, ..l }; - assert!(matches!(try_plane(1.0, 10, &few), Err(MeshOpsError::TooLarge { .. }))); - assert!(try_plane(1.0, 8, &few).is_ok()); - // A count under the builder's minimum is raised first, and the raised count is checked. - let two = Limits { max_segments: 2, ..l }; - assert!(try_sphere(1.0, 1, 2, &two).is_err(), "a sphere has at least 3 segments"); - assert!(try_plane(1.0, 0, &two).is_ok()); - // A box face has 12 segments along each axis, or 22 with a bevel. - let eleven = Limits { max_segments: 11, ..l }; - assert!(try_cube(1.0, &eleven).is_err()); - let twelve = Limits { max_segments: 12, ..l }; - assert!(try_cube(1.0, &twelve).is_ok()); - assert!(try_rounded_box(Vec3::ONE, 0.1, &twelve).is_err()); - // The builders without `try_` clamp to the limit. - assert_eq!(clamped(usize::MAX), l.max_segments); - assert_eq!(clamped(7), 7); - } - - #[test] - fn vertex_copies_from_tangents_count_against_the_vertex_limit() { - // A quad whose second triangle has mirrored UVs: the two shared vertices get one frame - // per triangle, so the tangents copy them. - let quad = |max_vertices: usize| { - let mut b = Builder::new(&Limits { max_vertices, ..Limits::default() }); - assert!(b.room(Some(4), Some(2))); - for (p, uv) in [(Vec3::ZERO, Vec2::ZERO), (Vec3::X, Vec2::X), (Vec3::Y, Vec2::Y), (Vec3::new(1.0, 1.0, 0.0), Vec2::ZERO)] { - b.vert(p, Vec3::Z, uv); - } - b.idx.extend_from_slice(&[0, 1, 2, 1, 3, 2]); - b.diag.extend_from_slice(&[0, 0]); - b.finish("Quad") - }; - let m = quad(usize::MAX).unwrap(); - let copies = m.positions.len() - 4; - assert!(copies > 0, "the mirrored triangle's corners get their own vertices"); - // The error comes at the first copy past the limit, before any later copy is made. - assert!(matches!(quad(4), Err(MeshOpsError::TooLarge { what: "vertex count", got: 5, limit: 4 }))); - let under = m.positions.len() - 1; - assert!( - matches!(quad(under), Err(MeshOpsError::TooLarge { what: "vertex count", got, limit }) if got == m.positions.len() as u64 && limit == under as u64) - ); - assert_eq!(quad(m.positions.len()).unwrap().positions.len(), m.positions.len()); - } - - #[test] - fn primitives_count_the_vertices_tangents_split() { - type Build = fn(&Limits) -> Result; - // A torus whose minor radius is larger than its major radius folds through its axis. - let builds: [(&str, Build); 6] = [ - ("folded torus", |l| try_torus(0.5, 2.0, 16, 8, l)), - ("torus", |l| try_torus(1.0, 0.3, 16, 8, l)), - ("sphere", |l| try_sphere(1.0, 16, 8, l)), - ("cylinder", |l| try_cylinder(1.0, 2.0, 16, l)), - ("rounded box", |l| try_rounded_box(Vec3::ONE, 0.2, l)), - ("plane", |l| try_plane(1.0, 4, l)), - ]; - let l = Limits::default(); - for (name, build) in builds { - let full = build(&l).unwrap().vertex_count(); - let under = Limits { max_vertices: full - 1, ..l }; - match build(&under) { - Ok(m) => panic!("{name}: {} vertices with a limit of {}", m.vertex_count(), full - 1), - Err(e) => assert!(matches!(e, MeshOpsError::TooLarge { what: "vertex count", .. }), "{name}: {e:?}"), - } - assert_eq!(build(&Limits { max_vertices: full, ..l }).unwrap().vertex_count(), full, "{name}"); - } - } - - #[test] - fn lathe_uvs_span_the_rectangle_at_any_radius_and_height() { - // With the radius 1e30 times the height, the profile step divided by the radius squares to - // zero in f32. - for (radius, height) in [(1e30f32, 1.0f32), (1.0, 1e30), (1e-30, 1.0)] { - let m = try_cylinder(radius, height, 16, &Limits::default()).unwrap(); - // The side is the first grid: 17 vertices on the top row, 17 on the bottom one. - let (top, bottom) = (&m.uvs[..17], &m.uvs[17..34]); - assert!(top.iter().all(|uv| (uv.y - 0.01).abs() < 1e-6), "{radius} {height}: {top:?}"); - assert!(bottom.iter().all(|uv| (uv.y - 0.49).abs() < 1e-6), "{radius} {height}: {bottom:?}"); - } - } } diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index e95d1aa2dd..2f2eafc0a0 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -8,49 +8,29 @@ use std::collections::{HashMap, VecDeque}; -use glam::{DVec2, DVec3, Vec2, Vec3}; +use glam::{Vec2, Vec3}; -use crate::{Limits, Mesh, MeshOpsError, Result, check_limit, reserved, try_filled, try_vec}; +use crate::{GeomError, Mesh, Result}; /// Faces of a chart stay within this angle of the seed face normal (cos 60°). const CHART_COS: f32 = 0.5; /// Packing never goes beyond this virtual resolution (texels per side). const MAX_PACK_RES: f32 = 65_536.0; -/// Bounds within this magnitude, with a diagonal of at least [`PLAIN_WELD_DIAGONAL`], are welded -/// in `f32`. Larger and smaller ones are welded in `f64`, where the diagonal and the grid cell -/// neither overflow nor round to zero. -const PLAIN_WELD_MAGNITUDE: f32 = 1e9; -const PLAIN_WELD_DIAGONAL: f32 = 1e-6; /// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of -/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. The grid -/// comes from the finite positions only. The id list and the lookup table are reserved up front, -/// and a reservation that fails is [`MeshOpsError::OutOfMemory`]. -pub fn weld_ids(positions: &[Vec3]) -> Result> { - let (lo, hi) = positions - .iter() - .filter(|p| p.is_finite()) - .fold(None, |b: Option<(Vec3, Vec3)>, p| Some(b.map_or((*p, *p), |(lo, hi)| (lo.min(*p), hi.max(*p))))) - .unwrap_or((Vec3::ZERO, Vec3::ZERO)); - let plain = lo.abs().max(hi.abs()).max_element() <= PLAIN_WELD_MAGNITUDE && (lo == hi || (hi - lo).length() >= PLAIN_WELD_DIAGONAL); +/// the bounding diagonal) share an id. Ids are dense, in order of first appearance. +pub fn weld_ids(positions: &[Vec3]) -> Vec { + let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); let cell = ((hi - lo).length() * 1e-6).max(1e-12); - let (wide_lo, wide_cell) = (lo.as_dvec3(), (hi.as_dvec3() - lo.as_dvec3()).length() * 1e-6); - let mut map: HashMap<[i64; 3], u32> = HashMap::new(); - reserved(map.try_reserve(positions.len()), "welded vertex table")?; - let mut ids = try_vec(positions.len(), "welded vertex ids")?; - ids.extend(positions.iter().map(|p| { - let key = if plain { + let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); + positions + .iter() + .map(|p| { let q = ((*p - lo) / cell).round(); - [q.x as i64, q.y as i64, q.z as i64] - } else { - // A zero cell (every finite position the same) divides 0 by 0; NaN casts to 0. - let q = ((p.as_dvec3() - wide_lo) / wide_cell).round(); - [q.x as i64, q.y as i64, q.z as i64] - }; - let next = map.len() as u32; - *map.entry(key).or_insert(next) - })); - Ok(ids) + let next = map.len() as u32; + *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) + }) + .collect() } /// True when the mesh has triangles and every one of them has two corners at the same position. @@ -66,292 +46,64 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { struct Chart { material: usize, - /// The seed face's first corner: projections are taken relative to it, in `f64`, so they - /// keep the chart's own detail wherever the chart lies. - origin: DVec3, /// Projection basis (right-handed with the seed normal). - t: DVec3, - b: DVec3, + t: Vec3, + b: Vec3, /// Rotation to the chart's principal axes (cos, sin). - rot: DVec2, - /// Bounds of the rotated chart. Charts are measured and packed in `f64`, where the extent of - /// any chart of finite `f32` positions and the scale that packs it neither overflow nor round - /// to zero. - lo: DVec2, - hi: DVec2, - /// Texel offset of the chart's packed rectangle. - offset: DVec2, + rot: Vec2, + lo: Vec2, + hi: Vec2, + /// Texel offset of the chart's packed rectangle and the material's scale and resolution. + offset: Vec2, } impl Chart { - fn local(&self, p: Vec3) -> DVec2 { - let d = p.as_dvec3() - self.origin; - let q = DVec2::new(d.dot(self.t), d.dot(self.b)); - DVec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + fn local(&self, p: Vec3) -> Vec2 { + let q = Vec2::new(p.dot(self.t), p.dot(self.b)); + Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) } - fn size(&self) -> DVec2 { - (self.hi - self.lo).max(DVec2::ZERO) + fn size(&self) -> Vec2 { + (self.hi - self.lo).max(Vec2::ZERO) } } -/// A face whose projected bounds cover more grid cells than this is compared with every face of -/// the chart instead of being entered in the grid. -const MAX_GRID_CELLS: i64 = 64; -/// Face pairs the overlap test may compare: this many per input face, plus [`OVERLAP_PAIRS_BASE`]. -/// Once they are used up, a face joins no chart but its own, which keeps the layout free of -/// overlaps at the cost of more charts. -const OVERLAP_PAIRS_PER_FACE: usize = 256; -const OVERLAP_PAIRS_BASE: usize = 1 << 20; - -/// A face projected onto its chart's plane, in `f64`: corners that are equal in `f32` project to -/// equal points, and the rounding of a projection stays far below the spacing of `f32` input. -type Flat = [DVec2; 3]; - -/// The overlap test of the chart being grown: a grid of square cells, each listing the faces -/// whose projected bounds touch it. The cell side is the median longest edge of the mesh's -/// faces. -struct Overlap { - cell: f64, - grid: HashMap<(i64, i64), Vec>, - /// The projection of each face, set when the face is added to its chart. - projected: Vec, - /// Faces of the current chart, and those of them that are not in the grid. - members: Vec, - large: Vec, - pairs_left: usize, -} - -impl Overlap { - /// The test for a mesh of `n` faces whose corners `corners` gives. - fn new(n: usize, corners: impl Fn(usize) -> [Vec3; 3]) -> Result { - let mut longest = try_vec(n, "UV charts")?; - for t in 0..n { - let [a, b, c] = corners(t).map(|p| p.as_dvec3()); - let l = (b - a).length().max((c - b).length()).max((a - c).length()); - if l > 0.0 && l.is_finite() { - longest.push(l); - } - } - let middle = longest.len() / 2; - let cell = if longest.is_empty() { 1.0 } else { *longest.select_nth_unstable_by(middle, f64::total_cmp).1 }; - Ok(Overlap { - cell, - grid: HashMap::new(), - projected: try_filled(n, [DVec2::ZERO; 3], "UV charts")?, - members: Vec::new(), - large: Vec::new(), - pairs_left: OVERLAP_PAIRS_BASE.saturating_add(n.saturating_mul(OVERLAP_PAIRS_PER_FACE)), - }) - } - - /// Empty the grid for the next chart. A large grid is dropped rather than cleared, so that - /// many small charts after one large one do not each pay for its capacity. - fn start_chart(&mut self) { - if self.grid.capacity() > 4096 { - self.grid = HashMap::new(); - } else { - self.grid.clear(); - } - self.members.clear(); - self.large.clear(); - } - - /// Whether the projected face has an interior. One without area cannot cover a texel that - /// another face covers. - fn has_area(tri: &Flat) -> bool { - height(tri) > 0.0 - } - - /// The grid cells the projected bounds cover: first and last column and row. - fn cells(&self, tri: &Flat) -> [i64; 4] { - let (lo, hi) = (tri[0].min(tri[1]).min(tri[2]), tri[0].max(tri[1]).max(tri[2])); - // `as` saturates, so far-away bounds give the extreme cells. - [(lo.x / self.cell).floor() as i64, (lo.y / self.cell).floor() as i64, (hi.x / self.cell).floor() as i64, (hi.y / self.cell).floor() as i64] - } - - fn cell_count([x0, y0, x1, y1]: [i64; 4]) -> i64 { - x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1)) - } - - /// Whether a face with this projection can join the current chart: its interior overlaps - /// none of the chart's faces. False when the comparisons allowed are used up. - fn fits(&mut self, tri: &Flat) -> bool { - if !Self::has_area(tri) { - return true; - } - let cells = self.cells(tri); - let (projected, pairs_left) = (&self.projected, &mut self.pairs_left); - let mut clear = |ids: &[u32]| { - ids.iter().all(|&id| { - if *pairs_left == 0 { - return false; - } - *pairs_left -= 1; - projected.get(id as usize).is_none_or(|other| !interiors_overlap(tri, other)) - }) - }; - if Self::cell_count(cells) > MAX_GRID_CELLS { - return clear(&self.members); - } - let [x0, y0, x1, y1] = cells; - if !clear(&self.large) { - return false; - } - for x in x0..=x1 { - for y in y0..=y1 { - if let Some(ids) = self.grid.get(&(x, y)) - && !clear(ids) - { - return false; - } - } - } - true - } - - /// Add face `face` with this projection to the current chart. - fn add(&mut self, face: usize, tri: Flat) -> Result<()> { - if let Some(slot) = self.projected.get_mut(face) { - *slot = tri; - } - if !Self::has_area(&tri) { - return Ok(()); - } - let id = face as u32; - reserved(self.members.try_reserve(1), "UV charts")?; - self.members.push(id); - let cells = self.cells(&tri); - if Self::cell_count(cells) > MAX_GRID_CELLS { - reserved(self.large.try_reserve(1), "UV charts")?; - self.large.push(id); - return Ok(()); - } - let [x0, y0, x1, y1] = cells; - for x in x0..=x1 { - for y in y0..=y1 { - if !self.grid.contains_key(&(x, y)) { - reserved(self.grid.try_reserve(1), "UV charts")?; - } - let ids = self.grid.entry((x, y)).or_default(); - reserved(ids.try_reserve(1), "UV charts")?; - ids.push(id); - } - } - Ok(()) - } -} - -/// The smallest height of a triangle: twice its area over its longest edge. 0 for a triangle -/// without area. -fn height(t: &Flat) -> f64 { - let longest = (t[1] - t[0]).length().max((t[2] - t[1]).length()).max((t[0] - t[2]).length()); - let twice_area = (t[1] - t[0]).perp_dot(t[2] - t[0]).abs(); - if longest > 0.0 { twice_area / longest } else { 0.0 } -} - -/// Whether the interiors of two triangles in a plane overlap: no edge direction of either -/// separates them (separating axis test). Projections that overlap by no more than a tolerance -/// only touch, as faces that share an edge or a corner do: 1e-5 of the smaller of the two -/// triangles' heights, so a thin triangle's own width counts, plus the `f64` rounding of -/// coordinates of their magnitude. -fn interiors_overlap(a: &Flat, b: &Flat) -> bool { - let magnitude = a.iter().chain(b).map(|p| p.abs().max_element()).fold(0.0f64, f64::max); - let tol = 1e-5 * height(a).min(height(b)) + 8.0 * f64::EPSILON * magnitude; - let span = |t: &Flat, axis: DVec2| t.iter().fold((f64::MAX, f64::MIN), |(lo, hi), p| (lo.min(p.dot(axis)), hi.max(p.dot(axis)))); - for tri in [a, b] { - for k in 0..3 { - let Some(axis) = (tri[(k + 1) % 3] - tri[k]).perp().try_normalize() else { continue }; - let ((a_lo, a_hi), (b_lo, b_hi)) = (span(a, axis), span(b, axis)); - if a_hi <= b_lo + tol || b_hi <= a_lo + tol { - return false; - } - } - } - true -} - /// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its -/// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away -/// from each other and the borders at `resolution`. Vertices are split at chart borders; -/// tangents are recomputed. -/// Returns the number of charts. A mesh that fails the checks (indices, submesh ranges and -/// materials, no triangle in submeshes of two materials, finite positions, finite normals and -/// colors when it has them, at least one -/// triangle that is not degenerate, and the default [`Limits`] that [`unwrap_core`] applies) is -/// left unchanged, as is one whose layout runs out of memory; running out of memory for the -/// tangents comes after the new layout is in place. +/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and +/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed. +/// Returns the number of charts. pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { - let (charts, _) = unwrap_core(mesh, padding_texels, resolution, &Limits::default())?; - mesh.try_compute_tangents()?; - mesh.validate()?; - Ok(charts) -} - -/// [`auto_unwrap`] without the tangents and the final check: returns the chart count and, per -/// new vertex, the old vertex it copies. The input's vertices over [`Limits::max_vertices`], its -/// triangles over [`Limits::max_unwrap_triangles`], or the triangles its submeshes list (a -/// triangle in two submeshes counts twice) over the same limit, are an error before any work. -/// More than `max_vertices` new vertices is an error too; the rebuilt arrays stop growing at -/// most three vertices past it. -pub(crate) fn unwrap_core(mesh: &mut Mesh, padding_texels: f32, resolution: u32, limits: &Limits) -> Result<(usize, Vec)> { - check_limit("vertex count", mesh.positions.len(), limits.max_vertices)?; - check_limit("triangle count", mesh.triangle_count(), limits.max_unwrap_triangles)?; - let listed = mesh.submeshes.iter().fold(0u64, |sum, s| sum.saturating_add(u64::from(s.count / 3))); - if listed > limits.max_unwrap_triangles as u64 { - return Err(MeshOpsError::TooLarge { what: "submesh triangle count", got: listed, limit: limits.max_unwrap_triangles as u64 }); - } mesh.validate_indices()?; - if mesh.positions.iter().any(|p| !p.is_finite()) { - return Err(MeshOpsError::Invalid("mesh has non-finite positions".into())); - } if all_triangles_degenerate(mesh) { - return Err(MeshOpsError::Invalid("every triangle of the mesh is degenerate".into())); + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } + if mesh.normals.len() != mesh.positions.len() { + mesh.compute_normals(); } - // Kept apart from the mesh until the layout is packed, so an error leaves the mesh as it was. - let computed_normals = if mesh.normals.len() != mesh.positions.len() { Some(mesh.smooth_normals()?) } else { None }; - let old_normals = computed_normals.as_deref().unwrap_or(&mesh.normals); let n = mesh.triangle_count(); - let weld = weld_ids(&mesh.positions)?; - let original = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); + let weld = weld_ids(&mesh.positions); + let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); - // Face normals (None for degenerate faces) and materials. The cross products are taken in - // `f64` from the positions as given, where they neither overflow nor round to zero, so a - // small face far from the origin keeps its plane. - let mut normal: Vec> = try_vec(n, "unwrap faces")?; - let mut area = try_vec(n, "unwrap faces")?; + // Face normals (None for degenerate faces) and materials. + let mut normal: Vec> = Vec::with_capacity(n); + let mut area = Vec::with_capacity(n); for t in 0..n { - let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]).map(|v| original(v).as_dvec3()); - let cr = (b - a).cross(c - a); + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); + let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a)); area.push(cr.length() * 0.5); - normal.push(cr.try_normalize().map(|n| n.as_vec3())); + normal.push(cr.try_normalize()); } - // Each material is packed into its own 0..1 square, so a triangle that submeshes of two - // materials list would be laid out over another chart of one of them. Triangles no submesh - // lists get material 0. - let mut material = try_filled(n, usize::MAX, "unwrap faces")?; + let mut material = vec![0usize; n]; for s in &mesh.submeshes { - // Checked by validate_indices: whole triangles inside the index buffer. - let end = (u64::from(s.start) + u64::from(s.count)) / 3; - for t in (s.start / 3) as usize..(end as usize).min(n) { + for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) { if let Some(m) = material.get_mut(t) { - if *m != usize::MAX && *m != s.material { - return Err(MeshOpsError::Invalid(format!("triangle {t} is in submeshes of materials {} and {}", *m, s.material))); - } *m = s.material; } } } - for m in &mut material { - if *m == usize::MAX { - *m = 0; - } - } - // Manifold edge adjacency over welded vertices: edge → (face, face, count). There are at - // most three edges per face, so the map does not grow past what is reserved here. - let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::new(); - reserved(edges.try_reserve(n.saturating_mul(3)), "unwrap edges")?; + // Manifold edge adjacency over welded vertices: edge → (face, face, count). + let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); let tri_edges = |t: usize| -> [(u32, u32); 3] { let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); let key = |x: usize, y: usize| { @@ -373,40 +125,65 @@ pub(crate) fn unwrap_core(mesh: &mut Mesh, padding_texels: f32, resolution: u32, } } - let faces = Faces { normal: &normal, area: &area, material: &material, edges: &edges }; - let corners = |f: usize| mesh.tri(f).unwrap_or([0; 3]).map(original); - let (chart_of, mut charts) = grow_charts(&faces, tri_edges, corners)?; + // Grow charts from the largest unassigned faces. + let mut order: Vec = (0..n).collect(); + order.sort_by(|a, b| area[*b].total_cmp(&area[*a])); + let mut chart_of = vec![u32::MAX; n]; + let mut charts: Vec = Vec::new(); + let mut queue = VecDeque::new(); + for &seed in &order { + if chart_of[seed] != u32::MAX { + continue; + } + let id = charts.len() as u32; + let sn = normal[seed].unwrap_or(Vec3::Z); + let t = sn.any_orthonormal_vector(); + charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO }); + chart_of[seed] = id; + queue.push_back(seed); + while let Some(f) = queue.pop_front() { + for e in tri_edges(f) { + let Some(&(f0, f1, 2)) = edges.get(&e) else { continue }; + let g = if f0 as usize == f { f1 } else { f0 } as usize; + let ok = normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); + if ok && chart_of.get(g) == Some(&u32::MAX) && material.get(g) == Some(&material[seed]) { + chart_of[g] = id; + queue.push_back(g); + } + } + } + } - // Principal axes and bounds of every chart, in f64 from the positions as given. - let mut cov = try_filled(charts.len(), (DVec2::ZERO, [0.0f64; 3], 0usize), "unwrap charts")?; + // Principal axes and bounds of every chart. + let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; for (t, &c) in chart_of.iter().enumerate() { let c = c as usize; for v in mesh.tri(t).unwrap_or([0; 3]) { if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { - let q = ch.local(original(v)); + let q = ch.local(pos(v)); acc.0 += q; - acc.1[0] += q.x * q.x; - acc.1[1] += q.y * q.y; - acc.1[2] += q.x * q.y; + acc.1[0] += (q.x * q.x) as f64; + acc.1[1] += (q.y * q.y) as f64; + acc.1[2] += (q.x * q.y) as f64; acc.2 += 1; } } } for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { let k = (*k).max(1) as f64; - let (mx, my) = (sum.x / k, sum.y / k); + let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k); let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); // Rotate so the principal axis lies along x. - ch.rot = DVec2::new((-angle).cos(), (-angle).sin()); - ch.lo = DVec2::splat(f64::MAX); - ch.hi = DVec2::splat(f64::MIN); + ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32); + ch.lo = Vec2::splat(f32::MAX); + ch.hi = Vec2::splat(f32::MIN); } for (t, &c) in chart_of.iter().enumerate() { let c = c as usize; for v in mesh.tri(t).unwrap_or([0; 3]) { if let Some(ch) = charts.get_mut(c) { - let q = ch.local(original(v)); + let q = ch.local(pos(v)); ch.lo = ch.lo.min(q); ch.hi = ch.hi.max(q); } @@ -415,172 +192,74 @@ pub(crate) fn unwrap_core(mesh: &mut Mesh, padding_texels: f32, resolution: u32, for ch in &mut charts { if ch.size().y > ch.size().x { // Quarter turn (x, y) → (y, −x) so shelves stay low. - ch.rot = DVec2::new(ch.rot.y, -ch.rot.x); + ch.rot = Vec2::new(ch.rot.y, -ch.rot.x); let (lo, hi) = (ch.lo, ch.hi); - ch.lo = DVec2::new(lo.y, -hi.x); - ch.hi = DVec2::new(hi.y, -lo.x); + ch.lo = Vec2::new(lo.y, -hi.x); + ch.hi = Vec2::new(hi.y, -lo.x); } } // Pack each material's charts into its own 0..1 square. let pad = padding_texels.max(1.0); let mut scale = HashMap::new(); - let by_material = charts_by_material(&charts)?; - for group in by_material.chunk_by(|a, b| a.0 == b.0) { - let m = group[0].0; - let mut sizes: Vec = try_vec(group.len(), "unwrap charts")?; - sizes.extend(group.iter().map(|&(_, i)| charts[i].size())); + let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); + for m in mats { + let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; - for (&(_, i), o) in group.iter().zip(offsets) { - charts[i].offset = o; + for (i, o) in ids.iter().zip(offsets) { + charts[*i].offset = o; } - reserved(scale.try_reserve(1), "unwrap charts")?; scale.insert(m, (s, res)); } - // Rebuild vertices: one per (vertex, chart). Each triangle reserves room for its three - // corners before adding them. - let mut remap: HashMap<(u32, u32), u32> = HashMap::new(); - reserved(remap.try_reserve(mesh.positions.len().saturating_mul(2)), "unwrap vertices")?; - let (mut positions, mut normals, mut uvs, mut colors, mut source) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); - let mut indices = try_vec(mesh.indices.len(), "indices")?; + // Rebuild vertices: one per (vertex, chart). + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut indices = Vec::with_capacity(mesh.indices.len()); for (t, &c) in chart_of.iter().enumerate() { let Some(ch) = charts.get(c as usize) else { continue }; - let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0f32)); - let reserve = |r| reserved(r, "unwrap vertices"); - reserve(remap.try_reserve(3))?; - reserve(positions.try_reserve(3))?; - reserve(normals.try_reserve(3))?; - reserve(uvs.try_reserve(3))?; - reserve(if mesh.colors.is_empty() { Ok(()) } else { colors.try_reserve(3) })?; - reserve(source.try_reserve(3))?; + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0)); for v in mesh.tri(t).unwrap_or([0; 3]) { let idx = *remap.entry((v as u32, c)).or_insert_with(|| { - let q = ch.local(original(v)); + let q = ch.local(pos(v)); // Chart y points up; UV v points down the image. - let texel = ch.offset + DVec2::splat(f64::from(pad)) + DVec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; - positions.push(original(v)); - normals.push(old_normals.get(v).copied().unwrap_or(Vec3::Y)); + let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + positions.push(pos(v)); + normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y)); if let Some(c) = mesh.colors.get(v) { colors.push(*c); } - uvs.push((texel / f64::from(res)).as_vec2().clamp(Vec2::ZERO, Vec2::ONE)); - source.push(v as u32); + uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE)); (positions.len() - 1) as u32 }); indices.push(idx); } - check_limit("vertex count", positions.len(), limits.max_vertices)?; } mesh.positions = positions; mesh.normals = normals; mesh.uvs = uvs; mesh.colors = colors; mesh.indices = indices; - Ok((charts.len(), source)) -} - -/// (material, chart id) for every chart, sorted by material and in chart order within each -/// material, so each material's charts are one run. -fn charts_by_material(charts: &[Chart]) -> Result> { - let mut ids = try_vec(charts.len(), "unwrap charts")?; - ids.extend(charts.iter().enumerate().map(|(id, chart)| (chart.material, id))); - // The pairs are distinct, so this order is the stable one; unlike a stable sort, it - // allocates nothing. - ids.sort_unstable(); - Ok(ids) -} - -/// What chart growing reads per face: its normal (None when degenerate), its area and its -/// material, and the faces on each manifold edge (edge → face, face, count). -struct Faces<'a> { - normal: &'a [Option], - area: &'a [f64], - material: &'a [usize], - edges: &'a HashMap<(u32, u32), (u32, u32, u8)>, -} - -/// Group the faces into charts by flood fill from the largest unassigned face, across the -/// welded edges `tri_edges` gives, while each face normal stays within 60° of the seed's and the -/// face's projection onto the seed plane overlaps no face already in the chart. `corners` gives -/// a face's positions. Returns each face's chart and the charts. -fn grow_charts(faces: &Faces, tri_edges: impl Fn(usize) -> [(u32, u32); 3], corners: impl Fn(usize) -> [Vec3; 3]) -> Result<(Vec, Vec)> { - let n = faces.area.len(); - let mut order: Vec = try_vec(n, "UV charts")?; - order.extend(0..n); - // Faces go largest first and equal areas in face order, which is the order a stable sort - // gives; an unstable sort allocates nothing. - order.sort_unstable_by(|a, b| faces.area[*b].total_cmp(&faces.area[*a]).then(a.cmp(b))); - let mut chart_of = try_filled(n, u32::MAX, "UV charts")?; - let mut charts: Vec = Vec::new(); - let mut queue = VecDeque::new(); - let mut overlap = Overlap::new(n, &corners)?; - for &seed in &order { - if chart_of[seed] != u32::MAX { - continue; - } - let id = charts.len() as u32; - let sn = faces.normal[seed].unwrap_or(Vec3::Z); - let t = sn.any_orthonormal_vector(); - let b = sn.cross(t); - let material = faces.material[seed]; - // Relative to the seed's first corner, so the rounding of a projection follows the - // chart's size rather than its distance from the origin. - let (origin, t, b) = (corners(seed)[0].as_dvec3(), t.as_dvec3(), b.as_dvec3()); - reserved(charts.try_reserve(1), "UV charts")?; - charts.push(Chart { material, origin, t, b, rot: DVec2::X, lo: DVec2::ZERO, hi: DVec2::ZERO, offset: DVec2::ZERO }); - // A face joins only when its projection onto the chart's plane does not overlap the - // faces already in it: a surface that winds around past a full turn stays within the - // normal cone and would otherwise cover the same texels twice. - let project = |f: usize| corners(f).map(|p| DVec2::new((p.as_dvec3() - origin).dot(t), (p.as_dvec3() - origin).dot(b))); - overlap.start_chart(); - overlap.add(seed, project(seed))?; - chart_of[seed] = id; - reserved(queue.try_reserve(1), "UV charts")?; - queue.push_back(seed); - while let Some(f) = queue.pop_front() { - for e in tri_edges(f) { - let Some(&(f0, f1, 2)) = faces.edges.get(&e) else { continue }; - let g = if f0 as usize == f { f1 } else { f0 } as usize; - let ok = faces.normal.get(g).is_some_and(|nn| nn.is_none_or(|nn| nn.dot(sn) >= CHART_COS)); - if !(ok && chart_of.get(g) == Some(&u32::MAX) && faces.material.get(g) == Some(&material)) { - continue; - } - let projected = project(g); - if overlap.fits(&projected) { - overlap.add(g, projected)?; - chart_of[g] = id; - reserved(queue.try_reserve(1), "UV charts")?; - queue.push_back(g); - } - } - } - } - Ok((chart_of, charts)) + mesh.compute_tangents(); + mesh.validate()?; + Ok(charts.len()) } /// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of /// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, -/// resolution used, texel offset per rectangle). The resolution doubles while the padding leaves -/// no room for a positive scale (very many charts, or padding as wide as the square), so the -/// result always fits in 0..1 and charts with a size keep it. The sizes and the scale are in -/// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero. -fn pack(sizes: &[DVec2], mut res: f32, pad: f32) -> Result<(f64, f32, Vec)> { - let mut order: Vec = try_vec(sizes.len(), "unwrap charts")?; - order.extend(0..sizes.len()); - // Tallest first and equal heights in input order, which is the order a stable sort gives; an - // unstable sort allocates nothing. - order.sort_unstable_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y).then(a.cmp(b))); - let mut out = try_filled(sizes.len(), DVec2::ZERO, "unwrap charts")?; - let pad = f64::from(pad); - // Shelf-place every rectangle at scale `s` into `out`; false when they do not fit. - let place = |s: f64, res: f32, out: &mut [DVec2]| -> bool { - let res = f64::from(res); - let (mut x, mut y, mut shelf) = (0.0f64, 0.0f64, 0.0f64); +/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone +/// cannot fit (very many charts), so the result always fits in 0..1. +fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> { + let mut order: Vec = (0..sizes.len()).collect(); + order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); + let place = |s: f32, res: f32| -> Option> { + let mut out = vec![Vec2::ZERO; sizes.len()]; + let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32); for &i in &order { - let r = sizes[i] * s + DVec2::splat(2.0 * pad); + let r = sizes[i] * s + Vec2::splat(2.0 * pad); if r.x > res { - return false; + return None; } if x + r.x > res { y += shelf; @@ -588,69 +267,47 @@ fn pack(sizes: &[DVec2], mut res: f32, pad: f32) -> Result<(f64, f32, Vec shelf = 0.0; } if y + r.y > res { - return false; - } - if let Some(o) = out.get_mut(i) { - *o = DVec2::new(x, y); + return None; } + out[i] = Vec2::new(x, y); x += r.x; shelf = shelf.max(r.y); } - true + Some(out) }; - let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max); - loop { - if place(0.0, res, &mut out) { - if largest <= 0.0 { - return Ok((0.0, res, out)); - } - // The largest scale that fits, by bisection; none above zero means a larger square. - let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); - if hi > 0.0 && place(hi, res, &mut out) { - lo = hi; - } - for _ in 0..40 { - if hi - lo <= lo * 1e-4 { - break; - } - let mid = 0.5 * (lo + hi); - if place(mid, res, &mut out) { lo = mid } else { hi = mid } - } - if lo > 0.0 && place(lo, res, &mut out) { - return Ok((lo, res, out)); - } - } + while place(0.0, res).is_none() { res *= 2.0; if res > MAX_PACK_RES { - return Err(MeshOpsError::Invalid("too many UV charts to pack".into())); + return Err(GeomError::Invalid("too many UV charts to pack".into())); } } + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max); + if largest <= 0.0 { + return Ok((0.0, res, place(0.0, res).unwrap_or_default())); + } + let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest); + if place(hi, res).is_some() { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res).is_some() { lo = mid } else { hi = mid } + } + Ok((lo, res, place(lo, res).unwrap_or_default())) } impl Mesh { - /// The checks before unwrapping: indices, submesh ranges and materials, and the normals and - /// colors the unwrap keeps. UVs and tangents are replaced, so they may be incomplete. + /// Index-range checks only (attribute arrays may be incomplete before unwrapping). fn validate_indices(&self) -> Result<()> { let n = self.positions.len(); if !self.indices.len().is_multiple_of(3) || self.indices.iter().any(|i| *i as usize >= n) { - return Err(MeshOpsError::Invalid("mesh indices are out of range".into())); + return Err(GeomError::Invalid("mesh indices are out of range".into())); } if self.triangle_count() > crate::MAX_TRIANGLES { - return Err(MeshOpsError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); - } - for s in &self.submeshes { - let end = u64::from(s.start) + u64::from(s.count); - if s.start % 3 != 0 || s.count % 3 != 0 || end > self.indices.len() as u64 || s.material >= self.materials.len().max(1) { - return Err(MeshOpsError::Invalid(format!("submesh {} is out of range", s.name))); - } - } - if !self.colors.is_empty() && self.colors.len() != n { - return Err(MeshOpsError::Invalid(format!("{} vertex colors for {n} vertices", self.colors.len()))); - } - // Normals of another length are recomputed. - let kept_normals = if self.normals.len() == n { self.normals.as_slice() } else { &[] }; - if kept_normals.iter().any(|v| !v.is_finite()) || self.colors.iter().any(|v| !v.is_finite()) { - return Err(MeshOpsError::Invalid("mesh has non-finite normals or colors".into())); + return Err(GeomError::Invalid(format!("mesh has more than {} triangles", crate::MAX_TRIANGLES))); } Ok(()) } @@ -724,327 +381,4 @@ mod tests { assert!(all_triangles_degenerate(&point)); assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); } - - #[test] - fn unwrap_rejects_bad_submeshes_and_positions_before_changing_the_mesh() { - let base = primitives::plane(1.0, 1); - // An unaligned split, an overflowing range and a non-finite position. - let mut unaligned = base.clone(); - unaligned.materials = vec!["a".into(), "b".into()]; - let part = |name: &str, material, start, count| crate::SubMesh { name: name.into(), material, start, count }; - unaligned.submeshes = vec![part("a", 0, 0, 4), part("b", 1, 4, 2)]; - let mut overflowing = base.clone(); - overflowing.submeshes[0].start = u32::MAX - 2; - overflowing.submeshes[0].count = 6; - let mut nan = base.clone(); - nan.positions[1].y = f32::NAN; - // A material past the list, colors for some vertices only and a non-finite normal. - let mut material = base.clone(); - material.submeshes[0].material = 1; - let mut colors = base.clone(); - colors.colors = vec![glam::Vec4::ONE; 2]; - let mut normal = base.clone(); - normal.normals[2].x = f32::INFINITY; - let cases = - [("unaligned", unaligned), ("overflowing", overflowing), ("nan", nan), ("material", material), ("colors", colors), ("normal", normal)]; - let mut wrong = Vec::new(); - for (name, mut m) in cases { - // Compared as text: NaN is not equal to itself. - let before = format!("{m:?}"); - if auto_unwrap(&mut m, 4.0, 256).is_ok() || format!("{m:?}") != before { - wrong.push(name); - } - } - assert!(wrong.is_empty(), "accepted or changed: {wrong:?}"); - // Padding no resolution can hold fails after the charts are made: the mesh still has no - // normals. - let mut bare = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y], indices: vec![0, 1, 2], ..Mesh::default() }; - let before = bare.clone(); - assert!(auto_unwrap(&mut bare, 65_536.0, 256).is_err()); - assert_eq!(bare, before); - } - - #[test] - fn unwrap_slices_return_source_vertices_and_respect_limits() { - let cube = primitives::cube(2.0); - let positions: Vec<[f32; 3]> = cube.positions.iter().map(|p| p.to_array()).collect(); - let l = crate::Limits::default(); - let out = crate::unwrap_uvs(&positions, &cube.indices, 4.0, 256, &l).unwrap(); - assert_eq!(out.indices.len(), cube.indices.len()); - assert_eq!(out.source.len(), out.uvs.len()); - for (k, &new) in out.indices.iter().enumerate() { - assert_eq!(out.source[new as usize], cube.indices[k], "corner {k} copies its old vertex"); - } - assert!(out.uvs.iter().flatten().all(|v| (0.0..=1.0).contains(v))); - assert!(out.charts >= 6); - let few = crate::Limits { max_unwrap_triangles: cube.triangle_count() - 1, ..l }; - assert!(matches!(crate::unwrap_uvs(&positions, &cube.indices, 4.0, 256, &few), Err(MeshOpsError::TooLarge { .. }))); - assert!(crate::unwrap_uvs(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, f32::INFINITY, 0.0]], &[0, 1, 2], 4.0, 256, &l).is_err()); - assert_eq!(crate::unwrap_uvs(&[], &[], 4.0, 256, &l).unwrap().charts, 0); - // A padding that is not finite is an error; a negative one counts as 1 texel. - for padding in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { - assert!(crate::unwrap_uvs(&positions, &cube.indices, padding, 256, &l).is_err(), "{padding}"); - } - let with_padding = |padding: f32| crate::unwrap_uvs(&positions, &cube.indices, padding, 256, &l).unwrap(); - assert_eq!(with_padding(-3.0), with_padding(1.0)); - // In the mesh form a NaN padding counts as 1 texel too. - let (mut with_nan, mut with_one) = (cube.clone(), cube.clone()); - assert_eq!(auto_unwrap(&mut with_nan, f32::NAN, 256).unwrap(), auto_unwrap(&mut with_one, 1.0, 256).unwrap()); - assert_eq!(with_nan, with_one); - // A cube of 8 shared corners splits into 4 vertices per face: the limit counts those. - let corners: Vec<[f32; 3]> = (0..8).map(|i| [(i & 1) as f32, (i >> 1 & 1) as f32, (i >> 2) as f32]).collect(); - let faces = [0, 2, 3, 0, 3, 1, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3, 0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5]; - let split = crate::unwrap_uvs(&corners, &faces, 4.0, 256, &l).unwrap(); - assert_eq!((split.charts, split.uvs.len()), (6, 24)); - let exact = crate::Limits { max_vertices: 24, ..l }; - assert!(crate::unwrap_uvs(&corners, &faces, 4.0, 256, &exact).is_ok()); - let under = crate::Limits { max_vertices: 23, ..l }; - assert!(matches!(crate::unwrap_uvs(&corners, &faces, 4.0, 256, &under), Err(MeshOpsError::TooLarge { .. }))); - } - - #[test] - fn auto_unwrap_respects_mesh_count_limits() { - let base = primitives::plane(1.0, 2); - let l = crate::Limits::default(); - let (v, t) = (base.vertex_count(), base.triangle_count()); - let too_large = |mut m: Mesh, limits: crate::Limits| { - let before = m.clone(); - let r = unwrap_core(&mut m, 4.0, 256, &limits); - assert_eq!(m, before, "the mesh is unchanged"); - match r { - Err(MeshOpsError::TooLarge { what, got, limit }) => Some((what, got, limit)), - _ => None, - } - }; - let (tv, tt) = (v as u64, t as u64); - assert_eq!(too_large(base.clone(), crate::Limits { max_vertices: v - 1, ..l }), Some(("vertex count", tv, tv - 1))); - assert_eq!(too_large(base.clone(), crate::Limits { max_unwrap_triangles: t - 1, ..l }), Some(("triangle count", tt, tt - 1))); - // A triangle listed by two submeshes is counted twice. - let mut twice = base.clone(); - twice.submeshes.push(twice.submeshes[0].clone()); - assert_eq!(too_large(twice.clone(), crate::Limits { max_unwrap_triangles: t, ..l }), Some(("submesh triangle count", 2 * tt, tt))); - assert!(unwrap_core(&mut twice, 4.0, 256, &crate::Limits { max_unwrap_triangles: 2 * t, ..l }).is_ok()); - // The mesh form applies the default limits. - let mut m = base.clone(); - let mut sliced = base; - assert_eq!(auto_unwrap(&mut m, 4.0, 256).unwrap(), unwrap_core(&mut sliced, 4.0, 256, &l).unwrap().0); - } - - #[test] - fn unwrap_core_stops_at_output_vertex_limit() { - // A cube of 8 shared corners splits into 24 vertices: 6 charts of 4. - let corners: Vec = (0..8).map(|i| Vec3::new((i & 1) as f32, (i >> 1 & 1) as f32, (i >> 2) as f32)).collect(); - let faces = vec![0, 2, 3, 0, 3, 1, 4, 5, 7, 4, 7, 6, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3, 0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5]; - let cube = Mesh::from_parts(corners, None, Vec::new(), faces, "m").unwrap(); - let l = crate::Limits::default(); - let mut exact = cube.clone(); - assert_eq!(unwrap_core(&mut exact, 4.0, 256, &crate::Limits { max_vertices: 24, ..l }).unwrap().1.len(), 24); - let mut under = cube.clone(); - let r = unwrap_core(&mut under, 4.0, 256, &crate::Limits { max_vertices: 23, ..l }); - assert!(matches!(r, Err(MeshOpsError::TooLarge { what: "vertex count", got: 24.., limit: 23 })), "{r:?}"); - assert_eq!(under, cube); - } - - #[test] - fn unwrap_many_materials_groups_charts_once() { - let chart = |material| Chart { - material, - origin: DVec3::ZERO, - t: DVec3::X, - b: DVec3::Y, - rot: DVec2::X, - lo: DVec2::ZERO, - hi: DVec2::ONE, - offset: DVec2::ZERO, - }; - let charts: Vec = [3, 0, 3, 1, 0, 3].into_iter().map(chart).collect(); - assert_eq!(charts_by_material(&charts).unwrap(), vec![(0, 1), (0, 4), (1, 3), (3, 0), (3, 2), (3, 5)]); - // Many single-chart materials: every chart lands in its own material's 0..1 square. - let mut p = Vec::new(); - let mut idx = Vec::new(); - for i in 0..64u32 { - let o = Vec3::new(i as f32 * 3.0, 0.0, 0.0); - p.extend([o, o + Vec3::X, o + Vec3::Y]); - idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); - } - let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); - m.materials = (0..64).map(|i| format!("m{i}")).collect(); - m.submeshes = (0..64u32).map(|i| crate::SubMesh { name: format!("m{i}"), material: i as usize, start: i * 3, count: 3 }).collect(); - assert_eq!(auto_unwrap(&mut m, 4.0, 128).unwrap(), 64); - for mat in 0..64 { - let g = UvGBuffer::new(&m, mat, 64, 64); - assert!(g.covered_count() > 64 * 64 / 8, "material {mat}: {}", g.covered_count()); - } - } - - #[test] - fn charts_do_not_overlap_where_a_flat_surface_winds_past_a_full_turn() { - // A flat fan around the origin through 0°, 100°, 200°, 300° and 400°: every face normal is - // +Z and each face shares an edge with the next, so the faces are one height field, but - // the first and the last cover the same part of the plane. - let mut positions = vec![[0.0f32, 0.0, 0.0]]; - for k in 0..5 { - let a = (k as f32 * 100.0).to_radians(); - positions.push([a.cos(), a.sin(), 0.0]); - } - let indices = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5]; - let out = crate::unwrap_uvs(&positions, &indices, 4.0, 256, &crate::Limits::default()).unwrap(); - assert!(out.charts >= 2, "{} charts", out.charts); - let uvs: Vec<[f32; 2]> = out.uvs.clone(); - let g = UvGBuffer::from_slices(&uvs, &out.indices, 256, 256, &crate::Limits::default()).unwrap(); - assert!(g.covered_count() > 0); - // Texels on an edge two triangles share count once per triangle; the fan has three such - // edges, so allow for those and no more. - let shared = 3 * 256 / 2; - assert!((g.overlaps as usize) < shared, "{} overlapping texels", g.overlaps); - // Each face covers its own texels: no face is drawn over another. - let mut owners = vec![0u32; 4]; - for t in &g.tri { - if let Some(o) = owners.get_mut(*t as usize) { - *o += 1; - } - } - assert!(owners.iter().all(|o| *o > 0), "{owners:?}"); - } - - #[test] - fn small_faces_that_overlap_a_large_one_start_another_chart() { - // Many unit faces set the grid, then a strip of faces 1e-4 across winds back over the - // first face: the overlap test measures each pair by its own size. - let mut positions = vec![[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; - let mut indices = vec![0u32, 1, 2]; - for k in 0..40u32 { - let o = 10.0 + 3.0 * k as f32; - let base = positions.len() as u32; - positions.extend([[o, 0.0, 0.0], [o + 1.0, 0.0, 0.0], [o, 1.0, 0.0]]); - indices.extend([base, base + 1, base + 2]); - } - // A tiny fan through 0°, 100°, 200°, 300° and 400° around (0.25, 0.25), on the first face. - let s = 1e-4; - let center = positions.len() as u32; - positions.push([0.25, 0.25, 0.0]); - for k in 0..5 { - let a = (k as f32 * 100.0).to_radians(); - positions.push([0.25 + s * a.cos(), 0.25 + s * a.sin(), 0.0]); - } - for k in 0..4 { - indices.extend([center, center + 1 + k, center + 2 + k]); - } - let out = crate::unwrap_uvs(&positions, &indices, 1.0, 4096, &crate::Limits::default()).unwrap(); - // The four fan faces share edges in a row; the first and the last overlap. - let fan = (indices.len() / 3 - 4)..indices.len() / 3; - let uv = |t: usize| [0, 1, 2].map(|k| Vec2::from_array(out.uvs[out.indices[t * 3 + k] as usize]).as_dvec2()); - let (first, last) = (uv(fan.start), uv(fan.end - 1)); - assert!(!interiors_overlap(&first, &last), "{first:?} {last:?}"); - } - - #[test] - fn thin_faces_that_overlap_start_another_chart() { - // The fan through 0° to 400°, squashed to 5e-6 and to 1e-7 of its width: its faces are - // slivers, and the first and the last still overlap. - for squash in [5e-6f32, 1e-7] { - let mut positions = vec![[0.0f32, 0.0, 0.0]]; - for k in 0..5 { - let a = (k as f32 * 100.0).to_radians(); - positions.push([a.cos(), squash * a.sin(), 0.0]); - } - let indices = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5]; - let out = crate::unwrap_uvs(&positions, &indices, 1.0, 256, &crate::Limits::default()).unwrap(); - assert!(out.charts >= 2, "squash {squash}: {} charts", out.charts); - } - } - - #[test] - fn faces_that_only_share_edges_and_corners_stay_in_one_chart() { - // 2 × 64 × 64 triangles of a flat grid touch along edges and at corners only. - let mut plane = primitives::plane(1.0, 64); - assert_eq!(auto_unwrap(&mut plane, 4.0, 1024).unwrap(), 1); - } - - #[test] - fn a_small_triangle_far_from_the_origin_unwraps_in_its_own_plane() { - // Unit edges along y and z at x = 1e24: divided by 1e24, their cross product underflows. - let out = - crate::unwrap_uvs(&[[1e24, 0.0, 0.0], [1e24, 1.0, 0.0], [1e24, 0.0, 1.0]], &[0, 1, 2], 4.0, 256, &crate::Limits::default()).unwrap(); - let [a, b, c] = [0, 1, 2].map(|k| Vec2::from_array(out.uvs[out.indices[k] as usize])); - let area = (b - a).perp_dot(c - a).abs() * 0.5; - assert!(area > 0.1, "UV area {area}: {:?}", out.uvs); - } - - #[test] - fn small_charts_far_from_the_origin_keep_their_shape_and_pack() { - let l = crate::Limits::default(); - let area = |positions: &[[f32; 3]; 3]| { - let out = crate::unwrap_uvs(positions, &[0, 1, 2], 4.0, 256, &l).unwrap(); - let [a, b, c] = [0, 1, 2].map(|k| Vec2::from_array(out.uvs[out.indices[k] as usize])); - (b - a).perp_dot(c - a).abs() * 0.5 - }; - // Edges of 1e-10 at x = 1e38: divided by 1e38, every corner is the same point. - let tiny = area(&[[1e38, 0.0, 0.0], [1e38, 1e-10, 0.0], [1e38, 0.0, 1e-10]]); - assert!(tiny > 0.1, "UV area {tiny}"); - // Unit edges at x = 1e38: divided by 1e38, the chart is about 1e-38 across and the scale - // that packs it is past f32::MAX. - let unit = area(&[[1e38, 0.0, 0.0], [1e38, 1.0, 0.0], [1e38, 0.0, 1.0]]); - assert!(unit > 0.1, "UV area {unit}"); - } - - #[test] - fn unwrap_rejects_a_triangle_in_two_materials() { - // Two separate copies of one triangle; material 0 lists both and material 1 the second. - let p = [Vec3::ZERO, Vec3::X, Vec3::Y]; - let positions: Vec = p.iter().copied().chain(p.iter().map(|q| *q + Vec3::Z * 5.0)).collect(); - let mut m = Mesh::from_parts(positions, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "a").unwrap(); - m.materials = vec!["a".into(), "b".into()]; - m.submeshes = vec![ - crate::SubMesh { name: "a".into(), material: 0, start: 0, count: 6 }, - crate::SubMesh { name: "b".into(), material: 1, start: 3, count: 3 }, - ]; - let before = m.clone(); - assert!(matches!(auto_unwrap(&mut m, 4.0, 256), Err(MeshOpsError::Invalid(_)))); - assert_eq!(m, before); - // Two submeshes of the same material may list a triangle twice. - m.submeshes[1].material = 0; - assert_eq!(auto_unwrap(&mut m, 4.0, 256).unwrap(), 2); - } - - #[test] - fn a_layout_that_fits_only_at_zero_scale_is_not_accepted() { - // With 8 texels of padding per side, a 16-texel square has no room left for the chart. - let out = crate::unwrap_uvs(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], &[0, 1, 2], 8.0, 16, &crate::Limits::default()).unwrap(); - let [a, b, c] = [0, 1, 2].map(|k| Vec2::from_array(out.uvs[out.indices[k] as usize])); - let area = (b - a).perp_dot(c - a).abs() * 0.5; - assert!(area > 0.01, "UV area {area}: {:?}", out.uvs); - assert!(out.uvs.iter().flatten().all(|v| (0.0..=1.0).contains(v))); - } - - #[test] - fn weld_ids_survive_extreme_and_non_finite_positions() { - let p = [Vec3::new(-3e38, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0), Vec3::new(3e38, 0.0, 0.0), Vec3::new(0.0, 0.0, 0.0)]; - assert_eq!(weld_ids(&p).unwrap(), vec![0, 1, 1, 2], "far-apart points stay apart and equal points weld"); - let q = [Vec3::ZERO, Vec3::X, Vec3::new(f32::NAN, 0.0, 0.0), Vec3::X]; - let ids = weld_ids(&q).unwrap(); - assert_eq!((ids[0], ids[1], ids[3]), (0, 1, 1)); - assert!(crate::weld(&[[0.0, 0.0, 0.0], [f32::NAN, 0.0, 0.0]], &crate::Limits::default()).is_err()); - // The grid follows a diagonal far below 1e-6, and a far-away point welds with its copy. - for s in [1e-20f32, 1e-30, 1e-40] { - let tiny = [Vec3::ZERO, Vec3::new(s, 0.0, 0.0), Vec3::new(s, 0.0, 0.0), Vec3::new(2.0 * s, 0.0, 0.0)]; - assert_eq!(weld_ids(&tiny).unwrap(), vec![0, 1, 1, 2], "scale {s}"); - } - assert_eq!(weld_ids(&[Vec3::splat(3e38); 2]).unwrap(), vec![0, 0]); - assert_eq!(weld_ids(&[]).unwrap(), Vec::::new()); - } - - #[test] - fn unwrap_gives_the_same_layout_at_extreme_scales() { - let cube = primitives::cube(2.0); - let l = crate::Limits::default(); - let at = |s: f32| -> Vec<[f32; 3]> { cube.positions.iter().map(|p| (*p * s).to_array()).collect() }; - let unit = crate::unwrap_uvs(&at(1.0), &cube.indices, 4.0, 256, &l).unwrap(); - assert!(unit.charts >= 6); - // Powers of two scale and divide back without rounding. - for exponent in [126, 100, -100] { - let scaled = crate::unwrap_uvs(&at(2f32.powi(exponent)), &cube.indices, 4.0, 256, &l).unwrap(); - assert_eq!(scaled, unit, "scale 2^{exponent}"); - } - } }