Skip to main content

brep_kernel/abi/
handles.rs

1use super::*;
2
3#[wasm_bindgen]
4pub struct WasmNurbsCurve {
5    pub(crate) curve: NurbsCurve,
6}
7
8#[wasm_bindgen]
9pub struct WasmNurbsSurface {
10    pub(crate) surface: NurbsSurface,
11}
12
13/// A solid encoded as one flat `Float64Array` plus a tiny JSON side channel
14/// for face/edge names — the zero-JSON result path for topology-heavy ops.
15/// Getters consume the buffers (each may be read once) to avoid double copies.
16#[wasm_bindgen]
17pub struct WasmSolidBuffer {
18    pub(crate) data: Vec<f64>,
19    pub(crate) names_json: String,
20    pub(crate) metadata_json: String,
21}
22
23#[wasm_bindgen]
24impl WasmSolidBuffer {
25    pub fn take_data(&mut self) -> Vec<f64> {
26        std::mem::take(&mut self.data)
27    }
28
29    pub fn names_json(&self) -> String {
30        self.names_json.clone()
31    }
32
33    /// Operation-specific extras (e.g. offset-shell face images); "{}" when
34    /// the operation has none.
35    pub fn metadata_json(&self) -> String {
36        self.metadata_json.clone()
37    }
38}
39
40pub(crate) fn solid_buffer(solid: &BrepSolid, metadata_json: String) -> Result<WasmSolidBuffer, JsValue> {
41    let (data, names) = encode_solid(solid).map_err(javascript_error)?;
42    Ok(WasmSolidBuffer {
43        data,
44        names_json: serde_json::to_string(&names)
45            .map_err(|error| javascript_error(error.to_string()))?,
46        metadata_json,
47    })
48}
49
50/// Tessellation output as typed arrays; getters consume the buffers.
51#[wasm_bindgen]
52pub struct WasmMeshBuffers {
53    pub(crate) positions: Vec<f64>,
54    pub(crate) normals: Vec<f64>,
55    pub(crate) indices: Vec<u32>,
56    pub(crate) face_ids: Vec<u32>,
57}
58
59#[wasm_bindgen]
60impl WasmMeshBuffers {
61    pub fn take_positions(&mut self) -> Vec<f64> {
62        std::mem::take(&mut self.positions)
63    }
64
65    pub fn take_normals(&mut self) -> Vec<f64> {
66        std::mem::take(&mut self.normals)
67    }
68
69    pub fn take_indices(&mut self) -> Vec<u32> {
70        std::mem::take(&mut self.indices)
71    }
72
73    pub fn take_face_ids(&mut self) -> Vec<u32> {
74        std::mem::take(&mut self.face_ids)
75    }
76}
77
78// ---------------------------------------------------------------------------
79// Persistent solid handle registry (Rust-pipeline migration, Stage 1).
80//
81// Keeps resident BrepSolids in the (single-threaded) main-thread wasm instance,
82// keyed by an opaque u32 handle, so ops consume/produce handles instead of
83// re-serializing the full topology across the wasm boundary on every call. The host pulls only
84// tessellation / mass-props / names across the boundary, and only when it needs
85// them — this is the foundation that eliminates the per-op round-trip (see
86//   the Rust pipeline-migration design, Stage 1).
87//
88// Handle lifetime is EXPLICIT: register_* mints a handle, free_solid drops it.
89// The wasm32 heap has a 4 GB ceiling and heavy solids are MB-scale resident, so
90// callers MUST free handles they no longer need. register_* keeps full arena +
91// validate (external / first-crossing ingest); kernel-produced results from the
92// *_handle ops are trusted (no double-validate — the kernel just built them).
93// ---------------------------------------------------------------------------
94thread_local! {
95    static SOLID_REGISTRY: std::cell::RefCell<SolidRegistry> =
96        std::cell::RefCell::new(SolidRegistry::new());
97}
98
99pub(crate) struct SolidRegistry {
100    pub(crate) next: u32,
101    pub(crate) solids: std::collections::HashMap<u32, BrepSolid>,
102}
103
104impl SolidRegistry {
105    fn new() -> Self {
106        Self {
107            next: 1,
108            solids: std::collections::HashMap::new(),
109        }
110    }
111    fn insert(&mut self, solid: BrepSolid) -> u32 {
112        let handle = self.next;
113        self.next = self.next.wrapping_add(1).max(1);
114        self.solids.insert(handle, solid);
115        handle
116    }
117}
118
119pub(crate) fn register_solid_value(solid: BrepSolid) -> u32 {
120    SOLID_REGISTRY.with(|registry| registry.borrow_mut().insert(solid))
121}
122
123/// Run `f` against a resident solid by handle (immutable borrow).
124pub(crate) fn with_registered_solid<T>(
125    handle: u32,
126    f: impl FnOnce(&BrepSolid) -> Result<T, JsValue>,
127) -> Result<T, JsValue> {
128    SOLID_REGISTRY.with(|registry| {
129        let registry = registry.borrow();
130        let solid = registry
131            .solids
132            .get(&handle)
133            .ok_or_else(|| javascript_error(format!("unknown solid handle {handle}")))?;
134        f(solid)
135    })
136}
137
138/// `String`-error sibling of [`with_registered_solid`] for the Rust feature
139/// pipeline, which stays JsValue-free internally (JsValue only at the wasm
140/// boundary; the host test target cannot run JsValue error paths). Short borrow:
141/// never hold the registry across a feature execution.
142pub(crate) fn with_registered_solid_str<T>(
143    handle: u32,
144    f: impl FnOnce(&BrepSolid) -> Result<T, String>,
145) -> Result<T, String> {
146    SOLID_REGISTRY.with(|registry| {
147        let registry = registry.borrow();
148        let solid = registry
149            .solids
150            .get(&handle)
151            .ok_or_else(|| format!("unknown solid handle {handle}"))?;
152        f(solid)
153    })
154}
155
156/// Run `f` against two resident solids in a single short borrow (the boolean /
157/// two-operand op shape). The error type follows `f` (a typed `KernelRefusal`
158/// from the boolean, or the `String` a stringly caller still uses) so the
159/// feature pipeline stays JsValue-free; an unknown handle is an `InvalidInput`
160/// refusal converted into that type. Never held across a feature execution (the RefCell would fight
161/// a re-entrant borrow otherwise).
162pub(crate) fn with_two_registered_solids<T, E: From<crate::KernelRefusal>>(
163    a: u32,
164    b: u32,
165    f: impl FnOnce(&BrepSolid, &BrepSolid) -> Result<T, E>,
166) -> Result<T, E> {
167    SOLID_REGISTRY.with(|registry| {
168        let registry = registry.borrow();
169        let handle = |id: u32| -> Result<&BrepSolid, E> {
170            registry.solids.get(&id).ok_or_else(|| {
171                crate::KernelRefusal::input(
172                    crate::KernelStage::Collect,
173                    "solid_handle",
174                    format!("unknown solid handle {id}"),
175                )
176                .into()
177            })
178        };
179        let sa = handle(a)?;
180        let sb = handle(b)?;
181        f(sa, sb)
182    })
183}
184
185/// Replace a resident solid's CONTENT under its EXISTING handle. The component
186/// re-pose lane (`feature_pipeline::component::update_component_transform`)
187/// mutates geometry in place so the handle — which the SceneMap, the history
188/// cache, and the display layer all hold — stays valid; a rigid re-pose keeps
189/// every topology id and name, so nothing keyed by them moves. Errors on an
190/// unknown handle (never silently mints one).
191pub(crate) fn replace_registered_solid(handle: u32, solid: BrepSolid) -> Result<(), String> {
192    SOLID_REGISTRY.with(|registry| {
193        let mut registry = registry.borrow_mut();
194        match registry.solids.get_mut(&handle) {
195            Some(slot) => {
196                *slot = solid;
197                Ok(())
198            }
199            None => Err(format!("unknown solid handle {handle}")),
200        }
201    })
202}
203
204/// Drop a resident solid by handle (feature-pipeline-internal, `pub(crate)`
205/// sibling of the wasm `free_solid`). No-op if the handle is unknown. Callers
206/// MUST free handles they no longer need — the wasm32 heap has a 4 GB ceiling.
207pub(crate) fn free_registered_solid(handle: u32) {
208    SOLID_REGISTRY.with(|registry| {
209        registry.borrow_mut().solids.remove(&handle);
210    });
211}
212
213/// Ingest a solid from the flat f64 codec into the resident registry (arena +
214/// validate kept — external / first-crossing ingest). Returns an opaque handle.
215#[wasm_bindgen]
216pub fn register_solid_buffer(data: &[f64], names_json: &str) -> Result<u32, JsValue> {
217    let solid = decode_solid_buffer(data, names_json)?;
218    let solid = validate_imported_solid(solid, "register_solid_buffer")?;
219    Ok(register_solid_value(solid))
220}
221
222/// Ingest a solid from JSON into the resident registry (arena + validate kept).
223#[wasm_bindgen]
224pub fn register_solid_json(solid_json: &str) -> Result<u32, JsValue> {
225    let solid: BrepSolid =
226        serde_json::from_str(solid_json).map_err(|error| javascript_error(error.to_string()))?;
227    let solid = validate_imported_solid(solid, "register_solid_json")?;
228    Ok(register_solid_value(solid))
229}
230
231/// Drop a resident solid. No-op if the handle is unknown.
232#[wasm_bindgen]
233pub fn free_solid(handle: u32) {
234    SOLID_REGISTRY.with(|registry| {
235        registry.borrow_mut().solids.remove(&handle);
236    });
237}
238
239/// A clone of a resident solid, for Rust callers that need the topology itself:
240/// the case-replay diagnostics and probes, and the history runner answering a
241/// drawing sheet's topology request (native thread or browser worker alike),
242/// which serializes the clone back to the main side. The feature pipeline's
243/// results only ever hand out handles, and this is no `#[wasm_bindgen]` export:
244/// JavaScript never calls it. Short borrow; the clone is the caller's.
245pub fn registered_solid_clone(handle: u32) -> Result<BrepSolid, String> {
246    with_registered_solid_str(handle, |solid| Ok(solid.clone()))
247}
248
249/// Number of resident solids (diagnostics / handle-leak detection).
250#[wasm_bindgen]
251pub fn registered_solid_count() -> usize {
252    SOLID_REGISTRY.with(|registry| registry.borrow().solids.len())
253}
254
255/// Boolean of two resident solids -> a NEW resident handle. The result never
256/// crosses the boundary as topology; only its handle is returned. Kernel-produced
257/// result is trusted (no double-validate).
258#[wasm_bindgen]
259pub fn boolean_handle(
260    a: u32,
261    b: u32,
262    operation: &str,
263    tolerance: f64,
264    merge_coplanar_faces: bool,
265) -> Result<u32, JsValue> {
266    let operation = match operation {
267        "union" => BooleanOperation::Union,
268        "intersect" => BooleanOperation::Intersect,
269        "subtract" => BooleanOperation::Subtract,
270        _ => return Err(javascript_error("unknown boolean operation".into())),
271    };
272    let result = SOLID_REGISTRY.with(|registry| {
273        let registry = registry.borrow();
274        let sa = registry
275            .solids
276            .get(&a)
277            .ok_or_else(|| javascript_error(format!("unknown solid handle {a}")))?;
278        let sb = registry
279            .solids
280            .get(&b)
281            .ok_or_else(|| javascript_error(format!("unknown solid handle {b}")))?;
282        boolean_operation(
283            sa,
284            sb,
285            operation,
286            &BooleanOptions {
287                tolerance,
288                merge_coplanar_faces,
289                ..BooleanOptions::default()
290            },
291        )
292        .map_err(crate::abi::geometry::javascript_refusal)
293    })?;
294    Ok(register_solid_value(result))
295}
296
297/// Tessellate a resident solid to watertight mesh buffers (the buffers cross the
298/// boundary; the solid does not).
299#[wasm_bindgen]
300pub fn tessellate_handle(handle: u32, chord_tolerance: f64) -> Result<WasmMeshBuffers, JsValue> {
301    with_registered_solid(handle, |solid| {
302        let mesh = tessellate_brep_watertight(solid, chord_tolerance).map_err(javascript_error)?;
303        Ok(WasmMeshBuffers {
304            positions: mesh.positions,
305            normals: mesh.normals,
306            indices: mesh.indices,
307            face_ids: mesh.face_ids,
308        })
309    })
310}
311
312/// Analytic mass properties of a resident solid (a handful of scalars).
313#[wasm_bindgen]
314pub fn mass_properties_handle(handle: u32) -> Result<String, JsValue> {
315    with_registered_solid(handle, |solid| {
316        let _caller = crate::mass_caller("abi.mass_properties");
317        let properties = solid_mass_properties(solid).map_err(javascript_error)?;
318        serde_json::to_string(&properties).map_err(|error| javascript_error(error.to_string()))
319    })
320}
321
322/// Rigid/affine transform of a resident solid -> a NEW resident handle (Stage 1b;
323/// unblocks Transform/Pattern/bakeTransform from the legacy serialize lane). The
324/// result never crosses the boundary as topology. Kernel-produced, so trusted.
325#[wasm_bindgen]
326pub fn transform_handle(
327    handle: u32,
328    matrix: &[f64],
329    reverse_orientation: bool,
330) -> Result<u32, JsValue> {
331    let matrix: [f64; 16] = matrix
332        .try_into()
333        .map_err(|_| javascript_error("transform matrix must contain 16 values".into()))?;
334    let transform = AffineTransform::new(matrix).map_err(javascript_error)?;
335    let result = with_registered_solid(handle, |solid| {
336        transform_brep(solid, transform, reverse_orientation).map_err(javascript_error)
337    })?;
338    Ok(register_solid_value(result))
339}
340
341/// The resident solid's face id -> name map (Stage 1b; lets the host rebuild its
342/// selection/name index from a handle without materializing the full graph).
343#[wasm_bindgen]
344pub fn face_names_handle(handle: u32) -> Result<String, JsValue> {
345    with_registered_solid(handle, |solid| {
346        let mut map: Vec<(u64, Option<String>)> = Vec::new();
347        for shell in &solid.shells {
348            for face in &shell.faces {
349                map.push((face.id, face.name.clone()));
350            }
351        }
352        serde_json::to_string(&map).map_err(|error| javascript_error(error.to_string()))
353    })
354}
355
356// ===========================================================================
357// Native in-process display accessors (brep-render). Plain pub fns — NOT
358// #[wasm_bindgen] — so they add nothing to the wasm export surface; the native
359// renderer links the kernel as an rlib and reads display data with no JSON or
360// typed-array boundary.
361// ===========================================================================
362
363/// Native sibling of [`boolean_handle`] (String errors — constructing a
364/// `JsValue` error panics off-wasm): boolean of two RESIDENT solids → a NEW
365/// resident handle, operands untouched. The assembly interference check's
366/// non-destructive INTERSECT lane; callers free the result handle when done.
367pub fn boolean_handle_native(
368    a: u32,
369    b: u32,
370    operation: BooleanOperation,
371    options: &BooleanOptions,
372) -> Result<u32, String> {
373    let result =
374        with_two_registered_solids(a, b, |sa, sb| boolean_operation(sa, sb, operation, options))?;
375    Ok(register_solid_value(result))
376}