Picking: remove the GPU pick buffer, the per-body BVHs answer alone (#4665) (#4666)

The pick buffer drew the model's surfaces and edge ids for every still
view to narrow which edges a pick tests. Measured against the BVHs alone
(release, M2 Max, 1400 x 900 view, 600 cursor positions), a pick costs
2-51 us through the BVHs and the tile saved 0-4 us of it, while each pass
cost 0.7-12.5 ms of GPU time per still view, plus gathering its scene on
the window thread, read-backs a frame or two late and repaints to wait for
them (and, before, a copy of every triangle, which made it refuse models
past 6 M triangles). Picks are unchanged: the BVHs give the same answers.

`pick_timing_on_curved_models` gains eight layers of bodies seen from above
(the pick buffer's best case) and `SOLIDCRAFT_BENCH_MESH` placements.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jackson OurslandandClaude Opus 5.5 authored and GitHub committed 2026-10-22 12:03:37 +00:00
1 parent f0fd5c10b7
commit f843a3f83c
8 files changed
+46 -1007

No files matched your search

-1
View File
@@ -21,7 +21,6 @@ use wgpu::util::DeviceExt;
pub mod capture;
mod pbr;
pub mod pick;
#[cfg(not(target_arch = "wasm32"))]
pub mod select;
pub mod view;
-503
View File
@@ -1,503 +0,0 @@
//! The pick buffer: which model edges are visible at each pixel of the viewport, for picking on a
//! large model without testing every edge. Surfaces are drawn into the depth buffer only; then
//! every edge segment is drawn as a line carrying its id, depth tested against them (lifted
//! toward the eye by the picker's slack, the depth by which an edge may lie behind a face and
//! still count as visible) and written into an `R32Uint` id texture (0: no edge).
//!
//! The pass is drawn once per view (camera, viewport size, model), and only small tiles around
//! the cursor are read back, so a pointer moving over a still view reads a few kilobytes and
//! draws nothing. Read-backs arrive a frame or two later ([`PickResults`]); until a tile is in,
//! the picker answers on the CPU. The ids are hints: the picker still runs its exact tests on
//! the edges a tile names.
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex};
use wgpu::util::DeviceExt;
/// The side of a read-back tile, in pixels (a multiple of 64, so rows need no padding).
pub const TILE: u32 = 128;
/// Most tiles kept from one view.
const KEEP: usize = 6;
/// Most read-backs in flight.
const IN_FLIGHT: usize = 3;
/// Bytes per surface vertex (position) and per edge vertex (position, id).
const FACE_VERTEX: u64 = 12;
const EDGE_VERTEX: u64 = 16;
const UNIFORM_SIZE: u64 = 96;
const SHADER: &str = r#"
struct U {
vp: mat4x4<f32>,
eye: vec4<f32>, // eye position, w = 1 for perspective
back: vec4<f32>, // toward the eye (orthographic), w = how far edges are lifted toward it
};
@group(0) @binding(0) var<uniform> u: U;
@vertex
fn vs_face(@location(0) p: vec3<f32>) -> @builtin(position) vec4<f32> {
return u.vp * vec4<f32>(p, 1.0);
}
@fragment
fn fs_face() -> @location(0) u32 {
return 0u;
}
struct EOut {
@builtin(position) pos: vec4<f32>,
@location(0) @interpolate(flat) id: u32,
};
@vertex
fn vs_edge(@location(0) p: vec3<f32>, @location(1) id: u32) -> EOut {
var toward = u.back.xyz;
if (u.eye.w > 0.5) {
let v = u.eye.xyz - p;
let l = length(v);
if (l > 0.0) {
toward = v / l;
}
}
var o: EOut;
o.pos = u.vp * vec4<f32>(p + toward * u.back.w, 1.0);
o.id = id;
return o;
}
@fragment
fn fs_edge(i: EOut) -> @location(0) u32 {
return i.id;
}
"#;
/// What the pass draws: surfaces (for depth) and edge segments with their ids (from 1).
#[derive(Default, Clone)]
pub struct PickScene {
faces: Vec<u8>,
edges: Vec<u8>,
}
impl PickScene {
pub fn triangle(&mut self, t: [[f32; 3]; 3]) {
for p in t {
for c in p {
self.faces.extend_from_slice(&c.to_le_bytes());
}
}
}
/// Segment `a`–`b` of the edge `id` (0 is no edge: not drawn).
pub fn segment(&mut self, a: [f32; 3], b: [f32; 3], id: u32) {
if id == 0 {
return;
}
for p in [a, b] {
for c in p {
self.edges.extend_from_slice(&c.to_le_bytes());
}
self.edges.extend_from_slice(&id.to_le_bytes());
}
}
pub fn is_empty(&self) -> bool {
self.edges.is_empty()
}
}
/// The view the pass is drawn for.
#[derive(Clone, Copy, Debug)]
pub struct PickView {
/// Changes whenever anything below or the scene changes.
pub key: u64,
/// Column-major view-projection (as [`crate::view::Frame::view_proj`]).
pub view_proj: [[f32; 4]; 4],
/// Eye position, and 1 for a perspective camera (0: orthographic).
pub eye: [f32; 4],
/// Direction toward the eye (orthographic).
pub back: [f32; 3],
/// How far edges are lifted toward the eye (model units).
pub lift: f32,
/// The viewport in physical pixels.
pub size: [u32; 2],
}
/// Edge ids of a block of pixels of one view.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickTile {
pub key: u64,
pub origin: [u32; 2],
pub size: [u32; 2],
/// Row-major, `size[0] * size[1]`.
pub ids: Vec<u32>,
}
impl PickTile {
/// Whether the tile is of view `key` and holds every pixel of `[x0, y0, x1, y1]` (inclusive)
/// that lies inside a viewport of `view` pixels.
pub fn covers(&self, key: u64, view: [u32; 2], [x0, y0, x1, y1]: [i64; 4]) -> bool {
let clamp = |v: i64, n: u32| v.clamp(0, i64::from(n.max(1)) - 1);
let (x0, x1, y0, y1) = (clamp(x0, view[0]), clamp(x1, view[0]), clamp(y0, view[1]), clamp(y1, view[1]));
let [ox, oy] = self.origin.map(i64::from);
let [w, h] = self.size.map(i64::from);
self.key == key && x0 >= ox && y0 >= oy && x1 < ox + w && y1 < oy + h
}
/// The ids within `[x0, y0, x1, y1]` (inclusive; outside the tile: none), each once.
pub fn ids_in(&self, [x0, y0, x1, y1]: [i64; 4]) -> Vec<u32> {
let [ox, oy] = self.origin.map(i64::from);
let [w, h] = self.size.map(i64::from);
let mut out = Vec::new();
for y in y0.max(oy)..=y1.min(oy + h - 1) {
for x in x0.max(ox)..=x1.min(ox + w - 1) {
if let Some(&id) = self.ids.get(((y - oy) * w + (x - ox)) as usize)
&& id != 0
{
out.push(id);
}
}
}
out.sort_unstable();
out.dedup();
out
}
}
/// The tiles read back so far (of the latest view only), newest last.
#[derive(Default, Debug)]
pub struct PickResults {
pub tiles: Vec<PickTile>,
}
impl PickResults {
/// The newest tile of view `key` covering `window`.
pub fn tile(&self, key: u64, view: [u32; 2], window: [i64; 4]) -> Option<&PickTile> {
self.tiles.iter().rev().find(|t| t.covers(key, view, window))
}
}
pub type PickOut = Arc<Mutex<PickResults>>;
/// The tile (origin and size) around pixel `centre` of a viewport of `view` pixels.
pub fn tile_around(centre: [u32; 2], view: [u32; 2]) -> ([u32; 2], [u32; 2]) {
let size = [TILE.min(view[0]), TILE.min(view[1])];
let origin = [0, 1].map(|k| centre[k].saturating_sub(size[k] / 2).min(view[k].saturating_sub(size[k])));
(origin, size)
}
const NEW: u8 = 0;
const MAPPING: u8 = 1;
const READY: u8 = 2;
const FAILED: u8 = 3;
/// A tile being copied out of the id texture.
struct Pending {
key: u64,
origin: [u32; 2],
size: [u32; 2],
bytes_per_row: u32,
buffer: wgpu::Buffer,
/// The frame whose commands copy it (it is mapped once they are submitted).
frame: u64,
state: Arc<AtomicU8>,
}
struct Target {
size: [u32; 2],
ids: wgpu::Texture,
ids_view: wgpu::TextureView,
depth_view: wgpu::TextureView,
}
struct Uploaded {
key: u64,
faces: Option<(wgpu::Buffer, u32)>,
edges: Option<(wgpu::Buffer, u32)>,
}
/// The pass's pipelines, its textures and the read-backs in flight, on one device.
pub struct PickBuffer {
face: wgpu::RenderPipeline,
edge: wgpu::RenderPipeline,
uniform: wgpu::Buffer,
bind: wgpu::BindGroup,
scene: Option<Uploaded>,
target: Option<Target>,
/// The view drawn into the textures.
drawn: Option<u64>,
pending: Vec<Pending>,
frame: u64,
}
const DEPTH: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
const IDS: wgpu::TextureFormat = wgpu::TextureFormat::R32Uint;
impl PickBuffer {
pub fn new(device: &wgpu::Device) -> PickBuffer {
let module =
device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("sc_pick"), source: wgpu::ShaderSource::Wgsl(SHADER.into()) });
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("sc_pick"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("sc_pick"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("sc_pick_u"),
size: UNIFORM_SIZE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("sc_pick"),
layout: &bgl,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }],
});
const FA: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x3];
const EA: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![0 => Float32x3, 1 => Uint32];
let pipeline = |label: &str,
vs: &str,
fs: &str,
stride: u64,
attributes: &'static [wgpu::VertexAttribute],
topology: wgpu::PrimitiveTopology,
write: bool,
mask: wgpu::ColorWrites| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some(vs),
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: stride, step_mode: wgpu::VertexStepMode::Vertex, attributes })],
compilation_options: Default::default(),
},
primitive: wgpu::PrimitiveState { topology, ..Default::default() },
depth_stencil: Some(wgpu::DepthStencilState {
format: DEPTH,
depth_write_enabled: Some(write),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some(fs),
targets: &[Some(wgpu::ColorTargetState { format: IDS, blend: None, write_mask: mask })],
compilation_options: Default::default(),
}),
multiview_mask: None,
cache: None,
})
};
let face =
pipeline("sc_pick_face", "vs_face", "fs_face", FACE_VERTEX, &FA, wgpu::PrimitiveTopology::TriangleList, true, wgpu::ColorWrites::empty());
let edge = pipeline("sc_pick_edge", "vs_edge", "fs_edge", EDGE_VERTEX, &EA, wgpu::PrimitiveTopology::LineList, false, wgpu::ColorWrites::ALL);
PickBuffer { face, edge, uniform, bind, scene: None, target: None, drawn: None, pending: Vec::new(), frame: 0 }
}
/// Before the frame is submitted: collect the tiles read back, then draw `view` of `scene`
/// (`scene_key` names it; it is uploaded when that changes) unless it is drawn already, and
/// start reading back the tile around pixel `centre` unless it is in or on its way. The tiles
/// land in `out` a frame or two later; keep frames coming until then.
#[allow(clippy::too_many_arguments)]
pub fn prepare(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
scene_key: u64,
scene: &PickScene,
view: &PickView,
centre: Option<[u32; 2]>,
out: &PickOut,
) {
self.frame += 1;
self.collect(device, out);
let [w, h] = view.size;
let max = device.limits().max_texture_dimension_2d;
if w == 0 || h == 0 || w > max || h > max {
return;
}
if self.scene.as_ref().is_none_or(|s| s.key != scene_key) {
let limit = device.limits().max_buffer_size;
let upload = |label: &str, bytes: &[u8], stride: u64| {
let n = bytes.len() as u64 / stride;
(n > 0 && (bytes.len() as u64) <= limit && n <= u64::from(u32::MAX)).then(|| {
(
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(label),
contents: bytes,
usage: wgpu::BufferUsages::VERTEX,
}),
n as u32,
)
})
};
self.scene = Some(Uploaded {
key: scene_key,
faces: upload("sc_pick_faces", &scene.faces, FACE_VERTEX),
edges: upload("sc_pick_edges", &scene.edges, EDGE_VERTEX),
});
self.drawn = None;
}
if self.target.as_ref().is_none_or(|t| t.size != view.size) {
let texture = |label: &str, format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let ids = texture("sc_pick_ids", IDS, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
let depth = texture("sc_pick_depth", DEPTH, wgpu::TextureUsages::RENDER_ATTACHMENT);
let (ids_view, depth_view) = (ids.create_view(&Default::default()), depth.create_view(&Default::default()));
self.target = Some(Target { size: view.size, ids, ids_view, depth_view });
self.drawn = None;
}
let (Some(target), Some(scene)) = (&self.target, &self.scene) else { return };
if self.drawn != Some(view.key) {
queue.write_buffer(&self.uniform, 0, &uniform_bytes(view));
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_pick"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.ids_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &target.depth_view,
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &self.bind, &[]);
for (pipeline, part) in [(&self.face, &scene.faces), (&self.edge, &scene.edges)] {
if let Some((buffer, n)) = part {
pass.set_pipeline(pipeline);
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..*n, 0..1);
}
}
drop(pass);
self.drawn = Some(view.key);
// Tiles of other views no longer answer.
self.pending.retain(|p| p.key == view.key);
if let Ok(mut o) = out.lock() {
o.tiles.retain(|t| t.key == view.key);
}
}
let Some(centre) = centre else { return };
let (origin, size) = tile_around(centre, view.size);
let known = out.lock().is_ok_and(|o| o.tiles.iter().any(|t| t.key == view.key && t.origin == origin && t.size == size))
|| self.pending.iter().any(|p| p.key == view.key && p.origin == origin && p.size == size);
if known || self.pending.len() >= IN_FLIGHT {
return;
}
let bytes_per_row = (size[0] * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("sc_pick_tile"),
size: u64::from(bytes_per_row) * u64::from(size[1]),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture: &target.ids,
mip_level: 0,
origin: wgpu::Origin3d { x: origin[0], y: origin[1], z: 0 },
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bytes_per_row), rows_per_image: Some(size[1]) },
},
wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
);
self.pending.push(Pending { key: view.key, origin, size, bytes_per_row, buffer, frame: self.frame, state: Arc::new(AtomicU8::new(NEW)) });
}
/// Whether read-backs are still on their way (keep frames coming).
pub fn waiting(&self) -> bool {
!self.pending.is_empty()
}
/// Maps the copies earlier frames submitted and moves the mapped ones into `out`.
fn collect(&mut self, device: &wgpu::Device, out: &PickOut) {
let frame = self.frame;
for p in &self.pending {
if p.frame < frame && p.state.load(Ordering::Acquire) == NEW {
p.state.store(MAPPING, Ordering::Release);
let state = p.state.clone();
p.buffer.slice(..).map_async(wgpu::MapMode::Read, move |r| state.store(if r.is_ok() { READY } else { FAILED }, Ordering::Release));
}
}
if self.pending.iter().any(|p| p.state.load(Ordering::Acquire) == MAPPING) {
let _ = device.poll(wgpu::PollType::Poll);
}
let mut done = Vec::new();
self.pending.retain(|p| match p.state.load(Ordering::Acquire) {
READY => {
if let Ok(bytes) = p.buffer.slice(..).get_mapped_range() {
let [w, h] = p.size;
let mut ids = Vec::with_capacity(w as usize * h as usize);
for row in bytes.chunks(p.bytes_per_row as usize).take(h as usize) {
ids.extend(row.as_chunks::<4>().0.iter().take(w as usize).map(|c| u32::from_le_bytes(*c)));
}
done.push(PickTile { key: p.key, origin: p.origin, size: p.size, ids });
}
p.buffer.unmap();
false
}
FAILED => false,
_ => true,
});
if !done.is_empty()
&& let Ok(mut o) = out.lock()
{
for t in done {
if self.drawn == Some(t.key) && t.ids.len() == t.size[0] as usize * t.size[1] as usize {
o.tiles.retain(|x| x.key == t.key);
o.tiles.push(t);
}
}
let excess = o.tiles.len().saturating_sub(KEEP);
o.tiles.drain(..excess);
}
}
}
fn uniform_bytes(v: &PickView) -> Vec<u8> {
let mut b = Vec::with_capacity(UNIFORM_SIZE as usize);
for col in v.view_proj {
for x in col {
b.extend_from_slice(&x.to_le_bytes());
}
}
for x in v.eye.into_iter().chain(v.back).chain([v.lift]) {
b.extend_from_slice(&x.to_le_bytes());
}
b
}
#[cfg(test)]
#[path = "pick_tests.rs"]
mod tests;
-79
View File
@@ -1,79 +0,0 @@
use super::*;
/// Looking down −z at x, y in −10..10 (orthographic): depth 0 at z = 50, 1 at z = −50.
const VIEW: [[f32; 4]; 4] = [[0.1, 0.0, 0.0, 0.0], [0.0, 0.1, 0.0, 0.0], [0.0, 0.0, -0.01, 0.0], [0.0, 0.0, 0.5, 1.0]];
const SIZE: u32 = 64;
/// The pixel of model point (x, y).
fn px(x: f32, y: f32) -> [i64; 2] {
[((x / 10.0 + 1.0) * 0.5 * SIZE as f32) as i64, ((1.0 - y / 10.0) * 0.5 * SIZE as f32) as i64]
}
/// A square face at z = 0 (x, y in −5..5), and three edges: 1 on it, 2 well behind it, 3 behind
/// it by less than the lift.
fn scene() -> PickScene {
let mut s = PickScene::default();
let (a, b, c, d) = ([-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]);
s.triangle([a, b, c]);
s.triangle([a, c, d]);
s.segment([-8.0, 0.0, 0.0], [8.0, 0.0, 0.0], 1);
s.segment([2.0, -8.0, -3.0], [2.0, 8.0, -3.0], 2);
s.segment([-2.0, -8.0, -0.2], [-2.0, 8.0, -0.2], 3);
s
}
#[test]
fn the_pick_buffer_names_the_edges_seen_at_each_pixel() {
let (_, device, queue) = match crate::open_headless() {
Ok(d) => d,
Err(e) => {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here: {e}");
eprintln!("skipping: {e}");
return;
}
};
let mut pb = PickBuffer::new(&device);
let out = PickOut::default();
let view = PickView { key: 7, view_proj: VIEW, eye: [0.0, 0.0, 100.0, 0.0], back: [0.0, 0.0, 1.0], lift: 0.5, size: [SIZE, SIZE] };
let scene = scene();
let all = [0, 0, SIZE as i64 - 1, SIZE as i64 - 1];
for _ in 0..8 {
let mut encoder = device.create_command_encoder(&Default::default());
pb.prepare(&device, &queue, &mut encoder, 1, &scene, &view, Some([SIZE / 2, SIZE / 2]), &out);
queue.submit([encoder.finish()]);
let _ = device.poll(wgpu::PollType::wait_indefinitely());
if out.lock().unwrap().tile(7, [SIZE, SIZE], all).is_some() {
break;
}
}
let results = out.lock().unwrap();
let tile = results.tile(7, [SIZE, SIZE], all).expect("the tile is read back within a few frames");
let at = |x: f32, y: f32| {
let [px, py] = px(x, y);
tile.ids_in([px - 1, py - 1, px + 1, py + 1])
};
assert_eq!(at(0.0, 0.0), vec![1], "the edge on the face");
assert_eq!(at(2.0, 3.0), Vec::<u32>::new(), "the edge behind the face is hidden");
assert_eq!(at(2.0, 7.5), vec![2], "and seen where the face does not cover it");
assert_eq!(at(-2.0, 3.0), vec![3], "an edge behind the face by less than the lift counts as seen");
assert_eq!(at(3.5, 3.5), Vec::<u32>::new(), "the face itself names no edge");
assert!(results.tile(8, [SIZE, SIZE], all).is_none(), "another view's tile does not answer");
drop(results);
assert!(!pb.waiting());
}
#[test]
fn tiles_cover_the_window_around_the_cursor_inside_the_view() {
assert_eq!(tile_around([10, 10], [1000, 800]), ([0, 0], [TILE, TILE]));
assert_eq!(tile_around([500, 400], [1000, 800]), ([500 - TILE / 2, 400 - TILE / 2], [TILE, TILE]));
assert_eq!(tile_around([999, 799], [1000, 800]), ([1000 - TILE, 800 - TILE], [TILE, TILE]));
assert_eq!(tile_around([30, 20], [50, 40]), ([0, 0], [50, 40]));
let t = PickTile { key: 1, origin: [100, 100], size: [TILE, TILE], ids: vec![0; (TILE * TILE) as usize] };
assert!(t.covers(1, [1000, 800], [110, 110, 120, 120]));
assert!(!t.covers(1, [1000, 800], [90, 110, 120, 120]));
assert!(!t.covers(2, [1000, 800], [110, 110, 120, 120]));
// A window past the view's border needs only the pixels inside it.
let corner = PickTile { key: 1, origin: [0, 0], size: [TILE, TILE], ids: vec![5; (TILE * TILE) as usize] };
assert!(corner.covers(1, [1000, 800], [-8, -8, 8, 8]));
assert_eq!(corner.ids_in([-8, -8, 8, 8]), vec![5]);
}
-1
View File
@@ -159,7 +159,6 @@ pub mod mouse_gesture;
pub(crate) mod navigation;
pub(crate) mod open_meshing;
pub mod params_dialog;
pub(crate) mod pick_buffer;
pub(crate) mod pick_index;
pub(crate) mod plugins;
pub mod prefs;
-259
View File
@@ -1,259 +0,0 @@
//! The GPU pick buffer in the viewport ([`solidcraft_gpu::pick`]): which model edges are seen at
//! each pixel, so a pick over a large model tests only the edges near the cursor that are not
//! hidden, instead of every edge the cursor's ray passes near.
//!
//! The pass is drawn for a view once it holds still (the same view two frames running), and a
//! tile around the cursor is read back; the tile arrives a frame or two later, and until it
//! does (and while the view moves) the picker answers from the CPU indexes
//! ([`crate::pick_index`]). The tile only narrows the candidates: the picker's exact tests
//! still decide. Not used for Select Other (every target along the ray), in wireframe (nothing
//! hides an edge there), without a GPU, or for a model past [`MAX_TRIANGLES`].
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
use egui::Pos2;
use solidcraft_engine::doc::ModelState;
use solidcraft_gpu::pick::{PickBuffer, PickOut, PickScene, PickView};
use crate::SolveApp;
use crate::viewport::Proj;
/// Most surface triangles the pass draws (beyond them the CPU indexes answer alone).
pub const MAX_TRIANGLES: usize = 6_000_000;
/// How near the cursor an edge's pixels are looked for (points): vertices pick within 7, edges 6.
const WINDOW: f32 = 8.0;
/// Frames kept coming after a tile is asked for, so its read-back lands.
const FRAMES: u8 = 4;
/// The pass's scene for one model state: the ids it draws stand for (body, edge).
struct Scene {
state: Arc<ModelState>,
key: u64,
scene: Arc<PickScene>,
/// Per id − 1: (body index in the state, edge index).
edges: Vec<(u32, u32)>,
/// One-point edges (no line to draw): always candidates.
points: Vec<(u32, u32)>,
}
#[derive(Default)]
pub(crate) struct State {
scene: Mutex<Option<Arc<Scene>>>,
out: PickOut,
/// A pick found no tile for its cursor: the view it was in and the pixel.
want: Mutex<Option<(u64, [u32; 2])>>,
/// The view of the last frame (the pass is drawn for a view that held still).
last_view: u64,
/// Frames still to request so read-backs land.
frames: u8,
}
/// The edges a tile names near the cursor, per body index of the world state.
pub(crate) struct NearEdges {
by_body: HashMap<usize, Vec<usize>>,
}
impl NearEdges {
/// Every segment of the named edges of body `index` of `mesh`, as (edge, first point), in
/// edge order.
pub(crate) fn segments(&self, index: usize, mesh: &solidcraft_engine::geom::Mesh) -> Vec<(usize, usize)> {
let mut v = Vec::new();
for &ei in self.by_body.get(&index).map_or(&[][..], |e| &e[..]) {
let n = mesh.edges.get(ei).map_or(0, |e| e.len().max(2) - 1);
v.extend((0..n).map(|si| (ei, si)));
}
v
}
}
/// What the pass's scene depends on: the world state, and which bodies show.
fn model_key(app: &SolveApp, st: &Arc<ModelState>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
(Arc::as_ptr(st) as usize).hash(&mut h);
app.session.revision.hash(&mut h);
app.session.visibility.hidden_bodies.hash(&mut h);
app.session.visibility.hidden_occurrences.hash(&mut h);
h.finish()
}
/// The view's pixels: the viewport's size in physical pixels.
fn view_size(app: &SolveApp, proj: &Proj) -> [u32; 2] {
let ppp = app.viewport.pixels_per_point();
[(proj.rect.width() * ppp).round().max(0.0) as u32, (proj.rect.height() * ppp).round().max(0.0) as u32]
}
/// How far edges are lifted toward the eye: the picker's slack for an edge behind a face.
fn lift(app: &SolveApp) -> f64 {
crate::viewport::scene_radius(app) * 0.02
}
/// Everything the drawn ids depend on.
fn view_key(app: &SolveApp, proj: &Proj, model: u64) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
model.hash(&mut h);
for col in proj.vp.to_f32() {
for x in col {
x.to_bits().hash(&mut h);
}
}
view_size(app, proj).hash(&mut h);
lift(app).to_bits().hash(&mut h);
h.finish()
}
fn usable(app: &SolveApp) -> bool {
app.viewport.gpu.is_some() && app.ui.visual_style != 2
}
/// The edges seen within reach of `pos`, when a tile of this view is in; otherwise `None`, and
/// a tile around `pos` is asked for.
pub(crate) fn edges_near(app: &SolveApp, proj: &Proj, pos: Pos2, st: &Arc<ModelState>) -> Option<NearEdges> {
if !usable(app) {
return None;
}
let model = model_key(app, st);
let scene = app.viewport.pick_buffer.scene.lock().ok()?.clone().filter(|s| s.key == model && Arc::ptr_eq(&s.state, st));
let key = view_key(app, proj, model);
let size = view_size(app, proj);
let ppp = app.viewport.pixels_per_point();
let (x, y) = ((pos.x - proj.rect.left()) * ppp, (pos.y - proj.rect.top()) * ppp);
if !(x >= 0.0 && y >= 0.0 && x < size[0] as f32 && y < size[1] as f32) {
return None;
}
let (x, y) = (x as i64, y as i64);
let r = (WINDOW * ppp).ceil() as i64;
let window = [x - r, y - r, x + r, y + r];
let ids = scene.as_ref().and_then(|_| app.viewport.pick_buffer.out.lock().ok()?.tile(key, size, window).map(|t| t.ids_in(window)));
let (Some(scene), Some(ids)) = (scene, ids) else {
if let Ok(mut w) = app.viewport.pick_buffer.want.lock() {
*w = Some((key, [x as u32, y as u32]));
}
return None;
};
let mut by_body: HashMap<usize, Vec<usize>> = HashMap::new();
for (b, e) in ids.iter().filter_map(|id| scene.edges.get((*id as usize).checked_sub(1)?)).chain(&scene.points) {
by_body.entry(*b as usize).or_default().push(*e as usize);
}
for v in by_body.values_mut() {
v.sort_unstable();
v.dedup();
}
Some(NearEdges { by_body })
}
/// The pass's scene for the world state: visible bodies' triangles, and their pickable edges.
/// `None` past [`MAX_TRIANGLES`] or without edges.
fn scene(app: &SolveApp, st: &Arc<ModelState>, key: u64) -> Option<Arc<Scene>> {
let f = |p: solidcraft_engine::geom::Vec3| [p.x as f32, p.y as f32, p.z as f32];
let mut scene = PickScene::default();
let (mut edges, mut points, mut triangles) = (Vec::new(), Vec::new(), 0usize);
for (bi, b) in st.bodies.iter().enumerate() {
if !app.session.body_visible(&b.name) {
continue;
}
let m = b.mesh();
triangles += m.triangles.len();
if triangles > MAX_TRIANGLES {
return None;
}
for t in &m.triangles {
if let Some([a, b, c]) = m.tri(t) {
scene.triangle([f(a), f(b), f(c)]);
}
}
for (ei, e) in m.edges.iter().enumerate() {
if !m.edge_pickable(ei) || edges.len() >= u32::MAX as usize - 1 {
continue;
}
if e.len() == 1 {
points.push((bi as u32, ei as u32));
continue;
}
edges.push((bi as u32, ei as u32));
let id = edges.len() as u32;
for w in e.windows(2) {
scene.segment(f(w[0]), f(w[1]), id);
}
}
}
(!scene.is_empty()).then(|| Arc::new(Scene { state: st.clone(), key, scene: Arc::new(scene), edges, points }))
}
/// In the frame's GPU paint: draw the pass for a view that held still when a pick asked for a
/// tile, and keep frames coming until the read-back lands.
pub(crate) fn paint(app: &mut SolveApp, ctx: &egui::Context, painter: &egui::Painter, proj: &Proj) {
if !usable(app) {
return;
}
let st = app.session.world_state();
let model = model_key(app, &st);
let key = view_key(app, proj, model);
let state = &mut app.viewport.pick_buffer;
let still = std::mem::replace(&mut state.last_view, key) == key;
let want = state.want.lock().ok().and_then(|mut w| w.take()).filter(|(k, _)| *k == key && still);
if want.is_none() && state.frames == 0 {
return;
}
state.frames = if want.is_some() { FRAMES } else { state.frames.saturating_sub(1) };
let cached = state.scene.lock().ok().and_then(|s| s.clone()).filter(|s| s.key == model && Arc::ptr_eq(&s.state, &st));
let scene = match cached {
Some(s) => s,
None => {
let Some(s) = scene(app, &st, model) else { return };
if let Ok(mut slot) = app.viewport.pick_buffer.scene.lock() {
*slot = Some(s.clone());
}
s
}
};
let e = proj.cam.eye().to_f32();
let view = PickView {
key,
view_proj: proj.vp.to_f32(),
eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }],
back: proj.cam.back().to_f32(),
lift: lift(app) as f32,
size: view_size(app, proj),
};
let cb =
PickCallback { scene_key: scene.key, scene: scene.scene.clone(), view, centre: want.map(|w| w.1), out: app.viewport.pick_buffer.out.clone() };
painter.add(egui_wgpu::Callback::new_paint_callback(proj.rect, cb));
ctx.request_repaint();
}
/// The pass as an egui paint callback: all its work is in `prepare` (it draws into its own
/// textures, not the frame).
struct PickCallback {
scene_key: u64,
scene: Arc<PickScene>,
view: PickView,
centre: Option<[u32; 2]>,
out: PickOut,
}
impl egui_wgpu::CallbackTrait for PickCallback {
fn prepare(
&self,
device: &egui_wgpu::wgpu::Device,
queue: &egui_wgpu::wgpu::Queue,
_screen: &egui_wgpu::ScreenDescriptor,
encoder: &mut egui_wgpu::wgpu::CommandEncoder,
resources: &mut egui_wgpu::CallbackResources,
) -> Vec<egui_wgpu::wgpu::CommandBuffer> {
if resources.get::<PickBuffer>().is_none() {
resources.insert(PickBuffer::new(device));
}
if let Some(pb) = resources.get_mut::<PickBuffer>() {
pb.prepare(device, queue, encoder, self.scene_key, &self.scene, &self.view, self.centre, &self.out);
}
Vec::new()
}
fn paint(&self, _info: egui::PaintCallbackInfo, _pass: &mut egui_wgpu::wgpu::RenderPass<'static>, _resources: &egui_wgpu::CallbackResources) {}
}
#[cfg(test)]
#[path = "pick_buffer_tests.rs"]
mod tests;
-141
View File
@@ -1,141 +0,0 @@
use egui::{Rect, pos2};
use serde_json::json;
use solidcraft_engine::geom::Vec3;
use solidcraft_gpu::pick::{PickTile, TILE, tile_around};
use super::*;
use crate::viewport::{Hit, pick, projection};
fn app() -> SolveApp {
let mut s = solidcraft_engine::Session::default();
s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap();
s.execute("solid.fillet", &json!({"edges": [[40, 15, 20]], "radius": 4})).unwrap();
s.execute("solid.cylinder", &json!({"radius": 8, "height": 35, "base": [10, 10, 0], "operation": "new_body"})).unwrap();
let mut app = SolveApp::new(s, crate::Services::default());
app.ui.show_origin = false;
app.cam.target = Vec3::new(20.0, 15.0, 12.0);
app.cam.distance = 110.0;
// A GPU viewport (no device is needed to hand the picker a tile).
app.viewport.gpu = Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false });
app
}
const RECT: Rect = Rect { min: pos2(0.0, 0.0), max: pos2(640.0, 480.0) };
/// Installs the pass's scene, as `paint` makes it, and returns the view's key.
fn install_scene(app: &SolveApp, proj: &Proj) -> u64 {
let st = app.session.world_state();
let model = model_key(app, &st);
let s = scene(app, &st, model).unwrap();
*app.viewport.pick_buffer.scene.lock().unwrap() = Some(s);
view_key(app, proj, model)
}
/// A tile only narrows the edges: the edge it names near the cursor is picked as the CPU picks
/// it, an edge it does not name (hidden there) is not, and without a tile the CPU indexes answer
/// and a tile is asked for.
#[test]
fn a_tile_names_the_edges_the_picker_tests() {
let app = app();
let proj = projection(&app, RECT);
// A point on the box's top front edge (y = 0, z = 20).
let at = proj.to_screen(Vec3::new(20.0, 0.0, 20.0)).unwrap();
let cpu = pick(&app, &proj, at);
let Some(Hit::Edge { index, body, .. }) = cpu.iter().find(|h| matches!(h, Hit::Edge { .. })).cloned() else { panic!("{cpu:?}") };
assert!(app.viewport.pick_buffer.want.lock().unwrap().is_some(), "no tile yet: one is asked for");
let key = install_scene(&app, &proj);
let st = app.session.world_state();
let bi = st.bodies.iter().position(|b| b.name == body).unwrap();
let s = app.viewport.pick_buffer.scene.lock().unwrap().clone().unwrap();
let id = s.edges.iter().position(|&(b, e)| b as usize == bi && e as usize == index).unwrap() as u32 + 1;
let size = view_size(&app, &proj);
let (origin, tsize) = tile_around([at.x as u32, at.y as u32], size);
let tile = |ids: Vec<u32>| PickTile { key, origin, size: tsize, ids };
let n = (tsize[0] * tsize[1]) as usize;
// The edge's id at the cursor's pixel.
let mut ids = vec![0; n];
ids[((at.y as u32 - origin[1]) * tsize[0] + (at.x as u32 - origin[0])) as usize] = id;
app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(ids)];
assert_eq!(pick(&app, &proj, at), cpu, "the named edge is picked as the CPU picks it");
// A tile naming no edge there: no edge or vertex is picked.
app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(vec![0; n])];
let none = pick(&app, &proj, at);
assert!(!none.iter().any(|h| matches!(h, Hit::Edge { .. } | Hit::Vertex { .. })), "{none:?}");
assert!(none.iter().any(|h| matches!(h, Hit::Face { .. })), "faces are still picked: {none:?}");
// A tile of another view does not answer.
app.viewport.pick_buffer.out.lock().unwrap().tiles = vec![PickTile { key: key ^ 1, ..tile(vec![0; n]) }];
assert_eq!(pick(&app, &proj, at), cpu);
// Wireframe: nothing hides an edge, and the buffer is not used.
let mut wire = app;
wire.ui.visual_style = 2;
wire.viewport.pick_buffer.out.lock().unwrap().tiles = vec![tile(vec![0; n])];
assert!(edges_near(&wire, &proj, at, &wire.session.world_state()).is_none());
}
/// On a real device: the pass drawn for the view, and picks over a grid of the view helped by its
/// tiles answer as the CPU picks (an edge's pixels and the CPU's visibility test can disagree by
/// a pixel at a silhouette, so a few may differ). Skipped without a GPU adapter.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn picks_through_the_pass_match_the_cpu() {
let Some((_, device, queue)) = crate::gpu::offscreen_device() else {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "a GPU is required here");
eprintln!("skipping: no GPU adapter");
return;
};
let mut app = app();
for (perspective, yaw, pitch) in [(false, 0.6, 0.5), (true, 2.4, 0.3)] {
app.ui.perspective = perspective;
app.cam.yaw = yaw;
app.cam.pitch = pitch;
let proj = projection(&app, RECT);
let key = install_scene(&app, &proj);
let s = app.viewport.pick_buffer.scene.lock().unwrap().clone().unwrap();
let e = proj.cam.eye().to_f32();
let view = PickView {
key,
view_proj: proj.vp.to_f32(),
eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }],
back: proj.cam.back().to_f32(),
lift: lift(&app) as f32,
size: view_size(&app, &proj),
};
let mut pb = PickBuffer::new(&device);
let out = app.viewport.pick_buffer.out.clone();
// Tiles over the whole view.
let mut wanted = Vec::new();
for ty in (0..view.size[1]).step_by(TILE as usize - 32) {
for tx in (0..view.size[0]).step_by(TILE as usize - 32) {
wanted.push([tx + TILE / 2, ty + TILE / 2]);
}
}
let mut tiles = Vec::new();
for c in wanted {
for _ in 0..6 {
let mut encoder = device.create_command_encoder(&Default::default());
pb.prepare(&device, &queue, &mut encoder, s.key, &s.scene, &view, Some(c), &out);
queue.submit([encoder.finish()]);
let _ = device.poll(egui_wgpu::wgpu::PollType::wait_indefinitely());
}
tiles.append(&mut out.lock().unwrap().tiles);
}
let (mut same, mut differ, mut edges) = (0, 0, 0);
for j in 0..46 {
for i in 0..62 {
let p = pos2(10.0 + i as f32 * 10.0 + (j % 3) as f32, 10.0 + j as f32 * 10.0);
let r = 8i64;
let w = [p.x as i64 - r, p.y as i64 - r, p.x as i64 + r, p.y as i64 + r];
let Some(t) = tiles.iter().find(|t| t.covers(key, view.size, w)).cloned() else { continue };
out.lock().unwrap().tiles = vec![t];
let through = pick(&app, &proj, p);
out.lock().unwrap().tiles.clear();
let cpu = pick(&app, &proj, p);
edges += usize::from(cpu.iter().any(|h| matches!(h, Hit::Edge { .. })));
if through == cpu { same += 1 } else { differ += 1 }
}
}
eprintln!("perspective {perspective}: {same} same, {differ} differ, {edges} with an edge");
assert!(edges > 100, "the grid reaches edges ({edges})");
assert!(differ * 100 <= same + differ, "{differ} of {} picks differ", same + differ);
}
}
+43 -10
View File
@@ -67,9 +67,12 @@ fn indexes_follow_the_model_state() {
assert!(app.viewport.pick_index.len() <= 5);
}
/// Timing, not a check (`cargo test -p solidcraft-ui-egui --lib pick_timing -- --ignored
/// --nocapture`): picks over a grid of the view, scanning every triangle and edge versus through
/// the indexes, on many curved bodies and on one body with many curved faces.
/// Timing, not a check (`cargo test --release -p solidcraft-ui-egui --lib pick_timing -- --ignored
/// --nocapture`; `SOLIDCRAFT_BENCH_MESH=part.stl` adds 25 placements of that mesh): picks over a
/// grid of a 1400 × 900 view, scanning every triangle and edge versus through the indexes, on many
/// curved bodies, on one body with many curved faces, and on eight layers of bodies seen from
/// above (rays passing near many hidden edges). Release, Apple M2 Max: tens of microseconds a
/// pick through the indexes on each, 25 placements of a 2 M-triangle scan included.
#[test]
#[ignore]
fn pick_timing_on_curved_models() {
@@ -89,21 +92,51 @@ fn pick_timing_on_curved_models() {
one.execute("solid.cylinder", &json!({"radius": 14, "height": 30, "base": [x, y, 0], "operation": "join"})).unwrap();
}
}
for (name, s) in [("many bodies", many), ("one body", one)] {
let mut app = SolveApp::new(s, crate::Services::default());
let mut deep = solidcraft_engine::Session::default();
for k in 0..8 {
for i in 0..8 {
for j in 0..8 {
let (x, y, z) = (f64::from(i) * 40.0 + f64::from(k) * 5.0, f64::from(j) * 40.0 + f64::from(k) * 3.0, f64::from(k) * 25.0);
deep.execute("solid.cylinder", &json!({"radius": 15, "height": 20, "base": [x, y, z], "operation": "new_body"})).unwrap();
}
}
}
let mut scenes = vec![
("many bodies", SolveApp::new(many, crate::Services::default()), 0.6),
("one body", SolveApp::new(one, crate::Services::default()), 0.6),
];
scenes.push(("eight layers", SolveApp::new(deep, crate::Services::default()), 1.2));
if let Some(path) = std::env::var_os("SOLIDCRAFT_BENCH_MESH") {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
let component = app.run("file.insert_mesh", json!({"path": path.to_string_lossy()})).unwrap()["component"].clone();
app.run("component.activate", json!({"component":"root"})).unwrap();
let size = app.session.world_state().bodies[0].mesh_bounds().size();
let step = size.x.max(size.y) * 1.3;
for k in 1..25 {
app.run("occurrence.copy", json!({"component":component,"translate":[f64::from(k % 5) * step, f64::from(k / 5) * step, 0.0]})).unwrap();
}
scenes.push(("25 placed meshes", app, 0.6));
}
for (name, mut app, pitch) in scenes {
app.ui.show_origin = false;
app.cam.target = solidcraft_engine::geom::Vec3::new(160.0, 160.0, 15.0);
app.cam.distance = 900.0;
(app.cam.yaw, app.cam.pitch) = (0.6, pitch);
let st = app.session.world_state();
app.cam.fit(&st.bodies.iter().fold(solidcraft_engine::geom::Aabb3::EMPTY, |a, b| a.union(&b.mesh_bounds())));
let (tris, segs) = st
.bodies
.iter()
.map(|b| b.mesh())
.map(|b| b.mesh_in_place().0)
.fold((0, 0), |(t, s), m| (t + m.triangles.len(), s + m.edges.iter().map(|e| e.len().saturating_sub(1)).sum::<usize>()));
let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(1400.0, 900.0));
let proj = projection(&app, rect);
let points: Vec<_> = (0..20).flat_map(|j| (0..30).map(move |i| pos2(30.0 + i as f32 * 45.0, 30.0 + j as f32 * 42.0))).collect();
// Indexes made once, before timing.
// Indexes made once, before timing (large ones on workers).
for b in &st.bodies {
let m = b.mesh_in_place().0;
while app.viewport.pick_index.of(&m).is_none() {
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
for p in &points {
pick(&app, &proj, *p);
}
@@ -116,7 +149,7 @@ fn pick_timing_on_curved_models() {
super::SCAN.with(|s| s.set(false));
t.elapsed().as_secs_f64() * 1000.0 / points.len() as f64
};
let (scan, indexed) = (time(true), time(false));
let (scan, indexed) = (if tris < 10_000_000 { time(true) } else { f64::NAN }, time(false));
eprintln!("{name}: {} bodies, {tris} triangles, {segs} edge segments: scan {scan:.3} ms per pick, indexed {indexed:.3} ms", st.bodies.len());
}
}
+3 -13
View File
@@ -79,8 +79,6 @@ pub struct ViewportState {
/// Each body mesh's picking index (made the first time a pick reaches the body), kept while
/// the mesh is part of the world state.
pub(crate) pick_index: crate::pick_index::PickIndexes,
/// The GPU pick buffer's scene, read-backs and requests.
pub(crate) pick_buffer: crate::pick_buffer::State,
/// The last click in the view was the middle button's (for the middle double-click).
pub(crate) middle_clicked: bool,
/// The last pick (its key and hits): reused while nothing it depends on changed.
@@ -1513,9 +1511,6 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,
let visible = |p: Vec3| wireframe || bestf.as_ref().is_none_or(|(t, _)| (p - o).dot(d) <= *t + slack);
// Vertices (edge end points) and edges, within 7 and 6 points of the cursor.
let reach = crate::pick_index::reach(proj, pos, 8.0);
// The edges seen near the cursor, when the GPU pick buffer has them for this view (Select
// Other wants hidden ones too).
let seen = if all { None } else { crate::pick_buffer::edges_near(app, proj, pos, &st) };
let mut bestv = Near::new(all);
let mut beste = Near::new(all);
for (i, b) in st.bodies.iter().enumerate() {
@@ -1533,13 +1528,9 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,
let Some((lo, ld)) = local_ray(&place, o, d) else { continue };
let moved = !solidcraft_engine::doc::is_identity(&place);
let at = |p: Vec3| if moved { solidcraft_engine::doc::apply_point(&place, p) } else { p };
// Only the segments that can come near the cursor: of the edges the pick buffer sees
// there, else from the index. Either way in the order a scan of every edge would meet
// them, so ties go the same way.
let near = match &seen {
Some(seen) => seen.segments(i, &m),
None => crate::pick_index::segments_near(app.viewport.pick_index.of(&m).as_deref(), &m, lo, ld, reach),
};
// Only the segments that can come near the cursor, from the index, in the order a scan
// of every edge would meet them, so ties go the same way.
let near = crate::pick_index::segments_near(app.viewport.pick_index.of(&m).as_deref(), &m, lo, ld, reach);
let mut last_edge = None;
for (ei, si) in near {
let Some(e) = m.edges.get(ei) else { continue };
@@ -2700,7 +2691,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
},
});
painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb));
crate::pick_buffer::paint(app, ui.ctx(), &painter, &proj);
}
analysis_legend(app, &painter, rect);
crate::frame_rate::paint(app, ui.ctx(), &painter, rect);