ifc_lite_export/
section_clip.rs1use std::collections::BTreeMap;
5use ifc_lite_core::{slot, EntityDecoder, EntityScanner, IfcType};
6use ifc_lite_geometry::math::v3;
7use ifc_lite_geometry::kernel::arrangement::Tri;
8use ifc_lite_processing::{process, ProcessingRequest, MeshData, MeshFrame};
9#[cfg(test)]
10use ifc_lite_processing::process_geometry;
11use ifc_lite_processing::element::GEOM_CLASS_LAYER_SLICE;
12use serde::{Deserialize, Serialize};
13
14#[path = "section_clip_mesh.rs"]
15mod mesh;
16#[path = "section_clip_parts.rs"]
17mod parts;
18#[path = "section_clip_safety.rs"]
19mod safety;
20
21#[derive(Clone, Debug, Deserialize)]
23pub struct SectionExportPlane {
24 pub normal: [f64; 3],
25 pub offset: f64,
26}
27
28#[derive(Debug, Serialize)]
30pub struct SectionExportPart {
31 pub positions: Vec<f64>,
32 pub indices: Vec<u32>,
33 pub color: [f32; 4],
34 pub closed: bool,
35 #[serde(rename = "faceColors", skip_serializing_if = "Vec::is_empty")]
36 pub face_colors: Vec<[f32; 4]>,
37}
38
39#[derive(Debug, Serialize)]
40#[serde(rename_all = "camelCase")]
41pub struct SectionExportElement {
42 pub express_id: u32,
43 pub parts: Vec<SectionExportPart>,
44}
45
46#[derive(Debug, Default, Serialize)]
48pub struct SectionExportPlan {
49 pub replacements: Vec<SectionExportElement>,
50 pub outside: Vec<u32>,
51}
52
53pub fn plan_section_export(
57 content: &[u8], planes: &[SectionExportPlane], trim: bool,
58) -> Result<SectionExportPlan, String> {
59 if planes.len() > 32 { return Err("section export supports at most 32 planes".into()); }
60 let planes = planes.iter().map(|plane| {
61 let length = v3::norm(plane.normal);
62 if !length.is_finite() || length <= 0.0 || !plane.offset.is_finite() {
63 return Err("section export requires finite, nonzero planes".to_string());
64 }
65 let normalized = SectionExportPlane { normal: plane.normal.map(|v| v / length), offset: plane.offset / length };
66 if !normalized.offset.is_finite() { return Err("section offset overflows during normalization".into()); }
67 Ok(normalized)
68 }).collect::<Result<Vec<_>, String>>()?;
69 if planes.is_empty() { return Ok(SectionExportPlan::default()); }
70 let mut safety = safety::Safety::default();
71 let processed = process(content, &ProcessingRequest::full_pass(), &mut safety);
72 let mut groups = BTreeMap::<u32, Vec<&MeshData>>::new();
73 for part in &processed.meshes {
74 if !matches!(part.geometry_class, 0 | GEOM_CLASS_LAYER_SLICE) {
75 return Err(format!("section export cannot safely crop geometry class {} for #{}", part.geometry_class, part.express_id));
76 }
77 groups.entry(part.express_id).or_default().push(part);
78 }
79 let mut decoder = EntityDecoder::new(content).with_strict_reals();
83 safety.index_attachments(content, &mut decoder)?;
84 let mut scanner = EntityScanner::new(content);
85 let mut unit = 1.0;
86 while let Some((id, name, _, _)) = scanner.next_entity() {
87 let kind = IfcType::from_str(name);
88 if kind == IfcType::IfcProject {
89 unit = ifc_lite_core::try_extract_length_unit_scale(&mut decoder, id)
90 .ok_or("section export cannot resolve project length units")?;
91 }
92 let product_kind = kind.is_subtype_of(IfcType::IfcProduct);
93 if product_kind && [IfcType::IfcOpeningElement, IfcType::IfcAnnotation, IfcType::IfcGrid]
94 .into_iter().any(|base| kind.is_subtype_of(base)) {
95 groups.remove(&id);
96 continue;
97 }
98 if product_kind || ifc_lite_core::has_geometry_by_name(name) {
99 let entity = decoder.decode_by_id(id).map_err(|error| error.to_string())?;
100 if entity.ref_at(slot::IfcProduct::REPRESENTATION).is_some() && !groups.contains_key(&id) {
101 return Err(format!("section export cannot safely crop unmeshed {name} #{id}"));
102 }
103 }
104 }
105 if !unit.is_finite() || unit <= 0.0 { return Err("invalid section export length unit".into()); }
106 let router = ifc_lite_geometry::GeometryRouter::with_scale(unit);
107 let mut plan = SectionExportPlan::default();
108 for (id, parts) in groups {
109 let textured = safety.require_product(id, &mut decoder, &processed.stats)?;
113 let _budget = ifc_lite_geometry::kernel::budget::enter_element();
114 let (clipped, changed) = parts::cut_parts(&parts, processed.frame, &planes, trim)
115 .map_err(|error| format!("section export #{id}, {error}"))?;
116 if clipped.is_empty() { plan.outside.push(id); continue; }
117 if !changed || !trim { continue; }
118 if textured || parts.iter().any(|part| part.texture.is_some() || part.uvs.is_some()) {
119 return Err(format!("section export cannot trim textured product #{id}: texture/UV preservation is unsupported"));
120 }
121 let product = decoder.decode_by_id(id).map_err(|error| error.to_string())?;
122 if product.ifc_type == IfcType::IfcAlignment
125 && ifc_lite_geometry::locate_axis_curve(&product, &mut decoder).is_some() {
126 return Err(format!("section export cannot trim axis-based alignment #{id}: preserving clipped Axis geometry is unsupported; use whole-element mode"));
127 }
128 let placement = router.resolve_scaled_placement_strict(&product, &mut decoder)
129 .map_err(|error| format!("section export cannot resolve placement #{id}: {error}"))?;
130 let inverse = nalgebra::Matrix4::from_column_slice(&placement).try_inverse()
131 .ok_or_else(|| format!("section export refuses singular placement #{id}"))?;
132 let mut replacements = Vec::new();
133 for part in clipped {
134 let closed = mesh::closed(&part.triangles);
135 let mut positions = Vec::with_capacity(part.triangles.len() * 9);
136 let mut indices = Vec::with_capacity(part.triangles.len() * 3);
137 for triangle in part.triangles {
138 for p in triangle {
139 let world = processed.frame.to_world(v3::add(p, part.origin));
140 let local = inverse * nalgebra::Vector4::new(world[0], world[1], world[2], 1.0);
141 positions.extend([local[0] / unit, local[1] / unit, local[2] / unit]);
142 indices.push(indices.len() as u32);
143 }
144 }
145 replacements.push(SectionExportPart { positions, indices, color: part.color, closed, face_colors: part.face_colors });
146 }
147 plan.replacements.push(SectionExportElement { express_id: id, parts: replacements });
148 }
149 Ok(plan)
150}
151
152fn cut_triangles(
153 mut triangles: Vec<Tri>, origin: [f64; 3], frame: MeshFrame, planes: &[SectionExportPlane],
154) -> Result<(Vec<Tri>, bool), String> {
155 let world_origin = frame.to_world(origin);
156 let mut changed = false;
157 for plane in planes {
158 if triangles.is_empty() { break; }
159 let normal = frame.rotate_into_frame(plane.normal);
160 let offset = plane.offset - v3::dot(plane.normal, world_origin);
161 let (mut inside, mut outside) = (false, false);
162 for p in triangles.iter().flatten() {
163 if v3::dot(normal, *p) <= offset { inside = true; } else { outside = true; }
164 }
165 if !outside { continue; }
166 changed = true;
167 if !inside { triangles.clear(); break; }
168 triangles = mesh::cut(&triangles, normal, offset)?;
169 }
170 Ok((triangles, changed))
171}
172
173#[cfg(test)]
174#[path = "section_clip_tests.rs"]
175mod tests;