1use std::cmp::Ordering;
6use std::collections::{BTreeSet, BinaryHeap, HashMap};
7
8type V3 = [f64; 3];
9
10fn sub(a: V3, b: V3) -> V3 {
11 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
12}
13
14fn cross(a: V3, b: V3) -> V3 {
15 [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
16}
17
18fn dot(a: V3, b: V3) -> f64 {
19 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
20}
21
22pub fn vertex_neighbours(vertex_count: usize, triangles: &[[usize; 3]]) -> Vec<BTreeSet<usize>> {
24 let mut n = vec![BTreeSet::new(); vertex_count];
25 for t in triangles {
26 for k in 0..3 {
27 n[t[k]].insert(t[(k + 1) % 3]);
28 n[t[(k + 1) % 3]].insert(t[k]);
29 }
30 }
31 n
32}
33
34pub fn boundary_vertices(vertex_count: usize, triangles: &[[usize; 3]]) -> Vec<bool> {
36 let mut count: HashMap<(usize, usize), usize> = HashMap::new();
37 for t in triangles {
38 for k in 0..3 {
39 let (a, b) = (t[k], t[(k + 1) % 3]);
40 *count.entry((a.min(b), a.max(b))).or_insert(0) += 1;
41 }
42 }
43 let mut boundary = vec![false; vertex_count];
44 for (&(a, b), &c) in &count {
45 if c == 1 {
46 boundary[a] = true;
47 boundary[b] = true;
48 }
49 }
50 boundary
51}
52
53fn umbrella_step(vertices: &mut [V3], neighbours: &[BTreeSet<usize>], fixed: &[bool], factor: f64) {
55 let old = vertices.to_vec();
56 for (i, v) in vertices.iter_mut().enumerate() {
57 if fixed[i] || neighbours[i].is_empty() {
58 continue;
59 }
60 let k = neighbours[i].len() as f64;
61 for d in 0..3 {
62 let mean = neighbours[i].iter().map(|&j| old[j][d]).sum::<f64>() / k;
63 v[d] += factor * (mean - old[i][d]);
64 }
65 }
66}
67pub fn laplacian_smoothing(vertices: &[V3], triangles: &[[usize; 3]], iterations: usize, lambda: f64, keep_boundary: bool) -> Vec<V3> {
73 let neighbours = vertex_neighbours(vertices.len(), triangles);
74 let fixed = if keep_boundary { boundary_vertices(vertices.len(), triangles) } else { vec![false; vertices.len()] };
75 let mut v = vertices.to_vec();
76 for _ in 0..iterations {
77 umbrella_step(&mut v, &neighbours, &fixed, lambda);
78 }
79 v
80}
81
82pub fn taubin_smoothing(vertices: &[V3], triangles: &[[usize; 3]], iterations: usize, lambda: f64, mu: f64, keep_boundary: bool) -> Vec<V3> {
86 let neighbours = vertex_neighbours(vertices.len(), triangles);
87 let fixed = if keep_boundary { boundary_vertices(vertices.len(), triangles) } else { vec![false; vertices.len()] };
88 let mut v = vertices.to_vec();
89 for _ in 0..iterations {
90 umbrella_step(&mut v, &neighbours, &fixed, lambda);
91 umbrella_step(&mut v, &neighbours, &fixed, mu);
92 }
93 v
94}
95
96#[derive(Clone, Copy, Default)]
98
99struct Quadric([f64; 10]);
100
101impl Quadric {
102 fn plane(n: V3, d: f64, weight: f64) -> Self {
103 let p = [n[0], n[1], n[2], d];
104 let mut q = [0.0; 10];
105 let mut k = 0;
106 for i in 0..4 {
107 for j in i..4 {
108 q[k] = weight * p[i] * p[j];
109 k += 1;
110 }
111 }
112 Quadric(q)
113 }
114
115 fn add(self, o: Quadric) -> Quadric {
116 let mut q = self.0;
117 q.iter_mut().zip(o.0).for_each(|(a, b)| *a += b);
118 Quadric(q)
119 }
120
121 fn error(&self, v: V3) -> f64 {
123 let q = &self.0;
124 let (x, y, z) = (v[0], v[1], v[2]);
125 q[0] * x * x + 2.0 * q[1] * x * y + 2.0 * q[2] * x * z + 2.0 * q[3] * x + q[4] * y * y + 2.0 * q[5] * y * z + 2.0 * q[6] * y + q[7] * z * z + 2.0 * q[8] * z + q[9]
126 }
127
128 fn optimum(&self) -> Option<V3> {
130 let q = &self.0;
131 let a = [[q[0], q[1], q[2]], [q[1], q[4], q[5]], [q[2], q[5], q[7]]];
132 let b = [-q[3], -q[6], -q[8]];
133 let det = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
134 let scale = (q[0] + q[4] + q[7]).powi(3).max(1e-300);
135 if det.abs() < 1e-10 * scale {
136 return None;
137 }
138 let col = |c: usize| {
139 let mut m = a;
140 for r in 0..3 {
141 m[r][c] = b[r];
142 }
143 m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
144 };
145 Some([col(0) / det, col(1) / det, col(2) / det])
146 }
147}
148
149#[derive(PartialEq)]
150
151struct Candidate {
152 cost: f64,
153 a: usize,
154 b: usize,
155 stamp: (u32, u32),
156}
157impl Eq for Candidate {}
158impl PartialOrd for Candidate {
159 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
160 Some(self.cmp(other))
161 }
162}
163impl Ord for Candidate {
164 fn cmp(&self, other: &Self) -> Ordering {
165 other.cost.total_cmp(&self.cost)
166 }
167}
168
169pub fn decimate(vertices: &[V3], triangles: &[[usize; 3]], target_triangles: usize) -> (Vec<V3>, Vec<[usize; 3]>) {
177 let n = vertices.len();
178 let mut pos = vertices.to_vec();
179 let mut tris: Vec<Option<[usize; 3]>> = triangles.iter().map(|&t| Some(t)).collect();
180 let mut quadric = vec![Quadric::default(); n];
181 let mut incident: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); n];
182 for (ti, t) in triangles.iter().enumerate() {
183 let normal = cross(sub(pos[t[1]], pos[t[0]]), sub(pos[t[2]], pos[t[0]]));
184 let length = dot(normal, normal).sqrt();
185 if length > 0.0 {
186 let unit = [normal[0] / length, normal[1] / length, normal[2] / length];
187 let q = Quadric::plane(unit, -dot(unit, pos[t[0]]), length / 2.0);
188 for &v in t {
189 quadric[v] = quadric[v].add(q);
190 }
191 }
192 for &v in t {
193 incident[v].insert(ti);
194 }
195 }
196 let boundary = boundary_vertices(n, triangles);
197 let mut version = vec![0u32; n];
198 let mut alive_count = triangles.len();
199 let placement = |a: usize, b: usize, pos: &[V3], q: &Quadric| -> V3 {
202 if boundary[a] {
203 return pos[a];
204 }
205 if boundary[b] {
206 return pos[b];
207 }
208 let midpoint = [(pos[a][0] + pos[b][0]) / 2.0, (pos[a][1] + pos[b][1]) / 2.0, (pos[a][2] + pos[b][2]) / 2.0];
209 q.optimum().unwrap_or(midpoint)
210 };
211 let candidate = |a: usize, b: usize, pos: &[V3], quadric: &[Quadric], version: &[u32]| -> Candidate {
212 let q = quadric[a].add(quadric[b]);
213 let target = placement(a, b, pos, &q);
214 let (a, b) = if boundary[b] { (b, a) } else { (a, b) };
216 Candidate { cost: q.error(target).max(0.0), a, b, stamp: (version[a], version[b]) }
217 };
218 let mut heap = BinaryHeap::new();
219 for (a, b) in edges(&tris) {
220 if !(boundary[a] && boundary[b]) {
221 heap.push(candidate(a, b, &pos, &quadric, &version));
222 }
223 }
224 while alive_count > target_triangles {
225 let Some(c) = heap.pop() else { break };
226 let (a, b) = (c.a, c.b);
227 if c.stamp != (version[a], version[b]) {
228 continue;
229 }
230 let shared: Vec<usize> = incident[a].intersection(&incident[b]).copied().collect();
233 if shared.len() != 2 {
234 continue;
235 }
236 let neighbours = |v: usize, inc: &BTreeSet<usize>, tris: &[Option<[usize; 3]>]| -> BTreeSet<usize> { inc.iter().flat_map(|&t| tris[t].expect("alive")).filter(|&w| w != v).collect() };
237 let common: Vec<usize> = neighbours(a, &incident[a], &tris).intersection(&neighbours(b, &incident[b], &tris)).copied().collect();
238 if common.len() != 2 {
239 continue;
240 }
241 let q = quadric[a].add(quadric[b]);
242 let target = placement(a, b, &pos, &q);
243 let flips = incident[a].union(&incident[b]).filter(|t| !shared.contains(t)).any(|&t| {
245 let tri = tris[t].expect("alive");
246 let before = cross(sub(pos[tri[1]], pos[tri[0]]), sub(pos[tri[2]], pos[tri[0]]));
247 let moved: Vec<V3> = tri.iter().map(|&v| if v == a || v == b { target } else { pos[v] }).collect();
248 let after = cross(sub(moved[1], moved[0]), sub(moved[2], moved[0]));
249 dot(before, after) <= 1e-12 * dot(before, before)
250 });
251 if flips {
252 continue;
253 }
254 for &t in &shared {
256 for &v in &tris[t].expect("alive") {
257 incident[v].remove(&t);
258 }
259 tris[t] = None;
260 alive_count -= 1;
261 }
262 let moved: Vec<usize> = incident[b].iter().copied().collect();
263 for t in moved {
264 let tri = tris[t].as_mut().expect("alive");
265 tri.iter_mut().for_each(|v| if *v == b { *v = a });
266 incident[a].insert(t);
267 }
268 incident[b].clear();
269 pos[a] = target;
270 quadric[a] = q;
271 version[a] += 1;
272 version[b] += 1;
273 let around: BTreeSet<usize> = incident[a].iter().flat_map(|&t| tris[t].expect("alive")).filter(|&w| w != a).collect();
274 for w in around {
275 if !(boundary[a] && boundary[w]) {
276 heap.push(candidate(a, w, &pos, &quadric, &version));
277 }
278 }
279 }
280 let mut remap = vec![usize::MAX; n];
282 let mut out_vertices = Vec::new();
283 let mut out_triangles = Vec::new();
284 for t in tris.into_iter().flatten() {
285 out_triangles.push(t.map(|v| {
286 if remap[v] == usize::MAX {
287 remap[v] = out_vertices.len();
288 out_vertices.push(pos[v]);
289 }
290 remap[v]
291 }));
292 }
293 (out_vertices, out_triangles)
294}
295
296fn edges(tris: &[Option<[usize; 3]>]) -> BTreeSet<(usize, usize)> {
297 tris.iter().flatten().flat_map(|t| (0..3).map(move |k| (t[k].min(t[(k + 1) % 3]), t[k].max(t[(k + 1) % 3])))).collect()
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 fn sphere(rings: usize, segments: usize) -> (Vec<V3>, Vec<[usize; 3]>) {
306 use std::f64::consts::PI;
307 let mut v = vec![[0.0, 0.0, 1.0]];
308 for r in 1..rings {
309 let theta = PI * r as f64 / rings as f64;
310 for s in 0..segments {
311 let phi = 2.0 * PI * s as f64 / segments as f64;
312 v.push([theta.sin() * phi.cos(), theta.sin() * phi.sin(), theta.cos()]);
313 }
314 }
315 v.push([0.0, 0.0, -1.0]);
316 let south = v.len() - 1;
317 let id = |r: usize, s: usize| 1 + (r - 1) * segments + s % segments;
318 let mut t = Vec::new();
319 for s in 0..segments {
320 t.push([0, id(1, s), id(1, s + 1)]);
321 t.push([south, id(rings - 1, s + 1), id(rings - 1, s)]);
322 for r in 1..rings - 1 {
323 t.push([id(r, s), id(r + 1, s), id(r + 1, s + 1)]);
324 t.push([id(r, s), id(r + 1, s + 1), id(r, s + 1)]);
325 }
326 }
327 (v, t)
328 }
329
330 fn euler_characteristic(v: usize, t: &[[usize; 3]]) -> i64 {
331 v as i64 - edges(&t.iter().map(|&x| Some(x)).collect::<Vec<_>>()).len() as i64 + t.len() as i64
332 }
333
334 #[test]
335 fn decimation_keeps_a_closed_sphere_round_and_watertight() {
336 let (v, t) = sphere(24, 48);
337 let (dv, dt) = decimate(&v, &t, t.len() / 5);
338 assert!(dt.len() <= t.len() / 5 + 2 && dt.len() > t.len() / 6, "{} of {}", dt.len(), t.len());
339 assert_eq!(euler_characteristic(dv.len(), &dt), 2);
340 assert!(boundary_vertices(dv.len(), &dt).iter().all(|&b| !b));
341 let worst = dv.iter().map(|p| (dot(*p, *p).sqrt() - 1.0).abs()).fold(0.0, f64::max);
342 assert!(worst < 0.02, "{worst}");
343 }
344
345 #[test]
346 fn flat_grids_collapse_without_error_and_keep_their_boundary() {
347 let n = 10;
348 let v: Vec<V3> = (0..=n).flat_map(|j| (0..=n).map(move |i| [i as f64, j as f64, 0.0])).collect();
349 let id = |i: usize, j: usize| j * (n + 1) + i;
350 let t: Vec<[usize; 3]> = (0..n).flat_map(|j| (0..n).flat_map(move |i| [[id(i, j), id(i + 1, j), id(i + 1, j + 1)], [id(i, j), id(i + 1, j + 1), id(i, j + 1)]])).collect();
351 let (dv, dt) = decimate(&v, &t, 0);
352 assert!(dv.len() <= 4 * n + 1 && dv.iter().all(|p| p[2] == 0.0), "{} vertices, {} triangles", dv.len(), dt.len());
355 let area: f64 = dt.iter().map(|tri| 0.5 * cross(sub(dv[tri[1]], dv[tri[0]]), sub(dv[tri[2]], dv[tri[0]]))[2]).sum();
356 assert!((area - 100.0).abs() < 1e-9, "{area}");
357 }
358
359 #[test]
360 fn taubin_smoothing_denoises_without_shrinking() {
361 let (v, t) = sphere(16, 32);
362 let mut s: u64 = 9;
363 let noisy: Vec<V3> = v.iter().map(|p| {
364 s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
365 let e = 1.0 + 0.05 * ((s >> 11) as f64 / (1u64 << 53) as f64 - 0.5);
366 [p[0] * e, p[1] * e, p[2] * e]
367 }).collect();
368 let radius_spread = |m: &[V3]| {
369 let r: Vec<f64> = m.iter().map(|p| dot(*p, *p).sqrt()).collect();
370 let mean = r.iter().sum::<f64>() / r.len() as f64;
371 (mean, (r.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / r.len() as f64).sqrt())
372 };
373 let (_, noise) = radius_spread(&noisy);
374 let (lap_mean, _) = radius_spread(&laplacian_smoothing(&noisy, &t, 20, 0.5, false));
375 let (taubin_mean, taubin_spread) = radius_spread(&taubin_smoothing(&noisy, &t, 20, 0.5, -0.53, false));
376 assert!(taubin_spread < noise / 2.0, "{taubin_spread} vs {noise}");
377 assert!((1.0 - taubin_mean).abs() < 0.03 && 1.0 - lap_mean > 2.0 * (1.0 - taubin_mean).abs(), "{lap_mean} {taubin_mean}");
378 let flat = laplacian_smoothing(&[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], &[[0, 1, 2]], 5, 0.5, true);
380 assert_eq!(flat[1], [1.0, 0.0, 0.0]);
381 }
382}