Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Move triad: dragging in large designs does less work per step (#7273) (#7276)

JK3Df0d305a78368
diff --git a/assets/locales/pending/move-drag-highlights.json b/assets/locales/pending/move-drag-highlights.json
new file mode 100644
index 0000000000..027a569f72
--- /dev/null
+++ b/assets/locales/pending/move-drag-highlights.json
@@ -0,0 +1,42 @@
+{
+ "en": {
+ "prefs.move_drag_highlights": "Highlight what is under the pointer while Move's arrows drag a component",
+ "prefs.move_drag_highlights_tip": "Off: while Move's arrows drag a component, nothing under the pointer is highlighted, which keeps large assemblies smooth. With a section or an analysis shown it is highlighted all the same, and a part dragged along its joints never highlights it."
+ },
+ "ar": {
+ "prefs.move_drag_highlights": "تمييز ما تحت المؤشر أثناء سحب مكوّن بأسهم أداة النقل",
+ "prefs.move_drag_highlights_tip": "عند الإيقاف: لا يُميَّز أي شيء تحت المؤشر أثناء سحب مكوّن بأسهم أداة النقل، فتبقى التجميعات الكبيرة سلسة. مع عرض مقطع أو تحليل يبقى التمييز كما هو، ولا يُميَّز شيء أبدًا عند سحب جزء على امتداد وصلاته."
+ },
+ "de": {
+ "prefs.move_drag_highlights": "Hervorheben, was unter dem Zeiger liegt, während die Pfeile von Verschieben eine Komponente ziehen",
+ "prefs.move_drag_highlights_tip": "Aus: Solange die Pfeile von Verschieben eine Komponente ziehen, wird nichts unter dem Zeiger hervorgehoben; so bleiben große Baugruppen flüssig. Mit einem Schnitt oder einer Analyse wird es trotzdem hervorgehoben, und ein entlang seiner Gelenke gezogenes Teil hebt nie etwas hervor."
+ },
+ "es": {
+ "prefs.move_drag_highlights": "Resaltar lo que hay bajo el puntero mientras las flechas de Mover arrastran un componente",
+ "prefs.move_drag_highlights_tip": "Desactivado: mientras las flechas de Mover arrastran un componente no se resalta nada bajo el puntero, y los ensamblajes grandes se mueven con fluidez. Con un corte o un análisis visible se resalta igualmente, y una pieza arrastrada a lo largo de sus uniones nunca lo resalta."
+ },
+ "fr": {
+ "prefs.move_drag_highlights": "Mettre en évidence ce qui est sous le pointeur pendant que les flèches de Déplacer font glisser un composant",
+ "prefs.move_drag_highlights_tip": "Désactivé : pendant que les flèches de Déplacer font glisser un composant, rien n’est mis en évidence sous le pointeur, ce qui garde les grands assemblages fluides. Avec une coupe ou une analyse affichée, la mise en évidence reste, et une pièce glissée le long de ses liaisons n’en montre jamais."
+ },
+ "he": {
+ "prefs.move_drag_highlights": "הדגשת מה שמתחת לסמן בזמן שחצי ההזזה גוררים רכיב",
+ "prefs.move_drag_highlights_tip": "כבוי: בזמן שחצי ההזזה גוררים רכיב, דבר אינו מודגש מתחת לסמן, וכך מכלולים גדולים נשארים חלקים. כשמוצג חתך או ניתוח ההדגשה נשארת, וחלק שנגרר לאורך המפרקים שלו לעולם אינו מדגיש."
+ },
+ "ja": {
+ "prefs.move_drag_highlights": "移動の矢印でコンポーネントをドラッグ中にポインターの下をハイライト",
+ "prefs.move_drag_highlights_tip": "オフ: 移動の矢印でコンポーネントをドラッグしている間はポインターの下をハイライトしないため、大きなアセンブリでも滑らかに動きます。断面や解析を表示中は通常どおりハイライトし、ジョイントに沿ってドラッグする部品ではハイライトしません。"
+ },
+ "ko": {
+ "prefs.move_drag_highlights": "이동 화살표로 구성 요소를 끄는 동안 포인터 아래 항목 강조 표시",
+ "prefs.move_drag_highlights_tip": "끄면 이동 화살표로 구성 요소를 끄는 동안 포인터 아래 항목을 강조 표시하지 않아 큰 어셈블리도 부드럽게 움직입니다. 단면이나 해석이 표시된 동안에는 그대로 강조 표시하며, 조인트를 따라 끄는 부품은 강조 표시하지 않습니다."
+ },
+ "vi": {
+ "prefs.move_drag_highlights": "Tô sáng thứ nằm dưới con trỏ khi các mũi tên của Di chuyển kéo một thành phần",
+ "prefs.move_drag_highlights_tip": "Tắt: khi các mũi tên của Di chuyển kéo một thành phần, không có gì dưới con trỏ được tô sáng, nhờ đó các cụm lắp ráp lớn vẫn mượt. Khi đang hiện mặt cắt hoặc phân tích thì vẫn tô sáng như thường, và chi tiết được kéo dọc theo khớp nối không bao giờ tô sáng."
+ },
+ "zh": {
+ "prefs.move_drag_highlights": "用移动的箭头拖动组件时高亮指针下的对象",
+ "prefs.move_drag_highlights_tip": "关闭:用移动的箭头拖动组件时,不高亮指针下的对象,大型装配体也能保持流畅。显示剖切或分析时仍照常高亮;沿关节拖动零件时从不高亮。"
+ }
+}
diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl
index d3172ece8e..ca7d8f376d 100644
--- a/assets/shaders/viewport.wgsl
+++ b/assets/shaders/viewport.wgsl
@@ -16,6 +16,9 @@ struct U {
ana_c: array<vec4<f32>, 8>,
ana_f: vec4<f32>, // x = 1: stripe the negative draft and blocked faces
depth: vec4<f32>, // x = 1: reversed depth (1 near, 0 far); y, z: the faces' push (`FACE_BIAS`)
+ // Where the drawn geometry is moved in the world: identity, or a dragged component's move
+ // from where its scene was built (`MovingLayer`)
+ model: mat4x4<f32>,
tint: vec4<f32>, // xyz added to a whole hovered body's colour before lighting
sel: vec4<f32>, // xyz a whole selected body's colour before lighting
// the section hatch colours by part (`solidcraft_render::hatch`), the first the cap's own
@@ -25,6 +28,16 @@ struct U {
sky: vec4<f32>, // xyz = world up; w = 1: shade in linear light with a sky fill (#7974)
};
+/// A scene's point in the world (see `U.model`).
+fn placed(p: vec3<f32>) -> vec3<f32> {
+ return (u.model * vec4<f32>(p, 1.0)).xyz;
+}
+
+/// A scene's direction in the world (see `placed`).
+fn turned(n: vec3<f32>) -> vec3<f32> {
+ return (u.model * vec4<f32>(n, 0.0)).xyz;
+}
+
fn reversed() -> bool {
return u.depth.x > 0.5;
}
@@ -83,10 +96,11 @@ struct TOut {
};
@vertex
-fn vs_tri(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: u32) -> TOut {
+fn vs_tri(@location(0) local: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c: u32) -> TOut {
var o: TOut;
+ let p = placed(local);
o.pos = u.vp * vec4<f32>(p, 1.0);
- o.n = n;
+ o.n = turned(n);
let e = palette_entry(c);
o.c = unpack_color(e.x);
o.h = e.y;
@@ -95,7 +109,8 @@ fn vs_tri(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) c:
}
/// Shared triangles (in their part's own frame) drawn at one placement: the rows of its rigid
-/// move (`r0`..`r2`, a point's coordinates are their dot products with (p, 1)) and its colour.
+/// move (`r0`..`r2`, a point's coordinates are their dot products with (p, 1)) and its colour,
+/// then moved like the rest of its scene (`placed`: a dragged component's layer).
/// The vertex colour (location 2) is not read.
@vertex
fn vs_tri_inst(
@@ -107,10 +122,11 @@ fn vs_tri_inst(
@location(6) c: u32,
) -> TOut {
let q = vec4<f32>(p, 1.0);
- let wp = vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q));
+ let wp = placed(vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q)));
+ let pn = vec3<f32>(dot(r0.xyz, n), dot(r1.xyz, n), dot(r2.xyz, n));
var o: TOut;
o.pos = u.vp * vec4<f32>(wp, 1.0);
- o.n = vec3<f32>(dot(r0.xyz, n), dot(r1.xyz, n), dot(r2.xyz, n));
+ o.n = turned(pn);
let e = palette_entry(c);
o.c = unpack_color(e.x);
o.h = e.y;
@@ -140,7 +156,7 @@ fn vs_tri_inst_flat(
@location(6) c: u32,
) -> FOut {
let q = vec4<f32>(p, 1.0);
- let wp = vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q));
+ let wp = placed(vec3<f32>(dot(r0, q), dot(r1, q), dot(r2, q)));
var o: FOut;
o.pos = u.vp * vec4<f32>(wp, 1.0);
o.rp = wp - u.eye.xyz;
@@ -785,7 +801,9 @@ fn lifted_z(p: vec3<f32>, c: vec4<f32>, px: f32, half: vec2<f32>) -> f32 {
}
@vertex
-fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(1) b: vec3<f32>, @location(2) c: u32, @location(3) wbits: u32) -> LOut {
+fn vs_line(@builtin(vertex_index) vi: u32, @location(0) local_a: vec3<f32>, @location(1) local_b: vec3<f32>, @location(2) c: u32, @location(3) wbits: u32) -> LOut {
+ let a = placed(local_a);
+ let b = placed(local_b);
var pa = a;
var pb = b;
var ca = u.vp * vec4<f32>(a, 1.0);
@@ -832,7 +850,7 @@ fn vs_line(@builtin(vertex_index) vi: u32, @location(0) a: vec3<f32>, @location(
var z = base.z;
if (lifted && base.w > 1e-6) {
let p = select(pa, pb, t > 0.5);
- let g = grazing(p, octahedral(wbits & 4095u), octahedral((wbits >> 12u) & 4095u));
+ let g = grazing(p, turned(octahedral(wbits & 4095u)), turned(octahedral((wbits >> 12u) & 4095u)));
z = lifted_z(p, base, wd * 0.5 * g + 1.0, half);
}
var o: LOut;
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs
index aa14a5c549..543a89a0dd 100644
--- a/crates/doc/src/eval.rs
+++ b/crates/doc/src/eval.rs
@@ -254,6 +254,35 @@ impl ModelBody {
self.mesh.clone()
}
+ /// Identity of the display cells of the solid this body shows: its own, or for a rigidly
+ /// placed copy its definition's (shared by every placement of it).
+ fn solid_id(&self) -> usize {
+ self.mesh_placement.as_deref().map_or(Arc::as_ptr(&self.mesh) as usize, placed_mesh::PlacedMesh::definition_id)
+ }
+
+ /// How this body is drawn moved from `before`: [`crate::IDENTITY`] when it is `before` where
+ /// it stood (its meshes and plans the same), the rigid motion between them when it is the same
+ /// solid placed elsewhere (a dragged component's body: `before`'s meshes and plans drawn moved
+ /// show it; a definition shown where it is defined is its own placement), `None` when it is
+ /// another body or its geometry differs.
+ pub fn display_moved_from(&self, before: &ModelBody) -> Option<crate::Mat> {
+ if self.name != before.name || self.solid_id() != before.solid_id() {
+ return None;
+ }
+ let (now, was) = (self.mesh_placement.as_deref(), before.mesh_placement.as_deref());
+ if let (Some(now), Some(was)) = (now, was)
+ && now.tolerance.to_bits() != was.tolerance.to_bits()
+ {
+ return None;
+ }
+ let at = |p: Option<&placed_mesh::PlacedMesh>| p.map_or(crate::IDENTITY, |p| *p.transform());
+ let (now, was) = (at(now), at(was));
+ if now == was {
+ return Some(crate::IDENTITY);
+ }
+ Some(crate::mat_mul(&now, &crate::mat_inverse(&was)?))
+ }
+
/// [`ModelBody::mesh`] as a shared mesh and the move that places it: for a rigid placement
/// of a definition, the definition's own mesh (the same one for every placement of it) and
/// the placement; for any other body its own mesh, unmoved. The mesh moved by the matrix is
@@ -8994,6 +9023,49 @@ mod world_placement_cache_tests {
assert!(Arc::ptr_eq(&original_mesh, &again.body("Block").unwrap().mesh()));
assert!(Arc::ptr_eq(&names, &crate::naming::face_names(again.body(&second_name).unwrap())));
}
+
+ /// A dragged component's bodies are drawn from the meshes and plans made where the drag found
+ /// them, moved: each is the same solid moved rigidly, the others stand where they were, and a
+ /// body whose geometry changed is no such move.
+ #[test]
+ fn a_moved_placement_is_drawn_moved_from_where_it_stood() {
+ // A placement moved, and the part moved off where it is defined.
+ for from_definition in [false, true] {
+ let mut doc = Document::new("placements");
+ let component = doc.add_component(Some("Part"), 0).unwrap();
+ doc.body_components.insert("Block".into(), component);
+ let start = if from_definition { crate::IDENTITY } else { crate::rigid(Vec3::new(10., 20., 0.), Vec3::ZERO, Vec3::Z, 0.4) };
+ let second = doc.add_occurrence(component, 0, start).unwrap();
+ let mut state = ModelState::default();
+ state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(), 1));
+ let before = world_state(&doc, &state).unwrap();
+ let delta = crate::rigid(Vec3::new(4., -7., 1.5), Vec3::new(1., 1., 0.), Vec3::new(0., 1., 1.), 0.6);
+ let moved = doc.occurrences.iter_mut().find(|o| o.id == second).unwrap();
+ moved.transform = crate::mat_mul(&delta, &moved.transform);
+ let after = world_state(&doc, &state).unwrap();
+ assert_eq!(after.bodies.len(), 2);
+ let mut moves = 0;
+ for now in &after.bodies {
+ let was = before.body(&now.name).unwrap();
+ let d = now.display_moved_from(was).unwrap();
+ if d == crate::IDENTITY {
+ assert!(Arc::ptr_eq(&now.mesh(), &was.mesh()), "{}: unchanged, the same mesh", now.name);
+ continue;
+ }
+ moves += 1;
+ assert!(d.iter().flatten().zip(delta.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-9), "{}: {d:?}", now.name);
+ // `was`'s mesh drawn moved is `now`'s.
+ for (p, q) in was.mesh().positions.iter().zip(&now.mesh().positions) {
+ assert!(crate::apply_point(&d, *p).dist(*q) < 1e-9);
+ }
+ }
+ assert_eq!(moves, 1, "from its definition: {from_definition}");
+ // Another body, or other geometry: no move draws it.
+ assert!(after.bodies[0].display_moved_from(&before.bodies[1]).is_none());
+ let other = ModelBody::new(before.bodies[0].name.clone(), kernel::box_solid(Vec3::ZERO, Vec3::new(1., 1., 1.)).unwrap(), 1);
+ assert!(other.display_moved_from(&before.bodies[0]).is_none());
+ }
+ }
}
#[cfg(test)]
diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rs
index 780fffcb6c..f4faff7b68 100644
--- a/crates/doc/src/placed_mesh.rs
+++ b/crates/doc/src/placed_mesh.rs
@@ -84,6 +84,16 @@ impl PlacedMesh {
})
}
+ /// Identity of the definition's display cells, shared by every placement of it.
+ pub(super) fn definition_id(&self) -> usize {
+ Arc::as_ptr(&self.mesh) as usize
+ }
+
+ /// Where this placement puts the definition.
+ pub(super) fn transform(&self) -> &crate::Mat {
+ &self.transform
+ }
+
pub(super) fn mesh(&self) -> Arc<Mesh> {
Arc::new(self.moved(&reference_mesh(&self.body, &self.mesh, self.tolerance)))
}
diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs
index df80e18171..ed8ef089ff 100644
--- a/crates/gpu/src/capture.rs
+++ b/crates/gpu/src/capture.rs
@@ -216,6 +216,12 @@ impl Capturer {
// is built), so the previous picture's highlight would show in this one.
frame.hl_key = state.key;
frame.hl_slot = Arc::new(Mutex::new(Some(highlight.unwrap_or_default())));
+ self.picture(state, &frame, scene.background.unwrap_or(BACKGROUND), [width, height])
+ }
+
+ /// `frame` drawn over the `background` gradient, read back as straight RGBA, and what it
+ /// drew (read while the caller holds `state`).
+ fn picture(&self, state: &mut State, frame: &Frame, (top, bottom): (Rgb, Rgb), [width, height]: [u32; 2]) -> Result<(Vec<u8>, DrawStats)> {
let (device, queue) = (&self.device, &self.queue);
let scopes = error_scopes(device);
let size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };
@@ -236,10 +242,9 @@ impl Capturer {
let depth = texture("sc_capture_depth", self.depth, self.samples, wgpu::TextureUsages::RENDER_ATTACHMENT);
let (resolved_view, depth_view) = (resolved.create_view(&Default::default()), depth.create_view(&Default::default()));
let multisampled_view = multisampled.as_ref().map(|t| t.create_view(&Default::default()));
- let (top, bottom) = scene.background.unwrap_or(BACKGROUND);
let background = background_vertices(device, top, bottom);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sc_capture") });
- state.renderer.prepare(device, queue, &mut encoder, &frame);
+ state.renderer.prepare(device, queue, &mut encoder, frame);
{
let (view, resolve_target, store) = match &multisampled_view {
Some(ms) => (ms, Some(&resolved_view), wgpu::StoreOp::Discard),
@@ -271,7 +276,7 @@ impl Capturer {
pass.set_pipeline(&state.background);
pass.set_vertex_buffer(0, background.slice(..));
pass.draw(0..6, 0..1);
- state.renderer.paint(&frame, &mut pass, [0.0, 0.0, width as f32, height as f32]);
+ state.renderer.paint(frame, &mut pass, [0.0, 0.0, width as f32, height as f32]);
}
let row = width * 4;
let padded = row.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
@@ -417,6 +422,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: scene.part_hatch.map_or_else(Default::default, |c| c.map(|Rgb(r, g, b)| [r, g, b].map(|x| f32::from(x) / 255.0))),
+ moving: None,
}
}
@@ -649,6 +655,97 @@ mod tests {
assert_eq!(color(&trace, &trace.glass).map(|c| c[3]), Some(13), "0.05 of 255");
}
+ /// Bodies dragged as a layer of their own ([`crate::view::MovingLayer`]) are drawn moved by
+ /// its transform: the picture is the one of the bodies built where they were moved to, and
+ /// the bodies go back to the model scene when the drag ends (on this machine's GPU, skipped
+ /// without one).
+ #[test]
+ fn a_moving_layer_is_drawn_moved_by_its_transform() {
+ let Ok(capturer) = Capturer::headless_single_sample() else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ let wide = Arc::new(Mesh {
+ positions: vec![Vec3::new(-1.0, 0.0, -0.5), Vec3::new(0.2, 0.0, -0.5), Vec3::new(-0.4, 0.0, 0.6)],
+ ..(*sheet()).clone()
+ });
+ let shift = Vec3::new(0.6, 0.0, 0.3);
+ let at = |offset: Vec3| {
+ let mesh = Mesh { positions: wide.positions.iter().map(|p| *p + offset).collect(), ..(*wide).clone() };
+ Scene { meshes: vec![SceneMesh::solid(Arc::new(mesh), Rgb(200, 30, 30))], ..Default::default() }
+ };
+ // Two and a half units of the view's height either side.
+ let cam = Camera { distance: 6.0, ..Camera::default() };
+ let size = [64, 64];
+ let slot = |sc: GpuScene| Arc::new(Mutex::new(Some(sc)));
+ let Ok(mut state) = capturer.state.lock() else { panic!("capturer state") };
+ // Drawn where it was moved to.
+ let moved = frame(&at(shift), &cam, size, 1, None);
+ let expected = capturer.picture(&mut state, &moved, BACKGROUND, size).unwrap().0;
+ assert!(expected.chunks(4).filter(|p| p[0] > p[1].saturating_add(60)).count() > 50, "the body shows");
+ // Drawn where it was, moved by the layer; the model scene empty.
+ let mut layered = frame(&Scene::default(), &cam, size, 2, None);
+ let transform = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [shift.x as f32, shift.y as f32, shift.z as f32, 1.0]];
+ layered.moving = Some(crate::view::MovingLayer { key: 3, slot: slot(scene_geometry(&at(Vec3::ZERO))), transform });
+ let drawn = capturer.picture(&mut state, &layered, BACKGROUND, size).unwrap().0;
+ let differ = expected.chunks(4).zip(drawn.chunks(4)).filter(|(a, b)| a.iter().zip(b.iter()).any(|(x, y)| x.abs_diff(*y) > 8)).count();
+ assert!(differ <= 4, "{differ} pixels differ from the body drawn where it was moved to");
+ // The drag over: the model scene draws it, and nothing is drawn twice or left behind.
+ let after = frame(&at(shift), &cam, size, 4, None);
+ let back = capturer.picture(&mut state, &after, BACKGROUND, size).unwrap().0;
+ assert_eq!(back, expected);
+ }
+
+ /// A dragged component's parts drawn as instances (one copy of a part's triangles, placed
+ /// many times) move with its layer too, lit flat or smooth: the layer built where the drag
+ /// found them and moved by its transform draws what the model scene draws with the
+ /// placements moved.
+ #[test]
+ fn a_moving_layers_instances_are_drawn_moved_by_its_transform() {
+ let Ok(capturer) = Capturer::headless_single_sample() else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ let flat = Mesh { positions: vec![Vec3::new(-1.0, 0.0, -0.5), Vec3::new(0.2, 0.0, -0.5), Vec3::new(-0.4, 0.0, 0.6)], ..(*sheet()).clone() };
+ let smooth = Mesh { normals: vec![Vec3::new(-0.2, -1.0, 0.0), Vec3::new(0.2, -1.0, 0.0), Vec3::new(0.0, -1.0, 0.2)], ..flat.clone() };
+ let shift = [0.6_f32, 0.0, 0.3];
+ let cam = Camera { distance: 6.0, ..Camera::default() };
+ let size = [64, 64];
+ let Ok(mut state) = capturer.state.lock() else { panic!("capturer state") };
+ for (k, mesh) in [flat, smooth].iter().enumerate() {
+ let tris = Arc::new(crate::view::SharedTris::new(mesh));
+ assert_eq!(tris.flat, k == 0);
+ let placed_at = |[x, y, z]: [f32; 3]| {
+ let mut inst = crate::view::InstancedMesh {
+ key: 1,
+ tris: tris.clone(),
+ instances: Vec::new(),
+ look: crate::view::InstanceLook::Opaque,
+ levels: Vec::new(),
+ closed: true,
+ };
+ let mut sc = GpuScene::default();
+ let red = sc.color([200, 30, 30, 255]);
+ inst.place([[1.0, 0.0, 0.0, x], [0.0, 1.0, 0.0, y], [0.0, 0.0, 1.0, z]], red);
+ sc.instanced = vec![inst];
+ Arc::new(Mutex::new(Some(sc)))
+ };
+ let key = 10 * k as u64;
+ // The model scene with the placement where it was moved to.
+ let mut moved = frame(&Scene::default(), &cam, size, key + 1, None);
+ moved.slot = placed_at(shift);
+ let expected = capturer.picture(&mut state, &moved, BACKGROUND, size).unwrap().0;
+ assert!(expected.chunks(4).filter(|p| p[0] > p[1].saturating_add(60)).count() > 50, "the part shows");
+ // Placed where it was, in the layer moved by the drag; the model scene empty.
+ let mut layered = frame(&Scene::default(), &cam, size, key + 2, None);
+ let transform = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [shift[0], shift[1], shift[2], 1.0]];
+ layered.moving = Some(crate::view::MovingLayer { key: key + 3, slot: placed_at([0.0; 3]), transform });
+ let drawn = capturer.picture(&mut state, &layered, BACKGROUND, size).unwrap().0;
+ let differ = expected.chunks(4).zip(drawn.chunks(4)).filter(|(a, b)| a.iter().zip(b.iter()).any(|(x, y)| x.abs_diff(*y) > 8)).count();
+ assert!(differ <= 4, "flat {}: {differ} pixels differ from the part placed where it was moved to", k == 0);
+ }
+ }
+
/// A face with a colour of its own is drawn in that colour, and takes its body's opacity:
/// painting one face does not make the body solid again.
#[test]
diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs
index e8883b9c8e..4d0380e657 100644
--- a/crates/gpu/src/view.rs
+++ b/crates/gpu/src/view.rs
@@ -185,9 +185,13 @@ fn octahedral6(n: [f32; 3]) -> u32 {
(q(y).min(63) << 6) | q(x).min(63)
}
/// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient
-/// occlusion radius), the 8 analysis colours, their flags, the depth direction and the two
-/// whole-body highlight colours, then the section hatch colours, the product lights, and the sky (`uniform_bytes`).
-const UNIFORM_SIZE: u64 = 416 + 16 * solidcraft_render::hatch::HATCH_COLOURS as u64 + 16 + 21 * 64 + 16;
+/// occlusion radius), the 8 analysis colours, their flags, the depth direction, the model
+/// matrix, the two whole-body highlight colours, then the section hatch colours, the product
+/// lights, and the sky (`uniform_bytes`).
+const UNIFORM_SIZE: u64 = 480 + 16 * solidcraft_render::hatch::HATCH_COLOURS as u64 + 16 + 21 * 64 + 16;
+
+/// The identity, column-major: a scene drawn where it was built.
+const IDENTITY: [[f32; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
/// A body drawn from its display plan, evaluated on the GPU: the plan, and a palette index per
/// face (the plan's face numbering; faces past the end take the last index).
@@ -1068,6 +1072,19 @@ pub struct Frame {
/// The world's up direction and 1 to shade in linear light with a sky fill that follows it
/// (#7974); 0 shades as before.
pub sky: [f32; 4],
+ /// Bodies being dragged (a component's Move triad), drawn moved; `None`: none.
+ pub moving: Option<MovingLayer>,
+}
+
+/// The bodies a component's Move triad drags: a scene of their own, built once where the drag
+/// found them and drawn moved by `transform` at every frame, so a frame of the drag builds,
+/// uploads and evaluates nothing (the model scene leaves them out meanwhile).
+#[derive(Clone)]
+pub struct MovingLayer {
+ pub key: u64,
+ pub slot: SceneSlot,
+ /// Column-major: from where the scene was built to where it is drawn (a rigid motion).
+ pub transform: [[f32; 4]; 4],
}
/// Heights of the model seen from a direction (an orthographic depth map): a point is reachable
@@ -1765,6 +1782,26 @@ impl Batches {
slot: &SceneSlot,
tess: Option<(&crate::TessGpu, &mut wgpu::CommandEncoder)>,
oit_available: bool,
+ ) {
+ self.take_sharing(device, queue, uniform, bgl, key, slot, tess, oit_available, None);
+ }
+
+ /// [`Batches::take`], taking over the blocks, evaluated chunks and instanced triangles the
+ /// scene shares with `donor` (another scene drawn in the same frame) instead of uploading and
+ /// evaluating them again: a dragged component's bodies move between the model scene and the
+ /// moving layer. `uniform` is the one the scene's palette is bound with (the layer has its
+ /// own).
+ fn take_sharing(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ uniform: &wgpu::Buffer,
+ bgl: &wgpu::BindGroupLayout,
+ key: u64,
+ slot: &SceneSlot,
+ tess: Option<(&crate::TessGpu, &mut wgpu::CommandEncoder)>,
+ oit_available: bool,
+ mut donor: Option<&mut Batches>,
) {
if self.key == Some(key) {
return;
@@ -1782,22 +1819,36 @@ impl Batches {
}
self.uploads.palette = written;
self.planned = match tess {
- Some((tess, encoder)) => self.planned(device, tess, encoder, &sc.planned),
+ Some((tess, encoder)) => self.planned(device, tess, encoder, &sc.planned, donor.as_deref_mut()),
None => Vec::new(),
};
- self.instanced = self.instanced(device, &sc.instanced);
+ self.instanced = self.instanced(device, &sc.instanced, donor.as_deref());
self.hover_planned = sc.hover_planned;
self.selected_planned = sc.selected_planned;
self.hover_blocks = sc.hover_blocks;
self.selected_blocks = sc.selected_blocks;
self.recoloured = sc.recoloured;
- self.hover_instanced = self.instanced(device, &sc.hover_instanced);
- self.selected_instanced = self.instanced(device, &sc.selected_instanced);
+ self.hover_instanced = self.instanced(device, &sc.hover_instanced, donor.as_deref());
+ self.selected_instanced = self.instanced(device, &sc.selected_instanced, donor.as_deref());
let mut kept = std::mem::take(&mut self.blocks);
let mut order = Vec::with_capacity(sc.blocks.len());
let mut geometry = 0;
for block in &sc.blocks {
- let old = kept.remove(&block.key);
+ // A block the other scene drawn in this frame holds with the same bytes (a dragged
+ // component's bodies moving between the model scene and the layer) is taken over
+ // rather than uploaded again.
+ let same = |g: &BlockGpu| Arc::ptr_eq(&g.bytes, &block.bytes);
+ let mine = kept.remove(&block.key);
+ let old = match mine {
+ Some(g) if same(&g) => Some(g),
+ mine => {
+ let shared = donor.as_deref_mut().and_then(|d| {
+ d.blocks.get(&block.key).filter(|g| same(g))?;
+ d.blocks.remove(&block.key)
+ });
+ shared.or(mine)
+ }
+ };
self.blocks.insert(block.key, BlockGpu::update(device, old, block.bytes.clone(), &mut geometry));
order.push(block.key);
}
@@ -1865,7 +1916,7 @@ impl Batches {
/// The instanced meshes on the GPU: triangles uploaded once per key (kept while the key comes
/// back with the same bytes), placements every time.
- fn instanced(&mut self, device: &wgpu::Device, meshes: &[InstancedMesh]) -> Vec<InstancedDraw> {
+ fn instanced(&mut self, device: &wgpu::Device, meshes: &[InstancedMesh], donor: Option<&Batches>) -> Vec<InstancedDraw> {
let mut kept = std::mem::take(&mut self.instanced_tris);
let mut out = Vec::with_capacity(meshes.len());
for m in meshes {
@@ -1877,7 +1928,8 @@ impl Batches {
let mut levels = Vec::with_capacity(1 + m.levels.len());
for (i, (tris, error)) in std::iter::once((&m.tris, 0.0f32)).chain(m.levels.iter().map(|(t, e)| (t, *e))).enumerate() {
let key = Arc::as_ptr(tris) as usize;
- let gpu = match kept.remove(&key).or_else(|| self.instanced_tris.remove(&key)).filter(|(b, _)| Arc::ptr_eq(b, tris)) {
+ let shared = || donor?.instanced_tris.get(&key).filter(|(b, _)| Arc::ptr_eq(b, tris)).cloned();
+ let gpu = match kept.remove(&key).or_else(|| self.instanced_tris.remove(&key)).filter(|(b, _)| Arc::ptr_eq(b, tris)).or_else(shared) {
Some(t) => t,
None => match SharedGpu::new(device, tris) {
Some(g) => {
@@ -1989,6 +2041,7 @@ impl Batches {
tess: &crate::TessGpu,
encoder: &mut wgpu::CommandEncoder,
bodies: &[PlannedBody],
+ mut donor: Option<&mut Batches>,
) -> Vec<PlannedDraw> {
// Chunks end where a body's own plan says (or when full), so a body whose plan changes
// (an edit, or a refinement as the view zooms in, #1320) re-evaluates only its own
@@ -2017,6 +2070,12 @@ impl Batches {
self.chunk_colors.retain(|k, _| chunks.iter().any(|c| key(c) == *k));
let mut out = Vec::with_capacity(chunks.len());
for chunk in &chunks {
+ let k = key(chunk);
+ if !self.resident.contains_key(&k)
+ && let Some(shared) = donor.as_deref_mut().and_then(|d| d.resident.remove(&k))
+ {
+ self.resident.insert(k, shared);
+ }
let mesh = match self.resident.get(&key(chunk)) {
Some((_, m)) => m.clone(),
None => {
@@ -2169,6 +2228,12 @@ pub struct Renderer {
bind: wgpu::BindGroup,
linear_out: bool,
model: Batches,
+ /// The dragged bodies ([`MovingLayer`]), drawn with their own uniform (`moving_uniform`,
+ /// bound by `moving_bind`) while `moving_on`.
+ moving: Batches,
+ moving_uniform: wgpu::Buffer,
+ moving_bind: wgpu::BindGroup,
+ moving_on: bool,
product: Batches,
empty: Batches,
sketch: Batches,
@@ -2599,6 +2664,22 @@ impl Renderer {
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&dummy_view) },
],
});
+ let moving_uniform = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("sc_viewport_moving_u"),
+ size: UNIFORM_SIZE,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ // The layer's stand-in for draws that read no colours, like `bind` (a scene with a palette
+ // binds its own, with `moving_uniform`).
+ let moving_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("sc_viewport_moving"),
+ layout: &bgl,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: moving_uniform.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&dummy_view) },
+ ],
+ });
let reversed = t.reversed_depth();
let depth = |compare: wgpu::CompareFunction, write: bool| -> Option<wgpu::DepthStencilState> {
t.depth.map(|format| wgpu::DepthStencilState {
@@ -3128,6 +3209,10 @@ impl Renderer {
bind,
linear_out: t.format.is_srgb(),
model: Batches::default(),
+ moving: Batches::default(),
+ moving_uniform,
+ moving_bind,
+ moving_on: false,
product: Batches::default(),
empty: Batches::default(),
sketch: Batches::default(),
@@ -3443,6 +3528,15 @@ pub fn frame_key(cb: &Frame) -> u64 {
cb.ao_radius.to_bits().hash(&mut h);
cb.ao_samples.hash(&mut h);
cb.ssaa.to_bits().hash(&mut h);
+ // A drag's layer: the scene it holds and where it is drawn.
+ match &cb.moving {
+ Some(m) => {
+ true.hash(&mut h);
+ m.key.hash(&mut h);
+ m.transform.iter().flatten().for_each(|v| v.to_bits().hash(&mut h));
+ }
+ None => false.hash(&mut h),
+ }
for img in &cb.images {
img.id.hash(&mut h);
img.version.hash(&mut h);
@@ -3522,22 +3616,36 @@ impl Renderer {
return;
}
res.take_ready_tessellation();
- res.model.take(
- device,
- queue,
- &res.uniform,
- &res.uniform_bgl,
- cb.key,
- &cb.slot,
- res.tess.as_ref().map(|t| (t, &mut *encoder)),
- res.oit.is_some(),
- );
- res.sketch.take(device, queue, &res.uniform, &res.uniform_bgl, cb.sketch_key, &cb.sketch_slot, None, res.oit.is_some());
- res.highlight.take(device, queue, &res.uniform, &res.uniform_bgl, cb.hl_key, &cb.hl_slot, None, res.oit.is_some());
- res.preview.take(device, queue, &res.uniform, &res.uniform_bgl, cb.pv_key, &cb.pv_slot, None, res.oit.is_some());
+ // The moving layer first: a drag starting takes the dragged bodies' buffers over from
+ // the model scene before the model scene without them lets them go (and the model scene
+ // takes them back when the drag ends). The layer's palette is bound with its own uniform.
+ let oit = res.oit.is_some();
+ if let Some(mv) = &cb.moving {
+ let tess = res.tess.as_ref().map(|t| (t, &mut *encoder));
+ res.moving.take_sharing(device, queue, &res.moving_uniform, &res.uniform_bgl, mv.key, &mv.slot, tess, oit, Some(&mut res.model));
+ }
+ let tess = res.tess.as_ref().map(|t| (t, &mut *encoder));
+ res.model.take_sharing(device, queue, &res.uniform, &res.uniform_bgl, cb.key, &cb.slot, tess, oit, Some(&mut res.moving));
+ match &cb.moving {
+ Some(mv) => {
+ res.moving.sort_glass(queue, local_direction(&mv.transform, cb.back));
+ queue.write_buffer(&res.moving_uniform, 0, &uniform_bytes_moved(cb, res.linear_out, res.target.reversed_depth(), mv.transform));
+ res.moving_on = true;
+ }
+ // The drag is over: its buffers go.
+ None if res.moving_on => {
+ res.moving = Batches::default();
+ res.moving_on = false;
+ }
+ None => {}
+ }
+ res.sketch.take(device, queue, &res.uniform, &res.uniform_bgl, cb.sketch_key, &cb.sketch_slot, None, oit);
+ res.highlight.take(device, queue, &res.uniform, &res.uniform_bgl, cb.hl_key, &cb.hl_slot, None, oit);
+ res.preview.take(device, queue, &res.uniform, &res.uniform_bgl, cb.pv_key, &cb.pv_slot, None, oit);
// See-through surfaces are drawn without sorting where the device can (order-independent
// transparency, in an offscreen frame); else their triangles are sorted for the view.
- let see_through = res.oit.is_some() && res.model.see_through();
+ // The dragged bodies' own (their blocks' glass is drawn only there with it) count too.
+ let see_through = res.oit.is_some() && (res.model.see_through() || (res.moving_on && res.moving.see_through()));
if !see_through {
res.model.sort_glass(queue, cb.back);
}
@@ -3561,8 +3669,14 @@ impl Renderer {
res.access_version = a.version;
}
let preview = if cb.pv_hide { &res.empty } else { &res.preview };
- let ao_binds = [scene_bind(&res.model, &res.bind), scene_bind(preview, &res.bind)];
- res.ao.prepare(device, encoder, ao_binds, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, preview]);
+ // Each scene with its own palette's bind (the layer's carries its own uniform too).
+ let moving = res.moving_on.then(|| (scene_bind(&res.moving, &res.moving_bind), &res.moving));
+ let layers: Vec<(&wgpu::BindGroup, &Batches)> =
+ [Some((scene_bind(&res.model, &res.bind), &res.model)), moving, Some((scene_bind(preview, &res.bind), preview))]
+ .into_iter()
+ .flatten()
+ .collect();
+ res.ao.prepare(device, encoder, cb.ao_radius, cb.size_px, res.target.reversed_depth(), &layers);
// Images: upload new or changed textures, drop removed ones, rebuild the quads.
res.textures.retain(|id, _| cb.images.iter().any(|i| i.id == *id));
res.quads.clear();
@@ -3725,32 +3839,44 @@ impl Renderer {
} else {
(&res.model, &res.sketch, &res.highlight, &res.preview)
};
- // A block's triangles of one class, drawn from its canonical vertex buffer.
- let block_class = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, class: TriClass| {
- for key in &m.block_order {
- let Some(block) = m.blocks.get(key) else { continue };
+ // A scene's block triangles of one class, drawn from each block's canonical vertex buffer.
+ let blocks_of = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, class: TriClass, b: &Batches| {
+ for key in &b.block_order {
+ let Some(block) = b.blocks.get(key) else { continue };
if block.class(class).is_some() {
pass.set_pipeline(p);
block.draw(pass, class, tally);
}
}
};
+ let block_class = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, class: TriClass| blocks_of(pass, p, class, m);
+ // The dragged bodies ([`MovingLayer`]): drawn after the model's part of each step, with
+ // their own palette and uniform. The model's bind is set again after them.
+ let moving = (res.moving_on && !cb.product).then_some(&res.moving);
+ let in_moving = |pass: &mut wgpu::RenderPass<'static>, draw: &dyn Fn(&mut wgpu::RenderPass<'static>, &Batches)| {
+ if let Some(mv) = moving {
+ pass.set_bind_group(0, scene_bind(mv, &res.moving_bind), &[]);
+ draw(pass, mv);
+ pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
+ }
+ };
if phase == Phase::AfterSeeThrough {
pass.set_bind_group(1, &res.access_bind, &[]);
pass.set_bind_group(2, &res.ao.maps.bind, &[]);
- Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines);
+ Self::draw_over(res, pass, sk, h, pv, m, moving, &tris, &lines);
return;
}
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
lines(pass, &res.overlay, &m.under);
+ in_moving(pass, &|pass, mv| lines(pass, &res.overlay, &mv.under));
pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);
lines(pass, &res.overlay, &sk.under);
pass.set_bind_group(1, &res.access_bind, &[]);
pass.set_bind_group(2, &res.ao.maps.bind, &[]);
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
// `counting`: only closed bodies, for a section's crossing count ([`Cut::count`]).
- let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, counting: bool| {
- for d in m.planned.iter().filter(|d| d.class == TriClass::Opaque && (d.closed || !counting)) {
+ let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Batches, counting: bool| {
+ for d in b.planned.iter().filter(|d| d.class == TriClass::Opaque && (d.closed || !counting)) {
pass.set_pipeline(p);
pass.set_vertex_buffer(0, d.mesh.vertices.slice(..));
pass.set_vertex_buffer(1, d.colors.slice(..));
@@ -3760,11 +3886,12 @@ impl Renderer {
}
};
// Instanced meshes, with the pipeline for smooth and for flat triangles.
- let instanced = |pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline, counting: bool| {
- for d in m.instanced.iter().filter(|d| d.look == InstanceLook::Opaque && (d.closed || !counting)) {
- d.draw(pass, smooth, flat, tally);
- }
- };
+ let instanced =
+ |pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline, b: &Batches, counting: bool| {
+ for d in b.instanced.iter().filter(|d| d.look == InstanceLook::Opaque && (d.closed || !counting)) {
+ d.draw(pass, smooth, flat, tally);
+ }
+ };
// Whole highlighted bodies: the model's own evaluated plan triangles, drawn again in a
// highlight colour (the pipeline adds or replaces the vertex colour).
let tinted = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, plans: &[Arc<solidcraft_geom::tess::TessPlan>]| {
@@ -3826,8 +3953,22 @@ impl Renderer {
tris(pass, pick(cut), &m.open_tris);
block_class(pass, pick(cut), TriClass::Opaque);
}
- planned(pass, pick(cut_planned), counting);
- instanced(pass, pick(cut_instanced), pick(cut_flat), counting);
+ planned(pass, pick(cut_planned), m, counting);
+ instanced(pass, pick(cut_instanced), pick(cut_flat), m, counting);
+ in_moving(pass, &|pass, mv| {
+ tris(pass, pick(cut), &mv.tris);
+ if counting {
+ for block in mv.block_order.iter().filter_map(|k| mv.blocks.get(k)).filter(|b| b.closed.is_some()) {
+ pass.set_pipeline(pick(cut));
+ block.draw_closed(pass, tally);
+ }
+ } else {
+ tris(pass, pick(cut), &mv.open_tris);
+ blocks_of(pass, pick(cut), TriClass::Opaque, mv);
+ }
+ planned(pass, pick(cut_planned), mv, counting);
+ instanced(pass, pick(cut_instanced), pick(cut_flat), mv, counting);
+ });
pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]);
tris(pass, pick(cut), &pv.tris);
if !counting {
@@ -3848,8 +3989,15 @@ impl Renderer {
tris(pass, &res.tri, &m.tris);
tris(pass, &res.tri, &m.open_tris);
block_class(pass, &res.tri, TriClass::Opaque);
- planned(pass, &res.tri_planned, false);
- instanced(pass, &res.tri_instanced, &res.tri_instanced_flat, false);
+ planned(pass, &res.tri_planned, m, false);
+ instanced(pass, &res.tri_instanced, &res.tri_instanced_flat, m, false);
+ in_moving(pass, &|pass, mv| {
+ tris(pass, &res.tri, &mv.tris);
+ tris(pass, &res.tri, &mv.open_tris);
+ blocks_of(pass, &res.tri, TriClass::Opaque, mv);
+ planned(pass, &res.tri_planned, mv, false);
+ instanced(pass, &res.tri_instanced, &res.tri_instanced_flat, mv, false);
+ });
pass.set_bind_group(0, scene_bind(pv, &res.bind), &[]);
tris(pass, &res.tri, &pv.tris);
tris(pass, &res.tri, &pv.open_tris);
@@ -3860,6 +4008,7 @@ impl Renderer {
if !cb.product {
res.clouds.paint(pass, &res.cloud_pipes, tally);
}
+ in_moving(pass, &|pass, mv| tris(pass, &res.pbr, &mv.pbr));
// Whole-body tints first, so a face or an edge highlighted over the body (in `h.tris`
// and `h.lines`) keeps its own colour, as it did when the body's triangles were built
// into the same list before them.
@@ -3896,10 +4045,12 @@ impl Renderer {
// edge beside it there with a light line.
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
lines(pass, &res.line_hidden, &m.hidden);
+ in_moving(pass, &|pass, mv| lines(pass, &res.line_hidden, &mv.hidden));
pass.set_bind_group(0, scene_bind(h, &res.bind), &[]);
lines(pass, &res.line_hidden, &h.hidden);
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
lines(pass, &res.line, &m.lines);
+ in_moving(pass, &|pass, mv| lines(pass, &res.line, &mv.lines));
pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);
lines(pass, &res.line, &sk.lines);
pass.set_bind_group(0, scene_bind(h, &res.bind), &[]);
@@ -3935,19 +4086,30 @@ impl Renderer {
}
// See-through instanced meshes (placements back to front) with the rest of their kind.
let see_through =
- |pass: &mut wgpu::RenderPass<'static>, look: InstanceLook, (smooth, flat): &(wgpu::RenderPipeline, wgpu::RenderPipeline)| {
- for d in m.instanced.iter().filter(|d| d.look == look) {
+ |pass: &mut wgpu::RenderPass<'static>, look: InstanceLook, (smooth, flat): &(wgpu::RenderPipeline, wgpu::RenderPipeline), b: &Batches| {
+ for d in b.instanced.iter().filter(|d| d.look == look) {
d.draw(pass, smooth, flat, tally);
}
};
tris(pass, &res.glass_far, &m.glass);
- see_through(pass, InstanceLook::Glass, &res.glass_far_instanced);
+ see_through(pass, InstanceLook::Glass, &res.glass_far_instanced, m);
+ in_moving(pass, &|pass, mv| {
+ tris(pass, &res.glass_far, &mv.glass);
+ see_through(pass, InstanceLook::Glass, &res.glass_far_instanced, mv);
+ });
tris(pass, &res.glass_near, &m.glass);
- see_through(pass, InstanceLook::Glass, &res.glass_near_instanced);
+ see_through(pass, InstanceLook::Glass, &res.glass_near_instanced, m);
+ in_moving(pass, &|pass, mv| {
+ tris(pass, &res.glass_near, &mv.glass);
+ see_through(pass, InstanceLook::Glass, &res.glass_near_instanced, mv);
+ tris(pass, &res.trans, &mv.trans);
+ blocks_of(pass, &res.trans, TriClass::Faded, mv);
+ see_through(pass, InstanceLook::Faded, &res.trans_instanced, mv);
+ });
tris(pass, &res.trans, &m.trans);
block_class(pass, &res.trans, TriClass::Faded);
- see_through(pass, InstanceLook::Faded, &res.trans_instanced);
- Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines);
+ see_through(pass, InstanceLook::Faded, &res.trans_instanced, m);
+ Self::draw_over(res, pass, sk, h, pv, m, moving, &tris, &lines);
}
/// What is drawn over the model's see-through surfaces.
@@ -3959,6 +4121,7 @@ impl Renderer {
h: &Batches,
pv: &Batches,
m: &Batches,
+ moving: Option<&Batches>,
tris: &dyn Fn(&mut wgpu::RenderPass<'static>, &wgpu::RenderPipeline, &Option<Batch>),
lines: &dyn Fn(&mut wgpu::RenderPass<'static>, &wgpu::RenderPipeline, &Option<Batch>),
) {
@@ -3972,16 +4135,28 @@ impl Renderer {
tris(pass, &res.xray, &pv.xray);
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
lines(pass, &res.overlay, &m.overlays);
+ if let Some(mv) = moving {
+ pass.set_bind_group(0, scene_bind(mv, &res.moving_bind), &[]);
+ lines(pass, &res.overlay, &mv.overlays);
+ }
pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);
lines(pass, &res.overlay, &sk.overlays);
pass.set_bind_group(0, scene_bind(h, &res.bind), &[]);
lines(pass, &res.overlay, &h.overlays);
}
- /// The model's see-through surfaces into the order-independent transparency's targets.
+ /// The model's see-through surfaces into the order-independent transparency's targets, then
+ /// a drag's layer's with its own palette and uniform.
fn draw_see_through(&self, pass: &mut wgpu::RenderPass<'static>, p: &oit::Pipelines, tally: &Tally) {
- let m = &self.model;
- pass.set_bind_group(0, scene_bind(m, &self.bind), &[]);
+ Self::see_through_of(&self.model, scene_bind(&self.model, &self.bind), pass, p, tally);
+ if self.moving_on {
+ Self::see_through_of(&self.moving, scene_bind(&self.moving, &self.moving_bind), pass, p, tally);
+ }
+ }
+
+ /// One scene's see-through surfaces, drawn with `bind` (see [`Renderer::draw_see_through`]).
+ fn see_through_of(m: &Batches, bind: &wgpu::BindGroup, pass: &mut wgpu::RenderPass<'static>, p: &oit::Pipelines, tally: &Tally) {
+ pass.set_bind_group(0, bind, &[]);
pass.set_pipeline(&p.built);
for batch in [&m.glass, &m.trans].into_iter().flatten() {
for (buffer, count) in &batch.parts {
@@ -4301,6 +4476,21 @@ fn load_depth<T>(first: bool, clear: T) -> wgpu::LoadOp<T> {
/// Uniform bytes for a frame.
pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) -> Vec<u8> {
+ uniform_bytes_placing(cb, w, h, linear, reversed, IDENTITY)
+}
+
+/// Uniform bytes for the frame's moving layer: its scene drawn moved by `model`.
+fn uniform_bytes_moved(cb: &Frame, linear: bool, reversed: bool, model: [[f32; 4]; 4]) -> Vec<u8> {
+ uniform_bytes_placing(cb, cb.size_px[0], cb.size_px[1], linear, reversed, model)
+}
+
+/// The world direction `d` in the frame a rigid `model` moves from (its rotation turned back).
+fn local_direction(model: &[[f32; 4]; 4], d: [f32; 3]) -> [f32; 3] {
+ let column = |c: usize| model.get(c).map_or(0.0, |col| col[0] * d[0] + col[1] * d[1] + col[2] * d[2]);
+ [column(0), column(1), column(2)]
+}
+
+fn uniform_bytes_placing(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool, model: [[f32; 4]; 4]) -> Vec<u8> {
let mut v: Vec<f32> = gpu_view_proj(cb.view_proj, reversed).iter().flatten().copied().collect();
v.extend([cb.back[0], cb.back[1], cb.back[2], if linear { 1.0 } else { 0.0 }]);
v.extend([w.max(1.0), h.max(1.0), 0.0, if cb.outline { 1.0 } else { 0.0 }]);
@@ -4318,6 +4508,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) -
v.extend([cb.ao_radius, cb.ao_samples.clamp(1, AO_SAMPLES) as f32, 0.0, 0.0]);
v.extend(cb.analysis_colors);
v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]);
+ v.extend(model.iter().flatten());
v.extend([cb.hover_tint[0], cb.hover_tint[1], cb.hover_tint[2], 0.0]);
v.extend([cb.selection_tint[0], cb.selection_tint[1], cb.selection_tint[2], 0.0]);
for [r, g, b] in cb.hatch {
@@ -4601,6 +4792,7 @@ mod tests {
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
outline: false,
eye: [0.0; 4],
ao_radius: 0.0,
@@ -4610,6 +4802,28 @@ mod tests {
}
}
+ /// A drag's layer is part of what a frame draws: a still frame is not blitted from the
+ /// picture drawn before the layer moved, changed scene or went away.
+ #[test]
+ fn a_frame_is_redrawn_when_its_drag_layer_changes() {
+ use std::sync::{Arc, Mutex};
+ let layer = |key: u64, x: f32| super::MovingLayer {
+ key,
+ slot: Arc::new(Mutex::new(None)),
+ transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [x, 0.0, 0.0, 1.0]],
+ };
+ let key = |moving: Option<super::MovingLayer>| {
+ let mut f = cached_frame();
+ f.moving = moving;
+ super::frame_key(&f)
+ };
+ let base = key(Some(layer(5, 0.0)));
+ assert_eq!(base, key(Some(layer(5, 0.0))), "the same layer draws the same picture");
+ for (what, changed) in [("no layer", key(None)), ("layer moved", key(Some(layer(5, 1.0)))), ("layer scene", key(Some(layer(6, 0.0))))] {
+ assert_ne!(base, changed, "{what} must draw again");
+ }
+ }
+
fn image(version: u64) -> super::GpuImage {
super::GpuImage { id: 1, version, size: [2, 2], rgba: std::sync::Arc::new(vec![0; 16]), corners: [[0.0; 3]; 4], opacity: 1.0 }
}
@@ -5067,6 +5281,7 @@ mod glass_tests {
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
};
let texture = |format, usage, sample_count| {
device.create_texture(&wgpu::TextureDescriptor {
@@ -5239,6 +5454,7 @@ mod glass_tests {
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
outline: false,
eye: [0.0, 0.0, 100.0, 0.0],
ao_radius: 0.0,
diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rs
index 0c6392b19c..3df6f17a07 100644
--- a/crates/gpu/src/view/ao.rs
+++ b/crates/gpu/src/view/ao.rs
@@ -154,9 +154,10 @@ fn term_target(view: &wgpu::TextureView) -> Option<wgpu::RenderPassColorAttachme
})
}
-/// The opaque triangles of `batches`, as neither pass counts them in the performance overlay.
-fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, binds: [&wgpu::BindGroup; 2], batches: [&Batches; 2]) {
- for (batch, bind) in batches.into_iter().zip(binds) {
+/// The opaque triangles of each scene in `layers` (its group 0 bind and batches), as neither pass
+/// counts them in the performance overlay.
+fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, layers: &[(&wgpu::BindGroup, &Batches)]) {
+ for &(bind, batch) in layers {
pass.set_bind_group(0, bind, &[]);
pass.set_pipeline(&pipelines.built);
for tris in [&batch.tris, &batch.open_tris, &batch.ground_ao].into_iter().flatten() {
@@ -291,11 +292,10 @@ impl Resources {
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
- binds: [&wgpu::BindGroup; 2],
radius: f32,
size_px: [f32; 2],
reversed: bool,
- batches: [&Batches; 2],
+ layers: &[(&wgpu::BindGroup, &Batches)],
) {
let enabled = radius.is_finite() && radius > 0.0;
// Bound memory at large window sizes; normalized coordinates also handle downsampling.
@@ -304,9 +304,10 @@ impl Resources {
self.maps = maps(device, &self.layout, size);
self.size = size;
}
- if !enabled {
+ // The blur reads the frame's uniform through the first scene's bind (the model's).
+ let Some(&(first, _)) = layers.first().filter(|_| enabled) else {
return;
- }
+ };
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_ao_prepass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
@@ -327,7 +328,7 @@ impl Resources {
occlusion_query_set: None,
multiview_mask: None,
});
- draw_opaque(&mut pass, &self.prepass, binds, batches);
+ draw_opaque(&mut pass, &self.prepass, layers);
drop(pass);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_ao_term"),
@@ -342,7 +343,7 @@ impl Resources {
multiview_mask: None,
});
pass.set_bind_group(2, &self.maps.bind, &[]);
- draw_opaque(&mut pass, &self.term, binds, batches);
+ draw_opaque(&mut pass, &self.term, layers);
drop(pass);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_ao_blur"),
@@ -353,7 +354,7 @@ impl Resources {
multiview_mask: None,
});
pass.set_pipeline(&self.blur);
- pass.set_bind_group(0, binds[0], &[]);
+ pass.set_bind_group(0, first, &[]);
pass.set_bind_group(2, &self.maps.blur_bind, &[]);
pass.draw(0..3, 0..1);
}
diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rs
index 8a846959b7..123e89422f 100644
--- a/crates/gpu/src/view/msaa_check.rs
+++ b/crates/gpu/src/view/msaa_check.rs
@@ -127,6 +127,7 @@ impl Renderer {
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
};
let size = wgpu::Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 };
let color = device.create_texture(&wgpu::TextureDescriptor {
diff --git a/crates/gpu/tests/ground_ao_measurement.rs b/crates/gpu/tests/ground_ao_measurement.rs
index a8104dd44d..0fed157945 100644
--- a/crates/gpu/tests/ground_ao_measurement.rs
+++ b/crates/gpu/tests/ground_ao_measurement.rs
@@ -232,6 +232,7 @@ fn comparison_frame(scene: GpuScene, cam: &Camera, width: u32, height: u32, key:
hatch: Default::default(),
sky: [0.0; 4],
ssaa: 1.0,
+ moving: None,
}
}
diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs
index 436a4b18d2..1b09f2f754 100644
--- a/crates/ui-egui/src/gpu.rs
+++ b/crates/ui-egui/src/gpu.rs
@@ -9,8 +9,8 @@ use std::sync::{Arc, Mutex};
use egui_wgpu::wgpu;
pub use solidcraft_gpu::view::{
AccessMap, BlockBuilder, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook,
- InstancedMesh, LINE_SIZE, LOD_PX, MAX_PALETTE, PBR_SIZE, Palette, PaletteIndex, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot,
- SharedTris, TRI_SIZE, TriClass, UploadError, extend_runs, level_for, lifted_width, placement_scale, runs_within, supersampled_size,
+ InstancedMesh, LINE_SIZE, LOD_PX, MAX_PALETTE, MovingLayer, PBR_SIZE, Palette, PaletteIndex, PlannedBody, Renderer, SHARED_SIZE, SceneBlock,
+ SceneSlot, SharedTris, TRI_SIZE, TriClass, UploadError, extend_runs, level_for, lifted_width, placement_scale, runs_within, supersampled_size,
};
/// A frame of the viewport as an egui paint callback.
@@ -572,6 +572,7 @@ fn offscreen(
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
});
let texture = |format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 7a11fc3c12..fc4331a7ca 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -1673,6 +1673,11 @@ preference_settings! {
ellipse_axes: bool = true, PAGE_SKETCH;
/// Drive Joints shows the moved parts' old place as a ghost (its Show ghost box, #5905).
drive_joints_ghost: bool = true, PAGE_TOOLS => check_tr("prefs.design_tools.ghost");
+ /// While Move's triad drags a component drawn as a layer of its own, what is under the pointer
+ /// is still picked and highlighted, as before #7273. Off by default: such a drag picks nothing,
+ /// so a step neither meshes the dragged bodies where they stand nor looks up the Browser row a
+ /// highlight follows (`drag_layer::holds_pointer`).
+ move_drag_highlights: bool = false, PAGE_TOOLS => check_id("prefs.move_drag_highlights");
/// Plugin ids turned off (Preferences › Plugins). An installed plugin whose id is absent is on.
disabled_plugins: std::collections::BTreeSet<String> = std::collections::BTreeSet::new(), PAGE_PLUGINS;
}
diff --git a/crates/ui-egui/src/prefs/tools.rs b/crates/ui-egui/src/prefs/tools.rs
index 627921872c..24ab1196ff 100644
--- a/crates/ui-egui/src/prefs/tools.rs
+++ b/crates/ui-egui/src/prefs/tools.rs
@@ -79,6 +79,14 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
});
let response = setting::drive_joints_ghost(app, ui);
crate::scenario::publish_target("prefs:drive_joints_ghost", response.rect);
+ ui.horizontal_wrapped(|ui| {
+ let tip = app.tr("prefs.move_drag_highlights_tip");
+ let response = setting::move_drag_highlights(app, ui).backing_on_hover_text(tip);
+ crate::scenario::publish_target("prefs:move_drag_highlights", response.rect);
+ if !crate::prefs_search::suppress_chrome(ui) {
+ ui_kit::help_icon(ui, tip);
+ }
+ });
let label_width =
["joint_move.coarse", "joint_move.fine"].into_iter().map(|id| ui_kit::ContentWidth::label(ui, app.tr(id))).fold(0.0, f32::max)
+ t.space_16
diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs
index aebab4f88c..5c74f926ed 100644
--- a/crates/ui-egui/src/render_workspace.rs
+++ b/crates/ui-egui/src/render_workspace.rs
@@ -2406,6 +2406,7 @@ fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera
[f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0]
},
hatch: Default::default(),
+ moving: None,
});
crate::blur::viewport(ui.painter(), rect, callback, rect, [background.viewport_top, background.viewport_bottom]);
Ok(())
diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs
index 29f0f1f344..d92b2d537a 100644
--- a/crates/ui-egui/src/scale_tests.rs
+++ b/crates/ui-egui/src/scale_tests.rs
@@ -297,6 +297,7 @@ pub(crate) fn view_frame(
hover_tint: [f32::from(t.hover_face_lift) / 255.0; 3],
selection_tint: [0.4, 0.6, 0.9],
hatch: Default::default(),
+ moving: None,
}
}
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 8bda105dad..bc8b8da38a 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -53,6 +53,9 @@ mod body_gizmo;
#[path = "navigation_cube.rs"]
mod navigation_cube;
+#[path = "viewport_drag_layer.rs"]
+mod drag_layer;
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NavMode {
Orbit,
@@ -160,6 +163,13 @@ pub struct ViewportState {
pub(crate) hl_key: u64,
/// Browser/timeline body feedback, independent of the camera and reference widget scale.
hover_block: std::sync::Mutex<Option<HoverBlock>>,
+ /// A component's Move triad drag drawn as a layer of its own (`viewport_drag_layer.rs`),
+ /// the world the last whole model scene was built from (where such a drag begins), and the
+ /// dragged bodies' scene.
+ drag: Option<drag_layer::DragLayer>,
+ scene_world: Option<drag_layer::SceneWorld>,
+ moving_slot: SceneSlot,
+ moving_key: u64,
/// Each shown body the model builds on the CPU: the block of the model scene that holds its
/// triangles, and the body's index and vertex ranges in it (for whole-body highlights).
body_tris: std::sync::Mutex<std::collections::HashMap<String, crate::gpu::BlockTris>>,
@@ -594,13 +604,21 @@ fn scene_key(app: &SolveApp) -> u64 {
(std::sync::Arc::as_ptr(&app.session.doc) as usize).hash(&mut h);
app.session.colored_components.hash(&mut h);
(std::sync::Arc::as_ptr(&crate::open_meshing::shown_world(app)) as usize).hash(&mut h);
+ base_scene_key(app).hash(&mut h);
+ lod_generation(app).hash(&mut h);
+ app.viewport.mesh_lods.generation().hash(&mut h);
+ h.finish()
+}
+
+/// Everything the model scene shows but the world, the session's revision and the display
+/// refinement (a drag drawn as a layer keeps the refinement it began with).
+fn base_scene_key(app: &SolveApp) -> u64 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
app.ui.visual_style.hash(&mut h);
app.preferences.vertex_markers.hash(&mut h);
// The cached ground AO receiver and the ellipse share the selected ground plane.
app.preferences.ground_shadow_follows_model.hash(&mut h);
solidcraft_engine::doc::display_quality::current().hash(&mut h);
- lod_generation(app).hash(&mut h);
- app.viewport.mesh_lods.generation().hash(&mut h);
// How bodies are drawn: from their plans on the GPU, or built here (until the evaluation
// shader has compiled, #4860).
app.viewport.gpu.is_some_and(|g| g.tess).hash(&mut h);
@@ -1436,8 +1454,11 @@ struct Instances {
impl Instances {
/// Keep reference meshes at every size: their triangles do not change when a joint moves.
/// Other bodies share triangles when repeated or large enough to warrant a separate draw.
- fn new(app: &SolveApp, shown: &[&solidcraft_engine::doc::ModelBody], shaded: bool) -> Instances {
- let kept = app.viewport.instanced_tris.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();
+ ///
+ /// A scene of only some of the bodies (`whole` false: a drag's layer and the model beside
+ /// it) leaves the kept triangles of the others where they are.
+ fn new(app: &SolveApp, shown: &[&solidcraft_engine::doc::ModelBody], shaded: bool, whole: bool) -> Instances {
+ let kept = app.viewport.instanced_tris.lock().map(|mut k| if whole { std::mem::take(&mut *k) } else { k.clone() }).unwrap_or_default();
let mut candidates = std::collections::HashMap::new();
if shaded {
let mut uses: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
@@ -1502,13 +1523,20 @@ impl Instances {
Some((mesh, m))
}
- /// The instanced meshes, keeping their triangles for the next scene.
- fn finish(self, app: &SolveApp) -> Vec<crate::gpu::InstancedMesh> {
+ /// The instanced meshes, keeping their triangles for the next scene (and, for a scene of
+ /// only some bodies, the others' too: their levels of detail stay).
+ fn finish(self, app: &SolveApp, whole: bool) -> Vec<crate::gpu::InstancedMesh> {
let kept: InstancedTris =
self.meshes.iter().map(|(mesh, inst)| (std::sync::Arc::as_ptr(mesh) as usize, (mesh.clone(), inst.tris.clone()))).collect();
- self.lods.retain(&kept.keys().copied().collect());
+ if whole {
+ self.lods.retain(&kept.keys().copied().collect());
+ }
if let Ok(mut k) = app.viewport.instanced_tris.lock() {
- *k = kept;
+ if whole {
+ *k = kept;
+ } else {
+ k.extend(kept);
+ }
}
self.meshes.into_iter().map(|(_, inst)| inst).collect()
}
@@ -1529,10 +1557,135 @@ fn shared_mesh(
}
pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
- let tk = Tokens::get();
- let s = &app.session;
// Bodies where their occurrences place them.
let st = crate::open_meshing::shown_world(app);
+ // The blocks the last scene built, reused when their bodies come back as they were.
+ let mut kept = app.viewport.blocks.lock().map(|mut b| std::mem::take(&mut *b)).unwrap_or_default();
+ let (mut sc, made) = body_scene(app, &st, |_| true, true, &mut kept);
+ keep_body_tris(app, &made);
+ if let Ok(mut b) = app.viewport.blocks.lock() {
+ *b = made;
+ }
+ sc.ground_ao = ground_ao(app, ground_bounds(app, &st));
+ section_outlines(&mut sc, app, &st);
+ continuity_seams(&mut sc, app);
+ isocurves(&mut sc, app);
+ crate::edit_in_place::draw_context(app, &mut sc);
+ sc
+}
+
+/// Section: the outline of each body where the plane cuts it, in the view's text colour (#4146),
+/// and the cut solid bodies' hatches by part on their palette entries.
+fn section_outlines(sc: &mut GpuScene, app: &SolveApp, st: &solidcraft_engine::doc::ModelState) {
+ let Some((o, n)) = section_plane(app) else { return };
+ let s = &app.session;
+ let active_bodies = active_body_names(app);
+ let col = sc.color(c4(Tokens::view().text.gamma_multiply(0.9)));
+ let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();
+ let mut made = std::collections::HashMap::with_capacity(kept.len());
+ // The closed solid bodies the plane cuts and where it cuts them: their hatches by part.
+ let by_part = app.preferences.section_hatch == crate::prefs::SectionHatch::ByPart;
+ let mut cuts: Vec<(&str, Vec<(Vec3, Vec3)>)> = Vec::new();
+ for b in st.bodies.iter().filter(|b| app.body_visible(&b.name)) {
+ let mesh = b.mesh();
+ let key = std::sync::Arc::as_ptr(&mesh) as usize;
+ let index = match kept.remove(&key).filter(|(m, _)| std::sync::Arc::ptr_eq(m, &mesh)) {
+ Some((_, index)) => index,
+ None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh)),
+ };
+ let segments = index.segments(&mesh, o, n);
+ for (a, c) in &segments {
+ sc.line(a.to_f32(), c.to_f32(), col, 1.8, false);
+ }
+ made.insert(key, (mesh, index));
+ let solid = b.is_closed() && !body_faded(app, b, &active_bodies) && s.doc.model_body_opacity(b) >= 0.999;
+ if by_part && solid && !segments.is_empty() {
+ cuts.push((b.name.as_str(), segments));
+ }
+ }
+ // Each cut body's hatch on all its palette entries (its colour, faces and placements).
+ let parts: Vec<solidcraft_engine::render::hatch::CutPart> = cuts
+ .iter()
+ .map(|(name, segments)| solidcraft_engine::render::hatch::CutPart { seed: solidcraft_engine::render::hatch::seed(name), segments })
+ .collect();
+ let hatches = solidcraft_engine::render::hatch::hatches(&parts, n);
+ let arena = app.viewport.palette.lock().unwrap_or_else(|e| e.into_inner());
+ let palette = std::sync::Arc::make_mut(&mut sc.palette);
+ for ((name, _), hatch) in cuts.iter().zip(hatches) {
+ let Some(slots) = arena.slots(name) else { continue };
+ for slot in (0..slots.face_capacity as usize).map(|f| slots.face(f)).chain([slots.body, slots.instance]) {
+ palette.set_hatch(slot, hatch);
+ }
+ }
+ if let Ok(mut k) = app.viewport.section_index.lock() {
+ *k = made;
+ }
+}
+
+/// Isocurve Analysis: the isoparametric curves of each face it shows, on the faces (depth
+/// tested, as edges are).
+fn isocurves(sc: &mut GpuScene, app: &SolveApp) {
+ let iso = app.session.isocurve_lines();
+ if !iso.is_empty() {
+ let col = sc.color(c4(Tokens::get().accent));
+ for line in iso.iter().flat_map(|lines| lines.iter()) {
+ for w in line.points.windows(2) {
+ if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
+ sc.line(a.to_f32(), b.to_f32(), col, 1.4, false);
+ }
+ }
+ }
+ }
+}
+
+/// Continuity analysis: each seam `inspect.continuity` measured, drawn over the model in the
+/// colour of its worst verdict.
+fn continuity_seams(sc: &mut GpuScene, app: &SolveApp) {
+ let tk = Tokens::get();
+ let s = &app.session;
+ for (seam, detail) in s.continuity.iter().zip(s.continuity_details()) {
+ if !detail.current {
+ continue;
+ }
+ let col = sc.color(c4(continuity_color(&tk, seam.order)));
+ let width = seam_width(seam.order);
+ for w in seam.points.windows(2) {
+ if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
+ sc.line(a.to_f32(), b.to_f32(), col, width, true);
+ }
+ }
+ }
+}
+
+/// Where each CPU-built body's triangles are in the model's blocks, for whole-body
+/// highlights (see `highlight_block_tris`).
+fn keep_body_tris(app: &SolveApp, made: &std::collections::HashMap<u64, CachedBlock>) {
+ let mut body_tris = std::collections::HashMap::new();
+ for (key, c) in made {
+ for range in &c.ranges {
+ if !range.vertices.is_empty() {
+ body_tris
+ .insert(range.name.clone(), crate::gpu::BlockTris { block: *key, tris: range.opaque.clone(), vertices: range.vertices.clone() });
+ }
+ }
+ }
+ if let Ok(mut m) = app.viewport.body_tris.lock() {
+ *m = body_tris;
+ }
+}
+
+/// The scene of the shown bodies of `st` that `takes` (by their place in it) and nothing else,
+/// built from the blocks in `kept` where their bodies come back as they were; with the blocks
+/// it holds by key. `whole`: all of the shown bodies (see [`Instances::new`]).
+fn body_scene(
+ app: &SolveApp,
+ st: &solidcraft_engine::doc::ModelState,
+ takes: impl Fn(usize) -> bool,
+ whole: bool,
+ kept: &mut std::collections::HashMap<u64, CachedBlock>,
+) -> (GpuScene, std::collections::HashMap<u64, CachedBlock>) {
+ let tk = Tokens::get();
+ let s = &app.session;
let active_bodies = active_body_names(app);
let (shaded, edges) = match app.ui.visual_style {
1 => (true, false),
@@ -1545,10 +1698,14 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
// Vertex markers are an option (#7834), off by default.
let markers = app.preferences.vertex_markers;
let hidden_col = c4(tk.text.gamma_multiply(0.35));
+ // Every shown body, and the ones this scene takes. The arena and the appearance cache
+ // keep every shown body, so a scene of some of them (a drag drawn as a layer) leaves the
+ // others' slots and looks as they were.
+ let visible = |b: &&solidcraft_engine::doc::ModelBody| app.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name);
+ let shown_names: Vec<&str> = st.bodies.iter().filter(visible).map(|b| b.name.as_str()).collect();
let shown: Vec<&solidcraft_engine::doc::ModelBody> =
- st.bodies.iter().filter(|b| app.body_visible(&b.name) && !app.preview.effective_replaced().contains(&b.name)).collect();
+ st.bodies.iter().enumerate().filter(|(i, b)| takes(*i) && visible(b)).map(|(_, b)| b).collect();
let mut arena = app.viewport.palette.lock().unwrap_or_else(|e| e.into_inner());
- let shown_names: Vec<&str> = shown.iter().map(|b| b.name.as_str()).collect();
arena.sync(shown_names.iter().copied());
// Allocate every body's slots before the scene's palette is copied, so the stable prefix
// covers them; the colours themselves are written in the loop below, into both the arena
@@ -1567,15 +1724,13 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
// key comes back unchanged are still reused.
appearance.keys.clear();
}
- // The blocks the last scene built, reused when their bodies come back as they were.
- let mut kept = app.viewport.blocks.lock().map(|mut b| std::mem::take(&mut *b)).unwrap_or_default();
let mut made: std::collections::HashMap<u64, CachedBlock> = std::collections::HashMap::new();
let mut run: Vec<BodyDraw> = Vec::new();
let mut run_key = std::collections::hash_map::DefaultHasher::new();
// Bodies drawn from the same triangles more than once (a part placed by many occurrences)
// are drawn as instances of them: one copy of the triangles on the GPU, and none moved on
// the CPU.
- let mut instances = Instances::new(app, &shown, shaded);
+ let mut instances = Instances::new(app, &shown, shaded, whole);
let mut thread_budget = solidcraft_engine::cosmetic_threads::Budget::default();
for (b, slots) in shown.into_iter().zip(slots) {
let faded = body_faded(app, b, &active_bodies);
@@ -1704,25 +1859,11 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
if key.is_multiple_of(16) || run.len() >= 64 {
let draws = std::mem::take(&mut run);
let block_key = std::mem::replace(&mut run_key, std::collections::hash_map::DefaultHasher::new()).finish();
- push_block(&mut sc, &mut kept, &mut made, block_key, draws, shaded, |d, out| d.build(out, shaded, edges, hidden_edges, markers));
+ push_block(&mut sc, kept, &mut made, block_key, draws, shaded, |d, out| d.build(out, shaded, edges, hidden_edges, markers));
}
}
if !run.is_empty() {
- push_block(&mut sc, &mut kept, &mut made, run_key.finish(), run, shaded, |d, out| d.build(out, shaded, edges, hidden_edges, markers));
- }
- // Where each CPU-built body's triangles are in the model's blocks, for whole-body
- // highlights (see `highlight_block_tris`).
- let mut body_tris = std::collections::HashMap::new();
- for (key, c) in &made {
- for range in &c.ranges {
- if !range.vertices.is_empty() {
- body_tris
- .insert(range.name.clone(), crate::gpu::BlockTris { block: *key, tris: range.opaque.clone(), vertices: range.vertices.clone() });
- }
- }
- }
- if let Ok(mut m) = app.viewport.body_tris.lock() {
- *m = body_tris;
+ push_block(&mut sc, kept, &mut made, run_key.finish(), run, shaded, |d, out| d.build(out, shaded, edges, hidden_edges, markers));
}
// Every shown body has its entries, so only a larger map holds bodies no longer shown.
if appearance.bodies.len() > shown_names.len() || appearance.keys.len() > shown_names.len() {
@@ -1730,87 +1871,8 @@ pub(crate) fn build_scene(app: &SolveApp) -> GpuScene {
appearance.bodies.retain(|name, _| names.contains(name.as_str()));
appearance.keys.retain(|name, _| names.contains(name.as_str()));
}
- if let Ok(mut b) = app.viewport.blocks.lock() {
- *b = made;
- }
- sc.instanced = instances.finish(app);
- if app.ui.visual_style != 2 {
- let bounds = ground_bounds(app, &st);
- let radius = (bounds.diagonal() * 0.04).clamp(1e-4, 1e6) as f32;
- sc.ground_ao = solidcraft_gpu::view::GroundAo::new(bounds, ground_height(app, bounds), app.cam.up, radius);
- }
- // Section: the outline of each body where the plane cuts it, in the view's text colour (#4146).
- if let Some((o, n)) = section_plane(app) {
- let col = sc.color(c4(Tokens::view().text.gamma_multiply(0.9)));
- let mut kept = app.viewport.section_index.lock().map(|mut k| std::mem::take(&mut *k)).unwrap_or_default();
- let mut made = std::collections::HashMap::with_capacity(kept.len());
- // The closed solid bodies the plane cuts and where it cuts them: their hatches by part.
- let by_part = app.preferences.section_hatch == crate::prefs::SectionHatch::ByPart;
- let mut cuts: Vec<(&str, Vec<(Vec3, Vec3)>)> = Vec::new();
- for b in st.bodies.iter().filter(|b| app.body_visible(&b.name)) {
- let mesh = b.mesh();
- let key = std::sync::Arc::as_ptr(&mesh) as usize;
- let index = match kept.remove(&key).filter(|(m, _)| std::sync::Arc::ptr_eq(m, &mesh)) {
- Some((_, index)) => index,
- None => std::sync::Arc::new(solidcraft_engine::view::SectionIndex::new(&mesh)),
- };
- let segments = index.segments(&mesh, o, n);
- for (a, c) in &segments {
- sc.line(a.to_f32(), c.to_f32(), col, 1.8, false);
- }
- made.insert(key, (mesh, index));
- let solid = b.is_closed() && !body_faded(app, b, &active_bodies) && s.doc.model_body_opacity(b) >= 0.999;
- if by_part && solid && !segments.is_empty() {
- cuts.push((b.name.as_str(), segments));
- }
- }
- // Each cut body's hatch on all its palette entries (its colour, faces and placements).
- let parts: Vec<solidcraft_engine::render::hatch::CutPart> = cuts
- .iter()
- .map(|(name, segments)| solidcraft_engine::render::hatch::CutPart { seed: solidcraft_engine::render::hatch::seed(name), segments })
- .collect();
- let hatches = solidcraft_engine::render::hatch::hatches(&parts, n);
- let palette = std::sync::Arc::make_mut(&mut sc.palette);
- for ((name, _), hatch) in cuts.iter().zip(hatches) {
- let Some(slots) = arena.slots(name) else { continue };
- for slot in (0..slots.face_capacity as usize).map(|f| slots.face(f)).chain([slots.body, slots.instance]) {
- palette.set_hatch(slot, hatch);
- }
- }
- if let Ok(mut k) = app.viewport.section_index.lock() {
- *k = made;
- }
- }
- // Continuity analysis: each seam `inspect.continuity` measured, drawn over the model in the
- // colour of its worst verdict.
- for (seam, detail) in s.continuity.iter().zip(s.continuity_details()) {
- if !detail.current {
- continue;
- }
- let col = sc.color(c4(continuity_color(&tk, seam.order)));
- let width = seam_width(seam.order);
- for w in seam.points.windows(2) {
- if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
- sc.line(a.to_f32(), b.to_f32(), col, width, true);
- }
- }
- }
- // Isocurve Analysis: the isoparametric curves of each face it shows, on the faces (depth
- // tested, as edges are).
- let iso = s.isocurve_lines();
- if !iso.is_empty() {
- let col = sc.color(c4(tk.accent));
- for line in iso.iter().flat_map(|lines| lines.iter()) {
- for w in line.points.windows(2) {
- if let (Some(a), Some(b)) = (w.first(), w.get(1)) {
- sc.line(a.to_f32(), b.to_f32(), col, 1.4, false);
- }
- }
- }
- }
- crate::edit_in_place::draw_context(app, &mut sc);
-
- sc
+ sc.instanced = instances.finish(app, whole);
+ (sc, made)
}
/// The colour of a measured seam whose highest order met is `order`, from the theme's
@@ -2056,21 +2118,38 @@ fn shadow_geometry(app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::M
/// A soft dark ellipse on the ground under the shown bodies (darkest in the middle).
fn ground_bounds(app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::ModelState>) -> solidcraft_engine::geom::Aabb3 {
+ let boxes = body_bounds(app, st);
+ let shown = st.bodies.iter().zip(boxes.iter()).filter(|(x, (_, bb))| !bb.is_empty() && app.body_visible(&x.name));
+ frame_bounds(app, shown.flat_map(|(_, (_, bb))| box_corners(bb)))
+}
+
+/// The corners of a box.
+fn box_corners(bb: &solidcraft_engine::geom::Aabb3) -> [Vec3; 8] {
+ std::array::from_fn(|i| {
+ Vec3::new(
+ if i & 1 == 0 { bb.min.x } else { bb.max.x },
+ if i & 2 == 0 { bb.min.y } else { bb.max.y },
+ if i & 4 == 0 { bb.min.z } else { bb.max.z },
+ )
+ })
+}
+
+/// The ground the model's ambient occlusion darkens (#3413) under the bodies whose box in the
+/// camera's frame is `bounds`; none in Wireframe.
+fn ground_ao(app: &SolveApp, bounds: solidcraft_engine::geom::Aabb3) -> Option<solidcraft_gpu::view::GroundAo> {
+ if app.ui.visual_style == 2 {
+ return None;
+ }
+ let radius = (bounds.diagonal() * 0.04).clamp(1e-4, 1e6) as f32;
+ solidcraft_gpu::view::GroundAo::new(bounds, ground_height(app, bounds), app.cam.up, radius)
+}
+
+/// The box around `corners` in the camera's Z-up frame.
+fn frame_bounds(app: &SolveApp, corners: impl Iterator<Item = Vec3>) -> solidcraft_engine::geom::Aabb3 {
// The bodies' box in the camera's Z-up frame (the ground is its XY plane).
let mut b = solidcraft_engine::geom::Aabb3::EMPTY;
- let boxes = body_bounds(app, st);
- for (x, (_, bb)) in st.bodies.iter().zip(boxes.iter()) {
- if bb.is_empty() || !app.body_visible(&x.name) {
- continue;
- }
- for i in 0..8 {
- let p = Vec3::new(
- if i & 1 == 0 { bb.min.x } else { bb.max.x },
- if i & 2 == 0 { bb.min.y } else { bb.max.y },
- if i & 4 == 0 { bb.min.z } else { bb.max.z },
- );
- b.add(app.cam.to_frame(p));
- }
+ for p in corners {
+ b.add(app.cam.to_frame(p));
}
b
}
@@ -2396,6 +2475,13 @@ pub(crate) fn body_bounds(
std::sync::Arc::new(Vec::new())
}
+/// `boxes` are the boxes of `st`'s bodies (worked out without its meshes).
+fn known_body_bounds(app: &SolveApp, st: &std::sync::Arc<solidcraft_engine::doc::ModelState>, boxes: Vec<(String, solidcraft_engine::geom::Aabb3)>) {
+ if let Ok(mut g) = app.viewport.pick_bounds.lock() {
+ *g = Some((st.clone(), std::sync::Arc::new(boxes)));
+ }
+}
+
type BodyBounds = (std::sync::Arc<solidcraft_engine::doc::ModelState>, std::sync::Arc<Vec<(String, solidcraft_engine::geom::Aabb3)>>);
/// The model's extent: bodies (from the cached boxes) and sketches.
@@ -4083,6 +4169,11 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
let st = crate::open_meshing::shown_world(app);
let s = &app.session;
let active_bodies = active_body_names(app);
+ // Whole bodies are lit by drawing the model's own triangles again, but a drag drawn as a layer
+ // moves its bodies' triangles on the GPU from where the drag found them: those are built
+ // where they stand.
+ let dragged = drag_layer::dragged_names(app);
+ let gpu_lit = |b: &solidcraft_engine::doc::ModelBody| !dragged.contains(b.name.as_str());
// Faces lit over the model use the triangles the model shows them with.
let product = crate::render_workspace::active(app);
// Bodies a Move dialog moves are lit where they stand (as they are picked). While its triad
@@ -4295,7 +4386,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
&& app.body_visible(name)
{
let lit = WholeBody { selected: true, colour: c4(t.body_selected) };
- if !light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut selected_instances) {
+ if !(gpu_lit(b) && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut selected_instances)) {
let m = shown(b);
let count = b.body.face_count();
mesh_tris(&mut feedback, &m, c4(t.body_selected), true, |f| (f as usize) < count);
@@ -4427,7 +4518,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
// A whole body the model draws from a plan is lit by redrawing the plan's own
// evaluated triangles, not by building every triangle again (see `highlight_plan`).
let lit = WholeBody { selected: false, colour: hover_col };
- if whole && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut hover_instances) {
+ if whole && gpu_lit(b) && light_whole_body(app, b, &active_bodies, lit, &body_slots, &mut feedback, &mut hover_instances) {
// Drawn again from what the model already has on the GPU.
} else {
let lit = shown(b);
@@ -4668,6 +4759,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let t = Tokens::get();
let rect = ui.max_rect();
app.viewport.rect = Some(rect);
+ // A component dragged as a layer is drawn from the meshes where its drag began.
+ let layered = drag_layer::follow(app);
refresh_layout(app, ui.ctx());
let resp = ui.interact(rect, ui.scope_id().with("viewport"), Sense::click_and_drag());
let flat = crate::dialogs_sheet::flat_active(app);
@@ -4724,9 +4817,14 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|| app.viewport.spin
|| app.cam_anim.is_some();
let joint_handle_pointer = hover.is_some_and(|p| inside && crate::joint_handles::owns_pointer(app, &proj, p));
- // A part dragged along its joint owns the pointer: nothing under it lights up (#5137).
+ // Nor while a component's triad drags it as a layer, unless the preference asks for the
+ // highlight (`drag_layer::holds_pointer`). A part dragged along its joint owns the pointer
+ // too: nothing under it lights up (#5137).
+ let dragging_layer = drag_layer::holds_pointer(app, layered, manipulator_dragging);
let hits = hover
- .filter(|_| inside && app.viewport.boxsel.is_none() && !crate::joint_drag::active(app) && !joint_handle_pointer && !navigating)
+ .filter(|_| {
+ inside && app.viewport.boxsel.is_none() && !crate::joint_drag::active(app) && !joint_handle_pointer && !navigating && !dragging_layer
+ })
.map(|p| pick_cached(app, &proj, p))
.unwrap_or_default();
// The Fillet and Chamfer window resolves its own corners: the nearest sketch point to a
@@ -4756,7 +4854,10 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
// ---- model ----
crate::frame_watch::step(app, "viewport before the model");
- update_refinement(app, ui.ctx(), &proj);
+ // A drag drawn as a layer keeps the refinements it began with.
+ if !layered {
+ update_refinement(app, ui.ctx(), &proj);
+ }
// Levels of detail being made: keep frames coming to draw them when they are.
if app.viewport.mesh_lods.busy() {
ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
@@ -4766,11 +4867,13 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
let t0 = crate::now_ms();
// Drawn on the GPU; without one (the headless harness, tests) the model is not drawn.
if app.viewport.gpu.is_some() {
- if key != app.viewport.key {
+ let moving = if layered { drag_layer::scenes(app) } else { None };
+ if !layered && key != app.viewport.key {
let sc = build_scene(app);
if let Ok(mut slot) = app.viewport.slot.lock() {
*slot = Some(sc);
}
+ drag_layer::whole_scene_built(app);
app.viewport.key = key;
app.viewport.build_ms = crate::now_ms() - t0;
crate::frame_watch::step(app, "model scene");
@@ -4838,6 +4941,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
[r, g, b]
}),
sky: sky_uniform(app.preferences.dark_parts_shading, proj.cam.up),
+ moving,
});
crate::blur::viewport(&painter, rect, cb, rect, [t.viewport_top, t.viewport_bottom]);
// The graphics card had no memory for the view's frame (#7296): say once why it looks
@@ -7246,6 +7350,138 @@ mod tests {
use super::*;
use crate::navigation::*;
+ /// A component dragged with its Move triad is drawn as a layer: its bodies' scene is built
+ /// once, where the drag found them, and drawn moved by the drag's motion, the rest of the
+ /// model scene stays as it was (with the ground its ambient occlusion darkens put together
+ /// again under the dragged bodies, but in Wireframe, which has none), and a step of the drag
+ /// builds and moves nothing. The ground shadow follows too, from the boxes the layer knows.
+ /// Captured, the model scene is whole again.
+ #[test]
+ fn a_dragged_component_is_drawn_as_a_layer_built_once() {
+ for wire in [false, true] {
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "body_name": "Stays"})).unwrap();
+ let first = s.execute("component.create", &json!({"name": "Part"})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4, "body_name": "Block", "operation": "new"})).unwrap();
+ let dragged = s.execute("occurrence.copy", &json!({"occurrence": first})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("occurrence.move", &json!({"occurrence": dragged, "translate": [20, 0, 0]})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ app.viewport.gpu =
+ Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
+ app.ui.visual_style = if wire { 2 } else { 0 };
+ app.ui.ground_shadow = true;
+ app.cam.pitch = 0.5;
+ let whole = build_scene(&app);
+ drag_layer::whole_scene_built(&mut app);
+ // What the scene draws of its bodies (a body outside the active component is faded),
+ // and its ground.
+ let drawn = |sc: GpuScene| {
+ let ground = sc.ground_ao;
+ let sc = sc.merged();
+ (sc.tris.len() + sc.lines.len(), sc.trans, ground)
+ };
+ let shadow = |app: &SolveApp| shadow_geometry(app, &crate::open_meshing::shown_world(app)).bytes;
+ let mut last_shadow = shadow(&app);
+ let (whole, whole_trans, _) = drawn(whole);
+ let base = app.session.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ let found = body_bounds(&app, &app.session.world_state().unwrap());
+ let taken = |slot: &SceneSlot| slot.lock().unwrap().take();
+ let mut first_step = None;
+ for step in 1..4 {
+ let x = 3.0 * f64::from(step);
+ app.run("occurrence.move", json!({"occurrence": dragged, "base_transform": base, "translate": [x, 0, 0], "capture": false})).unwrap();
+ assert!(drag_layer::follow(&mut app), "step {step}: drawn as a layer");
+ let moving = drag_layer::scenes(&mut app).unwrap();
+ assert_eq!(moving.transform[3][..3], [x as f32, 0.0, 0.0], "step {step}: drawn moved by the drag");
+ let now_shadow = shadow(&app);
+ assert!(now_shadow.len() == last_shadow.len() && now_shadow != last_shadow, "step {step}: the shadow follows");
+ last_shadow = now_shadow;
+ let (statics, layer) = (taken(&app.viewport.slot), taken(&moving.slot));
+ match (step, statics) {
+ (1, Some(statics)) => {
+ // The dragged body is the layer's, the others the model scene's.
+ let ((statics, statics_trans, statics_ground), (layer, layer_trans, layer_ground)) = (drawn(statics), drawn(layer.unwrap()));
+ assert!(statics > 0 && layer > 0 && statics + layer == whole, "{statics} + {layer} of {whole}");
+ assert_eq!(statics_trans.len() + layer_trans.len(), whole_trans.len());
+ assert!(layer_ground.is_none(), "the ground is the model scene's");
+ assert_eq!(statics_ground.is_some(), !wire, "Wireframe has no ground");
+ first_step = Some((app.viewport.key, moving.key, statics_ground));
+ }
+ (_, statics) => {
+ let Some((key, moving_key, first_ground)) = &first_step else { panic!("step {step}: no first step") };
+ assert!(layer.is_none() && *moving_key == moving.key, "step {step}: the dragged bodies not built again");
+ match statics {
+ // Only the ground moved.
+ Some(statics) if !wire => {
+ let (_, _, now) = drawn(statics);
+ assert!(now.is_some() && now != *first_ground, "step {step}: the ground follows");
+ }
+ None if wire => assert_eq!(app.viewport.key, *key, "step {step}"),
+ _ => panic!("step {step}: the model scene built again"),
+ }
+ }
+ }
+ // Its mesh is not moved to draw it.
+ let world = app.session.world_state().unwrap();
+ let unmoved: Vec<usize> = (0..world.bodies.len()).filter(|&i| world.bodies[i].cached_mesh().is_none()).collect();
+ assert_eq!(unmoved.len(), 1, "step {step}");
+ // Nor its box worked out from a mesh: it is the box the drag found it in, moved.
+ let known = app.viewport.pick_bounds.lock().unwrap().as_ref().is_some_and(|(st, _)| std::sync::Arc::ptr_eq(st, &world));
+ assert!(known, "step {step}: the boxes come with the layer");
+ let i = unmoved[0];
+ let (was, now) = (found[i].1, body_bounds(&app, &world)[i].1);
+ assert!(
+ (now.min - was.min - Vec3::new(x, 0.0, 0.0)).len() < 1e-9 && (now.max - was.max - Vec3::new(x, 0.0, 0.0)).len() < 1e-9,
+ "step {step}"
+ );
+ }
+ // Captured: no longer a drag, and the model scene is whole again.
+ app.run("component.capture_position", json!({})).unwrap();
+ assert!(!drag_layer::follow(&mut app), "captured: no longer a drag");
+ assert!(app.viewport.drag.is_none());
+ }
+ }
+
+ /// A drag that comes back to where its layer found the component (the triad snapped back, or
+ /// dragged back to where it began) draws the same layer, unmoved. Built again with nothing
+ /// dragged, it would put every dragged body back in the model scene (the GPU uploading them
+ /// again) and take them once more at the next step.
+ #[test]
+ fn a_drag_back_where_it_began_keeps_its_layer() {
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "body_name": "Stays"})).unwrap();
+ let first = s.execute("component.create", &json!({"name": "Part"})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4, "body_name": "Block", "operation": "new"})).unwrap();
+ let dragged = s.execute("occurrence.copy", &json!({"occurrence": first})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("occurrence.move", &json!({"occurrence": dragged, "translate": [20, 0, 0]})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
+ let _ = build_scene(&app);
+ drag_layer::whole_scene_built(&mut app);
+ let base = app.session.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ let step = |app: &mut SolveApp, x: f64| {
+ app.run("occurrence.move", json!({"occurrence": dragged, "base_transform": base, "translate": [x, 0, 0], "capture": false})).unwrap();
+ drag_layer::follow(app).then(|| drag_layer::scenes(app)).flatten()
+ };
+ // A drag that has not moved anything yet is drawn as before.
+ assert!(step(&mut app, 0.0).is_none(), "nothing dragged yet: no layer");
+ let _ = build_scene(&app);
+ drag_layer::whole_scene_built(&mut app);
+ let taken = |slot: &SceneSlot| slot.lock().unwrap().take();
+ let first = step(&mut app, 3.0).expect("drawn as a layer");
+ assert!(taken(&first.slot).is_some_and(|sc| !sc.blocks.is_empty()), "the dragged body's scene");
+ let statics = taken(&app.viewport.slot).expect("the model scene without it");
+ let blocks = |sc: &GpuScene| sc.blocks.iter().map(|b| (b.key, std::sync::Arc::as_ptr(&b.bytes))).collect::<Vec<_>>();
+ for x in [0.0, 6.0, 0.0, 9.0, 0.0] {
+ let moving = step(&mut app, x).expect("drawn as a layer");
+ assert_eq!(moving.transform[3][..3], [x as f32, 0.0, 0.0], "x {x}: drawn moved by the drag");
+ assert!(moving.key == first.key && taken(&moving.slot).is_none(), "x {x}: the dragged body's scene not built again");
+ // The model scene is not built again: only its ground follows the dragged body.
+ let model = taken(&app.viewport.slot).expect("x {x}: the ground moved");
+ assert!(blocks(&model) == blocks(&statics) && model.ground_ao != statics.ground_ao, "x {x}: the model scene not built again");
+ }
+ }
+
#[test]
fn raised_bodies_cast_ground_shadows_at_the_origin() -> Result<(), Box<dyn std::error::Error>> {
use solidcraft_engine::render::UpAxis;
@@ -8930,6 +9166,7 @@ mod tests {
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
hatch: Default::default(),
+ moving: None,
};
let t0 = std::time::Instant::now();
let mut encoder = device.create_command_encoder(&Default::default());
diff --git a/crates/ui-egui/src/viewport_drag_layer.rs b/crates/ui-egui/src/viewport_drag_layer.rs
new file mode 100644
index 0000000000..f88f738296
--- /dev/null
+++ b/crates/ui-egui/src/viewport_drag_layer.rs
@@ -0,0 +1,420 @@
+//! A component dragged with its Move triad, drawn as a layer of its own.
+//!
+//! Each step of the drag places the component anew, and drawing it moved every mesh of the
+//! component, built the model scene again and uploaded it: much of each frame on a large
+//! assembly. Instead the dragged bodies are drawn from the scene built where the drag found them,
+//! moved on the GPU by the drag's motion, and the rest of the model stays as it was, so a step
+//! meshes, builds and uploads no geometry. The model scene is whole again as soon as anything
+//! else changes: the move captured, the design edited, a section, an analysis or isocurves shown.
+
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+use solidcraft_engine::doc::{Document, Mat, ModelState};
+use solidcraft_engine::geom::Aabb3;
+
+use super::{GpuScene, SolveApp};
+use crate::gpu::MovingLayer;
+
+/// The most a dragged body's move may differ from the others' (per matrix entry, millimetres
+/// and rotation alike) to be drawn with them.
+const SAME_MOVE: f64 = 1e-7;
+
+/// The world a model scene was built from, with its design and everything else it showed but its
+/// display refinement ([`super::base_scene_key`]: a layer keeps the refinement it began with).
+#[derive(Clone)]
+pub(crate) struct SceneWorld {
+ world: Arc<ModelState>,
+ doc: Arc<Document>,
+ base: u64,
+}
+
+/// A drag drawn as a layer: the model scene without the dragged bodies, and the dragged bodies'
+/// own scene drawn moved by `delta`, both built from `from`.
+pub(crate) struct DragLayer {
+ from: SceneWorld,
+ /// The world shown now, drawn by this layer.
+ shown: Arc<ModelState>,
+ /// The boxes of `from`'s bodies.
+ boxes: Arc<Vec<(String, Aabb3)>>,
+ /// For each body of `from`: dragged.
+ moving: Vec<bool>,
+ /// The layer's scenes: the same while the same bodies are dragged from the same world.
+ key: u64,
+ /// The drag's motion from `from` to the world shown now.
+ delta: Mat,
+ /// The model scene without the dragged bodies (built once).
+ statics: Option<GpuScene>,
+}
+
+/// A whole model scene was built from the world shown now: a drag starting next draws from it.
+pub(super) fn whole_scene_built(app: &mut SolveApp) {
+ app.viewport.scene_world =
+ Some(SceneWorld { world: crate::open_meshing::shown_world(app), doc: app.session.doc.clone(), base: super::base_scene_key(app) });
+}
+
+/// Follow a component's drag: whether this frame draws it as a layer.
+pub(super) fn follow(app: &mut SolveApp) -> bool {
+ let layer = app.viewport.drag.take();
+ if drawable(app) {
+ app.viewport.drag = next_layer(app, layer);
+ }
+ app.viewport.drag.is_some()
+}
+
+/// Whether the pointer picks nothing this frame: the triad drags a component drawn as a layer
+/// (`layered`) and "Highlight what is under the pointer while Move's arrows drag a component"
+/// is off. Picking the dragged bodies would mesh them where they stand at every step, and a
+/// highlight has the Browser look up its row again.
+pub(super) fn holds_pointer(app: &SolveApp, layered: bool, manipulator_dragging: bool) -> bool {
+ layered && manipulator_dragging && !app.preferences.move_drag_highlights
+}
+
+fn transform(delta: &Mat) -> [[f32; 4]; 4] {
+ std::array::from_fn(|c| std::array::from_fn(|r| delta[c][r] as f32))
+}
+
+/// A drag can be drawn as a layer: the model is drawn on the GPU, components are moved without
+/// being captured, and no section, analysis or isocurve is shown (their outlines, colours and
+/// curves follow the bodies' places).
+fn drawable(app: &SolveApp) -> bool {
+ app.viewport.gpu.is_some()
+ && !app.session.pending_moves.is_empty()
+ && app.session.analysis.is_none()
+ && app.session.continuity.is_empty()
+ && app.session.isocurves.is_empty()
+ && super::section_plane(app).is_none()
+}
+
+/// The layer drawing the world shown now: the one under way when its bodies are still dragged
+/// (back where they began too), else one from the last whole scene's world; none when the world
+/// is not that world with one rigid motion of some of its bodies, or nothing is dragged yet. The
+/// world's body boxes are those of the layer's world, the dragged ones moved, so no step works out
+/// a box from a mesh.
+fn next_layer(app: &SolveApp, layer: Option<DragLayer>) -> Option<DragLayer> {
+ let base = super::base_scene_key(app);
+ let now = crate::open_meshing::shown_world(app);
+ let valid = |w: &SceneWorld| w.base == base && Arc::ptr_eq(&w.doc, &app.session.doc) && !Arc::ptr_eq(&w.world, &now);
+ // The same step of the drag (a frame without a move) draws as it did.
+ let layer = match layer {
+ Some(l) if Arc::ptr_eq(&l.shown, &now) && valid(&l.from) => return Some(l),
+ other => other,
+ };
+ let (from, before) = match layer {
+ Some(l) if valid(&l.from) => (l.from.clone(), Some(l)),
+ _ => (app.viewport.scene_world.clone().filter(valid)?, None),
+ };
+ let moved = moved_bodies(&from.world, &now)?;
+ let moved = match &before {
+ Some(l) => still_dragged(moved, &l.moving),
+ None if !moved.moving.contains(&true) => return None,
+ None => moved,
+ };
+ let boxes = match &before {
+ Some(l) => l.boxes.clone(),
+ None => super::body_bounds(app, &from.world),
+ };
+ if let Some(now_boxes) = moved_boxes(&boxes, &moved) {
+ super::known_body_bounds(app, &now, now_boxes);
+ }
+ let key = layer_key(&from, &moved.moving);
+ let statics = before.filter(|l| l.key == key).and_then(|l| l.statics);
+ Some(DragLayer { from, shown: now, boxes, moving: moved.moving, key, delta: moved.delta, statics })
+}
+
+/// The world shown now as the layer's world with some of its bodies moved.
+struct Moved {
+ /// For each body of the layer's world: moved.
+ moving: Vec<bool>,
+ /// For each body of the world shown now: its place in the layer's world.
+ from: Vec<usize>,
+ /// The moved bodies' common motion.
+ delta: Mat,
+}
+
+/// Which bodies of `from` are moved in `now`, and their common motion (none moved: no motion);
+/// none when a body is another or changed, or when the moved ones move differently. Bodies are
+/// found by name: an opened design shows its bodies in the order they were meshed until it
+/// changes, the session's world in the model's.
+fn moved_bodies(from: &ModelState, now: &ModelState) -> Option<Moved> {
+ if from.bodies.len() != now.bodies.len() {
+ return None;
+ }
+ let order: Vec<usize> = if from.bodies.iter().zip(&now.bodies).all(|(a, b)| a.name == b.name) {
+ (0..now.bodies.len()).collect()
+ } else {
+ let by_name: std::collections::HashMap<&str, usize> = from.bodies.iter().enumerate().map(|(i, b)| (b.name.as_str(), i)).collect();
+ now.bodies.iter().map(|b| by_name.get(b.name.as_str()).copied()).collect::<Option<_>>()?
+ };
+ let mut delta: Option<Mat> = None;
+ let mut moving = vec![false; from.bodies.len()];
+ let mut seen = vec![false; from.bodies.len()];
+ for (body, &i) in now.bodies.iter().zip(&order) {
+ // Each body of `from` once (names told apart).
+ if std::mem::replace(seen.get_mut(i)?, true) {
+ return None;
+ }
+ let d = body.display_moved_from(from.bodies.get(i)?)?;
+ if d == solidcraft_engine::doc::IDENTITY {
+ continue;
+ }
+ match &delta {
+ None => delta = Some(d),
+ Some(common) if same_move(common, &d) => {}
+ Some(_) => return None,
+ }
+ *moving.get_mut(i)? = true;
+ }
+ Some(Moved { moving, from: order, delta: delta.unwrap_or(solidcraft_engine::doc::IDENTITY) })
+}
+
+/// `moved`, with a layer's `dragged` bodies when none is moved: back where the layer's world has
+/// them (the triad snapped back, or the drag came back to where it began), they are still its
+/// bodies, drawn unmoved. A layer of nothing dragged would hand them all back to the model scene,
+/// and the next step would take them again.
+fn still_dragged(moved: Moved, dragged: &[bool]) -> Moved {
+ if moved.moving.contains(&true) {
+ return moved;
+ }
+ Moved { moving: dragged.to_vec(), ..moved }
+}
+
+/// The boxes of the world shown now from `boxes`, those of the layer's world: the moved bodies'
+/// moved (each the box around its moved corners).
+fn moved_boxes(boxes: &[(String, Aabb3)], moved: &Moved) -> Option<Vec<(String, Aabb3)>> {
+ let shifted = |bb: &Aabb3| {
+ let mut b = Aabb3::EMPTY;
+ super::box_corners(bb).into_iter().for_each(|p| b.add(solidcraft_engine::doc::apply_point(&moved.delta, p)));
+ b
+ };
+ moved
+ .from
+ .iter()
+ .map(|&i| {
+ let (name, bb) = boxes.get(i)?;
+ let m = moved.moving.get(i).copied().unwrap_or(false);
+ Some((name.clone(), if m && !bb.is_empty() { shifted(bb) } else { *bb }))
+ })
+ .collect()
+}
+
+fn same_move(a: &Mat, b: &Mat) -> bool {
+ a.iter().flatten().zip(b.iter().flatten()).all(|(x, y)| (x - y).abs() <= SAME_MOVE)
+}
+
+fn layer_key(from: &SceneWorld, moving: &[bool]) -> u64 {
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ from.base.hash(&mut h);
+ (Arc::as_ptr(&from.world) as usize).hash(&mut h);
+ moving.hash(&mut h);
+ h.finish()
+}
+
+/// This frame's model scene and moving layer, for a drag drawn as a layer: its scenes are built
+/// once, and afterwards only the ground the model's ambient occlusion darkens follows them. The
+/// ground shadow is the sketch scene's, which follows the world shown now.
+pub(super) fn scenes(app: &mut SolveApp) -> Option<MovingLayer> {
+ let mut layer = app.viewport.drag.take()?;
+ let t0 = crate::now_ms();
+ if layer.statics.is_none() {
+ layer.statics = Some(build(app, &layer));
+ app.viewport.build_ms = crate::now_ms() - t0;
+ }
+ let ground = app.ui.visual_style != 2;
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ layer.key.hash(&mut h);
+ if ground {
+ layer.delta.iter().flatten().for_each(|v| v.to_bits().hash(&mut h));
+ }
+ let key = h.finish();
+ if key != app.viewport.key
+ && let Some(statics) = &layer.statics
+ {
+ let mut sc = statics.clone();
+ if ground {
+ let shown = layer.from.world.bodies.iter().zip(layer.boxes.iter()).enumerate();
+ let corners = shown
+ .filter(|(_, (b, (_, bb)))| !bb.is_empty() && app.body_visible(&b.name))
+ .flat_map(|(i, (_, (_, bb)))| {
+ let moved = layer.moving.get(i).copied().unwrap_or(false);
+ super::box_corners(bb).map(|p| if moved { solidcraft_engine::doc::apply_point(&layer.delta, p) } else { p })
+ })
+ .collect::<Vec<_>>();
+ sc.ground_ao = super::ground_ao(app, super::frame_bounds(app, corners.into_iter()));
+ }
+ if let Ok(mut slot) = app.viewport.slot.lock() {
+ *slot = Some(sc);
+ }
+ app.viewport.key = key;
+ }
+ let moving = MovingLayer { key: app.viewport.moving_key, slot: app.viewport.moving_slot.clone(), transform: transform(&layer.delta) };
+ app.viewport.drag = Some(layer);
+ Some(moving)
+}
+
+/// The bodies a drag drawn as a layer moves, by name.
+pub(super) fn dragged_names(app: &SolveApp) -> std::collections::HashSet<&str> {
+ app.viewport
+ .drag
+ .iter()
+ .flat_map(|layer| layer.from.world.bodies.iter().zip(&layer.moving).filter(|(_, moved)| **moved).map(|(b, _)| b.name.as_str()))
+ .collect()
+}
+
+/// The layer's model scene without the dragged bodies (no ground), and the dragged
+/// bodies' scene put in the moving slot; both from the blocks the last scene built where they
+/// come back the same.
+fn build(app: &mut SolveApp, layer: &DragLayer) -> GpuScene {
+ let world = &layer.from.world;
+ let moved = |i: usize| layer.moving.get(i).copied().unwrap_or(false);
+ let mut kept = app.viewport.blocks.lock().map(|mut b| std::mem::take(&mut *b)).unwrap_or_default();
+ let (mut statics, mut made) = super::body_scene(app, world, |i| !moved(i), false, &mut kept);
+ let (moving, made_moving) = super::body_scene(app, world, moved, false, &mut kept);
+ made.extend(made_moving);
+ super::keep_body_tris(app, &made);
+ if let Ok(mut b) = app.viewport.blocks.lock() {
+ *b = made;
+ }
+ if let Ok(mut slot) = app.viewport.moving_slot.lock() {
+ *slot = Some(moving);
+ }
+ app.viewport.moving_key = layer.key;
+ // The assembly around a part edited in place stays where it is.
+ crate::edit_in_place::draw_context(app, &mut statics);
+ statics
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ /// A session with a body that stays and a placed copy of a part, moved off the part.
+ fn two_parts() -> (solidcraft_engine::Session, u64) {
+ let mut s = solidcraft_engine::Session::default();
+ s.execute("solid.box", &json!({"length": 5, "width": 5, "height": 5, "body_name": "Stays"})).unwrap();
+ let first = s.execute("component.create", &json!({"name": "Part"})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("solid.box", &json!({"length": 2, "width": 3, "height": 4, "body_name": "Block", "operation": "new"})).unwrap();
+ let dragged = s.execute("occurrence.copy", &json!({"occurrence": first})).unwrap()["occurrence"].as_u64().unwrap();
+ s.execute("occurrence.move", &json!({"occurrence": dragged, "translate": [20, 0, 0]})).unwrap();
+ (s, dragged)
+ }
+
+ fn with_gpu(app: &mut SolveApp) {
+ app.viewport.gpu =
+ Some(crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: false, oit: false });
+ }
+
+ /// Whole bodies light by drawing the model's own triangles again, but a drag drawn as a layer
+ /// moves its bodies' triangles on the GPU from where the drag found them: a selected dragged
+ /// body lights its triangles where it stands, and a body that stays reuses the model's.
+ #[test]
+ fn a_selected_body_dragged_as_a_layer_lights_where_it_stands() {
+ let (mut s, dragged) = two_parts();
+ // Nothing faded (faded bodies are built apart): the design itself active.
+ s.execute("component.activate", &json!({"component": 0})).unwrap();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ app.set_origin_shown(false);
+ with_gpu(&mut app);
+ let _ = super::super::build_scene(&app);
+ whole_scene_built(&mut app);
+ let before = app.session.world_state().unwrap();
+ let base = app.session.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ app.run("occurrence.move", json!({"occurrence": dragged, "base_transform": base, "translate": [4, 0, 0], "capture": false})).unwrap();
+ assert!(follow(&mut app));
+ let world = app.session.world_state().unwrap();
+ let moving = world.bodies.iter().find(|b| before.body(&b.name).is_some_and(|w| w.mesh_bounds().min.x != b.mesh_bounds().min.x)).unwrap();
+ let moving = moving.name.clone();
+ let select = |app: &mut SolveApp, names: &[&str]| {
+ app.session.selection = names.iter().map(|n| solidcraft_engine::Sel::Body { name: (*n).to_string() }).collect();
+ super::super::build_highlight(app)
+ };
+ let stays = select(&mut app, &["Stays"]);
+ assert_eq!(stays.selected_blocks.len(), 1, "a body that stays reuses the model's triangles");
+ assert!(stays.merged().tris.is_empty());
+ let lit = select(&mut app, &[moving.as_str()]);
+ assert!(lit.selected_blocks.is_empty() && lit.selected_planned.is_empty() && lit.selected_instanced.is_empty());
+ let tris = lit.merged().tris;
+ assert!(!tris.is_empty(), "the dragged body lights its own triangles");
+ let xs: Vec<f32> = tris
+ .as_chunks::<{ crate::gpu::TRI_SIZE }>()
+ .0
+ .iter()
+ .filter_map(|v| v.get(..4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])))
+ .collect();
+ assert!(xs.iter().all(|x| *x > 23.9), "lit where the drag put it: {xs:?}");
+ }
+
+ /// While the triad drags a component drawn as a layer, the pointer picks nothing; "Highlight
+ /// what is under the pointer while Move's arrows drag a component" picks and highlights as
+ /// before (#7273). A pointer that isn't dragging the triad picks either way.
+ #[test]
+ fn a_layer_drag_picks_under_the_pointer_only_with_its_preference() {
+ let (s, dragged) = two_parts();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ with_gpu(&mut app);
+ let _ = super::super::build_scene(&app);
+ whole_scene_built(&mut app);
+ let base = app.session.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ app.run("occurrence.move", json!({"occurrence": dragged, "base_transform": base, "translate": [4, 0, 0], "capture": false})).unwrap();
+ let layered = follow(&mut app);
+ assert!(layered, "the drag is drawn as a layer");
+ assert!(!app.preferences.move_drag_highlights, "off by default");
+ assert!(holds_pointer(&app, layered, true), "the triad's drag picks nothing");
+ assert!(!holds_pointer(&app, layered, false), "a pointer that isn't dragging the triad picks");
+ crate::prefs::set(&mut app, &json!({"move_drag_highlights": true})).unwrap();
+ assert!(app.preferences.move_drag_highlights, "the control channel sets it");
+ assert!(!holds_pointer(&app, layered, true), "with the preference the drag picks under the pointer");
+ }
+
+ /// Isocurve Analysis draws its curves where the bodies are, so a drag with them shown
+ /// draws the model whole, as with a section or an analysis.
+ #[test]
+ fn a_drag_with_isocurves_shown_is_not_drawn_as_a_layer() {
+ let (s, dragged) = two_parts();
+ let mut app = SolveApp::new(s, crate::Services::default());
+ with_gpu(&mut app);
+ let base = app.session.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ app.run("occurrence.move", json!({"occurrence": dragged, "base_transform": base, "translate": [4, 0, 0], "capture": false})).unwrap();
+ assert!(drawable(&app), "a plain drag is drawn as a layer");
+ let at = solidcore_record::Vec3::new(2.5, 2.5, 5.0);
+ app.session.isocurves.push(solidcraft_engine::IsoPick { body: "Stays".into(), at, count: 3 });
+ assert!(!drawable(&app), "with isocurves shown the model is drawn whole");
+ }
+
+ /// An opened design shows its bodies in the order they were meshed until it changes, and the
+ /// session's world (a drag's first step) in the model's: the drag finds each body by name,
+ /// and its boxes come in the order of the world shown now.
+ #[test]
+ fn a_drag_finds_its_bodies_by_name_in_another_order() {
+ let (mut s, dragged) = two_parts();
+ let mut meshed = (*s.world_state().unwrap()).clone();
+ meshed.bodies.reverse();
+ let base = s.doc.occurrences.iter().find(|o| o.id == dragged).map(|o| o.transform).unwrap();
+ s.execute("occurrence.move", &json!({"occurrence": dragged, "base_transform": base, "translate": [3, 0, 0], "capture": false})).unwrap();
+ let now = s.world_state().unwrap();
+ assert!(now.bodies.len() >= 3 && now.bodies.iter().zip(&meshed.bodies).any(|(a, b)| a.name != b.name));
+
+ let moved = moved_bodies(&meshed, &now).unwrap();
+ let dragged_now =
+ now.bodies.iter().position(|b| meshed.body(&b.name).is_some_and(|w| w.mesh_bounds().min.x != b.mesh_bounds().min.x)).unwrap();
+ let dragged_meshed = meshed.bodies.iter().position(|b| b.name == now.bodies[dragged_now].name).unwrap();
+ assert_eq!(moved.moving, (0..meshed.bodies.len()).map(|i| i == dragged_meshed).collect::<Vec<_>>());
+ assert!(now.bodies.iter().zip(&moved.from).all(|(b, &i)| meshed.bodies[i].name == b.name));
+ assert!((moved.delta[3][0] - 3.0).abs() < 1e-9 && moved.delta[3][1].abs() < 1e-9);
+
+ let boxes: Vec<(String, Aabb3)> = meshed.bodies.iter().map(|b| (b.name.clone(), b.mesh_bounds())).collect();
+ let shown = moved_boxes(&boxes, &moved).unwrap();
+ for (i, ((name, bb), b)) in shown.iter().zip(&now.bodies).enumerate() {
+ assert_eq!(name, &b.name);
+ let was = boxes[moved.from[i]].1;
+ let shift = if i == dragged_now { 3.0 } else { 0.0 };
+ assert!((bb.min.x - was.min.x - shift).abs() < 1e-9 && (bb.max.x - was.max.x - shift).abs() < 1e-9, "{name}");
+ }
+
+ // Two bodies of one name: no telling them apart.
+ let mut twins = meshed.clone();
+ twins.bodies[1].name = twins.bodies[0].name.clone();
+ assert!(moved_bodies(&twins, &now).is_none());
+ }
+}
diff --git a/docs/design/preferences/pages/tools.md b/docs/design/preferences/pages/tools.md
index a82ca5406f..ff81fa2968 100644
--- a/docs/design/preferences/pages/tools.md
+++ b/docs/design/preferences/pages/tools.md
@@ -24,6 +24,7 @@ Each group is a 120x64 figure at the left of its checkboxes, with a group name u
|---|---|---|---|---|---|---|
| Use joint motion handles for Move | Checkbox | `Prefs.assembly_move_handles` | `true` | "Off: the previous Move panel." | `assembly-move` | |
| Show moved parts' old place as a ghost | Checkbox | `Prefs.drive_joints_ghost` | `true` | none | `assembly-move` | |
+| Highlight what is under the pointer while Move's arrows drag a component | Checkbox | `Prefs.move_drag_highlights` | `false` | "Off: while Move's arrows drag a component, nothing under the pointer is highlighted, which keeps large assemblies smooth. With a section or an analysis shown it is highlighted all the same, and a part dragged along its joints never highlights it." | `assembly-move` | On: the highlight as before #7273, at the cost of a pick and a Browser lookup at each step. |
| Near-axis step | Number field (64 wide, aria "Degrees") with "deg" | `Prefs.joint_rotation_coarse` (0.001 to 180) | `10` | "Pull outside the dashed guide for the fine step." | `assembly-move` | Confirmed: near-axis uses the coarse step; the existing fine-mode hysteresis and rebasing remain unchanged. |
| Far-axis step | Number field with "deg" | `Prefs.joint_rotation_fine` (0.001 to 180) | `0.1` | none | `assembly-move` | Confirmed: far-axis uses the fine step. |