ifc_lite_geometry/
void_rels.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Void and aggregate relationship folds: the one kernel behind the
6//! production prepass (`ifc_lite_processing::prepass::resolve_prepass`, native
7//! and browser) and the standalone geometry scanners in `void_index`.
8//!
9//! Spans are `(express_id, start, end)` as `EntityScanner::next_entity`
10//! yields them. A span that fails to decode, or a relationship missing either
11//! end, is skipped.
12
13use crate::void_index::{propagate_voids_to_parts, propagate_voids_via_aggregates};
14use ifc_lite_core::{slot, EntityDecoder, EntityScanner};
15use rustc_hash::FxHashMap;
16
17/// Visit `(host, opening)` for each `IfcRelVoidsElement` span, in span order,
18/// once per relationship (no deduplication).
19pub(crate) fn for_each_void_rel(
20    spans: &[(u32, usize, usize)],
21    decoder: &mut EntityDecoder,
22    mut visit: impl FnMut(u32, u32),
23) {
24    for &(id, start, end) in spans {
25        let Ok(rel) = decoder.decode_at_with_id(id, start, end) else {
26            continue;
27        };
28        if let (Some(host), Some(opening)) = (
29            rel.ref_at(slot::IfcRelVoidsElement::RELATING_BUILDING_ELEMENT),
30            rel.ref_at(slot::IfcRelVoidsElement::RELATED_OPENING_ELEMENT),
31        ) {
32            visit(host, opening);
33        }
34    }
35}
36
37/// Fold `IfcRelAggregates` spans into parent โ†’ children, children appended in
38/// span then authored order. `RelatedObjects` is read bare-tolerant
39/// (`DecodedEntity::ref_list_at`): a bare `#id` is a one-element list, and a
40/// relationship with no child references adds nothing.
41pub(crate) fn fold_aggregate_rels(
42    spans: &[(u32, usize, usize)],
43    decoder: &mut EntityDecoder,
44) -> FxHashMap<u32, Vec<u32>> {
45    let mut aggregate_children: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
46    for &(id, start, end) in spans {
47        let Ok(rel) = decoder.decode_at_with_id(id, start, end) else {
48            continue;
49        };
50        let Some(parent) = rel.ref_at(slot::IfcRelAggregates::RELATING_OBJECT) else {
51            continue;
52        };
53        if let Some(children) = rel.ref_list_at(slot::IfcRelAggregates::RELATED_OBJECTS) {
54            aggregate_children
55                .entry(parent)
56                .or_default()
57                .extend(children);
58        }
59    }
60    aggregate_children
61}
62
63/// Canonicalise each host's opening order (#2019). The scan pushes in
64/// statement order, aggregate propagation in hashmap-walk order; neither is a
65/// property of the model. Sequential void cuts are not associative (each pass
66/// snaps f64->f32), so reordering them moves the world geometry hash on a
67/// re-export that only shuffled statements.
68pub(crate) fn canonicalize_void_order(void_index: &mut FxHashMap<u32, Vec<u32>>) {
69    for openings in void_index.values_mut() {
70        openings.sort_unstable();
71    }
72}
73
74/// The production host โ†’ openings index: fold the void relationships,
75/// propagate them through the aggregate tree (#845), then sort each host's
76/// openings (`canonicalize_void_order`). The aggregate spans are decoded only
77/// when there is a void to propagate.
78pub fn resolve_void_index(
79    void_spans: &[(u32, usize, usize)],
80    aggregate_spans: &[(u32, usize, usize)],
81    decoder: &mut EntityDecoder,
82) -> FxHashMap<u32, Vec<u32>> {
83    let mut void_index: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
84    for_each_void_rel(void_spans, decoder, |host, opening| {
85        void_index.entry(host).or_default().push(opening);
86    });
87    if !void_index.is_empty() && !aggregate_spans.is_empty() {
88        let aggregate_children = fold_aggregate_rels(aggregate_spans, decoder);
89        propagate_voids_via_aggregates(&mut void_index, &aggregate_children);
90    }
91    canonicalize_void_order(&mut void_index);
92    void_index
93}
94
95/// [`resolve_void_index`] over a whole file: scan `content` for the void and
96/// aggregate relationships (keyword in any case) and resolve them. For tests,
97/// harnesses and standalone callers that do not run the processing prepass.
98pub fn void_index_from_content<T>(
99    content: &T,
100    decoder: &mut EntityDecoder,
101) -> FxHashMap<u32, Vec<u32>>
102where
103    T: AsRef<[u8]> + ?Sized,
104{
105    let (void_spans, aggregate_spans) = scan_rel_spans(content.as_ref(), true, true);
106    resolve_void_index(&void_spans, &aggregate_spans, decoder)
107}
108
109/// Spans of the `IfcRelVoidsElement` and/or `IfcRelAggregates` records in
110/// `content`, in file order.
111pub(crate) fn scan_rel_spans(
112    content: &[u8],
113    voids: bool,
114    aggregates: bool,
115) -> (Vec<(u32, usize, usize)>, Vec<(u32, usize, usize)>) {
116    let mut scanner = EntityScanner::new(content);
117    let (mut void_spans, mut aggregate_spans) = (Vec::new(), Vec::new());
118    while let Some((id, type_name, start, end)) = scanner.next_entity() {
119        if voids && ifc_lite_core::keyword_eq(type_name, "IFCRELVOIDSELEMENT") {
120            void_spans.push((id, start, end));
121        } else if aggregates && ifc_lite_core::keyword_eq(type_name, "IFCRELAGGREGATES") {
122            aggregate_spans.push((id, start, end));
123        }
124    }
125    (void_spans, aggregate_spans)
126}
127
128#[cfg(test)]
129#[path = "void_rels_tests.rs"]
130mod tests;
131
132/// Compute the set of aggregated `IfcBuildingElementPart` ids to skip when the
133/// "merge multilayer wall as a single solid" toggle is on (issue #540): a part
134/// is skipped when its parent's layered build-up is *sliceable* in the caller's
135/// `material_layer_index` (the browser's per-content or prepass-injected one),
136/// so the parent's merged-layer geometry is drawn instead of the parts. An
137/// index with no sliceable buildup returns the empty set before any scan.
138///
139/// This layer/void **driver** composes the shared kernels
140/// ([`propagate_voids_to_parts`], [`crate::MaterialLayerIndex::is_sliceable`])
141/// next to them (#913 Phase 4 / ยง2.6) for the browser's `merge_layers` path. Its
142/// scratch `void_index` stays EMPTY (only the part โ†’ parent map is wanted);
143/// callers needing propagated voids call [`propagate_voids_to_parts`] themselves.
144#[must_use]
145pub fn compute_parts_to_skip_with_index<T>(
146    content: &T,
147    decoder: &mut EntityDecoder,
148    material_layer_index: &crate::MaterialLayerIndex,
149) -> rustc_hash::FxHashSet<u32>
150where
151    T: AsRef<[u8]> + ?Sized,
152{
153    if material_layer_index.sliceable_count() == 0 {
154        return rustc_hash::FxHashSet::default();
155    }
156    let mut void_index_scratch: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
157    propagate_voids_to_parts(&mut void_index_scratch, content.as_ref(), decoder)
158        .into_iter()
159        .filter(|(_, parent_id)| material_layer_index.is_sliceable(*parent_id))
160        .map(|(part_id, _)| part_id)
161        .collect()
162}