BREP_RANSAC 0.1.2

Topology-aware analytic surface recognition for CAD triangle meshes
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Safe translation of neighboring analytic geometry into constrained hints.
//!
//! These helpers deliberately produce ordinary [`SurfaceHint::Constrained`]
//! values. They do not add a hidden coupled solver or claim relations that the
//! current parameter-group constraints cannot preserve.

use crate::{
    AnalyticSurface, ConstraintMask, CylinderSurface, MetadataTrust, PlaneSurface, SphereSurface,
    SurfaceConstraints, SurfaceHint, SurfaceType, Vec3,
};
use std::fmt::{Display, Formatter};

/// Failure to express a requested design-intent relation with the current
/// parameter-group constraint model.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DesignIntentError {
    /// The target or reference carrier contains invalid parameters.
    InvalidSurface {
        /// Whether the invalid carrier was the `target` or `reference`.
        role: &'static str,
    },
    /// The supplied geometry does not determine a unique requested relation.
    DegenerateRelation {
        /// Human-readable name of the degenerate relation.
        relation: &'static str,
    },
    /// The relation cannot be represented by the current parameter groups.
    UnsupportedRelation {
        /// Human-readable name of the unsupported relation.
        relation: &'static str,
        /// Primitive type that would be constrained.
        target: SurfaceType,
        /// Primitive type used as design-intent evidence.
        reference: SurfaceType,
    },
}

impl Display for DesignIntentError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidSurface { role } => write!(formatter, "invalid {role} analytic surface"),
            Self::DegenerateRelation { relation } => {
                write!(formatter, "cannot derive a unique {relation} relation")
            }
            Self::UnsupportedRelation {
                relation,
                target,
                reference,
            } => write!(
                formatter,
                "{relation} is not representable for {target:?} from {reference:?} with current parameter groups"
            ),
        }
    }
}

impl std::error::Error for DesignIntentError {}

fn validate(target: AnalyticSurface, reference: AnalyticSurface) -> Result<(), DesignIntentError> {
    if !target.is_valid() {
        return Err(DesignIntentError::InvalidSurface { role: "target" });
    }
    if !reference.is_valid() {
        return Err(DesignIntentError::InvalidSurface { role: "reference" });
    }
    Ok(())
}

fn hint(surface: AnalyticSurface, fixed: ConstraintMask) -> SurfaceHint {
    SurfaceHint::Constrained {
        surface_type: surface.surface_type(),
        constraints: SurfaceConstraints {
            initial: Some(surface),
            fixed,
        },
        trust: MetadataTrust::StrongHint,
    }
}

fn axial_line(surface: AnalyticSurface) -> Option<(Vec3, Vec3)> {
    match surface {
        AnalyticSurface::Cylinder(value) => Some((value.axis_origin, value.axis)),
        AnalyticSurface::Cone(value) => Some((value.apex, value.axis)),
        AnalyticSurface::Torus(value) => Some((value.center, value.axis)),
        _ => None,
    }
}

fn aligned(reference: Vec3, preferred: Vec3) -> Vec3 {
    if reference.dot(preferred) < 0.0 {
        -reference
    } else {
        reference
    }
}

/// Fix a target cylinder, cone, or torus axis direction to an existing axial
/// carrier. Cone-to-nondirected-carrier transfer is rejected because a cone's
/// nappe direction is not sign-equivalent.
pub fn constrain_shared_axis(
    target: AnalyticSurface,
    reference: AnalyticSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    validate(target, reference)?;
    let (_, reference_axis) =
        axial_line(reference).ok_or_else(|| unsupported("shared axis", target, reference))?;
    let constrained = match target {
        AnalyticSurface::Cylinder(mut value) => {
            value.axis = aligned(reference_axis, value.axis);
            AnalyticSurface::Cylinder(value)
        }
        AnalyticSurface::Torus(mut value) => {
            value.axis = aligned(reference_axis, value.axis);
            AnalyticSurface::Torus(value)
        }
        AnalyticSurface::Cone(mut value) if matches!(reference, AnalyticSurface::Cone(_)) => {
            value.axis = reference_axis;
            AnalyticSurface::Cone(value)
        }
        _ => return Err(unsupported("shared axis", target, reference)),
    };
    Ok(hint(
        constrained,
        ConstraintMask {
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Constrain a cylinder to the complete axis line of another axial carrier.
/// This is safe because a cylinder's axis origin has gauge freedom along the
/// line; cone apex and torus center locations do not, so those target types are
/// intentionally unsupported here.
pub fn constrain_cylinder_coaxial(
    target: CylinderSurface,
    reference: AnalyticSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    let target_surface = AnalyticSurface::Cylinder(target);
    validate(target_surface, reference)?;
    let (reference_origin, reference_axis) = axial_line(reference)
        .ok_or_else(|| unsupported("coaxial axes", target_surface, reference))?;
    let constrained = AnalyticSurface::Cylinder(CylinderSurface {
        axis_origin: reference_origin,
        axis: aligned(reference_axis, target.axis),
        radius: target.radius,
    });
    Ok(hint(
        constrained,
        ConstraintMask {
            origin_or_center: true,
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Constrain a plane to be perpendicular to a known axis. The plane normal is
/// the axis direction; its offset remains free.
pub fn constrain_plane_perpendicular_to_axis(
    target: PlaneSurface,
    axis: Vec3,
) -> Result<SurfaceHint, DesignIntentError> {
    let axis = axis.normalized().filter(|axis| axis.is_finite()).ok_or(
        DesignIntentError::DegenerateRelation {
            relation: "plane perpendicular to axis",
        },
    )?;
    let target_surface = AnalyticSurface::Plane(target);
    if !target_surface.is_valid() {
        return Err(DesignIntentError::InvalidSurface { role: "target" });
    }
    Ok(hint(
        AnalyticSurface::Plane(PlaneSurface {
            normal: aligned(axis, target.normal),
            ..target
        }),
        ConstraintMask {
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Preserve parallelism to a reference plane while leaving plane offset free.
pub fn constrain_planes_parallel(
    target: PlaneSurface,
    reference: PlaneSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    let target_surface = AnalyticSurface::Plane(target);
    let reference_surface = AnalyticSurface::Plane(reference);
    validate(target_surface, reference_surface)?;
    Ok(hint(
        AnalyticSurface::Plane(PlaneSurface {
            normal: aligned(reference.normal, target.normal),
            ..target
        }),
        ConstraintMask {
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Preserve perpendicularity to a reference plane using the target's current
/// normal to select the otherwise non-unique perpendicular direction.
pub fn constrain_planes_perpendicular(
    target: PlaneSurface,
    reference: PlaneSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    let target_surface = AnalyticSurface::Plane(target);
    let reference_surface = AnalyticSurface::Plane(reference);
    validate(target_surface, reference_surface)?;
    let projected = target.normal - reference.normal * target.normal.dot(reference.normal);
    let normal = projected
        .normalized()
        .ok_or(DesignIntentError::DegenerateRelation {
            relation: "perpendicular planes",
        })?;
    Ok(hint(
        AnalyticSurface::Plane(PlaneSurface { normal, ..target }),
        ConstraintMask {
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Fix a plane to the same infinite carrier as a reference plane. Tangential
/// origin coordinates are a gauge and are preserved from the target.
pub fn constrain_planes_coplanar(
    target: PlaneSurface,
    reference: PlaneSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    let target_surface = AnalyticSurface::Plane(target);
    let reference_surface = AnalyticSurface::Plane(reference);
    validate(target_surface, reference_surface)?;
    let normal = aligned(reference.normal, target.normal);
    let origin = target.origin + normal * (reference.origin - target.origin).dot(normal);
    Ok(hint(
        AnalyticSurface::Plane(PlaneSurface { origin, normal }),
        ConstraintMask {
            origin_or_center: true,
            axis_or_normal: true,
            ..Default::default()
        },
    ))
}

/// Fix sphere or torus centers to an existing sphere/torus center.
pub fn constrain_concentric_centers(
    target: AnalyticSurface,
    reference: AnalyticSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    validate(target, reference)?;
    let reference_center = match reference {
        AnalyticSurface::Sphere(value) => value.center,
        AnalyticSurface::Torus(value) => value.center,
        _ => return Err(unsupported("concentric centers", target, reference)),
    };
    let constrained = match target {
        AnalyticSurface::Sphere(mut value) => {
            value.center = reference_center;
            AnalyticSurface::Sphere(value)
        }
        AnalyticSurface::Torus(mut value) => {
            value.center = reference_center;
            AnalyticSurface::Torus(value)
        }
        _ => return Err(unsupported("concentric centers", target, reference)),
    };
    Ok(hint(
        constrained,
        ConstraintMask {
            origin_or_center: true,
            ..Default::default()
        },
    ))
}

/// Fix equal radius groups for two carriers of the same type. For tori this
/// copies and fixes both major and minor radii; mixed-type radius semantics are
/// deliberately rejected.
pub fn constrain_equal_radii(
    target: AnalyticSurface,
    reference: AnalyticSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    validate(target, reference)?;
    let (constrained, fixed) = match (target, reference) {
        (AnalyticSurface::Sphere(mut target), AnalyticSurface::Sphere(reference)) => {
            target.radius = reference.radius;
            (
                AnalyticSurface::Sphere(target),
                ConstraintMask {
                    radius: true,
                    ..Default::default()
                },
            )
        }
        (AnalyticSurface::Cylinder(mut target), AnalyticSurface::Cylinder(reference)) => {
            target.radius = reference.radius;
            (
                AnalyticSurface::Cylinder(target),
                ConstraintMask {
                    radius: true,
                    ..Default::default()
                },
            )
        }
        (AnalyticSurface::Torus(mut target), AnalyticSurface::Torus(reference)) => {
            target.major_radius = reference.major_radius;
            target.minor_radius = reference.minor_radius;
            (
                AnalyticSurface::Torus(target),
                ConstraintMask {
                    radius: true,
                    major_radius: true,
                    ..Default::default()
                },
            )
        }
        _ => return Err(unsupported("equal radii", target, reference)),
    };
    Ok(hint(constrained, fixed))
}

/// Derive exact sphere/plane tangency from the target's current side and
/// orientation. Other tangency pairs require coupled parameters and are
/// rejected explicitly.
pub fn constrain_tangent(
    target: AnalyticSurface,
    reference: AnalyticSurface,
) -> Result<SurfaceHint, DesignIntentError> {
    validate(target, reference)?;
    match (target, reference) {
        (AnalyticSurface::Plane(target), AnalyticSurface::Sphere(reference)) => {
            let signed = (target.origin - reference.center).dot(target.normal);
            let side = if signed < 0.0 { -1.0 } else { 1.0 };
            let origin = reference.center + target.normal * (side * reference.radius);
            Ok(hint(
                AnalyticSurface::Plane(PlaneSurface { origin, ..target }),
                ConstraintMask {
                    origin_or_center: true,
                    axis_or_normal: true,
                    ..Default::default()
                },
            ))
        }
        (AnalyticSurface::Sphere(target), AnalyticSurface::Plane(reference)) => {
            let signed = (target.center - reference.origin).dot(reference.normal);
            let side = if signed < 0.0 { -1.0 } else { 1.0 };
            let tangent_component = target.center - reference.normal * signed;
            let center = tangent_component + reference.normal * (side * target.radius);
            Ok(hint(
                AnalyticSurface::Sphere(SphereSurface { center, ..target }),
                ConstraintMask {
                    origin_or_center: true,
                    radius: true,
                    ..Default::default()
                },
            ))
        }
        _ => Err(unsupported("tangency", target, reference)),
    }
}

fn unsupported(
    relation: &'static str,
    target: AnalyticSurface,
    reference: AnalyticSurface,
) -> DesignIntentError {
    DesignIntentError::UnsupportedRelation {
        relation,
        target: target.surface_type(),
        reference: reference.surface_type(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ConeSurface, TorusSurface};

    fn constraints(hint: SurfaceHint) -> SurfaceConstraints {
        let SurfaceHint::Constrained { constraints, .. } = hint else {
            unreachable!()
        };
        constraints
    }

    #[test]
    fn relation_helpers_set_only_representable_parameter_groups() {
        let plane = PlaneSurface {
            origin: Vec3::new(0.0, 0.0, 2.0),
            normal: Vec3::Z,
        };
        let tilted = PlaneSurface {
            origin: Vec3::new(1.0, 2.0, 4.0),
            normal: Vec3::new(0.1, 0.0, 0.995).normalized().unwrap(),
        };
        let parallel = constraints(constrain_planes_parallel(tilted, plane).unwrap());
        assert!(parallel.fixed.axis_or_normal);
        let perpendicular = constraints(
            constrain_planes_perpendicular(
                PlaneSurface {
                    normal: Vec3::new(0.9, 0.1, 0.4).normalized().unwrap(),
                    ..tilted
                },
                plane,
            )
            .unwrap(),
        );
        let Some(AnalyticSurface::Plane(perpendicular_plane)) = perpendicular.initial else {
            unreachable!()
        };
        assert!(perpendicular_plane.normal.dot(plane.normal).abs() < 1.0e-12);
        let coplanar = constraints(constrain_planes_coplanar(tilted, plane).unwrap());
        assert!(coplanar.fixed.origin_or_center && coplanar.fixed.axis_or_normal);
        let Some(AnalyticSurface::Plane(coplanar_plane)) = coplanar.initial else {
            unreachable!()
        };
        assert!(
            (coplanar_plane.origin - plane.origin)
                .dot(plane.normal)
                .abs()
                < 1.0e-12
        );

        let sphere = AnalyticSurface::Sphere(SphereSurface {
            center: Vec3::ZERO,
            radius: 3.0,
        });
        let tangent =
            constraints(constrain_tangent(AnalyticSurface::Plane(plane), sphere).unwrap());
        assert!(tangent.fixed.origin_or_center && tangent.fixed.axis_or_normal);
        let Some(AnalyticSurface::Plane(tangent_plane)) = tangent.initial else {
            unreachable!()
        };
        assert!((tangent_plane.origin.distance(Vec3::ZERO) - 3.0).abs() < 1.0e-12);

        let torus = AnalyticSurface::Torus(TorusSurface {
            center: Vec3::new(2.0, 0.0, 0.0),
            axis: Vec3::Z,
            major_radius: 5.0,
            minor_radius: 1.0,
        });
        let concentric = constraints(constrain_concentric_centers(torus, sphere).unwrap());
        assert!(concentric.fixed.origin_or_center);

        let reference_cylinder = AnalyticSurface::Cylinder(CylinderSurface {
            axis_origin: Vec3::ZERO,
            axis: Vec3::Z,
            radius: 7.0,
        });
        let target_cylinder = AnalyticSurface::Cylinder(CylinderSurface {
            axis_origin: Vec3::X,
            axis: Vec3::Y,
            radius: 2.0,
        });
        let shared =
            constraints(constrain_shared_axis(target_cylinder, reference_cylinder).unwrap());
        assert!(shared.fixed.axis_or_normal && !shared.fixed.origin_or_center);
        let equal =
            constraints(constrain_equal_radii(target_cylinder, reference_cylinder).unwrap());
        assert!(equal.fixed.radius);
        let Some(AnalyticSurface::Cylinder(equal_cylinder)) = equal.initial else {
            unreachable!()
        };
        assert_eq!(equal_cylinder.radius, 7.0);
    }

    #[test]
    fn unsafe_coupled_relations_are_explicit_errors() {
        let cone = AnalyticSurface::Cone(ConeSurface {
            apex: Vec3::ZERO,
            axis: Vec3::Z,
            half_angle: 0.4,
        });
        let sphere = AnalyticSurface::Sphere(SphereSurface {
            center: Vec3::ZERO,
            radius: 2.0,
        });
        assert!(matches!(
            constrain_tangent(cone, sphere),
            Err(DesignIntentError::UnsupportedRelation { .. })
        ));
        assert!(matches!(
            constrain_equal_radii(cone, sphere),
            Err(DesignIntentError::UnsupportedRelation { .. })
        ));
    }
}