ifc_lite_export/rhino/
wire.rs

1// SPDX-License-Identifier: MPL-2.0
2//! The `RhinoScene` records and their wire encoding (manifest JSON plus one
3//! little-endian blob). Field names are the wire contract in
4//! `docs/architecture/rhino-3dm-export.md`; the TypeScript adapter reads them.
5
6use serde::Serialize;
7
8/// Manifest `format` tag.
9pub const RHINO_SCENE_FORMAT: &str = "ifc-lite.rhino-scene";
10/// Manifest `version`; bumped on any incompatible change.
11pub const RHINO_SCENE_VERSION: u32 = 1;
12
13/// Document settings.
14#[derive(Debug, Clone, PartialEq, Serialize)]
15#[serde(rename_all = "camelCase")]
16pub struct RhinoSettings {
17    /// rhino3dm `UnitSystem` member name.
18    pub unit_system: &'static str,
19    pub meters_per_unit: f64,
20    /// 1 mm in `unit_system`.
21    pub absolute_tolerance: f64,
22    pub angle_tolerance_degrees: f64,
23    pub earth_anchor: Option<EarthAnchor>,
24}
25
26/// Rhino earth anchor point, from `IfcSite.RefLatitude` / `RefLongitude`.
27#[derive(Debug, Clone, PartialEq, Serialize)]
28#[serde(rename_all = "camelCase")]
29pub struct EarthAnchor {
30    pub latitude: f64,
31    pub longitude: f64,
32    /// Metres.
33    pub elevation: f64,
34    /// The site placement origin in written coordinates and units.
35    pub model_base_point: [f64; 3],
36    /// Unit direction of true north in written coordinates.
37    pub model_north: [f64; 3],
38    /// Unit direction of east in written coordinates.
39    pub model_east: [f64; 3],
40    pub name: String,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
44#[serde(rename_all = "camelCase")]
45pub struct RhinoLayer {
46    pub name: String,
47    pub parent: Option<usize>,
48    pub color: [u8; 4],
49    pub visible: bool,
50    pub locked: bool,
51    /// Layer user text: the IFC identity of a layer that stands for the
52    /// project or a spatial structure element; empty for every other layer.
53    pub user_strings: Vec<(String, String)>,
54}
55
56#[derive(Debug, Clone, PartialEq, Serialize)]
57pub struct RhinoMaterial {
58    pub name: String,
59    pub diffuse: [u8; 3],
60    pub transparency: f64,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
64pub struct RhinoGroup {
65    pub name: String,
66}
67
68/// One triangle mesh: positions in output units and coordinates.
69#[derive(Debug, Clone, PartialEq, Default)]
70pub struct RhinoMesh {
71    /// xyz triplets.
72    pub positions: Vec<f64>,
73    /// xyz triplets, one per vertex; `None` when normals are off.
74    pub normals: Option<Vec<f32>>,
75    /// Triangles.
76    pub indices: Vec<u32>,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
80pub struct RhinoBlock {
81    pub name: String,
82    pub description: String,
83    pub meshes: Vec<usize>,
84    pub layer: usize,
85}
86
87/// What an object draws.
88#[derive(Debug, Clone, PartialEq, Serialize)]
89#[serde(tag = "kind", rename_all = "lowercase")]
90pub enum RhinoGeometry {
91    Mesh { mesh: usize },
92    /// `xform` is row-major and maps block coordinates to written coordinates.
93    Instance { block: usize, xform: [f64; 16] },
94}
95
96#[derive(Debug, Clone, PartialEq, Serialize)]
97#[serde(rename_all = "camelCase")]
98pub struct RhinoObject {
99    #[serde(flatten)]
100    pub geometry: RhinoGeometry,
101    pub layer: usize,
102    pub name: String,
103    /// UUID string; see "Object identity" in the spec.
104    pub object_id: String,
105    pub color: [u8; 4],
106    pub material: usize,
107    pub groups: Vec<usize>,
108    pub user_strings: Vec<(String, String)>,
109}
110
111/// The scene: plain data saying which layer, material, group, block and user
112/// strings every object gets. [`RhinoScene::encode`] produces the wire form;
113/// it destructures every field, so a field added here does not compile until
114/// it has a place in the manifest.
115#[derive(Debug, Clone, PartialEq)]
116pub struct RhinoScene {
117    pub settings: RhinoSettings,
118    pub warnings: Vec<String>,
119    pub document_strings: Vec<(String, String)>,
120    pub layers: Vec<RhinoLayer>,
121    pub materials: Vec<RhinoMaterial>,
122    pub groups: Vec<RhinoGroup>,
123    pub meshes: Vec<RhinoMesh>,
124    pub blocks: Vec<RhinoBlock>,
125    pub objects: Vec<RhinoObject>,
126}
127
128/// A blob section: byte offset and element count.
129#[derive(Serialize)]
130struct BufferRef {
131    offset: usize,
132    count: usize,
133}
134
135#[derive(Serialize)]
136struct WireMesh {
137    positions: BufferRef,
138    normals: Option<BufferRef>,
139    indices: BufferRef,
140}
141
142/// The manifest JSON: the scene's fields in declaration order, with `meshes`
143/// as blob references.
144#[derive(Serialize)]
145#[serde(rename_all = "camelCase")]
146struct Manifest<'a> {
147    format: &'static str,
148    version: u32,
149    settings: &'a RhinoSettings,
150    warnings: &'a [String],
151    document_strings: &'a [(String, String)],
152    layers: &'a [RhinoLayer],
153    materials: &'a [RhinoMaterial],
154    groups: &'a [RhinoGroup],
155    meshes: &'a [WireMesh],
156    blocks: &'a [RhinoBlock],
157    objects: &'a [RhinoObject],
158}
159
160/// Append `values` little-endian to `blob` as the next section, starting on
161/// an 8-byte boundary (zero-padded up to it).
162fn push_section<T: Copy, const N: usize>(blob: &mut Vec<u8>, values: &[T], to_le: impl Fn(T) -> [u8; N]) -> BufferRef {
163    let offset = blob.len().next_multiple_of(8);
164    blob.resize(offset, 0);
165    blob.reserve(values.len() * N);
166    for &v in values {
167        blob.extend_from_slice(&to_le(v));
168    }
169    BufferRef { offset, count: values.len() }
170}
171
172impl RhinoScene {
173    /// The manifest JSON and the blob it references.
174    ///
175    /// Each mesh's sections are `positions` (f64), then `normals` (f32) when
176    /// present, then `indices` (u32), back to back, every section 8-byte
177    /// aligned and little-endian, so an adapter takes typed-array views
178    /// without copying. Consumes the scene and drops each mesh once its bytes
179    /// are written; that does not lower the peak (the blob grows while the
180    /// later meshes are still alive, and wasm linear memory never shrinks).
181    pub fn encode(self) -> (String, Vec<u8>) {
182        let RhinoScene { settings, warnings, document_strings, layers, materials, groups, meshes, blocks, objects } = self;
183        let mut blob = Vec::new();
184        let refs: Vec<WireMesh> = meshes
185            .into_iter()
186            .map(|m| WireMesh {
187                positions: push_section(&mut blob, &m.positions, f64::to_le_bytes),
188                normals: m.normals.as_deref().map(|n| push_section(&mut blob, n, f32::to_le_bytes)),
189                indices: push_section(&mut blob, &m.indices, u32::to_le_bytes),
190            })
191            .collect();
192        let manifest = Manifest {
193            format: RHINO_SCENE_FORMAT,
194            version: RHINO_SCENE_VERSION,
195            settings: &settings,
196            warnings: &warnings,
197            document_strings: &document_strings,
198            layers: &layers,
199            materials: &materials,
200            groups: &groups,
201            meshes: &refs,
202            blocks: &blocks,
203            objects: &objects,
204        };
205        // Plain structs of strings, integers and finite floats: nothing here can fail.
206        let json = serde_json::to_string(&manifest).expect("rhino scene manifest serializes");
207        (json, blob)
208    }
209}