ifc_geometry/lower/halfspace.rs
1//! Half-space lowering: infinite cutting tools for boolean trees.
2//!
3//! # The polarity inversion that silently cuts the wrong half
4//!
5//! IFC and the neutral kernel disagree about what the boundary flag means.
6//!
7//! - `IfcHalfSpaceSolid.AgreementFlag = .T.` means the material lies on the
8//! side the base surface normal points **away from**.
9//! - `axiolid_primitive::HalfSpace.agreement = true` selects the **normal**
10//! side.
11//!
12//! They are opposites. Transcribing the flag straight through produces a
13//! clipping tool that keeps exactly the half it should have removed. Nothing
14//! errors: the boolean still evaluates, the mesh is still watertight, and the
15//! wall simply has the wrong end missing. `flip` below is the whole fix, and
16//! the reason it is a named constant rather than an inline `!`.
17//!
18//! # Why a half space is never a root
19//!
20//! A half space has infinite volume. It is meaningful only as a boolean
21//! operand, and the dispatcher reaches this module only through
22//! `lower_boolean_result_node`. Lowering one as a representation item's root
23//! would hand a consumer a solid it cannot bound, tessellate, or measure.
24//!
25//! # Bounded subtypes
26//!
27//! `IfcBoxedHalfSpace.Enclosure` is a search box only; the IFC specification
28//! explicitly says it does not alter the Boolean result, so dropping that
29//! computational hint preserves geometry exactly. `IfcPolygonalBoundedHalfSpace`
30//! is different: its positioned boundary limits the cutting volume, so it
31//! lowers to a bounded node carrying `Position` and the boundary (see
32//! `boundary`), never widened to an infinite half-space.
33//!
34//! # The prism axis (#515)
35//!
36//! IFC bounds the half space by the boundary's infinite prism along
37//! `Position`'s Z axis, in both directions, whatever the plane's slope: a
38//! sloped roof plane over a vertical prism is the usual gable-wall clip.
39//! That is exactly Axiolid's `SolidOperation::BoundedHalfSpaceAlongZ`
40//! (axiolid-model 0.3.14, axiolid/kernel#321): the kept side of the plane
41//! within the lines through the boundary's region parallel to the
42//! placement's Z, the boundary point `(u, v)` at `placement * (u, v, 0)`
43//! with the frame read whole (its scale, shear and handedness), only the
44//! direction of Z counting. Every `IfcPolygonalBoundedHalfSpace` lowers to
45//! that one node, `Position` carried as written, so there is one path and
46//! nothing here decides an orientation, mirrors a footprint or splits a
47//! prism. Up to ifc-geometry 0.27.2 the clip lowered to
48//! `BoundedHalfSpace`, whose prism runs along the plane NORMAL: a plane
49//! against `Position`'s Z was read from its other side, and an oblique or
50//! rescaled prism lowered to a chain of half spaces for a convex polygon
51//! and was refused otherwise.
52//!
53//! `BoundedHalfSpace` is not emitted for the aligned case either, though it
54//! is the same set there and keeps such graphs on wire format 1.3: both of
55//! Axiolid's compilers compile the new node for every frame (the exact one
56//! certifies it), so a second, frame-dependent lowering would only buy an
57//! older wire label at the cost of the case analysis this module dropped.
58//!
59//! What the kernel refuses of the node it refuses by name when compiled,
60//! never here: a Z lying in the plane (the prism never crosses it), a
61//! degenerate placement, the node as a root or a union's operand (it is
62//! unbounded on its kept side), and in the exact compiler an arc boundary
63//! under an uneven scale (its wall is an elliptic cylinder, which the mesh
64//! compiler cuts). An IFC `Position` is orthonormal, so the frame is scaled,
65//! sheared or mirrored only by a mapped item's operator, whose scaled
66//! instance the exact compiler does not take in any case.
67//!
68//! # The depth (#519)
69//!
70//! The node carries no depth: it is the half space cut by an infinite
71//! prism, and the compilers bound it by the subject they cut
72//! (axiolid-mesh-compile 0.3.27, axiolid/kernel#325). Nothing in this
73//! bridge sizes the cut (ADR 0004).
74
75use axiolid_core::{Plane3, Point3, Vec3};
76use axiolid_model::{GeometryNode, NodeId, SolidOperation};
77use axiolid_primitive::HalfSpace;
78use ifc_model::EntityId;
79
80use crate::error::{GeometryError, GeometryResult};
81use crate::lower::session::LoweringSession;
82use crate::resource::placement::axis_placement_transform;
83use crate::solid::halfspace::{HalfSpaceSolid, PolygonalBoundedHalfSpace};
84use crate::surface::elementary::Plane;
85use crate::transform::Transform;
86
87/// Family label used for memoization.
88const KIND: &str = "half space";
89
90/// IFC's `.T.` is the side the normal points AWAY from; the kernel's `true`
91/// is the normal side. Every conversion goes through this.
92fn flip(ifc_agreement_flag: bool) -> bool {
93 !ifc_agreement_flag
94}
95
96/// Lower an `IfcHalfSpaceSolid` (or the geometry-equivalent boxed subtype).
97pub fn lower_half_space_node(
98 session: &mut LoweringSession<'_>,
99 id: EntityId,
100 frame: Transform,
101) -> GeometryResult<NodeId> {
102 let type_name = session.type_name(id)?;
103 if let Some(node) = session.memoized(id, KIND, frame) {
104 return Ok(node);
105 }
106 session.enter(id, KIND)?;
107 let result = if type_name.eq_ignore_ascii_case("IFCPOLYGONALBOUNDEDHALFSPACE") {
108 build_polygonal(session, id, frame)
109 } else {
110 build(session, id, frame)
111 };
112 session.exit(id);
113 let node = result?;
114 session.memoize(id, KIND, frame, node);
115 Ok(node)
116}
117
118/// `IfcPolygonalBoundedHalfSpace`: half space clipped by an extruded polygon.
119///
120/// `Position` is independent of `BaseSurface`, and the boundary is authored in
121/// that placement's XY plane, its prism along that placement's Z. The node
122/// carries `Position` whole, beside the plane, so the placement is never
123/// folded into the clip plane, which would move the clip (see "The prism
124/// axis" above).
125fn build_polygonal(
126 session: &mut LoweringSession<'_>,
127 id: EntityId,
128 frame: Transform,
129) -> GeometryResult<NodeId> {
130 let entity = session.entity(id, id)?;
131 let view = PolygonalBoundedHalfSpace::new(id, entity);
132 let base = view.base();
133 let type_name = base.type_name().to_string();
134
135 // The infinite half space, exactly as the unbounded case builds it.
136 let plane = plane_of(session, id, &type_name, base.base_surface()?, frame)?;
137 let agreement = flip(base.agreement_flag()?);
138 let position_ref = view.position()?;
139 let boundary = view.polygonal_boundary()?;
140
141 // Position both places the prism and orients the authored boundary
142 // within its own plane. It is carried as written: the kernel reads its
143 // scale, shear and handedness.
144 let position = session.entity(id, position_ref)?;
145 let local = axis_placement_transform(session.model(), position_ref, position)?
146 .to_metres(session.units());
147 let placed = frame.compose(&local);
148
149 let half_space = session.node_for(
150 id,
151 GeometryNode::HalfSpace(HalfSpace {
152 boundary: plane,
153 agreement,
154 }),
155 )?;
156
157 // The 2D boundary is a closed bounded curve, or a line-and-arc contour,
158 // in Position's XY plane. It lowers as a curve or a profile, never a 3D
159 // curve: that is the kernel's contract, and the 3D curve path produced
160 // graphs that lowered but never compiled (#45).
161 let boundary = boundary::lower_boundary_curve(session, id, boundary)?;
162
163 session.node_for(
164 id,
165 GeometryNode::SolidOperation(SolidOperation::BoundedHalfSpaceAlongZ {
166 half_space,
167 boundary,
168 placement: placed.to_geom(),
169 }),
170 )
171}
172
173fn build(
174 session: &mut LoweringSession<'_>,
175 id: EntityId,
176 frame: Transform,
177) -> GeometryResult<NodeId> {
178 let entity = session.entity(id, id)?;
179 let view = HalfSpaceSolid::new(id, entity);
180 let type_name = view.type_name().to_string();
181
182 let surface_ref = view.base_surface()?;
183 let agreement = view.agreement_flag()?;
184
185 let boundary = plane_of(session, id, &type_name, surface_ref, frame)?;
186 let half_space = HalfSpace {
187 boundary,
188 agreement: flip(agreement),
189 };
190 session.node_for(id, GeometryNode::HalfSpace(half_space))
191}
192
193/// Resolve the base surface to a placed plane.
194///
195/// Only `IfcPlane` is accepted. A curved base surface is legal IFC and would
196/// need an exact surface node; reporting it as unsupported names the real gap
197/// instead of silently substituting the tangent plane, which would cut along
198/// the wrong shape.
199fn plane_of(
200 session: &mut LoweringSession<'_>,
201 owner: EntityId,
202 owner_type: &str,
203 surface_ref: EntityId,
204 frame: Transform,
205) -> GeometryResult<Plane3> {
206 let surface = session.entity(owner, surface_ref)?;
207 let surface_type = surface.type_name.to_string();
208 if !surface_type.eq_ignore_ascii_case("IFCPLANE") {
209 return Err(session.unsupported(
210 surface_ref,
211 &surface_type,
212 "half-space base surfaces other than IfcPlane need exact surface nodes",
213 ));
214 }
215
216 let plane = Plane::new(surface_ref, surface);
217 let position_ref = plane.position_ref()?;
218 let position = session.entity(surface_ref, position_ref)?;
219 let local = axis_placement_transform(session.model(), position_ref, position)?
220 .to_metres(session.units());
221 let placed = frame.compose(&local);
222
223 // The placement's origin is a point on the plane. A normal is a covector,
224 // so non-uniform affine scale requires inverse-transpose transformation.
225 let origin = placed.apply([0.0, 0.0, 0.0]);
226 let normal =
227 placed
228 .apply_unit_normal([0.0, 0.0, 1.0])
229 .ok_or_else(|| GeometryError::Degenerate {
230 entity: owner,
231 type_name: owner_type.to_string(),
232 detail: "base plane transform is singular or non-finite".to_string(),
233 })?;
234
235 Ok(Plane3 {
236 origin: Point3::from_array(origin),
237 normal: Vec3::from_array(normal),
238 })
239}
240
241mod boundary;
242
243#[cfg(test)]
244mod tests;