Skip to main content

ifc_alignment/horizontal/
segment.rs

1//! IFC4x3 horizontal alignment segment parameters.
2
3use axiolid_core::Point2;
4use ifc_model::value::Value;
5use ifc_model::{Entity, EntityId, Model};
6
7use crate::error::{AlignmentError, AlignmentResult};
8
9/// Project unit conversion applied exactly once while reading a segment.
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct AlignmentUnits {
12    /// Factor converting a length attribute's stored value to metres.
13    pub length_to_metres: f64,
14    /// Factor converting an angle attribute's stored value to radians, or
15    /// `None` when the project declares no plane-angle unit; reading an angle
16    /// then refuses with [`AlignmentError::AngleUnitUndeclared`].
17    pub angle_to_radians: Option<f64>,
18}
19
20impl AlignmentUnits {
21    fn validate(self) -> AlignmentResult<Self> {
22        if !self.length_to_metres.is_finite() || self.length_to_metres <= 0.0 {
23            return Err(AlignmentError::InvalidUnits {
24                detail: "length factor must be finite and positive",
25            });
26        }
27        if self
28            .angle_to_radians
29            .is_some_and(|factor| !factor.is_finite() || factor <= 0.0)
30        {
31            return Err(AlignmentError::InvalidUnits {
32                detail: "angle factor must be finite and positive",
33            });
34        }
35        Ok(self)
36    }
37}
38
39/// IFC4x3 horizontal segment kind, preserving the declaration rather than guessing.
40#[non_exhaustive]
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum HorizontalSegmentType {
43    /// `LINE`: a straight tangent segment (zero curvature throughout).
44    Line,
45    /// `CIRCULARARC`: constant-radius arc; `StartRadiusOfCurvature` and
46    /// `EndRadiusOfCurvature` are equal.
47    CircularArc,
48    /// A transition-spiral `PredefinedType` token (e.g. `CLOTHOID`,
49    /// `CUBIC`, `BLOSS`), preserved verbatim -- which spiral laws this crate
50    /// can lower exactly is decided downstream, not by this type.
51    Transition(String),
52    /// `USERDEFINED`: an author-supplied law outside the enumerated set.
53    UserDefined,
54    /// `NOTDEFINED`: no horizontal segment kind was declared.
55    NotDefined,
56}
57
58impl HorizontalSegmentType {
59    /// The `PredefinedType` enumeration token this variant was read from.
60    pub fn source_name(&self) -> &str {
61        match self {
62            Self::Line => "LINE",
63            Self::CircularArc => "CIRCULARARC",
64            Self::Transition(name) => name,
65            Self::UserDefined => "USERDEFINED",
66            Self::NotDefined => "NOTDEFINED",
67        }
68    }
69}
70
71/// Resolved IFC4x3 `IfcAlignmentHorizontalSegment` parameters in SI units.
72#[derive(Debug, Clone, PartialEq)]
73#[non_exhaustive]
74pub struct HorizontalSegment {
75    /// The `IfcAlignmentHorizontalSegment` entity this was read from.
76    pub entity: EntityId,
77    /// `StartPoint`: the segment's start, resolved from the referenced
78    /// `IfcCartesianPoint`.
79    pub start_point: Point2,
80    /// `StartDirection`: bearing at the segment start, in radians.
81    pub start_direction: f64,
82    /// `StartRadiusOfCurvature`.
83    pub start_radius: f64,
84    /// `EndRadiusOfCurvature`.
85    pub end_radius: f64,
86    /// `SegmentLength`: arc length along the segment. Non-negative
87    /// (`IfcNonNegativeLengthMeasure`); zero only for the closing segment
88    /// IFC4.3 requires at the end of a layout, which the layout paths
89    /// accept in last place alone.
90    pub segment_length: f64,
91    /// `GravityCenterLineHeight`, when authored (rail/cant-related, not
92    /// used by exact lowering).
93    pub gravity_center_line_height: Option<f64>,
94    /// `PredefinedType`: which horizontal segment kind this is.
95    pub segment_type: HorizontalSegmentType,
96}
97
98// Slots live in `crate::slot` so the authoring side indexes the same
99// definitions these readers do (ADR 0011).
100use crate::slot::horizontal::{
101    END_RADIUS, GRAVITY_CENTER_LINE_HEIGHT, PREDEFINED_TYPE, SEGMENT_LENGTH, START_DIRECTION,
102    START_POINT, START_RADIUS,
103};
104
105/// Read one `IfcAlignmentHorizontalSegment` referenced by `id`.
106///
107/// Fails if `units` is non-finite or non-positive, `id` is missing or not an
108/// `IfcAlignmentHorizontalSegment`, `StartPoint` does not resolve to an
109/// `IfcCartesianPoint` with at least two coordinates, an attribute is
110/// missing or the wrong kind, any value is non-finite, or `SegmentLength`
111/// is negative.
112///
113/// A zero `SegmentLength` is read: IFC4.3 (concept template *Alignment
114/// Layout - Horizontal, Vertical and Cant*) requires a zero-length segment
115/// at the end of every layout. Where it may stand is a layout question, so
116/// the layout paths decide it, not this reader.
117pub fn read_horizontal_segment(
118    model: &Model,
119    id: EntityId,
120    units: AlignmentUnits,
121) -> AlignmentResult<HorizontalSegment> {
122    let units = units.validate()?;
123    let entity = model
124        .get(id)
125        .ok_or(AlignmentError::MissingEntity { entity: id })?;
126    if !entity.is_type("IFCALIGNMENTHORIZONTALSEGMENT") {
127        return Err(AlignmentError::WrongType {
128            entity: id,
129            expected: "IFCALIGNMENTHORIZONTALSEGMENT",
130            actual: entity.type_name.to_string(),
131        });
132    }
133    let point_ref = required_ref(entity, id, START_POINT, "StartPoint")?;
134    let point = model
135        .get(point_ref)
136        .ok_or(AlignmentError::MissingEntity { entity: point_ref })?;
137    if !point.is_type("IFCCARTESIANPOINT") {
138        return Err(AlignmentError::WrongType {
139            entity: point_ref,
140            expected: "IFCCARTESIANPOINT",
141            actual: point.type_name.to_string(),
142        });
143    }
144    let coordinates =
145        point
146            .attribute(0)
147            .and_then(Value::as_list)
148            .ok_or(AlignmentError::InvalidAttribute {
149                entity: point_ref,
150                index: 0,
151                name: "Coordinates",
152            })?;
153    if coordinates.len() < 2 {
154        return Err(AlignmentError::InvalidAttribute {
155            entity: point_ref,
156            index: 0,
157            name: "Coordinates",
158        });
159    }
160    let x = coordinates[0]
161        .unwrap_typed()
162        .as_f64()
163        .ok_or(AlignmentError::InvalidAttribute {
164            entity: point_ref,
165            index: 0,
166            name: "Coordinates",
167        })?
168        * units.length_to_metres;
169    let y = coordinates[1]
170        .unwrap_typed()
171        .as_f64()
172        .ok_or(AlignmentError::InvalidAttribute {
173            entity: point_ref,
174            index: 0,
175            name: "Coordinates",
176        })?
177        * units.length_to_metres;
178
179    let angle_to_radians = units
180        .angle_to_radians
181        .ok_or(AlignmentError::AngleUnitUndeclared { entity: id })?;
182    let start_direction =
183        required_number(entity, id, START_DIRECTION, "StartDirection")? * angle_to_radians;
184    let start_radius = required_number(entity, id, START_RADIUS, "StartRadiusOfCurvature")?
185        * units.length_to_metres;
186    let end_radius =
187        required_number(entity, id, END_RADIUS, "EndRadiusOfCurvature")? * units.length_to_metres;
188    let segment_length =
189        required_number(entity, id, SEGMENT_LENGTH, "SegmentLength")? * units.length_to_metres;
190    let gravity_center_line_height = optional_number(
191        entity,
192        id,
193        GRAVITY_CENTER_LINE_HEIGHT,
194        "GravityCenterLineHeight",
195    )?
196    .map(|value| value * units.length_to_metres);
197    let source_type = required_enum(entity, id, PREDEFINED_TYPE, "PredefinedType")?;
198    let segment_type = match source_type {
199        "LINE" => HorizontalSegmentType::Line,
200        "CIRCULARARC" => HorizontalSegmentType::CircularArc,
201        "USERDEFINED" => HorizontalSegmentType::UserDefined,
202        "NOTDEFINED" => HorizontalSegmentType::NotDefined,
203        other => HorizontalSegmentType::Transition(other.to_owned()),
204    };
205
206    let values = [
207        x,
208        y,
209        start_direction,
210        start_radius,
211        end_radius,
212        segment_length,
213    ];
214    if values.iter().any(|value| !value.is_finite())
215        || gravity_center_line_height.is_some_and(|value| !value.is_finite())
216        || segment_length < 0.0
217    {
218        return Err(AlignmentError::InvalidSegment {
219            entity: id,
220            detail: "coordinates and parameters must be finite and SegmentLength non-negative",
221        });
222    }
223
224    Ok(HorizontalSegment {
225        entity: id,
226        start_point: Point2::new(x, y),
227        start_direction,
228        start_radius,
229        end_radius,
230        segment_length,
231        gravity_center_line_height,
232        segment_type,
233    })
234}
235
236fn required_ref(
237    entity: &Entity,
238    id: EntityId,
239    index: usize,
240    name: &'static str,
241) -> AlignmentResult<EntityId> {
242    match entity.attribute(index) {
243        None | Some(Value::Null) => Err(AlignmentError::MissingAttribute {
244            entity: id,
245            index,
246            name,
247        }),
248        Some(Value::Ref(reference)) => Ok(*reference),
249        _ => Err(AlignmentError::InvalidAttribute {
250            entity: id,
251            index,
252            name,
253        }),
254    }
255}
256
257fn required_number(
258    entity: &Entity,
259    id: EntityId,
260    index: usize,
261    name: &'static str,
262) -> AlignmentResult<f64> {
263    match entity.attribute(index) {
264        None | Some(Value::Null) => Err(AlignmentError::MissingAttribute {
265            entity: id,
266            index,
267            name,
268        }),
269        Some(value) => value
270            .unwrap_typed()
271            .as_f64()
272            .ok_or(AlignmentError::InvalidAttribute {
273                entity: id,
274                index,
275                name,
276            }),
277    }
278}
279
280fn optional_number(
281    entity: &Entity,
282    id: EntityId,
283    index: usize,
284    name: &'static str,
285) -> AlignmentResult<Option<f64>> {
286    match entity.attribute(index) {
287        None | Some(Value::Null) => Ok(None),
288        Some(value) => {
289            value
290                .unwrap_typed()
291                .as_f64()
292                .map(Some)
293                .ok_or(AlignmentError::InvalidAttribute {
294                    entity: id,
295                    index,
296                    name,
297                })
298        }
299    }
300}
301
302fn required_enum<'a>(
303    entity: &'a Entity,
304    id: EntityId,
305    index: usize,
306    name: &'static str,
307) -> AlignmentResult<&'a str> {
308    match entity.attribute(index) {
309        Some(Value::Enum(value)) => Ok(value),
310        None | Some(Value::Null) => Err(AlignmentError::MissingAttribute {
311            entity: id,
312            index,
313            name,
314        }),
315        _ => Err(AlignmentError::InvalidAttribute {
316            entity: id,
317            index,
318            name,
319        }),
320    }
321}