pyrucast 0.6.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Getting rid of slivers.
//!
//! Refinement leaves one kind of bad cell behind, and it is the worst kind: a
//! **sliver**, four corners close to one plane and spread evenly around a
//! circle. Every measure refinement watches says it is fine — its edges are
//! all of a decent length, its circumsphere is small — and yet it has almost
//! no volume:
//!
//! ```text
//!        b                  the four corners sit near one circle, so no
//!       / \                 edge is short and the circumsphere is tight;
//!    a ─────── c            the cell is nonetheless flat, and its element
//!       \ /                 matrix nearly singular
//!        d
//! ```
//!
//! No node can be inserted to remove it — that is a theorem, not a gap in
//! the implementation — so the mesh has to be improved rather than
//! subdivided, by the two moves that change a mesh without changing what it
//! fills:
//!
//! - **reconnection**: the same nodes, joined differently. A sliver is often
//!   one flip away from two decent cells.
//! - **edge removal**: the sliver's own edges taken out, one at a time. This
//!   is the move that actually kills slivers, and the reason is geometric —
//!   a sliver is flat *across* an edge, so a 2-3 flip on one of its faces
//!   often has nowhere to go (the pair of cells is not convex there), while
//!   emptying the ring of cells around the offending edge and filling it
//!   again always has the room to. It subsumes the 3-2 flip and everything
//!   past it.
//! - **smoothing**: the same connections, with a node moved. Only interior
//!   nodes move; the envelope's own nodes are the caller's and are never
//!   touched, which is what keeps the surface exactly as it came in.
//!
//! Both are judged on the **smallest dihedral angle** of the cells they
//! touch, and applied only when it improves. That makes the pass
//! monotone — it can only make the worst angle in a neighbourhood better —
//! so it can be run until it stops paying without risk of undoing itself.

use std::collections::HashSet;

use crate::error::Result;
use crate::interrupt::Cancel;

use super::delaunay::TetMesh;
use super::flips::{flip23, remove_edge_if};
use super::recovery::Protected;

/// Below this angle (degrees) a cell is worth working on.
const POOR: f64 = 25.0;

/// Below this angle (degrees) a cell is bad enough to spend a pocket rebuild
/// on.
///
/// Edge removal costs far more than a flip, so it is kept for the cells that
/// a flip and a nudge have already failed to mend.
const DIRE: f64 = 12.0;

/// Largest pocket an edge removal may grow to while chasing a sliver.
///
/// Small on purpose. Widening is how recovery gets its answer when it must
/// have one; here there is no must — the next edge, or the next cell, is
/// always an option.
const SLIVER_REGION: usize = 8;

/// Sweeps of reconnection and smoothing before the pass gives up.
const ROUNDS: usize = 6;

/// How far a node is moved toward its target, in decreasing steps.
///
/// The full step is right when the neighbourhood is roomy and wrong when it
/// is tight, so the shorter ones are there to be fallen back on.
const STEPS: [f64; 4] = [1.0, 0.6, 0.3, 0.1];

/// Improve the badly shaped cells of `mesh`, in place.
///
/// `movable` marks the nodes that may be moved — the interior ones. `walls`
/// are the envelope's facets, which no reconnection may disturb. `inside`
/// says which slots hold material.
///
/// Returns the smallest dihedral angle left, in degrees.
pub fn smooth(
    mesh: &mut TetMesh,
    inside: &[bool],
    movable: &[bool],
    walls: &HashSet<[u32; 3]>,
    protect: &Protected<'_>,
    cancel: &dyn Cancel,
) -> Result<f64> {
    // Cells that no edge removal could mend. Without this the last rounds are
    // spent re-proving the same handful of cells hopeless, six edges at a
    // time, which is most of what the pass costs on a large mesh.
    let mut hopeless: HashSet<[u32; 4]> = HashSet::new();
    for _ in 0..ROUNDS {
        cancel.check()?;
        let reconnected = reconnect(mesh, inside, walls)?;
        let moved = relax(mesh, inside, movable);
        // Every round, not only the rounds the cheap moves gave up on:
        // relaxation reports a move whenever a node shifted at all, which on
        // a large mesh is every round, so gating on it would keep the pocket
        // rebuilds from ever running.
        let carved = carve(mesh, inside, protect, &mut hopeless, cancel)?;
        if !reconnected && !moved && !carved {
            break;
        }
    }
    Ok(worst_angle(mesh, inside))
}

/// Take out the edges of the cells that neither of the cheap moves fixed.
///
/// The six edges of a bad cell are tried in turn; which order hardly matters,
/// but an envelope edge is never offered, since removing one would change the
/// surface. The replacement is judged **before** it is committed, so the pass
/// stays monotone like the other two without ever copying the mesh.
fn carve(
    mesh: &mut TetMesh,
    inside: &[bool],
    protect: &Protected<'_>,
    hopeless: &mut HashSet<[u32; 4]>,
    cancel: &dyn Cancel,
) -> Result<bool> {
    const PAIRS: [(usize, usize); 6] = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)];
    let mut changed = false;
    for t in 0..mesh.slot_count() {
        cancel.check()?;
        let Some(v) = mesh.tet(t) else { continue };
        if !inside.get(t).copied().unwrap_or(false) {
            continue;
        }
        let before = min_dihedral(mesh, &v);
        if before >= DIRE || hopeless.contains(&key(&v)) {
            continue;
        }
        let mut freed = false;
        for (a, b) in PAIRS {
            let (p, q) = (v[a], v[b]);
            if !protect.on_edge(p, q).is_empty() {
                continue; // an edge of the envelope: not ours to remove
            }
            // The neighbourhood is judged before and after, so a removal
            // that merely moves the problem is undone.
            let Some(ring) = mesh.edge_fan(p, q) else {
                continue;
            };
            let around = ring
                .cells
                .iter()
                .filter_map(|&c| mesh.tet(c as usize))
                .map(|c| min_dihedral(mesh, &c))
                .fold(f64::INFINITY, f64::min);

            let better = |m: &TetMesh, cells: &[[u32; 4]]| {
                cells
                    .iter()
                    .map(|c| min_dihedral(m, c))
                    .fold(f64::INFINITY, f64::min)
                    > around
            };
            if remove_edge_if(mesh, p, q, protect, SLIVER_REGION, Some(&better))?.is_some() {
                changed = true;
                freed = true;
                break;
            }
        }
        // The cell is still there and all six of its edges were tried: its
        // neighbourhood would have to change on its own account before the
        // answer could differ, and if it does the cell is a different cell.
        if !freed {
            hopeless.insert(key(&v));
        }
    }
    Ok(changed)
}

/// A cell named by its vertices, whichever order they came in.
fn key(v: &[u32; 4]) -> [u32; 4] {
    let mut k = *v;
    k.sort_unstable();
    k
}

/// Flip the faces of poor cells, keeping what improves them.
///
/// The outcome of a 2-3 flip is known before it is made — three cells, on
/// vertices already in hand — so it is judged first and applied only if it
/// pays. Trying it and undoing it would mean copying the mesh once per
/// candidate face, which on a large mesh costs more than the whole pass.
fn reconnect(mesh: &mut TetMesh, inside: &[bool], walls: &HashSet<[u32; 3]>) -> Result<bool> {
    let mut changed = false;
    for t in 0..mesh.slot_count() {
        let Some(v) = mesh.tet(t) else { continue };
        if !inside.get(t).copied().unwrap_or(false) || min_dihedral(mesh, &v) >= POOR {
            continue;
        }
        for i in 0..4 {
            let f = mesh.face(t, i);
            let mut key = f;
            key.sort_unstable();
            if walls.contains(&key) {
                continue; // the envelope is not ours to re-cut
            }
            let Some(n) = mesh.neighbour(t, i) else {
                continue;
            };
            let Some(w) = mesh.tet(n) else { continue };
            let Some(e) = mesh.apex_beyond(n, &f) else {
                continue;
            };
            let d = v[i];

            let before = min_dihedral(mesh, &v).min(min_dihedral(mesh, &w));
            let candidates = [[f[0], f[1], d, e], [f[1], f[2], d, e], [f[2], f[0], d, e]];
            if candidates.iter().any(|c| mesh.orientation(c) <= 0.0) {
                continue; // the pair is not convex across this face
            }
            let after = candidates
                .iter()
                .map(|c| min_dihedral(mesh, c))
                .fold(f64::INFINITY, f64::min);
            if after <= before {
                continue;
            }
            if flip23(mesh, t, i)?.is_some() {
                changed = true;
                break;
            }
        }
    }
    Ok(changed)
}

/// Move each movable node toward wherever its own cells are least pinched.
fn relax(mesh: &mut TetMesh, inside: &[bool], movable: &[bool]) -> bool {
    let mut changed = false;
    for v in 0..mesh.points().len() as u32 {
        if !movable.get(v as usize).copied().unwrap_or(false) {
            continue;
        }
        // Every cell holding the node, not only the ones made of material:
        // moving it moves them all, and one turned inside out is a broken
        // mesh whether or not it is kept in the end.
        let star: Vec<[u32; 4]> = mesh
            .tets_around_vertex(v)
            .into_iter()
            .filter_map(|t| mesh.tet(t as usize))
            .collect();
        if star.is_empty() {
            continue;
        }
        let cells: Vec<[u32; 4]> = mesh
            .tets_around_vertex(v)
            .into_iter()
            .filter(|&t| inside.get(t as usize).copied().unwrap_or(false))
            .filter_map(|t| mesh.tet(t as usize))
            .collect();
        if cells.is_empty() {
            continue;
        }

        let before = cells
            .iter()
            .map(|c| min_dihedral(mesh, c))
            .fold(f64::INFINITY, f64::min);
        if before >= POOR {
            continue;
        }

        // The average of the neighbours pulls a pinched node toward the
        // roomiest spot its own cells leave it.
        let here = mesh.points()[v as usize];
        let mut sum = [0.0f64; 3];
        let mut count = 0.0;
        for c in &cells {
            for &x in c.iter().filter(|&&x| x != v) {
                let p = mesh.points()[x as usize];
                for k in 0..3 {
                    sum[k] += p[k];
                }
                count += 1.0;
            }
        }
        if count == 0.0 {
            continue;
        }
        let target = [sum[0] / count, sum[1] / count, sum[2] / count];

        let mut best = (before, here);
        for step in STEPS {
            let trial = [
                here[0] + step * (target[0] - here[0]),
                here[1] + step * (target[1] - here[1]),
                here[2] + step * (target[2] - here[2]),
            ];
            mesh.set_point(v, trial);
            // A move that turns any cell inside out is no move at all.
            let ok = star.iter().all(|c| mesh.orientation(c) > 0.0);
            let after = if ok {
                cells
                    .iter()
                    .map(|c| min_dihedral(mesh, c))
                    .fold(f64::INFINITY, f64::min)
            } else {
                f64::NEG_INFINITY
            };
            if after > best.0 {
                best = (after, trial);
            }
        }
        mesh.set_point(v, best.1);
        if best.1 != here {
            changed = true;
        }
    }
    changed
}

/// Cells that neither pass can reach, with how flat each one is.
///
/// A sliver whose four corners are all nodes of the envelope is beyond both
/// moves this module has: no node can be inserted to break it up, and none
/// of its own may be moved, since the caller's nodes are fixed. Naming them
/// is the only thing left to do — either to cut the surface there, or to
/// tell the caller their surface cannot carry a usable mesh as drawn.
///
/// Shape is measured by `η = 12 (3V)^(2/3) / Σℓ²`, which is 1 for a regular
/// tetrahedron and 0 for a flat one, and — unlike a volume — does not depend
/// on how big the rest of the mesh happens to be.
pub fn stubborn(
    mesh: &TetMesh,
    inside: &[bool],
    on_envelope: usize,
    floor: f64,
) -> Vec<([u32; 4], f64)> {
    mesh.iter()
        .filter(|(t, _)| inside.get(*t).copied().unwrap_or(false))
        .filter(|(_, v)| v.iter().all(|&x| (x as usize) < on_envelope))
        .map(|(_, v)| (v, shape(mesh, &v)))
        .filter(|&(_, q)| q < floor)
        .collect()
}

/// How near a regular tetrahedron a cell is: 1 for regular, 0 for flat.
fn shape(mesh: &TetMesh, v: &[u32; 4]) -> f64 {
    let p = mesh.points();
    let mut squares = 0.0;
    for a in 0..4 {
        for b in a + 1..4 {
            let (x, y) = (p[v[a] as usize], p[v[b] as usize]);
            squares += (0..3).map(|k| (x[k] - y[k]).powi(2)).sum::<f64>();
        }
    }
    if squares == 0.0 {
        return 0.0;
    }
    let volume = mesh.orientation(v).abs() / 6.0;
    12.0 * (3.0 * volume).powf(2.0 / 3.0) / squares
}

/// The smallest dihedral angle of the mesh's material, in degrees.
pub fn worst_angle(mesh: &TetMesh, inside: &[bool]) -> f64 {
    mesh.iter()
        .filter(|(t, _)| inside.get(*t).copied().unwrap_or(false))
        .map(|(_, v)| min_dihedral(mesh, &v))
        .fold(f64::INFINITY, f64::min)
}

/// The smallest angle between two faces of a cell, in degrees.
///
/// Along an edge, the dihedral is read by flattening the two opposite
/// corners into the plane across it: project each onto the plane
/// perpendicular to the edge, and take the angle between what is left.
fn min_dihedral(mesh: &TetMesh, v: &[u32; 4]) -> f64 {
    const EDGES: [(usize, usize, usize, usize); 6] = [
        (0, 1, 2, 3),
        (0, 2, 1, 3),
        (0, 3, 1, 2),
        (1, 2, 0, 3),
        (1, 3, 0, 2),
        (2, 3, 0, 1),
    ];
    let p = mesh.points();
    let mut worst = f64::INFINITY;
    for (a, b, c, d) in EDGES {
        let (pa, pb) = (p[v[a] as usize], p[v[b] as usize]);
        let e = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]];
        let len = (e[0] * e[0] + e[1] * e[1] + e[2] * e[2]).sqrt();
        if len == 0.0 {
            return 0.0;
        }
        let unit = [e[0] / len, e[1] / len, e[2] / len];
        let flatten = |x: [f64; 3]| {
            let w = [x[0] - pa[0], x[1] - pa[1], x[2] - pa[2]];
            let along = w[0] * unit[0] + w[1] * unit[1] + w[2] * unit[2];
            [
                w[0] - along * unit[0],
                w[1] - along * unit[1],
                w[2] - along * unit[2],
            ]
        };
        let (u, w) = (flatten(p[v[c] as usize]), flatten(p[v[d] as usize]));
        let (nu, nw) = (
            (u[0] * u[0] + u[1] * u[1] + u[2] * u[2]).sqrt(),
            (w[0] * w[0] + w[1] * w[1] + w[2] * w[2]).sqrt(),
        );
        if nu == 0.0 || nw == 0.0 {
            return 0.0;
        }
        let cos = ((u[0] * w[0] + u[1] * w[1] + u[2] * w[2]) / (nu * nw)).clamp(-1.0, 1.0);
        worst = worst.min(cos.acos().to_degrees());
    }
    worst
}