engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::f64::consts::TAU;

use crate::common::arc_segments_for_tol;
use crate::common::transform_points;
use crate::common::triangulation::ParallelBuilder;
use crate::geom2::Boundary2;
use crate::geom3::IsoExtensions3;
use crate::geom3::align3::{AlignSurfMatch3, SurfaceTarget3};
use crate::{Iso3, Mesh3, Point2, Point3, Result, To2D, To3D, UnitVec3, Vector3};

/// An `ExtrudedBoundary3` is a means of representing a surface in 3D space using a 2D [`Boundary2`]
/// entity and an arbitrary 3D position, direction, and length. The surface is the set of all points
/// which the boundary passes through in an imaginary sweep of the given length and in the
/// specified direction.
pub struct ExtrudedBoundary3 {
    /// A boundary in the X-Y plane which is the basis of the sweep. It does not matter if the
    /// boundary is closed or open.
    shape: Boundary2,

    /// A transformation that brings the X-Y boundary to an arbitrary position in 3D space.
    start: Iso3,

    /// The inverse of the start isometry
    start_inv: Iso3,

    /// The length that the boundary is extruded along the `start` isometry's Z axis in the 3D
    /// world coordinates.
    length: f64,
}

impl ExtrudedBoundary3 {
    /// Create a surface representation consisting of a boundary (defined in the 2D, X-Y plane)
    /// transformed to a given position and orientation in 3D space, and then swept along by a
    /// given length.
    ///
    /// # Arguments
    ///
    /// * `shape`: the 2d boundary, defined in the X-Y plane
    /// * `start`: an isometry to transform the 2D boundary to the starting position and orientation
    ///   in 3D space. The boundary will be swept along the positive Z direction of this starting
    ///   isometry.
    /// * `length`: the distance along the `start` argument's positive Z direction to sweep the
    ///   boundary. The boundary will exist between 0.0 and `length`.
    ///
    /// returns: ExtrudedBoundary3
    pub fn new(shape: Boundary2, start: Iso3, length: f64) -> Self {
        let start_inv = start.inverse();
        Self {
            shape,
            start,
            start_inv,
            length,
        }
    }

    pub fn to_mesh(&self, tol: f64) -> Result<Mesh3> {
        let points = self.shape.to_points(tol)?.to_3d();
        let mut builder = ParallelBuilder::new(points.len(), false);

        let p0 = transform_points(&points, &self.start);
        builder.push(&p0)?;

        let iso2 = self.start * Iso3::translation(0.0, 0.0, self.length);
        let p1 = transform_points(&points, &iso2);
        builder.push(&p1)?;

        let (points, faces) = builder.take();

        Ok(Mesh3::new(points, faces, false))
    }

    pub fn transform_by(&mut self, iso: &Iso3) {
        self.start = iso * self.start;
        self.start_inv = self.start.inverse();
    }
}

impl SurfaceTarget3 for ExtrudedBoundary3 {
    fn find_align_match(&self, p: &Point3) -> AlignSurfMatch3 {
        // First we want to bring the test point into the local coordinates of the start isometry
        // so we can work with the 2D boundary.
        let lp3 = self.start_inv * p;
        let lp2 = lp3.to_2d();

        // Now we get the closest point on the boundary and create the local 3d point and normal
        let (_, m) = self.shape.at_closest_to_point(&lp2);
        let lc3 = Point3::new(m.point.x, m.point.y, lp3.z);
        let ln3 = UnitVec3::new_normalize(m.normal.into_inner().to_3d());

        // Now we figure out if we're off the boundary by either missing the z interval or by
        // projecting onto a boundary end.
        let is_off = lp3.z < 0.0
            || lp3.z > self.length
            || (!self.shape.is_closed()
                && (m.l <= f64::EPSILON || m.l >= self.shape.length() - f64::EPSILON));

        AlignSurfMatch3::new(self.start * lc3, self.start * ln3, !is_off, 1.0)
    }
}

/// A `RevolvedBoundary3` is a means of representing a surface in 3D space using a 2D [`Boundary2`]
/// entity and an arbitrary 3D position, orientation, and sweep angle.  The boundary is defined in
/// the 2D X-Y plane, and transformed to 3D space by the `start` isometry. There it is rotated
/// around the `start` isometry's Y axis, which is the equivalent of the Y axis in the original
/// 2D boundary definition.  It is rotated by angle `theta`.
pub struct RevolvedBoundary3 {
    shape: Boundary2,
    start: Iso3,
    start_inv: Iso3,
    theta: f64,
}

impl RevolvedBoundary3 {
    /// Create a surface representation consisting of a boundary (defined in the 2D, X-Y plane)
    /// transformed to a given position and orientation in 3D space, and then revolved around the
    /// Y axis of the `start` isometry by a given angle.
    ///
    /// In the 2D profile, the X coordinate is the radial distance from the Y axis, and the Y
    /// coordinate is the position along the rotation axis.
    ///
    /// # Arguments
    ///
    /// * `shape`: the 2D boundary profile, defined in the X-Y plane
    /// * `start`: an isometry to transform the 2D boundary to a starting position and orientation
    ///   in 3D space. The profile will be revolved around the positive Y axis of this isometry.
    /// * `theta`: the angle in radians to sweep the boundary around the Y axis, starting from
    ///   angle 0. The boundary will exist between 0.0 and `theta`.
    ///
    /// returns: RevolvedBoundary3
    pub fn new(shape: Boundary2, start: Iso3, theta: f64) -> Self {
        let theta = if theta.abs() > TAU {
            TAU * theta.signum()
        } else {
            theta
        };

        let start_inv = start.inverse();
        Self {
            shape,
            start,
            start_inv,
            theta,
        }
    }

    /// Tessellate the revolved surface into a mesh.
    ///
    /// The profile and sweep are each discretized to a chordal tolerance of `tol`. The sweep's
    /// division count is calculated at the profile's largest radius, where a given angular step
    /// deviates most from the true surface. Every other point on the profile is therefore resolved
    /// at least as finely.
    ///
    /// # Arguments
    ///
    /// * `tol`: the maximum allowed chordal deviation, which must be positive and finite
    ///
    /// returns: `Result<Mesh3>`, failing if the boundary produced no points, if the profile lies
    /// entirely on the axis of revolution, or if `tol` is invalid
    pub fn to_mesh(&self, tol: f64) -> Result<Mesh3> {
        let points = self.shape.to_points(tol)?.to_3d();

        // Find the largest radius
        let r_max = points
            .iter()
            .map(|p| p.x.abs())
            .max_by(|a, b| a.partial_cmp(b).unwrap())
            .ok_or("Boundary has no points".to_string())?;

        // The sign of `theta` determines the sweep direction, while its magnitude determines the
        // number of steps.
        let n_segments = arc_segments_for_tol(r_max, self.theta, tol)?;
        let angle_step = self.theta / n_segments as f64;

        let mut builder = ParallelBuilder::new(points.len(), false);

        let p0 = transform_points(&points, &self.start);
        builder.push(&p0)?;

        for i in 0..n_segments {
            let t = (i + 1) as f64 * angle_step;
            let iso = self.start * Iso3::from_ry(t);
            let pn = transform_points(&points, &iso);
            builder.push(&pn)?;
        }

        let (points, faces) = builder.take();

        Ok(Mesh3::new(points, faces, false))
    }

    pub fn transform_by(&mut self, iso: &Iso3) {
        self.start = iso * self.start;
        self.start_inv = self.start.inverse();
    }
}

impl SurfaceTarget3 for RevolvedBoundary3 {
    fn find_align_match(&self, p: &Point3) -> AlignSurfMatch3 {
        // Transform to local coordinates where the rotation axis is Y and the profile starts
        // in the X-Y half-plane (positive X)
        let lp3 = self.start_inv * p;

        // Cylindrical coordinates: radial distance from Y axis and azimuthal angle
        let r = lp3.x.hypot(lp3.z);
        let phi = f64::atan2(lp3.z, lp3.x).rem_euclid(TAU);

        // Query the 2D profile boundary with (radius, axial) coordinates
        let lp2 = Point2::new(r, lp3.y);
        let (_, m) = self.shape.at_closest_to_point(&lp2);

        // Reconstruct the 3D closest point and surface normal at the same azimuthal angle
        let (cos_phi, sin_phi) = (phi.cos(), phi.sin());
        let r_c = m.point.x;
        let y_c = m.point.y;
        let n = m.normal.into_inner();
        let lc3 = Point3::new(r_c * cos_phi, y_c, r_c * sin_phi);
        let ln3 = UnitVec3::new_normalize(Vector3::new(n.x * cos_phi, n.y, n.x * sin_phi));

        // Off the surface if outside the angular sweep, or at ends of an open profile
        let is_off = phi > self.theta
            || (!self.shape.is_closed()
                && (m.l <= f64::EPSILON || m.l >= self.shape.length() - f64::EPSILON));

        AlignSurfMatch3::new(self.start * lc3, self.start * ln3, !is_off, 1.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Vector3;
    use crate::common::random_geometry::RandomGeometry3;
    use crate::geom2::{BoundaryData2, BoundaryEditor};
    use approx::assert_relative_eq;

    fn open_extruded() -> ExtrudedBoundary3 {
        let mut data = BoundaryData2::new_open_xy(1.0, 0.0);
        data.add_seg_xy(0.0, 0.0);
        data.add_seg_xy(0.0, 1.0);
        let b = data.try_to_boundary().unwrap();
        ExtrudedBoundary3::new(b, Iso3::identity(), 1.0)
    }

    fn p(x: f64, y: f64, z: f64) -> Point3 {
        Point3::new(x, y, z)
    }

    /// A straight profile at a constant distance of two units from the axis, so revolving it
    /// produces a cylinder with radius 2.
    fn straight_profile() -> Boundary2 {
        let mut data = BoundaryData2::new_open_xy(2.0, -1.0);
        data.add_seg_xy(2.0, 1.0);
        data.try_to_boundary().unwrap()
    }

    /// The sweep angle at which a mesh point was generated. `from_ry` sends `+z` toward `+x`, so
    /// the angle can be recovered from those two coordinates.
    fn sweep_angle(point: &Point3) -> f64 {
        (-point.z).atan2(point.x)
    }

    /// Every chord of the revolved surface must sag inward from the true cylinder by no more than
    /// the requested tolerance.
    #[test]
    fn a_revolve_holds_the_chordal_tolerance() -> Result<()> {
        let tol = 0.01;
        let radius = 2.0;
        let mesh =
            RevolvedBoundary3::new(straight_profile(), Iso3::identity(), TAU).to_mesh(tol)?;

        for f in mesh.faces() {
            let a = mesh.points()[f[0] as usize];
            let b = mesh.points()[f[1] as usize];
            let c = mesh.points()[f[2] as usize];

            for (u, v) in [(a, b), (b, c), (c, a)] {
                let mid = crate::na::center(&u, &v);
                let sag = radius - mid.x.hypot(mid.z);
                assert!(sag >= -1.0e-12, "a chord midpoint sits outside the surface");
                assert!(sag <= tol + 1.0e-12, "sag {sag} exceeds tol {tol}");
            }
        }

        Ok(())
    }

    /// A tolerance too loose to constrain the tessellation previously left the revolved surface
    /// with a single step, producing a wedge instead of a surface. The shared helper ensures that a
    /// full turn has at least eight steps, regardless of how loose the requested tolerance is.
    #[test]
    fn a_revolve_never_gets_fewer_than_eight_steps() -> Result<()> {
        let mesh =
            RevolvedBoundary3::new(straight_profile(), Iso3::identity(), TAU).to_mesh(10.0)?;

        let mut angles = mesh.points().iter().map(sweep_angle).collect::<Vec<_>>();
        angles.sort_by(|a, b| a.partial_cmp(b).unwrap());
        angles.dedup_by(|a, b| (*a - *b).abs() < 1.0e-9);

        // Eight steps around. The ring that closes the full turn contains a separate set of points
        // from the starting ring, but it lands at the same angle, leaving eight distinct angles.
        assert_eq!(angles.len(), 8);

        Ok(())
    }

    /// A tolerance that cannot be converted into a step count previously produced a NaN angle and
    /// then a silently malformed mesh.
    #[test]
    fn a_revolve_rejects_an_invalid_tolerance() {
        let target = RevolvedBoundary3::new(straight_profile(), Iso3::identity(), TAU);
        assert!(target.to_mesh(0.0).is_err());
        assert!(target.to_mesh(-1.0).is_err());
    }

    #[test]
    fn extruded_points_off() {
        let target = open_extruded();

        assert!(!target.find_align_match(&p(2.0, 0.0, 0.5)).is_on);
        assert!(!target.find_align_match(&p(0.0, 2.0, 0.5)).is_on);
        assert!(!target.find_align_match(&p(0.0, 0.0, -1.0)).is_on);
        assert!(!target.find_align_match(&p(0.0, 0.0, 2.0)).is_on);
    }

    #[test]
    fn extruded_points_on() {
        let target = open_extruded();
        assert!(target.find_align_match(&p(0.5, 0.1, 0.5)).is_on);
        assert!(target.find_align_match(&p(0.1, 0.5, 0.5)).is_on);
    }

    #[test]
    fn extruded_known_points() {
        let pairs = vec![
            ([0.0, 2.0, 0.5], [0.0, 1.0, 0.5], None),
            ([2.0, 0.0, 0.5], [1.0, 0.0, 0.5], None),
            ([0.5, 0.1, 0.3], [0.5, 0.0, 0.3], Some([0.0, 1.0, 0.0])),
            ([0.1, 0.5, 0.3], [0.0, 0.5, 0.3], Some([1.0, 0.0, 0.0])),
            ([0.0, 2.0, -1.0], [0.0, 1.0, -1.0], None),
            ([2.0, 0.0, -1.0], [1.0, 0.0, -1.0], None),
            ([0.0, 2.0, 2.0], [0.0, 1.0, 2.0], None),
            ([2.0, 0.0, 2.0], [1.0, 0.0, 2.0], None),
            ([-1.0, -1.0, 0.5], [0.0, 0.0, 0.5], None),
            ([-1.0, -1.0, -1.0], [0.0, 0.0, -1.0], None),
            ([-1.0, -1.0, 2.0], [0.0, 0.0, 2.0], None),
        ];

        let mut rg = RandomGeometry3::new();

        for _ in 0..100 {
            let iso = rg.iso3(10.0);

            let mut data = BoundaryData2::new_open_xy(1.0, 0.0);
            data.add_seg_xy(0.0, 0.0);
            data.add_seg_xy(0.0, 1.0);
            let b = data.try_to_boundary().unwrap();
            let target = ExtrudedBoundary3::new(b, iso, 1.0);

            for (t, e, n) in pairs.iter() {
                let t = iso * Point3::from(*t);
                let e = iso * Point3::from(*e);

                let c = target.find_align_match(&t);
                assert_relative_eq!(c.point, e, epsilon = 1.0e-6);

                if let Some(n) = n {
                    let n = iso * UnitVec3::new_normalize(Vector3::from_column_slice(n));
                    assert_relative_eq!(c.normal, n, epsilon = 1.0e-6);
                }
            }
        }
    }

    // Profile: open segment from (1,0) to (1,1) in 2D, a cylindrical surface at radius 1,
    // height 0..1, revolved by the given theta around the Y axis.
    fn open_revolved(theta: f64) -> RevolvedBoundary3 {
        let mut data = BoundaryData2::new_open_xy(1.0, 0.0);
        data.add_seg_xy(1.0, 1.0);
        let b = data.try_to_boundary().unwrap();
        RevolvedBoundary3::new(b, Iso3::identity(), theta)
    }

    #[test]
    fn revolved_points_on() {
        let full = open_revolved(TAU);
        // Front, side, and back of the cylinder mid-height
        assert!(full.find_align_match(&p(2.0, 0.5, 0.0)).is_on);
        assert!(full.find_align_match(&p(0.0, 0.5, 2.0)).is_on);
        assert!(full.find_align_match(&p(-2.0, 0.5, 0.0)).is_on);

        let half = open_revolved(std::f64::consts::PI);
        // phi=0 and phi=PI/2 are within [0, PI]
        assert!(half.find_align_match(&p(2.0, 0.5, 0.0)).is_on);
        assert!(half.find_align_match(&p(0.0, 0.5, 2.0)).is_on);
    }

    #[test]
    fn revolved_points_off() {
        let full = open_revolved(TAU);
        // Off at the open profile ends (above and below the height range)
        assert!(!full.find_align_match(&p(2.0, -1.0, 0.0)).is_on);
        assert!(!full.find_align_match(&p(2.0, 2.0, 0.0)).is_on);

        let half = open_revolved(std::f64::consts::PI);
        // phi = atan2(-2, 0) = -PI/2, rem_euclid = 3*PI/2 > PI: off angular sweep
        assert!(!half.find_align_match(&p(0.0, 0.5, -2.0)).is_on);
        // phi slightly greater than PI is off the half sweep
        assert!(!half.find_align_match(&p(-1.0, 0.5, -0.1)).is_on);
    }

    #[test]
    fn revolved_known_points() {
        use std::f64::consts::{FRAC_1_SQRT_2, SQRT_2};

        // (test_point, expected_closest, Option<expected_normal>)
        // Profile: open segment (1,0)→(1,1) in 2D, revolved fully (TAU) around the Y axis.
        // Rotation axis is Y; X is radial; Z is the other radial axis.
        // Note: off-surface points project onto the nearest profile point (not the query y).
        // Test table of (query, expected-point, expected-normal) triples.
        #[allow(clippy::type_complexity)]
        let pairs: Vec<([f64; 3], [f64; 3], Option<[f64; 3]>)> = vec![
            // +X side, mid-height
            ([2.0, 0.5, 0.0], [1.0, 0.5, 0.0], Some([1.0, 0.0, 0.0])),
            // +Z side (phi = PI/2)
            ([0.0, 0.5, 2.0], [0.0, 0.5, 1.0], Some([0.0, 0.0, 1.0])),
            // -X side (phi = PI)
            ([-2.0, 0.5, 0.0], [-1.0, 0.5, 0.0], Some([-1.0, 0.0, 0.0])),
            // Diagonal at phi = PI/4; test point r=2, closest r=1
            (
                [SQRT_2, 0.5, SQRT_2],
                [FRAC_1_SQRT_2, 0.5, FRAC_1_SQRT_2],
                Some([FRAC_1_SQRT_2, 0.0, FRAC_1_SQRT_2]),
            ),
            // Below profile (off, open end): closest projects to profile start at y=0
            ([2.0, -1.0, 0.0], [1.0, 0.0, 0.0], Some([1.0, 0.0, 0.0])),
            // Above profile (off, open end): closest projects to profile end at y=1
            ([2.0, 2.0, 0.0], [1.0, 1.0, 0.0], Some([1.0, 0.0, 0.0])),
        ];

        let mut rg = RandomGeometry3::new();

        for _ in 0..100 {
            let iso = rg.iso3(10.0);

            let mut data = BoundaryData2::new_open_xy(1.0, 0.0);
            data.add_seg_xy(1.0, 1.0);
            let b = data.try_to_boundary().unwrap();
            let target = RevolvedBoundary3::new(b, iso, TAU);

            for (t, e, n) in pairs.iter() {
                let t = iso * Point3::from(*t);
                let e = iso * Point3::from(*e);

                let c = target.find_align_match(&t);
                assert_relative_eq!(c.point, e, epsilon = 1.0e-6);

                if let Some(n) = n {
                    let n = iso * UnitVec3::new_normalize(Vector3::from_column_slice(n));
                    assert_relative_eq!(c.normal, n, epsilon = 1.0e-6);
                }
            }
        }
    }
}