ifc_lite_rhino_wasm/
lib.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//! Independently loaded exporters: the Rhino scene builder and CityJSON 2.0.
5//! Kept out of the default geometry engine (`ifc-lite-wasm`) so these rarely
6//! used exporters never grow the download every viewer load pays for; the
7//! payload is fetched only when a .3dm or CityJSON export runs.
8use js_sys::{Array, Object, Reflect};
9use wasm_bindgen::prelude::*;
10
11/// Encoded Rhino scene. Getters copy data out so the handle can be freed immediately.
12// Both values are copied into JS once, when the scene is built; a getter hands
13// out the same JS value, so neither read copies wasm memory again.
14#[wasm_bindgen]
15pub struct RhinoSceneJs {
16    manifest: js_sys::JsString,
17    blob: js_sys::Uint8Array,
18}
19
20#[wasm_bindgen]
21impl RhinoSceneJs {
22    #[wasm_bindgen(getter)]
23    pub fn manifest(&self) -> js_sys::JsString { self.manifest.clone() }
24    #[wasm_bindgen(getter)]
25    pub fn blob(&self) -> js_sys::Uint8Array { self.blob.clone() }
26}
27
28/// Build the shared Rhino scene; archive writing belongs to the adapter.
29/// A model with no render geometry throws an `Error` whose message starts with
30/// `NO_RENDER_GEOMETRY`, like the default engine's `exportUsd`.
31#[wasm_bindgen(js_name = exportRhinoScene)]
32pub fn export_rhino_scene(content: &[u8], options_json: &str) -> Result<RhinoSceneJs, JsValue> {
33    let options: ifc_lite_export::rhino::RhinoSceneOptions = serde_json::from_str(options_json)
34        .map_err(|e| JsValue::from(js_sys::Error::new(&e.to_string())))?;
35    let scene = ifc_lite_export::rhino::build_rhino_scene(content, &options)
36        .map_err(|e| JsValue::from(js_sys::Error::new(&e.to_string())))?;
37    let (manifest, blob) = scene.encode();
38    Ok(RhinoSceneJs { manifest: js_sys::JsString::from(manifest), blob: js_sys::Uint8Array::from(blob.as_slice()) })
39}
40
41#[wasm_bindgen(typescript_custom_section)]
42const CITYJSON_TYPES: &str = r#"
43export interface CityJsonExportJs {
44  text: string;
45  /** `metadata.referenceSystem`, or null for local coordinates. */
46  referenceSystem: string | null;
47  warnings: string[];
48  buildings: number;
49  cityObjects: number;
50  vertices: number;
51}
52"#;
53
54#[wasm_bindgen]
55extern "C" {
56    #[wasm_bindgen(typescript_type = "CityJsonExportJs")]
57    pub type CityJsonExportJs;
58}
59
60fn js_error(message: &str) -> JsValue {
61    JsValue::from(js_sys::Error::new(message))
62}
63
64/// `{ scale?: number, elementGeometry?: boolean, sequence?: boolean }`, every
65/// field optional; anything else is refused rather than ignored.
66fn cityjson_options(options_json: &str) -> Result<ifc_lite_export::CityJsonOptions, JsValue> {
67    let mut out = ifc_lite_export::CityJsonOptions::default();
68    let value: serde_json::Value = serde_json::from_str(options_json).map_err(|e| js_error(&format!("exportCityJson options: {e}")))?;
69    let Some(map) = value.as_object() else {
70        return if value.is_null() { Ok(out) } else { Err(js_error("exportCityJson options must be an object")) };
71    };
72    for (key, v) in map {
73        if v.is_null() {
74            continue;
75        }
76        let bad = |kind: &str| js_error(&format!("exportCityJson options.{key} must be a {kind}"));
77        match key.as_str() {
78            "scale" => out.scale = v.as_f64().ok_or_else(|| bad("number"))?,
79            "elementGeometry" => out.element_geometry = v.as_bool().ok_or_else(|| bad("boolean"))?,
80            "sequence" => out.sequence = v.as_bool().ok_or_else(|| bad("boolean"))?,
81            _ => return Err(js_error(&format!("exportCityJson options.{key} is not an option"))),
82        }
83    }
84    Ok(out)
85}
86
87fn set(target: &Object, key: &str, value: impl Into<JsValue>) -> Result<(), JsValue> {
88    Reflect::set(target, &JsValue::from_str(key), &value.into()).map(|_| ())
89}
90
91/// Export `content` as CityJSON 2.0 (or CityJSONSeq with `sequence`).
92///
93/// A model with no `IfcBuilding` throws an `Error` whose message starts with
94/// `CITYJSON_REFUSED:`. Georeferencing that cannot be resolved is not an
95/// error: the document is written in local coordinates and `warnings` says why.
96#[wasm_bindgen(js_name = exportCityJson)]
97pub fn export_cityjson(content: &[u8], options_json: &str) -> Result<CityJsonExportJs, JsValue> {
98    let options = cityjson_options(options_json)?;
99    let export = ifc_lite_export::try_export_cityjson(content, &options).map_err(|e| js_error(&e.to_string()))?;
100    let out = Object::new();
101    set(&out, "text", export.text)?;
102    set(&out, "referenceSystem", export.reference_system.map_or(JsValue::NULL, JsValue::from))?;
103    set(&out, "warnings", export.warnings.into_iter().map(JsValue::from).collect::<Array>())?;
104    set(&out, "buildings", export.buildings as f64)?;
105    set(&out, "cityObjects", export.city_objects as f64)?;
106    set(&out, "vertices", export.vertices as f64)?;
107    Ok(JsValue::from(out).into())
108}