BREP_app 0.3.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! An isolated, disposable reconstruction session. Accept transfers the exact
//! previewed STEP into the destination document as one ordinary import feature.
use brep_render::engine_state::EngineState;
use brep_render::runner::{
    ConversionPolicy, MeshImportFormat, StlConversionOptions, StlConversionOutput,
};
use eframe::egui;
use std::collections::BTreeMap;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PreviewAction {
    None,
    Accept,
    Cancel,
}

pub struct StlImportPreview {
    pub destination: u64,
    name: String,
    bytes: Vec<u8>,
    pub engine: EngineState,
    options: StlConversionOptions,
    revision: u64,
    pending: Option<(u64, u64)>,
    result: Option<(u64, StlConversionOutput)>,
    error: Option<String>,
    scene_changed: bool,
    hits: BTreeMap<String, [f32; 4]>,
}

impl StlImportPreview {
    pub fn new(destination: u64, name: String, bytes: Vec<u8>, mut engine: EngineState) -> Self {
        engine.settings.wireframe = false;
        let mut preview = Self {
            destination,
            name,
            bytes,
            engine,
            options: Default::default(),
            revision: 0,
            pending: None,
            result: None,
            error: None,
            scene_changed: true,
            hits: BTreeMap::new(),
        };
        preview.rebuild();
        preview
    }

    fn busy(&self) -> bool {
        self.pending.is_some() || self.engine.run_pending()
    }

    pub fn ready(&self) -> bool {
        !self.busy()
            && self.error.is_none()
            && self
                .result
                .as_ref()
                .is_some_and(|(revision, _)| *revision == self.revision)
            && !self.engine.scene.solids().is_empty()
    }

    pub fn step_text(&self) -> Option<&str> {
        self.ready()
            .then(|| self.result.as_ref().unwrap().1.step_text.as_str())
    }

    pub fn accept_into(
        &self,
        destination_id: u64,
        destination: &mut EngineState,
    ) -> Result<(), String> {
        if destination_id != self.destination {
            return Err(
                "The destination document changed; cancel this preview and import again.".into(),
            );
        }
        let step = self
            .step_text()
            .ok_or("Update the preview before accepting the import.")?;
        destination.import_step_feature(step).map(|_| ())
    }

    fn rebuild(&mut self) {
        if self.busy() {
            return;
        }
        self.error = None;
        match self.engine.reconstruct_mesh_preview(
            MeshImportFormat::Stl,
            self.bytes.clone(),
            self.options.clone(),
        ) {
            Ok(id) => self.pending = Some((id, self.revision)),
            Err(error) => self.error = Some(error),
        }
    }

    fn pump(&mut self) {
        self.engine.pump();
        while let Some(reply) = self.engine.take_mesh_preview() {
            let Some((id, revision)) = self.pending else {
                continue;
            };
            if reply.id != id {
                continue;
            }
            self.pending = None;
            match reply.result {
                Ok(output) => {
                    let document = serde_json::json!({
                        "features": [{"type": "IMPORT3D", "inputParams": {
                            "id": "IMPORT3D1", "stepText": output.step_text
                        }}], "featureCounter": 1
                    });
                    match self.engine.load_model_and_fit(&document.to_string()) {
                        Ok(_) => {
                            self.result = Some((revision, output));
                            self.scene_changed = true;
                        }
                        Err(error) => self.error = Some(error),
                    }
                }
                Err(error) => self.error = Some(error),
            }
        }
        if !self.busy()
            && self.result.is_some()
            && self.engine.scene.solids().is_empty()
            && self.error.is_none()
        {
            self.error = Some("The reconstructed BREP could not be displayed. Adjust the settings and update the preview.".into());
        }
    }

    fn hit(&mut self, key: &str, response: &egui::Response) {
        let r = response.rect;
        self.hits
            .insert(key.into(), [r.min.x, r.min.y, r.width(), r.height()]);
    }

    pub fn show(
        &mut self,
        ui: &mut egui::Ui,
        viewport: &mut crate::viewport::Viewport,
    ) -> PreviewAction {
        self.pump();
        self.hits.clear();
        let mut action = PreviewAction::None;
        egui::containers::panel::Panel::left("stl-preview-settings")
            .resizable(true)
            .default_size(350.0)
            .size_range(300.0..=550.0)
            .show(ui, |ui| {
                egui::ScrollArea::vertical().show(ui, |ui| {
                    action = self.controls(ui);
                });
            });
        if self.scene_changed {
            viewport.forget_document();
            self.scene_changed = false;
        }
        viewport.show(ui, &mut self.engine);
        if self.busy() {
            ui.ctx().request_repaint();
        }
        if ui
            .ctx()
            .input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape))
        {
            action = PreviewAction::Cancel;
        }
        action
    }

    fn controls(&mut self, ui: &mut egui::Ui) -> PreviewAction {
        ui.heading("STL import preview");
        ui.label(&self.name);
        ui.weak("Orbit and zoom to inspect the reconstructed BREP. Distances are in mm.");
        ui.separator();
        let mut changed = false;
        egui::Grid::new("stl-tolerances").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| {
            changed |= number(ui, &mut self.hits, "distance", "Surface distance", &mut self.options.recognition.distance_tolerance, 1e-12..=1e6, 1e-6,
                "Maximum absolute distance from mesh samples to a recognized surface. Binary STL coordinate precision sets a minimum.");
            changed |= number(ui, &mut self.hits, "relative", "Relative distance", &mut self.options.recognition.relative_tolerance, 0.0..=1.0, 1e-8,
                "Additional recognition tolerance relative to the model size.");
            let mut normal = self.options.recognition.normal_tolerance.to_degrees();
            if number(ui, &mut self.hits, "normal", "Normal angle (°)", &mut normal, 0.01..=89.0, 0.1,
                "Maximum angle between a recognized surface normal and the mesh normal.") {
                self.options.recognition.normal_tolerance = normal.to_radians(); changed = true;
            }
            let mut feature = self.options.recognition.feature_angle.to_degrees();
            if number(ui, &mut self.hits, "feature", "Feature angle (°)", &mut feature, 0.1..=89.0, 0.1,
                "Edges sharper than this angle split surface regions during recognition and BREP reconstruction.") {
                self.options.recognition.feature_angle = feature.to_radians();
                self.options.kernel_deflection_angle_degrees = feature; changed = true;
            }
            changed |= number(ui, &mut self.hits, "fit", "BREP relative fit", &mut self.options.kernel_fit_tolerance, 1e-12..=0.1, 1e-5,
                "Surface fitting tolerance for BREP reconstruction, relative to the bounding-box diagonal. Shared boundaries must also pass stricter geometry checks.");
            changed |= number(ui, &mut self.hits, "brepNormal", "BREP normal angle (°)", &mut self.options.kernel_normal_tolerance_degrees, 0.01..=89.0, 0.1,
                "Normal agreement required when grouping mesh triangles into BREP faces.");
        });
        ui.add_space(8.0);
        let mut auto_weld = self.options.weld_tolerance < 0.0;
        let auto = ui.checkbox(&mut auto_weld, "Automatic vertex weld tolerance");
        self.hit("autoWeld", &auto);
        if auto.changed() {
            self.options.weld_tolerance = if auto_weld { -1.0 } else { 1e-6 };
            changed = true;
        }
        if !auto_weld {
            egui::Grid::new("stl-weld").num_columns(2).show(ui, |ui| {
                changed |= number(ui, &mut self.hits, "weld", "Vertex weld distance", &mut self.options.weld_tolerance, 0.0..=1e3, 1e-6,
                    "Merge vertices closer than this distance. Zero merges identical coordinates only.");
            });
        }
        let mut strict = self.options.policy == ConversionPolicy::RequireFullyAnalytic;
        let response = ui
            .checkbox(&mut strict, "Require fully analytic surfaces")
            .on_hover_text("Reject reconstruction if any region must remain faceted.");
        self.hit("strict", &response);
        if response.changed() {
            self.options.policy = if strict {
                ConversionPolicy::RequireFullyAnalytic
            } else {
                ConversionPolicy::AllowFacetedFallback
            };
            changed = true;
        }
        let reset = ui.button("Reset tolerances");
        self.hit("reset", &reset);
        if reset.clicked() {
            self.options = Default::default();
            changed = true;
        }
        if changed {
            self.revision += 1;
        }
        ui.separator();
        let update = ui.add_enabled(!self.busy(), egui::Button::new("Update preview"));
        self.hit("update", &update);
        if update.clicked() {
            self.rebuild();
        }
        if self.busy() {
            ui.horizontal(|ui| {
                ui.spinner();
                ui.label("Reconstructing BREP…");
            });
        }
        if self
            .result
            .as_ref()
            .is_some_and(|(revision, _)| *revision != self.revision)
        {
            ui.colored_label(
                ui.visuals().warn_fg_color,
                "Settings changed — update the preview before accepting.",
            );
        }
        if let Some(error) = &self.error {
            ui.colored_label(ui.visuals().error_fg_color, error);
        }
        if let Some((_, output)) = &self.result {
            let report = &output.report;
            ui.add_space(8.0);
            ui.label(format!(
                "{} BREP faces · {} solid(s)",
                report.exported_advanced_faces, report.roundtrip_solids
            ));
            let cylinders = output.step_text.matches("CYLINDRICAL_SURFACE(").count();
            let cones = output.step_text.matches("CONICAL_SURFACE(").count();
            ui.label(format!(
                "{cylinders} cylindrical · {cones} conical surfaces"
            ));
            let facets = report
                .hybrid_rebuild
                .map(|r| r.faceted_faces)
                .or(report.faceted_faces_after_merge)
                .unwrap_or(0);
            if facets > 0 {
                ui.colored_label(
                    ui.visuals().warn_fg_color,
                    format!("{facets} faces remain faceted"),
                );
            }
            ui.weak(format!(
                "Effective surface distance: {:.3e} mm",
                report.effective_distance_tolerance
            ));
            ui.collapsing("Reconstruction details", |ui| {
                ui.label(&report.backend_reason);
                ui.label(format!(
                    "{} input triangles · {} unresolved",
                    report.input_triangles, report.unresolved_triangles
                ));
                ui.label(format!(
                    "Completed in {:.2} seconds",
                    report.timings.total_seconds
                ));
                for message in &report.messages {
                    ui.label(message);
                }
            });
        }
        ui.separator();
        ui.checkbox(&mut self.engine.settings.wireframe, "Wireframe preview");
        if ui.button("Fit preview to view").clicked() {
            self.engine.zoom_to_fit();
        }
        ui.add_space(8.0);
        let mut action = PreviewAction::None;
        ui.horizontal(|ui| {
            let accept = ui.add_enabled(self.ready(), egui::Button::new("Accept import"));
            self.hit("accept", &accept);
            if accept.clicked() {
                action = PreviewAction::Accept;
            }
            let cancel = ui.button("Cancel");
            self.hit("cancel", &cancel);
            if cancel.clicked() {
                action = PreviewAction::Cancel;
            }
        });
        action
    }

    pub fn state_json(&self) -> String {
        serde_json::json!({"name": self.name, "ready": self.ready(), "busy": self.busy(),
            "revision": self.revision, "previewRevision": self.result.as_ref().map(|(r, _)| r),
            "error": self.error, "options": self.options, "solidCount": self.engine.scene.solids().len(),
            "faces": self.result.as_ref().map(|(_, r)| r.report.exported_advanced_faces)
        }).to_string()
    }
    pub fn hits_json(&self) -> String {
        serde_json::to_string(&self.hits).unwrap()
    }
}

fn number(
    ui: &mut egui::Ui,
    hits: &mut BTreeMap<String, [f32; 4]>,
    key: &str,
    label: &str,
    value: &mut f64,
    range: std::ops::RangeInclusive<f64>,
    speed: f64,
    help: &str,
) -> bool {
    ui.label(label).on_hover_text(help);
    let response = ui
        .add(
            egui::DragValue::new(value)
                .range(range)
                .speed(speed)
                .max_decimals(12),
        )
        .on_hover_text(help);
    let r = response.rect;
    hits.insert(key.into(), [r.min.x, r.min.y, r.width(), r.height()]);
    ui.end_row();
    response.changed()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn bore() -> Vec<u8> {
        include_bytes!("../../../tests/fixtures/stl/caddev-d2877f90-bore.stl").to_vec()
    }

    #[test]
    fn preview_is_isolated_and_accepts_the_exact_result_as_one_undoable_feature() {
        let mut destination = EngineState::new();
        let original = destination.history_request_json();
        let mut preview = StlImportPreview::new(7, "bore.stl".into(), bore(), EngineState::new());
        assert!(!preview.ready());
        preview.pump();
        assert!(preview.ready(), "{}", preview.state_json());
        assert_eq!(destination.history_request_json(), original);
        assert_eq!(
            preview
                .result
                .as_ref()
                .unwrap()
                .1
                .report
                .exported_advanced_faces,
            4
        );
        let step = preview.step_text().unwrap().to_owned();
        assert!(preview.accept_into(8, &mut destination).is_err());
        assert_eq!(destination.history_request_json(), original);
        preview.accept_into(7, &mut destination).unwrap();
        assert_eq!(destination.history_len(), 1);
        let history: serde_json::Value =
            serde_json::from_str(&destination.history_request_json()).unwrap();
        assert_eq!(history["features"][0]["inputParams"]["stepText"], step);
        destination.undo();
        assert!(destination.scene.solids().is_empty());
    }

    #[test]
    fn edited_settings_block_acceptance_until_the_new_result_is_displayed() {
        let mut preview = StlImportPreview::new(7, "bore.stl".into(), bore(), EngineState::new());
        // The submitted result has already reached the inline runner, but the
        // user edits before it is consumed. It must remain visibly outdated.
        preview.options.recognition.distance_tolerance = 1e-4;
        preview.revision += 1;
        preview.pump();
        assert!(!preview.ready());
        let mut destination = EngineState::new();
        assert!(preview.accept_into(7, &mut destination).is_err());
        assert_eq!(destination.history_len(), 0);
        preview.rebuild();
        preview.pump();
        assert!(preview.ready(), "{}", preview.state_json());
        assert_eq!(
            preview
                .result
                .as_ref()
                .unwrap()
                .1
                .report
                .requested_distance_tolerance,
            1e-4
        );
    }

    #[test]
    fn failed_reconstruction_cannot_be_accepted() {
        let mut preview =
            StlImportPreview::new(7, "bad.stl".into(), vec![0, 1, 2], EngineState::new());
        preview.pump();
        assert!(!preview.ready());
        assert!(preview.error.is_some());
        let mut destination = EngineState::new();
        assert!(preview.accept_into(7, &mut destination).is_err());
        assert_eq!(destination.history_len(), 0);
    }
}