Skip to main content

ifc_alignment/curve/
elevation.rs

1//! Vertical segments as exact elevation laws.
2//!
3//! A vertical segment states height as a function of distance along the
4//! horizontal layout, not along the 3D curve. The two differ by
5//! sqrt(1 + g^2) wherever the grade is non-zero, so the distinction is kept
6//! explicit here rather than left to a caller to rediscover.
7//!
8//! `ElevationLaw::parabolic` encodes
9//! `z(d) = height + entry * d + (exit - entry) / (2 * length) * d^2`, which
10//! is the IFC parabolic vertical curve exactly, so PARABOLICARC needs no
11//! approximation.
12//!
13//! # Circular arcs are the circle itself (#258)
14//!
15//! IFC4.3 ADD2 (`IfcAlignmentVerticalSegmentTypeEnum`, 8.7.2.3) defines
16//! `CIRCULARARC` as "the derivative of vertical angle with respect to
17//! sloping length along the track (3D length) is constant": a circle in the
18//! (distance along, height) plane, of the signed `RadiusOfCurvature`
19//! (`IfcAlignmentVerticalSegment`: "positive values imply a CCW direction",
20//! a sag). Its height is not a polynomial in plan distance, and the
21//! standard quotes the EN 13803 ordinate `z_c(s) = s^2 / (2 R)` only as the
22//! offset from the tangent, not as the definition, so a parabola must not
23//! be substituted. `ElevationLaw::CircularArc` is that circle in closed
24//! form: `sin t(d) = sin t0 + d / R`, `t0 = atan(StartGradient)`.
25//!
26//! `RadiusOfCurvature` is the curve parameter; IFC4.3 lists the end
27//! direction among the values that "can be calculated". So the law is
28//! `StartHeight`, `StartGradient` and the radius, and `EndGradient` is only
29//! checked for the direction the radius turns, never used to place the
30//! road.
31//!
32//! # Clothoids stay a refusal
33//!
34//! A vertical `CLOTHOID` has curvature linear in its own 3D arc length
35//! (8.7.2.3: `kappa_v(s) = kappa_v1 + xi dkappa_v`), which
36//! `ElevationLaw::Intrinsic` carries exactly. But the business segment does
37//! not state `kappa_v1` or `kappa_v2`: `RadiusOfCurvature` is defined for
38//! arcs and parabolas only, and the reader refuses one on a clothoid. Two
39//! grades and a plan length leave the law one value short, so a
40//! `CLOTHOID` is a typed refusal naming that, not a guessed curvature. The
41//! geometry form (`IfcCurveSegment` over an `IfcClothoid` in an
42//! `IfcGradientCurve`) states the law and lowers in `ifc-geometry`.
43
44use axiolid_curve::ElevationLaw;
45use ifc_model::{EntityId, Model};
46
47use super::terminal::split_closing;
48use super::tolerance::SeamTolerance;
49use crate::error::{AlignmentError, AlignmentResult, ProfileSeam};
50use crate::horizontal::AlignmentUnits;
51use crate::vertical::{read_vertical_segment, VerticalSegment, VerticalSegmentType};
52use crate::view::AlignmentView;
53
54/// The exact elevation law for one `IfcAlignmentVerticalSegment`.
55///
56/// The law is written in the segment own distance, restarting at zero, so a
57/// segment can be moved along the profile without rewriting its
58/// coefficients.
59///
60/// # Errors
61///
62/// Refuses a segment whose family has no determined exact law (`CLOTHOID`,
63/// whose business segment states no curvature, and the user-defined and
64/// unknown families), and one whose stated parameters contradict its
65/// family.
66pub fn elevation_law(segment: &VerticalSegment) -> AlignmentResult<ElevationLaw> {
67    match segment.predefined_type {
68        VerticalSegmentType::ConstantGradient => constant_gradient(segment),
69        VerticalSegmentType::ParabolicArc => parabolic_arc(segment),
70        VerticalSegmentType::CircularArc => circular_arc(segment),
71        ref kind => Err(AlignmentError::Unsupported {
72            entity: segment.entity,
73            type_name: kind.source_name().to_owned(),
74            detail: refusal(kind),
75        }),
76    }
77}
78
79/// Why a vertical family has no exact elevation law, by name.
80fn refusal(kind: &VerticalSegmentType) -> &'static str {
81    match kind {
82        // Curvature linear in 3D arc length, but neither end value stated.
83        VerticalSegmentType::Clothoid => {
84            "no determined elevation law: a vertical clothoid's curvature runs linearly along its \
85             3D arc length, but IfcAlignmentVerticalSegment states neither its start nor its end \
86             curvature (RadiusOfCurvature is defined for arcs and parabolas only)"
87        }
88        _ => "no exact elevation law: the vertical PredefinedType defines no curve law",
89    }
90}
91
92/// `CONSTANTGRADIENT`: a straight grade, degree 1.
93///
94/// The two gradients are compared at rounding precision, not bit for bit:
95/// an exporter that writes `0.0424413181578388` and `0.0424413181578387`
96/// (Trimble, IFC4.x-IF) states one grade. The law uses `StartGradient`. A
97/// zero `RadiusOfCurvature` is the straight-line convention, not a curve.
98fn constant_gradient(segment: &VerticalSegment) -> AlignmentResult<ElevationLaw> {
99    let curved = segment.radius_of_curvature.is_some_and(|r| r != 0.0);
100    if curved
101        || !SeamTolerance::strict().same_gradient(segment.start_gradient, segment.end_gradient)
102    {
103        return Err(AlignmentError::InvalidSegment {
104            entity: segment.entity,
105            detail: "CONSTANTGRADIENT requires equal gradients and no non-zero curvature radius",
106        });
107    }
108    Ok(ElevationLaw::constant_grade(
109        segment.start_height,
110        segment.start_gradient,
111    ))
112}
113
114/// `PARABOLICARC`: the vertical curve joining two grades, degree 2.
115///
116/// `ElevationLaw::parabolic` divides by the length, and documents that a
117/// non-positive length is storable because naming it is a validator job.
118/// This is that validator: a zero-length parabola would otherwise produce an
119/// infinite or NaN coefficient and place the road surface nowhere.
120///
121/// The length check and the well-formedness check below overlap: removing
122/// either alone still refuses a zero length, because the infinity it
123/// produces is caught by the other. Both are kept deliberately. The length
124/// check names the actual fault, where `is_well_formed` would only report a
125/// non-finite coefficient, and it keeps holding if the kernel ever makes the
126/// division total.
127fn parabolic_arc(segment: &VerticalSegment) -> AlignmentResult<ElevationLaw> {
128    if segment.horizontal_length <= 0.0 {
129        return Err(AlignmentError::InvalidSegment {
130            entity: segment.entity,
131            detail: "PARABOLICARC requires a positive horizontal length",
132        });
133    }
134    let law = ElevationLaw::parabolic(
135        segment.start_height,
136        segment.start_gradient,
137        segment.end_gradient,
138        segment.horizontal_length,
139    );
140    // The guard above rules out the division blowing up, but the authored
141    // heights and grades are still file data.
142    if !law.is_well_formed() {
143        return Err(AlignmentError::InvalidSegment {
144            entity: segment.entity,
145            detail: "PARABOLICARC parameters do not form a finite elevation law",
146        });
147    }
148    Ok(law)
149}
150
151/// `CIRCULARARC`: the vertical circle, in closed form (see the module
152/// documentation).
153///
154/// Refuses a non-positive length, a radius whose sense contradicts the
155/// authored change of gradient (a sag, positive radius, must not lose
156/// grade), and an arc that turns vertical before its end
157/// (`|sin t0 + L / R| >= 1`): past that point it has no height at a plan
158/// distance.
159fn circular_arc(segment: &VerticalSegment) -> AlignmentResult<ElevationLaw> {
160    let invalid = |detail| {
161        Err(AlignmentError::InvalidSegment {
162            entity: segment.entity,
163            detail,
164        })
165    };
166    if segment.horizontal_length <= 0.0 {
167        return invalid("CIRCULARARC requires a positive horizontal length");
168    }
169    let Some(radius) = segment
170        .radius_of_curvature
171        .filter(|r| r.is_finite() && *r != 0.0)
172    else {
173        return invalid("CIRCULARARC requires a finite, non-zero RadiusOfCurvature");
174    };
175    let change = segment.end_gradient - segment.start_gradient;
176    let turns =
177        !SeamTolerance::strict().same_gradient(segment.start_gradient, segment.end_gradient);
178    if turns && change.signum() != radius.signum() {
179        return invalid(
180            "CIRCULARARC RadiusOfCurvature turns against the authored change of gradient \
181             (a positive radius is a sag and gains grade)",
182        );
183    }
184    let law = ElevationLaw::circular_arc(segment.start_height, segment.start_gradient, radius);
185    if !law.is_well_formed() || law.height_at(segment.horizontal_length).is_none() {
186        return invalid(
187            "CIRCULARARC turns vertical before its end: |sin t0 + L / R| reaches 1, so the arc \
188             has no height there",
189        );
190    }
191    Ok(law)
192}
193
194/// The whole vertical profile as one law over distance along the plan.
195///
196/// Segments are authored as a run, each with its own `StartDistAlong`, and
197/// `ElevationLaw::Piecewise` wants interior seams plus one law per piece,
198/// each written in its own distance restarting at zero. That is exactly how
199/// [`elevation_law`] writes a segment, so no rebasing is needed here.
200///
201/// Every segment restates where it starts: `StartDistAlong` and
202/// `StartHeight` must agree with where the previous segment ends (its
203/// station plus `HorizontalLength`, and its law's height there), or the
204/// profile has a gap or a step at the seam. Joining it anyway would
205/// silently shift every downstream height, so a step is refused with
206/// [`AlignmentError::ProfileDiscontinuity`] (`ProfileSeam::Height`).
207///
208/// A change of grade at a seam whose height is continuous is accepted: a
209/// grade break. IFC4.3 ADD2 (`IfcAlignmentVerticalSegment`): "The
210/// transition at the segment connection is not enforced to be tangential",
211/// and the schema has no attribute that would demand it. The pieces of the
212/// returned law are independent, so the break is carried exactly: each side
213/// keeps its own authored grade, and both meet at one height. Ask
214/// [`VerticalLayout::require_tangential`](crate::VerticalLayout::require_tangential)
215/// to demand tangency explicitly, and [`VerticalLayout::seams`](crate::VerticalLayout::seams)
216/// to list the breaks.
217///
218/// The zero-length segment IFC4.3 requires at the end of a layout adds no
219/// piece; its `StartDistAlong` and `StartHeight` are checked against the
220/// profile's end like any seam. A zero-length segment anywhere else, or as
221/// the only segment, is refused ([`AlignmentError::SemanticViolation`]).
222///
223/// Seams are compared with [`SeamTolerance::strict`]: floating-point
224/// rounding only. A file whose exporter rounds stations or heights states
225/// that in its `Precision`; use [`profile_law_within`] with
226/// [`SeamTolerance::for_model`], or [`vertical_profile_law`], to honour it.
227///
228/// # Errors
229///
230/// Refuses an empty profile, segments that are not sorted and contiguous,
231/// a height discontinuity at any seam, a misplaced zero-length segment, and
232/// any segment without an exact law.
233pub fn profile_law(segments: &[VerticalSegment]) -> AlignmentResult<ElevationLaw> {
234    profile_law_within(segments, SeamTolerance::strict())
235}
236
237/// [`profile_law`] with an explicit seam tolerance.
238///
239/// `tolerance` widens only the LENGTH seams (`StartDistAlong` contiguity and
240/// `StartHeight`). See [`SeamTolerance`] for the rule and its evidence.
241///
242/// # Errors
243///
244/// As [`profile_law`].
245pub fn profile_law_within(
246    segments: &[VerticalSegment],
247    tolerance: SeamTolerance,
248) -> AlignmentResult<ElevationLaw> {
249    let (body, closing) = split_closing(segments, |s| s.horizontal_length, |s| s.entity)?;
250    let Some(first) = body.first() else {
251        return Err(AlignmentError::SemanticViolation {
252            entity: None,
253            rule: "a vertical profile must have at least one segment",
254        });
255    };
256
257    let mut laws: Vec<ElevationLaw> = Vec::with_capacity(body.len());
258    let mut breaks = Vec::with_capacity(body.len() - 1);
259    let start = first.start_dist_along;
260    for (index, segment) in body.iter().enumerate() {
261        let law = elevation_law(segment)?;
262        if let (Some(previous), Some(previous_law)) =
263            (index.checked_sub(1).map(|i| &body[i]), laws.last())
264        {
265            check_seam(previous, previous_law, segment, tolerance)?;
266            breaks.push(segment.start_dist_along - start);
267        }
268        laws.push(law);
269    }
270    if let (Some(closing), Some(last), Some(last_law)) = (closing, body.last(), laws.last()) {
271        check_seam(last, last_law, closing, tolerance)?;
272    }
273    Ok(match laws.len() {
274        1 => laws.remove(0),
275        _ => ElevationLaw::Piecewise { breaks, laws },
276    })
277}
278
279/// Refuse a gap or overlap in station, or a step in height, where `segment`
280/// begins.
281///
282/// A gap or overlap means the profile does not describe one continuous
283/// road. The previous end height is evaluated from its exact law rather than
284/// recomputed here, so the seam is compared against the same polynomial the
285/// profile will evaluate. The grade is not compared: a grade break at a
286/// height-continuous seam is legal IFC4.3 (see [`profile_law`]).
287fn check_seam(
288    previous: &VerticalSegment,
289    previous_law: &ElevationLaw,
290    segment: &VerticalSegment,
291    tolerance: SeamTolerance,
292) -> AlignmentResult<()> {
293    let expected = previous.start_dist_along + previous.horizontal_length;
294    if !tolerance.same_length(segment.start_dist_along, expected) {
295        return Err(AlignmentError::InvalidSegment {
296            entity: segment.entity,
297            detail: "vertical segments must be contiguous and ascending in StartDistAlong",
298        });
299    }
300    let end_height = previous_law.height_at(previous.horizontal_length).ok_or(
301        AlignmentError::InvalidSegment {
302            entity: previous.entity,
303            detail: "vertical segment has no finite end height",
304        },
305    )?;
306    if !tolerance.same_length(segment.start_height, end_height) {
307        return Err(AlignmentError::ProfileDiscontinuity {
308            entity: segment.entity,
309            previous: previous.entity,
310            seam: ProfileSeam::Height,
311            expected: end_height,
312            actual: segment.start_height,
313        });
314    }
315    Ok(())
316}
317
318/// The exact profile of an `IfcAlignmentVertical`, checked at the seam
319/// tolerance the model declares.
320///
321/// Reads the nested segment chain in authored order and joins it with
322/// [`profile_law_within`] at [`SeamTolerance::for_model`]. This is the
323/// entry point for a profile read from a file: an exporter that rounds
324/// stations or heights to its stated `Precision` is accepted, a step beyond
325/// it is still refused.
326///
327/// Like [`profile_law`], the law is indexed by distance from the FIRST
328/// segment's `StartDistAlong`; the composed gradient curve re-indexes it to
329/// plan distance.
330///
331/// # Errors
332///
333/// Refuses a model that is not IFC4X3, an entity that is not an
334/// `IfcAlignmentVertical`, an empty layout, an invalid declared
335/// `Precision`, and everything [`profile_law`] refuses.
336pub fn vertical_profile_law(
337    model: &Model,
338    entity: EntityId,
339    units: AlignmentUnits,
340) -> AlignmentResult<ElevationLaw> {
341    let view = AlignmentView::for_model(model)?;
342    let layout = model
343        .get(entity)
344        .ok_or(AlignmentError::MissingEntity { entity })?;
345    if !view.schema.is_a(&layout.type_name, "IfcAlignmentVertical") {
346        return Err(AlignmentError::WrongType {
347            entity,
348            expected: "IfcAlignmentVertical",
349            actual: layout.type_name.to_string(),
350        });
351    }
352    let tolerance = SeamTolerance::for_model(model, units)?;
353    let segments = view
354        .segment_chain(entity, "IfcAlignmentVerticalSegment")?
355        .into_iter()
356        .map(|id| read_vertical_segment(model, id, units))
357        .collect::<AlignmentResult<Vec<_>>>()?;
358    if segments.is_empty() {
359        return Err(AlignmentError::SemanticViolation {
360            entity: Some(entity),
361            rule: "IfcAlignmentVertical must nest at least one IfcAlignmentSegment",
362        });
363    }
364    profile_law_within(&segments, tolerance)
365}
366
367/// Re-index a profile law from its first `StartDistAlong` to plan distance.
368///
369/// IFC4.3 ADD2 measures `IfcAlignmentVerticalSegment.StartDistAlong` "from
370/// the start point of `IfcAlignmentHorizontal`", and `Elevated3` reads its
371/// law at plan distance. [`profile_law`] writes the law from the profile's
372/// own start, so a profile starting at station `start` must be shifted by it
373/// before composition, or every height lands `start` metres early.
374///
375/// - `start` within `tolerance` of zero: the law is already plan-indexed.
376/// - `start < 0` (the profile begins before the plan): pieces wholly before
377///   the plan start are dropped and the piece straddling it is rewritten so
378///   plan distance 0 reads the profile at station 0: a polynomial by an
379///   exact Taylor shift, `q(d) = p(d + o)`, a circular arc as the same
380///   circle from its closed-form height and grade at `o`.
381/// - a profile starting after the plan start, or ending (`end`, its last
382///   station) before the plan ends (`plan_length`), beyond `tolerance`:
383///   refused. Heights outside the profile do not exist, and `Elevated3` has
384///   no domain bound to exclude them; composing anyway would invent the
385///   surface there. A profile running past the plan end is fine: the plan
386///   bounds the curve.
387pub(crate) fn indexed_from_plan_start(
388    law: ElevationLaw,
389    start: f64,
390    end: f64,
391    plan_length: f64,
392    vertical: EntityId,
393    tolerance: SeamTolerance,
394) -> AlignmentResult<ElevationLaw> {
395    let starts_late = start > 0.0 && !tolerance.same_length(start, 0.0);
396    let ends_early = end < plan_length && !tolerance.same_length(end, plan_length);
397    if starts_late || ends_early {
398        return Err(AlignmentError::Unsupported {
399            entity: vertical,
400            type_name: "IfcAlignmentVertical".to_owned(),
401            detail: "the vertical profile does not cover the whole plan; the composed curve has \
402                     no domain to leave stations outside the profile without heights",
403        });
404    }
405    if start >= 0.0 {
406        return Ok(law);
407    }
408    let offset = -start;
409    let malformed = || AlignmentError::InvalidSegment {
410        entity: vertical,
411        detail: "vertical profile law is not a run of polynomial and circular pieces",
412    };
413    let (breaks, laws) = match law {
414        ElevationLaw::Piecewise { breaks, laws } => (breaks, laws),
415        single => (Vec::new(), vec![single]),
416    };
417    // The piece holding profile distance `offset`, as `partition_point` in
418    // the kernel's own `piece_at` picks it: a seam belongs to the piece
419    // starting there.
420    let index = breaks.partition_point(|b| *b <= offset);
421    let piece_start = if index == 0 { 0.0 } else { breaks[index - 1] };
422    let mut laws = laws.into_iter().skip(index);
423    let local = offset - piece_start;
424    let first = match laws.next() {
425        Some(ElevationLaw::Polynomial { coefficients }) => taylor_shift(&coefficients, local),
426        // The same circle read from `local` on: its height and grade there,
427        // both closed form, and the unchanged radius.
428        Some(arc @ ElevationLaw::CircularArc { radius, .. }) => {
429            match (arc.height_at(local), arc.grade_at(local)) {
430                (Some(height), Some(grade)) => ElevationLaw::circular_arc(height, grade, radius),
431                _ => return Err(malformed()),
432            }
433        }
434        _ => return Err(malformed()),
435    };
436    let mut shifted = vec![first];
437    shifted.extend(laws);
438    Ok(match shifted.len() {
439        1 => shifted.remove(0),
440        _ => ElevationLaw::Piecewise {
441            breaks: breaks[index..].iter().map(|b| b - offset).collect(),
442            laws: shifted,
443        },
444    })
445}
446
447/// Coefficients of `q(d) = p(d + offset)`, exactly by the binomial theorem:
448/// `q_k = sum_{j >= k} C(j, k) p_j offset^(j - k)`.
449fn taylor_shift(coefficients: &[f64], offset: f64) -> ElevationLaw {
450    let shifted = (0..coefficients.len())
451        .map(|k| {
452            let mut binomial = 1.0;
453            let mut power = 1.0;
454            let mut sum = 0.0;
455            for (j, coefficient) in coefficients.iter().enumerate().skip(k) {
456                if j > k {
457                    binomial = binomial * j as f64 / (j - k) as f64;
458                    power *= offset;
459                }
460                sum += binomial * coefficient * power;
461            }
462            sum
463        })
464        .collect();
465    ElevationLaw::Polynomial {
466        coefficients: shifted,
467    }
468}