Tile: other panes keep their selected objects' outlines between frames

Each pane other than the current document's, under Window > Arrange >
Tile and in floating document windows, made and flattened the outlines
of its document's selected objects on every frame, and with more points
than are outlined it measured the bounds of every selected object on
every frame. The pane now keeps the outline shapes by slot and makes
them again when the document's revision, the document, the selection or
the pane's screen mapping changes. The shapes drawn are the same as
before. A pane with View > Edges off keeps none, and the outlines of
panes that no longer show are dropped with the pane's other state.

With every object selected, one frame of a pane's outlines with their
tessellation takes 28.9 ms of CPU time in a release build instead of
40.1 ms for 20,000 rectangles, 116.7 ms instead of 197.2 ms for 20,000
ellipses, and 0.05 ms instead of 32.0 ms for 150,000 rectangles (medians
of seven interleaved runs of 20 frames, pane_outlines_timing).
This commit is contained in:
dotCooCoo
2026-11-17 11:47:47 -08:00
parent 36b5a5920c
commit e24d15c40c
3 changed files with 272 additions and 11 deletions
+66 -11
View File
@@ -9,12 +9,12 @@ use std::collections::HashMap;
use std::sync::Arc;
use super::grid::LineLook;
use super::outline::{c32, node_outline, stroke_path, too_many_anchors};
use super::outline::{c32, node_outline, to_screen_path, too_many_anchors};
use super::view::fit_zoom;
use super::{
Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key,
dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers,
shows_artboards, textured_quad, vec2, view_rects,
Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop,
cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2,
rulers, shows_artboards, textured_quad, vec2, view_rects,
};
use crate::doc_windows::Win;
use crate::thumb_worker::ThumbWorker;
@@ -42,6 +42,32 @@ pub struct Panes {
/// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and
/// center the fit gave.
fits: HashMap<Slot, (egui::Vec2, f64, Point)>,
/// By slot: the outlines of the selected objects the pane drew last, and what they show.
outlines: HashMap<Slot, Outlines>,
/// How many times a pane's outlines were made.
outlines_made: u64,
}
/// A pane's selected-object outlines as screen shapes, and the document revision, document,
/// selection and screen mapping they were made for.
struct Outlines {
revision: u64,
doc: usize,
selection: Vec<vectorcraft_doc::NodeId>,
affine: [f64; 6],
shapes: Vec<egui::Shape>,
}
impl Outlines {
/// Whether these outlines show `st`'s selection through the screen mapping `affine`.
fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool {
self.revision == st.revision && self.doc == doc_address(st) && self.affine == *affine && self.selection == st.selection.objects
}
}
/// The address of `st`'s document, which tells two documents with the same revision apart.
fn doc_address(st: &vectorcraft_engine::DocState) -> usize {
Arc::as_ptr(&st.doc) as usize
}
impl Panes {
@@ -51,6 +77,7 @@ impl Panes {
self.pending.clear();
self.last.clear();
self.fits.clear();
self.outlines.clear();
}
/// Upload `img`, the render `key` describes, for `slot`.
@@ -220,6 +247,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
app.canvas.panes.clear();
}
app.canvas.panes.last.clear();
// Only the floating windows draw panes now.
let floating = &app.ui.floating;
app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n));
return false;
}
// The current window's pane is the canvas, unless it is a floating one.
@@ -229,6 +259,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
app.canvas.panes.shown.retain(|s, _| live.contains(s));
app.canvas.panes.pending.retain(|s, _| live.contains(s));
app.canvas.panes.fits.retain(|s, _| live.contains(s));
app.canvas.panes.outlines.retain(|s, _| live.contains(s));
// A window opened, closed, floated or docked changes the grid, and so does coming back to the
// panes from one window: each window fits its new pane.
if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) {
@@ -456,7 +487,9 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
guides_of(app, st, (&painter, &xf, &t), rect);
}
if app.ui.view.edges {
selected_objects(st, &painter, &xf);
selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf);
} else {
app.canvas.panes.outlines.remove(&slot);
}
if app.ui.view.rulers && app.ui.screen_mode < 3 {
rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t);
@@ -474,23 +507,45 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed())
}
/// The outlines of the objects selected in `st`, in their layers' colors; their bounds when they
/// have too many points to outline.
fn selected_objects(st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) {
/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from
/// the outlines `panes` kept for the slot while they show the same revision, document, selection
/// and screen mapping, and made again otherwise.
fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) {
let affine = xf.affine().as_coeffs();
if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) {
let shapes = outline_shapes(st, xf);
let kept = Outlines { revision: st.revision, doc: doc_address(st), selection: st.selection.objects.clone(), affine, shapes };
panes.outlines.insert(slot, kept);
panes.outlines_made += 1;
}
for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) {
painter.add(shape.clone());
}
}
/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their
/// layers' colors; their bounds when they have too many points to outline.
fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec<egui::Shape> {
let mut shapes = vec![];
if st.selection.objects.is_empty() {
return shapes;
}
let symbols = st.doc.symbol_boxes();
let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> =
st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect();
let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id)));
let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s)));
if too_many_anchors(nodes.iter().map(|(_, n)| *n)) {
let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b));
if let (Some(b), Some((id, _))) = (bounds, nodes.first()) {
stroke_path(painter, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, color(*id));
stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id));
}
return;
return shapes;
}
for (id, n) in nodes {
stroke_path(painter, &node_outline(n, &symbols), xf, color(id));
stroke(&node_outline(n, &symbols), color(id));
}
shapes
}
#[cfg(test)]
+205
View File
@@ -540,6 +540,132 @@ fn other_panes_draw_their_guides_and_selected_objects() {
assert_ne!(layer, Color32::TRANSPARENT);
}
/// The selected objects' outlines as the panes made them on every frame before they kept them,
/// to hold the kept outlines against.
fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec<Shape> {
let mut shapes = vec![];
let symbols = st.doc.symbol_boxes();
let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> =
st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect();
let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id)));
let mut stroke_path = |bp: &BezPath, s: Stroke| {
for line in to_screen_path(bp, xf) {
shapes.push(Shape::line(line, s));
}
};
if too_many_anchors(nodes.iter().map(|(_, n)| *n)) {
let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b));
if let (Some(b), Some((id, _))) = (bounds, nodes.first()) {
stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id));
}
return shapes;
}
for (id, n) in nodes {
stroke_path(&node_outline(n, &symbols), color(id));
}
shapes
}
/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they
/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order.
fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] {
let pane = panes(app).1[0];
let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]);
let slot = (app.session.documents()[0].uid, 1);
let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes;
assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh");
assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines");
kept
}
/// Run `cmd` on the first document of a tiled pair, then make the second current again.
fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value {
app.run("document.activate", json!({"index": 0})).unwrap();
let out = app.session.execute(cmd, &args).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
out
}
#[test]
fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() {
let mut app = app_with(2);
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("window.arrange.tile", json!({})).unwrap();
let ctx = egui::Context::default();
let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone();
let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone();
in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]}));
frame(&mut app, &ctx, vec![]);
let drawn = frame(&mut app, &ctx, vec![]);
assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined");
let made = app.canvas.panes.outlines_made;
let drawn = frame(&mut app, &ctx, vec![]);
kept_outlines(&app, &ctx, &drawn);
assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines");
let changed = |app: &mut VectorcraftApp, what: &str| {
let made = app.canvas.panes.outlines_made;
let drawn = frame(app, &ctx, vec![]);
kept_outlines(app, &ctx, &drawn);
assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once");
let drawn = frame(app, &ctx, vec![]);
kept_outlines(app, &ctx, &drawn);
assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines");
};
in_first(&mut app, "select.set", json!({"ids": [ellipse]}));
changed(&mut app, "a new selection");
in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10}));
changed(&mut app, "a move");
let layer = app.session.documents()[0].doc.layers[0].id.0;
in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"}));
changed(&mut app, "a new layer color");
app.views[0].center.x += 25.0;
changed(&mut app, "a pan");
app.views[0].zoom *= 1.5;
app.views[0].rotation = 20.0;
changed(&mut app, "a zoom and a turn");
app.ui.view.edges = false;
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept");
app.ui.view.edges = true;
changed(&mut app, "Edges on again");
in_first(&mut app, "select.none", json!({}));
changed(&mut app, "an empty selection");
let drawn = frame(&mut app, &ctx, vec![]);
assert!(kept_outlines(&app, &ctx, &drawn).is_empty());
// 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds.
let st = &app.session.documents()[0];
let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.session
.edit("Fill", |d, _| {
let layer = d.layers[0].id;
for _ in 0..30_000 {
let mut n = rect.clone();
n.id = d.alloc_id();
d.insert(Some(layer), usize::MAX, n)?;
}
Ok(())
})
.unwrap();
app.run("select.all", json!({})).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
changed(&mut app, "selecting more points than are outlined");
let drawn = frame(&mut app, &ctx, vec![]);
assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds");
app.run("window.arrange.consolidateAllWindows", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines");
// Panes that stop showing before their render arrives keep no outlines either.
app.run("window.arrange.tile", json!({})).unwrap();
frame(&mut app, &ctx, vec![]);
assert_eq!(app.canvas.panes.outlines.len(), 1);
app.ui.tiled = false;
app.canvas.panes.shown.clear();
app.canvas.panes.last.clear();
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept");
}
#[test]
fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() {
let mut app = app_with(2);
@@ -874,3 +1000,82 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con
assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color");
assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color");
}
fn thread_cpu_ns() -> Option<u128> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and
/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so
/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the
/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or
/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time
/// per frame of 7 runs is printed.
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; performance depends on machine load"]
fn pane_outlines_timing() {
const FRAMES: u32 = 20;
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames");
for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] {
let mut app = app_with(1);
let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap();
app.session
.edit("Fill", |d, _| {
let layer = d.layers[0].id;
for _ in 1..count {
let mut n = node.clone();
n.id = d.alloc_id();
d.insert(Some(layer), usize::MAX, n)?;
}
Ok(())
})
.unwrap();
app.run("select.all", json!({})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.selection.objects.len(), count);
let ctx = egui::Context::default();
let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0));
let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 };
let mut kept = Panes::default();
let slot = (st.uid, 1);
let mut pass = |fresh: bool| {
let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() };
let out = ctx.run_ui(raw, |ui| {
let painter = ui.painter_at(area);
if fresh {
for s in outlines_made_each_frame(st, &xf) {
painter.add(s);
}
} else {
selected_objects(&mut kept, slot, st, &painter, &xf);
}
});
ctx.tessellate(out.shapes, out.pixels_per_point).len()
};
assert_eq!(pass(true), pass(false), "both sides draw as much");
let mut time = |fresh: bool| {
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
for _ in 0..FRAMES {
pass(fresh);
}
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
ns as f64 / f64::from(FRAMES) / 1e6
};
let (mut fresh, mut cached) = (vec![], vec![]);
for _ in 0..7 {
fresh.push(time(true));
cached.push(time(false));
}
let median = |v: &mut Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len());
eprintln!("{count} x {shape} ({shapes} lines drawn)");
eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh));
eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached));
}
}
+1
View File
@@ -2236,6 +2236,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Control bar and task bar on large paths:** the Control bar and the contextual task bar read the first selected object in place each frame instead of copying it; the task bar copies the object only when it is a basic shape, for its Shape Properties. With one selected open path of 200,000 anchors, an idle frame with both bars shown takes 3.8 ms in a release build instead of 8.0 ms (medians of five interleaved runs). Tests: `the_control_bar_label_follows_edits_undo_documents_and_selection`, `the_task_bar_follows_the_active_document`, `the_task_bar_follows_edits_and_undo`.
- **Paste of many objects:** Paste leaves pasted copies as they are when no resource has another name or color in the document and the objects link no graphic style. It looks up the pasted type in one walk of the tree. A paste and undo of 20,000 rectangles in 200 groups uses 49.2 ms of CPU time in a release build instead of 59.4 ms, and of 5,000 point type objects 25.3 ms instead of 29.4 ms (medians of seven interleaved rounds, each round the CPU time of a 61-paste run minus a 1-paste run, divided by 60). Tests: `crates/engine/tests/it/paste_many.rs`.
- **Selected objects in other panes:** under Window › Arrange › Tile and in floating document windows, each pane other than the current document's keeps the outlines of its selected objects between frames, and makes them again when its document, its selection or its view changes; with View › Edges off it keeps none. The outlines drawn are the same as before. With every object selected, a frame of a pane's outlines, tessellation included, takes 28.9 ms of CPU time in a release build instead of 40.1 ms for 20,000 rectangles, 116.7 ms instead of 197.2 ms for 20,000 ellipses, and 0.05 ms instead of 32.0 ms for 150,000 rectangles, which the pane draws as their bounds (medians of seven interleaved runs of 20 frames). Tests: `canvas::panes::tests::other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes`; timing: `pane_outlines_timing`.
- **Type drawn as glyph outlines:** under a geometry effect, in EMF and WMF export, in DXF export when it is written as outlines, flattened with Convert All Text to Outlines, and inside an envelope, type keeps its underline and strikethrough, the weight and dashes of its character strokes when it is scaled, and the placement of its gradients and patterns, as the canvas draws it. A group's or layer's own fills and strokes also paint the underline and strikethrough of the type in it.