Skip to content

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

Viewport: cut dashed lines to the view, so a huge distance can't fill the memory (#8540)

semmelrinde11f208f6655f
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 1140d82302..c08f423c7c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1189,7 +1189,13 @@ fn radius_spline_handles(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Pain
let at = |u: f64| e.start + (e.other - e.start) * u;
let g = e.spline.greville();
let tips: Vec<Option<Pos2>> = g.iter().zip(&e.spline.radii).map(|(u, r)| proj.to_screen(at(*u) + e.n * *r)).collect();
- painter.add(egui::Shape::dashed_line(&tips.iter().flatten().copied().collect::<Vec<_>>(), Stroke::new(1.0, t.manipulator), 4.0, 3.0));
+ painter.extend(crate::viewport::dashed_line(
+ &tips.iter().flatten().copied().collect::<Vec<_>>(),
+ painter.clip_rect(),
+ Stroke::new(1.0, t.manipulator),
+ 4.0,
+ 3.0,
+ ));
for (k, (u, ts)) in g.iter().zip(&tips).enumerate() {
let Some(ts) = *ts else { continue };
crate::scenario::publish_handle(&if i == 0 { format!("fillet_r{k}") } else { format!("fillet_e{i}_r{k}") }, ts);
@@ -1329,7 +1335,7 @@ fn measure_components(app: &SolveApp, painter: &egui::Painter, proj: &Proj, a: V
let (at, offset) = if let Some((sa, sb)) = screen {
let leg = sb - sa;
if leg.length_sq() > 1.0 {
- painter.add(egui::Shape::dashed_line(&[sa, sb], Stroke::new(1.5, color), 5.0, 3.0));
+ painter.extend(crate::viewport::dashed_line(&[sa, sb], painter.clip_rect(), Stroke::new(1.5, color), 5.0, 3.0));
let normal = vec2(-leg.y, leg.x).normalized();
for p in [sa, sb] {
painter.line_segment([p - normal * 3.0, p + normal * 3.0], Stroke::new(1.0, color));
@@ -1413,7 +1419,7 @@ fn taper_handle(
crate::scenario::publish_handle("taper", es);
let hot = r.hovered() || r.dragged();
let col = if hot { t.accent } else { t.manipulator };
- painter.add(egui::Shape::dashed_line(&[fs, es], Stroke::new(1.2, col), 5.0, 3.0));
+ painter.extend(crate::viewport::dashed_line(&[fs, es], painter.clip_rect(), Stroke::new(1.2, col), 5.0, 3.0));
painter.circle(es, if hot { 6.5 } else { 5.0 }, t.overlay, Stroke::new(2.0, col));
if hot {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
diff --git a/crates/ui-egui/src/drag_snap.rs b/crates/ui-egui/src/drag_snap.rs
index d30c9c9d7e..f59650ba4b 100644
--- a/crates/ui-egui/src/drag_snap.rs
+++ b/crates/ui-egui/src/drag_snap.rs
@@ -6,7 +6,7 @@
use std::cell::{Cell, RefCell};
-use egui::{Align2, FontId, Shape, Stroke};
+use egui::{Align2, FontId, Stroke};
use serde_json::{Value, json};
use solidcraft_engine::geom::Vec2;
use solidcraft_engine::sketch::{CurveKind, Sketch};
@@ -223,7 +223,7 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
let tk = Tokens::get();
for (a, b) in &s.guides {
if let (Some(a), Some(b)) = (to(*a), to(*b)) {
- painter.add(Shape::dashed_line(&[a, b], Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
+ painter.extend(crate::viewport::dashed_line(&[a, b], painter.clip_rect(), Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
}
}
let Some(sp) = to(s.at) else { return };
diff --git a/crates/ui-egui/src/inference.rs b/crates/ui-egui/src/inference.rs
index 0dfc9b3380..69b59065dd 100644
--- a/crates/ui-egui/src/inference.rs
+++ b/crates/ui-egui/src/inference.rs
@@ -6,7 +6,7 @@
use std::cell::RefCell;
-use egui::{Shape, Stroke};
+use egui::Stroke;
use serde_json::json;
use solidcraft_engine::geom::Vec2;
use solidcraft_engine::sketch::{CurveKind, Sketch};
@@ -246,7 +246,7 @@ pub fn show(app: &SolveApp, painter: &egui::Painter, proj: &Proj) {
let to = |p: Vec2| proj.to_screen(ss.plane.to_world(p));
let tk = Tokens::get();
if let (Some(a), Some(b)) = (to(i.guide.0), to(i.guide.1)) {
- painter.add(Shape::dashed_line(&[a, b], Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
+ painter.extend(crate::viewport::dashed_line(&[a, b], painter.clip_rect(), Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
}
}
@@ -339,7 +339,7 @@ pub(crate) fn track_and_show(app: &mut SolveApp, painter: &egui::Painter, proj:
&& let (Some(a), Some(b)) = (proj.to_screen(ss.plane.to_world(a)), proj.to_screen(ss.plane.to_world(b)))
{
let tk = Tokens::get();
- painter.add(Shape::dashed_line(&[a, b], Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
+ painter.extend(crate::viewport::dashed_line(&[a, b], painter.clip_rect(), Stroke::new(1.0, tk.rubber_band), 5.0, 4.0));
painter.circle_stroke(a, 4.0, Stroke::new(1.0, tk.rubber_band));
}
}
diff --git a/crates/ui-egui/src/sketch_text_handles.rs b/crates/ui-egui/src/sketch_text_handles.rs
index 9ee81b438c..b340c5364f 100644
--- a/crates/ui-egui/src/sketch_text_handles.rs
+++ b/crates/ui-egui/src/sketch_text_handles.rs
@@ -6,7 +6,7 @@
//! the same way).
use std::cell::RefCell;
-use egui::{Align2, CursorIcon, FontId, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, vec2};
+use egui::{Align2, CursorIcon, FontId, Painter, Pos2, Rect, Stroke, StrokeKind, vec2};
use serde_json::json;
use solidcraft_engine::geom::Vec2;
use solidcraft_engine::sketch::{LinkKind, LinkSource};
@@ -275,7 +275,7 @@ pub(crate) fn show(app: &SolveApp, ui: &egui::Ui, painter: &Painter, proj: &Proj
let line = Stroke::new(1.0, tk.accent);
let mut outline = s.corners.to_vec();
outline.push(s.corners[0]);
- painter.add(Shape::dashed_line(&outline, line, 5.0, 4.0));
+ painter.extend(crate::viewport::dashed_line(&outline, painter.clip_rect(), line, 5.0, 4.0));
painter.line_segment([s.knob_base, s.knob], line);
let drag = DRAG.with(|d| d.borrow().as_ref().map(|d| d.grab));
let under = hover.and_then(|p| hit(app, proj, p)).map(|(_, g)| g);
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 8fdbd992bf..4a543bda52 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -325,6 +325,84 @@ pub(crate) fn projected_polygon(pts: &[Pos2], fill: Color32, stroke: Stroke) ->
out
}
+/// [`Shape::dashed_line`] for points projected into the viewport, cut to `clip` (grown by two
+/// dash periods, so the cuts lie off screen). epaint makes one shape per dash and steps along in
+/// f32, so a line reaching far off screen made millions of shapes, or never ended: an Extrude
+/// distance of 1e9 mm filled the memory within a second. A line inside the bounds is dashed as
+/// before; a cut one keeps its dashes in phase along the whole line, so they don't crawl as the
+/// view moves.
+pub(crate) fn dashed_line(pts: &[Pos2], clip: Rect, stroke: Stroke, dash: f32, gap: f32) -> Vec<Shape> {
+ let bounds = clip.expand(2.0 * (dash + gap));
+ if pts.iter().all(|p| bounds.contains(*p)) {
+ return Shape::dashed_line(pts, stroke, dash, gap);
+ }
+ let period = f64::from(dash + gap);
+ let mut out = Vec::new();
+ let mut run: Vec<Pos2> = Vec::new();
+ let mut offset = 0.0;
+ let mut flush = |run: &mut Vec<Pos2>, offset: f32| {
+ if run.len() >= 2 && period > 0.0 {
+ out.extend(Shape::dashed_line_with_offset(run, stroke, &[dash], &[gap], offset));
+ }
+ run.clear();
+ };
+ let mut along = 0.0_f64;
+ for w in pts.windows(2) {
+ let (a, b) = (w[0], w[1]);
+ let len = f64::from(a.distance(b));
+ match clip_segment(a, b, bounds).filter(|_| len.is_finite()) {
+ Some((t0, t1)) => {
+ // In f64: a cut a trillion points from `a` is lost in f32.
+ let at = |t: f64| pos2((f64::from(a.x) + f64::from(b.x - a.x) * t) as f32, (f64::from(a.y) + f64::from(b.y - a.y) * t) as f32);
+ let (from, to) = (at(t0), at(t1));
+ if run.is_empty() || t0 > 0.0 {
+ flush(&mut run, offset);
+ // How far into its period the pattern is where the run begins: a cut run
+ // waits for the next dash (the wait is off screen), the line's start begins one.
+ let phase = (along + len * t0) % period;
+ offset = if t0 > 0.0 { ((period - phase) % period) as f32 } else { 0.0 };
+ run.push(from);
+ }
+ run.push(to);
+ if t1 < 1.0 {
+ flush(&mut run, offset);
+ }
+ }
+ None => flush(&mut run, offset),
+ }
+ if len.is_finite() {
+ along += len;
+ }
+ }
+ flush(&mut run, offset);
+ out
+}
+
+/// The part of segment `a`–`b` inside `r`, as parameters `0 ≤ t0 ≤ t1 ≤ 1` along it; `None` when
+/// it misses `r` or a coordinate is not finite (Liang–Barsky, in f64).
+fn clip_segment(a: Pos2, b: Pos2, r: Rect) -> Option<(f64, f64)> {
+ let (x0, y0, dx, dy) = (f64::from(a.x), f64::from(a.y), f64::from(b.x - a.x), f64::from(b.y - a.y));
+ if ![x0, y0, dx, dy].iter().all(|v| v.is_finite()) {
+ return None;
+ }
+ let (mut t0, mut t1) = (0.0_f64, 1.0_f64);
+ for (p, q) in [(-dx, x0 - f64::from(r.min.x)), (dx, f64::from(r.max.x) - x0), (-dy, y0 - f64::from(r.min.y)), (dy, f64::from(r.max.y) - y0)] {
+ if p == 0.0 {
+ if q < 0.0 {
+ return None;
+ }
+ } else {
+ let t = q / p;
+ if p < 0.0 {
+ t0 = t0.max(t);
+ } else {
+ t1 = t1.min(t);
+ }
+ }
+ }
+ (t0 <= t1).then_some((t0, t1))
+}
+
/// View directions all round, a few degrees apart, none exactly along an axis.
#[cfg(test)]
pub(crate) fn orbit_directions() -> impl Iterator<Item = Vec3> {
diff --git a/crates/ui-egui/src/viewport_overlays_tests.rs b/crates/ui-egui/src/viewport_overlays_tests.rs
index 601dbf4fe5..1738048625 100644
--- a/crates/ui-egui/src/viewport_overlays_tests.rs
+++ b/crates/ui-egui/src/viewport_overlays_tests.rs
@@ -740,3 +740,44 @@ fn corner_toasts_share_one_width_against_the_right_edge() {
}
ToastPlace::Corner.publish(&ctx);
}
+
+/// A dashed line reaching far off screen is cut to the view before it is dashed: epaint makes a
+/// shape per dash and steps along in f32, so one a trillion points long made billions of them,
+/// or never finished. A line in view is dashed exactly as before, and a cut one keeps its
+/// dashes in phase with its start.
+#[test]
+fn a_dashed_line_far_off_screen_is_cut_to_the_view() {
+ let view = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0));
+ let stroke = Stroke::new(1.0, Color32::WHITE);
+ let near = [pos2(100.0, 100.0), pos2(700.0, 400.0), pos2(900.0, 100.0)];
+ assert_eq!(dashed_line(&near, view, stroke, 5.0, 3.0), Shape::dashed_line(&near, stroke, 5.0, 3.0));
+ let far = dashed_line(&[pos2(100.0, 500.0), pos2(1e12, 500.0)], view, stroke, 5.0, 3.0);
+ assert!(!far.is_empty() && far.len() < 250, "{} dashes", far.len());
+ for s in &far {
+ let Shape::LineSegment { points, .. } = s else { panic!("{s:?}") };
+ let periods = (points[0].x - 100.0) / 8.0;
+ assert!((periods - periods.round()).abs() < 1e-3, "a dash starts at {points:?}, off the line's pattern");
+ }
+ let across = dashed_line(&[pos2(-1e12, 500.0), pos2(1e12, 500.0)], view, stroke, 5.0, 3.0);
+ assert!(across.len() < 250, "{} dashes", across.len());
+ assert!(across.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } if (700.0..900.0).contains(&points[0].x))), "the line shows in view");
+ for missing in [[pos2(f32::NAN, 0.0), pos2(10.0, 10.0)], [pos2(f32::INFINITY, 0.0), pos2(10.0, 10.0)], [pos2(-1e9, -1e9), pos2(-1e9, 1e9)]] {
+ assert!(dashed_line(&missing, view, stroke, 5.0, 3.0).is_empty(), "{missing:?}");
+ }
+}
+
+/// Extrude with a distance of 1e9 mm drew the taper handle's dashed line a billion millimetres
+/// long into the viewport: the frame never finished and filled the memory. It now draws at once.
+#[test]
+fn a_huge_extrude_distance_draws_its_handles_at_once() {
+ let mut h = Harness::new();
+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap();
+ h.settle();
+ h.step(&json!({"start": "solid.extrude"})).unwrap();
+ h.step(&json!({"click": {"world": [20, 15, 20]}})).unwrap();
+ let started = std::time::Instant::now();
+ h.step(&json!({"text": "1e9"})).unwrap();
+ h.frames(4);
+ assert!(crate::scenario::handle_at("taper").is_some(), "the taper handle is drawn");
+ assert!(started.elapsed().as_secs_f64() < 10.0, "{:?}", started.elapsed());
+}