Skip to main content

axiolid_construct/
loft.rs

1//! Lofting a sequence of station rings into a solid.
2//!
3//! Every sweep family reduces to the same shape: place the profile at a
4//! series of stations along a path, stitch consecutive stations into
5//! walls, and cap the ends unless the path closes on itself. Extrusion is
6//! two stations; revolution is an arc of them; a sectioned spine supplies
7//! its own.
8//!
9//! Writing that once means winding, hole orientation and cap pairing are
10//! fixed in one place rather than re-derived per family.
11
12use axiolid_contracts::{GeomError, GeomResult};
13use axiolid_core::{Point2, Point3, Scalar, Vec3};
14use axiolid_mesh::TriMesh;
15
16use crate::profile::Rings;
17
18/// One station: the profile's rings already placed in 3D.
19#[derive(Debug, Clone)]
20pub struct Station {
21    /// Outer ring followed by each hole, in `Rings` order.
22    pub loops: Vec<Vec<Point3>>,
23}
24
25/// Place `rings` into 3D with a per-point mapping.
26///
27/// The mapping takes the profile's 2D point and returns its 3D image, so a
28/// caller expresses only what its family does: extrusion translates,
29/// revolution rotates, a spine sweep applies a frame.
30pub fn place(rings: &Rings, mut f: impl FnMut(Point2) -> Point3) -> Station {
31    let mut loops = Vec::with_capacity(1 + rings.holes.len());
32    loops.push(rings.outer.iter().map(|p| f(*p)).collect());
33    for hole in &rings.holes {
34        loops.push(hole.iter().map(|p| f(*p)).collect());
35    }
36    Station { loops }
37}
38
39/// Stitch stations into a closed solid.
40///
41/// `closed` wraps the last station onto the first, which welds a periodic
42/// seam by index rather than by two samplings agreeing numerically. Open
43/// lofts are capped with the profile triangulation at each end.
44///
45/// All stations must share the profile's ring structure: the walls pair
46/// vertices by position, so a differing ring length has no meaningful
47/// pairing and is refused rather than silently truncated.
48pub fn loft(rings: &Rings, stations: &[Station], closed: bool) -> GeomResult<TriMesh> {
49    loft_welded(rings, stations, closed, &[])
50}
51
52/// [`loft`] with some ring points welded across stations (#363).
53///
54/// `welded[f]` marks the `f`-th ring point (outer ring first, then each hole,
55/// the order of a [`Station`]) as fixed under the sweep, as a point on a
56/// revolution axis is: its stations coincide, so they share one vertex, taken
57/// from the last station. A wall quad with one welded end collapses to its
58/// one triangle that is not degenerate; a quad with both ends welded lies
59/// along the fixed line and emits nothing. Caps index the shared vertices, so
60/// the solid stays closed. An empty `welded` welds nothing.
61pub(crate) fn loft_welded(
62    rings: &Rings,
63    stations: &[Station],
64    closed: bool,
65    welded: &[bool],
66) -> GeomResult<TriMesh> {
67    if stations.len() < 2 {
68        return Err(GeomError::InvalidInput(format!(
69            "a loft needs at least two stations, got {}",
70            stations.len()
71        )));
72    }
73    let shape: Vec<usize> = stations[0].loops.iter().map(|r| r.len()).collect();
74    for s in stations {
75        let this: Vec<usize> = s.loops.iter().map(|r| r.len()).collect();
76        if this != shape {
77            return Err(GeomError::InvalidInput(
78                "loft stations must share the profile's ring structure".to_owned(),
79            ));
80        }
81    }
82    let per_station: usize = shape.iter().sum();
83    if !welded.is_empty() && welded.len() != per_station {
84        return Err(GeomError::InvalidInput(
85            "welded flags must cover every ring point".to_owned(),
86        ));
87    }
88    let is_welded = |f: usize| welded.get(f).copied().unwrap_or(false);
89    // `id[s * per_station + f]` is the vertex of ring point `f` at station
90    // `s`; a welded point has one vertex, placed at the last station.
91    let mut positions: Vec<Point3> = Vec::with_capacity(stations.len() * per_station);
92    let mut id: Vec<u32> = vec![0; stations.len() * per_station];
93    let mut shared: Vec<Option<u32>> = vec![None; per_station];
94    let last_station = &stations[stations.len() - 1];
95    for (s, station) in stations.iter().enumerate() {
96        let mut f = 0;
97        for (ring, last_ring) in station.loops.iter().zip(&last_station.loops) {
98            for (point, last_point) in ring.iter().zip(last_ring) {
99                id[s * per_station + f] = match (is_welded(f), shared[f]) {
100                    (true, Some(v)) => v,
101                    (welded_here, _) => {
102                        let v = positions.len() as u32;
103                        positions.push(if welded_here { *last_point } else { *point });
104                        if welded_here {
105                            shared[f] = Some(v);
106                        }
107                        v
108                    }
109                };
110                f += 1;
111            }
112        }
113    }
114    // A closed loft wraps onto station 0; an open one stops one short.
115    let spans = if closed {
116        stations.len()
117    } else {
118        stations.len() - 1
119    };
120    let mut indices: Vec<u32> = Vec::new();
121    for s in 0..spans {
122        let a0 = s * per_station;
123        let b0 = ((s + 1) % stations.len()) * per_station;
124        let mut base = 0usize;
125        for m in shape.iter() {
126            for k in 0..*m {
127                let kn = (k + 1) % *m;
128                let (fk, fkn) = (base + k, base + kn);
129                let (a, b) = (id[a0 + fk], id[a0 + fkn]);
130                let (c, d) = (id[b0 + fk], id[b0 + fkn]);
131                // Both rings wind the same way here. A hole ring is already
132                // stored clockwise (profile.rs keeps holes reversed), which
133                // is what turns its wall normal inward; flipping the index
134                // order as well would invert it a second time.
135                match (is_welded(fk), is_welded(fkn)) {
136                    (false, false) => indices.extend([a, b, d, a, d, c]),
137                    (true, false) => indices.extend([a, b, d]),
138                    (false, true) => indices.extend([a, d, c]),
139                    (true, true) => {}
140                }
141            }
142            base += *m;
143        }
144    }
145    // Caps. A closed loft needs none: the wall meets itself. An open one is
146    // bounded by the profile at each end, wound opposite so both face out.
147    if !closed {
148        let (points, tris) = crate::profile::triangulate(rings)?;
149        if points.len() != per_station {
150            return Err(GeomError::Degenerate(format!(
151                "cap triangulation produced {} points for {per_station} ring points",
152                points.len()
153            )));
154        }
155        let last = (stations.len() - 1) * per_station;
156        for t in &tris {
157            let first = t.map(|f| id[f as usize]);
158            let end = t.map(|f| id[last + f as usize]);
159            indices.extend([first[0], first[2], first[1]]);
160            indices.extend([end[0], end[1], end[2]]);
161        }
162    }
163    if !welded.is_empty() {
164        (positions, indices) = compact(positions, indices);
165    }
166    Ok(TriMesh::new(positions, indices))
167}
168
169/// Drop the vertices no triangle uses, keeping the order of the rest. A
170/// welded point whose ring neighbours are all welded has no wall quad and,
171/// in a closed loft, no cap either (#363).
172fn compact(positions: Vec<Point3>, mut indices: Vec<u32>) -> (Vec<Point3>, Vec<u32>) {
173    let mut used = vec![false; positions.len()];
174    for i in &indices {
175        used[*i as usize] = true;
176    }
177    let mut new_id = vec![0u32; positions.len()];
178    let mut kept = Vec::with_capacity(positions.len());
179    for (v, p) in positions.into_iter().enumerate() {
180        if used[v] {
181            new_id[v] = kept.len() as u32;
182            kept.push(p);
183        }
184    }
185    for i in &mut indices {
186        *i = new_id[*i as usize];
187    }
188    (kept, indices)
189}
190
191/// How far the bilinear patch over one wall quad can sit from the two
192/// triangles [`loft`] splits it into.
193///
194/// The quad joins ring points `a -> b` on one station to `c -> d` on the
195/// next, and [`loft`] cuts it along the diagonal `a-d` into `(a, b, d)` and
196/// `(a, d, c)`. The patch `B(x, y) = (1-y)((1-x)a + xb) + y((1-x)c + xd)`
197/// is the surface the chords between the two stations span: its row at
198/// fixed `x` is the chord between the two placements of one profile point,
199/// which is why the sweeps bound the exact surface against it. Every bound
200/// below holds pointwise, so the smallest is returned:
201///
202/// - `|T| / 4` with the twist `T = a - b - c + d`. On the half `x >= y`,
203///   `B - L = -y(1-x) T` where `L` is the point of `(a, b, d)` with the
204///   same barycentric weights, and `y(1-x) <= 1/4` there; the other half is
205///   symmetric. Always valid.
206/// - `|b - a|`: `B` is within `(1-y)x|b - a|` of the point
207///   `(1-y)a + y((1-x)c + xd)` of triangle `(a, d, c)`. Likewise `|c - a|`
208///   against `(a, b, d)`. These make a quad that collapses to a triangle on
209///   an axis (a ring point on a revolution axis) exact.
210/// - `2|d - c|`: `B` is within `xy|d - c|` of the point
211///   `(1-y)((1-x)a + xb) + yc` of the plane triangle `(a, b, c)`, and moving
212///   that triangle's `c` to `d` moves the point by at most `|d - c|`.
213///   Likewise `2|d - b|`.
214/// - The flattening bound. Take a plane with unit normal `n` and heights
215///   `h(p) = n.p - k`, project the corners onto it, and suppose the
216///   projected quad `a', b', d', c'` is convex. The projected patch is a
217///   convex combination of the projected corners, so it lies in that quad,
218///   which the two plane triangles `(a', b', d')`, `(a', d', c')` cover:
219///   each `B(x, y)` has a point `Z` there with `Z = B(x, y)` in the plane.
220///   Lifting `Z` back with the same weights gives a point of `(a, b, d)` or
221///   `(a, d, c)`, and the two heights are weighted means of corner heights,
222///   so the distance is at most the spread of the corner heights. Two
223///   planes are used. The plane through `a, b, c` leaves only `d` off it,
224///   at the height `g`: bound `|g|`. The plane parallel to both diagonals,
225///   halfway between them, puts `a, d` at `e` and `b, c` at `-e`, with
226///   `2|e|` the distance between the diagonals: bound `2|e|`, half of
227///   `|g|` for a twisted quad (where `|g| = 4|e|`). A planar convex quad,
228///   the wall a revolution builds about an axis in the profile's plane,
229///   gets 0.
230///
231/// The convexity test runs in floating point with a relative slack of
232/// `1e-12`: a quad that fails it by less leaves an uncovered sliver some
233/// `1e-12` of its size wide, far below any chord budget.
234pub fn quad_deviation(a: Point3, b: Point3, c: Point3, d: Point3) -> Scalar {
235    let twist = (a - b - c + d).length() / 4.0;
236    let mut best = twist
237        .min((b - a).length())
238        .min((c - a).length())
239        .min(2.0 * (d - c).length())
240        .min(2.0 * (d - b).length());
241    // The plane through a, b, c: only d leaves it.
242    if let Some(n) = unit((b - a).cross(c - a)) {
243        let g = (d - a).dot(n);
244        if convex_projection([a, b, d - n * g, c], n) {
245            best = best.min(g.abs());
246        }
247    }
248    // The plane halfway between the diagonals a-d and b-c.
249    if let Some(n) = unit((d - a).cross(c - b)) {
250        let e = 0.5 * (a - b).dot(n);
251        let (a2, d2) = (a - n * e, d - n * e);
252        let (b2, c2) = (b + n * e, c + n * e);
253        if convex_projection([a2, b2, d2, c2], n) {
254            best = best.min(2.0 * e.abs());
255        }
256    }
257    best
258}
259
260/// `v` scaled to unit length, or `None` when it has none to scale.
261fn unit(v: Vec3) -> Option<Vec3> {
262    let length = v.length();
263    (length > 0.0 && length.is_finite()).then(|| v / length)
264}
265
266/// Whether the polygon `p0 -> p1 -> p2 -> p3`, lying in a plane with unit
267/// normal `n`, is convex: it turns the same way, about `n`, at every
268/// corner (either way round), with a relative slack of `1e-12`.
269fn convex_projection(corners: [Point3; 4], n: Vec3) -> bool {
270    let scale = (0..4)
271        .map(|k| (corners[(k + 1) % 4] - corners[k]).length())
272        .fold(0.0, Scalar::max);
273    let slack = 1e-12 * scale * scale;
274    let turns: Vec<Scalar> = (0..4)
275        .map(|k| {
276            let (p, q, r) = (corners[k], corners[(k + 1) % 4], corners[(k + 2) % 4]);
277            (q - p).cross(r - q).dot(n)
278        })
279        .collect();
280    turns.iter().all(|t| *t >= -slack) || turns.iter().all(|t| *t <= slack)
281}
282
283/// The largest [`quad_deviation`] over the walls between two stations.
284///
285/// Pairs ring points exactly as [`loft`] does: point `k` with `k + 1`,
286/// wrapping, on every ring.
287pub(crate) fn span_deviation(from: &Station, to: &Station) -> Scalar {
288    let mut worst: Scalar = 0.0;
289    for (ring, next) in from.loops.iter().zip(&to.loops) {
290        let m = ring.len().min(next.len());
291        for k in 0..m {
292            let kn = (k + 1) % m;
293            worst = worst.max(quad_deviation(ring[k], ring[kn], next[k], next[kn]));
294        }
295    }
296    worst
297}
298
299/// An orthonormal frame at a point on a path.
300///
301/// A sweep needs a full frame, not just a tangent: the profile's x and y
302/// axes have to be carried along the path, and how they are carried is
303/// exactly what distinguishes the sweep families from each other.
304#[derive(Debug, Clone)]
305pub struct Frame {
306    /// Frame origin on the directrix.
307    pub origin: Point3,
308    /// Image of the profile's +x.
309    pub x: Vec3,
310    /// Image of the profile's +y.
311    pub y: Vec3,
312}
313
314impl Frame {
315    /// Frame whose z is `tangent` and whose x is `reference` made
316    /// perpendicular to it.
317    ///
318    /// Refuses a reference parallel to the tangent instead of silently
319    /// picking a fallback axis: the caller supplied a direction that cannot
320    /// orient the profile, and quietly substituting one rotates the section
321    /// by an arbitrary angle.
322    pub fn from_reference(origin: Point3, tangent: Vec3, reference: Vec3) -> GeomResult<Self> {
323        let t = tangent.normalize_or_zero();
324        if t == Vec3::ZERO {
325            return Err(GeomError::InvalidInput(
326                "sweep tangent must be a non-zero direction".to_owned(),
327            ));
328        }
329        let x = (reference - t * t.dot(reference)).normalize_or_zero();
330        if x == Vec3::ZERO {
331            return Err(GeomError::InvalidInput(
332                "sweep reference direction must not be parallel to the directrix".to_owned(),
333            ));
334        }
335        Ok(Self {
336            origin,
337            x,
338            y: t.cross(x),
339        })
340    }
341}
342
343/// Place a profile point using a frame.
344pub fn at(frame: &Frame, p: Point2) -> Point3 {
345    frame.origin + frame.x * p.x + frame.y * p.y
346}
347
348/// Linear blend of two profile rings.
349///
350/// Tapered families interpolate between a start and an end profile, so the
351/// blend belongs here rather than in each of them.
352pub fn blend(a: Point2, b: Point2, t: Scalar) -> Point2 {
353    Point2::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
354}
355
356/// Loft where the two ends carry different profiles.
357///
358/// [`loft`] caps both ends from one ring set, which is wrong the moment the
359/// ends differ: a tapered solid needs each cap triangulated from its own
360/// profile. The walls are identical, so only the caps are rebuilt here.
361pub fn loft_tapered(start: &Rings, end: &Rings, stations: &[Station]) -> GeomResult<TriMesh> {
362    let mut mesh = loft(start, stations, false)?;
363    let per_station: usize = stations[0].loops.iter().map(|r| r.len()).sum();
364    // Drop the caps `loft` built from `start` and rebuild the far one from
365    // `end`. Wall triangles come first, so truncating to the wall count is
366    // exact rather than a search.
367    let spans = stations.len() - 1;
368    let ring_edges: usize = stations[0].loops.iter().map(|r| r.len()).sum();
369    let wall_indices = spans * ring_edges * 6;
370    mesh.indices.truncate(wall_indices);
371    let (near_pts, near_tris) = crate::profile::triangulate(start)?;
372    let (far_pts, far_tris) = crate::profile::triangulate(end)?;
373    if near_pts.len() != per_station || far_pts.len() != per_station {
374        return Err(GeomError::Degenerate(
375            "tapered cap triangulation disagrees with the station rings".to_owned(),
376        ));
377    }
378    let last = (spans * per_station) as u32;
379    for t in &near_tris {
380        mesh.indices.extend([t[0], t[2], t[1]]);
381    }
382    for t in &far_tris {
383        mesh.indices.extend([last + t[0], last + t[1], last + t[2]]);
384    }
385    Ok(mesh)
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use axiolid_measure::proximity::closest_point_on_triangle;
392
393    /// The largest distance from a dense sampling of the bilinear patch to
394    /// the loft's two triangles, measured by brute force.
395    fn measured(a: Point3, b: Point3, c: Point3, d: Point3) -> Scalar {
396        let n = 64;
397        let mut worst: Scalar = 0.0;
398        for i in 0..=n {
399            for j in 0..=n {
400                let (x, y) = (i as Scalar / n as Scalar, j as Scalar / n as Scalar);
401                let p = (a * (1.0 - x) + b * x) * (1.0 - y) + (c * (1.0 - x) + d * x) * y;
402                let near = [[a, b, d], [a, d, c]]
403                    .iter()
404                    .filter_map(|t| closest_point_on_triangle(p, *t).ok())
405                    .map(|q| p.distance(q))
406                    .fold(Scalar::INFINITY, Scalar::min);
407                worst = worst.max(near);
408            }
409        }
410        worst
411    }
412
413    /// A deterministic spread of quads: planar convex, planar concave
414    /// (the loft's diagonal outside the quad), twisted, and collapsed.
415    fn quads() -> Vec<[Point3; 4]> {
416        let mut seed: u64 = 0x2310_5eed;
417        let mut next = move || {
418            seed = seed
419                .wrapping_mul(6_364_136_223_846_793_005)
420                .wrapping_add(1_442_695_040_888_963_407);
421            ((seed >> 11) as Scalar / (1u64 << 53) as Scalar) * 2.0 - 1.0
422        };
423        let mut out = vec![
424            // Planar trapezoid: a revolution's wall about an in-plane axis.
425            [
426                Point3::new(0.0, 0.0, 0.0),
427                Point3::new(1.0, 0.0, 0.0),
428                Point3::new(0.0, 1.0, 0.0),
429                Point3::new(1.2, 1.0, 0.0),
430            ],
431            // Planar, but `d` folded back across the diagonal a-d: concave.
432            [
433                Point3::new(0.0, 0.0, 0.0),
434                Point3::new(1.0, 0.0, 0.0),
435                Point3::new(0.0, 1.0, 0.0),
436                Point3::new(0.2, 0.2, 0.0),
437            ],
438            // A saddle: the hyperbolic paraboloid z = xy.
439            [
440                Point3::new(0.0, 0.0, 0.0),
441                Point3::new(1.0, 0.0, 0.0),
442                Point3::new(0.0, 1.0, 0.0),
443                Point3::new(1.0, 1.0, 1.0),
444            ],
445            // Collapsed onto an axis: a and b coincide.
446            [
447                Point3::new(0.0, 0.0, 0.0),
448                Point3::new(0.0, 0.0, 0.0),
449                Point3::new(0.0, 1.0, 0.0),
450                Point3::new(1.0, 1.0, 0.3),
451            ],
452        ];
453        for _ in 0..200 {
454            let mut q = [Point3::ZERO; 4];
455            for p in &mut q {
456                *p = Point3::new(next(), next(), 0.3 * next());
457            }
458            out.push(q);
459        }
460        out
461    }
462
463    #[test]
464    fn the_quad_bound_holds_for_every_quad() {
465        for [a, b, c, d] in quads() {
466            let bound = quad_deviation(a, b, c, d);
467            let got = measured(a, b, c, d);
468            assert!(
469                got <= bound * (1.0 + 1e-9) + 1e-12,
470                "quad {a:?} {b:?} {c:?} {d:?}: patch {got} from its triangles, bound {bound}"
471            );
472        }
473    }
474
475    #[test]
476    fn a_planar_convex_quad_costs_nothing() {
477        let [a, b, c, d] = quads()[0];
478        assert!(quad_deviation(a, b, c, d) <= 1e-15);
479    }
480
481    #[test]
482    fn a_twisted_quad_is_bounded_tightly() {
483        // z = xy: the patch's centre is |T| / 4 = 1/4 above the diagonal's
484        // midpoint, and 1/(4 sqrt 2) from the triangles' planes.
485        let [a, b, c, d] = quads()[2];
486        let bound = quad_deviation(a, b, c, d);
487        assert!((bound - 0.25).abs() <= 1e-12, "{bound}");
488        let got = measured(a, b, c, d);
489        assert!((got - 0.25 / 2f64.sqrt()).abs() <= 1e-3, "{got}");
490    }
491}