brep_kernel/feature_pipeline/assembly.rs
1//! Assembly constraint state, lifecycle, and solver mapping — build-spec §4,
2//! §6, §7 (Wave-2 lane E).
3//!
4//! # The `assembly` block (spec §7)
5//!
6//! Constraints are kernel history state: a top-level `assembly` block on the
7//! history request — `{ constraints: [ { type, inputParams, persistentData,
8//! enabled, open } ], idCounter }` — that round-trips through the saved
9//! document. The pre-purge envelope keys (`assemblyConstraints` /
10//! `assemblyConstraintIdCounter`) are NOT read (no-backwards-compat).
11//!
12//! # Lifecycle (spec §6), run at the tail of every history execution
13//!
14//! 1. VALIDATE ([`lifecycle`]): disabled → `status:'disabled'`; unknown type →
15//! an error entry without aborting the rest; duplicate detection across the
16//! overlapping family {touch_align, distance, angle, concentric,
17//! perpendicular, tangent} via order-independent selection-pair signatures.
18//! 2. MAP ([`mapping`]): each element ref resolves through
19//! `solvers/assembly_resolve` to an analytic frame in the owning component's
20//! LOCAL space; constraints become [`crate::MateKind`] mates per the spec §4
21//! table. Unresolvable/unsupported selections fail that constraint only
22//! (status from [`crate::ResolveError::status`]); the solve continues.
23//! 3. SOLVE: ONE [`crate::solve_assembly`] call over every mapped constraint;
24//! per-mate residuals/statuses + solver diagnostics merge into each
25//! constraint's `persistentData`; distance/angle first-solve initialization
26//! commits into `inputParams` only on success.
27//! 4. WRITE BACK: solved poses re-pose the scene components in place
28//! ([`crate::feature_pipeline::component`]) and are exported as generic
29//! `inputParams.transform` JSON updates for the owning ACOMP features (the
30//! pose-authority contract; applied by [`assembly_apply_document_json`] with
31//! no compile-time dependency on the ACOMP feature).
32//!
33//! # Pose self-consistency (why an unapplied write-back cannot corrupt)
34//!
35//! Mate-local frames are computed as `record.transform⁻¹ · world_frame`, and
36//! each body's solver pose IS `record.transform` — so even when the record's
37//! absolute pose is stale (the app has not yet folded a pose update back into
38//! the ACOMP feature), the solve is self-consistent: reconstructed world frames
39//! equal the actual world geometry, satisfied constraints produce no motion,
40//! and a re-executed component simply re-solves to the same poses. The
41//! write-back matters for PERSISTENCE (save/load) and cache fingerprints, not
42//! for per-run geometric correctness.
43
44use serde::{Deserialize, Serialize};
45
46use crate::feature_pipeline::Env;
47
48pub(crate) mod exports;
49pub(crate) mod infer;
50pub(crate) mod lifecycle;
51pub(crate) mod mapping;
52pub(crate) mod constraints;
53
54pub use exports::{
55 assembly_add_constraint_json, assembly_apply_document_json,
56 assembly_apply_inferred_constraints_json, assembly_dof_json,
57 assembly_infer_constraints_json, assembly_inferable_types_json,
58 assembly_move_constraint_json, assembly_overlay_json, assembly_pose_updates_json,
59 assembly_remove_constraint_json, assembly_run_solve_json,
60 assembly_set_constraint_enabled_json, assembly_set_constraint_open_json,
61 assembly_state_json, assembly_statuses_json, assembly_update_constraint_json,
62 // The native doors: the same mutations with their errors as text. A native
63 // caller must use these — a `JsValue` error aborts a native build.
64 assembly_add_constraint_impl, assembly_apply_document_impl, assembly_move_constraint_impl,
65 assembly_remove_constraint_impl, assembly_run_solve_impl,
66 assembly_set_constraint_enabled_impl, assembly_set_constraint_open_impl,
67 assembly_update_constraint_impl,
68};
69pub use constraints::{
70 constraint_schema_catalogue, constraint_type, ConstraintTypeDef, CONSTRAINT_TYPES,
71};
72// The pose write-back encoder (`mapping::transform_to_pose_params`): the ONE
73// matrix → `{translate, rotateEulerDeg}` (intrinsic XYZ, degrees) conversion,
74// re-exported so out-of-crate ACOMP authors reuse it instead of re-deriving
75// the Euler decomposition (and its gimbal-lock branch).
76pub use mapping::transform_to_pose_params;
77
78// ===========================================================================
79// The persisted state — spec §7, clean shape
80// ===========================================================================
81
82/// The document's `assembly` block: the ordered constraint list plus the
83/// persistent id counter (monotonic, never reused — mirrors the feature
84/// counter's contract).
85#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
86pub struct AssemblyState {
87 #[serde(default)]
88 pub constraints: Vec<ConstraintEntry>,
89 #[serde(default, rename = "idCounter")]
90 pub id_counter: u64,
91}
92
93/// One persisted constraint: `{ type, inputParams, persistentData, enabled,
94/// open }`. `inputParams` carries `id`, `elements` (selection ref strings) and
95/// the type-specific params; `persistentData` is the solver-state merge target
96/// (status/message/diagnostics/orientation cache).
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98pub struct ConstraintEntry {
99 #[serde(rename = "type")]
100 pub constraint_type: String,
101 #[serde(rename = "inputParams", default = "empty_object")]
102 pub input_params: serde_json::Value,
103 #[serde(rename = "persistentData", default = "empty_object")]
104 pub persistent_data: serde_json::Value,
105 #[serde(default = "default_true")]
106 pub enabled: bool,
107 #[serde(default)]
108 pub open: bool,
109}
110
111fn empty_object() -> serde_json::Value {
112 serde_json::Value::Object(serde_json::Map::new())
113}
114
115fn default_true() -> bool {
116 true
117}
118
119impl ConstraintEntry {
120 /// The constraint id (`inputParams.id`), empty when unset.
121 pub fn id(&self) -> &str {
122 self.input_params
123 .get("id")
124 .and_then(|value| value.as_str())
125 .unwrap_or("")
126 }
127
128 /// The selection refs (`inputParams.elements`), string entries only.
129 pub fn elements(&self) -> Vec<String> {
130 self.input_params
131 .get("elements")
132 .and_then(|value| value.as_array())
133 .map(|items| {
134 items
135 .iter()
136 .filter_map(|item| item.as_str())
137 .map(str::to_string)
138 .collect()
139 })
140 .unwrap_or_default()
141 }
142
143 /// A boolean param (absent → false).
144 pub fn flag(&self, key: &str) -> bool {
145 self.input_params
146 .get(key)
147 .and_then(|value| value.as_bool())
148 .unwrap_or(false)
149 }
150
151 /// A numeric param, expression-capable (a string evaluates against the
152 /// part's expression scope — requirements §3). Absent → `default`.
153 pub fn number(&self, key: &str, env: &Env, default: f64) -> Result<f64, String> {
154 match self.input_params.get(key) {
155 None | Some(serde_json::Value::Null) => Ok(default),
156 Some(serde_json::Value::Number(number)) => number
157 .as_f64()
158 .ok_or_else(|| format!("param `{key}` is not a finite number")),
159 Some(serde_json::Value::String(source)) => env
160 .eval(source)
161 .map_err(|error| format!("param `{key}`: {error}")),
162 Some(other) => Err(format!(
163 "param `{key}` must be a number or expression string, found {other}"
164 )),
165 }
166 }
167
168 /// Merge a key into `persistentData` (created as an object when missing).
169 pub fn set_persistent(&mut self, key: &str, value: serde_json::Value) {
170 if !self.persistent_data.is_object() {
171 self.persistent_data = empty_object();
172 }
173 if let Some(map) = self.persistent_data.as_object_mut() {
174 map.insert(key.to_string(), value);
175 }
176 }
177
178 /// Remove a key from `persistentData` (no-op when absent).
179 pub fn remove_persistent(&mut self, key: &str) {
180 if let Some(map) = self.persistent_data.as_object_mut() {
181 map.remove(key);
182 }
183 }
184
185 /// A `persistentData` field, if present.
186 pub fn persistent(&self, key: &str) -> Option<&serde_json::Value> {
187 self.persistent_data.get(key)
188 }
189
190 /// Set the run status vocabulary trio (`status`, `message`, `satisfied`)
191 /// and clear stale duplicate bookkeeping unless this IS a duplicate mark.
192 pub fn set_status(&mut self, status: &str, message: impl Into<String>, satisfied: bool) {
193 self.set_persistent("status", serde_json::Value::String(status.to_string()));
194 self.set_persistent("message", serde_json::Value::String(message.into()));
195 self.set_persistent("satisfied", serde_json::Value::Bool(satisfied));
196 if status != "duplicate" {
197 self.remove_persistent("duplicateConstraintIDs");
198 self.remove_persistent("duplicateSignature");
199 }
200 if status != "satisfied" && status != "adjusted" {
201 self.remove_persistent("error");
202 self.remove_persistent("kernel");
203 }
204 }
205
206 /// The current status word (empty when the constraint never ran).
207 pub fn status(&self) -> &str {
208 self.persistent("status")
209 .and_then(|value| value.as_str())
210 .unwrap_or("")
211 }
212}
213
214// ===========================================================================
215// History-tail hook (spec §6 scheduling: solve at the END of every run)
216// ===========================================================================
217
218/// Run the request's assembly constraints against the just-built scene and
219/// install the post-solve session the exported ABI serves (`exports`). Called
220/// unconditionally at the tail of [`crate::feature_pipeline::execute_history`]
221/// — a request without an `assembly` block installs an EMPTY session, so a
222/// document switch can never serve stale constraint state.
223pub(crate) fn finish_history_run(
224 request: &crate::feature_pipeline::HistoryRequest,
225 scene: &mut crate::feature_pipeline::SceneMap,
226 env: &Env,
227) {
228 let mut state = request.assembly.clone().unwrap_or_default();
229 let outcome = if state.constraints.is_empty() {
230 lifecycle::LifecycleOutcome::empty()
231 } else {
232 lifecycle::run_constraints(&mut state, scene, env)
233 };
234 exports::install_session(
235 state,
236 scene.clone(),
237 request.expressions.clone(),
238 request.configurator.clone(),
239 outcome,
240 );
241}
242