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