Algorithmcore
Metro mesh comparison
Also called Metro tool, mesh Hausdorff error.
Cignoni, Rocchini and Scopigno's estimate of the one-sided and symmetric Hausdorff and mean distances between two meshes by sampling one surface.
- Time
- O(S F) brute_force · grid_worst
- Space
- O(F + C) grid
- Where
- C = the number of grid cells; F = the number of triangles of the other mesh; S = the number of samples
- Model
- Real RAM
- Properties
- randomizednot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Paolo Cignoni, Claudio Rocchini, Roberto Scopigno, 1998
Metro is the standard way to say how far apart two triangle meshes are, for example a mesh and its simplified copy. It samples the surface of one mesh, finds for each sample the nearest point of the other mesh, and reports the largest of these distances, an estimate of the one-sided Hausdorff distance, with their mean and root mean square. It does the same in the other direction, and the larger of the two maxima estimates the symmetric Hausdorff distance. Paolo Cignoni, Claudio Rocchini and Roberto Scopigno released it in 1998 as a tool to compare mesh simplification methods. The estimate is never too large, and it is too small by at most the spacing of the samples.
In plain words
Two meshes describe nearly the same shape, and you want to know how much they differ. Put many points on the first surface. For each point, measure how far it is to the second surface. The largest of these distances tells you the worst place, and the average tells you the typical error.
The worst place can be missed if no point lands on it. More points make the miss smaller. A point that is far from the second surface can only be found from the first surface, so the measurement is done in both directions.
The problem
The input is two triangle meshes and . The distance of a point to is . The one-sided Hausdorff distance is , and the symmetric one is . The mean distance is , where is the area of . Metro estimates these numbers. The distance does not depend on the orientation of the faces; the code of the page keeps the usual convention that faces are oriented so that the outward normal follows the right-hand rule, but it does not use it.
The algorithm
The core step is the exact distance from a point to a triangle. The plane around a triangle splits into seven regions, the three corner regions, the three edge regions and the inside, and the nearest point is the corner, the foot of the perpendicular on the edge, or the projection onto the plane. Six dot products of edge vectors with minus a corner decide the region, as in the orientation test, and only ring operations and one division follow, so the result is exact for rational input.
For speed, the triangles of are put into a uniform grid of cubic cells: each triangle goes into every cell that meets its bounding box. A query visits rings of cells around the cell of , of growing radius , and stops as soon as the nearest triangle found is at most away, where is the cell size, because every triangle not yet seen is at least that far.
METRO(A, B, k, n)- 1
S ← the vertices of a k × k similar subdivision of each triangle of A, and n random points of A - 2
for each p ∈ S do δ(p)² ← min over triangles T of B near p of |p − CLOSEST-POINT(p, T)|² - 3
h_AB ← max over p ∈ S of δ(p) - 4
mean_AB ← average of δ(p); rms_AB ← square root of the average of δ(p)² - 5
compute h_BA, mean_BA and rms_BA by L1 to L4 with A and B exchanged - 6
return h_AB, h_BA and max(h_AB, h_BA)
The random points of L1 are uniform by area: a triangle is chosen with probability proportional to its area, and two uniform numbers in give the point , with replaced by when . This reflection maps the unit square onto the triangle twice, evenly.
Degenerate cases. A triangle of zero area has no inside region and the formula divides by zero; the code requires positive area. A sample that lies on has distance 0. If and are the same mesh, all distances are 0. A mesh with no triangles has no defined distance. The grid needs a cell size ; a very small makes many cells and a very large puts all triangles in one cell, which is the brute-force loop.
Example
Let be the unit square in the plane , as two triangles, and the triangle , , , the lower left half of the square. With , L1 gives the 9 points with coordinates in .
| step | value |
|---|---|
| L2 | the 6 points with lie on : |
| L2 | and are from the edge |
| L2 | is from that edge |
| L3 | , the true value, because the farthest corner is a sample |
| L4 | mean , rms |
| L5 | lies on , so |
| L6 | the symmetric estimate is |
The true mean is and the true rms is . The grid points overweight the corner of the square, so their mean is too large. The table compares the two kinds of samples in the code of the page.
| samples | max | mean | rms |
|---|---|---|---|
| subdivision, (9 points) | 0.7071 | 0.1571 | 0.2887 |
| subdivision, (81 points) | 0.7071 | 0.1309 | 0.2282 |
| subdivision, (1089 points) | 0.7071 | 0.1214 | 0.2104 |
| Monte Carlo, 100 points | 0.6555 | 0.1180 | 0.2053 |
| Monte Carlo, 10000 points | 0.7015 | 0.1173 | 0.2033 |
| true value | 0.7071 | 0.1179 | 0.2041 |
The subdivision vertices find the maximum when it is at a vertex, and Monte Carlo points estimate the mean without bias but miss the maximum. Metro uses both kinds for this reason.
When the arithmetic is floating point. The code of the page computes every squared distance exactly in rational arithmetic and takes square roots only for the reported numbers. In doubles, the region tests are signs of dot products and the last step divides by a sum that is proportional to the squared area of the triangle. For a sliver of length 2 and width , the float distance from a point at distance 0.41 was off by 0.025, a case of catastrophic cancellation; for widths down to the float error stayed below in 3000 random queries. Simplified meshes often contain slivers, so a tool that compares them should guard the division, use exact predicates for the region tests, or fall back to the three edge distances when the area is tiny. This is the robustness problem of geometry in a mild form: the answer is a measured number, and a wrong region gives a point of the triangle whose distance is close to the true one unless the triangle is nearly degenerate.
Correctness
Every sample lies on , so its distance to is at most , and the sampled maximum is a lower bound. The distance to is 1-Lipschitz: moving the point by changes it by at most . The worst point of is within of a sample, where is the largest distance from a point of to its nearest sample, so the sampled maximum is at least . For the subdivision of each triangle into similar copies, is at most the longest edge of divided by . The closest-point routine finds the nearest point of a triangle by its Voronoi regions, and the grid search stops only when no unseen triangle can be closer. The full proof is below.
Proof: Metro's sampled distance is a lower bound of the one-sided Hausdorff distance, and it is within the sample spacing of the true valuefull
Setting. and are finite sets of triangles in , each of positive area, and they also denote the union of their triangles, which are closed sets. The distance from a point to is , and the one-sided Hausdorff distance is . The symmetric distance is . A sample set is a finite set of points. The code reports , and the mean and root mean square of over . The subdivision sample of a triangle is the set of points with and , and is the union over the triangles of .
Claim.
- For a point and a triangle , the function CLOSEST-POINT of the code returns the point of nearest to , so is computed exactly for rational input.
- The uniform grid query returns , the same value as the loop over all triangles.
- For every sample set , .
- If every point of is within of a point of , then . For , , where is the longest edge of . Also .
- The symmetric value returned is , and it lies between and when both sample sets are -dense.
Step 1 (part 1). The squared distance is a convex quadratic on the convex set . Its minimizer is the unique point of with for all . The plane around is split into seven regions: three corner regions, three edge regions and the inside. The corner region of is ; there for all in , so . The same holds at and with the tests and of the code. If is in none of them, the code tests the edge regions: for edge , says that the projection of onto the plane is on the outer side of the line (the quantity is the area coordinate of times twice the area times ), and says that the foot on the line falls between and ; then , the foot of the perpendicular on the segment, and is orthogonal to and points away from , which gives the variational inequality. The other two edges are the same. If is in no corner or edge region, all three area coordinates are positive and the projection of onto the plane lies in , so is that projection, with barycentric weights and . Every operation is a ring operation or a division by a nonzero rational, so the result is exact. The tests of the page also check it against another exact route on 3000 random cases.
Step 2 (part 2). Let the cell of a point be in each coordinate. Each triangle is stored in every cell that meets its bounding box, so a triangle is stored in the cell of each of its points. Let be in cell . After the query has visited all cells with , any point in a cell with differs from by at least in some coordinate, so . If is a triangle not yet seen, its point nearest to is in such a cell (else would be stored in a visited cell and seen), so . The query stops when the best value found, so no unseen triangle is closer. It also stops when the ring has passed all occupied cells, and then every triangle has been seen. In both cases it returns the minimum over all triangles.
Step 3 (part 3). Every sample is a point of , so for each sample and the maximum over is at most .
Step 4 (part 4). The function is 1-Lipschitz: for nearest to , . The maximum is attained at some , because is compact and is continuous. Take with ; then . For , the subdivision of a triangle with corners into the small triangles with corners in covers the triangle, each small triangle is similar to it with ratio , and a point of a triangle is within the diameter of that triangle, its longest edge, of each of its corners. So . Finally , since , so the maximum can only grow.
Step 5 (part 5). The code returns the larger of the two one-sided estimates. By parts 3 and 4 each is between and for its direction, and the maximum of two numbers each in such an interval is in .
What is measured, not proved. The mean and the root mean square are estimates of the area-weighted mean and of the square root of . The Monte Carlo samples choose a triangle with probability proportional to its area and a point in it with the reflection trick, which maps the uniform distribution on the unit square to the uniform distribution on the triangle; with samples the error of the mean shrinks like . The code draws the two coordinates from a grid of step , so the points are uniform up to that grid. The vertices of are not area-weighted (the edges of the mesh get more of them), so a mean over alone is biased, as the example of the page shows.
Termination. Sampling makes points per triangle plus random points. Each grid query visits rings of growing radius and stops at the latest when the ring has passed all occupied cells, a finite number.
Complexity
With samples and triangles in , the brute-force query costs per sample and in total. The grid takes space for cells, counting a triangle once per cell it meets. A query on a mesh with evenly sized triangles and a cell size near the triangle size touches cells and triangles, but in the worst case, for example one long triangle in every cell, it touches all . The subdivision gives about samples per triangle, so the sampling error falls like while the cost grows like . The Monte Carlo mean has an error that falls like .
Properties
- One-sided lower bound. The sampled maximum never exceeds the true Hausdorff distance, and it grows when samples are added.
- Two-sided error bound. The true value is at most the sampled maximum plus the sample spacing.
- Not symmetric. and can be very different, as in the example, where they are 0.707 and 0.
- Randomized. The Monte Carlo samples depend on the seed; the subdivision samples do not.
- Unsigned. The distance does not say on which side of the sample lies.
Variants and improvements
- Sampling schemes. The original tool offers similar-triangle subdivision, Monte Carlo sampling and a sampling by scan conversion of each triangle, a form of stratified sampling, with a sampling density per unit area.
- Vertex-only error. Measuring only at the vertices of is cheap but misses the error in the middle of large triangles, which is where a simplified mesh is far from the original.
- MESH. Aspert, Santa-Cruz and Ebrahimi (2002) gave a similar tool with a different sampling and a grid query.
- Chamfer distance. Averaging the nearest distances both ways, instead of taking the maximum, gives the chamfer distance, which is common in learning on point sets.
- Error during simplification. Quadric error metrics bound a different quantity, the sum of squared distances to planes, during the simplification itself; Metro checks the result afterwards.
When to use it
Use Metro to report the approximation error of a simplified, remeshed or compressed mesh against the original, and to compare methods such as mesh simplification or isotropic remeshing fairly. Report both one-sided maxima, the mean and the sampling density. When a guarantee is needed rather than an estimate, add the spacing bound to the maximum, or use an exact algorithm for the Hausdorff distance between triangle meshes.
Pitfalls
- Only one direction. The distance from the simplified mesh to the original is often small while the other direction is large, for example when a thin part has been removed. Always measure both.
- Too few samples. The maximum can be missed by up to the sample spacing. State the density.
- Mean over vertices. A mean over subdivision vertices is not area-weighted, as the example shows: 0.157 against 0.118.
- Units. The values are absolute lengths. Divide by the diagonal of the bounding box to compare meshes of different size, and say so.
- Slivers in floating point. Nearly degenerate triangles give wrong distances with doubles, as shown above.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metro-mesh-comparison/. The authors are listed in prov/YBB4K3.jsonl.
"""Metro mesh comparison (Cignoni, Rocchini and Scopigno 1998).
Sample the surface A, find for each sample the distance to the surface B,
and report the largest (an estimate of the one-sided Hausdorff distance from
A to B), the mean and the root mean square. The symmetric Hausdorff distance
is the larger of the two one-sided values.
Squared point-to-triangle distances are exact for int or Fraction input. A
uniform grid over the triangles of B answers the nearest-triangle query; it
returns the same exact value as a loop over all triangles. Square roots are
taken only at the end, for the reported numbers.
"""
import math
import random
from fractions import Fraction
from mp3geom import add, dot, scale, sub
def closest_point_on_triangle(p, a, b, c):
"""The point of triangle abc closest to p, by the Voronoi regions of the corners and edges. Exact."""
ab, ac, ap = sub(b, a), sub(c, a), sub(p, a)
d1, d2 = dot(ab, ap), dot(ac, ap)
if d1 <= 0 and d2 <= 0:
return a
bp = sub(p, b)
d3, d4 = dot(ab, bp), dot(ac, bp)
if d3 >= 0 and d4 <= d3:
return b
vc = d1 * d4 - d3 * d2
if vc <= 0 and d1 >= 0 and d3 <= 0:
return add(a, scale(Fraction(d1) / (d1 - d3), ab))
cp = sub(p, c)
d5, d6 = dot(ab, cp), dot(ac, cp)
if d6 >= 0 and d5 <= d6:
return c
vb = d5 * d2 - d1 * d6
if vb <= 0 and d2 >= 0 and d6 <= 0:
return add(a, scale(Fraction(d2) / (d2 - d6), ac))
va = d3 * d6 - d5 * d4
if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0:
return add(b, scale(Fraction(d4 - d3) / ((d4 - d3) + (d5 - d6)), sub(c, b)))
denom = Fraction(1) / (va + vb + vc)
return add(a, add(scale(vb * denom, ab), scale(vc * denom, ac)))
def dist2_point_triangle(p, a, b, c):
q = closest_point_on_triangle(p, a, b, c)
d = sub(p, q)
return dot(d, d)
def brute_force_dist2(p, points, faces):
"""Squared distance from p to the mesh, by a loop over all triangles."""
return min(dist2_point_triangle(p, *(points[v] for v in f)) for f in faces)
class UniformGrid:
"""Triangles of a mesh bucketed by their bounding boxes in cubic cells of side h."""
def __init__(self, points, faces, h):
self.points, self.faces, self.h = points, faces, Fraction(h)
self.cells = {}
for i, f in enumerate(faces):
lo = [min(points[v][k] for v in f) for k in range(3)]
hi = [max(points[v][k] for v in f) for k in range(3)]
rng = [range(self.cell(lo[k]), self.cell(hi[k]) + 1) for k in range(3)]
for x in rng[0]:
for y in rng[1]:
for z in rng[2]:
self.cells.setdefault((x, y, z), []).append(i)
keys = list(self.cells)
self.lo = tuple(min(k[j] for k in keys) for j in range(3))
self.hi = tuple(max(k[j] for k in keys) for j in range(3))
def cell(self, x):
return math.floor(Fraction(x) / self.h)
def dist2(self, p):
"""Exact squared distance from p to the mesh. Visits rings of cells around p until no closer triangle can exist."""
c = tuple(self.cell(x) for x in p)
best, seen, ring = None, set(), 0
reach = max(max(abs(c[j] - self.lo[j]), abs(c[j] - self.hi[j])) for j in range(3))
while True:
for key in self.ring(c, ring):
for i in self.cells.get(key, ()):
if i not in seen:
seen.add(i)
d = dist2_point_triangle(p, *(self.points[v] for v in self.faces[i]))
if best is None or d < best:
best = d
# every cell not yet visited is at least ring * h away from p
if best is not None and (ring * self.h) ** 2 >= best:
return best
if ring > reach:
return best
ring += 1
@staticmethod
def ring(c, r):
for dx in range(-r, r + 1):
for dy in range(-r, r + 1):
for dz in range(-r, r + 1):
if max(abs(dx), abs(dy), abs(dz)) == r:
yield (c[0] + dx, c[1] + dy, c[2] + dz)
def subdivision_samples(points, faces, k):
"""The vertices of the subdivision of every triangle into k * k similar triangles. Exact."""
out = set()
for f in faces:
a, b, c = (points[v] for v in f)
for i in range(k + 1):
for j in range(k + 1 - i):
u, v = Fraction(i, k), Fraction(j, k)
out.add(tuple(x + u * (y - x) + v * (z - x) for x, y, z in zip(a, b, c)))
return sorted(out)
def area(a, b, c):
e1, e2 = sub(b, a), sub(c, a)
n = (e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0])
return math.sqrt(float(dot(n, n))) / 2
def monte_carlo_samples(points, faces, n, rng, denominator=10**6):
"""n points uniform by area: a triangle by its area, then a point by the reflection trick. Exact coordinates."""
weights = [area(*(points[v] for v in f)) for f in faces]
out = []
for f in rng.choices(faces, weights=weights, k=n):
a, b, c = (points[v] for v in f)
u, v = Fraction(rng.randint(0, denominator), denominator), Fraction(rng.randint(0, denominator), denominator)
if u + v > 1:
u, v = 1 - u, 1 - v
out.append(tuple(x + u * (y - x) + v * (z - x) for x, y, z in zip(a, b, c)))
return out
def one_sided(samples, points_b, faces_b, h=None):
"""(max, mean, rms) of the distances from the samples to mesh B."""
query = UniformGrid(points_b, faces_b, h).dist2 if h else (lambda p: brute_force_dist2(p, points_b, faces_b))
d2 = [query(p) for p in samples] # @line L2
worst = max(d2) # @line L3
mean = sum(math.sqrt(float(x)) for x in d2) / len(d2) # @line L4
rms = math.sqrt(float(sum(d2)) / len(d2))
return math.sqrt(float(worst)), mean, rms
def metro(points_a, faces_a, points_b, faces_b, k=8, n=2000, seed=1998, h=None):
"""One-sided values both ways and the symmetric Hausdorff estimate."""
rng = random.Random(seed)
sa = subdivision_samples(points_a, faces_a, k) + monte_carlo_samples(points_a, faces_a, n, rng) # @line L1
sb = subdivision_samples(points_b, faces_b, k) + monte_carlo_samples(points_b, faces_b, n, rng)
ab = one_sided(sa, points_b, faces_b, h) # @line L5
ba = one_sided(sb, points_a, faces_a, h)
return ab, ba, max(ab[0], ba[0]) # @line L6
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mp3 pages.
Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""
from fractions import Fraction
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def orient2d(a, b, c):
"""Twice the signed area of triangle abc: > 0 if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def orient3d(a, b, c, d):
"""((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
return dot(cross(sub(b, a), sub(c, a)), sub(d, a))
def sign(x):
return (x > 0) - (x < 0)
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a list of n rows of length n, b is a list of n rows of length m
(m right-hand sides). Entries are Fraction (exact) or float. Returns the
n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
an exact singular matrix always raises when tol is 0.
"""
n = len(a)
m = len(b[0]) if n else 0
rows = [list(a[i]) + list(b[i]) for i in range(n)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
if abs(rows[piv][col]) <= tol:
raise ValueError("singular matrix")
rows[col], rows[piv] = rows[piv], rows[col]
pr = rows[col]
inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
for r in range(col + 1, n):
f = rows[r][col]
if f:
f = f * inv
row = rows[r]
for k in range(col, n + m):
if pr[k]:
row[k] -= f * pr[k]
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
row = rows[i]
for k in range(m):
s = row[n + k]
for j in range(i + 1, n):
if row[j]:
s -= row[j] * x[j][k]
x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
return x
def directed_edges(faces):
"""Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
out = {}
for f, tri in enumerate(faces):
for k in range(3):
e = (tri[k], tri[(k + 1) % 3])
if e in out:
raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
out[e] = (f, k)
return out
def neighbours(faces):
"""Map each vertex to the set of its neighbours."""
nb = {}
for tri in faces:
for k in range(3):
i, j = tri[k], tri[(k + 1) % 3]
nb.setdefault(i, set()).add(j)
nb.setdefault(j, set()).add(i)
return nb
def boundary_loop(faces):
"""The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
de = directed_edges(faces)
nxt = {}
for i, j in de:
if (j, i) not in de:
if i in nxt:
raise ValueError("boundary vertex %r is not manifold" % (i,))
nxt[i] = j
if not nxt:
raise ValueError("the mesh has no boundary")
start = min(nxt)
loop = [start]
while True:
v = nxt[loop[-1]]
if v == start:
break
loop.append(v)
if len(loop) != len(nxt):
raise ValueError("the boundary has more than one loop")
return loop
def euler_characteristic(faces):
verts = {v for tri in faces for v in tri}
edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
return len(verts) - len(edges) + len(faces)
test_metro_mesh_comparison.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/metro-mesh-comparison/. The authors are listed in prov/YBB4K3.jsonl.
import math
import random
from fractions import Fraction
from metro_mesh_comparison import (
UniformGrid,
brute_force_dist2,
dist2_point_triangle,
metro,
monte_carlo_samples,
one_sided,
subdivision_samples,
)
from mp3geom import cross, dot, sub
SQUARE = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
SQUARE_FACES = [(0, 1, 2), (0, 2, 3)]
def segment_dist2(p, a, b):
ab, ap = sub(b, a), sub(p, a)
t = min(max(Fraction(dot(ap, ab), dot(ab, ab)), 0), 1)
d = tuple(x - (y + t * z) for x, y, z in zip(p, a, ab))
return dot(d, d)
def reference_dist2(p, a, b, c):
"""Exact distance by another route: the plane if the foot is inside, else the three edges."""
n = cross(sub(b, a), sub(c, a))
nn = dot(n, n)
s = Fraction(dot(n, sub(p, a)), nn)
q = tuple(x - s * y for x, y in zip(p, n))
inside = all(dot(cross(sub(v, u), sub(q, u)), n) >= 0 for u, v in ((a, b), (b, c), (c, a)))
if inside:
return s * s * nn
return min(segment_dist2(p, a, b), segment_dist2(p, b, c), segment_dist2(p, c, a))
def random_mesh(rng, n_faces, size=6):
points = [tuple(rng.randint(-size, size) for _ in range(3)) for _ in range(n_faces + 2)]
faces = []
while len(faces) < n_faces:
f = tuple(rng.sample(range(len(points)), 3))
a, b, c = (points[v] for v in f)
if cross(sub(b, a), sub(c, a)) != (0, 0, 0):
faces.append(f)
return points, faces
def test_point_triangle_distance_is_exact() -> None:
rng = random.Random(1998)
for _ in range(3000):
while True:
a, b, c = (tuple(rng.randint(-5, 5) for _ in range(3)) for _ in range(3))
if cross(sub(b, a), sub(c, a)) != (0, 0, 0):
break
p = tuple(Fraction(rng.randint(-40, 40), 4) for _ in range(3))
assert dist2_point_triangle(p, a, b, c) == reference_dist2(p, a, b, c)
# the corners, edge points and inner points of the triangle are at distance 0
a, b, c = (0, 0, 0), (4, 0, 0), (0, 4, 0)
for p in (a, b, c, (2, 0, 0), (2, 2, 0), (1, 1, 0)):
assert dist2_point_triangle(p, a, b, c) == 0
def test_grid_equals_brute_force() -> None:
rng = random.Random(7)
for h in (1, 2, Fraction(5, 2)):
points, faces = random_mesh(rng, 25)
grid = UniformGrid(points, faces, h)
for _ in range(120):
p = tuple(Fraction(rng.randint(-60, 60), 5) for _ in range(3))
assert grid.dist2(p) == brute_force_dist2(p, points, faces)
def test_parallel_squares() -> None:
up = [(x, y, Fraction(1, 2)) for x, y, _ in SQUARE]
ab, ba, sym = metro(SQUARE, SQUARE_FACES, up, SQUARE_FACES, k=4, n=200)
for maximum, mean, rms in (ab, ba):
assert maximum == mean == rms == 0.5
assert sym == 0.5
def test_square_against_half_square() -> None:
# The corner (1, 1, 0) of the square is sqrt(2)/2 from the triangle, and the triangle lies on the square.
half = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
ab, ba, sym = metro(SQUARE, SQUARE_FACES, half, [(0, 1, 2)], k=4, n=200)
assert ab[0] == math.sqrt(2) / 2
assert ba == (0.0, 0.0, 0.0)
assert sym == math.sqrt(2) / 2
def test_tilted_plane_mean_and_rms() -> None:
# B lies in the plane z = x / 2. A point (x, y, 0) of A is x / sqrt(5) from it, and its foot is inside B.
tilted = [(0, 0, 0), (1, 0, Fraction(1, 2)), (1, 1, Fraction(1, 2)), (0, 1, 0)]
samples = monte_carlo_samples(SQUARE, SQUARE_FACES, 3000, random.Random(17))
maximum, mean, rms = one_sided(samples + subdivision_samples(SQUARE, SQUARE_FACES, 8), tilted, SQUARE_FACES)
assert maximum == math.sqrt(Fraction(1, 5)) # exact sample at x = 1
assert abs(mean - 1 / (2 * math.sqrt(5))) < 0.01 # the true mean; 0.01 is about 4 standard errors
assert abs(rms - math.sqrt(1 / 15)) < 0.01
def test_refinement_sandwich() -> None:
# sampled(k) <= sampled(2k) <= the true one-sided distance <= sampled(k) + the longest sub-triangle edge
rng = random.Random(3)
for _ in range(4):
pa, fa = random_mesh(rng, 4)
pb, fb = random_mesh(rng, 6)
longest = max(math.sqrt(dot(sub(pa[f[i]], pa[f[(i + 1) % 3]]), sub(pa[f[i]], pa[f[(i + 1) % 3]]))) for f in fa for i in range(3))
k = 3
lo = one_sided(subdivision_samples(pa, fa, k), pb, fb)[0]
hi = one_sided(subdivision_samples(pa, fa, 2 * k), pb, fb)[0]
assert lo <= hi + 1e-12
assert hi <= lo + longest / k + 1e-12
def test_float_fails_on_a_sliver() -> None:
# A triangle of length 2 and width 1e-15: in doubles the region tests and the division lose all digits.
a, b = (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)
c = (1.9875242733132161, 8.342347734145901e-16, 7.384876595764672e-16)
p = (0.5196353826017766, 0.3307482815418452, -0.24314659152190998)
exact = dist2_point_triangle(tuple(map(Fraction, p)), *(tuple(map(Fraction, v)) for v in (a, b, c)))
assert exact == reference_dist2(tuple(map(Fraction, p)), *(tuple(map(Fraction, v)) for v in (a, b, c)))
error = abs(math.sqrt(dist2_point_triangle(p, a, b, c)) - math.sqrt(exact))
assert error > 0.02 # measured 0.0251
def test_grid_and_brute_force_give_the_same_report() -> None:
rng = random.Random(11)
pa, fa = random_mesh(rng, 6)
pb, fb = random_mesh(rng, 8)
assert metro(pa, fa, pb, fb, k=3, n=100) == metro(pa, fa, pb, fb, k=3, n=100, h=2)
History
The Hausdorff distance goes back to Felix Hausdorff's 1914 book on set theory. Mesh simplification grew fast in the 1990s, and papers measured their error in different ways, often only at the vertices. Cignoni, Rocchini and Scopigno released Metro in 1998 at the CNR in Pisa as a free tool that made the comparison uniform, with sampling of the first surface, a uniform grid for the distance queries, and a coloured map of the error on the surface. It became the usual way to report the error of simplified meshes. Aspert, Santa-Cruz and Ebrahimi described the similar tool MESH in 2002, and the Metro code later became part of the VCG library and of MeshLab.
References
- Paolo Cignoni, Claudio Rocchini and Roberto Scopigno, Metro, measuring error on simplified surfaces, Computer Graphics Forum 17(2), 1998, 167 to 174, the one-sided and symmetric Hausdorff distance, the mean error, the sampling of the first surface (similar-triangle subdivision, Monte Carlo, scan conversion), and the uniform grid for distance queries
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 7, Simplification and Approximation (the error metrics of simplification; general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YBB4K3 Edit this page History Report an error Markdown