Skip to main content

brep_render/sketch/
solve.rs

1//! Solve wiring — call the kernel's 2D constraint solver in-process.
2//!
3//! `brep-render` links the kernel crate directly (a plain Rust path dependency,
4//! for BOTH native and the wasm canvas build), so the solver is reached by a
5//! direct `brep_kernel::solve_sketch(&SolveSketchRequest)` call on every
6//! target — there is NO wasm-bindgen JSON hop (that boundary only existed for the
7//! previous app calling INTO the wasm module from the browser; here the solver is
8//! compiled into the same binary/module). The solver is pure numeric Rust with no `std::time`,
9//! so it is wasm-clean.
10//!
11//! The solver returns `{sketch: {points, geometries, constraints, diagnostics}}`.
12//! We split that into the solved [`SketchDoc`] (the three editable arrays) and the
13//! read-only [`SketchDiagnostics`] the overlay coloring + DOF readout consume.
14
15use super::doc::{SketchDiagnostics, SketchDoc};
16use brep_kernel::{solve_sketch, solve_sketch_min_change, SolveSketchRequest};
17
18/// Whether a drag frame solves for the least motion from the previous frame
19/// (`BREP_SKETCH_DRAG_MIN_CHANGE=1`; OFF by default). The frame meets every
20/// constraint exactly while each line the drag does not hold by an end keeps its
21/// length, so a point held on a line with a free far end, or a line parallel to a
22/// fixed one, turns its line instead of stretching or collapsing it, and geometry
23/// the drag never forces stays where it was.
24pub fn drag_min_change() -> bool {
25    brep_kernel::switch!("BREP_SKETCH_DRAG_MIN_CHANGE", false)
26}
27
28/// User-tunable 2D solver knobs (the "Solver Settings" section), all optional
29/// — `None` keeps the kernel's default. Held on the [`super::SketchSession`] and
30/// read by every `resolve`, so a change re-solves with the new settings without
31/// threading params through each edit path.
32#[derive(Clone, Debug, PartialEq)]
33pub struct SketchSolverSettings {
34    /// Convergence tolerance (kernel default when `None`).
35    pub tolerance: Option<f64>,
36    /// Max solver iterations (defaults to 1000 when `None`).
37    pub iterations: Option<u32>,
38    /// Distance-slide threshold ratio (kernel default when `None`).
39    pub distance_slide_threshold_ratio: Option<f64>,
40    /// Distance-slide step ratio (kernel default when `None`).
41    pub distance_slide_step_ratio: Option<f64>,
42    /// Distance-slide minimum step (kernel default when `None`).
43    pub distance_slide_min_step: Option<f64>,
44}
45
46impl Default for SketchSolverSettings {
47    fn default() -> Self {
48        // All `None`/default → byte-identical to the historical hard-coded request
49        // (iterations 1000, everything else the kernel default), so an untouched
50        // solver behaves exactly as before this knob existed.
51        Self {
52            tolerance: None,
53            iterations: Some(1000),
54            distance_slide_threshold_ratio: None,
55            distance_slide_step_ratio: None,
56            distance_slide_min_step: None,
57        }
58    }
59}
60
61/// Solve `doc` and return the solved coordinates plus the constraint diagnostics.
62///
63/// `remove_implied_duplicates` is left off (the display path never edits
64/// constraints, so we keep every authored constraint) and the Newton polish is
65/// left on (`polish: None` → default true) so the displayed coordinates match
66/// what a committed feature-pipeline solve would produce.
67pub fn solve(doc: &SketchDoc) -> Result<(SketchDoc, SketchDiagnostics), String> {
68    solve_with(doc, &SketchSolverSettings::default())
69}
70
71/// Like [`solve`], but with user-tunable [`SketchSolverSettings`] (the Solver
72/// Settings panel). Default settings reproduce [`solve`] byte-for-byte.
73pub fn solve_with(
74    doc: &SketchDoc,
75    settings: &SketchSolverSettings,
76) -> Result<(SketchDoc, SketchDiagnostics), String> {
77    solve_entry(doc, settings, false)
78}
79
80/// Like [`solve_with`], for one interactive drag frame: the kernel's
81/// [`solve_sketch_min_change`] first moves the free points by the smallest step that
82/// meets every constraint, and relaxes as [`solve_with`] does only when it cannot.
83pub fn solve_drag_with(
84    doc: &SketchDoc,
85    settings: &SketchSolverSettings,
86) -> Result<(SketchDoc, SketchDiagnostics), String> {
87    solve_entry(doc, settings, true)
88}
89
90fn solve_entry(
91    doc: &SketchDoc,
92    settings: &SketchSolverSettings,
93    min_change: bool,
94) -> Result<(SketchDoc, SketchDiagnostics), String> {
95    let sketch = serde_json::to_value(doc).map_err(|e| format!("sketch serialize: {e}"))?;
96    let request = SolveSketchRequest {
97        sketch,
98        iterations: settings.iterations,
99        remove_implied_duplicates: false,
100        tolerance: settings.tolerance,
101        distance_slide_threshold_ratio: settings.distance_slide_threshold_ratio,
102        distance_slide_step_ratio: settings.distance_slide_step_ratio,
103        distance_slide_min_step: settings.distance_slide_min_step,
104        polish: None,
105    };
106
107    let response = if min_change {
108        solve_sketch_min_change(&request)?
109    } else {
110        solve_sketch(&request)?
111    };
112    let solved = response
113        .get("sketch")
114        .cloned()
115        .ok_or_else(|| "solve_sketch: response missing `sketch`".to_string())?;
116
117    let diagnostics = match solved.get("diagnostics").cloned() {
118        Some(value) => {
119            serde_json::from_value(value).map_err(|e| format!("diagnostics parse: {e}"))?
120        }
121        None => SketchDiagnostics::default(),
122    };
123    let solved_doc: SketchDoc =
124        serde_json::from_value(solved).map_err(|e| format!("solved sketch parse: {e}"))?;
125
126    Ok((solved_doc, diagnostics))
127}