ifc_lite_processing/types/mesh.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//! Mesh data types for serialization.
6
7use ifc_lite_geometry::InstanceMeta;
8use serde::{Deserialize, Serialize};
9use std::collections::BTreeMap;
10
11/// A surface texture attached to a mesh (issues #961, #1781). Exactly one of
12/// `rgba` / `url` is set:
13/// - `rgba`: decoded in Rust (`IfcBlobTexture` PNG / `IfcPixelTexture` raw);
14/// the browser only uploads it to a GPU texture — no image logic in TS.
15/// - `url`: an `IfcImageTexture` reference (#1781) the HOST layer resolves —
16/// typically a sibling image file inside the `.ifcZIP` container. Real files
17/// share one multi-megapixel image across dozens of face sets, so the
18/// pipeline ships the reference, never per-mesh pixels.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct MeshTextureData {
21 /// Express id of the source `IfcSurfaceTexture` — the stable dedup key:
22 /// every mesh sampling the same image carries the same id, so consumers
23 /// create ONE GPU texture per id, not one per mesh. 0 in legacy payloads.
24 #[serde(default)]
25 pub texture_id: u32,
26 /// `width * height * 4` bytes, row-major, top-down, straight alpha.
27 /// `Arc`-shared across meshes; `None` for an external image reference.
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 pub rgba: Option<std::sync::Arc<Vec<u8>>>,
30 #[serde(default)]
31 pub width: u32,
32 #[serde(default)]
33 pub height: u32,
34 /// `IfcImageTexture.URLReference` verbatim (#1781); `None` for decoded.
35 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub url: Option<String>,
37 /// Sampler wrap from `IfcSurfaceTexture.RepeatS/RepeatT`.
38 pub repeat_s: bool,
39 pub repeat_t: bool,
40}
41
42impl MeshTextureData {
43 /// Build from the geometry crate's per-face-set attachment.
44 pub fn from_attachment(att: &ifc_lite_geometry::TextureAttachment) -> Self {
45 match &att.source {
46 ifc_lite_geometry::TextureSource::Decoded(tex) => Self {
47 texture_id: att.texture_id,
48 rgba: Some(tex.rgba.clone()),
49 width: tex.width,
50 height: tex.height,
51 url: None,
52 repeat_s: tex.repeat_s,
53 repeat_t: tex.repeat_t,
54 },
55 ifc_lite_geometry::TextureSource::Image(img) => Self {
56 texture_id: att.texture_id,
57 rgba: None,
58 width: 0,
59 height: 0,
60 url: Some(img.url.clone()),
61 repeat_s: img.repeat_s,
62 repeat_t: img.repeat_t,
63 },
64 }
65 }
66}
67
68/// Individual mesh data with geometry and metadata.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70pub struct MeshData {
71 /// Express ID of the IFC element.
72 pub express_id: u32,
73 /// IFC type name (e.g., "IfcWall").
74 pub ifc_type: String,
75 /// IFC GlobalId (Root attribute #0) when available.
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub global_id: Option<String>,
78 /// IFC Name (Root/Object attribute #2) when available.
79 #[serde(skip_serializing_if = "Option::is_none")]
80 pub name: Option<String>,
81 /// IFC presentation layer assignment name when available.
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub presentation_layer: Option<String>,
84 /// Vertex positions (x, y, z triplets).
85 pub positions: Vec<f32>,
86 /// Vertex normals (x, y, z triplets).
87 pub normals: Vec<f32>,
88 /// Triangle indices.
89 pub indices: Vec<u32>,
90 /// RGBA color [r, g, b, a] in 0-1 range.
91 pub color: [f32; 4],
92 /// Optional material/style name resolved from per-item IFC styling.
93 #[serde(skip_serializing_if = "Option::is_none")]
94 pub material_name: Option<String>,
95 /// The `IfcRepresentationItem` this mesh was tessellated from.
96 ///
97 /// ALWAYS a representation item, and never a material — a host can follow
98 /// it to source and land on the entity that produced the geometry. Before
99 /// #3199 this field also carried the `IfcMaterial` id for material-layered
100 /// walls and slabs, so following it landed on the wrong entity with nothing
101 /// to warn the caller.
102 ///
103 /// `None` where the identity is genuinely merged away: the single-mesh
104 /// fallback and the cached `IfcMappedItem` path. A boolean result reports
105 /// the `IfcBooleanResult` id, which is a real entity. GPU-instanced
106 /// occurrences used to be `None` here too; they now carry the id through
107 /// [`RawInstanceOccurrence::geometry_item_id`] and the IFNS wire format.
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub geometry_item_id: Option<u32>,
110 /// The `IfcMaterial` whose layer this mesh is a slice of.
111 ///
112 /// ALWAYS a material, and never a representation item. Set only on the
113 /// material-layer path (`router/layers.rs`), and DISJOINT from
114 /// [`Self::geometry_item_id`] — never both, so a consumer that ignores the
115 /// distinction still cannot read one as the other (#3199).
116 #[serde(skip_serializing_if = "Option::is_none")]
117 pub material_id: Option<u32>,
118 /// Optional IFC property set values keyed by IFC property names.
119 /// Primarily attached for IfcSpace/IfcZone so downstream tools can build room attribute UIs.
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub properties: Option<BTreeMap<String, String>>,
122 /// Per-vertex texture coordinates (u, v pairs, 1:1 with `positions`),
123 /// present only for textured meshes (issue #961).
124 #[serde(skip_serializing_if = "Option::is_none")]
125 pub uvs: Option<Vec<f32>>,
126 /// Decoded surface texture, present only for textured meshes (#961).
127 #[serde(skip_serializing_if = "Option::is_none")]
128 pub texture: Option<MeshTextureData>,
129 /// Provenance of the geometry for the viewer's Model/Types switch (#957):
130 /// 0 = ordinary occurrence, 1 = orphan type-product RepresentationMap (no
131 /// occurrence instantiates it), 2 = instanced type-product map (the type
132 /// library shape; its occurrences already draw the real geometry).
133 /// Serde-default so existing JSON payloads and disk caches stay readable;
134 /// skipped when 0 so ordinary meshes serialize byte-identically.
135 #[serde(default, skip_serializing_if = "geometry_class_is_occurrence")]
136 pub geometry_class: u8,
137 /// Per-mesh local origin (world/RTC frame, f64). `positions` are stored
138 /// RELATIVE to this — the world position of a vertex is `origin + position` —
139 /// so building/georef-scale placement never collapses adjacent vertices to
140 /// bit-identical f32. The renderer applies it as a per-mesh translation
141 /// (camera-relative). `[0, 0, 0]` ⇒ positions are absolute (legacy/local).
142 /// Serde-default + skip-when-zero so existing payloads/caches stay readable
143 /// and local meshes serialize byte-identically.
144 #[serde(default, skip_serializing_if = "origin_is_zero")]
145 pub origin: [f64; 3],
146 /// GPU-instancing metadata (rep-identity + per-occurrence world transform),
147 /// attached only when `IFC_LITE_INSTANCING` is on and the element is a clean
148 /// single-item mapped instance. Purely in-memory for the native streaming
149 /// path — `#[serde(skip)]` because instancing is recomputed fresh each load
150 /// and never round-trips through the JSON/disk cache.
151 #[serde(skip)]
152 pub instance: Option<InstanceMeta>,
153 /// Local (pre-placement, object-space) AABB (issue #1474) — see
154 /// `ifc_lite_geometry::Mesh::local_bounds`. Purely in-memory, like
155 /// `instance` — `#[serde(skip)]`, recomputed fresh each load.
156 #[serde(skip)]
157 pub local_bounds: Option<[f32; 6]>,
158 /// The resolved `IfcLocalPlacement` chain applied to this mesh (issue
159 /// #1474), row-major — see `ifc_lite_geometry::Mesh::local_to_world`.
160 /// Purely in-memory, like `instance` — `#[serde(skip)]`.
161 #[serde(skip)]
162 pub local_to_world: Option<[f64; 16]>,
163}
164
165fn geometry_class_is_occurrence(class: &u8) -> bool {
166 *class == 0
167}
168
169fn origin_is_zero(origin: &[f64; 3]) -> bool {
170 origin[0] == 0.0 && origin[1] == 0.0 && origin[2] == 0.0
171}
172
173impl MeshData {
174 /// Create a new MeshData from geometry components.
175 pub fn new(
176 express_id: u32,
177 ifc_type: String,
178 positions: Vec<f32>,
179 normals: Vec<f32>,
180 indices: Vec<u32>,
181 color: [f32; 4],
182 ) -> Self {
183 Self {
184 express_id,
185 ifc_type,
186 global_id: None,
187 name: None,
188 presentation_layer: None,
189 positions,
190 normals,
191 indices,
192 color,
193 material_name: None,
194 geometry_item_id: None,
195 material_id: None,
196 properties: None,
197 uvs: None,
198 texture: None,
199 geometry_class: 0,
200 origin: [0.0; 3],
201 instance: None,
202 local_bounds: None,
203 local_to_world: None,
204 }
205 }
206
207 /// Attach GPU-instancing metadata (see the `instance` field).
208 pub fn with_instance(mut self, instance: Option<InstanceMeta>) -> Self {
209 self.instance = instance;
210 self
211 }
212
213 /// Set the local (pre-placement, object-space) AABB (see `local_bounds`).
214 pub fn with_local_bounds(mut self, local_bounds: Option<[f32; 6]>) -> Self {
215 self.local_bounds = local_bounds;
216 self
217 }
218
219 /// Set the resolved placement transform (see `local_to_world`).
220 pub fn with_local_to_world(mut self, local_to_world: Option<[f64; 16]>) -> Self {
221 self.local_to_world = local_to_world;
222 self
223 }
224
225 /// Tag the geometry's provenance for the Model/Types view switch (#957).
226 pub fn with_geometry_class(mut self, geometry_class: u8) -> Self {
227 self.geometry_class = geometry_class;
228 self
229 }
230
231 /// Set the per-mesh local origin (positions are relative to it).
232 pub fn with_origin(mut self, origin: [f64; 3]) -> Self {
233 self.origin = origin;
234 self
235 }
236
237 /// Set element-level IFC metadata.
238 pub fn with_element_metadata(
239 mut self,
240 global_id: Option<String>,
241 name: Option<String>,
242 presentation_layer: Option<String>,
243 ) -> Self {
244 self.global_id = global_id;
245 self.name = name;
246 self.presentation_layer = presentation_layer;
247 self
248 }
249
250 /// Set material name and the source id, routed to whichever of the two
251 /// disjoint fields the id actually IS.
252 ///
253 /// Takes the discriminator rather than the destination field so a caller
254 /// cannot put a material id in `geometry_item_id` by picking the wrong
255 /// setter — the confusion #3199 removes is exactly that, and a two-setter
256 /// API would leave it one typo away.
257 ///
258 /// **A source id of `0` becomes `None`, on BOTH fields.** STEP instance
259 /// names start at `#1`, so `0` is never an entity; every producer that
260 /// hands one here is passing its own "no reference" sentinel through.
261 /// `material_layer_index.rs` is the live case: `IfcMaterialLayer.Material`
262 /// is OPTIONAL and the layer's `material_id` is `get_ref(0).unwrap_or(0)`,
263 /// so an air gap or ventilated cavity arrives as `0`. Storing that would
264 /// make `material_id` say "a slice of `IfcMaterial #0`", and a host that
265 /// followed it — the one thing this field exists for — would land on
266 /// nothing. That is the defect #3199 fixes, one field over, so the filter
267 /// lives HERE rather than at each producer, where the next producer would
268 /// have to remember it.
269 pub fn with_style_metadata(
270 mut self,
271 material_name: Option<String>,
272 source_id: Option<u32>,
273 id_is_material: bool,
274 ) -> Self {
275 self.material_name = material_name;
276 self.geometry_item_id = Self::style_geometry_item_id(source_id, id_is_material);
277 // The two fields are disjoint BY CONSTRUCTION: the same source id is a
278 // material id exactly when it is not a geometry item id, so the material
279 // half is the same rule with the discriminator negated. Spelling it as
280 // two independent branches is what lets one drift from the other.
281 self.material_id = Self::style_geometry_item_id(source_id, !id_is_material);
282 self
283 }
284
285 /// The `geometry_item_id` a producer's `source_id` resolves to, given the
286 /// #3199 discriminator: `None` when the id is a material's, and `None` for
287 /// the `0` sentinel (see [`Self::with_style_metadata`], which owns the why).
288 /// Passing the NEGATED discriminator gives the `material_id` half.
289 ///
290 /// Both rules live HERE because both are invisible when violated. `element.rs`
291 /// computes the same id for a don't-bake `RawInstanceOccurrence`, which has no
292 /// `MeshData` to run `with_style_metadata` over, so it calls this rather than
293 /// restating the pair.
294 pub fn style_geometry_item_id(source_id: Option<u32>, id_is_material: bool) -> Option<u32> {
295 if id_is_material {
296 None
297 } else {
298 source_id.filter(|&id| id != 0)
299 }
300 }
301
302 /// Attach optional IFC property set values.
303 pub fn with_properties(mut self, properties: Option<BTreeMap<String, String>>) -> Self {
304 self.properties = properties;
305 self
306 }
307
308 /// Get the number of vertices.
309 pub fn vertex_count(&self) -> usize {
310 self.positions.len() / 3
311 }
312
313 /// Get the number of triangles.
314 pub fn triangle_count(&self) -> usize {
315 self.indices.len() / 3
316 }
317
318 /// Check if the mesh is empty.
319 pub fn is_empty(&self) -> bool {
320 self.positions.is_empty() || self.indices.is_empty()
321 }
322}
323
324/// #1623 Phase 2 "don't-bake": a non-template occurrence of a shared
325/// `IfcRepresentationMap` that skipped the per-occurrence vertex materialize. The
326/// router emits an instance-only placeholder (empty geometry carrying
327/// `InstanceMeta`); [`crate::element::emit_sub_meshes`] turns it into one of these,
328/// and the streaming finalize resolves it against the template MeshData into an
329/// [`InstanceRecord`]. Purely in-memory (recomputed each load), never serialized.
330#[derive(Debug, Clone)]
331pub struct RawInstanceOccurrence {
332 /// This occurrence's IFC element id.
333 pub express_id: u32,
334 /// IFC type name (e.g. "IfcFlowFitting").
335 pub ifc_type: String,
336 /// IFC GlobalId when available.
337 pub global_id: Option<String>,
338 /// IFC Name when available.
339 pub name: Option<String>,
340 /// IFC presentation layer assignment name when available.
341 pub presentation_layer: Option<String>,
342 /// This occurrence's resolved RGBA colour.
343 pub color: [f32; 4],
344 /// Shared-template key = the `IfcRepresentationMap` express id. Matches the
345 /// template MeshData's `instance.rep_identity`.
346 pub rep_identity: u128,
347 /// PRE-RTC composed world transform (row-major) `transform · local · canonical`
348 /// — the same composition `collate_refs` computes for a baked occurrence, but
349 /// captured WITHOUT materializing vertices. The finalize reduces it to the
350 /// post-RTC frame and derives the template-relative `InstanceRecord.transform`.
351 pub world_transform: [f64; 16],
352 /// The `IfcRepresentationItem` this occurrence's geometry comes from — the
353 /// same id a materialized sub-mesh would carry in
354 /// [`MeshData::geometry_item_id`], read off the sub-mesh that was NOT
355 /// baked. `None` when the collection's ids are material ids rather than
356 /// item ids (#3199) or when the producer had none.
357 pub geometry_item_id: Option<u32>,
358}
359
360/// #1623 Phase 2: one resolved occurrence of a shared template geometry, emitted in
361/// [`crate::ProcessingResult::instances`] instead of a full materialized mesh when
362/// `StreamingOptions.enable_instancing` is set. The consumer uploads the template
363/// MeshData (`template_express_id`, still in `meshes`) once and draws this occurrence
364/// by applying `transform` to the template's baked world geometry. Purely in-memory,
365/// like [`MeshData::instance`] — recomputed fresh each load, never round-trips a cache.
366#[derive(Debug, Clone)]
367pub struct InstanceRecord {
368 /// This occurrence's IFC element id.
369 pub express_id: u32,
370 /// IFC type name (e.g. "IfcFlowFitting").
371 pub ifc_type: String,
372 /// IFC GlobalId when available.
373 pub global_id: Option<String>,
374 /// IFC Name when available.
375 pub name: Option<String>,
376 /// IFC presentation layer assignment name when available.
377 pub presentation_layer: Option<String>,
378 /// This occurrence's RGBA colour (may differ from the template occurrence's).
379 pub color: [f32; 4],
380 /// `express_id` of the template `MeshData` this occurrence instantiates — the
381 /// consumer's link from record to the geometry it draws (JS-safe u32).
382 pub template_express_id: u32,
383 /// Representation-identity of the shared geometry (`IfcRepresentationMap` id).
384 pub rep_identity: u128,
385 /// Row-major, TEMPLATE-RELATIVE mat4: applied to the template's baked world
386 /// geometry (`template.origin + positions`) it yields this occurrence's world
387 /// geometry (`rel_k = post_rtc(M_k) · post_rtc(M_ref)⁻¹`).
388 pub transform: [f32; 16],
389 /// The `IfcRepresentationItem` this occurrence's geometry comes from, so a
390 /// host can drill from a rendered instanced piece back into the source.
391 /// Same meaning and same disjointness rule as [`MeshData::geometry_item_id`]
392 /// — always a representation item, never an `IfcMaterial`.
393 pub geometry_item_id: Option<u32>,
394}