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 lifecycle;
50pub(crate) mod mapping;
51pub(crate) mod constraints;
52
53pub use exports::{
54 assembly_add_constraint_json, assembly_apply_document_json, assembly_dof_json,
55 assembly_move_constraint_json, assembly_overlay_json, assembly_pose_updates_json,
56 assembly_remove_constraint_json, assembly_run_solve_json,
57 assembly_set_constraint_enabled_json, assembly_set_constraint_open_json,
58 assembly_state_json, assembly_statuses_json, assembly_update_constraint_json,
59};
60pub use constraints::{
61 constraint_schema_catalogue, constraint_type, ConstraintTypeDef, CONSTRAINT_TYPES,
62};
63// The pose write-back encoder (`mapping::transform_to_pose_params`): the ONE
64// matrix → `{translate, rotateEulerDeg}` (intrinsic XYZ, degrees) conversion,
65// re-exported so out-of-crate ACOMP authors reuse it instead of re-deriving
66// the Euler decomposition (and its gimbal-lock branch).
67pub use mapping::transform_to_pose_params;
68
69// ===========================================================================
70// The persisted state — spec §7, clean shape
71// ===========================================================================
72
73/// The document's `assembly` block: the ordered constraint list plus the
74/// persistent id counter (monotonic, never reused — mirrors the feature
75/// counter's contract).
76#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
77pub struct AssemblyState {
78 #[serde(default)]
79 pub constraints: Vec<ConstraintEntry>,
80 #[serde(default, rename = "idCounter")]
81 pub id_counter: u64,
82}
83
84/// One persisted constraint: `{ type, inputParams, persistentData, enabled,
85/// open }`. `inputParams` carries `id`, `elements` (selection ref strings) and
86/// the type-specific params; `persistentData` is the solver-state merge target
87/// (status/message/diagnostics/orientation cache).
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub struct ConstraintEntry {
90 #[serde(rename = "type")]
91 pub constraint_type: String,
92 #[serde(rename = "inputParams", default = "empty_object")]
93 pub input_params: serde_json::Value,
94 #[serde(rename = "persistentData", default = "empty_object")]
95 pub persistent_data: serde_json::Value,
96 #[serde(default = "default_true")]
97 pub enabled: bool,
98 #[serde(default)]
99 pub open: bool,
100}
101
102fn empty_object() -> serde_json::Value {
103 serde_json::Value::Object(serde_json::Map::new())
104}
105
106fn default_true() -> bool {
107 true
108}
109
110impl ConstraintEntry {
111 /// The constraint id (`inputParams.id`), empty when unset.
112 pub fn id(&self) -> &str {
113 self.input_params
114 .get("id")
115 .and_then(|value| value.as_str())
116 .unwrap_or("")
117 }
118
119 /// The selection refs (`inputParams.elements`), string entries only.
120 pub fn elements(&self) -> Vec<String> {
121 self.input_params
122 .get("elements")
123 .and_then(|value| value.as_array())
124 .map(|items| {
125 items
126 .iter()
127 .filter_map(|item| item.as_str())
128 .map(str::to_string)
129 .collect()
130 })
131 .unwrap_or_default()
132 }
133
134 /// A boolean param (absent → false).
135 pub fn flag(&self, key: &str) -> bool {
136 self.input_params
137 .get(key)
138 .and_then(|value| value.as_bool())
139 .unwrap_or(false)
140 }
141
142 /// A numeric param, expression-capable (a string evaluates against the
143 /// part's expression scope — requirements §3). Absent → `default`.
144 pub fn number(&self, key: &str, env: &Env, default: f64) -> Result<f64, String> {
145 match self.input_params.get(key) {
146 None | Some(serde_json::Value::Null) => Ok(default),
147 Some(serde_json::Value::Number(number)) => number
148 .as_f64()
149 .ok_or_else(|| format!("param `{key}` is not a finite number")),
150 Some(serde_json::Value::String(source)) => env
151 .eval(source)
152 .map_err(|error| format!("param `{key}`: {error}")),
153 Some(other) => Err(format!(
154 "param `{key}` must be a number or expression string, found {other}"
155 )),
156 }
157 }
158
159 /// Merge a key into `persistentData` (created as an object when missing).
160 pub fn set_persistent(&mut self, key: &str, value: serde_json::Value) {
161 if !self.persistent_data.is_object() {
162 self.persistent_data = empty_object();
163 }
164 if let Some(map) = self.persistent_data.as_object_mut() {
165 map.insert(key.to_string(), value);
166 }
167 }
168
169 /// Remove a key from `persistentData` (no-op when absent).
170 pub fn remove_persistent(&mut self, key: &str) {
171 if let Some(map) = self.persistent_data.as_object_mut() {
172 map.remove(key);
173 }
174 }
175
176 /// A `persistentData` field, if present.
177 pub fn persistent(&self, key: &str) -> Option<&serde_json::Value> {
178 self.persistent_data.get(key)
179 }
180
181 /// Set the run status vocabulary trio (`status`, `message`, `satisfied`)
182 /// and clear stale duplicate bookkeeping unless this IS a duplicate mark.
183 pub fn set_status(&mut self, status: &str, message: impl Into<String>, satisfied: bool) {
184 self.set_persistent("status", serde_json::Value::String(status.to_string()));
185 self.set_persistent("message", serde_json::Value::String(message.into()));
186 self.set_persistent("satisfied", serde_json::Value::Bool(satisfied));
187 if status != "duplicate" {
188 self.remove_persistent("duplicateConstraintIDs");
189 self.remove_persistent("duplicateSignature");
190 }
191 if status != "satisfied" && status != "adjusted" {
192 self.remove_persistent("error");
193 self.remove_persistent("kernel");
194 }
195 }
196
197 /// The current status word (empty when the constraint never ran).
198 pub fn status(&self) -> &str {
199 self.persistent("status")
200 .and_then(|value| value.as_str())
201 .unwrap_or("")
202 }
203}
204
205// ===========================================================================
206// History-tail hook (spec §6 scheduling: solve at the END of every run)
207// ===========================================================================
208
209/// Run the request's assembly constraints against the just-built scene and
210/// install the post-solve session the exported ABI serves (`exports`). Called
211/// unconditionally at the tail of [`crate::feature_pipeline::execute_history`]
212/// — a request without an `assembly` block installs an EMPTY session, so a
213/// document switch can never serve stale constraint state.
214pub(crate) fn finish_history_run(
215 request: &crate::feature_pipeline::HistoryRequest,
216 scene: &mut crate::feature_pipeline::SceneMap,
217 env: &Env,
218) {
219 let mut state = request.assembly.clone().unwrap_or_default();
220 let outcome = if state.constraints.is_empty() {
221 lifecycle::LifecycleOutcome::empty()
222 } else {
223 lifecycle::run_constraints(&mut state, scene, env)
224 };
225 exports::install_session(
226 state,
227 scene.clone(),
228 request.expressions.clone(),
229 request.configurator.clone(),
230 outcome,
231 );
232}
233
234#[cfg(test)]
235#[path = "assembly/tests.rs"]
236mod tests;