draw: the Bezier overlay looks each knot up in the selection's anchors gathered once per pass

scene, parts, paint and other_handles asked the selection about every knot
they drew. has_anchor searched the edited path's anchor list and
draws_selected searched every entry of `others`, so a frame cost the knot
count times the number of selected anchors.

The overlay now gathers the selection's anchors into hash sets once per
scene (SelectedAnchors) and every per-knot question reads those sets. A path
listed more than once in `others` still counts as one path holding every
anchor listed for it. The handles and the selected marks drawn do not
change.

Measured in VectorCraft on Linux x86_64 (release test build), with
craft-libs at the VectorCraft pin plus #3466 and #3472:

- one path with 16,000 anchors, all selected, Direct Selection: an idle
  frame went from 515 ms to 33 ms, the first frame from 1,124 ms to 153 ms
- 1,500 selected rectangles, Properties open: an idle frame went from
  26.3 ms to 25.0 ms

Trial a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection
counts the anchor-list entries a frame reads for 60 and for 120 selected
paths, and fails when the count grows faster than the selection.
This commit is contained in:
dotCooCoo
2026-11-25 07:55:39 -08:00
parent 9dfaf04f02
commit 96434df276
4 changed files with 157 additions and 25 deletions
+41 -19
View File
@@ -4,6 +4,7 @@ use craft_behavior::CanvasView;
use egui::Pos2;
use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point};
use super::model::SelectedAnchors;
use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection};
/// A shown direction handle: its path's index, its knot, side and screen end.
@@ -46,20 +47,34 @@ impl BezierOverlay<'_> {
reach: f32,
) -> Option<BezierHit> {
// pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind).
let shown = shown_handles(paths, selection, handles, view);
let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view);
let anchors = paths.iter().map(EditPath::anchor_count).sum::<usize>() <= MAX_ANCHORS;
hit_in(paths, &shown, anchors, view, at, reach)
}
}
/// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection
/// does not show.
pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
shown_handles_of(paths, sel, sel.selected_len(), handles, view)
/// does not show. `anchors` holds the anchors `sel` selects.
pub(super) fn shown_handles(
paths: &[EditPath],
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view)
}
/// [`shown_handles`] with `selected` as the number of selected anchors that `OneAnchor` counts.
fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the
/// number of selected anchors that `OneAnchor` counts.
fn shown_handles_of(
paths: &[EditPath],
sel: &PathSelection,
has_anchor: impl Fn(u64, KnotRef) -> bool,
selected: usize,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let mut shown = Vec::new();
for (index, path) in paths.iter().enumerate() {
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
@@ -70,8 +85,8 @@ fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, ha
let Some(knot) = path.knot(knot_ref) else { continue };
for side in [HandleSide::In, HandleSide::Out] {
let of_selection = || {
sel.has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, sel, knot_ref, side)
has_anchor(path.key, knot_ref)
|| next_to_selected_anchor(path, &has_anchor, knot_ref, side)
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
};
let wanted = match handles {
@@ -91,15 +106,22 @@ fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, ha
/// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not
/// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted.
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per
/// path, so it reads the other paths' anchor counts from `sel` and copies none of their anchors.
pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none.
pub(super) fn other_handles(
paths: &[EditPath],
at: usize,
sel: &PathSelection,
anchors: &SelectedAnchors,
handles: HandlesShown,
view: &CanvasView,
) -> Vec<Shown> {
let Some(path) = paths.get(at) else { return Vec::new() };
let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key));
let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() };
let rest: usize = sel.others.iter().filter(|(key, _)| *key != path.key).map(|(_, rest)| rest.len()).sum();
let edited = sel.path.filter(|edited| *edited != path.key).map_or(0, |_| sel.anchors.len());
let own = PathSelection::new(Some(path.key), anchors.clone(), None);
shown_handles_of(std::slice::from_ref(path), &own, anchors.len() + rest + edited, handles, view)
if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) {
return Vec::new();
}
let edited = sel.path.map_or(0, |_| sel.anchors.len());
let own = PathSelection::new(Some(path.key), Vec::new(), None);
shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view)
.into_iter()
.map(|shown| Shown { path: at, ..shown })
.collect()
@@ -107,14 +129,14 @@ pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection,
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out
/// handle or the next anchor's in handle, across a closed subpath's seam too.
fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool {
fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
let count = sub.knots.len();
match side {
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))),
HandleSide::In => {
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
}
}
}
+13 -6
View File
@@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles};
pub(crate) use mark::paint_mark;
pub use mark::{AnchorsShown, HitMark, SegmentMark};
use mark::{Fill, paint_handle, segment_path, stroke};
use model::SelectedAnchors;
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) use model::reads;
pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection};
pub use style::BezierStyle;
pub use words::BezierWords;
@@ -381,6 +384,8 @@ struct Scene {
items: Vec<Item>,
/// Over [`MAX_ANCHORS`] or hidden: outlines only.
limited: bool,
/// The anchors the selection selects (none when `limited`).
selected: SelectedAnchors,
}
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
@@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> {
let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::<usize>() > MAX_ANCHORS;
let mut items = Vec::new();
if limited {
return Scene { items, limited };
return Scene { items, limited, selected: SelectedAnchors::default() };
}
let selected = SelectedAnchors::of(self.selection);
let near = rect.expand(reach);
let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) };
let shown =
if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) };
let mut handles = shown.iter().peekable();
for (at, path) in paths.iter().enumerate() {
let count = path.anchor_count();
@@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> {
}
}
}
Scene { items, limited }
Scene { items, limited, selected }
}
/// Whether the press on `item` is the tool's.
@@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> {
for item in &scene.items {
let press = self.takes(item);
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot);
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
let part = if press { part.sense(PRESS) } else { part };
let part = if keyboard {
@@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> {
draw_end(path, item.knot, item.at, fill);
}
Kind::Anchor if item.shown => {
let fill = if self.selection.draws_selected(path.key, item.knot) {
let fill = if scene.selected.draws_selected(path.key, item.knot) {
Fill::Path(style.line)
} else {
Fill::Style(if cx.part_if_declared(item.part()).is_some() {
@@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> {
// The handles of anchors selected in paths the overlay does not edit: drawn, never parts.
if !circles {
for (at, path) in paths.iter().enumerate() {
for shown in other_handles(paths, at, self.selection, self.handles, &view) {
for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) {
draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill)));
}
}
+79
View File
@@ -2,6 +2,8 @@
//! the overlays report. The host converts its own path type to these each frame and applies the
//! edits to its own.
use std::collections::HashSet;
use craft_theme::Srgba;
use kurbo::{BezPath, CubicBez, Point, Vec2};
@@ -235,6 +237,8 @@ impl PathSelection {
/// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`.
pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum());
self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot))
}
@@ -245,6 +249,8 @@ impl PathSelection {
/// Whether `knot` of `path` is a selected anchor.
pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
#[cfg(all(test, feature = "screen-testing"))]
reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 });
self.path == Some(path) && self.anchors.contains(&knot)
}
@@ -268,6 +274,79 @@ impl PathSelection {
}
}
/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays
/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one
/// path holding every anchor listed for it.
#[derive(Default)]
pub(super) struct SelectedAnchors {
path: Option<u64>,
anchors: HashSet<KnotRef>,
others: HashSet<(u64, KnotRef)>,
listed: HashSet<u64>,
others_len: usize,
}
impl SelectedAnchors {
/// The anchors `sel` selects.
pub(super) fn of(sel: &PathSelection) -> Self {
let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum();
#[cfg(all(test, feature = "screen-testing"))]
reads::add(sel.anchors.len() + others_len);
Self {
path: sel.path,
anchors: sel.anchors.iter().copied().collect(),
others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(),
listed: sel.others.iter().map(|(key, _)| *key).collect(),
others_len,
}
}
/// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]).
pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.path == Some(path) && self.anchors.contains(&knot)
}
/// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]).
pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
}
/// Whether `knot` is one of the anchors `others` lists for `path`.
pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.others.contains(&(path, knot))
}
/// Whether `others` lists `path`, with or without anchors.
pub(super) fn lists(&self, path: u64) -> bool {
self.listed.contains(&path)
}
/// The number of anchors `others` lists over every path.
pub(super) fn others_len(&self) -> usize {
self.others_len
}
}
/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work.
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) mod reads {
use std::cell::Cell;
thread_local! {
static READS: Cell<usize> = const { Cell::new(0) };
}
/// Counts `n` entries read.
pub(crate) fn add(n: usize) {
READS.with(|reads| reads.set(reads.get() + n));
}
/// The entries read since the last call, and starts the count again.
pub(crate) fn take() -> usize {
READS.with(|reads| reads.replace(0))
}
}
/// Which of a knot's two direction handles.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
+24
View File
@@ -489,6 +489,30 @@ fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_a
);
}
// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square:
// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries
// read (a search of the lists for each anchor laid out or drawn quadruples them).
#[trial]
fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
let reads_for = |n: usize| {
let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0));
let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]);
let others: Vec<EditPath> =
(0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect();
let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None);
for other in &others {
selection = selection.also(other.key, (0..4).map(kr).collect());
}
let mut h = harness(std::iter::once(edited).chain(others).collect());
craft_draw::ui::pen::bezier::reads::take();
h.update(|st| st.selection = selection);
craft_draw::ui::pen::bezier::reads::take()
};
let (small, large) = (reads_for(60), reads_for(120));
assert!(small > 0, "the frame reads the selection");
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
}
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.