Skip to main content

axiolid_evaluate/
station.rs

1//! Stations: a position at a distance along a curve, framed by the curve's
2//! section (#241, ADR 0082).
3//!
4//! A station names a place by a measure along a basis curve instead of by
5//! coordinates, the way an alignment is staked out. Reading it back is
6//! curve evaluation, so it lives here, beside the arc-length machinery it
7//! reuses ([`crate::arc_parameter`]).
8//!
9//! # Distance convention
10//!
11//! The distance is measured in the basis curve's own convention, from its
12//! start:
13//!
14//! - an [`Elevated3`](axiolid_curve::Elevated3) or a
15//!   [`Banked3`](axiolid_curve::Banked3) is authored against PLAN distance,
16//!   its own parameter, and a station on it is a plan distance (the
17//!   curve-evaluation contract's `DistanceConvention::PlanDistance`);
18//! - every other curve, 2D or 3D, is measured by its arc length (for a 2D
19//!   curve, the plan length).
20//!
21//! The start is parameter `0` for a line, a circle, an ellipse, an
22//! intrinsic curve and a chain, and the first parameter of the domain for
23//! a polyline or a B-spline. A distance must lie in `[0, L]`, `L` the
24//! curve's length ([`station_length2`], [`station_length3`]): one full turn
25//! for a closed conic, no limit for a line. A negative or non-finite
26//! distance, and one past `L` by more than
27//! [`ARC_LENGTH_TOLERANCE`]` * max(1, L)`, is refused by name; one past it
28//! by less is read at `L`.
29//!
30//! # Section frame
31//!
32//! [`SectionFrame`] carries the point and three unit axes: `tangent` along
33//! the curve, `lateral` to the LEFT of it, and `up = tangent x lateral`.
34//!
35//! - A 2D curve lies in the plane `z = 0`: `lateral` is the left normal,
36//!   `up` is `+Z`.
37//! - A [`Banked3`](axiolid_curve::Banked3) is framed by its rolled section
38//!   ([`crate::banked::banked_section`]): `lateral` towards the left rail
39//!   head.
40//! - Every other 3D curve, an [`Elevated3`](axiolid_curve::Elevated3)
41//!   included, gets the reference-up frame against `+Z`, the one
42//!   `ReferenceCurveEvaluator::frame_at` returns: `lateral` is horizontal,
43//!   `up` leans back with the grade. A vertical tangent has no such frame
44//!   and is refused by name.
45//!
46//! [`SectionFrame::frame`] returns the axes in the curve-evaluation
47//! provider's layout: `x` the tangent, `y` up, `z = -lateral` (to the
48//! right), the layout the contract's `frame_at` documents (#242).
49//!
50//! The curve-evaluation provider reads a seam side through this module:
51//! `ReferenceCurveEvaluator`'s `point_at_on`, `tangent_at_on` and
52//! `frame_at_on` answer a measure on a seam (below) with
53//! [`station_section3_on`] (#286).
54//!
55//! [`SectionFrame::plan`] is the vertical alternative: the tangent's
56//! horizontal projection, the horizontal left normal and `+Z`, with grade
57//! and bank dropped.
58//!
59//! # Explicit orientation (#246)
60//!
61//! [`SectionFrame::oriented`] turns a section frame by an explicit axis and
62//! reference direction given as components in that frame, `(tangent,
63//! lateral, up)`, not in world coordinates: a linear placement's axes "are
64//! relative to the curve used for linear referencing ..., maintaining the
65//! relationship to the tangent of the curve" (buildingSMART IFC 4.3,
66//! `IfcAxis2PlacementLinear`), whose local `X`, `Y`, `Z` are the tangent,
67//! the left lateral and up. The axis is the oriented up, exact; the
68//! reference direction is made perpendicular to it (Gram-Schmidt, axis
69//! primary) and becomes the oriented tangent. The point does not move.
70//!
71//! # Seams (#263)
72//!
73//! A curve made of pieces has two frames where a polyline turns at a
74//! vertex, a B-spline at a corner knot, an elevated curve's grade breaks
75//! or a banked curve's cant jumps. A station within
76//! [`ARC_LENGTH_TOLERANCE`]` * max(1, s)` of such a seam is ON it: it is
77//! read at the seam's own distance, from the piece that starts there
78//! (`SeamSide::Outgoing`, [`station_section2`] and [`station_section3`])
79//! or from the side [`station_section2_on`] and [`station_section3_on`]
80//! are given. [`station_seams2`] and [`station_seams3`] say where the
81//! seams are without evaluating the curve, and [`Mitre`] is the plane a
82//! run of sections crossing one stands in; see [`seam`] for both. At the
83//! curve's start and end there is one piece, and both sides read it.
84//!
85//! # Placing at a station (#264)
86//!
87//! [`SectionFrame::placement`] is the rigid motion a node placed at a
88//! station is moved by: local `x`, `y`, `z` onto the tangent, the left
89//! lateral and up, the origin onto the point (a linear placement's
90//! reading). [`station_frame_is_exact2`] and [`station_frame_is_exact3`]
91//! say whether that frame is exact (a line) or carries the tolerances
92//! below. [`SectionFrame::carried`] is the frame a station on the placed
93//! curve has (#285): the source's moved where the placement keeps `+Z`,
94//! the placed curve's own reference-up frame where it tilts it.
95//!
96//! # Composite bases (#285)
97//!
98//! [`CompositeBasis`] measures stations along pieces of atomic curves laid
99//! end to end ([`StationPiece`]: a span of a curve, reversed or placed),
100//! the neutral form of a composite curve relation. The distance runs
101//! through the pieces in their common convention, every joint is a seam
102//! read by the rule above, and a frame is exact only where every piece up
103//! to the one read is; see [`composite`].
104//!
105//! # Offset bases (#289)
106//!
107//! A piece may be an offset of a base piece ([`StationOffset`]), measured
108//! in its OWN length from its start: arc length, or its own plan length
109//! beside an elevated or banked curve. [`offset_pieces`] offsets pieces
110//! laid end to end, one offset piece per span between seams; see
111//! [`offset`] for the closed forms, the numerical reading and the
112//! refusals.
113//!
114//! # Certified joint distances and seam-snapping windows (#294)
115//!
116//! A composite's joints lie at the running sum of its pieces' lengths, and
117//! some of those lengths are quadratures (an offset other than a line or a
118//! circle beside one, an ellipse, a B-spline). [`certify`] bounds each from
119//! both sides, so [`CompositeBasis::joint_intervals`] answers every joint
120//! with a [`DistanceInterval`] that contains its true distance, no wider
121//! than a requested tolerance; a sum of stored lengths is a point. The
122//! curve-evaluation provider hands them out as `path_joint_distances`.
123//!
124//! A station may carry a seam-snapping window, wider than the arc-length
125//! tolerance: [`snapped_distance2`], [`snapped_distance3`] and
126//! [`CompositeBasis::snapped_distance`] read a station within its window
127//! of exactly one seam whose frame may jump at that seam, using the
128//! certified intervals where a seam's distance is numerical, and refuse a
129//! window holding two seams or with one on its edge by name; see
130//! [`window`].
131//!
132//! # Accuracy contract
133//!
134//! The point and frame are the exact curve's at a measure within
135//! [`ARC_LENGTH_TOLERANCE`]` * max(1, s)` of `s` where the arc length is
136//! numerical (a conic, a polyline is exact, a B-spline), at `s` itself on a
137//! line, an intrinsic curve, a chain and an elevated or banked curve (their
138//! parameter is the measure), each evaluated to its own stated accuracy
139//! (Gauss-Legendre quadrature for intrinsic positions, ADR 0060). A station
140//! on a seam is read at the seam's distance, within the same tolerance of
141//! its own.
142
143use axiolid_contracts::{GeomError, GeomResult};
144use axiolid_core::{Frame3, Point3, Scalar, Transform3, Vec3};
145use axiolid_curve::{Curve2, Curve3, SeamSide};
146/// The convention a station basis is measured in (#285): the
147/// curve-evaluation contract's, re-exported so a caller can name it.
148pub use axiolid_curve_evaluate_contract::DistanceConvention;
149
150pub mod certify;
151pub mod composite;
152pub mod frame_bound;
153pub mod offset;
154pub mod path_bound;
155pub mod seam;
156pub mod window;
157
158pub use certify::{DistanceInterval, MAX_CERTIFIED_PANELS, POINT_ROUNDING, UNCERTIFIED_LENGTH};
159pub use composite::{CompositeBasis, StationCurve, StationPiece, JOINT_TOLERANCE};
160pub use frame_bound::{piece_frame_bounds, FrameLaw, FrameLawBounds, FrameReading};
161pub use offset::{offset_pieces, StationOffset, CUSP_TOLERANCE, OFFSET_TOLERANCE};
162pub use path_bound::{
163    point_bound_tolerance, PATH_POINT_AMBIGUOUS, PATH_POINT_OFF_CURVE, POINT_BOUND_UNSUPPORTED,
164};
165pub use seam::{
166    exact_station_seams2, exact_station_seams3, station_seams2, station_seams3, Mitre, StationSeam,
167    MITRE_TOLERANCE, SEAM_TANGENT_TOLERANCE,
168};
169pub use window::{
170    snapped_distance2, snapped_distance3, SEAM_WINDOW_AMBIGUOUS, SEAM_WINDOW_STRADDLED,
171    WINDOW_CERTIFICATION,
172};
173
174use crate::arc_parameter::{
175    arc_length2, arc_length3, parameter_at_arc_length2, parameter_at_arc_length3,
176    ARC_LENGTH_TOLERANCE,
177};
178use crate::curve::{derivative2, derivative3, domain2, domain3, evaluate2, evaluate3};
179
180/// Largest sine of the angle between an orientation's axis and reference
181/// direction that still counts as parallel ([`SectionFrame::oriented`]);
182/// the graph refuses the same pairs when a station is pushed.
183pub const ORIENTATION_TOLERANCE: Scalar = 1e-9;
184
185/// How far a rigid placement's image of `+Z` may lean and still count as
186/// keeping `+Z` ([`SectionFrame::carried`]): rounding only.
187pub const KEEPS_UP_TOLERANCE: Scalar = 1e-12;
188
189fn invalid(detail: String) -> GeomError {
190    GeomError::InvalidInput(detail)
191}
192
193/// A point on a curve and the section axes there: tangent, left lateral
194/// and up, unit and right-handed (`up = tangent x lateral`).
195#[non_exhaustive]
196#[derive(Debug, Clone, Copy, PartialEq)]
197pub struct SectionFrame {
198    /// The curve point.
199    pub point: Point3,
200    /// Unit tangent, in the direction of increasing distance.
201    pub tangent: Vec3,
202    /// Unit lateral axis, to the left of the tangent.
203    pub lateral: Vec3,
204    /// Unit section up, `tangent x lateral`.
205    pub up: Vec3,
206}
207
208impl SectionFrame {
209    /// The point offset from this frame's point: `lateral` along the
210    /// lateral axis (positive to the left), `vertical` along up and
211    /// `longitudinal` along the tangent.
212    #[must_use]
213    pub fn place(&self, lateral: Scalar, vertical: Scalar, longitudinal: Scalar) -> Point3 {
214        self.point + lateral * self.lateral + vertical * self.up + longitudinal * self.tangent
215    }
216
217    /// The same point framed vertically: the tangent's horizontal
218    /// projection, the horizontal left normal and `+Z`. Grade and bank are
219    /// dropped.
220    ///
221    /// # Errors
222    ///
223    /// A vertical tangent, which has no horizontal projection.
224    pub fn plan(&self) -> GeomResult<Self> {
225        let horizontal = Vec3::new(self.tangent.x, self.tangent.y, 0.0);
226        let length = horizontal.length();
227        if !length.is_finite() || length <= 1e-12 {
228            return Err(invalid(
229                "station: the tangent is vertical, so it has no plan direction".into(),
230            ));
231        }
232        let tangent = horizontal / length;
233        Ok(Self {
234            point: self.point,
235            tangent,
236            lateral: Vec3::new(-tangent.y, tangent.x, 0.0),
237            up: Vec3::Z,
238        })
239    }
240
241    /// The same point with its axes turned by an explicit orientation
242    /// (#246): `axis` and `ref_direction` are components in THIS frame,
243    /// `(tangent, lateral, up)`, defaulting to `(0, 0, 1)` and `(1, 0, 0)`.
244    ///
245    /// Gram-Schmidt with the axis primary: `up' = axis / |axis|`,
246    /// `tangent' = normalise(r - (r . up') up')` for the unit reference
247    /// direction `r`, `lateral' = up' x tangent'`. This is the reading of a
248    /// linear placement's `Axis` and `RefDirection` relative to the curve
249    /// (see the [module documentation](self#explicit-orientation-246)).
250    ///
251    /// # Errors
252    ///
253    /// A zero or non-finite vector, or an axis and reference direction
254    /// parallel or anti-parallel within [`ORIENTATION_TOLERANCE`], by name.
255    pub fn oriented(&self, axis: Option<Vec3>, ref_direction: Option<Vec3>) -> GeomResult<Self> {
256        let unit = |vector: Vec3, what: &str| {
257            let length = vector.length();
258            if vector.is_finite() && length.is_finite() && length > 1e-12 {
259                Ok(vector / length)
260            } else {
261                Err(invalid(format!(
262                    "station: the orientation's {what} {vector:?} is zero or not finite"
263                )))
264            }
265        };
266        let axis = unit(axis.unwrap_or(Vec3::Z), "axis")?;
267        let reference = unit(ref_direction.unwrap_or(Vec3::X), "reference direction")?;
268        if axis.cross(reference).length() <= ORIENTATION_TOLERANCE {
269            return Err(invalid(format!(
270                "station: the orientation's axis {axis:?} and reference direction \
271                 {reference:?} are parallel"
272            )));
273        }
274        let x = (reference - reference.dot(axis) * axis).normalize();
275        let y = axis.cross(x);
276        let world = |v: Vec3| v.x * self.tangent + v.y * self.lateral + v.z * self.up;
277        Ok(Self {
278            point: self.point,
279            tangent: world(x),
280            lateral: world(y),
281            up: world(axis),
282        })
283    }
284
285    /// The rigid placement this frame stands for (#264): local `x` onto the
286    /// tangent, `y` onto the lateral (to the left), `z` onto up, the local
287    /// origin onto the point.
288    ///
289    /// This is how a linear placement maps its local axes (buildingSMART
290    /// IFC 4.3, `IfcAxis2PlacementLinear`: `X` the tangent, `Y` the left
291    /// lateral, `Z` up), and how a node placed at a station is moved. It is
292    /// not [`Self::frame`]'s provider layout (`y` up, `z` right).
293    #[must_use]
294    pub fn placement(&self) -> Transform3 {
295        Transform3::from_cols(self.tangent, self.lateral, self.up, self.point)
296    }
297
298    /// This frame carried by a rigid motion: the point by `rigid`, the
299    /// axes by its linear part.
300    ///
301    /// A section frame on a curve moved rigidly is the moved curve's own
302    /// only where its convention does not depend on the world: always for
303    /// its tangent, and for the reference-up and plan frames only when
304    /// `rigid` keeps `+Z`; checking that is the caller's.
305    #[must_use]
306    pub fn moved(&self, rigid: Transform3) -> Self {
307        Self {
308            point: rigid.transform_point3(self.point),
309            tangent: rigid.transform_vector3(self.tangent),
310            lateral: rigid.transform_vector3(self.lateral),
311            up: rigid.transform_vector3(self.up),
312        }
313    }
314
315    /// This frame, read on a curve, as the section frame of that curve
316    /// carried by the rigid motion `rigid` (#264, #285): the frame a
317    /// station on the placed curve has, `measure` the convention the
318    /// source curve is measured in.
319    ///
320    /// Where `rigid` keeps `+Z` (within [`KEEPS_UP_TOLERANCE`]) this is
321    /// [`Self::moved`]: the moved reference-up, planar or banked frame is
322    /// the placed curve's own, and plan distance is kept. Where it tilts
323    /// `+Z`, an arc-length-measured curve (arc length is kept by any rigid
324    /// motion) gets the reference-up frame against `+Z` of its moved point
325    /// and tangent, which is the placed 3D curve's own section frame; the
326    /// moved frame would not be.
327    ///
328    /// # Errors
329    ///
330    /// A plan-measured curve (elevated or banked) under a motion that
331    /// tilts `+Z`, whose plan distance and section frame are not the placed
332    /// curve's, by a typed [`GeomError::UnsupportedInput`]; and a moved
333    /// tangent with no reference-up frame (vertical), by name.
334    pub fn carried(&self, rigid: Transform3, measure: DistanceConvention) -> GeomResult<Self> {
335        if (rigid.transform_vector3(Vec3::Z) - Vec3::Z).length() <= KEEPS_UP_TOLERANCE {
336            return Ok(self.moved(rigid));
337        }
338        if measure == DistanceConvention::PlanDistance {
339            return Err(GeomError::UnsupportedInput {
340                backend: axiolid_contracts::BackendId::new("axiolid-evaluate"),
341                operation: axiolid_contracts::Operation::CurveEvaluation,
342                input: PLAN_MEASURED_TILTED,
343            });
344        }
345        reference_up_frame(
346            rigid.transform_point3(self.point),
347            rigid.transform_vector3(self.tangent),
348        )
349    }
350
351    /// The frame in the curve-evaluation provider's layout: `x` the
352    /// tangent, `y` up, `z = x x y`, which is `-lateral` (to the right).
353    #[must_use]
354    pub fn frame(&self) -> Frame3 {
355        Frame3 {
356            origin: self.point,
357            x: self.tangent,
358            y: self.up,
359            z: -self.lateral,
360        }
361    }
362}
363
364/// The refusal of a plan-measured curve placed in a tilted frame.
365const PLAN_MEASURED_TILTED: &str =
366    "a station along an elevated or banked curve placed at a station whose frame tilts +Z: its \
367     plan distance and its section frame carried by the placement are not the placed curve's own \
368     (#264)";
369
370/// A 2D curve's point and unit tangent lifted to `z = 0`, framed with the
371/// left normal and `+Z`.
372fn planar_frame(
373    point: axiolid_core::Point2,
374    tangent: axiolid_core::Vec2,
375) -> GeomResult<SectionFrame> {
376    let length = tangent.length();
377    if !length.is_finite() || length <= 0.0 {
378        return Err(invalid(
379            "station: the curve has no tangent direction there".into(),
380        ));
381    }
382    let t = tangent / length;
383    Ok(SectionFrame {
384        point: Point3::new(point.x, point.y, 0.0),
385        tangent: Vec3::new(t.x, t.y, 0.0),
386        lateral: Vec3::new(-t.y, t.x, 0.0),
387        up: Vec3::Z,
388    })
389}
390
391/// The reference-up frame against `+Z`, as `ReferenceCurveEvaluator`
392/// builds it: `right = t x Z`, `up = right x t`, `lateral = -right`.
393fn reference_up_frame(point: Point3, derivative: Vec3) -> GeomResult<SectionFrame> {
394    let length = derivative.length();
395    if !length.is_finite() || length <= 0.0 {
396        return Err(invalid(
397            "station: the curve has no tangent direction there".into(),
398        ));
399    }
400    let tangent = derivative / length;
401    let right = tangent.cross(Vec3::Z);
402    let magnitude = right.length();
403    if !magnitude.is_finite() || magnitude <= 1e-12 {
404        return Err(invalid(
405            "station: the tangent is vertical, so the section has no lateral axis".into(),
406        ));
407    }
408    let right = right / magnitude;
409    Ok(SectionFrame {
410        point,
411        tangent,
412        lateral: -right,
413        up: right.cross(tangent),
414    })
415}
416
417/// A banked curve's rolled section at plan distance `d`, as a station
418/// frame.
419fn banked_frame(curve: &axiolid_curve::Banked3, d: Scalar) -> GeomResult<SectionFrame> {
420    let section = crate::banked::banked_section(curve, d)?;
421    Ok(SectionFrame {
422        point: section.point,
423        tangent: section.tangent,
424        lateral: section.lateral,
425        up: section.up,
426    })
427}
428
429/// Check `distance` against the curve length `length` (`None`:
430/// unbounded) and return the distance to read, clamped onto `L` within
431/// tolerance.
432fn admitted(distance: Scalar, length: Option<Scalar>) -> GeomResult<Scalar> {
433    if !distance.is_finite() {
434        return Err(invalid(format!(
435            "station: distance {distance} along the curve is not finite"
436        )));
437    }
438    if distance < 0.0 {
439        return Err(invalid(format!(
440            "station: distance {distance} is before the curve's start"
441        )));
442    }
443    match length {
444        None => Ok(distance),
445        Some(length) => {
446            let slack = ARC_LENGTH_TOLERANCE * length.abs().max(1.0);
447            if distance > length + slack {
448                Err(invalid(format!(
449                    "station: distance {distance} is beyond the curve's length {length}"
450                )))
451            } else {
452                Ok(distance.min(length))
453            }
454        }
455    }
456}
457
458fn unmeasured(dimension: &str) -> GeomError {
459    invalid(format!(
460        "station: this {dimension} curve family has no distance a station can be measured by"
461    ))
462}
463
464/// Where a 2D curve's measure starts: parameter `0`, or the domain's
465/// first parameter for a polyline or a B-spline.
466fn start2(curve: &Curve2) -> Scalar {
467    match curve {
468        Curve2::Polyline(_) | Curve2::BSpline(_) => {
469            let domain = domain2(curve);
470            domain.start.min(domain.end)
471        }
472        _ => 0.0,
473    }
474}
475
476fn start3(curve: &Curve3) -> Scalar {
477    match curve {
478        Curve3::Polyline(_) | Curve3::BSpline(_) => {
479            let domain = domain3(curve);
480            domain.start.min(domain.end)
481        }
482        _ => 0.0,
483    }
484}
485
486/// The length a station on a 2D curve is measured against: `None` for a
487/// line (unbounded), one turn for a circle or an ellipse, the arc length
488/// of its domain for a polyline or a B-spline, the stated length of an
489/// intrinsic curve or a chain.
490///
491/// # Errors
492///
493/// Any other family, a chain without a valid length, and the quadrature's
494/// refusals, by name.
495pub fn station_length2(curve: &Curve2) -> GeomResult<Option<Scalar>> {
496    match curve {
497        Curve2::Line(_) => Ok(None),
498        Curve2::Circle(_) | Curve2::Ellipse(_) => {
499            arc_length2(curve, 0.0, core::f64::consts::TAU).map(Some)
500        }
501        Curve2::Polyline(_) | Curve2::BSpline(_) => {
502            let domain = domain2(curve);
503            let (lo, hi) = (domain.start.min(domain.end), domain.start.max(domain.end));
504            if hi <= lo {
505                return Err(invalid("station: the curve has an empty domain".into()));
506            }
507            arc_length2(curve, lo, hi).map(Some)
508        }
509        Curve2::Intrinsic(intrinsic) => {
510            if intrinsic.length.is_finite() && intrinsic.length > 0.0 {
511                Ok(Some(intrinsic.length))
512            } else {
513                Err(invalid(
514                    "station: the intrinsic curve has no positive finite length".into(),
515                ))
516            }
517        }
518        Curve2::Chain(chain) => chain
519            .length()
520            .map(Some)
521            .ok_or_else(|| invalid("station: the chain has no valid length".into())),
522        _ => Err(unmeasured("2D")),
523    }
524}
525
526/// The length a station on a 3D curve is measured against, as
527/// [`station_length2`]; an elevated curve's is its plan's, a banked
528/// curve's the span of its cant law.
529///
530/// # Errors
531///
532/// As [`station_length2`].
533pub fn station_length3(curve: &Curve3) -> GeomResult<Option<Scalar>> {
534    match curve {
535        Curve3::Line(_) => Ok(None),
536        Curve3::Circle(_) | Curve3::Ellipse(_) => {
537            arc_length3(curve, 0.0, core::f64::consts::TAU).map(Some)
538        }
539        Curve3::Polyline(_) | Curve3::BSpline(_) => {
540            let domain = domain3(curve);
541            let (lo, hi) = (domain.start.min(domain.end), domain.start.max(domain.end));
542            if hi <= lo {
543                return Err(invalid("station: the curve has an empty domain".into()));
544            }
545            arc_length3(curve, lo, hi).map(Some)
546        }
547        Curve3::Intrinsic(intrinsic) => {
548            if intrinsic.length.is_finite() && intrinsic.length > 0.0 {
549                Ok(Some(intrinsic.length))
550            } else {
551                Err(invalid(
552                    "station: the intrinsic curve has no positive finite length".into(),
553                ))
554            }
555        }
556        Curve3::Elevated(elevated) => station_length2(&elevated.plan),
557        Curve3::Banked(banked) => {
558            let domain = domain3(curve);
559            if domain.end > domain.start {
560                Ok(Some(domain.end))
561            } else {
562                Err(invalid(format!(
563                    "station: the banked curve's cant law has no valid span ({})",
564                    banked.span()
565                )))
566            }
567        }
568        _ => Err(unmeasured("3D")),
569    }
570}
571
572/// Whether a station frame on this 2D curve is exact (#264): its point
573/// and axes at the station's distance itself, in closed form, rounding
574/// aside, with no quadrature or root find behind them.
575///
576/// Only a line: on every other family the distance is read by the
577/// arc-length inverse ([`ARC_LENGTH_TOLERANCE`], an estimate) or the point
578/// by quadrature (an intrinsic curve, a chain), so the frame is not exact
579/// and a placement in it must not be reported as exact.
580#[must_use]
581pub fn station_frame_is_exact2(curve: &Curve2) -> bool {
582    matches!(curve, Curve2::Line(_))
583}
584
585/// [`station_frame_is_exact2`] for a 3D curve: only a line.
586#[must_use]
587pub fn station_frame_is_exact3(curve: &Curve3) -> bool {
588    matches!(curve, Curve3::Line(_))
589}
590
591/// The section of a 2D curve at arc length `distance` from its start; see
592/// the [module documentation](self) for the conventions.
593///
594/// # Errors
595///
596/// A distance that is not finite, negative or beyond the curve's length,
597/// an unmeasurable family, and the evaluators' refusals, by name.
598pub fn station_section2(curve: &Curve2, distance: Scalar) -> GeomResult<SectionFrame> {
599    station_section2_on(curve, distance, SeamSide::Outgoing)
600}
601
602/// [`station_section2`] reading `side` of a seam the station lies on (see
603/// the [module documentation](self#seams-263)); off a seam the side does
604/// not matter.
605///
606/// # Errors
607///
608/// As [`station_section2`].
609pub fn station_section2_on(
610    curve: &Curve2,
611    distance: Scalar,
612    side: SeamSide,
613) -> GeomResult<SectionFrame> {
614    let distance = admitted(distance, station_length2(curve)?)?;
615    if let Some(section) = seam::seam_section2(curve, distance, side)? {
616        return Ok(section);
617    }
618    let t = parameter_at_arc_length2(curve, start2(curve), distance)?;
619    planar_frame(evaluate2(curve, t)?, derivative2(curve, t)?)
620}
621
622/// Whether a station at `distance` along a 3D curve lies ON a seam it
623/// reads two ways, by the rule [`station_section3_on`] applies (#286):
624/// the curve-evaluation provider's sided queries read a station there
625/// through it and answer every other measure side-lessly.
626///
627/// A distance outside `[0, L]` lies on no interior seam: `false`, so the
628/// side-less query keeps its own refusal or answer there.
629///
630/// # Errors
631///
632/// A curve whose length or seams cannot be read, by name.
633pub(crate) fn station_on_seam3(curve: &Curve3, distance: Scalar) -> GeomResult<bool> {
634    if !seam::sided3(curve) {
635        return Ok(false);
636    }
637    let Ok(distance) = admitted(distance, station_length3(curve)?) else {
638        return Ok(false);
639    };
640    Ok(seam::seam_at3(curve, distance)?.is_some())
641}
642
643/// The section of a 3D curve at `distance` from its start: plan distance
644/// on an elevated or banked curve, arc length on any other; see the
645/// [module documentation](self).
646///
647/// # Errors
648///
649/// As [`station_section2`], and a vertical tangent where the reference-up
650/// frame is built.
651pub fn station_section3(curve: &Curve3, distance: Scalar) -> GeomResult<SectionFrame> {
652    station_section3_on(curve, distance, SeamSide::Outgoing)
653}
654
655/// [`station_section3`] reading `side` of a seam the station lies on (see
656/// the [module documentation](self#seams-263)); off a seam the side does
657/// not matter.
658///
659/// # Errors
660///
661/// As [`station_section3`].
662pub fn station_section3_on(
663    curve: &Curve3,
664    distance: Scalar,
665    side: SeamSide,
666) -> GeomResult<SectionFrame> {
667    let distance = admitted(distance, station_length3(curve)?)?;
668    if let Some(section) = seam::seam_section3(curve, distance, side)? {
669        return Ok(section);
670    }
671    match curve {
672        Curve3::Banked(banked) => banked_frame(banked, distance),
673        Curve3::Elevated(elevated) => reference_up_frame(
674            crate::arc_length::elevated_point(elevated, distance)?,
675            crate::arc_length::elevated_tangent(elevated, distance)?,
676        ),
677        _ => {
678            let t = parameter_at_arc_length3(curve, start3(curve), distance)?;
679            reference_up_frame(evaluate3(curve, t)?, derivative3(curve, t)?)
680        }
681    }
682}