1use 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 pub(crate) new_records: Vec<(u32, String)>,
40 pub(crate) repoint: (u32, usize, String),
44 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 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
108fn 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
147pub(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
168pub(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
196pub 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
199pub(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;