Skip to main content

brep_geometry/geometry/analytic_surface/
recognition.rs

1use super::*;
2
3pub fn nearly_equal_points(a: &NurbsSurface, b: &NurbsSurface, scale: f64) -> bool {
4    if a.degree_u != b.degree_u
5        || a.degree_v != b.degree_v
6        || a.knots_u.len() != b.knots_u.len()
7        || a.knots_v.len() != b.knots_v.len()
8        || a.control_points.len() != b.control_points.len()
9    {
10        return false;
11    }
12    // Numerical knot dedup for exact-reconstruction recognition (see curve.rs).
13    let knot_tolerance = crate::curve::KNOT_DEDUP_EPS;
14    if a.knots_u
15        .iter()
16        .zip(&b.knots_u)
17        .any(|(x, y)| (x - y).abs() > knot_tolerance)
18        || a.knots_v
19            .iter()
20            .zip(&b.knots_v)
21            .any(|(x, y)| (x - y).abs() > knot_tolerance)
22    {
23        return false;
24    }
25    let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
26    a.control_points
27        .iter()
28        .zip(&b.control_points)
29        .all(|(row_a, row_b)| {
30            row_a.len() == row_b.len()
31                && row_a.iter().zip(row_b).all(|(p, q)| {
32                    (p.x - q.x).abs() <= tolerance
33                        && (p.y - q.y).abs() <= tolerance
34                        && (p.z - q.z).abs() <= tolerance
35                        && (p.w - q.w).abs() <= RECOGNITION_TOLERANCE
36                })
37        })
38}
39
40pub fn surface_scale(surface: &NurbsSurface) -> f64 {
41    surface
42        .control_points
43        .iter()
44        .flatten()
45        .map(|p| (p.x.abs() / p.w).max(p.y.abs() / p.w).max(p.z.abs() / p.w))
46        .fold(0.0, f64::max)
47}
48
49pub fn full_circle_knots(spans: usize) -> Vec<f64> {
50    let mut knots = vec![0.0, 0.0, 0.0];
51    for index in 1..spans {
52        let knot = index as f64 / spans as f64;
53        knots.extend([knot, knot]);
54    }
55    knots.extend([1.0, 1.0, 1.0]);
56    knots
57}
58
59fn recognize_plane(surface: &NurbsSurface) -> Option<AnalyticSurface> {
60    if !surface.is_affine().unwrap_or(false) {
61        return None;
62    }
63    let u_domain = [surface.knots_u[0], *surface.knots_u.last()?];
64    let v_domain = [surface.knots_v[0], *surface.knots_v.last()?];
65    let extent_u = u_domain[1] - u_domain[0];
66    let extent_v = v_domain[1] - v_domain[0];
67    if extent_u <= 0.0 || extent_v <= 0.0 {
68        return None;
69    }
70    let p00 = surface.control_points[0][0].point().ok()?;
71    let p10 = surface.control_points[1][0].point().ok()?;
72    let p01 = surface.control_points[0][1].point().ok()?;
73    Some(AnalyticSurface::Plane {
74        origin: p00,
75        u_dir: p10.sub(p00).scale(1.0 / extent_u),
76        v_dir: p01.sub(p00).scale(1.0 / extent_v),
77        u_domain,
78        v_domain,
79    })
80}
81
82fn recognize_revolution(surface: &NurbsSurface) -> Option<AnalyticSurface> {
83    if surface.degree_u != 2 || surface.control_points.len() != 9 {
84        return None;
85    }
86    let expected_knots = full_circle_knots(4);
87    if surface.knots_u.len() != expected_knots.len()
88        || surface
89            .knots_u
90            .iter()
91            .zip(&expected_knots)
92            .any(|(a, b)| (a - b).abs() > 1e-12)
93    {
94        return None;
95    }
96    let scale = surface_scale(surface);
97    let rows = &surface.control_points;
98    // Antipodal full-circle control points straddle the axis; their midpoint
99    // lies on it for every generatrix column.
100    let mut frame: Option<RevolutionFrame> = None;
101    for column in 0..rows[0].len() {
102        let p0 = rows[0][column].point().ok()?;
103        let p180 = rows[4][column].point().ok()?;
104        let p90 = rows[2][column].point().ok()?;
105        let center = p0.add(p180).scale(0.5);
106        let radial = p0.sub(center);
107        let radius = radial.length();
108        if radius <= RECOGNITION_TOLERANCE * scale.max(1.0) {
109            continue;
110        }
111        let toward_90 = p90.sub(center);
112        let axis = radial.cross(toward_90).normalized().ok()?;
113        let x_axis = radial.scale(1.0 / radius);
114        let y_axis = axis.cross(x_axis);
115        frame = Some(RevolutionFrame {
116            origin: center,
117            axis,
118            x_axis,
119            y_axis,
120        });
121        break;
122    }
123    let frame = frame?;
124    let generatrix =
125        NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), rows[0].clone()).ok()?;
126    let rebuilt =
127        make_revolution(frame.origin, frame.axis, &generatrix, std::f64::consts::TAU).ok()?;
128    if !nearly_equal_points(surface, &rebuilt, scale) {
129        return None;
130    }
131    classify_generatrix(surface, frame, &generatrix, scale)
132}
133
134fn classify_generatrix(
135    surface: &NurbsSurface,
136    frame: RevolutionFrame,
137    generatrix: &NurbsCurve,
138    scale: f64,
139) -> Option<AnalyticSurface> {
140    let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
141    let controls = &generatrix.control_points;
142    if generatrix.degree == 1
143        && controls.len() == 2
144        && (controls[0].w - 1.0).abs() <= RECOGNITION_TOLERANCE
145        && (controls[1].w - 1.0).abs() <= RECOGNITION_TOLERANCE
146        && (surface.knots_v[0], *surface.knots_v.last()?) == (0.0, 1.0)
147        && generatrix_is_meridional_half_ray(generatrix, &frame)
148    {
149        let p0 = controls[0].point().ok()?;
150        let p1 = controls[1].point().ok()?;
151        let (_, rho0, z0) = frame.cylindrical(p0);
152        let (_, rho1, z1) = frame.cylindrical(p1);
153        let height = z1 - z0;
154        if height.abs() <= tolerance {
155            return None;
156        }
157        // Rebase the frame origin to the generatrix start's axial position
158        // so v = axial / height exactly.
159        let origin = frame.origin.add(frame.axis.scale(z0));
160        return Some(AnalyticSurface::RuledRevolution {
161            frame: RevolutionFrame { origin, ..frame },
162            rho0,
163            rho1,
164            height,
165        });
166    }
167    if generatrix.degree == 2 && controls.len() == 5 {
168        // Polar meridian: poles at both ends, equator at the middle column.
169        let south = controls[0].point().ok()?;
170        let north = controls[4].point().ok()?;
171        let (_, rho_south, z_south) = frame.cylindrical(south);
172        let (_, rho_north, z_north) = frame.cylindrical(north);
173        if rho_south <= tolerance && rho_north <= tolerance {
174            let radius = (z_north - z_south) * 0.5;
175            if radius <= tolerance {
176                return None;
177            }
178            let center = frame.origin.add(frame.axis.scale(z_south + radius));
179            let meridian = make_arc(
180                center,
181                frame.x_axis,
182                frame.axis,
183                radius,
184                -std::f64::consts::FRAC_PI_2,
185                std::f64::consts::FRAC_PI_2,
186            )
187            .ok()?;
188            if curves_nearly_equal(generatrix, &meridian, scale) {
189                return Some(AnalyticSurface::Sphere {
190                    frame: RevolutionFrame {
191                        origin: center,
192                        ..frame
193                    },
194                    radius,
195                });
196            }
197        }
198        return None;
199    }
200    if generatrix.degree == 2 && controls.len() == 9 {
201        let tube_start = controls[0].point().ok()?;
202        let tube_opposite = controls[4].point().ok()?;
203        let tube_center = tube_start.add(tube_opposite).scale(0.5);
204        let minor = tube_start.sub(tube_center).length();
205        let (_, major, axial) = frame.cylindrical(tube_center);
206        if minor <= tolerance || major <= minor || axial.abs() > tolerance {
207            return None;
208        }
209        let tube = make_arc(
210            tube_center,
211            frame.x_axis,
212            frame.axis,
213            minor,
214            0.0,
215            std::f64::consts::TAU,
216        )
217        .ok()?;
218        if curves_nearly_equal(generatrix, &tube, scale) {
219            return Some(AnalyticSurface::Torus {
220                frame,
221                major_radius: major,
222                minor_radius: minor,
223            });
224        }
225        return None;
226    }
227    None
228}
229
230fn curves_nearly_equal(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
231    if a.degree != b.degree
232        || a.knots.len() != b.knots.len()
233        || a.control_points.len() != b.control_points.len()
234    {
235        return false;
236    }
237    if a.knots
238        .iter()
239        .zip(&b.knots)
240        .any(|(x, y)| (x - y).abs() > 1e-12)
241    {
242        return false;
243    }
244    let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
245    a.control_points
246        .iter()
247        .zip(&b.control_points)
248        .all(|(p, q)| {
249            (p.x - q.x).abs() <= tolerance
250                && (p.y - q.y).abs() <= tolerance
251                && (p.z - q.z).abs() <= tolerance
252                && (p.w - q.w).abs() <= RECOGNITION_TOLERANCE
253        })
254}
255
256pub fn recognize(surface: &NurbsSurface) -> Option<AnalyticSurface> {
257    recognize_plane(surface)
258        .or_else(|| recognize_revolution(surface))
259        .or_else(|| recognize_general_revolution(surface))
260}
261
262/// Fallback recognizer: any `make_revolution` product the specialized
263/// quadric recognizers above rejected (arbitrary generatrix, partial
264/// sweep), validated by exact reconstruction in `revolution_structure`.
265fn recognize_general_revolution(surface: &NurbsSurface) -> Option<AnalyticSurface> {
266    let structure = revolution_structure(surface)?;
267    let spans = (surface.control_points.len() - 1) / 2;
268    Some(AnalyticSurface::Revolution {
269        frame: structure.frame,
270        spans,
271        sweep: structure.sweep,
272        generatrix: structure.generatrix,
273    })
274}
275
276/// Whether the generatrix lies in the axis frame's starting meridian
277/// half-plane.  Only then can a surface projection be reduced to projection
278/// onto the unrotated 3D generatrix.
279pub fn generatrix_is_meridional_half_ray(
280    generatrix: &NurbsCurve,
281    frame: &RevolutionFrame,
282) -> bool {
283    let mut scale = 0.0_f64;
284    for control in &generatrix.control_points {
285        let Ok(point) = control.point() else {
286            return false;
287        };
288        let offset = point.sub(frame.origin);
289        let radial = offset.sub(frame.axis.scale(offset.dot(frame.axis)));
290        scale = scale.max(radial.length());
291    }
292    let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
293    generatrix.control_points.iter().all(|control| {
294        let Ok(point) = control.point() else {
295            return false;
296        };
297        let offset = point.sub(frame.origin);
298        let radial = offset.sub(frame.axis.scale(offset.dot(frame.axis)));
299        radial.dot(frame.y_axis).abs() <= tolerance
300            && radial.dot(frame.x_axis) >= -tolerance
301    })
302}
303
304/// `BREP_PARTIAL_SPHERE` (default off, `1` on): a revolution of any sweep
305/// whose generatrix is an arc of a circle centred on the axis reads as its
306/// sphere ([`meridian_arc_sphere`]), not only a full pole-to-pole meridian
307/// swept all round.
308fn partial_sphere_enabled() -> bool {
309    crate::switch!(live "BREP_PARTIAL_SPHERE", false)
310}
311
312/// The sphere a revolution sweeps when its generatrix is a circular arc in
313/// the start meridian half-plane centred on the axis. The centre is the axis
314/// point equidistant from the generatrix's ends; the arc is PROVED circular
315/// span by span, exactly: the generatrix must be a rational quadratic in
316/// Bezier form (every interior knot doubled), and each span's ends lie at the
317/// radius, its middle control point on both end tangents, and its middle
318/// weight (normalized by the end weights) is the cosine of half the span's
319/// angle, which is what a circular arc's quadratic is.
320fn meridian_arc_sphere(frame: &RevolutionFrame, generatrix: &NurbsCurve) -> Option<(Vec3, f64)> {
321    if !generatrix_is_meridional_half_ray(generatrix, frame) || generatrix.degree != 2 {
322        return None;
323    }
324    let controls = &generatrix.control_points;
325    if controls.len() < 3 || controls.len() % 2 == 0 {
326        return None;
327    }
328    // Bezier form: knots 0,0,0, a,a, b,b, ..., 1,1,1.
329    let knots = &generatrix.knots;
330    if knots.len() != controls.len() + 3 {
331        return None;
332    }
333    for span in 0..(controls.len() - 1) / 2 {
334        if span > 0 && knots[2 * span + 1] != knots[2 * span + 2] {
335            return None;
336        }
337    }
338    let start = controls[0].point().ok()?;
339    let end = controls[controls.len() - 1].point().ok()?;
340    let (_, rho0, z0) = frame.cylindrical(start);
341    let (_, rho1, z1) = frame.cylindrical(end);
342    let scale = curve_scale(generatrix);
343    let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
344    if (z1 - z0).abs() <= tolerance {
345        return None;
346    }
347    let center_z = (z1 * z1 - z0 * z0 + rho1 * rho1 - rho0 * rho0) / (2.0 * (z1 - z0));
348    let center = frame.origin.add(frame.axis.scale(center_z));
349    let radius = start.sub(center).length();
350    if !(radius > tolerance) {
351        return None;
352    }
353    for span in 0..(controls.len() - 1) / 2 {
354        let (c0, c1, c2) = (controls[2 * span], controls[2 * span + 1], controls[2 * span + 2]);
355        let (p0, p1, p2) = (c0.point().ok()?, c1.point().ok()?, c2.point().ok()?);
356        let (r0, r2) = (p0.sub(center), p2.sub(center));
357        if (r0.length() - radius).abs() > tolerance || (r2.length() - radius).abs() > tolerance {
358            return None;
359        }
360        // The middle control point on both end tangents.
361        if p1.sub(p0).dot(r0).abs() > tolerance * radius || p1.sub(p2).dot(r2).abs() > tolerance * radius {
362            return None;
363        }
364        // The middle weight is cos(half the span's angle).
365        if !(c0.w > 0.0 && c2.w > 0.0) {
366            return None;
367        }
368        // A span that turns: distinct ends.
369        if p2.sub(p0).length() <= tolerance {
370            return None;
371        }
372        let cos_angle = (r0.dot(r2) / (radius * radius)).clamp(-1.0, 1.0);
373        let cos_half = ((1.0 + cos_angle) * 0.5).sqrt();
374        // The tangents meet at r / cos(half the angle) from the centre.
375        if !(cos_half > 1e-12) || (p1.sub(center).length() - radius / cos_half).abs() > tolerance / cos_half {
376            return None;
377        }
378        if (c1.w / (c0.w * c2.w).sqrt() - cos_half).abs() > 1e-9 {
379            return None;
380        }
381    }
382    Some((center, radius))
383}
384
385impl AnalyticSurface {
386    /// The centre and radius of a carrier that IS a sphere, whichever way
387    /// it is parameterized.
388    ///
389    /// The `Sphere` variant is the south-to-north meridian swept
390    /// counter-clockwise about its polar axis — exactly what `make_sphere_surface`
391    /// builds.  A REFLECTED sphere (the mirror feature, any negative-determinant
392    /// `transform_brep`) is the same point set with the opposite handedness:
393    /// relative to the u-consistent right-handed frame the recognizer derives,
394    /// its meridian runs north → south, so the `Sphere` template rejects it and
395    /// it recognizes as a general `Revolution`.  That representation is
396    /// faithful (explicit generatrix, exact projection), but a closed-form
397    /// consumer keyed on the `Sphere` variant alone then falls back to the
398    /// marcher — which cannot terminate on a point tangency (a corner blend's
399    /// sphere kissing the mirrored copy's face plane).
400    ///
401    /// Verified by exact reconstruction like every recognition: the generatrix
402    /// must be the polar meridian semicircle of `(centre, radius)` in either
403    /// direction, every control point and weight matching.
404    pub fn sphere_geometry(&self) -> Option<(Vec3, f64)> {
405        match self {
406            AnalyticSurface::Sphere { frame, radius } => Some((frame.origin, *radius)),
407            AnalyticSurface::Revolution {
408                frame,
409                sweep,
410                generatrix,
411                ..
412            } => {
413                let partial = || partial_sphere_enabled().then(|| meridian_arc_sphere(frame, generatrix)).flatten();
414                if *sweep < std::f64::consts::TAU - 1e-9 {
415                    return partial();
416                }
417                let controls = &generatrix.control_points;
418                if generatrix.degree != 2 || controls.len() != 5 {
419                    return partial();
420                }
421                let start = controls[0].point().ok()?;
422                let end = controls[4].point().ok()?;
423                let scale = curve_scale(generatrix);
424                let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
425                // Both meridian ends sit on the axis: the poles.
426                let (_, rho_start, z_start) = frame.cylindrical(start);
427                let (_, rho_end, z_end) = frame.cylindrical(end);
428                if rho_start > tolerance || rho_end > tolerance {
429                    return None;
430                }
431                let radius = (z_end - z_start).abs() * 0.5;
432                if radius <= tolerance {
433                    return None;
434                }
435                // The frame origin is on the axis but not necessarily at the
436                // centre (`revolution_structure` anchors it at the generatrix's
437                // first control circle — a pole here); the centre is the poles'
438                // midpoint.
439                let center = start.add(end).scale(0.5);
440                // Rebuild the meridian in the direction this generatrix runs.
441                let polar = if z_end > z_start {
442                    frame.axis
443                } else {
444                    frame.axis.scale(-1.0)
445                };
446                let meridian = make_arc(
447                    center,
448                    frame.x_axis,
449                    polar,
450                    radius,
451                    -std::f64::consts::FRAC_PI_2,
452                    std::f64::consts::FRAC_PI_2,
453                )
454                .ok()?;
455                curves_nearly_equal(generatrix, &meridian, scale).then_some((center, radius))
456            }
457            _ => None,
458        }
459    }
460
461    /// The centre, radius and a RIGHT-HANDED orthonormal basis of a carrier
462    /// that IS a sphere — [`Self::sphere_geometry`] plus the orientation the
463    /// pole-free cube atlas (`geometry/sphere_chart.rs`) is built on.
464    ///
465    /// The basis is `[x_axis, y_axis, axis]` of the recognition frame, so
466    /// `basis[2]` is the polar axis: the atlas puts the two degenerate poles at
467    /// the CENTRES of its `±z` charts, which is the whole point — a pole is then
468    /// an ordinary interior point of a regular chart rather than a coordinate
469    /// singularity. Derived only from data stored on the surface, so two call
470    /// sites looking at the same surface always build the same atlas, and a
471    /// REFLECTED sphere (which recognizes as a general `Revolution`) gets a
472    /// basis exactly as a direct one does.
473    pub fn sphere_frame(&self) -> Option<(Vec3, f64, [Vec3; 3])> {
474        let (center, radius) = self.sphere_geometry()?;
475        let frame = match self {
476            AnalyticSurface::Sphere { frame, .. } => frame,
477            AnalyticSurface::Revolution { frame, .. } => frame,
478            _ => return None,
479        };
480        Some((center, radius, [frame.x_axis, frame.y_axis, frame.axis]))
481    }
482
483    /// The frame (origin ON the axis at the tube centre's axial position),
484    /// major and minor radius of a carrier that IS a torus, whichever way it
485    /// is parameterized — the `Torus` variant, or the general `Revolution` a
486    /// reflected torus recognizes as (its tube circle runs the opposite way
487    /// round, so the `Torus` template rejects it; see [`Self::sphere_geometry`]).
488    /// Verified by exact reconstruction of the tube circle in either direction.
489    pub fn torus_geometry(&self) -> Option<(RevolutionFrame, f64, f64)> {
490        match self {
491            AnalyticSurface::Torus {
492                frame,
493                major_radius,
494                minor_radius,
495            } => Some((frame.clone(), *major_radius, *minor_radius)),
496            AnalyticSurface::Revolution {
497                frame,
498                sweep,
499                generatrix,
500                ..
501            } => {
502                if *sweep < std::f64::consts::TAU - 1e-9 {
503                    return None;
504                }
505                let controls = &generatrix.control_points;
506                if generatrix.degree != 2 || controls.len() != 9 {
507                    return None;
508                }
509                let tube_start = controls[0].point().ok()?;
510                let tube_opposite = controls[4].point().ok()?;
511                let tube_center = tube_start.add(tube_opposite).scale(0.5);
512                let minor = tube_start.sub(tube_center).length();
513                let scale = curve_scale(generatrix);
514                let tolerance = RECOGNITION_TOLERANCE * scale.max(1.0);
515                let (_, major, axial) = frame.cylindrical(tube_center);
516                if minor <= tolerance || major <= minor {
517                    return None;
518                }
519                for polar in [frame.axis, frame.axis.scale(-1.0)] {
520                    let tube = make_arc(
521                        tube_center,
522                        frame.x_axis,
523                        polar,
524                        minor,
525                        0.0,
526                        std::f64::consts::TAU,
527                    )
528                    .ok()?;
529                    if curves_nearly_equal(generatrix, &tube, scale) {
530                        return Some((
531                            RevolutionFrame {
532                                origin: frame.origin.add(frame.axis.scale(axial)),
533                                ..frame.clone()
534                            },
535                            major,
536                            minor,
537                        ));
538                    }
539                }
540                None
541            }
542            _ => None,
543        }
544    }
545}
546
547/// Largest absolute Cartesian coordinate over a curve's control points — the
548/// curve counterpart of [`surface_scale`], for scale-relative tolerances.
549pub fn curve_scale(curve: &NurbsCurve) -> f64 {
550    curve
551        .control_points
552        .iter()
553        .map(|p| (p.x.abs() / p.w).max(p.y.abs() / p.w).max(p.z.abs() / p.w))
554        .fold(0.0, f64::max)
555}
556