1use crate::ProcessingResult;
16use ifc_lite_geometry::document::{
17 DefinitionHandle, DocumentError, GeometryDocument, OccurrenceHandle,
18};
19use ifc_lite_geometry::Mesh;
20use std::collections::BTreeMap;
21
22#[derive(Debug, Clone, Copy)]
27pub struct RetainedMeshRecord {
28 pub mesh_index: usize,
29 pub definition: DefinitionHandle,
30 pub occurrence: OccurrenceHandle,
31}
32
33#[derive(Debug, Clone, Copy)]
36pub struct RetainedInstanceRecord {
37 pub instance_index: usize,
38 pub mesh_index: usize,
39 pub occurrence: OccurrenceHandle,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum RetainedGeometryLocation {
45 Mesh(usize),
47 Instance(usize),
49}
50
51#[derive(Debug, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum RetainedGeometryErrorCause {
55 Document(DocumentError),
57 MissingTemplate { template_express_id: u32 },
59}
60
61impl std::fmt::Display for RetainedGeometryErrorCause {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 match self {
64 Self::Document(error) => std::fmt::Display::fmt(error, f),
65 Self::MissingTemplate {
66 template_express_id,
67 } => write!(f, "instance template {template_express_id} has no mesh"),
68 }
69 }
70}
71
72impl std::error::Error for RetainedGeometryErrorCause {
73 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
74 match self {
75 Self::Document(error) => Some(error),
76 Self::MissingTemplate { .. } => None,
77 }
78 }
79}
80
81pub struct RetainedGeometryError {
84 pub location: RetainedGeometryLocation,
85 pub source: RetainedGeometryErrorCause,
86 processed: Box<ProcessingResult>,
87}
88
89impl RetainedGeometryError {
90 pub fn into_processing_result(self) -> ProcessingResult {
92 *self.processed
93 }
94}
95
96impl std::fmt::Debug for RetainedGeometryError {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 f.debug_struct("RetainedGeometryError")
99 .field("location", &self.location)
100 .field("source", &self.source)
101 .finish()
102 }
103}
104
105impl std::fmt::Display for RetainedGeometryError {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 write!(
108 f,
109 "{:?} failed retained admission: {}",
110 self.location, self.source
111 )
112 }
113}
114
115impl std::error::Error for RetainedGeometryError {
116 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
117 Some(&self.source)
118 }
119}
120
121pub struct RetainedGeometry {
129 processed: ProcessingResult,
130 document: GeometryDocument,
131 records: Vec<RetainedMeshRecord>,
132 instances: Vec<RetainedInstanceRecord>,
133}
134
135impl RetainedGeometry {
136 pub fn try_from_processing(processed: ProcessingResult) -> Result<Self, RetainedGeometryError> {
143 match admit(&processed) {
144 Ok((document, records, instances)) => Ok(Self {
145 processed,
146 document,
147 records,
148 instances,
149 }),
150 Err((location, source)) => Err(RetainedGeometryError {
151 location,
152 source,
153 processed: Box::new(processed),
154 }),
155 }
156 }
157
158 pub fn processed(&self) -> &ProcessingResult {
160 &self.processed
161 }
162
163 pub fn document(&self) -> &GeometryDocument {
165 &self.document
166 }
167
168 pub fn records(&self) -> &[RetainedMeshRecord] {
171 &self.records
172 }
173
174 pub fn instances(&self) -> &[RetainedInstanceRecord] {
177 &self.instances
178 }
179
180 pub fn into_processing_result(self) -> ProcessingResult {
182 self.processed
183 }
184}
185
186type Admission = (
187 GeometryDocument,
188 Vec<RetainedMeshRecord>,
189 Vec<RetainedInstanceRecord>,
190);
191type AdmissionError = (RetainedGeometryLocation, RetainedGeometryErrorCause);
192
193fn admit(processed: &ProcessingResult) -> Result<Admission, AdmissionError> {
194 let mut document = GeometryDocument::new();
195 let mut records = Vec::with_capacity(processed.meshes.len());
196 let mut templates: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
197 for (mesh_index, source) in processed.meshes.iter().enumerate() {
198 let mut mesh = Mesh::new();
199 mesh.positions = source.positions.clone();
200 mesh.normals = source.normals.clone();
201 mesh.indices = source.indices.clone();
202 let definition = document
203 .add_mesh_definition(source.geometry_item_id.unwrap_or(source.express_id), mesh)
204 .map_err(|source| {
205 (
206 RetainedGeometryLocation::Mesh(mesh_index),
207 RetainedGeometryErrorCause::Document(source),
208 )
209 })?;
210 let [x, y, z] = source.origin;
211 let occurrence = document
212 .add_occurrence(
213 definition,
214 source.express_id,
215 [
216 1.0, 0.0, 0.0, x, 0.0, 1.0, 0.0, y, 0.0, 0.0, 1.0, z, 0.0, 0.0, 0.0, 1.0,
217 ],
218 )
219 .map_err(|source| {
220 (
221 RetainedGeometryLocation::Mesh(mesh_index),
222 RetainedGeometryErrorCause::Document(source),
223 )
224 })?;
225 records.push(RetainedMeshRecord {
226 mesh_index,
227 definition,
228 occurrence,
229 });
230 templates
231 .entry(source.express_id)
232 .or_default()
233 .push(mesh_index);
234 }
235 let instances = admit_instances(processed, &records, &templates, &mut document)?;
236 Ok((document, records, instances))
237}
238
239fn admit_instances(
240 processed: &ProcessingResult,
241 records: &[RetainedMeshRecord],
242 templates: &BTreeMap<u32, Vec<usize>>,
243 document: &mut GeometryDocument,
244) -> Result<Vec<RetainedInstanceRecord>, AdmissionError> {
245 let mut instances = Vec::with_capacity(processed.instances.len());
246 for (instance_index, source) in processed.instances.iter().enumerate() {
247 let location = RetainedGeometryLocation::Instance(instance_index);
248 let mesh_indices = templates.get(&source.template_express_id).ok_or((
249 location,
250 RetainedGeometryErrorCause::MissingTemplate {
251 template_express_id: source.template_express_id,
252 },
253 ))?;
254 for &mesh_index in mesh_indices {
255 let mut transform = source.transform.map(f64::from);
256 let origin = processed.meshes[mesh_index].origin;
257 for row in 0..4 {
261 transform[row * 4 + 3] += transform[row * 4] * origin[0]
262 + transform[row * 4 + 1] * origin[1]
263 + transform[row * 4 + 2] * origin[2];
264 }
265 let occurrence = document
266 .add_occurrence(records[mesh_index].definition, source.express_id, transform)
267 .map_err(|error| (location, RetainedGeometryErrorCause::Document(error)))?;
268 instances.push(RetainedInstanceRecord {
269 instance_index,
270 mesh_index,
271 occurrence,
272 });
273 }
274 }
275 Ok(instances)
276}