mod boundary;
mod collapse;
mod constraint;
mod contraction;
mod face_map;
#[cfg(test)]
mod invariants;
mod overlay;
use super::{
AlumPolyMesh, CollapseGate, DecimateReport, DecimateStats, DecimateTarget, Placement, Quadric,
QuadricKind, StarFace, Structural, candidate_positions, quadric_of_vertex, run_decimation,
set_boundary_locks,
};
use crate::geom3::half_edge3::HalfEdgeMesh3;
use crate::{Result, Vector3};
use alum::{HH, Handle, HasIterators, HasTopology, VH};
use boundary::boundary_chain;
use collapse::{Collapse, ErrorRule};
use constraint::ErrorBound;
use contraction::Contraction;
use face_map::AffineFaceMap;
use overlay::ProjectedOverlay;
use std::f64::consts::PI;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ErrorMethod {
Contraction,
AffineFaceMap,
#[default]
ProjectedOverlay,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DecimateOpts {
pub tol: f64,
pub max_normal_deviation: f64,
pub min_aspect: f64,
pub lock_boundary: bool,
pub boundary_tol: Option<f64>,
pub placement: Placement,
pub target: DecimateTarget,
pub quadric: QuadricKind,
pub error_method: ErrorMethod,
}
impl Default for DecimateOpts {
fn default() -> Self {
Self {
tol: 0.0,
max_normal_deviation: PI / 4.0,
min_aspect: 0.01,
lock_boundary: true,
boundary_tol: None,
placement: Placement::Optimal,
target: DecimateTarget::ToTolerance,
quadric: QuadricKind::Triangle,
error_method: ErrorMethod::ProjectedOverlay,
}
}
}
impl DecimateOpts {
pub fn to_tolerance(tol: f64) -> Self {
Self {
tol,
target: DecimateTarget::ToTolerance,
..Default::default()
}
}
pub fn to_face_count(tol: f64, faces: usize) -> Self {
Self {
tol,
target: DecimateTarget::FaceCount(faces),
..Default::default()
}
}
pub fn to_ratio(tol: f64, ratio: f64) -> Self {
Self {
tol,
target: DecimateTarget::Ratio(ratio),
..Default::default()
}
}
pub fn with_max_normal_deviation(mut self, value: f64) -> Self {
self.max_normal_deviation = value;
self
}
pub fn with_min_aspect(mut self, value: f64) -> Self {
self.min_aspect = value;
self
}
pub fn with_lock_boundary(mut self, value: bool) -> Self {
self.lock_boundary = value;
self
}
pub fn with_boundary_tol(mut self, value: f64) -> Self {
self.boundary_tol = Some(value);
self
}
pub fn with_placement(mut self, value: Placement) -> Self {
self.placement = value;
self
}
pub fn with_quadric(mut self, value: QuadricKind) -> Self {
self.quadric = value;
self
}
pub fn with_error_method(mut self, value: ErrorMethod) -> Self {
self.error_method = value;
self
}
fn validate(&self) -> Result<()> {
if self.tol.is_nan() || self.tol <= 0.0 {
return Err(
format!("A decimation tolerance must be positive, got {}", self.tol).into(),
);
}
if self.max_normal_deviation.is_nan() || self.max_normal_deviation <= 0.0 {
return Err("The maximum normal deviation must be positive".into());
}
if let Some(t) = self.boundary_tol
&& (t.is_nan() || t <= 0.0)
{
return Err("A boundary tolerance must be positive".into());
}
self.target.validate()
}
}
pub(crate) struct Accepted {
position: Vector3,
quadric: Quadric,
cost: f64,
error: f64,
tolerance: f64,
}
pub struct ToleranceVolumeDecimator {
opts: DecimateOpts,
quadrics: Vec<Quadric>,
error: alum::VProperty<f64>,
tolerance: alum::VProperty<f64>,
pinned: Vec<bool>,
structural: Structural,
}
const ERROR_PROP: &str = "engeom_decimate_error";
const TOLERANCE_PROP: &str = "engeom_decimate_tolerance";
impl ToleranceVolumeDecimator {
pub fn new(mesh: &mut HalfEdgeMesh3, opts: DecimateOpts) -> Result<Self> {
opts.validate()?;
let error = mesh.vertex_prop_f64(ERROR_PROP, 0.0)?;
let mut tolerance = mesh.vertex_prop_f64(TOLERANCE_PROP, opts.tol)?;
{
let inner = mesh.as_alum();
let mut tol = tolerance
.try_borrow_mut()
.map_err(|_| "Failed to borrow the tolerance volume")?;
for v in inner.vertices() {
tol[v] = match opts.boundary_tol {
Some(t) if v.is_boundary(inner) => t,
_ => opts.tol,
};
}
}
let inner = mesh.as_alum();
let pinned = {
let vstatus = inner.vertex_status_prop();
let vstatus = vstatus
.try_borrow()
.map_err(|_| "Failed to borrow vertex status")?;
inner.vertices().map(|v| vstatus[v].feature()).collect()
};
let mut quadrics = vec![Quadric::default(); inner.num_vertices()];
for v in inner.vertices() {
quadrics[v.index() as usize] = quadric_of_vertex(inner, v, opts.quadric)?;
}
Ok(Self {
opts,
quadrics,
error,
tolerance,
pinned,
structural: Structural::new(opts.max_normal_deviation, opts.min_aspect),
})
}
fn candidates(&self, q: &Quadric, v2: VH, p1: Vector3, p2: Vector3) -> Vec<Vector3> {
let pinned = self
.pinned
.get(v2.index() as usize)
.copied()
.unwrap_or(false);
candidate_positions(self.opts.placement, pinned, q, p1, p2)
}
fn budget(&self, mesh: &AlumPolyMesh, v1: VH, v2: VH, e: &[f64], t: &[f64]) -> Option<f64> {
let mut budget = t[v1.index() as usize].min(t[v2.index() as usize]);
for v in mesh.vv_ccw_iter(v1).chain(mesh.vv_ccw_iter(v2)) {
budget = budget.min(t[v.index() as usize]);
}
for v in mesh.vv_ccw_iter(v1).chain(mesh.vv_ccw_iter(v2)) {
if v != v1 && v != v2 && e[v.index() as usize] > budget {
return None;
}
}
Some(budget)
}
fn accept(&self, c: &Collapse<'_>, budget: f64) -> Option<f64> {
let bound = match self.opts.error_method {
ErrorMethod::Contraction => Contraction.bound(c),
ErrorMethod::AffineFaceMap => AffineFaceMap.bound(c),
ErrorMethod::ProjectedOverlay => {
let overlay = ProjectedOverlay.bound(c);
if c.outline.parts_regions(c.p0) {
let mine = match overlay {
ErrorBound::Bound(v) => Some(v),
_ => {
self.structural.bump_not_applicable();
None
}
};
let theirs = match AffineFaceMap.bound(c) {
ErrorBound::Bound(v) => Some(v),
_ => None,
};
match mine.into_iter().chain(theirs).reduce(f64::min) {
Some(v) => ErrorBound::Bound(v),
None => ErrorBound::Unsatisfiable,
}
} else {
match overlay {
ErrorBound::NotApplicable => {
self.structural.bump_not_applicable();
AffineFaceMap.bound(c)
}
settled => settled,
}
}
}
};
let error = match bound {
ErrorBound::Bound(v) => v,
ErrorBound::Unsatisfiable | ErrorBound::NotApplicable => {
self.structural.bump_error_veto();
return None;
}
};
if error > budget {
self.structural.bump_error_veto();
return None;
}
Some(error)
}
fn evaluate(&self, mesh: &AlumPolyMesh, h: HH) -> Option<Accepted> {
self.structural.bump_evaluation();
let v1 = h.tail(mesh);
let v2 = h.head(mesh);
let points = mesh.points();
let points = points.try_borrow().ok()?;
let e = self.error.try_borrow().ok()?;
let t = self.tolerance.try_borrow().ok()?;
let p1 = points[v1];
let p2 = points[v2];
let q = self.quadrics[v1.index() as usize] + self.quadrics[v2.index() as usize];
let star = self.structural.stars(mesh, v1, v2, &points)?;
if star.is_empty() {
return None;
}
let budget = match self.budget(mesh, v1, v2, &e, &t) {
Some(b) => b,
None => {
self.structural.bump_error_veto();
return None;
}
};
let outline = boundary_chain(&star, v1, v2);
for candidate in self.candidates(&q, v2, p1, p2) {
self.structural.bump_acceptance();
let Some(new) = self.structural.reshape(&star, v1, v2, candidate, &points) else {
continue;
};
let c = Collapse {
star: &star,
new: &new,
points: &points,
e: &e,
v1,
v2,
p0: candidate,
outline,
};
if let Some(error) = self.accept(&c, budget) {
return Some(Accepted {
position: candidate,
quadric: q,
cost: q.residual(candidate),
error,
tolerance: budget,
});
}
}
None
}
}
impl CollapseGate for ToleranceVolumeDecimator {
type Accepted = Accepted;
fn evaluate(&self, mesh: &AlumPolyMesh, h: HH) -> Option<Accepted> {
ToleranceVolumeDecimator::evaluate(self, mesh, h)
}
fn cost(accepted: &Accepted) -> f64 {
accepted.cost
}
fn position(accepted: &Accepted) -> Vector3 {
accepted.position
}
fn commit(&mut self, v: VH, accepted: Accepted) -> Result<()> {
self.quadrics[v.index() as usize] = accepted.quadric;
let mut e = self
.error
.try_borrow_mut()
.map_err(|_| "Failed to borrow the error volume")?;
let mut t = self
.tolerance
.try_borrow_mut()
.map_err(|_| "Failed to borrow the tolerance volume")?;
e[v] = accepted.error;
t[v] = accepted.tolerance;
Ok(())
}
fn stats(&self) -> DecimateStats {
self.structural.stats.get()
}
}
impl HalfEdgeMesh3 {
pub fn decimate_guaranteed(&mut self, opts: &DecimateOpts) -> Result<DecimateReport> {
if self.error_volume_stale() {
return Err(
"A guaranteed decimation cannot follow a best-effort one on the same \
mesh: the error volume it reasons from no longer accounts for what the \
best-effort pass moved, so its bound would not be a bound. Rebuild the half-edge \
mesh if that result is meant to be the new reference."
.into(),
);
}
opts.validate()?;
set_boundary_locks(self, opts.lock_boundary)?;
let mut gate = ToleranceVolumeDecimator::new(self, *opts)?;
run_decimation(self, &mut gate, opts.target)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geom3::half_edge3::RepairOpts;
use crate::geom3::half_edge3::difference::ShapeDifference;
use crate::{Mesh3, Point3};
use std::sync::OnceLock;
fn deviation(original: &Mesh3, decimated: &Mesh3) -> ShapeDifference {
ShapeDifference::new(original, decimated).unwrap()
}
const BLADE_TOL: f64 = 0.05;
fn flat_grid(n: usize) -> Mesh3 {
let mut points = Vec::new();
for i in 0..=n {
for j in 0..=n {
points.push(Point3::new(i as f64, j as f64, 0.0));
}
}
let mut faces = Vec::new();
let idx = |i: usize, j: usize| (i * (n + 1) + j) as u32;
for i in 0..n {
for j in 0..n {
faces.push([idx(i, j), idx(i + 1, j), idx(i + 1, j + 1)]);
faces.push([idx(i, j), idx(i + 1, j + 1), idx(i, j + 1)]);
}
}
Mesh3::new(points, faces, false)
}
fn decimate_blade(opts: &DecimateOpts) -> (Mesh3, Mesh3, DecimateReport) {
static DEFAULT_RUN: OnceLock<(Mesh3, Mesh3, DecimateReport)> = OnceLock::new();
if *opts == DecimateOpts::to_tolerance(BLADE_TOL) {
return DEFAULT_RUN
.get_or_init(|| decimate_blade_uncached(opts))
.clone();
}
decimate_blade_uncached(opts)
}
fn decimate_blade_uncached(opts: &DecimateOpts) -> (Mesh3, Mesh3, DecimateReport) {
let original = crate::tests::engine_blade();
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
let report = he.decimate_guaranteed(opts).unwrap();
let out = Mesh3::try_from(&he).unwrap();
(original, out, report)
}
#[test]
fn both_directions_are_within_tolerance() {
for tol in [0.001, 0.01, 0.05, 0.1, 0.5, 1.0] {
let (original, out, _) = decimate_blade(&DecimateOpts::to_tolerance(tol));
deviation(&original, &out).assert_within(tol);
}
}
#[test]
fn the_overlay_is_what_makes_a_tight_tolerance_usable() {
let tol = BLADE_TOL;
let opts = DecimateOpts::to_tolerance(tol);
let mut faces = Vec::new();
for method in [
ErrorMethod::Contraction,
ErrorMethod::AffineFaceMap,
ErrorMethod::ProjectedOverlay,
] {
let (original, out, report) = decimate_blade(&opts.with_error_method(method));
let d = deviation(&original, &out);
assert!(d.hausdorff() <= tol, "{:?} broke the bound: {}", method, d);
faces.push((method, report.faces_after));
}
let overlay = faces[2].1;
for (method, count) in faces.iter().take(2) {
assert!(
overlay * 2 < *count,
"the overlay ({}) should be far ahead of {:?} ({})",
overlay,
method,
count
);
}
}
#[test]
fn every_method_holds_the_bound() {
for method in [
ErrorMethod::Contraction,
ErrorMethod::AffineFaceMap,
ErrorMethod::ProjectedOverlay,
] {
for tol in [0.01, 0.05, 0.5] {
let opts = DecimateOpts::to_tolerance(tol).with_error_method(method);
let (original, out, _) = decimate_blade(&opts);
let d = deviation(&original, &out);
assert!(
d.hausdorff() <= tol,
"{:?} broke the bound at tol={}: {}",
method,
tol,
d
);
}
}
}
#[test]
fn a_flat_region_decimates_at_any_tolerance() {
let plane = flat_grid(20);
let mut he = HalfEdgeMesh3::try_from(&plane).unwrap();
let report = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(1.0e-6))
.unwrap();
let out = Mesh3::try_from(&he).unwrap();
assert!(
report.ratio() < 0.2,
"a plane should flatten at any tolerance, got {}",
report
);
assert!(
deviation(&plane, &out).hausdorff() < 1.0e-9,
"collapsing within a plane must not move the surface"
);
}
#[test]
fn a_locked_boundary_never_reaches_the_fallback() {
let plane = flat_grid(20);
let mut he = HalfEdgeMesh3::try_from(&plane).unwrap();
let report = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(1.0e-6))
.unwrap();
assert_eq!(
report.stats.method_not_applicable, 0,
"the overlay should judge every one of these unaided: {}",
report.stats
);
assert!(report.ratio() < 0.2, "expected real decimation: {}", report);
}
#[test]
fn the_budget_is_nearly_spent() {
let (original, out, report) = decimate_blade(&DecimateOpts::to_tolerance(BLADE_TOL));
let d = deviation(&original, &out);
let ratio = d.hausdorff() / BLADE_TOL;
assert!(ratio <= 1.0, "over the bound: {}", d);
assert!(ratio > 0.5, "leaving most of the budget unused: {}", d);
assert!(
report.ratio() < 0.85,
"expected real decimation, got {}",
report
);
}
#[test]
fn a_tighter_tolerance_decimates_less() {
let (original, coarse, coarse_report) =
decimate_blade(&DecimateOpts::to_tolerance(BLADE_TOL));
let (_, fine, fine_report) = decimate_blade(&DecimateOpts::to_tolerance(BLADE_TOL / 5.0));
assert!(fine_report.faces_after > coarse_report.faces_after);
assert!(deviation(&original, &fine).hausdorff() <= BLADE_TOL / 5.0);
assert!(deviation(&original, &coarse).hausdorff() <= BLADE_TOL);
}
#[test]
fn endpoint_placement_keeps_the_points_a_subset() {
let original = Mesh3::create_sphere(10.0, 0.06).unwrap();
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
he.decimate_guaranteed(
&DecimateOpts::to_tolerance(0.5).with_placement(Placement::Endpoint),
)
.unwrap();
let out = Mesh3::try_from(&he).unwrap();
assert!(out.points().len() < original.points().len());
for p in out.points() {
let d = original
.points()
.iter()
.map(|o| (o - p).norm())
.fold(f64::INFINITY, f64::min);
assert!(d < 1e-12, "point {:?} was not one of the originals", p);
}
}
#[test]
fn a_locked_boundary_is_preserved() {
let original = crate::tests::stanford_bun_4();
let (mut he, _) =
HalfEdgeMesh3::from_mesh_repaired(&original, &RepairOpts::default()).unwrap();
let before = Mesh3::try_from(&he).unwrap();
let boundary_before = before.compute_nav().boundary_vertices(None).len();
he.decimate_guaranteed(&DecimateOpts::to_tolerance(0.02))
.unwrap();
let after = Mesh3::try_from(&he).unwrap();
let boundary_after = after.compute_nav().boundary_vertices(None).len();
assert_eq!(
boundary_before, boundary_after,
"a locked boundary should not lose vertices"
);
let moved = deviation(&before, &after).boundary.unwrap();
assert!(
moved < 1.0e-12,
"a locked boundary should not move at all, but the outline shifted by {}",
moved
);
}
#[test]
fn a_later_run_can_unlock_a_previously_locked_boundary() {
let plane = flat_grid(12);
let mut he = HalfEdgeMesh3::try_from(&plane).unwrap();
he.decimate_guaranteed(&DecimateOpts::to_tolerance(1.0e-6))
.unwrap();
let locked = Mesh3::try_from(&he).unwrap();
let boundary_locked = locked.compute_nav().boundary_vertices(None).len();
he.decimate_guaranteed(&DecimateOpts::to_tolerance(1.0e-6).with_lock_boundary(false))
.unwrap();
let unlocked = Mesh3::try_from(&he).unwrap();
let boundary_unlocked = unlocked.compute_nav().boundary_vertices(None).len();
assert!(
boundary_unlocked < boundary_locked,
"the second run asked for a free boundary and should have simplified the outline, \
but it stayed at {} vertices",
boundary_locked
);
}
#[test]
fn an_unlocked_boundary_can_collapse() {
let original = crate::tests::stanford_bun_4();
let (mut he, _) =
HalfEdgeMesh3::from_mesh_repaired(&original, &RepairOpts::default()).unwrap();
let before = Mesh3::try_from(&he).unwrap();
let boundary_before = before.compute_nav().boundary_vertices(None).len();
he.decimate_guaranteed(&DecimateOpts::to_tolerance(0.02).with_lock_boundary(false))
.unwrap();
let after = Mesh3::try_from(&he).unwrap();
let boundary_after = after.compute_nav().boundary_vertices(None).len();
assert!(boundary_after < boundary_before);
}
#[test]
fn an_unlocked_boundary_still_holds_the_bound() {
let original = crate::tests::stanford_bun_4();
for method in [
ErrorMethod::Contraction,
ErrorMethod::AffineFaceMap,
ErrorMethod::ProjectedOverlay,
] {
for tol in [0.005, 0.02, 0.1] {
let (mut he, _) =
HalfEdgeMesh3::from_mesh_repaired(&original, &RepairOpts::default()).unwrap();
let before = Mesh3::try_from(&he).unwrap();
let report = he
.decimate_guaranteed(
&DecimateOpts::to_tolerance(tol)
.with_lock_boundary(false)
.with_error_method(method),
)
.unwrap();
let after = Mesh3::try_from(&he).unwrap();
assert!(
report.ratio() < 0.9,
"{:?} at tol={} did nothing: {}",
method,
tol,
report
);
let d = deviation(&before, &after);
assert!(
d.hausdorff() <= tol,
"{:?} broke the bound at tol={} with the boundary unlocked: {}",
method,
tol,
d
);
}
}
}
#[test]
fn repeated_runs_do_not_compound_error() {
let original = crate::tests::engine_blade();
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
for _ in 0..3 {
he.decimate_guaranteed(&DecimateOpts::to_tolerance(BLADE_TOL))
.unwrap();
}
let out = Mesh3::try_from(&he).unwrap();
let d = deviation(&original, &out);
assert!(d.hausdorff() <= BLADE_TOL, "three runs drifted to {}", d);
}
#[test]
fn a_second_run_continues_from_the_first() {
let original = crate::tests::engine_blade();
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
let first = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(BLADE_TOL))
.unwrap();
let second = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(BLADE_TOL))
.unwrap();
assert_eq!(second.faces_before, first.faces_after);
assert!(
second.faces_after <= second.faces_before,
"a second run grew the mesh: {}",
second
);
}
#[test]
fn invalid_options_are_rejected() {
let original = crate::tests::engine_blade();
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
assert!(
he.decimate_guaranteed(&DecimateOpts::to_tolerance(0.0))
.is_err()
);
assert!(
he.decimate_guaranteed(&DecimateOpts::to_tolerance(-1.0))
.is_err()
);
assert!(
he.decimate_guaranteed(&DecimateOpts::to_ratio(0.01, 0.0))
.is_err()
);
assert!(
he.decimate_guaranteed(&DecimateOpts::to_ratio(0.01, 1.5))
.is_err()
);
}
#[test]
fn both_quadric_kinds_respect_the_bound() {
for kind in [QuadricKind::Triangle, QuadricKind::Probabilistic] {
let (original, out, report) =
decimate_blade(&DecimateOpts::to_tolerance(BLADE_TOL).with_quadric(kind));
let d = deviation(&original, &out);
assert!(d.hausdorff() <= BLADE_TOL, "{:?} drifted to {}", kind, d);
assert!(report.ratio() < 0.95, "{:?} did nothing: {}", kind, report);
}
}
#[test]
#[ignore = "measurement harness, not a correctness test"]
fn decimate_profile() {
let original = crate::tests::engine_blade();
println!(
"\nengine-blade: {} faces, {} points\n",
original.faces().len(),
original.points().len()
);
for tol in [0.001, 0.005, 0.01, 0.05, 0.1, 0.5] {
for method in [
ErrorMethod::Contraction,
ErrorMethod::AffineFaceMap,
ErrorMethod::ProjectedOverlay,
] {
println!("--- {:?}", method);
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
let start = std::time::Instant::now();
let report = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(tol).with_error_method(method))
.unwrap();
let elapsed = start.elapsed();
let out = Mesh3::try_from(&he).unwrap();
let d = deviation(&original, &out);
let verdict = if d.hausdorff() <= tol { "OK " } else { "OVER" };
let (rev, fwd) = (d.dense.reference_to_test, d.dense.test_to_reference);
println!(
"{verdict} tol={tol:<7} {report} rev={rev:.6} ({:.1}x) fwd={fwd:.6} ({:.1}x) \
[{elapsed:?}]",
rev / tol,
fwd / tol
);
println!(" {}", report.stats);
println!(
" acceptance tests per collapse: {:.1}, evaluations per collapse: {:.1}",
report.stats.acceptance_tests as f64 / report.collapses.max(1) as f64,
report.stats.evaluations as f64 / report.collapses.max(1) as f64,
);
}
}
}
#[test]
#[ignore = "measurement harness, not a correctness test"]
fn fallback_rate() {
fn report_on(label: &str, build: impl Fn() -> HalfEdgeMesh3, tol: f64) {
run(label, build, tol, true);
}
fn run(label: &str, build: impl Fn() -> HalfEdgeMesh3, tol: f64, lock: bool) {
let mut he = build();
let before = Mesh3::try_from(&he).unwrap();
let open = before.compute_nav().boundary_vertices(None).len();
let open = 100.0 * open as f64 / before.points().len().max(1) as f64;
let report = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(tol).with_lock_boundary(lock))
.unwrap();
let s = report.stats;
let rate = 100.0 * s.method_not_applicable as f64 / s.acceptance_tests.max(1) as f64;
println!(
"{label:<16} tol={tol:<8} lock={lock:<5} boundary {open:>5.1}% {report}\n \
{} of {} acceptance tests fell back ({rate:.3}%)",
s.method_not_applicable, s.acceptance_tests,
);
}
println!();
let blade = crate::tests::engine_blade();
for tol in [0.001, 0.005, 0.01, 0.05, 0.1, 0.5] {
report_on(
"engine-blade",
|| HalfEdgeMesh3::try_from(&blade).unwrap(),
tol,
);
}
let bunny = crate::tests::stanford_bun_4();
for tol in [0.005, 0.02, 0.1] {
report_on(
"stanford-bunny",
|| {
HalfEdgeMesh3::from_mesh_repaired(&bunny, &RepairOpts::default())
.unwrap()
.0
},
tol,
);
}
for n in [20usize, 60] {
let plane = flat_grid(n);
report_on(
&format!("flat-grid-{n}"),
|| HalfEdgeMesh3::try_from(&plane).unwrap(),
1.0e-6,
);
}
println!("\n--- boundary unlocked, which is Gueziec's Type I collapse");
for n in [20usize, 60] {
let plane = flat_grid(n);
run(
&format!("flat-grid-{n}"),
|| HalfEdgeMesh3::try_from(&plane).unwrap(),
1.0e-6,
false,
);
}
for tol in [0.005, 0.02, 0.1] {
run(
"stanford-bunny",
|| {
HalfEdgeMesh3::from_mesh_repaired(&bunny, &RepairOpts::default())
.unwrap()
.0
},
tol,
false,
);
}
}
#[test]
#[ignore = "measurement harness, not a correctness test"]
fn error_volume_slack() {
let original = crate::tests::engine_blade();
for tol in [0.1, 0.5, 1.0] {
let mut he = HalfEdgeMesh3::try_from(&original).unwrap();
let report = he
.decimate_guaranteed(&DecimateOpts::to_tolerance(tol))
.unwrap();
let mut radii = he.vertex_prop_f64(ERROR_PROP, 0.0).unwrap();
let mut radii: Vec<f64> = {
let r = radii.try_borrow_mut().unwrap();
r.iter().copied().collect()
};
radii.sort_by(|a, b| a.partial_cmp(b).unwrap());
let at = |q: f64| radii[((radii.len() - 1) as f64 * q) as usize];
let out = Mesh3::try_from(&he).unwrap();
let d = deviation(&original, &out);
println!(
"tol={tol:<5} {report}\n radii: median {:.6} p90 {:.6} max {:.6} \
measured {:.6} ({:.0}% of the worst radius)",
at(0.5),
at(0.9),
at(1.0),
d.hausdorff(),
100.0 * d.hausdorff() / at(1.0).max(f64::MIN_POSITIVE)
);
}
}
}