Skip to main content

ifc_alignment/curve/
gradient.rs

1//! The 3D centreline: a horizontal layout paired with its vertical profile.
2//!
3//! This is the `IfcGradientCurve` idea. The plan and the profile are both
4//! exact and stay exact: `Curve3::Elevated` composes them rather than
5//! re-encoding either, so a clothoid stays a clothoid and a parabolic
6//! vertical curve stays a parabola.
7//!
8//! Height is a function of distance along the PLAN, not along the 3D curve.
9//! The two diverge by sqrt(1 + g^2) wherever grade is non-zero, and the
10//! kernel names that convention in the type, so nothing here re-derives it.
11//!
12//! `Elevated3.plan` is a single `Curve2`, so the plan is the whole
13//! horizontal layout as ONE curve parameterised by arc length
14//! ([`lower_horizontal_plan`]): an intrinsic curve with a piecewise
15//! curvature law, or an arc-length chain when the layout holds a `CUBIC`,
16//! never the per-segment composite. Its parameter is distance along the
17//! plan from the first horizontal segment's start. Seams the plan could not
18//! verify in closed form are reported on the result.
19
20use axiolid_curve::{Curve2, Curve3, Elevated3};
21use axiolid_model::{GeometryGraphBuilder, GeometryNode};
22use ifc_model::{EntityId, Model};
23
24use super::assemble::{finish, LoweredAlignmentCurve};
25use super::elevation::{indexed_from_plan_start, profile_law_within};
26use super::plan::lower_horizontal_plan;
27use super::seam::HorizontalSeam;
28use super::tolerance::SeamTolerance;
29use crate::cant::CantLayout;
30use crate::error::{AlignmentError, AlignmentResult};
31use crate::horizontal::AlignmentUnits;
32use crate::vertical::read_vertical_segment;
33use crate::view::AlignmentView;
34
35/// Lower an `IfcAlignment` to an exact 3D centreline.
36///
37/// Pairs the alignment horizontal layout with its vertical profile as a
38/// `Curve3::Elevated`. Both halves stay exact and either can be recovered
39/// unchanged.
40///
41/// # Errors
42///
43/// Refuses an alignment without both layouts, a vertical segment family
44/// with no determined elevation law (`CLOTHOID`), a non-contiguous profile,
45/// and any plan
46/// [`lower_horizontal_plan`] refuses (a segment without an exact law, a
47/// heading kink, or a closed-form position gap). Seams after a transition
48/// spiral are reported in [`LoweredAlignmentCurve::seams`], not refused.
49pub fn lower_gradient_curve(
50    model: &Model,
51    entity: EntityId,
52    units: AlignmentUnits,
53) -> AlignmentResult<LoweredAlignmentCurve> {
54    let view = AlignmentView::for_model(model)?;
55    let alignment = model
56        .get(entity)
57        .ok_or(AlignmentError::MissingEntity { entity })?;
58    if !view.schema.is_a(&alignment.type_name, "IfcAlignment") {
59        return Err(AlignmentError::WrongType {
60            entity,
61            expected: "IfcAlignment",
62            actual: alignment.type_name.to_string(),
63        });
64    }
65
66    let horizontal = sole_layout(&view, entity, "IfcAlignmentHorizontal")?;
67    let vertical = sole_layout(&view, entity, "IfcAlignmentVertical")?;
68
69    let cant = optional_cant(model, &view, entity, units)?;
70    let composed = compose(model, &view, horizontal, vertical, units, cant.as_ref())?;
71
72    let mut builder = GeometryGraphBuilder::new();
73    let root = builder
74        .push(GeometryNode::Curve3(Curve3::Elevated(composed.centreline)))
75        .map_err(|error| AlignmentError::Graph {
76            detail: error.to_string(),
77        })?;
78
79    let mut sources = vec![horizontal, vertical];
80    sources.extend(composed.vertical_ids);
81    let mut lowered = finish(builder, root, sources)?;
82    lowered.seams = composed.seams;
83    Ok(lowered)
84}
85
86/// The single nested layout of a given type.
87///
88/// IFC allows an alignment to nest several layouts; pairing an arbitrary one
89/// would silently pick a road other than the one the caller meant.
90pub(super) fn sole_layout(
91    view: &AlignmentView,
92    alignment: EntityId,
93    expected: &'static str,
94) -> AlignmentResult<EntityId> {
95    let children = view.nested_children(alignment, expected)?;
96    match children.as_slice() {
97        [only] => Ok(*only),
98        [] => Err(AlignmentError::SemanticViolation {
99            entity: Some(alignment),
100            rule: "a gradient curve needs both a horizontal and a vertical layout",
101        }),
102        _ => Err(AlignmentError::SemanticViolation {
103            entity: Some(alignment),
104            rule: "an alignment with several layouts of one kind is ambiguous to compose",
105        }),
106    }
107}
108
109/// The composed centreline, without a surrounding graph.
110///
111/// Shared by the graph lowering and by callers that need the curve itself
112/// to hand to an evaluator. One composition, so the two cannot drift.
113pub(super) fn compose(
114    model: &Model,
115    view: &AlignmentView<'_>,
116    horizontal: EntityId,
117    vertical: EntityId,
118    units: AlignmentUnits,
119    cant: Option<&CantLayout>,
120) -> AlignmentResult<Composed> {
121    let plan = lower_horizontal_plan(model, horizontal, units, cant)?;
122    let ids = view.segment_chain(vertical, "IfcAlignmentVerticalSegment")?;
123    let mut segments = Vec::with_capacity(ids.len());
124    for id in &ids {
125        segments.push(read_vertical_segment(model, *id, units)?);
126    }
127    // The profile's seams are checked at the precision the file declares
128    // (#141), the same rule `vertical_profile_law` applies.
129    let tolerance = SeamTolerance::for_model(model, units)?;
130    let profile = profile_law_within(&segments, tolerance)?;
131    // `profile_law` is indexed from the first StartDistAlong; the plan from
132    // its own start. Re-index so both halves read the same distance, and
133    // refuse a profile that does not cover the whole plan.
134    let start = segments.first().map_or(0.0, |s| s.start_dist_along);
135    let end = segments
136        .last()
137        .map_or(0.0, |s| s.start_dist_along + s.horizontal_length);
138    let plan_length = match &plan.curve {
139        Curve2::Intrinsic(intrinsic) => Some(intrinsic.length),
140        Curve2::Chain(chain) => chain.length(),
141        _ => None,
142    }
143    .ok_or_else(|| AlignmentError::Graph {
144        detail: "the horizontal plan did not lower to an arc-length curve".to_owned(),
145    })?;
146    let elevation = indexed_from_plan_start(profile, start, end, plan_length, vertical, tolerance)?;
147    Ok(Composed {
148        centreline: Elevated3::new(plan.curve, elevation),
149        plan_length,
150        vertical_ids: ids,
151        seams: plan.seams,
152    })
153}
154
155/// The composed centreline and what the callers report about it.
156pub(super) struct Composed {
157    /// Plan and profile, both exact.
158    pub(super) centreline: Elevated3,
159    /// Arc length of the plan.
160    pub(super) plan_length: f64,
161    /// The vertical segments, in authored order.
162    pub(super) vertical_ids: Vec<EntityId>,
163    /// The plan's seams.
164    pub(super) seams: Vec<HorizontalSeam>,
165}
166
167/// The exact 3D centreline of `entity`, an `IfcAlignment`.
168///
169/// Same composition the graph lowering uses, returned directly so a caller
170/// can pass it to a `CurveEvaluator`. Returning the curve rather than a
171/// point keeps evaluation the caller's choice: this crate stores exact
172/// geometry and never computes on it.
173pub fn gradient_curve3(
174    model: &Model,
175    entity: EntityId,
176    units: AlignmentUnits,
177) -> AlignmentResult<Curve3> {
178    let view = AlignmentView::for_model(model)?;
179    let alignment = model
180        .get(entity)
181        .ok_or(AlignmentError::MissingEntity { entity })?;
182    if !view.schema.is_a(&alignment.type_name, "IfcAlignment") {
183        return Err(AlignmentError::WrongType {
184            entity,
185            expected: "IfcAlignment",
186            actual: alignment.type_name.to_string(),
187        });
188    }
189    let horizontal = sole_layout(&view, entity, "IfcAlignmentHorizontal")?;
190    let vertical = sole_layout(&view, entity, "IfcAlignmentVertical")?;
191    let cant = optional_cant(model, &view, entity, units)?;
192    let composed = compose(model, &view, horizontal, vertical, units, cant.as_ref())?;
193    Ok(Curve3::Elevated(composed.centreline))
194}
195
196/// The alignment cant layout, when it has exactly one.
197///
198/// Cant is optional: a road alignment has none, and its absence is not an
199/// error. Several cant layouts are ambiguous, which is.
200fn optional_cant(
201    model: &Model,
202    view: &AlignmentView,
203    alignment: EntityId,
204    units: AlignmentUnits,
205) -> AlignmentResult<Option<CantLayout>> {
206    let children = view.nested_children(alignment, "IfcAlignmentCant")?;
207    match children.as_slice() {
208        [] => Ok(None),
209        [only] => CantLayout::resolve(model, *only, units).map(Some),
210        _ => Err(AlignmentError::SemanticViolation {
211            entity: Some(alignment),
212            rule: "an alignment with several cant layouts is ambiguous to compose",
213        }),
214    }
215}