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