use std::collections::{HashMap, HashSet};
use crate::pick::{front_face_at, point_view_depth, PickCandidate, PickKind, PickOptions};
use crate::scene::RenderScene;
use crate::view::{Projection, ViewCamera};
const GRID_SAMPLES: f64 = 1600.0;
const SAMPLES_PER_ENTITY: usize = 24;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenBox {
pub x0: f64,
pub y0: f64,
pub x1: f64,
pub y1: f64,
}
impl ScreenBox {
pub fn from_drag(start: (f64, f64), end: (f64, f64)) -> Self {
Self { x0: start.0, y0: start.1, x1: end.0, y1: end.1 }
}
pub fn crossing(&self) -> bool {
self.x1 < self.x0
}
fn min_max(&self) -> (f64, f64, f64, f64) {
(self.x0.min(self.x1), self.y0.min(self.y1), self.x0.max(self.x1), self.y0.max(self.y1))
}
fn contains(&self, x: f64, y: f64) -> bool {
let (ax, ay, bx, by) = self.min_max();
x >= ax && x <= bx && y >= ay && y <= by
}
}
struct Probe<'a> {
scene: &'a RenderScene,
camera: &'a ViewCamera,
options: &'a PickOptions,
cache: HashMap<(i64, i64), Option<PickCandidate>>,
}
impl Probe<'_> {
fn front(&mut self, x: f64, y: f64) -> Option<PickCandidate> {
let key = (x.round() as i64, y.round() as i64);
if let Some(hit) = self.cache.get(&key) {
return hit.clone();
}
let hit = front_face_at(self.scene, self.camera, key.0 as f64, key.1 as f64, self.options);
self.cache.insert(key, hit.clone());
hit
}
fn slack(&self, depth: f64) -> f64 {
1e-4 * depth.abs().max(1.0) + self.camera.world_per_pixel() * 1.5
}
fn point_visible(&mut self, x: f64, y: f64, depth: f64) -> bool {
match self.front(x, y) {
None => true,
Some(front) => depth <= front.depth + self.slack(depth),
}
}
}
fn project(camera: &ViewCamera, p: [f64; 3]) -> Option<(f64, f64, f64)> {
let (x, y, depth) = camera.project(p);
if matches!(camera.projection, Projection::Perspective { .. }) && depth <= 1e-6 {
return None;
}
Some((x, y, depth))
}
fn f64s(p: [f32; 3]) -> [f64; 3] {
[p[0] as f64, p[1] as f64, p[2] as f64]
}
pub fn box_pick(scene: &RenderScene, camera: &ViewCamera, rect: ScreenBox, options: &PickOptions) -> Vec<PickCandidate> {
let crossing = rect.crossing();
let (ax, ay, bx, by) = rect.min_max();
let mut probe = Probe { scene, camera, options, cache: HashMap::new() };
let mut out: Vec<PickCandidate> = Vec::new();
if bx - ax < 1.0 && by - ay < 1.0 {
return out;
}
let mut touched_faces: HashSet<(String, String)> = HashSet::new();
let mut touched_solids: HashSet<String> = HashSet::new();
let step = (((bx - ax) * (by - ay)) / GRID_SAMPLES).sqrt().max(3.0);
let mut y = ay;
while y <= by {
let mut x = ax;
while x <= bx {
if let Some(hit) = probe.front(x, y) {
match hit.kind {
PickKind::Face => {
touched_solids.insert(hit.solid.clone());
touched_faces.insert((hit.solid, hit.name));
}
_ => {
touched_solids.insert(hit.solid);
}
}
}
x += step;
}
y += step;
}
for solid in scene.solids() {
if !solid.visible {
continue;
}
let positions = &solid.mesh.positions;
let indices = &solid.mesh.indices;
let mut solid_all_inside = true;
let mut solid_seen = touched_solids.contains(&solid.name);
let mut solid_depth = f64::INFINITY;
for (index, face) in solid.faces.iter().enumerate() {
if face.tri_count == 0 || !solid.visibility.is_face_visible(index) {
continue;
}
let start = face.tri_start as usize;
let end = (start + face.tri_count as usize).min(indices.len() / 3);
let mut all_inside = true;
let mut depth = f64::INFINITY;
let mut position = [0.0; 3];
for tri in start..end {
for k in 0..3 {
let p = f64s(positions[indices[tri * 3 + k] as usize]);
match project(camera, p) {
Some((sx, sy, d)) => {
if !rect.contains(sx, sy) {
all_inside = false;
}
if d < depth {
depth = d;
position = p;
}
}
None => all_inside = false,
}
}
}
if !all_inside {
solid_all_inside = false;
}
if !crossing && !all_inside {
continue;
}
let key = (solid.name.clone(), face.name.clone());
let mut visible = touched_faces.contains(&key);
if !visible {
let count = end.saturating_sub(start);
let stride = (count / SAMPLES_PER_ENTITY).max(1);
let mut tri = start;
while tri < end && !visible {
let c = (0..3).fold([0.0; 3], |acc, k| {
let p = f64s(positions[indices[tri * 3 + k] as usize]);
[acc[0] + p[0] / 3.0, acc[1] + p[1] / 3.0, acc[2] + p[2] / 3.0]
});
if let Some((sx, sy, _)) = project(camera, c) {
if rect.contains(sx, sy) {
visible = probe
.front(sx, sy)
.is_some_and(|hit| hit.kind == PickKind::Face && hit.solid == solid.name && hit.name == face.name);
}
}
tri += stride;
}
}
if visible {
solid_seen = true;
solid_depth = solid_depth.min(depth);
out.push(PickCandidate {
kind: PickKind::Face,
name: face.name.clone(),
solid: solid.name.clone(),
depth,
screen_dist: 0.0,
position,
});
}
}
for (index, edge) in solid.edges.iter().enumerate() {
if edge.aux || !solid.visibility.is_edge_visible(index) || edge.polyline.is_empty() {
continue;
}
let projected: Vec<Option<(f64, f64, f64)>> =
edge.polyline.iter().map(|p| project(camera, f64s(*p))).collect();
let all_inside = projected.iter().all(|p| p.is_some_and(|(x, y, _)| rect.contains(x, y)));
if !all_inside {
solid_all_inside = false;
}
if !crossing && !all_inside {
continue;
}
let mut samples: Vec<(f64, f64, f64, [f64; 3], bool)> = Vec::new();
let last_segment = edge.polyline.len().saturating_sub(2);
for (i, pair) in edge.polyline.windows(2).enumerate() {
let (Some(a), Some(b)) = (projected[i], projected[i + 1]) else { continue };
let len = ((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt();
let n = ((len / 4.0).ceil() as usize).clamp(1, 32);
let (pa, pb) = (f64s(pair[0]), f64s(pair[1]));
for j in 0..=n {
let t = j as f64 / n as f64;
let w = [pa[0] + (pb[0] - pa[0]) * t, pa[1] + (pb[1] - pa[1]) * t, pa[2] + (pb[2] - pa[2]) * t];
let (sx, sy) = (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
if rect.contains(sx, sy) {
let end = (i == 0 && j == 0) || (i == last_segment && j == n);
samples.push((sx, sy, point_view_depth(camera, w), w, end));
}
}
}
if edge.polyline.len() == 1 {
if let Some((sx, sy, d)) = projected[0] {
if rect.contains(sx, sy) {
samples.push((sx, sy, d, f64s(edge.polyline[0]), true));
}
}
}
let inner: Vec<_> = samples.iter().filter(|s| !s.4).copied().collect();
let samples = if inner.is_empty() { samples } else { inner };
let stride = (samples.len() / SAMPLES_PER_ENTITY).max(1);
let hit = samples.iter().step_by(stride).find(|s| probe.point_visible(s.0, s.1, s.2)).copied();
if let Some((_, _, depth, position, _)) = hit {
solid_seen = true;
solid_depth = solid_depth.min(depth);
out.push(PickCandidate {
kind: PickKind::Edge,
name: edge.name.clone(),
solid: solid.name.clone(),
depth,
screen_dist: 0.0,
position,
});
}
}
for (index, vertex) in solid.vertices.iter().enumerate() {
if !solid.visibility.is_vertex_visible(index) {
continue;
}
let Some((sx, sy, depth)) = project(camera, vertex.position) else {
solid_all_inside = false;
continue;
};
if !rect.contains(sx, sy) {
solid_all_inside = false;
continue;
}
if probe.point_visible(sx, sy, depth) {
out.push(PickCandidate {
kind: PickKind::Vertex,
name: String::new(),
solid: solid.name.clone(),
depth,
screen_dist: 0.0,
position: vertex.position,
});
}
}
if solid_seen && (crossing || solid_all_inside) {
out.push(PickCandidate {
kind: PickKind::Solid,
name: solid.name.clone(),
solid: solid.name.clone(),
depth: if solid_depth.is_finite() { solid_depth } else { 0.0 },
screen_dist: 0.0,
position: [0.0; 3],
});
}
}
out
}