Skip to main content

ifc_alignment/cant/
segment.rs

1//! IFC4x3 cant alignment segment parameters.
2
3use ifc_model::value::Value;
4use ifc_model::{EntityId, Model};
5
6use crate::error::{AlignmentError, AlignmentResult};
7use crate::horizontal::AlignmentUnits;
8use crate::slot;
9
10/// `IfcAlignmentCantSegmentTypeEnum` member: the cant transition law applied
11/// over one segment's distance-along span.
12#[non_exhaustive]
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum CantSegmentType {
15    /// `BLOSSCURVE`: a bloss (cubic) transition between cant values.
16    BlossCurve,
17    /// `CONSTANTCANT`: cant held level across the segment.
18    ConstantCant,
19    /// `COSINECURVE`: a cosine-shaped transition between cant values.
20    CosineCurve,
21    /// `HELMERTCURVE`: a Helmert (parabolic) transition between cant values.
22    HelmertCurve,
23    /// `LINEARTRANSITION`: a straight-line ramp between cant values.
24    LinearTransition,
25    /// `SINECURVE`: a sine-shaped transition between cant values.
26    SineCurve,
27    /// `VIENNESEBEND`: a cant swing whose bank angle follows a
28    /// closed-form quartic.
29    ///
30    /// Cant evaluation resolves this exactly. It is the one type that also
31    /// needs the parent `IfcAlignmentCant.RailHeadDistance`, because the
32    /// spec defines the swing through a bank angle rather than a cant
33    /// value directly.
34    VienneseBend,
35    /// `USERDEFINED`: an author-supplied law outside the enumerated set.
36    UserDefined,
37    /// `NOTDEFINED`: no cant transition law was declared.
38    NotDefined,
39    /// An enumeration token this crate does not recognise, preserved verbatim.
40    Other(String),
41}
42
43/// Borrowed projection of one nested segment of an `IfcAlignmentCant` layout
44/// (`IfcAlignmentCantSegment`), with lengths already reduced to metres.
45#[derive(Debug, Clone, PartialEq)]
46#[non_exhaustive]
47pub struct CantSegment {
48    /// The `IfcAlignmentCantSegment` entity this was read from.
49    pub entity: EntityId,
50    /// `StartDistAlong`: distance along the parent alignment where this
51    /// segment begins.
52    pub start_dist_along: f64,
53    /// `HorizontalLength`: the segment's span along the alignment.
54    pub horizontal_length: f64,
55    /// `StartCantLeft`: cant applied to the left rail at the segment start.
56    pub start_cant_left: f64,
57    /// `EndCantLeft`: cant applied to the left rail at the segment end, when
58    /// authored. Absence is legal only when `end_cant_right` is also absent.
59    pub end_cant_left: Option<f64>,
60    /// `StartCantRight`: cant applied to the right rail at the segment start.
61    pub start_cant_right: f64,
62    /// `EndCantRight`: cant applied to the right rail at the segment end,
63    /// when authored. Absence is legal only when `end_cant_left` is also
64    /// absent.
65    pub end_cant_right: Option<f64>,
66    /// `PredefinedType`: which transition law governs this segment.
67    pub predefined_type: CantSegmentType,
68}
69
70impl CantSegment {
71    /// The `PredefinedType` enumeration token this segment was read from.
72    pub(crate) fn predefined_type_name(&self) -> &str {
73        match &self.predefined_type {
74            CantSegmentType::BlossCurve => "BLOSSCURVE",
75            CantSegmentType::ConstantCant => "CONSTANTCANT",
76            CantSegmentType::CosineCurve => "COSINECURVE",
77            CantSegmentType::HelmertCurve => "HELMERTCURVE",
78            CantSegmentType::LinearTransition => "LINEARTRANSITION",
79            CantSegmentType::SineCurve => "SINECURVE",
80            CantSegmentType::VienneseBend => "VIENNESEBEND",
81            CantSegmentType::UserDefined => "USERDEFINED",
82            CantSegmentType::NotDefined => "NOTDEFINED",
83            CantSegmentType::Other(name) => name,
84        }
85    }
86}
87
88/// Read one `IfcAlignmentCantSegment` referenced by `id`.
89///
90/// Fails if `id` is missing, is not an `IfcAlignmentCantSegment`, an
91/// attribute is missing or the wrong kind, `HorizontalLength` is negative,
92/// any value is non-finite, or exactly one of `EndCantLeft`/`EndCantRight`
93/// is supplied without the other.
94pub fn read_cant_segment(
95    model: &Model,
96    id: EntityId,
97    units: AlignmentUnits,
98) -> AlignmentResult<CantSegment> {
99    validate_units(units)?;
100    let entity = model
101        .get(id)
102        .ok_or(AlignmentError::MissingEntity { entity: id })?;
103    if !entity
104        .type_name
105        .eq_ignore_ascii_case("IFCALIGNMENTCANTSEGMENT")
106    {
107        return Err(AlignmentError::WrongType {
108            entity: id,
109            expected: "IFCALIGNMENTCANTSEGMENT",
110            actual: entity.type_name.to_string(),
111        });
112    }
113    // IFC4X3_ADD2: inherited StartTag/EndTag are slots 0..1; this declaration
114    // contributes StartDistAlong through PredefinedType at slots 2..8.
115    let values = &entity.attributes;
116    let start_dist_along = length(
117        number(values, id, slot::cant::START_DIST_ALONG, "StartDistAlong")?,
118        units,
119    );
120    let horizontal_length = length(
121        number(
122            values,
123            id,
124            slot::cant::HORIZONTAL_LENGTH,
125            "HorizontalLength",
126        )?,
127        units,
128    );
129    let start_cant_left = length(
130        number(values, id, slot::cant::START_CANT_LEFT, "StartCantLeft")?,
131        units,
132    );
133    let end_cant_left = optional_number(values, id, slot::cant::END_CANT_LEFT, "EndCantLeft")?
134        .map(|value| length(value, units));
135    let start_cant_right = length(
136        number(values, id, slot::cant::START_CANT_RIGHT, "StartCantRight")?,
137        units,
138    );
139    let end_cant_right = optional_number(values, id, slot::cant::END_CANT_RIGHT, "EndCantRight")?
140        .map(|value| length(value, units));
141    let predefined_type = parse_type(enum_name(
142        values,
143        id,
144        slot::cant::PREDEFINED_TYPE,
145        "PredefinedType",
146    )?);
147
148    let finite = [
149        start_dist_along,
150        horizontal_length,
151        start_cant_left,
152        start_cant_right,
153    ]
154    .into_iter()
155    .all(f64::is_finite)
156        && end_cant_left.is_none_or(f64::is_finite)
157        && end_cant_right.is_none_or(f64::is_finite);
158    if !finite || horizontal_length < 0.0 {
159        return Err(AlignmentError::InvalidSegment {
160            entity: id,
161            detail: "cant parameters must be finite and horizontal length non-negative",
162        });
163    }
164    let ends_are_paired = end_cant_left.is_some() == end_cant_right.is_some();
165    if !ends_are_paired {
166        return Err(AlignmentError::InvalidSegment {
167            entity: id,
168            detail: "left and right end cant must both be supplied or both omitted",
169        });
170    }
171
172    Ok(CantSegment {
173        entity: id,
174        start_dist_along,
175        horizontal_length,
176        start_cant_left,
177        end_cant_left,
178        start_cant_right,
179        end_cant_right,
180        predefined_type,
181    })
182}
183
184fn parse_type(name: &str) -> CantSegmentType {
185    match name.to_ascii_uppercase().as_str() {
186        "BLOSSCURVE" => CantSegmentType::BlossCurve,
187        "CONSTANTCANT" => CantSegmentType::ConstantCant,
188        "COSINECURVE" => CantSegmentType::CosineCurve,
189        "HELMERTCURVE" => CantSegmentType::HelmertCurve,
190        "LINEARTRANSITION" => CantSegmentType::LinearTransition,
191        "SINECURVE" => CantSegmentType::SineCurve,
192        "VIENNESEBEND" => CantSegmentType::VienneseBend,
193        "USERDEFINED" => CantSegmentType::UserDefined,
194        "NOTDEFINED" => CantSegmentType::NotDefined,
195        _ => CantSegmentType::Other(name.to_string()),
196    }
197}
198
199fn validate_units(units: AlignmentUnits) -> AlignmentResult<()> {
200    if !units.length_to_metres.is_finite() || units.length_to_metres <= 0.0 {
201        return Err(AlignmentError::InvalidUnits {
202            detail: "length factor must be finite and positive",
203        });
204    }
205    Ok(())
206}
207
208fn length(value: f64, units: AlignmentUnits) -> f64 {
209    value * units.length_to_metres
210}
211
212fn number(values: &[Value], id: EntityId, slot: usize, name: &'static str) -> AlignmentResult<f64> {
213    // A typed parameter (`IFCLENGTHMEASURE(1.)`) reads as the bare number,
214    // as in the horizontal reader (#140).
215    values
216        .get(slot)
217        .and_then(|value| value.unwrap_typed().as_f64())
218        .ok_or(AlignmentError::InvalidAttribute {
219            entity: id,
220            index: slot,
221            name,
222        })
223}
224
225fn optional_number(
226    values: &[Value],
227    id: EntityId,
228    slot: usize,
229    name: &'static str,
230) -> AlignmentResult<Option<f64>> {
231    match values.get(slot) {
232        Some(Value::Null) => Ok(None),
233        _ => number(values, id, slot, name).map(Some),
234    }
235}
236
237fn enum_name<'a>(
238    values: &'a [Value],
239    id: EntityId,
240    slot: usize,
241    name: &'static str,
242) -> AlignmentResult<&'a str> {
243    match values.get(slot) {
244        Some(Value::Enum(value)) => Ok(value),
245        _ => Err(AlignmentError::InvalidAttribute {
246            entity: id,
247            index: slot,
248            name,
249        }),
250    }
251}