Skip to content

cvc/geometry: metric simplify error, carried attributes, attribute-seam-aware QEM, progressive pyramids - #505

Merged
transfix merged 15 commits into
masterfrom
fix/lod-simplify-metric
Oct 1, 2026
Merged

transfix merged 15 commits into
masterfrom
fix/lod-simplify-metric

Conversation

@transfix

Copy link
Copy Markdown
Owner

Makes cvc::simplify and build_mesh_pyramid correct enough to drive real LOD ladders. The branch went through four rounds of adversarial review; each round's findings were fixed and the fixes were themselves re-reviewed.

Bugs fixed (merged in #483/#485)

  • Error was not in metres (B1). Face quadrics are area-weighted and the boundary quadric had a constant weight, so scaling a mesh 10× scaled the reported error ~93×, and LOD never got past rung 1 in a km-scale scene. Now:
    • boundary and seam quadrics are weighted by |e|²;
    • world_error is a sampled symmetric Hausdorff distance in metres, measured over a BVH;
    • collapse costs are evaluated in per-vertex local frames, so a distant part can't change a local result.
  • Normals were recomputed. Input normals, uvs and colours are now carried bit-exactly. recompute_normals is an option, exposed in pyramid_params.

New behaviour

  • Progressive mode. One collapse pass snapshots every rung, bit-identical to independent runs. build_mesh_pyramid uses it, and rungs that barely coarsen (< 5%) are dropped.
  • Attribute-seam-aware QEM:
    • vertices bit-identical in position and attributes are welded, so soups and split meshes with continuous attributes decimate like the welded mesh;
    • position-coincident vertices with different attributes form seams, collapsed only when every dropped wedge maps onto a partner. No uv, colour or normal ever moves off its position (no texture shear) and seams stay closed;
    • a link-condition check refuses collapses that would create non-manifold fins;
    • only referenced vertices are emitted.
  • Weld search. Exact duplicates are deduplicated by sorting; near pairs are found with a median-split k-d tree (exact against brute force, 0 mismatches over 2,000 randomized cases) with bounded pair memory. The per-vertex tolerance is min(eps, max(1e-3 × median incident edge, 4 float32 ulps of |p|)), capped at 1e-6 of the scene extent. Fine parts keep their own scale, and float32-rounded joins at km coordinates stay closed. Stated limit: joins jittered above both the local cap and the floor are not welded.
  • Honest errors. Triangles that weld shut are still measured, so world_error equals the true sampled Hausdorff distance. Non-finite input never reports an error of 0, and simplify never removes the last triangle.

Tests

  • geometry_simplify_test (43):
    • 10× scale gives 10× error;
    • world_error equals an independent Hausdorff measurement;
    • carried normals are bitwise equal to the source;
    • progressive, independent and pooled runs are bitwise equal;
    • uv stays on its position (planar uv = xy) on soups and flat-shaded meshes;
    • 0 cracks across joins, including float32-rounded joins 2.5 km out and joins at a sliver;
    • fine parts in a km scene survive, with honest error;
    • timing and memory-ratio regressions on coincident and jittered piles;
    • link condition; distant-geometry invariance.
  • lod_pyramid_test (12), including the 5% rung rule.
  • lod_select_test, lod_store_test and lod_tiles_test pass on the merged tree.
  • ASan/UBSan fuzz is clean. Every meaningful mutant is killed, except a 1-ε vs 4-ε safety margin, which is deliberately left unpinned.

Performance

  • Hausdorff measurement on large uniform meshes: an earlier BVH regression was addressed.
  • 1M-triangle soup: +3.5% end to end.
  • A jittered 20k pile goes from 18 s / 4.7 GB to 0.25 s / 39 MB.

API

simplify_params gains weld_seams, seam_epsilon and recompute_normals. simplify_result gains seam_vertices and weld_pairs_held. pyramid_params gains weld_seams, seam_epsilon and recompute_normals. All are additive, with the defaults described in the headers.

…gressive mode

world_error was sqrt(max quadric cost), and that cost mixed area-weighted
face planes (area x distance^2) with constant-weight boundary planes, so
it was neither a length nor scale-consistent: a 10x copy of a mesh
reported ~91-97x the error. LOD switch radii derived from it were
meaningless beyond the first rung.

- Boundary constraint planes are weighted boundary_weight * |edge|^2, so
  face and boundary terms share units and the collapse order is
  scale-invariant. Quadrics are evaluated in a mesh-centred frame,
  round-off costs snap to 0, and costs compare at 24-bit precision with
  a vertex-index tie-break, so geometric ties resolve the same way at any
  scale or placement and on any standard library's heap.
- world_error is now measured: a sampled symmetric Hausdorff distance
  (vertices, unique edge midpoints and face centroids of both surfaces,
  exact point-to-triangle distances over a uniform grid), exposed as
  cvc::sampled_hausdorff. max_error stays a stopping rule, now on a
  length-valued proxy sqrt(cost / plane weight).
- Input normals are carried through collapses bit-for-bit like uvs and
  colours (recompute_normals opts back in), so a rung switch no longer
  re-shades unchanged surfaces.
- lock_component_seams (default on) never drops a vertex that coincides
  with a vertex of another connected component, so unwelded parts that
  touch (a roof on its walls) do not open gaps.
- simplify_progressive runs one collapse pass and snapshots each target;
  simplify() is that engine with a single target, so snapshots are
  bit-identical to independent runs.

The setup, seam search and Hausdorff samples fan over the pool with
bit-identical results. ErrorBudgetStopsEarly is re-baselined: world_error
is the Hausdorff measure and legitimately exceeds the max_error proxy, so
it now checks that a looser budget decimates further at a larger error.
New tests on an unwelded box city cover 10x scaling, brute-force
Hausdorff agreement, bitwise normals, progressive == independent,
pooled == serial, and roof-to-wall gaps with and without seam locking.
build_mesh_pyramid ran cvc::simplify from the source once per rung, so
every rung repaid the collapses of the finer ones and the coarsest rung
alone dominated. It now calls simplify_progressive: one collapse pass
snapshots each rung on the way to the coarsest target, bit-identical to
the per-rung runs. The pool still fans the per-face setup, and now also
each rung's error measurement.

world_error_m is therefore the metric (sampled Hausdorff, in the mesh's
length unit) error from cvc::simplify, lifted by the existing running
max so the ladder stays monotone. The public pyramid API is unchanged.

On a synthetic 377k-triangle city a four-rung ladder drops from ~9.8 s
(independent runs, old metric) to ~4.2 s serial including the Hausdorff
measurement. New tests check each rung against an independent
simplify() bit-for-bit, a 10x mesh giving a 10x ladder, and pooled ==
serial down to the vertex bits.
Locking every vertex that touches another component froze meshes split
for hard edges: in a triangle soup or a flat-shaded export every vertex
is on a seam, so nothing decimated and coarse rungs repeated rung 0.
Collapse on the welded topology instead. Coincident vertices form one
collapse vertex, and each input vertex keeps its own uv, colour and
normal. On a collapse, each vertex follows the vertex it shares a
vanishing triangle with, or moves onto the kept position if it shares
none. Seams stay closed, and split meshes decimate like the surface
they form.

Quadrics now live in a frame centred on their own vertex, and costs
snap to zero only inside a round-off band built from the magnitudes
actually summed. The old 1e-12 * bbox^2 floor treated real features as
free once the mesh was large, so one far-away triangle changed how a
local part decimated. The default seam_epsilon is likewise capped at
1e-3 of the median edge.

The loop no longer removes the last triangle, so the error of a result
is always finite; an empty result reported infinity.

The Hausdorff measurement moves from a uniform grid sized by mean
triangle area to a BVH. A huge ground quad under fine detail piled the
detail into a few cells and made the measurement quadratic (100x+).

New tests cover welded split faces and soups, locality to far geometry,
target 0, the ground-quad cost, and the plan's 1.05x pixel-budget check
at switch_radius_m on the box city. The scale and Hausdorff tests are
re-baselined to targets where the welded city is lossy: welded, it
decimates losslessly down to ~146 triangles.
build_mesh_pyramid always ran simplify with its seam defaults and gave
callers no way to change them. pyramid_params now forwards weld_seams
and seam_epsilon.

A rung whose target the collapse cannot reach, because every remaining
collapse is guarded, used to repeat the rung before it with a positive
error. It added nothing to the ladder but a switch point. Such rungs
are now left out, so the ladder can be shorter than max_rungs.

world_error_m is now documented as a sampled lower bound. On
feature-aligned meshes it equals the dense measure. On strongly curved
terrain that is decimated coarsely, a switch radius derived from it
can exceed the pixel budget by up to ~25%. P2's selection work should
take this into account.
…osition

Weld-aware collapse moved a seam vertex that had no partner in a
vanishing triangle onto the kept position but kept its own uv, colour
and normal. On soups and split meshes this attached texture
coordinates to foreign positions, and a planar-projected texture
sheared by tens of grid cells. The same scheme left the kept and
opposite vertices of every vanishing triangle in the output, so coarse
rungs of split meshes were mostly unreferenced vertices. The seam
search compared every pair in a 64*eps hash cell, which is quadratic
on piles of coincident corners and on fine parts inside large scenes.

Weld the standard way instead. Input vertices bit-identical in
position and in every carried attribute become one vertex, so a soup
or a split mesh whose attributes agree is the welded mesh itself.
Vertices that still share a position form a seam. A collapse maps each
vertex of the dropped position onto the vertex of the kept position it
shares a vanishing triangle with, and is refused when a vertex that a
surviving triangle uses has no such partner, or two. Vertices never
move, seams collapse only along themselves and stay closed, and both
sides of a seam carry constraint planes like open borders. The result
holds only the vertices its triangles use.

The weld finds exact coincidence by sorting position bits, and
searches cells 2*eps wide over distinct positions only, skipping a
position's own component. A pile of 21000 coincident corners, or a
1 mm part in a 3 km scene, now costs what the unwelded mesh costs.

A non-finite coordinate, or one large enough to overflow a squared
distance, made the round-off floor infinite and world_error 0. Such
input is now returned unchanged at +infinity, and sampled_hausdorff
reports +infinity. The floor also scales with coordinate magnitude, so
coincident surfaces measure 0 far from the origin. Triangles whose
corners weld together no longer count toward world_error, and no
longer leave an empty result.

New tests cover exact welding of agreeing splits, planar uv on soups
and flat-shaded sheets, colour blocks, a crease inside one component,
the seams of a closed box, a colour patch on a plane, changed-centroid
samples, collapse-order invariance under scale and translation,
non-finite input, triangles that weld away, coincidence far from the
origin, and the weld's cost on piles and fine parts. Each one fails
against a mutant of the code it guards.
On a 1M-triangle grid the BVH measurement took 2.5x as long as the
uniform grid it replaced: 3.0 s serial and 1.2 s pooled, against 1.2 s
and 0.5 s. A mesh that lists its vertices and triangles in no spatial
order took 2.5x longer again. Consecutive samples then defeated the
leaf hint, and each query descended from the root.

Samples are now visited in Morton order of their positions: a stable
radix sort on a 1024^3 lattice with one scale on every axis, so
consecutive samples are neighbours whatever the mesh's own order. A
query that its hint leaf does not settle searches the subtree five
levels above that leaf before the root. The tree is laid out in
preorder, with each subtree at an offset fixed by its size, so the
subtrees under the top levels build in parallel and bit-identically.
Centroids travel with their triangle indices during the splits.

Leaves stay at 4 triangles, since 8 and 16 were slower. Precomputed
edge vectors saved about 8% of query time for a third more triangle
memory, so they were left out.

On the 1M grid sampled_hausdorff now takes 2.1 s serial and 0.8 s
pooled. With shuffled vertex and triangle order it drops from 7.7 s to
3.2 s serial and from 2.8 s to 1.2 s pooled. Results are unchanged:
distances above the round-off floor are still exact, and pooled equals
serial bit for bit.
The weld rework in cvc::simplify changes what a mesh pyramid holds. A
flat-shaded sheet or a triangle soup whose attributes agree now
coarsens as the welded sheet, and every rung keeps each uv on its own
position and holds only the vertices its triangles use. A new test
checks both for every rung of a flat-shaded sheet and of a soup that
carry a planar-projected texture.

The header also contradicted itself and simplify.h. It gave a 25%
pixel-budget overshoot where simplify.h gave a 20% error shortfall for
the same effect, so both now state the one measured figure: the dense
distance was up to ~1.25x world_error_m on synthetic bumpy terrain. It
said rung k matches simplify at rung k's target, which stops holding
once a stalled rung is left out; it now says each kept rung matches
simplify at its own target. It also notes that triangles which weld
away are in no rung and do not count toward a rung's error.
build_mesh_pyramid stopped at the first snapshot that did not have
fewer triangles than the rung before it, on the assumption that the
collapse pass had stalled. But one collapse removes two or more
triangles, so it can pass two close targets at once while the pass
goes on. On an 8x8 sheet with mesh_ratio 0.99, one collapse took the
count from 96 to 94, past the targets 95 and 94, and the rungs for 93
and 92 were lost with it.

Leave out only the repeated snapshot. A stalled pass still yields
nothing after the stall, because every later snapshot repeats it too.
The header now says that rung k need not be the one built for the k-th
target.
…shut

The default seam tolerance was one number for the whole scene: 1e-6 of
the extent, capped at 1e-3 of the median edge. In a 3 km scene that is
about 4 mm, and the median edge belongs to the terrain. Fine parts a few
millimetres apart, such as an array of 2 mm fittings 3 mm apart or a
flat-shaded 1 mm soup, welded into one another. Chains of those welds
closed the parts' own triangles, so the parts vanished from every rung.
Those triangles were also left out of the surface world_error measures,
so the loss was hidden: on the reviewer's scene world_error was 0 while
sampled_hausdorff(input, result) was 58.9.

The default is now local. Each vertex gets 1e-6 of the extent, but no
more than 1e-3 of its shortest incident edge, and two vertices weld only
within both their tolerances. A fine part keeps its own scale and
survives, and whether it survives no longer depends on its neighbours.
An explicit seam_epsilon is still used as given for every pair. Only
true needles (two corners at one bit-identical position) are left out
of the measured source. A triangle that welds shut within the
tolerance is dropped from the result but still measured, so world_error
equals sampled_hausdorff(input, result) whenever the input has no
needles. That holds for every pyramid rung too.

The near-coincidence search was a hash grid of 2*eps cells. It stored
every within-eps pair before the union, so memory grew with the square
of a near-coincident cluster: 2.3 GB for 24k jittered positions. It is
now a median-split k-d tree over the distinct positions, and each
position queries its own radius. Nodes record their largest tolerance
and their component when they have only one. A query skips subtrees out
of reach and subtrees of its own component. A node whose box fits within
its smallest tolerance and that holds several components is a clique:
it is chained once, reached through one pair, and its members pair with
each target once between them. Each block keeps only a spanning forest
of the pairs it finds. The tree and the BVH share one median-split
builder, so the BVH is unchanged bit for bit. partners() now sorts its
wedge map, so a class with k wedges costs O(k log k) instead of O(k^2).

With 7000 unit triangles jittered by 1e-5 on a 100x100 grid (21000
distinct near-coincident corners), welding took 22.6x as long as not
welding. It now takes 1.7x. The same pile of tiny triangles under an
explicit tolerance went from 91.8x to 1.3x. Peak memory stays flat
where it grew to 2.3 GB. On a 124k-triangle grid, simplify runs under
1.5% more instructions (welded, soup or unwelded). On a 1M-triangle
grid, wall-clock time is unchanged within noise.

New tests: fine parts in a km-scale scene survive, and an explicit
tolerance's losses are measured, including in pyramid rungs. A
position two parts share welds to both. A join jittered by 1e-9 across
7200 positions stays closed. A seamed block sheet reaches its target
through the partner fallback. A double-sided sheet keeps its border. A
crease whose copies differ only in the sign of zero stays one seam. A
soup of a creased sheet decimates exactly as the creased sheet. A
jittered pile and a mixed-scale pile weld with bounded time and pairs.
Together they kill the mutants the review found surviving: no -0
normalisation, the last component winning at a shared position, pins
on single-triangle sides only, no partner fallback, and one block's
pairs only. They also kill mutants of the new code: no local cap, no
clique chain, no pair forest, and welded-shut triangles left
unmeasured.
The collapse loop checked each candidate for fold-overs (the normal-flip
test) and for a clean wedge map, but not for the link condition. On
meshes with attribute seams, ordinary collapses could then fold the
surface onto itself. The review's seamed-sphere fuzz (closed bumpy
spheres with Voronoi color/uv regions, soups and salted regions, in
shuffled order) found 22 of about 1050 runs at 60/30/10% targets with
two faces over the same three positions and an edge carrying more than
two triangles. Unseamed spheres never did.

A collapse is now refused unless the classes adjacent to both keep and
drop are exactly the third corners of the triangles on the edge. Any
other common neighbour w would merge the edges keep-w and drop-w into
one that carries both edges' triangles. The check is O(degree), with
per-class stamps and no sorting. Like a flip, a refused collapse is
dropped, and a re-pushed copy may succeed later.

On the same fuzz (1600 runs), no run at 60/30/10% has a doubled face
or an edge with three triangles. The only non-manifold results left
are at a target of 1, where a closed sphere ends as a two-sided
triangle (148 runs, every one of them 2 triangles). That end state is
documented and is what the pyramid's tetrahedron test expects. Reach
is unchanged: 43 missed targets against 42 before, and 177680 output
triangles against 177666. Together with the previous commit, a
124k-triangle grid runs under 1.5% more instructions than before
either.

A new test decimates 48 seamed spheres (per-region copies, soups, salted
regions) to 60/30/10% with and without constraint planes. It asserts no
doubled faces, every edge with exactly two triangles, no region mixing
and no uv shear. Removing the check fails it.
…oarsen

A curved mesh exported with per-face normals splits every vertex, and
its attributes jump at every one. Its seams then allow almost no
collapse, so only the open border can go. simplify offers
recompute_normals as the way out, since fresh normals do not split
vertices, but pyramid_params had no such switch. build_mesh_pyramid
therefore kept a rung that removed a handful of border triangles at a
large error, and then stalled. The review's faceted 100x100 soup got
rungs of 19602 and 19590 triangles.

pyramid_params::recompute_normals now reaches simplify, and pyramid.h
explains when a ladder needs it. A snapshot is kept only if it removes
at least 5% of the triangles of the rung before it, or half the step
mesh_ratio asks for when that is smaller. A rung that barely coarsens
is not worth a switch or its storage. The half-step clause keeps
fine-stepped ladders (mesh_ratio 0.99) intact. The faceted soup now
yields rung 0 alone by default, and five rungs (19602, 6860, 2400, 839,
293) with recompute_normals.

A new test builds the ladder of a faceted bumpy soup with per-face
normals both ways. With normals carried it expects only rung 0, and
simplify removes under 3% at the first target. With recompute_normals
it expects four rungs, each at least 5% coarser than the last and
equal to simplify with the same switch. Dropping the pass-through or
the 5% rule fails it.
The default weld tolerance was capped at 1e-3 of each vertex's shortest
incident edge. That kept fine parts in a large scene apart, but it
reopened cracks at real joins. A single sliver at a join vertex shrank
its tolerance by orders of magnitude. And float32 rounding far from the
origin (about 1.2e-4 at 2.5 km) already exceeds 1e-3 of any edge under
about 12 cm. Such a join no longer welded, so each side decimated its
border on its own and the join opened. world_error does not see the
gap.

The cap is now 1e-3 of the vertex's median incident edge: the two sides
of every triangle corner there, zero lengths left out, taking the upper
median of an even count. It also never drops below 4 float32 epsilons
of the vertex's largest coordinate magnitude, the rounding of
float32-stored coordinates, and the whole tolerance stays under the
scene-wide 1e-6 of the extent. Fine parts still keep their own scale:
the 2 mm tetrahedra 1 mm apart in a 3 km scene stay unwelded. Parts
closer than the float32 floor do weld, and world_error measures what
that loses. The floor never exceeds the 1e-6 cap, so double-precision
data far from the origin is not welded by the metre. simplify.h states
what is left: a join apart by more than both the local cap and the
floor, or beyond the 1e-6 cap, is not welded and can crack.

simplify_result::weld_pairs_held reports the most pairs any block of
the seam search held at once. The mixed-scale pile test moves to the
origin, where the floor is nil, and asserts that the search passes its
4096-pair budget and trims back under it. Disabling the trimming now
fails that test.

New tests:
- a join rounded to float32 2.5 km out
- a join vertex with a 1 mm sliver, and one carrying a point
- a 1 km spike beside the 5 mm contact (median, not longest edge)
- a 1 mm contact that must weld (the 1e-3 factor)
- a scene 1000 km out whose float32 floor must stay under the 1e-6 cap
- a point triangle beside a sheet vertex that must not weld to it
- a pyramid snapshot 7% coarser that is kept, and one 3% coarser that
  is left out (the 5% rule)
…dder checks per tile

MSVC: <minwindef.h> defines near and far as empty macros, so `u32 near = hint;` in the
Hausdorff BVH and two `far` locals in geometry_simplify_test failed to compile on the
Windows lanes (C2513).

cvcgl_lod_node: its real-ladder block assumed rung 3's switch radius sits well clear of
rung 2's across all tiles (r3min > 1.5 * r2max) and that one overhead pose puts every
tile on rung 2. That held only while world_error_m overstated the error uniformly. Now
that it is a measured Hausdorff distance, each tile's ladder reflects its own relief and
the per-tile radii overlap, so no single pose can put every tile on one rung. Check what
must hold for any honest ladder instead, with poses derived from the ladders: beyond
every tile's rung-2 radius no tile draws rung 0 or 1 (and drawn triangles drop), beyond
every rung-3 radius every tile draws rung 3, and across the set the coarsest rung is the
coarser one. The old TODO's prediction (real ladders coarsening at the fixed 2.5 km pose)
does not hold on this relief -- rung 2's true error is only affordable several km out at
the balanced preset -- and the note now says so.
@transfix
transfix merged commit 9ff6693 into master Oct 1, 2026
13 checks passed
@transfix
transfix deleted the fix/lod-simplify-metric branch October 29, 2026 20:53
transfix added a commit that referenced this pull request Oct 30, 2026
… one copy

link-host.sh left libvtklibxml2-*.a out of the host link (#872): VTK's
bundled libxml2 kept 65 internals under plain names, which collided with the
libxml2 ImageMagick brings and made a module node could not compile. vtk
9.5.0+cvc.4 (cy-pca/cvcpkg#497, #505) builds its wasm variants against
cvcpkg's libxml2, libtiff, liblzma and freetype, so the bundle no longer
ships libvtk{libxml2,tiff,lzma,freetype} and the exclusion matches nothing.
Every deps archive goes into the group again; the comment says why an older
vtk would break and that the workflow's node check catches it.
transfix added a commit that referenced this pull request Oct 30, 2026
…; no arigl in the build (#910)

* pycvc wasm: link VTK's libxml2 replacement again; vtk 9.5.0+cvc.4 has one copy

link-host.sh left libvtklibxml2-*.a out of the host link (#872): VTK's
bundled libxml2 kept 65 internals under plain names, which collided with the
libxml2 ImageMagick brings and made a module node could not compile. vtk
9.5.0+cvc.4 (cy-pca/cvcpkg#497, #505) builds its wasm variants against
cvcpkg's libxml2, libtiff, liblzma and freetype, so the bundle no longer
ships libvtk{libxml2,tiff,lzma,freetype} and the exclusion matches nothing.
Every deps archive goes into the group again; the comment says why an older
vtk would break and that the workflow's node check catches it.

* pycvc-gl wasm: no arigl in the build; it fails cmake --install

Since arigl took the network flags, every wasm link of it pulls in cvc::net's fetch backend and
needs -sFETCH=1, which only the examples' gallery link gives it. pycvc-gl's wasm build has the
examples off, so arigl.js fails to link (undefined emscripten_fetch*), and cmake --install then
stops on the missing bin/arigl.js before link-host.sh runs. The package never shipped arigl, so
turn it off, as publish-cvcgl-wasm.yml already does; build-wasm.ps1 gets the ari and arigl
options build-wasm.sh has.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant