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 smallest change from the previous frame
19/// (`BREP_SKETCH_DRAG_MIN_CHANGE=1`; OFF by default). It was promoted and then set
20/// back to off: dragging a point held on a line whose far end is free, or a line
21/// parallel to a fixed one, the minimum-norm steps move free endpoints across the
22/// line, so over a long drag such a line grows several times its length or
23/// collapses, which is worse than the plain per-frame solve. It stays opt-in until
24/// the step keeps free line lengths and directions.
25pub fn drag_min_change() -> bool {
26    brep_kernel::switch!("BREP_SKETCH_DRAG_MIN_CHANGE", false)
27}
28
29/// User-tunable 2D solver knobs (the "Solver Settings" section), all optional
30/// — `None` keeps the kernel's default. Held on the [`super::SketchSession`] and
31/// read by every `resolve`, so a change re-solves with the new settings without
32/// threading params through each edit path.
33#[derive(Clone, Debug, PartialEq)]
34pub struct SketchSolverSettings {
35    /// Convergence tolerance (kernel default when `None`).
36    pub tolerance: Option<f64>,
37    /// Max solver iterations (defaults to 1000 when `None`).
38    pub iterations: Option<u32>,
39    /// Distance-slide threshold ratio (kernel default when `None`).
40    pub distance_slide_threshold_ratio: Option<f64>,
41    /// Distance-slide step ratio (kernel default when `None`).
42    pub distance_slide_step_ratio: Option<f64>,
43    /// Distance-slide minimum step (kernel default when `None`).
44    pub distance_slide_min_step: Option<f64>,
45}
46
47impl Default for SketchSolverSettings {
48    fn default() -> Self {
49        // All `None`/default → byte-identical to the historical hard-coded request
50        // (iterations 1000, everything else the kernel default), so an untouched
51        // solver behaves exactly as before this knob existed.
52        Self {
53            tolerance: None,
54            iterations: Some(1000),
55            distance_slide_threshold_ratio: None,
56            distance_slide_step_ratio: None,
57            distance_slide_min_step: None,
58        }
59    }
60}
61
62/// Solve `doc` and return the solved coordinates plus the constraint diagnostics.
63///
64/// `remove_implied_duplicates` is left off (the display path never edits
65/// constraints, so we keep every authored constraint) and the Newton polish is
66/// left on (`polish: None` → default true) so the displayed coordinates match
67/// what a committed feature-pipeline solve would produce.
68pub fn solve(doc: &SketchDoc) -> Result<(SketchDoc, SketchDiagnostics), String> {
69    solve_with(doc, &SketchSolverSettings::default())
70}
71
72/// Like [`solve`], but with user-tunable [`SketchSolverSettings`] (the Solver
73/// Settings panel). Default settings reproduce [`solve`] byte-for-byte.
74pub fn solve_with(
75    doc: &SketchDoc,
76    settings: &SketchSolverSettings,
77) -> Result<(SketchDoc, SketchDiagnostics), String> {
78    solve_entry(doc, settings, false)
79}
80
81/// Like [`solve_with`], for one interactive drag frame: the kernel's
82/// [`solve_sketch_min_change`] first moves the free points by the smallest step that
83/// meets every constraint, and relaxes as [`solve_with`] does only when it cannot.
84pub fn solve_drag_with(
85    doc: &SketchDoc,
86    settings: &SketchSolverSettings,
87) -> Result<(SketchDoc, SketchDiagnostics), String> {
88    solve_entry(doc, settings, true)
89}
90
91fn solve_entry(
92    doc: &SketchDoc,
93    settings: &SketchSolverSettings,
94    min_change: bool,
95) -> Result<(SketchDoc, SketchDiagnostics), String> {
96    let sketch = serde_json::to_value(doc).map_err(|e| format!("sketch serialize: {e}"))?;
97    let request = SolveSketchRequest {
98        sketch,
99        iterations: settings.iterations,
100        remove_implied_duplicates: false,
101        tolerance: settings.tolerance,
102        distance_slide_threshold_ratio: settings.distance_slide_threshold_ratio,
103        distance_slide_step_ratio: settings.distance_slide_step_ratio,
104        distance_slide_min_step: settings.distance_slide_min_step,
105        polish: None,
106    };
107
108    let response = if min_change {
109        solve_sketch_min_change(&request)?
110    } else {
111        solve_sketch(&request)?
112    };
113    let solved = response
114        .get("sketch")
115        .cloned()
116        .ok_or_else(|| "solve_sketch: response missing `sketch`".to_string())?;
117
118    let diagnostics = match solved.get("diagnostics").cloned() {
119        Some(value) => {
120            serde_json::from_value(value).map_err(|e| format!("diagnostics parse: {e}"))?
121        }
122        None => SketchDiagnostics::default(),
123    };
124    let solved_doc: SketchDoc =
125        serde_json::from_value(solved).map_err(|e| format!("solved sketch parse: {e}"))?;
126
127    Ok((solved_doc, diagnostics))
128}