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 offset;
153pub mod path_bound;
154pub mod seam;
155pub mod window;
156
157pub use certify::{DistanceInterval, MAX_CERTIFIED_PANELS, POINT_ROUNDING, UNCERTIFIED_LENGTH};
158pub use composite::{CompositeBasis, StationCurve, StationPiece, JOINT_TOLERANCE};
159pub use offset::{offset_pieces, StationOffset, CUSP_TOLERANCE, OFFSET_TOLERANCE};
160pub use path_bound::{
161    point_bound_tolerance, PATH_POINT_AMBIGUOUS, PATH_POINT_OFF_CURVE, POINT_BOUND_UNSUPPORTED,
162};
163pub use seam::{
164    exact_station_seams2, exact_station_seams3, station_seams2, station_seams3, Mitre, StationSeam,
165    MITRE_TOLERANCE, SEAM_TANGENT_TOLERANCE,
166};
167pub use window::{
168    snapped_distance2, snapped_distance3, SEAM_WINDOW_AMBIGUOUS, SEAM_WINDOW_STRADDLED,
169    WINDOW_CERTIFICATION,
170};
171
172use crate::arc_parameter::{
173    arc_length2, arc_length3, parameter_at_arc_length2, parameter_at_arc_length3,
174    ARC_LENGTH_TOLERANCE,
175};
176use crate::curve::{derivative2, derivative3, domain2, domain3, evaluate2, evaluate3};
177
178/// Largest sine of the angle between an orientation's axis and reference
179/// direction that still counts as parallel ([`SectionFrame::oriented`]);
180/// the graph refuses the same pairs when a station is pushed.
181pub const ORIENTATION_TOLERANCE: Scalar = 1e-9;
182
183/// How far a rigid placement's image of `+Z` may lean and still count as
184/// keeping `+Z` ([`SectionFrame::carried`]): rounding only.
185pub const KEEPS_UP_TOLERANCE: Scalar = 1e-12;
186
187fn invalid(detail: String) -> GeomError {
188    GeomError::InvalidInput(detail)
189}
190
191/// A point on a curve and the section axes there: tangent, left lateral
192/// and up, unit and right-handed (`up = tangent x lateral`).
193#[non_exhaustive]
194#[derive(Debug, Clone, Copy, PartialEq)]
195pub struct SectionFrame {
196    /// The curve point.
197    pub point: Point3,
198    /// Unit tangent, in the direction of increasing distance.
199    pub tangent: Vec3,
200    /// Unit lateral axis, to the left of the tangent.
201    pub lateral: Vec3,
202    /// Unit section up, `tangent x lateral`.
203    pub up: Vec3,
204}
205
206impl SectionFrame {
207    /// The point offset from this frame's point: `lateral` along the
208    /// lateral axis (positive to the left), `vertical` along up and
209    /// `longitudinal` along the tangent.
210    #[must_use]
211    pub fn place(&self, lateral: Scalar, vertical: Scalar, longitudinal: Scalar) -> Point3 {
212        self.point + lateral * self.lateral + vertical * self.up + longitudinal * self.tangent
213    }
214
215    /// The same point framed vertically: the tangent's horizontal
216    /// projection, the horizontal left normal and `+Z`. Grade and bank are
217    /// dropped.
218    ///
219    /// # Errors
220    ///
221    /// A vertical tangent, which has no horizontal projection.
222    pub fn plan(&self) -> GeomResult<Self> {
223        let horizontal = Vec3::new(self.tangent.x, self.tangent.y, 0.0);
224        let length = horizontal.length();
225        if !length.is_finite() || length <= 1e-12 {
226            return Err(invalid(
227                "station: the tangent is vertical, so it has no plan direction".into(),
228            ));
229        }
230        let tangent = horizontal / length;
231        Ok(Self {
232            point: self.point,
233            tangent,
234            lateral: Vec3::new(-tangent.y, tangent.x, 0.0),
235            up: Vec3::Z,
236        })
237    }
238
239    /// The same point with its axes turned by an explicit orientation
240    /// (#246): `axis` and `ref_direction` are components in THIS frame,
241    /// `(tangent, lateral, up)`, defaulting to `(0, 0, 1)` and `(1, 0, 0)`.
242    ///
243    /// Gram-Schmidt with the axis primary: `up' = axis / |axis|`,
244    /// `tangent' = normalise(r - (r . up') up')` for the unit reference
245    /// direction `r`, `lateral' = up' x tangent'`. This is the reading of a
246    /// linear placement's `Axis` and `RefDirection` relative to the curve
247    /// (see the [module documentation](self#explicit-orientation-246)).
248    ///
249    /// # Errors
250    ///
251    /// A zero or non-finite vector, or an axis and reference direction
252    /// parallel or anti-parallel within [`ORIENTATION_TOLERANCE`], by name.
253    pub fn oriented(&self, axis: Option<Vec3>, ref_direction: Option<Vec3>) -> GeomResult<Self> {
254        let unit = |vector: Vec3, what: &str| {
255            let length = vector.length();
256            if vector.is_finite() && length.is_finite() && length > 1e-12 {
257                Ok(vector / length)
258            } else {
259                Err(invalid(format!(
260                    "station: the orientation's {what} {vector:?} is zero or not finite"
261                )))
262            }
263        };
264        let axis = unit(axis.unwrap_or(Vec3::Z), "axis")?;
265        let reference = unit(ref_direction.unwrap_or(Vec3::X), "reference direction")?;
266        if axis.cross(reference).length() <= ORIENTATION_TOLERANCE {
267            return Err(invalid(format!(
268                "station: the orientation's axis {axis:?} and reference direction \
269                 {reference:?} are parallel"
270            )));
271        }
272        let x = (reference - reference.dot(axis) * axis).normalize();
273        let y = axis.cross(x);
274        let world = |v: Vec3| v.x * self.tangent + v.y * self.lateral + v.z * self.up;
275        Ok(Self {
276            point: self.point,
277            tangent: world(x),
278            lateral: world(y),
279            up: world(axis),
280        })
281    }
282
283    /// The rigid placement this frame stands for (#264): local `x` onto the
284    /// tangent, `y` onto the lateral (to the left), `z` onto up, the local
285    /// origin onto the point.
286    ///
287    /// This is how a linear placement maps its local axes (buildingSMART
288    /// IFC 4.3, `IfcAxis2PlacementLinear`: `X` the tangent, `Y` the left
289    /// lateral, `Z` up), and how a node placed at a station is moved. It is
290    /// not [`Self::frame`]'s provider layout (`y` up, `z` right).
291    #[must_use]
292    pub fn placement(&self) -> Transform3 {
293        Transform3::from_cols(self.tangent, self.lateral, self.up, self.point)
294    }
295
296    /// This frame carried by a rigid motion: the point by `rigid`, the
297    /// axes by its linear part.
298    ///
299    /// A section frame on a curve moved rigidly is the moved curve's own
300    /// only where its convention does not depend on the world: always for
301    /// its tangent, and for the reference-up and plan frames only when
302    /// `rigid` keeps `+Z`; checking that is the caller's.
303    #[must_use]
304    pub fn moved(&self, rigid: Transform3) -> Self {
305        Self {
306            point: rigid.transform_point3(self.point),
307            tangent: rigid.transform_vector3(self.tangent),
308            lateral: rigid.transform_vector3(self.lateral),
309            up: rigid.transform_vector3(self.up),
310        }
311    }
312
313    /// This frame, read on a curve, as the section frame of that curve
314    /// carried by the rigid motion `rigid` (#264, #285): the frame a
315    /// station on the placed curve has, `measure` the convention the
316    /// source curve is measured in.
317    ///
318    /// Where `rigid` keeps `+Z` (within [`KEEPS_UP_TOLERANCE`]) this is
319    /// [`Self::moved`]: the moved reference-up, planar or banked frame is
320    /// the placed curve's own, and plan distance is kept. Where it tilts
321    /// `+Z`, an arc-length-measured curve (arc length is kept by any rigid
322    /// motion) gets the reference-up frame against `+Z` of its moved point
323    /// and tangent, which is the placed 3D curve's own section frame; the
324    /// moved frame would not be.
325    ///
326    /// # Errors
327    ///
328    /// A plan-measured curve (elevated or banked) under a motion that
329    /// tilts `+Z`, whose plan distance and section frame are not the placed
330    /// curve's, by a typed [`GeomError::UnsupportedInput`]; and a moved
331    /// tangent with no reference-up frame (vertical), by name.
332    pub fn carried(&self, rigid: Transform3, measure: DistanceConvention) -> GeomResult<Self> {
333        if (rigid.transform_vector3(Vec3::Z) - Vec3::Z).length() <= KEEPS_UP_TOLERANCE {
334            return Ok(self.moved(rigid));
335        }
336        if measure == DistanceConvention::PlanDistance {
337            return Err(GeomError::UnsupportedInput {
338                backend: axiolid_contracts::BackendId::new("axiolid-evaluate"),
339                operation: axiolid_contracts::Operation::CurveEvaluation,
340                input: PLAN_MEASURED_TILTED,
341            });
342        }
343        reference_up_frame(
344            rigid.transform_point3(self.point),
345            rigid.transform_vector3(self.tangent),
346        )
347    }
348
349    /// The frame in the curve-evaluation provider's layout: `x` the
350    /// tangent, `y` up, `z = x x y`, which is `-lateral` (to the right).
351    #[must_use]
352    pub fn frame(&self) -> Frame3 {
353        Frame3 {
354            origin: self.point,
355            x: self.tangent,
356            y: self.up,
357            z: -self.lateral,
358        }
359    }
360}
361
362/// The refusal of a plan-measured curve placed in a tilted frame.
363const PLAN_MEASURED_TILTED: &str =
364    "a station along an elevated or banked curve placed at a station whose frame tilts +Z: its \
365     plan distance and its section frame carried by the placement are not the placed curve's own \
366     (#264)";
367
368/// A 2D curve's point and unit tangent lifted to `z = 0`, framed with the
369/// left normal and `+Z`.
370fn planar_frame(
371    point: axiolid_core::Point2,
372    tangent: axiolid_core::Vec2,
373) -> GeomResult<SectionFrame> {
374    let length = tangent.length();
375    if !length.is_finite() || length <= 0.0 {
376        return Err(invalid(
377            "station: the curve has no tangent direction there".into(),
378        ));
379    }
380    let t = tangent / length;
381    Ok(SectionFrame {
382        point: Point3::new(point.x, point.y, 0.0),
383        tangent: Vec3::new(t.x, t.y, 0.0),
384        lateral: Vec3::new(-t.y, t.x, 0.0),
385        up: Vec3::Z,
386    })
387}
388
389/// The reference-up frame against `+Z`, as `ReferenceCurveEvaluator`
390/// builds it: `right = t x Z`, `up = right x t`, `lateral = -right`.
391fn reference_up_frame(point: Point3, derivative: Vec3) -> GeomResult<SectionFrame> {
392    let length = derivative.length();
393    if !length.is_finite() || length <= 0.0 {
394        return Err(invalid(
395            "station: the curve has no tangent direction there".into(),
396        ));
397    }
398    let tangent = derivative / length;
399    let right = tangent.cross(Vec3::Z);
400    let magnitude = right.length();
401    if !magnitude.is_finite() || magnitude <= 1e-12 {
402        return Err(invalid(
403            "station: the tangent is vertical, so the section has no lateral axis".into(),
404        ));
405    }
406    let right = right / magnitude;
407    Ok(SectionFrame {
408        point,
409        tangent,
410        lateral: -right,
411        up: right.cross(tangent),
412    })
413}
414
415/// A banked curve's rolled section at plan distance `d`, as a station
416/// frame.
417fn banked_frame(curve: &axiolid_curve::Banked3, d: Scalar) -> GeomResult<SectionFrame> {
418    let section = crate::banked::banked_section(curve, d)?;
419    Ok(SectionFrame {
420        point: section.point,
421        tangent: section.tangent,
422        lateral: section.lateral,
423        up: section.up,
424    })
425}
426
427/// Check `distance` against the curve length `length` (`None`:
428/// unbounded) and return the distance to read, clamped onto `L` within
429/// tolerance.
430fn admitted(distance: Scalar, length: Option<Scalar>) -> GeomResult<Scalar> {
431    if !distance.is_finite() {
432        return Err(invalid(format!(
433            "station: distance {distance} along the curve is not finite"
434        )));
435    }
436    if distance < 0.0 {
437        return Err(invalid(format!(
438            "station: distance {distance} is before the curve's start"
439        )));
440    }
441    match length {
442        None => Ok(distance),
443        Some(length) => {
444            let slack = ARC_LENGTH_TOLERANCE * length.abs().max(1.0);
445            if distance > length + slack {
446                Err(invalid(format!(
447                    "station: distance {distance} is beyond the curve's length {length}"
448                )))
449            } else {
450                Ok(distance.min(length))
451            }
452        }
453    }
454}
455
456fn unmeasured(dimension: &str) -> GeomError {
457    invalid(format!(
458        "station: this {dimension} curve family has no distance a station can be measured by"
459    ))
460}
461
462/// Where a 2D curve's measure starts: parameter `0`, or the domain's
463/// first parameter for a polyline or a B-spline.
464fn start2(curve: &Curve2) -> Scalar {
465    match curve {
466        Curve2::Polyline(_) | Curve2::BSpline(_) => {
467            let domain = domain2(curve);
468            domain.start.min(domain.end)
469        }
470        _ => 0.0,
471    }
472}
473
474fn start3(curve: &Curve3) -> Scalar {
475    match curve {
476        Curve3::Polyline(_) | Curve3::BSpline(_) => {
477            let domain = domain3(curve);
478            domain.start.min(domain.end)
479        }
480        _ => 0.0,
481    }
482}
483
484/// The length a station on a 2D curve is measured against: `None` for a
485/// line (unbounded), one turn for a circle or an ellipse, the arc length
486/// of its domain for a polyline or a B-spline, the stated length of an
487/// intrinsic curve or a chain.
488///
489/// # Errors
490///
491/// Any other family, a chain without a valid length, and the quadrature's
492/// refusals, by name.
493pub fn station_length2(curve: &Curve2) -> GeomResult<Option<Scalar>> {
494    match curve {
495        Curve2::Line(_) => Ok(None),
496        Curve2::Circle(_) | Curve2::Ellipse(_) => {
497            arc_length2(curve, 0.0, core::f64::consts::TAU).map(Some)
498        }
499        Curve2::Polyline(_) | Curve2::BSpline(_) => {
500            let domain = domain2(curve);
501            let (lo, hi) = (domain.start.min(domain.end), domain.start.max(domain.end));
502            if hi <= lo {
503                return Err(invalid("station: the curve has an empty domain".into()));
504            }
505            arc_length2(curve, lo, hi).map(Some)
506        }
507        Curve2::Intrinsic(intrinsic) => {
508            if intrinsic.length.is_finite() && intrinsic.length > 0.0 {
509                Ok(Some(intrinsic.length))
510            } else {
511                Err(invalid(
512                    "station: the intrinsic curve has no positive finite length".into(),
513                ))
514            }
515        }
516        Curve2::Chain(chain) => chain
517            .length()
518            .map(Some)
519            .ok_or_else(|| invalid("station: the chain has no valid length".into())),
520        _ => Err(unmeasured("2D")),
521    }
522}
523
524/// The length a station on a 3D curve is measured against, as
525/// [`station_length2`]; an elevated curve's is its plan's, a banked
526/// curve's the span of its cant law.
527///
528/// # Errors
529///
530/// As [`station_length2`].
531pub fn station_length3(curve: &Curve3) -> GeomResult<Option<Scalar>> {
532    match curve {
533        Curve3::Line(_) => Ok(None),
534        Curve3::Circle(_) | Curve3::Ellipse(_) => {
535            arc_length3(curve, 0.0, core::f64::consts::TAU).map(Some)
536        }
537        Curve3::Polyline(_) | Curve3::BSpline(_) => {
538            let domain = domain3(curve);
539            let (lo, hi) = (domain.start.min(domain.end), domain.start.max(domain.end));
540            if hi <= lo {
541                return Err(invalid("station: the curve has an empty domain".into()));
542            }
543            arc_length3(curve, lo, hi).map(Some)
544        }
545        Curve3::Intrinsic(intrinsic) => {
546            if intrinsic.length.is_finite() && intrinsic.length > 0.0 {
547                Ok(Some(intrinsic.length))
548            } else {
549                Err(invalid(
550                    "station: the intrinsic curve has no positive finite length".into(),
551                ))
552            }
553        }
554        Curve3::Elevated(elevated) => station_length2(&elevated.plan),
555        Curve3::Banked(banked) => {
556            let domain = domain3(curve);
557            if domain.end > domain.start {
558                Ok(Some(domain.end))
559            } else {
560                Err(invalid(format!(
561                    "station: the banked curve's cant law has no valid span ({})",
562                    banked.span()
563                )))
564            }
565        }
566        _ => Err(unmeasured("3D")),
567    }
568}
569
570/// Whether a station frame on this 2D curve is exact (#264): its point
571/// and axes at the station's distance itself, in closed form, rounding
572/// aside, with no quadrature or root find behind them.
573///
574/// Only a line: on every other family the distance is read by the
575/// arc-length inverse ([`ARC_LENGTH_TOLERANCE`], an estimate) or the point
576/// by quadrature (an intrinsic curve, a chain), so the frame is not exact
577/// and a placement in it must not be reported as exact.
578#[must_use]
579pub fn station_frame_is_exact2(curve: &Curve2) -> bool {
580    matches!(curve, Curve2::Line(_))
581}
582
583/// [`station_frame_is_exact2`] for a 3D curve: only a line.
584#[must_use]
585pub fn station_frame_is_exact3(curve: &Curve3) -> bool {
586    matches!(curve, Curve3::Line(_))
587}
588
589/// The section of a 2D curve at arc length `distance` from its start; see
590/// the [module documentation](self) for the conventions.
591///
592/// # Errors
593///
594/// A distance that is not finite, negative or beyond the curve's length,
595/// an unmeasurable family, and the evaluators' refusals, by name.
596pub fn station_section2(curve: &Curve2, distance: Scalar) -> GeomResult<SectionFrame> {
597    station_section2_on(curve, distance, SeamSide::Outgoing)
598}
599
600/// [`station_section2`] reading `side` of a seam the station lies on (see
601/// the [module documentation](self#seams-263)); off a seam the side does
602/// not matter.
603///
604/// # Errors
605///
606/// As [`station_section2`].
607pub fn station_section2_on(
608    curve: &Curve2,
609    distance: Scalar,
610    side: SeamSide,
611) -> GeomResult<SectionFrame> {
612    let distance = admitted(distance, station_length2(curve)?)?;
613    if let Some(section) = seam::seam_section2(curve, distance, side)? {
614        return Ok(section);
615    }
616    let t = parameter_at_arc_length2(curve, start2(curve), distance)?;
617    planar_frame(evaluate2(curve, t)?, derivative2(curve, t)?)
618}
619
620/// Whether a station at `distance` along a 3D curve lies ON a seam it
621/// reads two ways, by the rule [`station_section3_on`] applies (#286):
622/// the curve-evaluation provider's sided queries read a station there
623/// through it and answer every other measure side-lessly.
624///
625/// A distance outside `[0, L]` lies on no interior seam: `false`, so the
626/// side-less query keeps its own refusal or answer there.
627///
628/// # Errors
629///
630/// A curve whose length or seams cannot be read, by name.
631pub(crate) fn station_on_seam3(curve: &Curve3, distance: Scalar) -> GeomResult<bool> {
632    if !seam::sided3(curve) {
633        return Ok(false);
634    }
635    let Ok(distance) = admitted(distance, station_length3(curve)?) else {
636        return Ok(false);
637    };
638    Ok(seam::seam_at3(curve, distance)?.is_some())
639}
640
641/// The section of a 3D curve at `distance` from its start: plan distance
642/// on an elevated or banked curve, arc length on any other; see the
643/// [module documentation](self).
644///
645/// # Errors
646///
647/// As [`station_section2`], and a vertical tangent where the reference-up
648/// frame is built.
649pub fn station_section3(curve: &Curve3, distance: Scalar) -> GeomResult<SectionFrame> {
650    station_section3_on(curve, distance, SeamSide::Outgoing)
651}
652
653/// [`station_section3`] reading `side` of a seam the station lies on (see
654/// the [module documentation](self#seams-263)); off a seam the side does
655/// not matter.
656///
657/// # Errors
658///
659/// As [`station_section3`].
660pub fn station_section3_on(
661    curve: &Curve3,
662    distance: Scalar,
663    side: SeamSide,
664) -> GeomResult<SectionFrame> {
665    let distance = admitted(distance, station_length3(curve)?)?;
666    if let Some(section) = seam::seam_section3(curve, distance, side)? {
667        return Ok(section);
668    }
669    match curve {
670        Curve3::Banked(banked) => banked_frame(banked, distance),
671        Curve3::Elevated(elevated) => reference_up_frame(
672            crate::arc_length::elevated_point(elevated, distance)?,
673            crate::arc_length::elevated_tangent(elevated, distance)?,
674        ),
675        _ => {
676            let t = parameter_at_arc_length3(curve, start3(curve), distance)?;
677            reference_up_frame(evaluate3(curve, t)?, derivative3(curve, t)?)
678        }
679    }
680}