ifc_lite_export/plan/
placement.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Placement patch: rewrite a product's `IfcLocalPlacement`
3//! `RelativePlacement` from a caller-supplied 4x4, relative to whatever
4//! `PlacementRelTo` already names — that attribute is never touched, so the
5//! parent relationship the source encoded stays exactly as it was.
6//!
7//! The new `Location`/`Axis`/`RefDirection` are written as fresh
8//! `IfcCartesianPoint`/`IfcDirection` records rather than edited in place,
9//! even when the old ones are unshared: `IfcAxis2Placement3D` is itself
10//! usually unshared but its `Location`/`Axis` sub-records occasionally are
11//! (two placements at the same origin), and this executor has no per-slot
12//! sharing check finer than the placement record itself. Always appending
13//! keeps that case from silently repointing someone else's origin.
14//!
15//! The old chain does not just sit there unreferenced: [`sweep_orphans`]
16//! walks forward from the one edge this patch actually removed
17//! (`RelativePlacement` no longer names the old `IfcAxis2Placement3D`) and
18//! prunes whatever that leaves with no OTHER referrer, cascading into the
19//! old point/directions the same way. It starts from that one known edge,
20//! not from a whole-file walk, so it can only ever remove something THIS
21//! patch orphaned — a record still shared elsewhere keeps a referrer and
22//! stops the walk, and a record that was already unreferenced in the source
23//! is never visited at all.
24
25use std::collections::{HashSet, VecDeque};
26
27use ifc_lite_geometry::math::v3::{cross, dot};
28
29use crate::step_ids::IdAllocator;
30
31use super::attrs::attribute_index;
32use super::index::FileIndex;
33use super::types::PlacementPatch;
34
35#[derive(Debug)]
36pub(crate) struct PlacementWrite {
37    /// New records to append, in order, already STEP-serialized without a
38    /// trailing newline.
39    pub(crate) new_records: Vec<(u32, String)>,
40    /// The existing `IfcLocalPlacement`'s `RelativePlacement` attribute
41    /// index and its new value (a `#ref` to the freshly appended
42    /// `IfcAxis2Placement3D`).
43    pub(crate) repoint: (u32, usize, String),
44    /// Records this patch's OWN redirect leaves with no referrer at all,
45    /// found by [`sweep_orphans`] — the caller drops these from the output.
46    pub(crate) orphaned: HashSet<u32>,
47}
48
49pub(crate) fn resolve_placement(
50    index: &FileIndex,
51    file_schema: &str,
52    object_id: u32,
53    patch: &PlacementPatch,
54    ids: &mut IdAllocator,
55) -> Result<PlacementWrite, String> {
56    let object_type = index.type_of(object_id).unwrap_or_default();
57    let op_idx = attribute_index(file_schema, &object_type, "ObjectPlacement")
58        .ok_or_else(|| format!("{object_type} has no ObjectPlacement attribute in {file_schema}"))?;
59    let placement_id = index
60        .attrs(object_id)
61        .and_then(|a| a.get(op_idx).and_then(|a| a.scalar))
62        .ok_or("object carries no ObjectPlacement reference to patch")?;
63    let placement_type = index.type_of(placement_id).unwrap_or_default();
64    if placement_type == "IFCGRIDPLACEMENT" {
65        return Err("IfcGridPlacement is grid-relative, not a local transform this executor can rewrite".into());
66    }
67    if placement_type == "IFCLINEARPLACEMENT" {
68        return Err("IfcLinearPlacement is curve-relative, not a local transform this executor can rewrite".into());
69    }
70    if placement_type != "IFCLOCALPLACEMENT" {
71        return Err(format!("ObjectPlacement is {placement_type}, not an IfcLocalPlacement"));
72    }
73
74    // Shared when more than one product's OWN ObjectPlacement names this
75    // same IfcLocalPlacement — not counting a child's PlacementRelTo chain,
76    // which is the normal parent/child shape and not what "shared" means
77    // here.
78    let sharing_products: HashSet<u32> = index
79        .referrers(placement_id)
80        .iter()
81        .filter(|&&(referrer, idx)| {
82            let rtype = index.type_of(referrer).unwrap_or_default();
83            attribute_index(file_schema, &rtype, "ObjectPlacement") == Some(idx)
84        })
85        .map(|&(referrer, _)| referrer)
86        .collect();
87    if sharing_products.len() > 1 {
88        return Err(format!(
89            "IfcLocalPlacement #{placement_id} is shared by {} products; refusing rather than moving them together",
90            sharing_products.len()
91        ));
92    }
93
94    let relplacement_idx = attribute_index(file_schema, "IFCLOCALPLACEMENT", "RelativePlacement")
95        .ok_or("IFCLOCALPLACEMENT has no RelativePlacement attribute in this schema")?;
96    let old_axis_placement = index.attrs(placement_id).and_then(|a| a.get(relplacement_idx).and_then(|a| a.scalar));
97
98    let (new_records, a2p_id) = axis_placement_records(&patch.matrix, ids)?;
99
100    let orphaned = match old_axis_placement {
101        Some(old) => sweep_orphans(index, placement_id, old),
102        None => HashSet::new(),
103    };
104
105    Ok(PlacementWrite { new_records, repoint: (placement_id, relplacement_idx, format!("#{a2p_id}")), orphaned })
106}
107
108/// Walk forward from the one edge `from -> to` that a redirect just
109/// removed: if `to` has no OTHER live referrer, it is orphaned by this
110/// patch alone, so it is pruned and the walk continues from ITS own
111/// outgoing references (the old point/directions), each checked the same
112/// way. `IfcProject` is the only protected stop — everything else is judged
113/// purely by whether removing this one edge left it referenced.
114///
115/// "Other live referrer" is counted, not listed: `to`'s distinct referrers,
116/// less those among `from` and what this sweep already removed (each of
117/// which is checked by reading its own references). A `to` whose count has
118/// not been collected yet is treated as still referenced this round.
119fn sweep_orphans(index: &FileIndex, from: u32, to: u32) -> HashSet<u32> {
120    let mut removed = HashSet::new();
121    let mut queue: VecDeque<(u32, u32)> = VecDeque::new();
122    queue.push_back((from, to));
123    while let Some((from, to)) = queue.pop_front() {
124        if removed.contains(&to) {
125            continue;
126        }
127        if index.type_of(to).as_deref() == Some("IFCPROJECT") {
128            continue;
129        }
130        let Some(referrers) = index.referrer_count(to) else { continue };
131        let gone = removed
132            .iter()
133            .copied()
134            .chain((!removed.contains(&from)).then_some(from))
135            .filter(|&r| index.refs_of(r).contains(&to))
136            .count();
137        if referrers <= gone {
138            removed.insert(to);
139            for target in index.refs_of(to) {
140                queue.push_back((to, target));
141            }
142        }
143    }
144    removed
145}
146
147/// Refuse a matrix that cannot become an `IfcAxis2Placement3D`: a
148/// non-finite entry (not a STEP real), or anything beyond a rotation and a
149/// translation. The placement holds only its Z and X axes, so a zero or
150/// parallel pair, a reflection, scale, shear or projective row would be
151/// dropped without a word.
152pub(crate) fn check_matrix(m: &[[f64; 4]; 4]) -> Result<(), String> {
153    if m.iter().flatten().any(|v| !v.is_finite()) {
154        return Err("placement matrix has a non-finite entry".into());
155    }
156    let col = |c: usize| [m[0][c], m[1][c], m[2][c]];
157    let (x, y, z) = (col(0), col(1), col(2));
158    let unit = |v: [f64; 3]| (dot(v, v) - 1.0).abs() <= 1e-6;
159    let orthogonal = dot(x, y).abs() <= 1e-6 && dot(y, z).abs() <= 1e-6 && dot(z, x).abs() <= 1e-6;
160    let right_handed = dot(cross(x, y), z) > 0.0;
161    let affine = (m[3][0].abs() + m[3][1].abs() + m[3][2].abs() + (m[3][3] - 1.0).abs()) <= 1e-9;
162    if !(unit(x) && unit(y) && unit(z) && orthogonal && right_handed && affine) {
163        return Err("placement matrix is not a rotation and a translation".into());
164    }
165    Ok(())
166}
167
168/// A fresh `IfcAxis2Placement3D` for `matrix` (row-major; translation in
169/// the last column, local Z in the third, local X in the first), with its
170/// own point and directions. Returns the records in order and the axis
171/// placement's id. Shared by the placement patch and by
172/// [`super::Disposition::Add`], so there is one reading of the matrix.
173pub(crate) fn axis_placement_records(
174    m: &[[f64; 4]; 4],
175    ids: &mut IdAllocator,
176) -> Result<(Vec<(u32, String)>, u32), String> {
177    check_matrix(m)?;
178    let location = (m[0][3], m[1][3], m[2][3]);
179    let axis = (m[0][2], m[1][2], m[2][2]);
180    let ref_dir = (m[0][0], m[1][0], m[2][0]);
181
182    let cp_id = ids.allocate().ok_or("id space exhausted while writing a placement")?;
183    let axis_id = ids.allocate().ok_or("id space exhausted while writing a placement")?;
184    let refdir_id = ids.allocate().ok_or("id space exhausted while writing a placement")?;
185    let a2p_id = ids.allocate().ok_or("id space exhausted while writing a placement")?;
186
187    let records = vec![
188        (cp_id, format!("#{cp_id}=IFCCARTESIANPOINT(({},{},{}));", fmt(location.0), fmt(location.1), fmt(location.2))),
189        (axis_id, format!("#{axis_id}=IFCDIRECTION(({},{},{}));", fmt(axis.0), fmt(axis.1), fmt(axis.2))),
190        (refdir_id, format!("#{refdir_id}=IFCDIRECTION(({},{},{}));", fmt(ref_dir.0), fmt(ref_dir.1), fmt(ref_dir.2))),
191        (a2p_id, format!("#{a2p_id}=IFCAXIS2PLACEMENT3D(#{cp_id},#{axis_id},#{refdir_id});")),
192    ];
193    Ok((records, a2p_id))
194}
195
196/// The identity 4x4, row-major: no rotation, no translation.
197pub const IDENTITY: [[f64; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
198
199/// A STEP real literal always carries a decimal point (`1.` not `1`).
200pub(crate) fn fmt(v: f64) -> String {
201    let s = format!("{v}");
202    if s.contains('.') { s } else { format!("{s}.") }
203}
204
205#[cfg(test)]
206#[path = "placement_tests.rs"]
207mod tests;