1use crate::ui_kit;
16use crate::automation::hit_keys::HitKeyDoc;
17use crate::form_view::{form_view, FormViewSpec};
18use brep_render::draft_analysis::DraftClass;
19use brep_render::engine_state::{EngineState, RefSelectTarget};
20use brep_render::features::form_fields_from_schema;
21use eframe::egui;
22use serde_json::{json, Value};
23use std::collections::HashMap;
24
25pub fn schema() -> Value {
27 json!({
28 "inputParamsSchema": {
29 "pullDirection": {
30 "type": "reference_selection",
31 "selectionFilter": ["FACE", "PLANE", "EDGE", "DATUM"],
32 "multiple": false,
33 "default_value": null,
34 "label": "Pull direction",
35 "hint": "The direction the part leaves the mould. A flat face gives its outward normal, a datum plane its normal, a straight edge its direction. Empty: the last Draft feature's pull, else +Z."
36 },
37 "flipPull": {
38 "type": "boolean",
39 "default_value": false,
40 "label": "Flip pull",
41 "hint": "Reverse the pull direction."
42 },
43 "minAngle": {
44 "type": "number",
45 "step": 0.5,
46 "default_value": 1,
47 "label": "Minimum draft (°)",
48 "hint": "Faces drafted at least this much with the pull are positive, at least this much against it negative; less is Needs draft."
49 }
50 }
51 })
52}
53
54pub const SUBJECT: &str = "draftAnalysis";
56
57#[derive(Default)]
58pub struct DraftAnalysisWindow {
59 hits: HashMap<String, egui::Rect>,
61}
62
63pub static HIT_KEYS: &[HitKeyDoc] = &[
64 HitKeyDoc { panel: "draftAnalysis", prefix: "draftAnalysis:legend:", meaning: "a legend row: click selects that class's faces", command: None },
65 HitKeyDoc { panel: "draftAnalysis", prefix: "draftAnalysis:", meaning: "a Draft Analysis form field", command: Some("draft_analysis") },
66];
67
68impl DraftAnalysisWindow {
69 pub fn new() -> Self {
70 Self::default()
71 }
72
73 pub fn hits_json(&self) -> String {
74 crate::automation::hit_rects::hits_json(&self.hits)
75 }
76
77 pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState) {
78 self.hits.clear();
79 if !state.draft_analysis_active() {
80 return;
81 }
82 let mut open = true;
83 egui::Window::new("Draft Analysis")
84 .id(egui::Id::new("brep-draft-analysis-window"))
85 .open(&mut open)
86 .movable(true)
87 .resizable(true)
88 .default_size([340.0, 360.0])
89 .default_pos(super::below_chrome(ctx, 860.0, 0.0))
90 .show(ctx, |ui| {
91 egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| self.body(ui, state));
92 });
93 if !open {
94 if state.ref_select_field().is_some_and(|f| f.target == RefSelectTarget::DraftAnalysis) {
95 state.cancel_ref_select();
96 }
97 state.draft_analysis_close();
98 }
99 if let Some(text) = state.draft_analysis_hover_text() {
101 if let Some(pos) = ctx.pointer_hover_pos() {
102 egui::Area::new(egui::Id::new("brep-draft-analysis-hover"))
103 .order(egui::Order::Tooltip)
104 .fixed_pos(pos + egui::vec2(16.0, 16.0))
105 .interactable(false)
106 .show(ctx, |ui| {
107 egui::Frame::popup(ui.style()).show(ui, |ui| {
108 ui.label(text);
109 });
110 });
111 }
112 }
113 }
114
115 fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
116 let schema = schema();
117 let fields = form_fields_from_schema(&schema);
118 let mut params = state.draft_analysis_params();
119 let before = params.clone();
120 let picking = state.ref_select_field().filter(|f| f.target == RefSelectTarget::DraftAnalysis);
121 let read = state.draft_analysis_json();
122 let error = read["error"].as_str().map(str::to_string);
123 let banner_color = ui.visuals().error_fg_color;
124 let spec = FormViewSpec {
125 title: "Draft Analysis",
126 subtitle: Some("Display only: nothing is added to the model."),
127 fields: &fields,
128 hidden: None,
129 banner: error.as_deref().map(|text| crate::form_view::FormBanner::note(text, banner_color)),
130 trailing: None,
131 extra: None,
132 exit_label: "Close",
133 rollback: false,
134 hits_prefix: "draftAnalysis:",
135 read_only: None,
136 picking: picking.as_ref().map(|f| crate::form::ActivePick { path: &f.path, names: &f.names }),
137 };
138 let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
139 if let Some(activate) = out.ref_activate {
140 if state.ref_select_active() {
141 state.finish_ref_select();
142 }
143 state.begin_ref_select_for_draft_analysis(activate.path, activate.label, activate.filter, activate.seed);
144 }
145 if let Some(index) = out.pick_remove {
146 state.ref_select_remove(index);
147 }
148 if out.pick_done {
149 state.finish_ref_select();
150 }
151 if out.changed && params != before {
152 let pull = (params["pullDirection"] != before["pullDirection"]).then(|| first_name(¶ms["pullDirection"]));
153 let flip = params["flipPull"].as_bool();
154 let minimum = number(¶ms["minAngle"]);
155 if let Err(error) = state.draft_analysis_set(pull, flip, minimum) {
156 state.push_notice(format!("Draft Analysis: {error}"));
157 }
158 }
159 if out.exit_clicked {
160 state.draft_analysis_close();
161 return;
162 }
163 if picking.is_some() {
164 state.ref_select_claim();
165 }
166 ui.separator();
167 let pull = read["pull"].as_array().map(|p| p.iter().filter_map(Value::as_f64).collect::<Vec<_>>()).unwrap_or_default();
168 if error.is_none() && pull.len() == 3 {
169 ui.weak(format!(
170 "Pull ({:+.3}, {:+.3}, {:+.3}) {}",
171 pull[0],
172 pull[1],
173 pull[2],
174 read["pullSource"].as_str().unwrap_or_default()
175 ));
176 }
177 for class in DraftClass::ALL {
178 let count = read["counts"][class.key()].as_u64().unwrap_or(0);
179 let [r, g, b] = class.color().map(|v| (v * 255.0).round() as u8);
180 let row = ui.horizontal(|ui| {
181 let (rect, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), egui::Sense::hover());
182 ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(r, g, b));
183 ui.add(ui_kit::Button::ghost(&format!("{} {count}", class.label())))
184 });
185 let response = row.inner.on_hover_text("Select these faces");
186 self.hits.insert(format!("draftAnalysis:legend:{}", class.key()), response.rect);
187 if response.clicked() {
188 let faces = state.draft_analysis_faces_of(class);
189 state.set_selection(&[], &faces, &[], &[]);
190 }
191 }
192 ui.weak("A curved face is read at its mesh points; hover it to see its range.");
193 }
194}
195
196fn first_name(value: &Value) -> Option<String> {
197 match value {
198 Value::String(name) => Some(name.clone()),
199 Value::Array(names) => names.first().and_then(Value::as_str).map(str::to_string),
200 _ => None,
201 }
202 .filter(|name| !name.trim().is_empty())
203}
204
205fn number(value: &Value) -> Option<f64> {
206 value.as_f64().or_else(|| value.as_str().and_then(|s| s.trim().parse().ok()))
207}