Skip to main content

brep_render/
pick.rs

1//! Picking in Rust (R23/R24), replacing the retired raycaster +
2//! `selectionMethods._pickAtEvent`: returns KERNEL NAMES with the candidate
3//! priority order VERTEX > EDGE > FACE > … > SOLID, CSS-pixel thresholds for
4//! lines/points (the earlier picker's `worldPerPixel * 6` is exactly 6 CSS px), a
5//! double-sided face toggle, and a ranked candidate list feeding the host's
6//! multi-candidate popup. Selection-filter *filtering* stays in the UI layer where the
7//! filter state lives — the engine reports everything under the cursor.
8//!
9//! CPU ray/screen-space testing over the scene's display buffers: exact,
10//! deterministic, identical on native and wasm, and cheap at CAD face counts
11//! (dense meshes use cached kernel BVHs before exact triangle tests).
12
13use crate::geometry2d::point_segment_distance;
14
15use crate::scene::{RenderScene, SolidDisplay};
16use crate::view::{add3, cross3, dot3, scale3, sub3, Projection, Ray, ViewCamera};
17
18/// Pick thresholds in CSS pixels (ported from `selectionMethods`).
19pub const EDGE_PICK_PX: f64 = 6.0;
20pub const VERTEX_PICK_PX: f64 = 6.0;
21const MAX_CANDIDATES: usize = 16;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub enum PickKind {
25    Vertex = 0,
26    Edge = 1,
27    Face = 2,
28    /// A construction PLANE / DATUM base plane (the pick-list category right
29    /// AFTER faces). Never produced by the ray tests here — the plane cards live
30    /// in the widget registry, so the engine appends one candidate per drawn card
31    /// the pointer ray crosses (`EngineState::pick_candidates_at`); `name` is the
32    /// datum FRAME name (`Pl`, `Datum:XY`), `solid` is empty.
33    ///
34    /// Ranking below FACE is deliberate: a plane competes for a pick by KIND, not
35    /// by depth, so a face under the cursor always out-priorities the (large,
36    /// unshaded) plane card — the plane is still listed, one row down, instead of
37    /// swallowing the click. See `EngineState::pick_candidates_at`.
38    Plane = 3,
39    Solid = 4,
40    /// An assembly COMPONENT entry (the pick-list category after solids). Never
41    /// produced by the ray tests here — the engine appends one per owning
42    /// component when the selection filter's COMPONENT lane is on
43    /// (`candidates_filtered_at`); `name` is the component id, `solid` is empty.
44    Component = 5,
45}
46
47impl PickKind {
48    pub fn as_str(&self) -> &'static str {
49        match self {
50            PickKind::Vertex => "VERTEX",
51            PickKind::Edge => "EDGE",
52            PickKind::Face => "FACE",
53            PickKind::Plane => "PLANE",
54            PickKind::Solid => "SOLID",
55            PickKind::Component => "COMPONENT",
56        }
57    }
58}
59
60#[derive(Debug, Clone)]
61pub struct PickCandidate {
62    pub kind: PickKind,
63    /// Kernel name (faces/edges; empty for unnamed). For vertices this is
64    /// empty — vertices resolve by `position` within `solid`.
65    pub name: String,
66    /// Owning solid's scene name.
67    pub solid: String,
68    /// View-space depth of the hit (for ranking within a kind).
69    pub depth: f64,
70    /// Cursor→hit distance in CSS px (0 for face hits).
71    pub screen_dist: f64,
72    /// World-space hit position (face hit point / edge closest point / vertex).
73    pub position: [f64; 3],
74}
75
76#[derive(Debug, Clone, Copy)]
77pub struct PickOptions {
78    pub double_sided: bool,
79    pub edge_px: f64,
80    pub vertex_px: f64,
81}
82
83impl Default for PickOptions {
84    fn default() -> Self {
85        Self {
86            // The retired picker force-flipped FrontSide materials to DoubleSide
87            // for every pick, so double-sided is the parity default.
88            double_sided: true,
89            edge_px: EDGE_PICK_PX,
90            vertex_px: VERTEX_PICK_PX,
91        }
92    }
93}
94
95/// The view depth of the nearest FACE of `scene` under CSS-pixel `(x, y)`, if
96/// any: what a translucent context scene puts in front of the clicked point.
97pub fn nearest_face_depth(scene: &RenderScene, camera: &ViewCamera, x: f64, y: f64, options: &PickOptions) -> Option<f64> {
98    pick(scene, camera, x, y, options)
99        .into_iter()
100        .filter(|candidate| candidate.kind == PickKind::Face)
101        .map(|candidate| candidate.depth)
102        .min_by(f64::total_cmp)
103}
104
105/// [`pick`] in `scene`, without what `context` hides: a candidate deeper than
106/// the nearest context face under the cursor is behind that face. A context
107/// drawn translucent (a Work part's surrounding assembly) is still in front, so
108/// a click on it is not a click on the part behind it. Touching faces (a mating
109/// face flush with the context) stay pickable.
110pub fn pick_unoccluded(
111    scene: &RenderScene,
112    context: &RenderScene,
113    camera: &ViewCamera,
114    x: f64,
115    y: f64,
116    options: &PickOptions,
117) -> Vec<PickCandidate> {
118    let mut hits = pick(scene, camera, x, y, options);
119    if context.solids().is_empty() {
120        return hits;
121    }
122    if let Some(front) = nearest_face_depth(context, camera, x, y, options) {
123        let tolerance = 1e-6 * front.abs().max(1.0) + 1e-4;
124        hits.retain(|candidate| candidate.depth <= front + tolerance);
125    }
126    hits
127}
128
129/// The FRONT face hit under CSS-pixel `(x, y)` — what the depth buffer shows
130/// there: a FACE candidate, or a SOLID one for a section cap. Faces only (no
131/// edge/vertex screen tests), so it is the cheap visibility probe box
132/// selection ([`crate::box_pick`]) casts per sample.
133pub(crate) fn front_face_at(
134    scene: &RenderScene,
135    camera: &ViewCamera,
136    x: f64,
137    y: f64,
138    options: &PickOptions,
139) -> Option<PickCandidate> {
140    let ray = camera.pick_ray(x, y);
141    let (_, _, forward) = camera.basis();
142    let mut hits: Vec<PickCandidate> = Vec::new();
143    let mut triangles = Vec::new();
144    for solid in scene.solids() {
145        if !solid.visible || !ray_hits_aabb(&ray, &solid.bbox) {
146            continue;
147        }
148        let candidates = if solid.mesh.indices.len() / 3 > 128 {
149            triangles.clear();
150            scene.pick_triangles(solid, &ray, &mut triangles);
151            Some(triangles.as_slice())
152        } else {
153            None
154        };
155        pick_faces(solid, camera, &ray, forward, options, candidates, &mut hits);
156    }
157    hits.into_iter().min_by(|a, b| a.depth.total_cmp(&b.depth))
158}
159
160/// The view depth of a world point (along the camera's forward axis).
161pub(crate) fn point_view_depth(camera: &ViewCamera, point: [f64; 3]) -> f64 {
162    let (_, _, forward) = camera.basis();
163    view_depth(camera, forward, point)
164}
165
166/// Rank candidates under CSS-pixel `(x, y)`. Ordered by the priority chain
167/// then depth; a SOLID entry per hit solid is appended at the end (the earlier
168/// "extras" behavior).
169pub fn pick(
170    scene: &RenderScene,
171    camera: &ViewCamera,
172    x: f64,
173    y: f64,
174    options: &PickOptions,
175) -> Vec<PickCandidate> {
176    let ray = camera.pick_ray(x, y);
177    let (_, _, forward) = camera.basis();
178    let persp = matches!(camera.projection, Projection::Perspective { .. });
179
180    let mut hits: Vec<PickCandidate> = Vec::new();
181    let mut triangles = Vec::new();
182    for solid in scene.solids() {
183        if !solid.visible {
184            continue;
185        }
186        if ray_hits_aabb(&ray, &solid.bbox) {
187            // Small component meshes cost less to scan than to index. Dense
188            // copper/silkscreen displays dominate UNO hover time without this
189            // broad phase, even though they contain only a handful of faces.
190            let candidates = if solid.mesh.indices.len() / 3 > 128 {
191                triangles.clear();
192                scene.pick_triangles(solid, &ray, &mut triangles);
193                Some(triangles.as_slice())
194            } else {
195                None
196            };
197            pick_faces(solid, camera, &ray, forward, options, candidates, &mut hits);
198        }
199        pick_edges(solid, camera, x, y, forward, persp, options, &mut hits);
200        pick_vertices(solid, camera, x, y, forward, persp, options, &mut hits);
201    }
202
203    hits.sort_by(|a, b| {
204        (a.kind as u8)
205            .cmp(&(b.kind as u8))
206            .then(a.depth.total_cmp(&b.depth))
207            .then(a.screen_dist.total_cmp(&b.screen_dist))
208    });
209    hits.truncate(MAX_CANDIDATES);
210
211    // Append one SOLID candidate per hit solid, ordered by first (best) hit.
212    // A section cap's SOLID hit is one of them, not a second entry.
213    let mut solids_seen: Vec<String> = Vec::new();
214    let mut solid_entries: Vec<PickCandidate> = Vec::new();
215    for hit in &hits {
216        if solids_seen.iter().any(|name| name == &hit.solid) {
217            continue;
218        }
219        solids_seen.push(hit.solid.clone());
220        solid_entries.push(PickCandidate {
221            kind: PickKind::Solid,
222            name: hit.solid.clone(),
223            solid: hit.solid.clone(),
224            depth: hit.depth,
225            screen_dist: hit.screen_dist,
226            position: hit.position,
227        });
228    }
229    hits.retain(|hit| hit.kind != PickKind::Solid);
230    hits.extend(solid_entries);
231    hits
232}
233
234/// The nearest hit of an ALLOWED KIND under CSS-pixel `(x, y)`, using the same
235/// ranking as [`pick`]. `filter` is a set of kind strings (`"SOLID"`, `"FACE"`,
236/// `"EDGE"`, `"VERTEX"`, case-insensitive); an empty filter means any kind. This
237/// is the type-constrained pick the reference-selection widget uses so a
238/// `targetSolid` field resolves the SOLID under the cursor (candidates rank
239/// faces first, then the trailing SOLID entry — `find` walks that order and
240/// returns the first candidate whose kind is allowed). Returns the full
241/// candidate (name + owning solid + position) or `None` on a miss.
242pub fn pick_filtered(
243    scene: &RenderScene,
244    camera: &ViewCamera,
245    x: f64,
246    y: f64,
247    options: &PickOptions,
248    filter: &[String],
249) -> Option<PickCandidate> {
250    pick(scene, camera, x, y, options).into_iter().find(|c| {
251        filter.is_empty() || filter.iter().any(|f| f.eq_ignore_ascii_case(c.kind.as_str()))
252    })
253}
254
255fn view_depth(camera: &ViewCamera, forward: [f64; 3], point: [f64; 3]) -> f64 {
256    dot3(sub3(point, camera.eye), forward)
257}
258
259#[allow(clippy::too_many_arguments)]
260fn pick_faces(
261    solid: &SolidDisplay,
262    camera: &ViewCamera,
263    ray: &Ray,
264    forward: [f64; 3],
265    options: &PickOptions,
266    candidates: Option<&[usize]>,
267    out: &mut Vec<PickCandidate>,
268) {
269    if solid.mesh.indices.is_empty() {
270        return;
271    }
272    if !ray_hits_aabb(ray, &solid.bbox) {
273        return;
274    }
275    let positions = &solid.mesh.positions;
276    let indices = &solid.mesh.indices;
277    let first_hit = out.len();
278    let mut cap_depth: Option<f64> = None;
279    for (index, face) in solid.faces.iter().enumerate() {
280        // Per-entity visibility (the scene tree's face checkboxes): a hidden
281        // face isn't rendered, so it must not be hoverable/pickable either.
282        if !solid.visibility.is_face_visible(index) {
283            continue;
284        }
285        if face.tri_count == 0 {
286            continue;
287        }
288        let mut best: Option<(f64, [f64; 3])> = None;
289        let start = face.tri_start as usize;
290        let end = start + face.tri_count as usize;
291        let end = end.min(indices.len() / 3);
292        let mut test_triangle = |tri: usize| {
293            let i0 = indices[tri * 3] as usize;
294            let i1 = indices[tri * 3 + 1] as usize;
295            let i2 = indices[tri * 3 + 2] as usize;
296            let a = to_f64(positions[i0]);
297            let b = to_f64(positions[i1]);
298            let c = to_f64(positions[i2]);
299            if let Some(t) = ray_triangle(ray, a, b, c, options.double_sided) {
300                let point = add3(ray.origin, scale3(ray.dir, t));
301                if best.map(|(bt, _)| t < bt).unwrap_or(true) {
302                    best = Some((t, point));
303                }
304            }
305        };
306        match candidates {
307            Some(triangles) => {
308                let first = triangles.partition_point(|&tri| tri < start);
309                let last = triangles.partition_point(|&tri| tri < end);
310                for &tri in &triangles[first..last] {
311                    test_triangle(tri);
312                }
313            }
314            None => {
315                for tri in start..end {
316                    test_triangle(tri);
317                }
318            }
319        }
320        if let Some((_, point)) = best {
321            let depth = view_depth(camera, forward, point);
322            // A section cap is the cut of the solid, not a face of it: a
323            // SOLID hit.
324            if face.kind == crate::scene::FaceKind::SectionCap {
325                cap_depth = Some(cap_depth.map_or(depth, |d| d.min(depth)));
326                out.push(PickCandidate {
327                    kind: PickKind::Solid,
328                    name: solid.name.clone(),
329                    solid: solid.name.clone(),
330                    depth,
331                    screen_dist: 0.0,
332                    position: point,
333                });
334                continue;
335            }
336            out.push(PickCandidate {
337                kind: PickKind::Face,
338                name: face.name.clone(),
339                solid: solid.name.clone(),
340                depth,
341                screen_dist: 0.0,
342                position: point,
343            });
344        }
345    }
346    // The cap closes the cut: this solid's faces behind it are not under the
347    // cursor (a click on the cut must not pick the inside of the far wall).
348    if let Some(cap) = cap_depth {
349        let tolerance = 1e-6 * cap.abs().max(1.0);
350        let mut index = first_hit;
351        while index < out.len() {
352            if out[index].kind == PickKind::Face && out[index].depth > cap + tolerance {
353                out.remove(index);
354            } else {
355                index += 1;
356            }
357        }
358    }
359}
360
361#[allow(clippy::too_many_arguments)]
362fn pick_edges(
363    solid: &SolidDisplay,
364    camera: &ViewCamera,
365    x: f64,
366    y: f64,
367    forward: [f64; 3],
368    persp: bool,
369    options: &PickOptions,
370    out: &mut Vec<PickCandidate>,
371) {
372    for (index, edge) in solid.edges.iter().enumerate() {
373        // Hidden edges (scene-tree checkboxes) are not rendered → not pickable.
374        // An AUX edge is display-only — a board's copper outline — and has no
375        // entity to hover or select.
376        if edge.aux || !solid.visibility.is_edge_visible(index) {
377            continue;
378        }
379        let mut best: Option<(f64, f64, [f64; 3])> = None; // (screen_dist, depth, world)
380        for pair in edge.polyline.windows(2) {
381            let mut a = to_f64(pair[0]);
382            let mut b = to_f64(pair[1]);
383            if persp {
384                let da = view_depth(camera, forward, a);
385                let db = view_depth(camera, forward, b);
386                const EPS: f64 = 1e-6;
387                if da <= EPS && db <= EPS {
388                    continue;
389                }
390                if da <= EPS || db <= EPS {
391                    // Clip the behind-eye endpoint to just in front.
392                    let t = (EPS - da) / (db - da);
393                    let clip = add3(a, scale3(sub3(b, a), t));
394                    if da <= EPS {
395                        a = clip;
396                    } else {
397                        b = clip;
398                    }
399                }
400            }
401            let (ax, ay, _) = camera.project(a);
402            let (bx, by, _) = camera.project(b);
403            let (dist, t) = point_segment_distance((x, y), (ax, ay), (bx, by));
404            if dist <= options.edge_px {
405                let world = add3(a, scale3(sub3(b, a), t));
406                let depth = view_depth(camera, forward, world);
407                if best
408                    .map(|(bd, bdepth, _)| dist < bd || (dist == bd && depth < bdepth))
409                    .unwrap_or(true)
410                {
411                    best = Some((dist, depth, world));
412                }
413            }
414        }
415        if let Some((screen_dist, depth, position)) = best {
416            out.push(PickCandidate {
417                kind: PickKind::Edge,
418                name: edge.name.clone(),
419                solid: solid.name.clone(),
420                depth,
421                screen_dist,
422                position,
423            });
424        }
425    }
426}
427
428#[allow(clippy::too_many_arguments)]
429fn pick_vertices(
430    solid: &SolidDisplay,
431    camera: &ViewCamera,
432    x: f64,
433    y: f64,
434    forward: [f64; 3],
435    persp: bool,
436    options: &PickOptions,
437    out: &mut Vec<PickCandidate>,
438) {
439    for (index, vertex) in solid.vertices.iter().enumerate() {
440        // Hidden vertices (scene-tree checkboxes) are not rendered → not pickable.
441        if !solid.visibility.is_vertex_visible(index) {
442            continue;
443        }
444        let depth = view_depth(camera, forward, vertex.position);
445        if persp && depth <= 1e-6 {
446            continue;
447        }
448        let (sx, sy, _) = camera.project(vertex.position);
449        let dist = ((sx - x).powi(2) + (sy - y).powi(2)).sqrt();
450        if dist <= options.vertex_px {
451            out.push(PickCandidate {
452                kind: PickKind::Vertex,
453                name: String::new(),
454                solid: solid.name.clone(),
455                depth,
456                screen_dist: dist,
457                position: vertex.position,
458            });
459        }
460    }
461}
462
463fn to_f64(p: [f32; 3]) -> [f64; 3] {
464    [p[0] as f64, p[1] as f64, p[2] as f64]
465}
466
467/// Möller–Trumbore; returns the ray parameter t of the hit.
468fn ray_triangle(ray: &Ray, a: [f64; 3], b: [f64; 3], c: [f64; 3], double_sided: bool) -> Option<f64> {
469    let e1 = sub3(b, a);
470    let e2 = sub3(c, a);
471    let pvec = cross3(ray.dir, e2);
472    let det = dot3(e1, pvec);
473    const EPS: f64 = 1e-14;
474    if double_sided {
475        if det.abs() < EPS {
476            return None;
477        }
478    } else if det < EPS {
479        return None;
480    }
481    let inv_det = 1.0 / det;
482    let tvec = sub3(ray.origin, a);
483    let u = dot3(tvec, pvec) * inv_det;
484    if !(-1e-9..=1.0 + 1e-9).contains(&u) {
485        return None;
486    }
487    let qvec = cross3(tvec, e1);
488    let v = dot3(ray.dir, qvec) * inv_det;
489    if v < -1e-9 || u + v > 1.0 + 1e-9 {
490        return None;
491    }
492    let t = dot3(e2, qvec) * inv_det;
493    if t <= 0.0 {
494        return None;
495    }
496    Some(t)
497}
498
499fn ray_hits_aabb(ray: &Ray, bbox: &crate::camera::Aabb) -> bool {
500    if bbox.is_empty() {
501        return false;
502    }
503    let mut t_min = f64::NEG_INFINITY;
504    let mut t_max = f64::INFINITY;
505    for axis in 0..3 {
506        let dir = ray.dir[axis];
507        let origin = ray.origin[axis];
508        if dir.abs() < 1e-15 {
509            if origin < bbox.min[axis] - 1e-9 || origin > bbox.max[axis] + 1e-9 {
510                return false;
511            }
512            continue;
513        }
514        let inv = 1.0 / dir;
515        let t0 = (bbox.min[axis] - origin) * inv;
516        let t1 = (bbox.max[axis] - origin) * inv;
517        let (lo, hi) = if t0 <= t1 { (t0, t1) } else { (t1, t0) };
518        t_min = t_min.max(lo);
519        t_max = t_max.min(hi);
520        if t_min > t_max {
521            return false;
522        }
523    }
524    t_max > 0.0
525}
526
527/// Serialize candidates for the R3 JSON boundary.
528pub fn candidates_to_json(candidates: &[PickCandidate]) -> String {
529    let list: Vec<serde_json::Value> = candidates
530        .iter()
531        .map(|c| {
532            serde_json::json!({
533                "kind": c.kind.as_str(),
534                "name": c.name,
535                "solid": c.solid,
536                "depth": c.depth,
537                "screenDist": c.screen_dist,
538                "position": c.position,
539            })
540        })
541        .collect();
542    serde_json::Value::Array(list).to_string()
543}
544