Skip to content

Commit

Permalink
Faster dashed lines generation
Browse files Browse the repository at this point in the history
  • Loading branch information
lampsitter committed Jan 4, 2022
1 parent b1fd6a4 commit fce3083
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
1 change: 1 addition & 0 deletions epaint/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ All notable changes to the epaint crate will be documented in this file.

## Unreleased

* Added `Shape::dashed_line_many` ([#1027](https://github.com/emilk/egui/pull/1027)).

## 0.16.0 - 2021-12-29
* Anti-alias path ends ([#893](https://github.com/emilk/egui/pull/893)).
Expand Down
26 changes: 19 additions & 7 deletions epaint/src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ impl Shape {
shapes
}

/// Turn a line into dashes. If you need to create many dashed lines use this instead of
/// [`Self::dashed_line`]
pub fn dashed_line_many(
points: &[Pos2],
stroke: impl Into<Stroke>,
dash_length: f32,
gap_length: f32,
shapes: &mut Vec<Shape>,
) {
dashes_from_line(points, stroke.into(), dash_length, gap_length, shapes);
}

/// A convex polygon with a fill and optional stroke.
#[inline]
pub fn convex_polygon(
Expand Down Expand Up @@ -425,27 +437,27 @@ fn dashes_from_line(
let end = window[1];
let vector = end - start;
let segment_length = vector.length();

let mut start_point = start;
while position_on_segment < segment_length {
let new_point = start + vector * (position_on_segment / segment_length);
if drawing_dash {
// This is the end point.
if let Shape::Path(PathShape { points, .. }) = shapes.last_mut().unwrap() {
points.push(new_point);
}
shapes.push(Shape::line_segment([start_point, new_point], stroke));
position_on_segment += gap_length;
} else {
// Start a new dash.
shapes.push(Shape::line(vec![new_point], stroke));
start_point = new_point;
position_on_segment += dash_length;
}
drawing_dash = !drawing_dash;
}

// If the segment ends and the dash is not finished, add the segment's end point.
if drawing_dash {
if let Shape::Path(PathShape { points, .. }) = shapes.last_mut().unwrap() {
points.push(end);
}
shapes.push(Shape::line_segment([start_point, end], stroke));
}

position_on_segment -= segment_length;
});
}

0 comments on commit fce3083

Please sign in to comment.