Skip to main content

ifc_geometry/compile/
directrix.rs

1//! The directrix of a sweep as a polyline (#661).
2//!
3//! A swept disk (a pipe, a reinforcing bar) or a directrix sweep is described
4//! by [`crate::body_description`] with its directrix by reference and its
5//! `StartParam`/`EndParam` as authored. This is the sibling for a caller that
6//! wants the path as points and says how closely: the directrix is lowered
7//! exactly as the sweep's own lowering lowers it, trimmed to the sweep's
8//! range, and handed to a [`PolylineCompiler`], which chord-samples it within
9//! the caller's [`Tolerance`] and certifies the bound. No code here samples a
10//! curve (ADR 0004).
11//!
12//! # Frames
13//!
14//! The directrix of a swept disk lies in the sweep's item frame. The
15//! directrix of a swept-area sweep lies in the sweep's `Position` frame, which
16//! is placed into the item frame. `frame` places the points from the item
17//! frame: pass [`crate::BodyItem::item_world`] for world coordinates and
18//! [`Transform::identity`] for the item frame. The range is applied to the
19//! curve before it is placed (the `Position` and `frame` as one placement),
20//! because the kernel grows its bound by a placement's stretch and refuses a
21//! trim of a placed curve.
22//!
23//! # A trimmed or relational directrix with a range
24//!
25//! A range on a directrix that is itself a curve relation (an
26//! `IfcTrimmedCurve`, an `IfcIndexedPolyCurve` with `Segments`, an offset
27//! curve) is a trim of a trim, which the kernel compiles. Point and
28//! arc-length selectors on a relation stay refused by the kernel
29//! (axiolid/kernel#432) and surface as `CompilationRefused` naming the sweep.
30//!
31//! # The path is the authored directrix
32//!
33//! An `IfcSweptDiskSolidPolygonal`'s `FilletRadius` is not applied: the
34//! polyline is the authored directrix, with sharp corners.
35
36use axiolid_contracts::ExecutionOptions;
37use axiolid_model::{
38    CurveRelation, GeometryNode, Instance, TrimSelector, TrimmingPreference as KernelPreference,
39};
40use ifc_model::{Entity, EntityId, Model};
41
42use super::{refused, CompiledPolyline, PolylineCompiler, Tolerance};
43use crate::error::GeometryResult;
44use crate::lower::curve::lower_sweep_directrix;
45use crate::lower::swept::directrix_parameter_trims;
46use crate::lower::LoweringSession;
47use crate::resource::placement::axis_placement_transform;
48use crate::slots::Slots;
49use crate::solid::swept::swept_area_slot;
50use crate::solid::swept::{
51    FixedReferenceSweptAreaSolid, SurfaceCurveSweptAreaSolid, SweptDiskSolid,
52};
53use crate::transform::Transform;
54use crate::units::{self, UnitScale};
55
56#[cfg(feature = "compile-reference-backend")]
57use super::default_backend;
58
59/// `sweep`'s directrix as a polyline in `frame`, sampled by `backend` within
60/// `tolerance`.
61///
62/// Accepts `IfcSweptDiskSolid`, `IfcSweptDiskSolidPolygonal`,
63/// `IfcFixedReferenceSweptAreaSolid`,
64/// `IfcDirectrixDerivedReferenceSweptAreaSolid` and
65/// `IfcSurfaceCurveSweptAreaSolid`. `StartParam`/`EndParam` are applied in
66/// the directrix's own parameterisation, as the sweep's lowering applies them;
67/// an `IfcCompositeCurve` directrix is cut structurally. The result's
68/// `curve` is the directrix and its `deviation` the backend's certified bound.
69/// The `FilletRadius` of an `IfcSweptDiskSolidPolygonal` is not applied: the
70/// polyline is the authored directrix, with sharp corners.
71///
72/// The directrix of a swept-area sweep is placed by the sweep's `Position`
73/// (identity when absent) and then by `frame`; a swept disk has no `Position`.
74/// A ranged directrix that is a curve relation is trimmed again by the
75/// kernel.
76///
77/// Refused, each naming the sweep:
78///
79/// - any other entity, as [`GeometryError::Unsupported`](crate::GeometryError);
80/// - an IFC4X3 `IfcLengthMeasure` `StartParam`/`EndParam`, which is a distance
81///   along the directrix, as `Unsupported`;
82/// - one of `StartParam`/`EndParam` without the other, as `Degenerate`;
83/// - a dangling directrix or `Position`, as `MissingEntity`;
84/// - a directrix the backend refuses, as `CompilationRefused`.
85///
86/// # Errors
87///
88/// As above, plus whatever lowering the directrix and unit resolution refuse.
89pub fn compile_sweep_directrix_with<B: PolylineCompiler>(
90    backend: &B,
91    model: &Model,
92    sweep: EntityId,
93    frame: Transform,
94    tolerance: Tolerance,
95) -> GeometryResult<CompiledPolyline> {
96    let scale = units::resolve(model)?;
97    let mut session = LoweringSession::new(model, &scale);
98    let entity = session.entity(sweep, sweep)?;
99    let type_name = entity.type_name.to_ascii_uppercase();
100    let (directrix, start, end, position) = match type_name.as_str() {
101        "IFCSWEPTDISKSOLID" | "IFCSWEPTDISKSOLIDPOLYGONAL" => {
102            let view = SweptDiskSolid::new(sweep, entity);
103            (
104                view.directrix()?,
105                view.start_param(),
106                view.end_param(),
107                Transform::identity(),
108            )
109        }
110        "IFCFIXEDREFERENCESWEPTAREASOLID" | "IFCDIRECTRIXDERIVEDREFERENCESWEPTAREASOLID" => {
111            let view = FixedReferenceSweptAreaSolid::new(sweep, entity);
112            let (start, end) = directrix_parameter_trims(
113                &session,
114                sweep,
115                &type_name,
116                view.start_param()?,
117                view.end_param()?,
118            )?;
119            (
120                view.directrix()?,
121                start,
122                end,
123                sweep_position(&session, sweep, entity, &scale)?,
124            )
125        }
126        "IFCSURFACECURVESWEPTAREASOLID" => {
127            let view = SurfaceCurveSweptAreaSolid::new(sweep, entity);
128            let (start, end) = directrix_parameter_trims(
129                &session,
130                sweep,
131                &type_name,
132                view.start_param()?,
133                view.end_param()?,
134            )?;
135            (
136                view.directrix()?,
137                start,
138                end,
139                sweep_position(&session, sweep, entity, &scale)?,
140            )
141        }
142        _ => {
143            return Err(session.unsupported(sweep, &type_name, "not a sweep along a directrix"));
144        }
145    };
146    Slots::new(sweep, entity).resolve(model, directrix)?;
147
148    let (curve, range) = lower_sweep_directrix(
149        &mut session,
150        sweep,
151        &type_name,
152        directrix,
153        Transform::identity(),
154        start,
155        end,
156    )?;
157    // Trim first, then place: a placed curve cannot be trimmed.
158    let mut node = curve;
159    if let Some((start, end)) = range {
160        node = session.node_for(
161            directrix,
162            GeometryNode::CurveRelation(CurveRelation::Trimmed {
163                basis: node,
164                start: vec![TrimSelector::Parameter(start)],
165                end: vec![TrimSelector::Parameter(end)],
166                sense_agreement: true,
167                preference: KernelPreference::Parameter,
168            }),
169        )?;
170    }
171    let frame = frame.compose(&position);
172    if !frame.is_identity(0.0) {
173        node = session.node_for(
174            directrix,
175            GeometryNode::Instance(Instance {
176                source: node,
177                transform: frame.to_geom(),
178            }),
179        )?;
180    }
181    let lowered = session.finish(node)?;
182    let outcome = backend
183        .compile_polyline(
184            &lowered.graph,
185            lowered.root,
186            &ExecutionOptions::new(tolerance),
187        )
188        .map_err(|error| refused(sweep, error, &lowered.provenance))?;
189    Ok(CompiledPolyline {
190        curve: Some(directrix),
191        closed: outcome.closed,
192        deviation: outcome.deviation,
193        points: outcome.points,
194    })
195}
196
197/// The `Position` of an `IfcSweptAreaSolid`, in metres; the identity when
198/// absent.
199fn sweep_position(
200    session: &LoweringSession<'_>,
201    sweep: EntityId,
202    entity: &Entity,
203    scale: &UnitScale,
204) -> GeometryResult<Transform> {
205    let Some(position_id) = Slots::new(sweep, entity).opt_ref(swept_area_slot::POSITION) else {
206        return Ok(Transform::identity());
207    };
208    let position = session.entity(sweep, position_id)?;
209    Ok(axis_placement_transform(session.model(), position_id, position)?.to_metres(scale))
210}
211
212/// [`compile_sweep_directrix_with`] with [`default_backend`].
213///
214/// # Errors
215///
216/// As [`compile_sweep_directrix_with`].
217#[cfg(feature = "compile-reference-backend")]
218pub fn compile_sweep_directrix(
219    model: &Model,
220    sweep: EntityId,
221    frame: Transform,
222    tolerance: Tolerance,
223) -> GeometryResult<CompiledPolyline> {
224    compile_sweep_directrix_with(&default_backend(), model, sweep, frame, tolerance)
225}