Skip to main content

ifc_geometry/resource/
axes.rs

1//! `IfcBaseAxis`: deriving an orthonormal frame from optional axis hints.
2//!
3//! A transformation operator names its axes `Axis1`/`Axis2`/`Axis3` instead of
4//! a placement's `RefDirection`/`Axis`, all of them optional, and the schema
5//! function `IfcBaseAxis` says how to turn whichever subset the file supplied
6//! into a full frame. The 2D and 3D cases follow different rules, so they live
7//! here rather than being open-coded per operator subtype.
8//!
9//! # What `Axis2` actually contributes
10//!
11//! Nothing about direction: the derived Y is forced orthogonal to X (and, in
12//! 3D, to Z) whatever `Axis2` says. Its **sign** is all that survives, and
13//! that is precisely how a mirroring operator is expressed. Ignoring it turns
14//! a mirrored component into an unmirrored one, which reads as correct
15//! geometry facing the wrong way -- the worst kind of wrong.
16
17use crate::transform::Transform;
18
19/// The 3D case of `IfcBaseAxis`.
20///
21/// `Axis3` is the frame's Z and `Axis1` its approximate X, which is the
22/// reverse naming of a placement's `Axis`/`RefDirection` but the identical
23/// construction, so the Gram-Schmidt projection is delegated to
24/// [`Transform::from_axes`] rather than repeated.
25///
26/// Returns `None` when the axes are degenerate: zero-length, or `Axis1`
27/// parallel to `Axis3` so that no X survives the projection.
28pub fn base_axes_3d(
29    origin: [f64; 3],
30    axis1: Option<[f64; 3]>,
31    axis2: Option<[f64; 3]>,
32    axis3: Option<[f64; 3]>,
33) -> Option<Transform> {
34    if !origin.iter().all(|component| component.is_finite())
35        || axis2.is_some_and(|axis| !axis_is_finite_nonzero(axis))
36    {
37        return None;
38    }
39    let frame = Transform::from_axes(origin, axis3, axis1)?;
40    Some(match axis2 {
41        Some(a2) if dot(a2, frame.basis[1]) < 0.0 => Transform {
42            basis: [frame.basis[0], negate(frame.basis[1]), frame.basis[2]],
43            origin,
44        },
45        _ => frame,
46    })
47}
48
49/// The 2D case of `IfcBaseAxis`.
50///
51/// Returned as a 3D transform lying in the z=0 plane so consumers never carry
52/// two transform types. Y is the orthogonal complement of X (X turned a
53/// quarter turn counter-clockwise), flipped when `Axis2` opposes it.
54///
55/// When only `Axis2` is given, X is derived *from it* by the reverse quarter
56/// turn, which is why this cannot simply call [`Transform::from_axes`] with a
57/// default X: there is no 3D analogue of that rule.
58pub fn base_axes_2d(
59    origin: [f64; 3],
60    axis1: Option<[f64; 3]>,
61    axis2: Option<[f64; 3]>,
62) -> Option<Transform> {
63    if !origin.iter().all(|component| component.is_finite())
64        || axis2.is_some_and(|axis| !axis_2d_is_finite_nonzero(axis))
65    {
66        return None;
67    }
68    let x = match (axis1, axis2) {
69        (Some(a1), _) => [a1[0], a1[1]],
70        // Axis2 alone: X is Y turned a quarter turn clockwise.
71        (None, Some(a2)) => [a2[1], -a2[0]],
72        (None, None) => [1.0, 0.0],
73    };
74    let x = normalize_2d(x)?;
75    let mut y = [-x[1], x[0]];
76    // Only meaningful when Axis1 fixed X. If Y came from Axis2 it already
77    // agrees with it by construction.
78    if let (Some(_), Some(a2)) = (axis1, axis2) {
79        if a2[0] * y[0] + a2[1] * y[1] < 0.0 {
80            y = [-y[0], -y[1]];
81        }
82    }
83    Some(Transform {
84        basis: [[x[0], x[1], 0.0], [y[0], y[1], 0.0], [0.0, 0.0, 1.0]],
85        origin,
86    })
87}
88
89/// Normalize a 2D vector, or `None` when it is zero or non-finite.
90fn normalize_2d(v: [f64; 2]) -> Option<[f64; 2]> {
91    let scale = v[0].abs().max(v[1].abs());
92    if scale == 0.0 || !scale.is_finite() {
93        return None;
94    }
95    let scaled = [v[0] / scale, v[1] / scale];
96    let length = (scaled[0] * scaled[0] + scaled[1] * scaled[1]).sqrt();
97    Some([scaled[0] / length, scaled[1] / length])
98}
99
100fn axis_is_finite_nonzero(axis: [f64; 3]) -> bool {
101    axis.iter().all(|component| component.is_finite())
102        && axis.iter().any(|component| *component != 0.0)
103}
104
105fn axis_2d_is_finite_nonzero(axis: [f64; 3]) -> bool {
106    axis[0].is_finite()
107        && axis[1].is_finite()
108        && axis[2].is_finite()
109        && (axis[0] != 0.0 || axis[1] != 0.0)
110}
111
112fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
113    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
114}
115
116fn negate(v: [f64; 3]) -> [f64; 3] {
117    [-v[0], -v[1], -v[2]]
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    const O: [f64; 3] = [0.0, 0.0, 0.0];
125
126    fn close(a: [f64; 3], b: [f64; 3]) -> bool {
127        a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9)
128    }
129
130    #[test]
131    fn omitting_every_axis_gives_the_global_frame() {
132        assert_eq!(
133            base_axes_3d(O, None, None, None).unwrap(),
134            Transform::identity()
135        );
136        assert_eq!(base_axes_2d(O, None, None).unwrap(), Transform::identity());
137    }
138
139    #[test]
140    fn axis1_is_the_local_x_and_axis3_the_local_z() {
141        let t = base_axes_3d(O, Some([0.0, 1.0, 0.0]), None, Some([1.0, 0.0, 0.0])).unwrap();
142        assert!(close(t.basis[0], [0.0, 1.0, 0.0]), "X follows Axis1");
143        assert!(close(t.basis[2], [1.0, 0.0, 0.0]), "Z follows Axis3");
144    }
145
146    /// The only information `Axis2` can still carry once Y is forced
147    /// orthogonal is its sign, and that sign is the mirror flag.
148    #[test]
149    fn an_opposing_axis2_flips_handedness_rather_than_being_ignored() {
150        let upright = base_axes_3d(O, Some([1.0, 0.0, 0.0]), Some([0.0, 1.0, 0.0]), None).unwrap();
151        let mirrored =
152            base_axes_3d(O, Some([1.0, 0.0, 0.0]), Some([0.0, -1.0, 0.0]), None).unwrap();
153        assert!(close(upright.basis[1], [0.0, 1.0, 0.0]));
154        assert!(close(mirrored.basis[1], [0.0, -1.0, 0.0]));
155    }
156
157    /// A non-perpendicular `Axis2` still only decides sign; Y stays orthogonal.
158    #[test]
159    fn axis2_never_shears_the_frame() {
160        let t = base_axes_3d(O, Some([1.0, 0.0, 0.0]), Some([0.3, 0.9, 0.0]), None).unwrap();
161        assert!(close(t.basis[1], [0.0, 1.0, 0.0]));
162    }
163
164    #[test]
165    fn two_dimensional_y_is_x_turned_a_quarter_turn_counter_clockwise() {
166        let t = base_axes_2d(O, Some([0.0, 1.0, 0.0]), None).unwrap();
167        assert!(close(t.basis[0], [0.0, 1.0, 0.0]));
168        assert!(close(t.basis[1], [-1.0, 0.0, 0.0]));
169    }
170
171    /// `IfcBaseAxis` derives X from `Axis2` when `Axis1` is absent; defaulting
172    /// X to global X instead would silently rotate the frame.
173    #[test]
174    fn axis2_alone_determines_x_in_two_dimensions() {
175        let t = base_axes_2d(O, None, Some([0.0, 1.0, 0.0])).unwrap();
176        assert!(close(t.basis[0], [1.0, 0.0, 0.0]));
177        assert!(close(t.basis[1], [0.0, 1.0, 0.0]));
178    }
179
180    #[test]
181    fn unnormalized_and_extreme_axes_still_yield_a_unit_frame() {
182        let t = base_axes_2d(O, Some([7.0, 0.0, 0.0]), None).unwrap();
183        assert!(close(t.basis[0], [1.0, 0.0, 0.0]));
184        let huge = base_axes_3d(
185            O,
186            Some([f64::MAX, 0.0, 0.0]),
187            None,
188            Some([0.0, 0.0, f64::MAX]),
189        )
190        .unwrap();
191        assert!(close(huge.basis[0], [1.0, 0.0, 0.0]));
192        assert!(close(huge.basis[2], [0.0, 0.0, 1.0]));
193    }
194
195    #[test]
196    fn zero_length_and_non_finite_axes_are_rejected_before_frame_construction() {
197        assert!(base_axes_2d(O, Some([0.0, 0.0, 0.0]), None).is_none());
198        assert!(base_axes_3d(O, None, None, Some([0.0, 0.0, 0.0])).is_none());
199        assert!(base_axes_3d(O, None, Some([f64::NAN, 1.0, 0.0]), None).is_none());
200        assert!(base_axes_2d(O, None, Some([0.0, 0.0, 1.0])).is_none());
201        assert!(base_axes_3d([f64::INFINITY, 0.0, 0.0], None, None, None).is_none());
202    }
203
204    /// Parallel X and Z leave nothing after the projection.
205    #[test]
206    fn axis1_parallel_to_axis3_is_degenerate() {
207        assert!(base_axes_3d(O, Some([0.0, 0.0, 2.0]), None, Some([0.0, 0.0, 1.0])).is_none());
208    }
209
210    /// A 3D `Axis1` in a 2D operator contributes only its XY part; keeping z
211    /// would tilt a frame that is required to lie in the z=0 plane.
212    #[test]
213    fn two_dimensional_axes_ignore_any_z_component() {
214        let t = base_axes_2d(O, Some([1.0, 0.0, 5.0]), None).unwrap();
215        assert_eq!(t.basis[2], [0.0, 0.0, 1.0]);
216        assert!(close(t.basis[0], [1.0, 0.0, 0.0]));
217    }
218}