Skip to main content

brep_kernel/feature_pipeline/assembly/
exports.rs

1//! The assembly SESSION + exported ABI (build-spec §10 item 5): constraint
2//! CRUD with auto-solve, manual solve, per-constraint status JSON, DOF summary
3//! JSON, overlay-geometry JSON, and the generic document fold that writes the
4//! solved state + poses back into the history document.
5//!
6//! The session is installed by the history-execution tail
7//! ([`super::finish_history_run`]) after EVERY run: the post-solve constraint
8//! state, a clone of the final scene map (names + resident handles — the
9//! handles stay owned by the history cache), and the expression sheet for
10//! expression-capable params. Constraint mutations between runs operate on the
11//! session and AUTO-SOLVE against the live resident geometry; the app folds
12//! the result back into its document via [`assembly_apply_document_json`]
13//! before the next history run (the pose-authority contract).
14
15use std::cell::RefCell;
16use std::collections::BTreeMap;
17
18use wasm_bindgen::prelude::*;
19
20use super::lifecycle::{self, LifecycleOutcome};
21use super::{constraints, mapping, AssemblyState, ConstraintEntry};
22use crate::feature_pipeline::{Env, SceneMap};
23
24struct Session {
25    state: AssemblyState,
26    scene: SceneMap,
27    expressions: String,
28    configurator: serde_json::Value,
29    /// Component id → solved `inputParams.transform` JSON. ACCUMULATES across
30    /// mutation solves (later solves overwrite per id); replaced wholesale by
31    /// the next history run.
32    pose_updates: BTreeMap<String, serde_json::Value>,
33    /// Component id → grounded write-back (`inputParams.isFixed`).
34    fixed_updates: BTreeMap<String, bool>,
35    /// The last solve's report (`ok` + diagnostics, or `error`).
36    report: serde_json::Value,
37}
38
39thread_local! {
40    static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
41}
42
43/// Install the post-run session (the history tail). Pose/fixed updates start
44/// from THIS run's outcome — the previous session's pending updates are
45/// dropped (the run consumed the document they were meant for).
46pub(super) fn install_session(
47    state: AssemblyState,
48    scene: SceneMap,
49    expressions: String,
50    configurator: serde_json::Value,
51    outcome: LifecycleOutcome,
52) {
53    SESSION.with(|session| {
54        *session.borrow_mut() = Some(Session {
55            state,
56            scene,
57            expressions,
58            configurator,
59            pose_updates: outcome.pose_updates,
60            fixed_updates: outcome.fixed_updates,
61            report: outcome.report,
62        });
63    });
64}
65
66fn with_session<T>(f: impl FnOnce(&mut Session) -> Result<T, String>) -> Result<T, String> {
67    SESSION.with(|session| {
68        let mut session = session.borrow_mut();
69        let session = session
70            .as_mut()
71            .ok_or_else(|| "no assembly session (run a history first)".to_string())?;
72        f(session)
73    })
74}
75
76/// Re-solve the session state against the session scene, merging the
77/// outcome's write-backs (the auto-solve every mutation triggers). The
78/// returned report carries `movedSolids` (built by the lifecycle) — the
79/// display lane re-tessellates exactly those in-place-moved resident solids.
80fn solve_session(session: &mut Session) -> serde_json::Value {
81    let env = Env::build(&session.expressions, &session.configurator)
82        .unwrap_or_else(Env::poisoned);
83    let outcome = lifecycle::run_constraints(&mut session.state, &mut session.scene, &env);
84    session.pose_updates.extend(outcome.pose_updates);
85    session.fixed_updates.extend(outcome.fixed_updates);
86    session.report = outcome.report.clone();
87    outcome.report
88}
89
90// ===========================================================================
91// Read surface
92// ===========================================================================
93
94/// The current `assembly` block (post-solve) as JSON — the panel's list source
95/// and the state the app folds back into its document.
96#[wasm_bindgen]
97pub fn assembly_state_json() -> String {
98    SESSION.with(|session| {
99        session
100            .borrow()
101            .as_ref()
102            .map(|session| serde_json::to_value(&session.state).unwrap_or_default())
103            .unwrap_or_else(|| serde_json::to_value(AssemblyState::default()).unwrap_or_default())
104            .to_string()
105    })
106}
107
108/// Per-constraint status rows: `[{id, type, enabled, open, status, message,
109/// satisfied, error}]` (requirements §5 vocabulary).
110#[wasm_bindgen]
111pub fn assembly_statuses_json() -> String {
112    SESSION.with(|session| {
113        let rows: Vec<serde_json::Value> = session
114            .borrow()
115            .as_ref()
116            .map(|session| {
117                session
118                    .state
119                    .constraints
120                    .iter()
121                    .map(|entry| {
122                        serde_json::json!({
123                            "id": entry.id(),
124                            "type": entry.constraint_type,
125                            "enabled": entry.enabled,
126                            "open": entry.open,
127                            "status": entry.status(),
128                            "message": entry
129                                .persistent("message")
130                                .and_then(|value| value.as_str())
131                                .unwrap_or(""),
132                            "satisfied": entry
133                                .persistent("satisfied")
134                                .and_then(|value| value.as_bool())
135                                .unwrap_or(false),
136                            "error": entry.persistent("error").cloned(),
137                        })
138                    })
139                    .collect()
140            })
141            .unwrap_or_default();
142        serde_json::Value::Array(rows).to_string()
143    })
144}
145
146/// The last solve's DOF/diagnostics summary (`{ok, dof, rank, redundant,
147/// status, strategy, iterations, maxResidual, ...}` or `{ok:false, error}`).
148#[wasm_bindgen]
149pub fn assembly_dof_json() -> String {
150    SESSION.with(|session| {
151        session
152            .borrow()
153            .as_ref()
154            .map(|session| session.report.to_string())
155            .unwrap_or_else(|| serde_json::json!({ "ok": true, "mates": 0 }).to_string())
156    })
157}
158
159/// The pending generic feature write-backs: `{"poses": {componentId:
160/// transformParam}, "isFixed": {componentId: bool}}`. The transform param is
161/// `{translate, rotateEulerDeg (deg, intrinsic XYZ)}` — exactly the shape the
162/// ACOMP feature's `inputParams.transform` reader expects.
163#[wasm_bindgen]
164pub fn assembly_pose_updates_json() -> String {
165    SESSION.with(|session| {
166        session
167            .borrow()
168            .as_ref()
169            .map(|session| {
170                serde_json::json!({
171                    "poses": session.pose_updates,
172                    "isFixed": session.fixed_updates,
173                })
174                .to_string()
175            })
176            .unwrap_or_else(|| serde_json::json!({ "poses": {}, "isFixed": {} }).to_string())
177    })
178}
179
180/// Fold the session's solved state into a history DOCUMENT: replaces the
181/// top-level `assembly` block and writes each pending pose / grounded flag
182/// into the owning feature's `inputParams` (matched by `inputParams.id` —
183/// generic JSON, no dependency on the ACOMP feature shape). The app calls this
184/// on its document before persisting or re-running (the pose-authority
185/// write-back, spec §6 step 4).
186#[wasm_bindgen]
187pub fn assembly_apply_document_json(document_json: &str) -> Result<String, JsValue> {
188    apply_document(document_json).map_err(|error| JsValue::from_str(&error))
189}
190
191fn apply_document(document_json: &str) -> Result<String, String> {
192    let mut document: serde_json::Value = serde_json::from_str(document_json)
193        .map_err(|error| format!("assembly document fold: bad document: {error}"))?;
194    with_session(|session| {
195        let object = document
196            .as_object_mut()
197            .ok_or_else(|| "assembly document fold: document must be an object".to_string())?;
198        object.insert(
199            "assembly".into(),
200            serde_json::to_value(&session.state)
201                .map_err(|error| format!("assembly state serialize: {error}"))?,
202        );
203        if let Some(features) = object.get_mut("features").and_then(|v| v.as_array_mut()) {
204            for feature in features {
205                let Some(params) = feature
206                    .get_mut("inputParams")
207                    .and_then(|value| value.as_object_mut())
208                else {
209                    continue;
210                };
211                let Some(id) = params.get("id").and_then(|value| value.as_str()) else {
212                    continue;
213                };
214                let id = id.to_string();
215                if let Some(pose) = session.pose_updates.get(&id) {
216                    params.insert("transform".into(), pose.clone());
217                }
218                if let Some(&fixed) = session.fixed_updates.get(&id) {
219                    params.insert("isFixed".into(), serde_json::Value::Bool(fixed));
220                }
221            }
222        }
223        Ok(())
224    })?;
225    Ok(document.to_string())
226}
227
228/// Overlay geometry for the viewport graphics lane: per enabled constraint,
229/// the resolved WORLD anchor points/directions/geometry classes (post-solve),
230/// the status, the evaluated value, and (multi-element types) the element
231/// role groups — `[{id, type, status, message, anchors, directions, geoms,
232/// value, unit, target, groups}]`. Constraints whose selections do not
233/// resolve emit status/message only (no anchors).
234#[wasm_bindgen]
235pub fn assembly_overlay_json() -> String {
236    SESSION.with(|session| {
237        let session = session.borrow();
238        let Some(session) = session.as_ref() else {
239            return serde_json::Value::Array(Vec::new()).to_string();
240        };
241        let env = Env::build(&session.expressions, &session.configurator)
242            .unwrap_or_else(Env::poisoned);
243        let rows: Vec<serde_json::Value> = session
244            .state
245            .constraints
246            .iter()
247            .filter(|entry| entry.enabled)
248            .map(|entry| overlay_row(entry, &session.scene, &env))
249            .collect();
250        serde_json::Value::Array(rows).to_string()
251    })
252}
253
254fn overlay_row(entry: &ConstraintEntry, scene: &SceneMap, env: &Env) -> serde_json::Value {
255    let mut row = serde_json::json!({
256        "id": entry.id(),
257        "type": entry.constraint_type,
258        "status": entry.status(),
259        "message": entry
260            .persistent("message")
261            .and_then(|value| value.as_str())
262            .unwrap_or(""),
263    });
264    let elements = entry.elements();
265    let resolved: Vec<_> = elements
266        .iter()
267        .filter_map(|name| mapping::resolve_element(scene, name).ok())
268        .collect();
269    if resolved.len() != elements.len() || resolved.is_empty() {
270        return row;
271    }
272    let object = row.as_object_mut().expect("row is an object");
273    object.insert(
274        "anchors".into(),
275        serde_json::Value::Array(
276            resolved
277                .iter()
278                .map(|element| {
279                    let p = element.world.representative_point();
280                    serde_json::json!([p.x, p.y, p.z])
281                })
282                .collect(),
283        ),
284    );
285    object.insert(
286        "directions".into(),
287        serde_json::Value::Array(
288            resolved
289                .iter()
290                .map(|element| match mapping::direction_of(&element.world) {
291                    Some(direction) => serde_json::json!([direction.x, direction.y, direction.z]),
292                    None => serde_json::Value::Null,
293                })
294                .collect(),
295        ),
296    );
297    // Per-element geometry class, aligned index-wise with anchors/directions —
298    // the render-side distance-arrow builder needs to identify the BASE PLANE
299    // (the perpendicular-foot construction); a direction alone is ambiguous
300    // (lines and circles carry one too).
301    object.insert(
302        "geoms".into(),
303        serde_json::Value::Array(
304            resolved
305                .iter()
306                .map(|element| serde_json::json!(geometry_tag(&element.world)))
307                .collect(),
308        ),
309    );
310    // Measured value/target — and the element ROLE groups a multi-element type
311    // inferred (center's `[width pair, tab]`) — via the mapper on a THROWAWAY
312    // clone (the mapper maintains the orientation-preference cache; an
313    // overlay read must not mutate persisted state).
314    // `fixed` has no mapper (it grounds a body; nothing to measure).
315    if entry.constraint_type == "fixed" {
316        return row;
317    }
318    let mut scratch = entry.clone();
319    if let Ok(mapped) = mapping::map_constraint(&mut scratch, &resolved, env) {
320        if let Some((value, unit)) = mapped.measured {
321            object.insert("value".into(), serde_json::json!(value));
322            object.insert("unit".into(), serde_json::json!(unit));
323        }
324        if let Some(target) = mapped.target {
325            object.insert("target".into(), serde_json::json!(target));
326        }
327        if !mapped.groups.is_empty() {
328            object.insert("groups".into(), serde_json::json!(mapped.groups));
329        }
330    }
331    row
332}
333
334/// The coarse geometry class of a resolved selection (the overlay row's
335/// `geoms` vocabulary — lowercase `SelectionGeometry` variant names).
336fn geometry_tag(geometry: &crate::SelectionGeometry) -> &'static str {
337    match geometry {
338        crate::SelectionGeometry::Plane { .. } => "plane",
339        crate::SelectionGeometry::Line { .. } => "line",
340        crate::SelectionGeometry::Axis { .. } => "axis",
341        crate::SelectionGeometry::Circle { .. } => "circle",
342        crate::SelectionGeometry::Sphere { .. } => "sphere",
343        crate::SelectionGeometry::Point { .. } => "point",
344    }
345}
346
347// ===========================================================================
348// Mutation surface (spec §6 scheduling: every mutation auto-solves)
349// ===========================================================================
350
351/// Add a constraint of `constraint_type` with the given `inputParams` JSON
352/// (elements etc.; `id` is minted from the type's short name + the persistent
353/// counter when absent). Auto-solves; returns `{id, report}`.
354#[wasm_bindgen]
355pub fn assembly_add_constraint_json(
356    constraint_type: &str,
357    params_json: &str,
358) -> Result<String, JsValue> {
359    add_constraint(constraint_type, params_json).map_err(|error| JsValue::from_str(&error))
360}
361
362fn add_constraint(constraint_type: &str, params_json: &str) -> Result<String, String> {
363    let def = constraints::constraint_type(constraint_type)
364        .ok_or_else(|| format!("Unknown constraint type: {constraint_type}"))?;
365    let mut params: serde_json::Value = serde_json::from_str(params_json)
366        .map_err(|error| format!("constraint params: {error}"))?;
367    if !params.is_object() {
368        return Err("constraint params must be a JSON object".to_string());
369    }
370    with_session(|session| {
371        let id = match params.get("id").and_then(|value| value.as_str()) {
372            Some(id) if !id.is_empty() => id.to_string(),
373            _ => {
374                session.state.id_counter += 1;
375                let id = format!("{}{}", def.short_name, session.state.id_counter);
376                params
377                    .as_object_mut()
378                    .expect("checked object above")
379                    .insert("id".into(), serde_json::Value::String(id.clone()));
380                id
381            }
382        };
383        session.state.constraints.push(ConstraintEntry {
384            constraint_type: constraint_type.to_string(),
385            input_params: params.clone(),
386            persistent_data: serde_json::Value::Object(serde_json::Map::new()),
387            enabled: true,
388            open: true,
389        });
390        let report = solve_session(session);
391        Ok(serde_json::json!({ "id": id, "report": report }).to_string())
392    })
393}
394
395/// Replace a constraint's `inputParams` (the dialog commit). Auto-solves;
396/// returns the solve report.
397#[wasm_bindgen]
398pub fn assembly_update_constraint_json(id: &str, params_json: &str) -> Result<String, JsValue> {
399    update_constraint(id, params_json).map_err(|error| JsValue::from_str(&error))
400}
401
402fn update_constraint(id: &str, params_json: &str) -> Result<String, String> {
403    let mut params: serde_json::Value = serde_json::from_str(params_json)
404        .map_err(|error| format!("constraint params: {error}"))?;
405    if !params.is_object() {
406        return Err("constraint params must be a JSON object".to_string());
407    }
408    if params.get("id").and_then(|value| value.as_str()).is_none() {
409        params
410            .as_object_mut()
411            .expect("checked object above")
412            .insert("id".into(), serde_json::Value::String(id.to_string()));
413    }
414    with_session(|session| {
415        let entry = find_entry(session, id)?;
416        entry.input_params = params.clone();
417        Ok(solve_session(session).to_string())
418    })
419}
420
421/// Delete a constraint. Auto-solves; returns the solve report.
422#[wasm_bindgen]
423pub fn assembly_remove_constraint_json(id: &str) -> Result<String, JsValue> {
424    remove_constraint(id).map_err(|error| JsValue::from_str(&error))
425}
426
427fn remove_constraint(id: &str) -> Result<String, String> {
428    with_session(|session| {
429        let index = find_index(session, id)?;
430        session.state.constraints.remove(index);
431        Ok(solve_session(session).to_string())
432    })
433}
434
435/// Enable/disable a constraint. Auto-solves; returns the solve report.
436#[wasm_bindgen]
437pub fn assembly_set_constraint_enabled_json(id: &str, enabled: bool) -> Result<String, JsValue> {
438    set_enabled(id, enabled).map_err(|error| JsValue::from_str(&error))
439}
440
441fn set_enabled(id: &str, enabled: bool) -> Result<String, String> {
442    with_session(|session| {
443        find_entry(session, id)?.enabled = enabled;
444        Ok(solve_session(session).to_string())
445    })
446}
447
448/// Persist a constraint row's dialog expansion state (view state — no solve).
449#[wasm_bindgen]
450pub fn assembly_set_constraint_open_json(id: &str, open: bool) -> Result<(), JsValue> {
451    with_session(|session| {
452        find_entry(session, id)?.open = open;
453        Ok(())
454    })
455    .map_err(|error| JsValue::from_str(&error))
456}
457
458/// Reorder a constraint to `index` (clamped). Auto-solves; returns the report.
459#[wasm_bindgen]
460pub fn assembly_move_constraint_json(id: &str, index: usize) -> Result<String, JsValue> {
461    move_constraint(id, index).map_err(|error| JsValue::from_str(&error))
462}
463
464fn move_constraint(id: &str, index: usize) -> Result<String, String> {
465    with_session(|session| {
466        let from = find_index(session, id)?;
467        let entry = session.state.constraints.remove(from);
468        let to = index.min(session.state.constraints.len());
469        session.state.constraints.insert(to, entry);
470        Ok(solve_session(session).to_string())
471    })
472}
473
474// ===========================================================================
475// Automatic inference (super::infer)
476// ===========================================================================
477
478/// The inferable constraint types, joined to the catalogue: `[{type, label,
479/// icon, longName, detects, defaultOn}]`. Session-free — the dialog can list
480/// what the button offers before any document is open.
481#[wasm_bindgen]
482pub fn assembly_inferable_types_json() -> String {
483    super::infer::inferable_types_json().to_string()
484}
485
486/// SCAN the live scene for constraints its component placement implies, without
487/// creating anything. `options_json` is [`super::infer::InferOptions`] (`{}` for
488/// the defaults). Never `Err`: a missing session or a bad options object comes
489/// back as `{ok: false, error}` — a `JsValue` error aborts a native build.
490#[wasm_bindgen]
491pub fn assembly_infer_constraints_json(options_json: &str) -> String {
492    match infer_scan(options_json) {
493        Ok(report) => report.to_string(),
494        Err(error) => refusal(&error),
495    }
496}
497
498/// Scan and CREATE: every accepted candidate becomes a constraint, then ONE
499/// solve runs for the whole batch (each inferred constraint is already
500/// satisfied at the pose it was read from, so a healthy assembly does not
501/// move). Returns `{ok, created: [id…], report, solve}`.
502#[wasm_bindgen]
503pub fn assembly_apply_inferred_constraints_json(options_json: &str) -> String {
504    match infer_apply(options_json) {
505        Ok(report) => report.to_string(),
506        Err(error) => refusal(&error),
507    }
508}
509
510fn refusal(error: &str) -> String {
511    serde_json::json!({ "ok": false, "error": error }).to_string()
512}
513
514fn infer_scan(options_json: &str) -> Result<serde_json::Value, String> {
515    let options = super::infer::InferOptions::parse(options_json)?;
516    with_session(|session| Ok(super::infer::scan(&session.state, &session.scene, &options).report()))
517}
518
519fn infer_apply(options_json: &str) -> Result<serde_json::Value, String> {
520    let options = super::infer::InferOptions::parse(options_json)?;
521    with_session(|session| {
522        let scan = super::infer::scan(&session.state, &session.scene, &options);
523        let report = scan.report();
524        let created = super::infer::apply(&mut session.state, &scan.candidates);
525        let solve = if created.is_empty() {
526            serde_json::Value::Null
527        } else {
528            solve_session(session)
529        };
530        Ok(serde_json::json!({
531            "ok": true,
532            "created": created,
533            "report": report,
534            "solve": solve,
535        }))
536    })
537}
538
539/// Manual solve (the panel's Solve button). Returns the solve report.
540#[wasm_bindgen]
541pub fn assembly_run_solve_json() -> Result<String, JsValue> {
542    with_session(|session| Ok(solve_session(session).to_string()))
543        .map_err(|error| JsValue::from_str(&error))
544}
545
546fn find_index(session: &Session, id: &str) -> Result<usize, String> {
547    session
548        .state
549        .constraints
550        .iter()
551        .position(|entry| entry.id() == id)
552        .ok_or_else(|| format!("unknown constraint '{id}'"))
553}
554
555fn find_entry<'a>(session: &'a mut Session, id: &str) -> Result<&'a mut ConstraintEntry, String> {
556    let index = find_index(session, id)?;
557    Ok(&mut session.state.constraints[index])
558}