mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 18:25:34 +01:00
Global Edit: the canvas shares the kept outlines instead of copying them each frame
With one object selected and the Selection tool active, or while Global Edit is on, every frame copied each highlighted outline out of the kept list and made one overlay per object, which the canvas flattened and stroked again. With 10,000 matching objects that was most of a 27 ms frame. highlights and similar now return the kept outlines as a shared Highlights, grouped by layer color with a revision that changes only when the outlines are found again. The session sends one Overlay::Outlines per color, and the canvas shows it as a SelectionOutline keyed by that revision, so the lines are stroked again only when the outlines or the view change.
This commit is contained in:
1 parent
619a6e5ed1
commit
3617039ef5
6 files changed
+136
-19
No files matched your search
@@ -194,6 +194,51 @@ impl Options {
|
||||
/// Outlines with their layer colours ([`highlights`]).
|
||||
pub type Outlines = Vec<(BezPath, [u8; 3])>;
|
||||
|
||||
/// The outlines [`highlights`] gives the canvas, grouped by layer color. The canvas asks every frame and gets the same
|
||||
/// allocation back until the outlines are found again.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Highlights {
|
||||
/// A number given to each set of outlines when it is found, and never to another set: the canvas keeps the lines
|
||||
/// it stroked for these outlines while the number stays the same.
|
||||
pub revision: u64,
|
||||
/// The outlines in each layer color, the colors in the order of their first outline.
|
||||
pub groups: Vec<([u8; 3], std::sync::Arc<[BezPath]>)>,
|
||||
}
|
||||
|
||||
/// The [`Highlights::revision`] the next set of outlines takes.
|
||||
static NEXT_HIGHLIGHTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// [`Highlights`] with no outline, shared so the frames that show none allocate nothing.
|
||||
static NO_HIGHLIGHTS: std::sync::LazyLock<std::sync::Arc<Highlights>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
impl Highlights {
|
||||
/// `outlines` grouped by color, under a new revision.
|
||||
fn new(outlines: Outlines) -> std::sync::Arc<Self> {
|
||||
if outlines.is_empty() {
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let mut groups: Vec<([u8; 3], Vec<BezPath>)> = vec![];
|
||||
for (path, color) in outlines {
|
||||
match groups.iter_mut().find(|(c, _)| *c == color) {
|
||||
Some((_, paths)) => paths.push(path),
|
||||
None => groups.push((color, vec![path])),
|
||||
}
|
||||
}
|
||||
let revision = NEXT_HIGHLIGHTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::sync::Arc::new(Highlights { revision, groups: groups.into_iter().map(|(c, paths)| (c, paths.into())).collect() })
|
||||
}
|
||||
|
||||
/// How many outlines there are, in every color.
|
||||
pub fn len(&self) -> usize {
|
||||
self.groups.iter().map(|(_, paths)| paths.len()).sum()
|
||||
}
|
||||
|
||||
/// Whether there is no outline.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.groups.iter().all(|(_, paths)| paths.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Global Edit in progress (per document; not saved, not an undo step).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct GlobalEdit {
|
||||
@@ -202,7 +247,7 @@ pub struct GlobalEdit {
|
||||
/// outline onto its own.
|
||||
pub members: Vec<(NodeId, Affine)>,
|
||||
/// [`highlights`] as of a document revision: the canvas asks every frame.
|
||||
outlines: std::cell::RefCell<Option<(u64, Outlines)>>,
|
||||
outlines: std::cell::RefCell<Option<(u64, std::sync::Arc<Highlights>)>>,
|
||||
}
|
||||
|
||||
/// An outline reduced to its form: the anchors and handles placed in a unit box, with what tells
|
||||
@@ -1017,31 +1062,31 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
|
||||
/// highlights them while Global Edit is on. While it is off, with one supported object selected,
|
||||
/// they are the outlines of the objects Start Global Edit would take with the Global Edit Options
|
||||
/// ([`similar`]).
|
||||
pub fn highlights(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
pub fn highlights(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
let Some(ge) = &st.global_edit else { return similar(s) };
|
||||
if let Some((rev, out)) = &*ge.outlines.borrow()
|
||||
&& *rev == st.revision
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = outlines(st, &ge.members);
|
||||
let out = Highlights::new(outlines(st, &ge.members));
|
||||
*ge.outlines.borrow_mut() = Some((st.revision, out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
/// [`similar`]'s outlines as of a document revision and the options they were found with.
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, Outlines)>>;
|
||||
pub type SimilarCache = std::cell::RefCell<Option<(u64, Options, std::sync::Arc<Highlights>)>>;
|
||||
|
||||
/// Before Global Edit starts: with one supported object selected, the outlines of the other
|
||||
/// objects Start Global Edit would take now with the session's Global Edit Options, so the canvas
|
||||
/// shows them as soon as the object is selected. None while an interaction (a drag) is in
|
||||
/// progress, or when fewer than two objects would be taken. Kept per document revision and
|
||||
/// options, as finding them walks the whole document.
|
||||
pub fn similar(s: &Session) -> Outlines {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
pub fn similar(s: &Session) -> std::sync::Arc<Highlights> {
|
||||
let Some(st) = s.active() else { return NO_HIGHLIGHTS.clone() };
|
||||
if st.global_edit.is_some() || st.interaction.is_some() || st.selection.objects.len() != 1 {
|
||||
return vec![];
|
||||
return NO_HIGHLIGHTS.clone();
|
||||
}
|
||||
let o = &s.global_edit_options;
|
||||
if let Some((rev, opts, out)) = &*st.similar_outlines.borrow()
|
||||
@@ -1050,10 +1095,10 @@ pub fn similar(s: &Session) -> Outlines {
|
||||
{
|
||||
return out.clone();
|
||||
}
|
||||
let out = match matches(s, o) {
|
||||
let out = Highlights::new(match matches(s, o) {
|
||||
Ok(m) if m.len() >= 2 => outlines(st, &m),
|
||||
_ => vec![],
|
||||
};
|
||||
});
|
||||
*st.similar_outlines.borrow_mut() = Some((st.revision, o.clone(), out.clone()));
|
||||
out
|
||||
}
|
||||
|
||||
@@ -150,7 +150,7 @@ fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() {
|
||||
assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar");
|
||||
assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match");
|
||||
let moved = node(&s, copies[1]).stroke_path().unwrap();
|
||||
assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now");
|
||||
assert!(shown.groups.iter().flat_map(|(_, paths)| paths.iter()).any(|p| *p == moved), "the moved copy is shown where it is now");
|
||||
s.execute("select.globalEditOptions", &json!({"size": true})).unwrap();
|
||||
assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out");
|
||||
assert_eq!(crate::cmd::globaledit::match_count(&s), 38);
|
||||
@@ -162,9 +162,7 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
|
||||
let [a, b, ..] = squares(&mut s);
|
||||
let outline = node(&s, b).stroke_path().unwrap();
|
||||
let shown = |s: &mut Session| {
|
||||
s.overlays(ViewInfo::default())
|
||||
.iter()
|
||||
.any(|o| matches!(o, vectorcraft_tools::Overlay::Path { path, width, .. } if *path == outline && *width == 1.0))
|
||||
s.overlays(ViewInfo::default()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Outlines { paths, .. } if paths.contains(&outline)))
|
||||
};
|
||||
sel(&mut s, &[a]);
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
@@ -175,6 +173,42 @@ fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_too
|
||||
assert!(shown(&mut s), "while Global Edit is on, with any tool");
|
||||
}
|
||||
|
||||
/// Each frame hands the canvas the kept outlines, one overlay per layer color sharing them, with no copy of a path; the
|
||||
/// revision changes when the outlines are found again.
|
||||
#[test]
|
||||
fn every_frame_shares_the_kept_outlines_instead_of_copying_each_one() {
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_tools::Overlay;
|
||||
let outlines = |s: &mut Session| -> Vec<(Arc<[vectorcraft_geom::BezPath]>, u64)> {
|
||||
s.overlays(ViewInfo::default())
|
||||
.into_iter()
|
||||
.filter_map(|o| if let Overlay::Outlines { paths, revision, .. } = o { Some((paths, revision)) } else { None })
|
||||
.collect()
|
||||
};
|
||||
let mut s = session();
|
||||
let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
for i in 1..200 {
|
||||
rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0);
|
||||
}
|
||||
sel(&mut s, &[key]);
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
let first = outlines(&mut s);
|
||||
let [(paths, revision)] = &first[..] else { panic!("one overlay for the one layer color, not one per object: {}", first.len()) };
|
||||
assert_eq!(paths.len(), 199);
|
||||
let second = outlines(&mut s);
|
||||
let [(again, same)] = &second[..] else { panic!("{}", second.len()) };
|
||||
assert!(Arc::ptr_eq(paths, again), "the next frame gets the same outlines, not a copy");
|
||||
assert_eq!(same, revision);
|
||||
s.execute("select.globalEdit", &json!({})).unwrap();
|
||||
let on = outlines(&mut s);
|
||||
let [(members, started)] = &on[..] else { panic!("{}", on.len()) };
|
||||
assert_eq!(members.len(), 199);
|
||||
assert_ne!(started, revision, "outlines found again take a new revision");
|
||||
let next = outlines(&mut s);
|
||||
let [(kept, still)] = &next[..] else { panic!("{}", next.len()) };
|
||||
assert!(Arc::ptr_eq(members, kept) && still == started, "and are kept from frame to frame while Global Edit is on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_and_appearance_options_narrow_the_match() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1478,9 +1478,12 @@ impl Session {
|
||||
// Global Edit: the objects edited with the selected one are highlighted; before it starts,
|
||||
// with the Selection tool, the objects it would take.
|
||||
let ge_on = self.active().is_some_and(|d| d.global_edit.is_some());
|
||||
let shown = if ge_on || self.tool.id() == "selection" { crate::cmd::globaledit::highlights(self) } else { vec![] };
|
||||
for (path, color) in shown {
|
||||
v.push(Overlay::Path { path, color, width: 1.0, dashed: false });
|
||||
// One overlay per layer color, sharing the kept outlines.
|
||||
if ge_on || self.tool.id() == "selection" {
|
||||
let shown = crate::cmd::globaledit::highlights(self);
|
||||
for (color, paths) in &shown.groups {
|
||||
v.push(Overlay::Outlines { paths: paths.clone(), color: *color, revision: shown.revision });
|
||||
}
|
||||
}
|
||||
if let Some((cmd, p)) = deferred_preview {
|
||||
v.extend(self.deferred_preview_overlays_from_command(&cmd, &p));
|
||||
|
||||
@@ -88,6 +88,11 @@ pub enum Overlay {
|
||||
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
|
||||
/// as the whole line does.
|
||||
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
|
||||
/// Thin solid outlines of many objects in one color (the objects Global Edit takes). Later calls
|
||||
/// return the same `paths` with the same `revision` for as long as the outlines do not change, and
|
||||
/// a new `revision` when they do. The host strokes them again only when `revision` or the view
|
||||
/// changes.
|
||||
Outlines { paths: std::sync::Arc<[BezPath]>, color: [u8; 3], revision: u64 },
|
||||
/// A line segment (smart guide, handle line).
|
||||
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
|
||||
/// An anchor square: filled = selected.
|
||||
|
||||
@@ -48,7 +48,7 @@ pub(super) fn show(app: &VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace,
|
||||
});
|
||||
}
|
||||
|
||||
/// The framework control `o` stands for, if it is one: a marquee, a settled outline or a distance.
|
||||
/// The framework control `o` stands for, if it is one: a marquee, a settled outline, a set of outlines or a distance.
|
||||
fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
|
||||
match o {
|
||||
Overlay::Marquee(r) => {
|
||||
@@ -65,6 +65,11 @@ fn show_control(ui: &mut egui::Ui, rect: ScreenRect, o: &Overlay) {
|
||||
let outline = if dash.is_some() { SelectionOutline::dashed(Label::Empty, paths) } else { SelectionOutline::solid(Label::Empty, paths) };
|
||||
outline.color(data(*color)).revision(revision).show_at(ui, rect);
|
||||
}
|
||||
Overlay::Outlines { paths, color, revision } => {
|
||||
// The overlay's revision changes whenever its paths do, so the lines are stroked again only then or when
|
||||
// the view changes.
|
||||
SelectionOutline::solid(Label::Empty, paths).color(data(*color)).revision(*revision).show_at(ui, rect);
|
||||
}
|
||||
Overlay::Distance { .. } => {
|
||||
if let Some((measure, color)) = distance_measure(o) {
|
||||
SmartGuides::new(&[], std::slice::from_ref(&measure)).color(color).show_at(ui, rect);
|
||||
@@ -180,7 +185,7 @@ impl Component for ToolMarks<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths and distances are controls
|
||||
/// Paints the marks of `overlays` through `draw` in `view`; the marquees, shared paths, outlines and distances are controls
|
||||
/// of their own and paint nothing here.
|
||||
// PLAN: contract cv.S14 gives `paint(draw, view, overlays, options)`; the pill, ink and ring colours come from the theme, so the style goes too.
|
||||
fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &PathOptionsSettings, style: &ToolMarksStyle) {
|
||||
@@ -244,6 +249,7 @@ fn paint(draw: &Draw<'_>, view: &CanvasView, overlays: &[Overlay], options: &Pat
|
||||
Overlay::Marquee(_)
|
||||
| Overlay::SelectionMarquee { .. }
|
||||
| Overlay::SharedPath { .. }
|
||||
| Overlay::Outlines { .. }
|
||||
| Overlay::Distance { .. }
|
||||
| Overlay::HoverText { .. } => {}
|
||||
}
|
||||
|
||||
@@ -333,6 +333,30 @@ fn a_selection_drag_draws_its_marks_in_the_frame_the_pointer_moves() {
|
||||
assert!(moved >= 4, "the drag moves the object: {moved} frames");
|
||||
}
|
||||
|
||||
/// With one rectangle selected, the canvas outlines its copies, which Start Global Edit would take, at their corners.
|
||||
#[test]
|
||||
fn the_canvas_outlines_the_objects_global_edit_would_take() {
|
||||
let mut app = drag_app();
|
||||
let rect = |app: &mut VectorcraftApp, x: f64| {
|
||||
app.session.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 40, "height": 30})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let key = rect(&mut app, 20.0);
|
||||
let copies = [rect(&mut app, 120.0), rect(&mut app, 220.0)];
|
||||
app.select_tool("selection");
|
||||
app.session.execute("select.set", &json!({"ids": [key]})).unwrap();
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let xf = app.canvas_view().unwrap();
|
||||
let points = painted_points(&mut app, &ctx, vec![]);
|
||||
for id in copies {
|
||||
let b = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
|
||||
for corner in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y1)] {
|
||||
let at = xf.to_screen(corner);
|
||||
assert!(points.iter().any(|p| p.distance(at) < 1.0), "copy {id} is outlined at {at:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Pen drag draws the handle it pulls out in the frame the pointer moves: its end at that frame's pointer, and
|
||||
/// none at the pointer of the frame before.
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user