use crate::error::Result;
use super::delaunay::{Boundary, EdgeFan, TetMesh};
use super::fill::{delaunay_fill, fill, Constraints, DEFAULT_BUDGET};
use super::predicates::orient3d;
use super::recovery::Protected;
const OPPORTUNIST_BUDGET: usize = 400;
pub type Accept<'a> = &'a dyn Fn(&TetMesh, &[[u32; 4]]) -> bool;
pub fn flip23(mesh: &mut TetMesh, t: usize, i: usize) -> Result<Option<Vec<u32>>> {
let Some(n) = mesh.neighbour(t, i) else {
return Ok(None);
};
let f = mesh.face(t, i);
let d = mesh.tet(t).expect("live cell")[i];
let Some(e) = mesh.apex_beyond(n, &f) else {
return Ok(None);
};
let new = [[f[0], f[1], d, e], [f[1], f[2], d, e], [f[2], f[0], d, e]];
if new.iter().any(|v| mesh.orientation(v) <= 0.0) {
return Ok(None); }
mesh.replace_region(&[t as u32, n as u32], &new, "a 2-3 flip")
.map(Some)
}
#[allow(dead_code)] pub fn flip32(mesh: &mut TetMesh, u: u32, v: u32) -> Result<Option<Vec<u32>>> {
let Some(ring) = mesh.tets_around_edge(u, v) else {
return Ok(None);
};
if ring.len() != 3 {
return Ok(None);
}
let mut outer: Vec<u32> = Vec::with_capacity(3);
for &t in &ring {
for x in mesh.tet(t as usize).expect("live ring cell") {
if x != u && x != v && !outer.contains(&x) {
outer.push(x);
}
}
}
if outer.len() != 3 {
return Ok(None);
}
let (a, b, c) = (outer[0], outer[1], outer[2]);
let su = mesh.orientation(&[a, b, c, u]);
let sv = mesh.orientation(&[a, b, c, v]);
let new = if su > 0.0 && sv < 0.0 {
[[a, b, c, u], [a, c, b, v]]
} else if su < 0.0 && sv > 0.0 {
[[a, b, c, v], [a, c, b, u]]
} else {
return Ok(None);
};
mesh.replace_region(&ring, &new, "a 3-2 flip").map(Some)
}
#[allow(dead_code)] pub fn flip22(mesh: &mut TetMesh, p: u32, q: u32) -> Result<Option<Vec<u32>>> {
let fan = mesh.tets_with_edge(p, q);
if fan.len() != 2 {
return Ok(None);
}
let (t1, t2) = (fan[0], fan[1]);
let (c1, c2) = (
mesh.tet(t1 as usize).expect("live fan cell"),
mesh.tet(t2 as usize).expect("live fan cell"),
);
let rest =
|c: &[u32; 4]| -> Vec<u32> { c.iter().copied().filter(|&x| x != p && x != q).collect() };
let (r1, r2) = (rest(&c1), rest(&c2));
let Some(&z) = r1.iter().find(|x| r2.contains(x)) else {
return Ok(None);
};
let (Some(&x), Some(&y)) = (r1.iter().find(|&&a| a != z), r2.iter().find(|&&a| a != z)) else {
return Ok(None);
};
if orient3d(
&mesh.points()[p as usize],
&mesh.points()[q as usize],
&mesh.points()[x as usize],
&mesh.points()[y as usize],
) != 0.0
{
return Ok(None);
}
if !mesh.face_is_free(t1, &[p, q, x]) || !mesh.face_is_free(t2, &[p, q, y]) {
return Ok(None);
}
let sp = mesh.orientation(&[x, y, z, p]);
let sq = mesh.orientation(&[x, y, z, q]);
let new = if sp > 0.0 && sq < 0.0 {
[[x, y, z, p], [y, x, z, q]]
} else if sp < 0.0 && sq > 0.0 {
[[y, x, z, p], [x, y, z, q]]
} else {
return Ok(None);
};
mesh.replace_region_with(&fan, &new, "a 2-2 flip", Boundary::MayRecutHull)
.map(Some)
}
pub fn remove_edge(
mesh: &mut TetMesh,
p: u32,
q: u32,
protect: &Protected<'_>,
max_region: usize,
) -> Result<Option<Vec<u32>>> {
remove_edge_if(mesh, p, q, protect, max_region, None)
}
pub fn remove_edge_if(
mesh: &mut TetMesh,
p: u32,
q: u32,
protect: &Protected<'_>,
max_region: usize,
accept: Option<Accept<'_>>,
) -> Result<Option<Vec<u32>>> {
let Some(fan) = mesh.edge_fan(p, q) else {
return Ok(None);
};
let mut region = fan.cells.clone();
loop {
if let Some(created) = rebuild_without(mesh, p, q, &fan, ®ion, protect, accept)? {
return Ok(Some(created));
}
let wider = grow(mesh, ®ion);
if wider.len() == region.len() || wider.len() > max_region {
return Ok(None);
}
region = wider;
}
}
fn rebuild_without(
mesh: &mut TetMesh,
p: u32,
q: u32,
fan: &EdgeFan,
region: &[u32],
protect: &Protected<'_>,
accept: Option<Accept<'_>>,
) -> Result<Option<Vec<u32>>> {
let mut boundary = mesh.region_boundary(region);
let mode = if fan.closed {
Boundary::Preserved
} else {
let (x0, xn) = (fan.link[0], *fan.link.last().expect("non-empty link"));
let first = *fan.cells.first().expect("non-empty fan");
let last = *fan.cells.last().expect("non-empty fan");
if !mesh.face_is_free(first, &[p, q, x0]) || !mesh.face_is_free(last, &[p, q, xn]) {
return Ok(None);
}
let pts = mesh.points();
if orient3d(
&pts[p as usize],
&pts[q as usize],
&pts[x0 as usize],
&pts[xn as usize],
) != 0.0
{
return Ok(None); }
if protect.holds(&[p, q, x0]) || protect.holds(&[p, q, xn]) {
return Ok(None);
}
let Some(recut) = recut_end_faces(mesh, fan, p, q) else {
return Ok(None);
};
boundary.retain(|f| {
let k = sorted(f);
k != sorted(&[p, q, x0]) && k != sorted(&[p, q, xn])
});
boundary.extend_from_slice(&recut);
Boundary::MayRecutHull
};
let keep = relevant(mesh, region, protect);
let want = Constraints {
without_edges: &[(p, q)],
with_faces: &keep,
..Default::default()
};
let budget = match accept {
Some(_) => OPPORTUNIST_BUDGET,
None => DEFAULT_BUDGET,
};
let Ok(new) = delaunay_fill(mesh.points(), &boundary, want)
.or_else(|_| fill(mesh.points(), &boundary, want, budget).ok_or(()))
else {
return Ok(None);
};
if let Some(accept) = accept
&& !accept(mesh, &new)
{
return Ok(None);
}
match mesh.replace_region_with(region, &new, "an edge removal", mode) {
Ok(created) => Ok(Some(created)),
Err(_) => Ok(None),
}
}
pub fn relevant(mesh: &TetMesh, region: &[u32], protect: &Protected<'_>) -> Vec<[u32; 3]> {
let mut here: Vec<u32> = region
.iter()
.filter_map(|&t| mesh.tet(t as usize))
.flatten()
.collect();
here.sort_unstable();
here.dedup();
let mut out: Vec<[u32; 3]> = here
.iter()
.flat_map(|&x| protect.at(x))
.filter(|f| f.iter().all(|x| here.binary_search(x).is_ok()) && mesh.has_face(f))
.copied()
.collect();
out.sort_unstable();
out.dedup();
out
}
fn grow(mesh: &TetMesh, region: &[u32]) -> Vec<u32> {
let mut out: Vec<u32> = region.to_vec();
for &t in region {
for i in 0..4 {
if let Some(n) = mesh.neighbour(t as usize, i)
&& !out.contains(&(n as u32))
{
out.push(n as u32);
}
}
}
out.sort_unstable();
out
}
fn recut_end_faces(mesh: &TetMesh, fan: &EdgeFan, p: u32, q: u32) -> Option<[[u32; 3]; 2]> {
let (x0, xn) = (fan.link[0], *fan.link.last()?);
let inside = mesh.apex_beyond(*fan.cells.first()? as usize, &[p, q, x0])?;
let facing_out = |f: [u32; 3]| -> [u32; 3] {
let pts = mesh.points();
if orient3d(
&pts[f[0] as usize],
&pts[f[1] as usize],
&pts[f[2] as usize],
&pts[inside as usize],
) < 0.0
{
f
} else {
[f[0], f[2], f[1]]
}
};
Some([facing_out([x0, xn, p]), facing_out([x0, xn, q])])
}
fn sorted(f: &[u32; 3]) -> [u32; 3] {
let mut k = *f;
k.sort_unstable();
k
}
#[cfg(test)]
mod tests {
use super::*;
use crate::interrupt::NoCancel;
fn bipyramid() -> Vec<[f64; 3]> {
vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.2, 0.2, -1.0],
[0.2, 0.2, 1.0],
]
}
fn build(points: &[[f64; 3]]) -> TetMesh {
let mesh = TetMesh::delaunay(points, &NoCancel).unwrap();
assert_eq!(mesh.find_defect(), None);
mesh
}
fn flip_any_face(mesh: &mut TetMesh) -> Option<(usize, usize)> {
for t in 0..mesh.slot_count() {
if mesh.tet(t).is_none() {
continue;
}
for i in 0..4 {
if mesh.neighbour(t, i).is_some() {
let before = mesh.clone();
if flip23(mesh, t, i).unwrap().is_some() {
return Some((t, i));
}
*mesh = before;
}
}
}
None
}
#[test]
fn a_flip_preserves_the_region_and_its_volume() {
let mut mesh = build(&bipyramid());
let volume = mesh.volume();
let cells = mesh.len();
let created = flip_any_face(&mut mesh).map(|_| ()).map(|_| mesh.len());
assert!(created.is_some(), "no flippable face in a bipyramid");
assert_eq!(mesh.find_defect(), None);
assert!((mesh.volume() - volume).abs() < 1e-15, "{}", mesh.volume());
assert_eq!(mesh.len(), cells + 1, "2-3 replaces two cells with three");
}
#[test]
fn the_two_flips_are_inverse() {
let mut mesh = build(&bipyramid());
let before: Vec<[u32; 4]> = mesh.iter().map(|(_, v)| v).collect();
let volume = mesh.volume();
let (t, i) = flip_any_face(&mut mesh).expect("a flippable face");
let _ = (t, i);
let (_, v0) = mesh.iter().next().unwrap();
let mut undone = false;
'search: for a in 0..4 {
for b in a + 1..4 {
let mut probe = mesh.clone();
if flip32(&mut probe, v0[a], v0[b]).unwrap().is_some() {
mesh = probe;
undone = true;
break 'search;
}
}
}
assert!(undone, "the 2-3 flip could not be undone");
assert_eq!(mesh.find_defect(), None);
assert!((mesh.volume() - volume).abs() < 1e-15);
let after: Vec<[u32; 4]> = mesh.iter().map(|(_, v)| v).collect();
assert_eq!(after.len(), before.len());
let key = |cells: &[[u32; 4]]| {
let mut k: Vec<[u32; 4]> = cells
.iter()
.map(|v| {
let mut s = *v;
s.sort_unstable();
s
})
.collect();
k.sort_unstable();
k
};
assert_eq!(key(&after), key(&before));
}
#[test]
fn a_boundary_face_cannot_be_flipped() {
let mut mesh = build(&bipyramid());
let mut refused = 0;
for t in 0..mesh.slot_count() {
if mesh.tet(t).is_none() {
continue;
}
for i in 0..4 {
if mesh.neighbour(t, i).is_none() {
assert!(flip23(&mut mesh, t, i).unwrap().is_none());
refused += 1;
}
}
}
assert!(refused > 0, "a bipyramid has boundary faces");
assert_eq!(mesh.find_defect(), None);
}
#[test]
fn a_non_convex_pair_is_refused() {
let points = vec![
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[4.0, 4.0, -0.1],
];
let mut mesh = build(&points);
let before: Vec<[u32; 4]> = mesh.iter().map(|(_, v)| v).collect();
let volume = mesh.volume();
for t in 0..mesh.slot_count() {
if mesh.tet(t).is_none() {
continue;
}
for i in 0..4 {
let snapshot: Vec<[u32; 4]> = mesh.iter().map(|(_, v)| v).collect();
if flip23(&mut mesh, t, i).unwrap().is_none() {
assert_eq!(mesh.iter().map(|(_, v)| v).collect::<Vec<_>>(), snapshot);
}
}
}
assert_eq!(mesh.find_defect(), None);
assert!((mesh.volume() - volume).abs() < 1e-15);
assert!(!before.is_empty());
}
#[test]
fn an_edge_with_the_wrong_ring_size_is_refused() {
let mesh = build(&bipyramid());
let mut tried = 0;
for t in 0..mesh.slot_count() {
let Some(v) = mesh.tet(t) else { continue };
for a in 0..4 {
for b in a + 1..4 {
let mut probe = mesh.clone();
if flip32(&mut probe, v[a], v[b]).unwrap().is_none() {
tried += 1;
}
}
}
}
assert!(tried > 0);
assert_eq!(mesh.find_defect(), None);
}
#[test]
fn flips_keep_the_mesh_sound_over_many_moves() {
let points: Vec<[f64; 3]> = (0..80)
.map(|i| {
let f = |s: u64| {
let mut x = (i as u64 ^ s).wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 29;
(x >> 11) as f64 / (1u64 << 53) as f64
};
[f(1), f(2), f(3)]
})
.collect();
let mut mesh = build(&points);
let volume = mesh.volume();
let mut applied = 0;
for round in 0..40 {
let t = (round * 7) % mesh.slot_count();
if mesh.tet(t).is_none() {
continue;
}
for i in 0..4 {
if flip23(&mut mesh, t, i).unwrap().is_some() {
applied += 1;
assert_eq!(mesh.find_defect(), None, "after flip {applied}");
assert!(
(mesh.volume() - volume).abs() < 1e-12,
"volume drifted to {}",
mesh.volume()
);
break;
}
}
}
assert!(applied > 5, "only {applied} flips applied");
}
}