Skip to main content

ifc_model/
model.rs

1//! The entity graph — storage, lookup, and nothing else.
2//!
3//! # What this type deliberately does NOT do
4//!
5//! `Model` has no idea what a cost item, a task, a wall, or a material is. It
6//! stores entities and answers structural questions about them. Every domain
7//! meaning lives in a separate crate that borrows a `&Model` and interprets it.
8//!
9//! That is not a stylistic preference, it is what makes two things possible:
10//!
11//! 1. **Thin builds.** An app that only reads geometry compiles no cost,
12//!    schedule, or structural code, because those crates are optional features
13//!    rather than parts of the model.
14//! 2. **Lossless round-trips of data we do not understand.** Since the model
15//!    stores entities structurally, a cost entity survives parse and re-export
16//!    byte-for-byte in content even when `ifc-cost` is not compiled in. If the
17//!    model instead held a `CostItem` struct, dropping the feature would drop
18//!    the data.
19//!
20//! The rule to preserve: **no `if type_name == "IFCWALL"` in this crate.**
21
22use crate::diagnostic::Diagnostic;
23use crate::entity::Entity;
24use crate::header::Header;
25use crate::value::EntityId;
26use ahash::AHashMap;
27
28/// A parsed IFC file: header, entities, and indices over them.
29#[derive(Debug, Clone, Default)]
30pub struct Model {
31    header: Header,
32    /// Entities keyed by their in-file id, so `#42` survives a round-trip.
33    entities: AHashMap<EntityId, Entity>,
34    /// Insertion order, so a re-export preserves the original file order
35    /// instead of hash order. Diffing two exports is otherwise unreadable.
36    order: Vec<EntityId>,
37    /// Type name to entity ids. Built during insertion because "every
38    /// IfcWall" is the most common query in any consumer.
39    by_type: AHashMap<String, Vec<EntityId>>,
40    max_id: u64,
41    /// Bumped by every structural change. A transaction opened against one
42    /// revision refuses to commit against another, so an editor working from
43    /// a stale view is told rather than silently overwriting.
44    ///
45    /// Not a content hash: two different edit sequences can reach the same
46    /// bytes and still get different revisions. It answers "did anything
47    /// change", which is the question optimistic concurrency asks.
48    revision: u64,
49    /// Non-fatal findings from the read that produced this model. Empty
50    /// unless a codec recovered from damaged input.
51    diagnostics: Vec<Diagnostic>,
52}
53
54impl Model {
55    /// An empty model.
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// The file header (schema declaration, description, author).
61    pub fn header(&self) -> &Header {
62        &self.header
63    }
64
65    /// Mutable access to the header, for writers and editors.
66    pub fn header_mut(&mut self) -> &mut Header {
67        &mut self.header
68    }
69
70    /// Non-fatal problems reported by the codec that read this model.
71    ///
72    /// Empty for a clean file. A non-empty slice means the model is
73    /// incomplete relative to its source: the codec recovered from damage and
74    /// each entry says exactly what was dropped, so a consumer can surface
75    /// "loaded, 1 record skipped" instead of pretending the read was lossless.
76    pub fn diagnostics(&self) -> &[Diagnostic] {
77        &self.diagnostics
78    }
79
80    /// Whether the read that produced this model dropped anything.
81    pub fn is_complete(&self) -> bool {
82        self.diagnostics.is_empty()
83    }
84
85    /// Attaches a codec diagnostic. Called by codecs during a recovered read.
86    pub fn push_diagnostic(&mut self, diagnostic: Diagnostic) {
87        self.diagnostics.push(diagnostic);
88    }
89
90    /// Insert an entity under a specific id, replacing any previous occupant.
91    ///
92    /// Codecs use this to preserve file ids exactly.
93    pub fn insert(&mut self, id: EntityId, entity: Entity) {
94        let key = entity.type_name.to_ascii_uppercase();
95        match self.entities.insert(id, entity) {
96            None => self.order.push(id),
97            // Replacing an occupant: drop its old type-index entry, otherwise
98            // `ids_of_type` reports the id twice for the same type, or keeps
99            // reporting it under a type the entity no longer has. Both make an
100            // edit layer silently wrong.
101            Some(previous) => {
102                let previous_key = previous.type_name.to_ascii_uppercase();
103                if previous_key != key {
104                    if let Some(ids) = self.by_type.get_mut(&previous_key) {
105                        ids.retain(|existing| *existing != id);
106                    }
107                } else {
108                    // Same type: the entry is still correct, so re-adding it
109                    // below would duplicate it.
110                    self.max_id = self.max_id.max(id.0);
111                    self.revision += 1;
112                    return;
113                }
114            }
115        }
116        self.by_type.entry(key).or_default().push(id);
117        self.max_id = self.max_id.max(id.0);
118        self.revision += 1;
119    }
120
121    /// Append an entity, allocating the next free id.
122    pub fn push(&mut self, entity: Entity) -> EntityId {
123        let id = EntityId(self.max_id + 1);
124        self.insert(id, entity);
125        id
126    }
127
128    /// How many structural changes this model has seen.
129    ///
130    /// Starts at zero and increases; the absolute value carries no meaning
131    /// beyond comparison. See [`Transaction`](crate::Transaction).
132    pub fn revision(&self) -> u64 {
133        self.revision
134    }
135
136    /// Record a structural change made through a sibling mutation module.
137    pub(crate) fn bump_revision(&mut self) {
138        self.revision += 1;
139    }
140
141    /// The id [`Model::push`] would allocate next.
142    ///
143    /// A transaction reserves ids from here so several creates in one batch
144    /// cannot collide with each other or with existing entities.
145    pub fn next_id(&self) -> EntityId {
146        EntityId(self.max_id + 1)
147    }
148
149    /// Look up one entity.
150    pub fn get(&self, id: EntityId) -> Option<&Entity> {
151        self.entities.get(&id)
152    }
153
154    /// Number of entities.
155    pub fn len(&self) -> usize {
156        self.entities.len()
157    }
158
159    /// Whether the model holds no entities.
160    pub fn is_empty(&self) -> bool {
161        self.entities.is_empty()
162    }
163
164    /// Entity ids in original file order.
165    pub fn ids(&self) -> impl Iterator<Item = EntityId> + '_ {
166        self.order.iter().copied()
167    }
168
169    /// Entities in original file order.
170    pub fn iter(&self) -> impl Iterator<Item = (EntityId, &Entity)> + '_ {
171        self.order
172            .iter()
173            .filter_map(move |id| self.entities.get(id).map(|e| (*id, e)))
174    }
175
176    /// Ids of every entity with this exact type name, case-insensitive.
177    ///
178    /// This is an exact-type query and does **not** include subtypes: asking
179    /// for `IfcElement` will not return walls. Subtype queries need the schema,
180    /// which this crate does not depend on; `ifc-schema` provides that on top.
181    pub fn ids_of_type(&self, type_name: &str) -> &[EntityId] {
182        self.by_type
183            .get(&type_name.to_ascii_uppercase())
184            .map(|v| v.as_slice())
185            .unwrap_or(&[])
186    }
187
188    /// Entities with this exact type name.
189    pub fn of_type<'a>(&'a self, type_name: &str) -> impl Iterator<Item = (EntityId, &'a Entity)> {
190        self.ids_of_type(type_name)
191            .iter()
192            .filter_map(move |id| self.entities.get(id).map(|e| (*id, e)))
193            .collect::<Vec<_>>()
194            .into_iter()
195    }
196
197    /// Every distinct type name present, with its instance count.
198    ///
199    /// Useful as a cheap file summary and as the basis for a coverage report
200    /// of what a given build can and cannot interpret.
201    pub fn type_histogram(&self) -> Vec<(&str, usize)> {
202        let mut v: Vec<_> = self
203            .by_type
204            .iter()
205            .map(|(k, ids)| (k.as_str(), ids.len()))
206            .collect();
207        v.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
208        v
209    }
210
211    /// Ids that are referenced by some entity but do not exist.
212    ///
213    /// A dangling reference is the most common corruption in real files, and
214    /// it is a structural question, so it belongs here rather than in a
215    /// validation crate.
216    pub fn dangling_references(&self) -> Vec<(EntityId, EntityId)> {
217        let mut out = Vec::new();
218        for (id, entity) in self.iter() {
219            for target in entity.references() {
220                if !self.entities.contains_key(&target) {
221                    out.push((id, target));
222                }
223            }
224        }
225        out
226    }
227
228    // --- crate-internal seams for `mutation::edit` -----------------------
229    //
230    // Kept private-to-crate rather than `pub`: an edit that changes
231    // `type_name` must also fix up `by_type`, or `ids_of_type` silently goes
232    // stale. `mutation::edit` is the only module trusted to touch these
233    // fields directly, and it exists precisely to keep that invariant in one
234    // place instead of copied into every editor.
235
236    pub(crate) fn entities_mut(&mut self) -> &mut AHashMap<EntityId, Entity> {
237        &mut self.entities
238    }
239
240    pub(crate) fn by_type_mut(&mut self) -> &mut AHashMap<String, Vec<EntityId>> {
241        &mut self.by_type
242    }
243
244    pub(crate) fn order_mut(&mut self) -> &mut Vec<EntityId> {
245        &mut self.order
246    }
247}