1use std::collections::{HashMap, HashSet};
15
16use crate::pick::{front_face_at, point_view_depth, PickCandidate, PickKind, PickOptions};
17use crate::scene::RenderScene;
18use crate::view::{Projection, ViewCamera};
19
20const GRID_SAMPLES: f64 = 1600.0;
22const SAMPLES_PER_ENTITY: usize = 24;
24
25#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct ScreenBox {
28 pub x0: f64,
29 pub y0: f64,
30 pub x1: f64,
31 pub y1: f64,
32}
33
34impl ScreenBox {
35 pub fn from_drag(start: (f64, f64), end: (f64, f64)) -> Self {
38 Self { x0: start.0, y0: start.1, x1: end.0, y1: end.1 }
39 }
40
41 pub fn crossing(&self) -> bool {
43 self.x1 < self.x0
44 }
45
46 fn min_max(&self) -> (f64, f64, f64, f64) {
47 (self.x0.min(self.x1), self.y0.min(self.y1), self.x0.max(self.x1), self.y0.max(self.y1))
48 }
49
50 fn contains(&self, x: f64, y: f64) -> bool {
51 let (ax, ay, bx, by) = self.min_max();
52 x >= ax && x <= bx && y >= ay && y <= by
53 }
54}
55
56struct Probe<'a> {
57 scene: &'a RenderScene,
58 camera: &'a ViewCamera,
59 options: &'a PickOptions,
60 cache: HashMap<(i64, i64), Option<PickCandidate>>,
61}
62
63impl Probe<'_> {
64 fn front(&mut self, x: f64, y: f64) -> Option<PickCandidate> {
66 let key = (x.round() as i64, y.round() as i64);
67 if let Some(hit) = self.cache.get(&key) {
68 return hit.clone();
69 }
70 let hit = front_face_at(self.scene, self.camera, key.0 as f64, key.1 as f64, self.options);
71 self.cache.insert(key, hit.clone());
72 hit
73 }
74
75 fn slack(&self, depth: f64) -> f64 {
78 1e-4 * depth.abs().max(1.0) + self.camera.world_per_pixel() * 1.5
79 }
80
81 fn point_visible(&mut self, x: f64, y: f64, depth: f64) -> bool {
84 match self.front(x, y) {
85 None => true,
86 Some(front) => depth <= front.depth + self.slack(depth),
87 }
88 }
89}
90
91fn project(camera: &ViewCamera, p: [f64; 3]) -> Option<(f64, f64, f64)> {
93 let (x, y, depth) = camera.project(p);
94 if matches!(camera.projection, Projection::Perspective { .. }) && depth <= 1e-6 {
95 return None;
96 }
97 Some((x, y, depth))
98}
99
100fn f64s(p: [f32; 3]) -> [f64; 3] {
101 [p[0] as f64, p[1] as f64, p[2] as f64]
102}
103
104pub fn box_pick(scene: &RenderScene, camera: &ViewCamera, rect: ScreenBox, options: &PickOptions) -> Vec<PickCandidate> {
108 let crossing = rect.crossing();
109 let (ax, ay, bx, by) = rect.min_max();
110 let mut probe = Probe { scene, camera, options, cache: HashMap::new() };
111 let mut out: Vec<PickCandidate> = Vec::new();
112 if bx - ax < 1.0 && by - ay < 1.0 {
113 return out;
114 }
115
116 let mut touched_faces: HashSet<(String, String)> = HashSet::new();
119 let mut touched_solids: HashSet<String> = HashSet::new();
120 let step = (((bx - ax) * (by - ay)) / GRID_SAMPLES).sqrt().max(3.0);
121 let mut y = ay;
122 while y <= by {
123 let mut x = ax;
124 while x <= bx {
125 if let Some(hit) = probe.front(x, y) {
126 match hit.kind {
127 PickKind::Face => {
128 touched_solids.insert(hit.solid.clone());
129 touched_faces.insert((hit.solid, hit.name));
130 }
131 _ => {
132 touched_solids.insert(hit.solid);
133 }
134 }
135 }
136 x += step;
137 }
138 y += step;
139 }
140
141 for solid in scene.solids() {
142 if !solid.visible {
143 continue;
144 }
145 let positions = &solid.mesh.positions;
146 let indices = &solid.mesh.indices;
147 let mut solid_all_inside = true;
148 let mut solid_seen = touched_solids.contains(&solid.name);
149 let mut solid_depth = f64::INFINITY;
150
151 for (index, face) in solid.faces.iter().enumerate() {
153 if face.tri_count == 0 || !solid.visibility.is_face_visible(index) {
154 continue;
155 }
156 let start = face.tri_start as usize;
157 let end = (start + face.tri_count as usize).min(indices.len() / 3);
158 let mut all_inside = true;
159 let mut depth = f64::INFINITY;
160 let mut position = [0.0; 3];
161 for tri in start..end {
162 for k in 0..3 {
163 let p = f64s(positions[indices[tri * 3 + k] as usize]);
164 match project(camera, p) {
165 Some((sx, sy, d)) => {
166 if !rect.contains(sx, sy) {
167 all_inside = false;
168 }
169 if d < depth {
170 depth = d;
171 position = p;
172 }
173 }
174 None => all_inside = false,
175 }
176 }
177 }
178 if !all_inside {
179 solid_all_inside = false;
180 }
181 if !crossing && !all_inside {
182 continue;
183 }
184 let key = (solid.name.clone(), face.name.clone());
185 let mut visible = touched_faces.contains(&key);
186 if !visible {
187 let count = end.saturating_sub(start);
190 let stride = (count / SAMPLES_PER_ENTITY).max(1);
191 let mut tri = start;
192 while tri < end && !visible {
193 let c = (0..3).fold([0.0; 3], |acc, k| {
194 let p = f64s(positions[indices[tri * 3 + k] as usize]);
195 [acc[0] + p[0] / 3.0, acc[1] + p[1] / 3.0, acc[2] + p[2] / 3.0]
196 });
197 if let Some((sx, sy, _)) = project(camera, c) {
198 if rect.contains(sx, sy) {
199 visible = probe
200 .front(sx, sy)
201 .is_some_and(|hit| hit.kind == PickKind::Face && hit.solid == solid.name && hit.name == face.name);
202 }
203 }
204 tri += stride;
205 }
206 }
207 if visible {
208 solid_seen = true;
209 solid_depth = solid_depth.min(depth);
210 out.push(PickCandidate {
211 kind: PickKind::Face,
212 name: face.name.clone(),
213 solid: solid.name.clone(),
214 depth,
215 screen_dist: 0.0,
216 position,
217 });
218 }
219 }
220
221 for (index, edge) in solid.edges.iter().enumerate() {
223 if edge.aux || !solid.visibility.is_edge_visible(index) || edge.polyline.is_empty() {
224 continue;
225 }
226 let projected: Vec<Option<(f64, f64, f64)>> =
227 edge.polyline.iter().map(|p| project(camera, f64s(*p))).collect();
228 let all_inside = projected.iter().all(|p| p.is_some_and(|(x, y, _)| rect.contains(x, y)));
229 if !all_inside {
230 solid_all_inside = false;
231 }
232 if !crossing && !all_inside {
233 continue;
234 }
235 let mut samples: Vec<(f64, f64, f64, [f64; 3], bool)> = Vec::new();
238 let last_segment = edge.polyline.len().saturating_sub(2);
239 for (i, pair) in edge.polyline.windows(2).enumerate() {
240 let (Some(a), Some(b)) = (projected[i], projected[i + 1]) else { continue };
241 let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
242 let n = ((len / 4.0).ceil() as usize).clamp(1, 32);
243 let (pa, pb) = (f64s(pair[0]), f64s(pair[1]));
244 for j in 0..=n {
245 let t = j as f64 / n as f64;
246 let w = [pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t, pa[2] + (pb[2] - pa[2]) * t];
247 let (sx, sy) = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
248 if rect.contains(sx, sy) {
249 let end = (i == 0 && j == 0) || (i == last_segment && j == n);
250 samples.push((sx, sy, point_view_depth(camera, w), w, end));
251 }
252 }
253 }
254 if edge.polyline.len() == 1 {
255 if let Some((sx, sy, d)) = projected[0] {
256 if rect.contains(sx, sy) {
257 samples.push((sx, sy, d, f64s(edge.polyline[0]), true));
258 }
259 }
260 }
261 let inner: Vec<_> = samples.iter().filter(|s| !s.4).copied().collect();
266 let samples = if inner.is_empty() { samples } else { inner };
267 let stride = (samples.len() / SAMPLES_PER_ENTITY).max(1);
268 let hit = samples.iter().step_by(stride).find(|s| probe.point_visible(s.0, s.1, s.2)).copied();
269 if let Some((_, _, depth, position, _)) = hit {
270 solid_seen = true;
271 solid_depth = solid_depth.min(depth);
272 out.push(PickCandidate {
273 kind: PickKind::Edge,
274 name: edge.name.clone(),
275 solid: solid.name.clone(),
276 depth,
277 screen_dist: 0.0,
278 position,
279 });
280 }
281 }
282
283 for (index, vertex) in solid.vertices.iter().enumerate() {
285 if !solid.visibility.is_vertex_visible(index) {
286 continue;
287 }
288 let Some((sx, sy, depth)) = project(camera, vertex.position) else {
289 solid_all_inside = false;
290 continue;
291 };
292 if !rect.contains(sx, sy) {
293 solid_all_inside = false;
294 continue;
295 }
296 if probe.point_visible(sx, sy, depth) {
297 out.push(PickCandidate {
298 kind: PickKind::Vertex,
299 name: String::new(),
300 solid: solid.name.clone(),
301 depth,
302 screen_dist: 0.0,
303 position: vertex.position,
304 });
305 }
306 }
307
308 if solid_seen && (crossing || solid_all_inside) {
311 out.push(PickCandidate {
312 kind: PickKind::Solid,
313 name: solid.name.clone(),
314 solid: solid.name.clone(),
315 depth: if solid_depth.is_finite() { solid_depth } else { 0.0 },
316 screen_dist: 0.0,
317 position: [0.0; 3],
318 });
319 }
320 }
321 out
322}