1use crate::style::{FullIndexedColourMap, GeometryStyleInfo};
25use ifc_lite_core::{DecodedEntity, EntityDecoder};
26use rustc_hash::FxHashMap;
27
28pub type Span = (u32, usize, usize);
30
31#[derive(Debug, Default, Clone)]
33pub struct PrepassSpans {
34 pub styled_items: Vec<Span>,
38 pub indexed_colour_maps: Vec<Span>,
41 pub material_def_reprs: Vec<Span>,
43 pub rel_associates_material: Vec<Span>,
45 pub void_rels: Vec<Span>,
47 pub fills_rels: Vec<Span>,
50 pub aggregate_rels: Vec<Span>,
53}
54
55#[derive(Debug, Clone, Copy)]
57pub struct ResolveOptions {
58 pub collect_indexed_colour_full: bool,
63 pub defer_attached_styles: bool,
69}
70
71impl Default for ResolveOptions {
72 fn default() -> Self {
73 Self {
74 collect_indexed_colour_full: true,
75 defer_attached_styles: false,
76 }
77 }
78}
79
80#[derive(Debug, Default)]
82pub struct ResolvedPrepass {
83 pub geometry_style_index: FxHashMap<u32, GeometryStyleInfo>,
87 pub indexed_colour_index: FxHashMap<u32, [f32; 4]>,
89 pub indexed_colour_full: FxHashMap<u32, FullIndexedColourMap>,
92 pub orphan_styled_items: FxHashMap<u32, [f32; 4]>,
94 pub material_def_reprs: FxHashMap<u32, Vec<u32>>,
96 pub element_to_material: FxHashMap<u32, u32>,
98 pub element_material_colors: FxHashMap<u32, Vec<[f32; 4]>>,
101 pub void_index: FxHashMap<u32, Vec<u32>>,
103 pub filling_by_opening: FxHashMap<u32, u32>,
105 pub deferred_attached_styled_spans: Vec<(usize, usize)>,
108}
109
110pub use crate::prepass_styled::{resolve_styled_items_into, StyleSeeds};
111
112pub fn resolve_prepass(
114 spans: &PrepassSpans,
115 decoder: &mut EntityDecoder,
116 opts: ResolveOptions,
117) -> ResolvedPrepass {
118 resolve_prepass_with_style_seeds(spans, decoder, opts, None)
119}
120
121pub fn resolve_prepass_with_style_seeds(
125 spans: &PrepassSpans,
126 decoder: &mut EntityDecoder,
127 opts: ResolveOptions,
128 style_seeds: Option<StyleSeeds>,
129) -> ResolvedPrepass {
130 let mut out = ResolvedPrepass::default();
131
132 if let Some((orphan, geom)) = style_seeds {
133 out.orphan_styled_items = orphan;
134 out.geometry_style_index = geom;
135 }
136 resolve_styled_items_into(
138 &spans.styled_items,
139 decoder,
140 opts.defer_attached_styles,
141 &mut out.orphan_styled_items,
142 &mut out.geometry_style_index,
143 &mut out.deferred_attached_styled_spans,
144 );
145
146 for &(id, start, end) in &spans.indexed_colour_maps {
148 let Ok(icm) = decoder.decode_at_with_id(id, start, end) else {
149 continue;
150 };
151 let Some(full) = crate::style::resolve_indexed_colour_map_full(&icm, decoder) else {
152 continue;
153 };
154 let geometry_id = full.geometry_id;
155 out.indexed_colour_index
156 .entry(geometry_id)
157 .or_insert(full.dominant().to_array());
158 if opts.collect_indexed_colour_full {
159 out.indexed_colour_full.entry(geometry_id).or_insert(full);
160 }
161 }
162
163 for &(id, start, end) in &spans.material_def_reprs {
165 if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
166 if let Some(material_id) = entity.get_ref(3) {
168 if let Some(reprs) = refs_from_list(&entity, 2) {
169 out.material_def_reprs
170 .entry(material_id)
171 .or_default()
172 .extend(reprs);
173 }
174 }
175 }
176 }
177 for &(id, start, end) in &spans.rel_associates_material {
178 if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
179 if let Some(material_select_id) = entity.get_ref(5) {
181 if let Some(related) = refs_from_list(&entity, 4) {
182 for element_id in related {
183 out.element_to_material.insert(element_id, material_select_id);
184 }
185 }
186 }
187 }
188 }
189
190 for &(id, start, end) in &spans.void_rels {
192 if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
193 if let (Some(host), Some(opening)) = (entity.get_ref(4), entity.get_ref(5)) {
194 out.void_index.entry(host).or_default().push(opening);
195 }
196 }
197 }
198 for &(id, start, end) in &spans.fills_rels {
199 if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
200 if let (Some(opening_id), Some(filling_id)) = (entity.get_ref(4), entity.get_ref(5)) {
202 out.filling_by_opening.insert(opening_id, filling_id);
203 }
204 }
205 }
206 if !out.void_index.is_empty() && !spans.aggregate_rels.is_empty() {
207 let mut aggregate_children: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
208 for &(id, start, end) in &spans.aggregate_rels {
209 if let Ok(entity) = decoder.decode_at_with_id(id, start, end) {
210 let Some(parent_id) = entity.get_ref(4) else {
211 continue;
212 };
213 if let Some(children) = refs_from_list(&entity, 5) {
214 aggregate_children
215 .entry(parent_id)
216 .or_default()
217 .extend(children);
218 }
219 }
220 }
221 ifc_lite_geometry::propagate_voids_via_aggregates(
222 &mut out.void_index,
223 &aggregate_children,
224 );
225 }
226
227 out.element_material_colors = crate::style::build_element_material_colors(
229 &out.material_def_reprs,
230 &out.orphan_styled_items,
231 &out.element_to_material,
232 decoder,
233 );
234
235 out
236}
237
238pub fn resolve_styled_item_spans(
242 spans: &[(usize, usize)],
243 decoder: &mut EntityDecoder,
244) -> FxHashMap<u32, GeometryStyleInfo> {
245 let mut styles: FxHashMap<u32, GeometryStyleInfo> = FxHashMap::default();
246 for &(start, end) in spans {
247 if let Ok(styled_item) = decoder.decode_at(start, end) {
248 if styled_item.get_ref(0).is_some() {
249 collect_geometry_style_info(&mut styles, &styled_item, decoder);
250 }
251 }
252 }
253 styles
254}
255
256pub fn merge_indexed_colours(
261 geometry_styles: &mut FxHashMap<u32, GeometryStyleInfo>,
262 indexed_colours: &FxHashMap<u32, [f32; 4]>,
263) {
264 for (&geometry_id, &color) in indexed_colours {
265 geometry_styles
266 .entry(geometry_id)
267 .or_insert_with(|| GeometryStyleInfo::from_color(color));
268 }
269}
270
271#[derive(Debug, Clone, Copy)]
273pub struct UnitScales {
274 pub length_unit_scale: f64,
276 pub plane_angle_to_radians: f64,
278 pub project_id: Option<u32>,
280}
281
282impl Default for UnitScales {
283 fn default() -> Self {
284 Self {
285 length_unit_scale: 1.0,
286 plane_angle_to_radians: 1.0,
287 project_id: None,
288 }
289 }
290}
291
292pub fn resolve_unit_scales(
308 content: &[u8],
309 project_id_hint: Option<u32>,
310 decoder: &mut EntityDecoder,
311) -> UnitScales {
312 let project_id = project_id_hint.or_else(|| find_ifcproject_id(content));
313 let Some(pid) = project_id else {
314 return UnitScales::default();
315 };
316
317 let length = ifc_lite_core::try_extract_length_unit_scale(decoder, pid);
322 let angle = ifc_lite_core::try_extract_plane_angle_to_radians(decoder, pid);
323
324 if let (Some(length_unit_scale), Some(plane_angle_to_radians)) = (length, angle) {
325 return UnitScales {
326 length_unit_scale,
327 plane_angle_to_radians,
328 project_id,
329 };
330 }
331
332 let full_index = ifc_lite_core::build_entity_index(content);
334 let mut full_decoder = EntityDecoder::with_index(content, full_index);
335 UnitScales {
336 length_unit_scale: length.or_else(|| {
337 ifc_lite_core::extract_length_unit_scale(&mut full_decoder, pid).ok()
338 })
339 .unwrap_or(1.0),
340 plane_angle_to_radians: angle
341 .or_else(|| {
342 ifc_lite_core::extract_plane_angle_to_radians(&mut full_decoder, pid).ok()
343 })
344 .unwrap_or(1.0),
345 project_id,
346 }
347}
348
349pub fn find_ifcproject_id(content: &[u8]) -> Option<u32> {
352 let mut from = 0usize;
353 while let Some(rel) = memchr::memmem::find(&content[from..], b"IFCPROJECT(") {
361 let kw = from + rel;
362 let mut i = kw;
364 while i > 0 && content[i - 1].is_ascii_whitespace() {
365 i -= 1;
366 }
367 if i > 0 && content[i - 1] == b'=' {
368 i -= 1; while i > 0 && content[i - 1].is_ascii_whitespace() {
371 i -= 1;
372 }
373 let digits_end = i;
375 while i > 0 && content[i - 1].is_ascii_digit() {
376 i -= 1;
377 }
378 if i > 0 && content[i - 1] == b'#' && i < digits_end {
379 let mut id: u32 = 0;
380 for &b in &content[i..digits_end] {
381 id = id.wrapping_mul(10).wrapping_add((b - b'0') as u32);
382 }
383 return Some(id);
384 }
385 }
386 from = kw + 1;
389 }
390 None
391}
392
393pub fn flat_styles_rgba8(resolved: &ResolvedPrepass, decoder: &mut EntityDecoder) -> (Vec<u32>, Vec<u8>) {
399 let mut merged: FxHashMap<u32, [f32; 4]> = resolved
400 .geometry_style_index
401 .iter()
402 .map(|(&id, info)| (id, info.color))
403 .collect();
404 for (&geometry_id, &color) in &resolved.indexed_colour_index {
405 merged.entry(geometry_id).or_insert(color);
406 }
407 let material_styles = crate::style::build_material_style_index(
410 &resolved.material_def_reprs,
411 &resolved.orphan_styled_items,
412 decoder,
413 );
414 for (&mat_id, &color) in crate::style::flatten_material_color_index(&material_styles).iter() {
415 merged.entry(mat_id).or_insert(color);
416 }
417 for (&element_id, colors) in &resolved.element_material_colors {
418 if let Some(&color) = colors.first() {
419 merged.entry(element_id).or_insert(color);
420 }
421 }
422
423 let mut entries: Vec<(u32, [f32; 4])> = merged.into_iter().collect();
427 entries.sort_unstable_by_key(|&(id, _)| id);
428 let mut ids: Vec<u32> = Vec::with_capacity(entries.len());
429 let mut rgba: Vec<u8> = Vec::with_capacity(entries.len() * 4);
430 for (id, color) in entries {
431 ids.push(id);
432 rgba.extend_from_slice(&crate::style::Rgba::from_array(color).to_rgba8());
433 }
434 (ids, rgba)
435}
436
437pub fn flat_voids(void_index: &FxHashMap<u32, Vec<u32>>) -> (Vec<u32>, Vec<u32>, Vec<u32>) {
447 let mut hosts: Vec<(&u32, &Vec<u32>)> = void_index.iter().collect();
448 hosts.sort_unstable_by_key(|&(&host_id, _)| host_id);
449 let mut keys: Vec<u32> = Vec::with_capacity(hosts.len());
450 let mut counts: Vec<u32> = Vec::with_capacity(hosts.len());
451 let mut values: Vec<u32> = Vec::new();
452 for (&host_id, openings) in hosts {
453 keys.push(host_id);
454 counts.push(openings.len() as u32);
455 values.extend(openings.iter().copied());
456 }
457 (keys, counts, values)
458}
459
460pub fn flat_material_colors(
469 element_material_colors: &FxHashMap<u32, Vec<[f32; 4]>>,
470) -> (Vec<u32>, Vec<u32>, Vec<u8>) {
471 let mut elements: Vec<(&u32, &Vec<[f32; 4]>)> = element_material_colors.iter().collect();
472 elements.sort_unstable_by_key(|&(&element_id, _)| element_id);
473 let mut ids: Vec<u32> = Vec::with_capacity(elements.len());
474 let mut counts: Vec<u32> = Vec::with_capacity(elements.len());
475 let mut rgba: Vec<u8> = Vec::new();
476 for (&element_id, colors) in elements {
477 if colors.is_empty() {
478 continue;
479 }
480 ids.push(element_id);
481 counts.push(colors.len() as u32);
482 for &c in colors {
483 rgba.extend_from_slice(&crate::style::Rgba::from_array(c).to_rgba8());
484 }
485 }
486 (ids, counts, rgba)
487}
488
489pub fn material_colors_from_flat(
492 element_ids: &[u32],
493 counts: &[u32],
494 rgba: &[u8],
495) -> FxHashMap<u32, Vec<[f32; 4]>> {
496 let mut out: FxHashMap<u32, Vec<[f32; 4]>> = FxHashMap::default();
497 let mut offset = 0usize;
498 for (i, &element_id) in element_ids.iter().enumerate() {
499 let Some(&count) = counts.get(i) else { break };
500 let count = count as usize;
501 let mut colors: Vec<[f32; 4]> = Vec::with_capacity(count);
502 for c in 0..count {
503 let base = (offset + c) * 4;
504 if base + 3 >= rgba.len() {
505 break;
506 }
507 colors.push(
508 crate::style::Rgba::from_rgba8([
509 rgba[base],
510 rgba[base + 1],
511 rgba[base + 2],
512 rgba[base + 3],
513 ])
514 .to_array(),
515 );
516 }
517 offset += count;
518 if !colors.is_empty() {
519 out.insert(element_id, colors);
520 }
521 }
522 out
523}
524
525pub(crate) fn collect_geometry_style_info(
530 geometry_styles: &mut FxHashMap<u32, GeometryStyleInfo>,
531 styled_item: &DecodedEntity,
532 decoder: &mut EntityDecoder,
533) {
534 let Some(geometry_id) = styled_item.get_ref(0) else {
535 return;
536 };
537 if geometry_styles.contains_key(&geometry_id) {
538 return;
539 }
540 if let Some(style_info) = extract_style_info_from_styled_item(styled_item, decoder) {
541 geometry_styles.insert(geometry_id, style_info);
542 }
543}
544
545pub(crate) fn extract_style_info_from_styled_item(
548 styled_item: &DecodedEntity,
549 decoder: &mut EntityDecoder,
550) -> Option<GeometryStyleInfo> {
551 let style_refs = refs_from_list(styled_item, 1)?;
552
553 for style_id in style_refs {
554 if let Ok(style) = decoder.decode_by_id(style_id) {
555 if let Some(inner_refs) = refs_from_list(&style, 0) {
557 for inner_id in inner_refs {
558 if let Some(info) = extract_surface_style_info(inner_id, decoder) {
559 return Some(info);
560 }
561 }
562 }
563
564 if let Some(info) = extract_surface_style_info(style_id, decoder) {
566 return Some(info);
567 }
568 }
569 }
570
571 None
572}
573
574fn extract_surface_style_info(
579 style_id: u32,
580 decoder: &mut EntityDecoder,
581) -> Option<GeometryStyleInfo> {
582 let style = decoder.decode_by_id(style_id).ok()?;
583 let material_name = normalize_style_name(style.get_string(0));
584 let (color, shading_color) = crate::style::extract_surface_style_colors(style_id, decoder)?;
585 Some(GeometryStyleInfo {
586 color,
587 shading_color,
588 material_name,
589 })
590}
591
592fn normalize_style_name(raw: Option<&str>) -> Option<String> {
593 let name = raw?.trim();
594 if name.is_empty() || name == "$" {
595 return None;
596 }
597 if name.eq_ignore_ascii_case("<unnamed>") || name.eq_ignore_ascii_case("unnamed") {
598 return None;
599 }
600 Some(name.to_string())
601}
602
603fn refs_from_list(entity: &DecodedEntity, index: usize) -> Option<Vec<u32>> {
605 let list = entity.get_list(index)?;
606 let refs: Vec<u32> = list.iter().filter_map(|v| v.as_entity_ref()).collect();
607 if refs.is_empty() {
608 None
609 } else {
610 Some(refs)
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617 use ifc_lite_core::{EntityIndex, EntityScanner};
618
619 #[test]
620 fn find_ifcproject_id_late_in_file() {
621 let ifc = b"ISO-10303-21;\nDATA;\n#1=IFCWALL('x',$,$,$,$,$,$,$,$);\n#999123=IFCPROJECT('g',$,'P',$,$,$,$,$,$);\nENDSEC;\n";
622 assert_eq!(find_ifcproject_id(ifc), Some(999123));
623 }
624
625 #[test]
626 fn find_ifcproject_id_absent() {
627 let ifc = b"ISO-10303-21;\nDATA;\n#1=IFCWALL('x',$,$,$,$,$,$,$,$);\nENDSEC;\n";
628 assert_eq!(find_ifcproject_id(ifc), None);
629 }
630
631 #[test]
632 fn find_ifcproject_id_skips_string_decoys() {
633 let ifc = b"DATA;\n#5=IFCWALL('decoy =IFCPROJECT( in a name',$);\n#7=IFCPROJECT('g',$);\n";
634 assert_eq!(find_ifcproject_id(ifc), Some(7));
635 }
636
637 #[test]
638 fn find_ifcproject_id_handles_whitespace_around_equals() {
639 let space_after = b"DATA;\n#1=IFCWALL('x',$);\n#1593796= IFCPROJECT('g',$,'P',$,$,$,$,$,$);\n";
643 assert_eq!(find_ifcproject_id(space_after), Some(1593796));
644
645 let space_both = b"DATA;\n#42 = IFCPROJECT('g',$);\n";
646 assert_eq!(find_ifcproject_id(space_both), Some(42));
647
648 let crs_only = b"DATA;\n#9= IFCPROJECTEDCRS('EPSG:32632',$,'WGS84',$,'UTM','32N',$);\n";
650 assert_eq!(find_ifcproject_id(crs_only), None);
651 }
652
653 #[test]
660 fn resolve_unit_scales_recovers_degrees_when_measure_past_partial_index() {
661 const IFC: &[u8] = br#"ISO-10303-21;
662HEADER;
663FILE_DESCRIPTION((''),'2;1');
664FILE_NAME('u.ifc','2026-06-26T00:00:00',(''),(''),'','','');
665FILE_SCHEMA(('IFC2X3'));
666ENDSEC;
667DATA;
668#10= IFCPROJECT('g',$,'P',$,$,$,$,$,#11);
669#11= IFCUNITASSIGNMENT((#12,#13));
670#12= IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);
671#13= IFCCONVERSIONBASEDUNIT(#14,.PLANEANGLEUNIT.,'DEGREE',#15);
672#14= IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0);
673#16= IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);
674#15= IFCMEASUREWITHUNIT(IFCRATIOMEASURE(0.0174532925199433),#16);
675ENDSEC;
676END-ISO-10303-21;
677"#;
678 let mut partial = EntityIndex::default();
681 let mut scanner = EntityScanner::new(&IFC);
682 while let Some((id, _t, start, end)) = scanner.next_entity() {
683 if id == 15 || id == 14 {
684 continue; }
686 partial.insert(id, (start, end));
687 }
688 let mut decoder = EntityDecoder::with_index(IFC, partial);
689 let scales = resolve_unit_scales(IFC, Some(10), &mut decoder);
690 assert_eq!(scales.project_id, Some(10));
691 assert!((scales.length_unit_scale - 0.001).abs() < 1e-12);
692 assert!(
693 (scales.plane_angle_to_radians - 0.0174532925199433).abs() < 1e-12,
694 "expected degrees via full-index retry, got {}",
695 scales.plane_angle_to_radians
696 );
697 }
698
699 #[test]
700 fn material_colors_flat_round_trip() {
701 let mut map: FxHashMap<u32, Vec<[f32; 4]>> = FxHashMap::default();
702 map.insert(10, vec![[0.5, 0.5, 0.5, 1.0], [0.7, 0.9, 0.5, 0.2]]);
703 map.insert(42, vec![[1.0, 0.0, 0.0, 1.0]]);
704
705 let (ids, counts, rgba) = flat_material_colors(&map);
706 let back = material_colors_from_flat(&ids, &counts, &rgba);
707
708 assert_eq!(back.len(), 2);
709 assert_eq!(back[&42].len(), 1);
710 assert_eq!(back[&10].len(), 2);
711 for (orig, round) in map[&10].iter().zip(back[&10].iter()) {
713 for (a, b) in orig.iter().zip(round.iter()) {
714 assert!((a - b).abs() <= 1.0 / 255.0 + 1e-6);
715 }
716 }
717 }
718
719 #[test]
723 fn flat_wire_arrays_are_sorted_by_id() {
724 let mut voids: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
725 voids.insert(300, vec![301, 302]);
726 voids.insert(7, vec![8]);
727 voids.insert(90, vec![91]);
728 let (keys, counts, values) = flat_voids(&voids);
729 assert_eq!(keys, vec![7, 90, 300]);
730 assert_eq!(counts, vec![1, 1, 2]);
731 assert_eq!(values, vec![8, 91, 301, 302]);
733
734 let mut colors: FxHashMap<u32, Vec<[f32; 4]>> = FxHashMap::default();
735 colors.insert(42, vec![[1.0, 0.0, 0.0, 1.0]]);
736 colors.insert(10, vec![[0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.5]]);
737 let (ids, counts, rgba) = flat_material_colors(&colors);
738 assert_eq!(ids, vec![10, 42]);
739 assert_eq!(counts, vec![2, 1]);
740 assert_eq!(rgba.len(), 12);
741 assert_eq!(&rgba[0..4], &[0, 255, 0, 255]);
743 }
744
745 #[test]
746 fn resolve_unit_scales_resolves_degrees_and_millimetres() {
747 const IFC: &[u8] = br#"ISO-10303-21;
748HEADER;
749FILE_DESCRIPTION((''),'2;1');
750FILE_NAME('u.ifc','2026-06-12T00:00:00',(''),(''),'','','');
751FILE_SCHEMA(('IFC4'));
752ENDSEC;
753DATA;
754#1=IFCWALL('w',$,$,$,$,$,$,$,$);
755#10=IFCPROJECT('g',$,'P',$,$,$,$,$,#11);
756#11=IFCUNITASSIGNMENT((#12,#13));
757#12=IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.);
758#13=IFCCONVERSIONBASEDUNIT(#14,.PLANEANGLEUNIT.,'DEGREE',#15);
759#14=IFCDIMENSIONALEXPONENTS(0,0,0,0,0,0,0);
760#15=IFCMEASUREWITHUNIT(IFCPLANEANGLEMEASURE(0.017453292519943295),#16);
761#16=IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.);
762ENDSEC;
763END-ISO-10303-21;
764"#;
765 let mut decoder = EntityDecoder::new(IFC);
767 let scales = resolve_unit_scales(IFC, None, &mut decoder);
768 assert_eq!(scales.project_id, Some(10));
769 assert!((scales.length_unit_scale - 0.001).abs() < 1e-12);
770 assert!((scales.plane_angle_to_radians - 0.017_453_292_519_943_295).abs() < 1e-12);
771 }
772}