Merge pull request #2598 from LS254/perf/partial-upload

M8: the browser's canvas uploads only what an edit changed of its image
This commit is contained in:
BFlat
2026-11-28 14:56:49 +07:00
committed by GitHub
6 changed files with 386 additions and 58 deletions
+36 -5
View File
@@ -195,12 +195,28 @@ impl Steps {
#[derive(Default)]
pub struct Retained {
last: Option<Frame>,
/// See [`Self::patched`].
patched: Option<Vec<[u32; 4]>>,
}
impl Retained {
/// Forget the kept image (the next render is full).
pub fn clear(&mut self) {
self.last = None;
self.patched = None;
}
/// The image kept from the last render.
pub fn image(&self) -> Option<&Pixmap> {
self.last.as_ref().map(|f| &f.pix)
}
/// Where the last render's image differs from the one before it, when it is that image with
/// some areas drawn again in place (`[x, y, width, height]` in its pixels; none for a render
/// reused as it was): whoever holds the image before needs only these to have this one.
/// `None` after a full render and after a pan, which moves every pixel.
pub fn patched(&self) -> Option<&[[u32; 4]]> {
self.patched.as_deref()
}
/// Render `view` of `page`, reusing the previous render where nothing changed. Returns the
@@ -267,6 +283,7 @@ impl Retained {
/// The previous render patched where it could be (kept, see [`Self::keep`]), or what a full
/// render of `view` needs.
fn prepare(&mut self, doc: &Arc<Document>, page: NodeId, view: &View, opts: &Options) -> Option<Prepared> {
self.patched = None;
// A view that can't be put on a pixel grid (non-finite or absurd) draws nothing.
let Some((snapped, px)) = snap(view) else {
self.last = None;
@@ -296,9 +313,10 @@ impl Retained {
{
let same_doc = Arc::ptr_eq(&last.doc, doc);
let s = if same_doc { last.sensitive.clone() } else { Arc::new(sensitive(doc)) };
if let Some((pix, pixels)) = patch(last, doc, page, &snapped, px, opts, &s) {
if let Some((pix, pixels, areas)) = patch(last, doc, page, &snapped, px, opts, &s) {
let work = if pixels == 0 { Work::Reused } else { Work::Partial { pixels } };
self.keep(doc, page, (&snapped, px, fonts), opts, pix, s);
self.patched = areas;
return Some(Prepared::Patched(snapped, work));
}
sens = Some(s);
@@ -524,8 +542,18 @@ fn moved_points_area(before: &Document, after: &Document, page: NodeId, id: Node
}
/// The previous frame brought up to date for `doc` at `px`, rendering only what changed; `None`
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered.
fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64, i64), opts: &Options, s: &Sensitive) -> Option<(Pixmap, u64)> {
/// when a full render is the better (or only correct) choice. Also returns the pixels rendered,
/// and the areas they are in when nothing else of the image changed (it didn't move).
#[allow(clippy::type_complexity)]
fn patch(
last: Frame,
doc: &Arc<Document>,
page: NodeId,
view: &View,
px: (i64, i64),
opts: &Options,
s: &Sensitive,
) -> Option<(Pixmap, u64, Option<Vec<[u32; 4]>>)> {
let (w, h) = (i64::from(view.width), i64::from(view.height));
let (dx, dy) = (px.0.checked_sub(last.px.0)?, px.1.checked_sub(last.px.1)?);
if dx.abs() >= w || dy.abs() >= h {
@@ -581,7 +609,7 @@ fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64,
}
let mut damage: Vec<Px> = damage.iter().filter_map(|d| d.clamp(w, h)).collect();
if damage.is_empty() && dx == 0 && dy == 0 {
return Some((last.pix, 0));
return Some((last.pix, 0, Some(Vec::new())));
}
// Layers whose look depends on where they are cut are redrawn whole.
let sensitive: Vec<Px> = s.areas.iter().chain(last.sensitive.areas.iter()).filter_map(|r| to_px(*r, view.scale, px)).collect();
@@ -616,7 +644,10 @@ fn patch(last: Frame, doc: &Arc<Document>, page: NodeId, view: &View, px: (i64,
for d in &damage {
render_into(FrameRender { doc, page, view, px, opts }, d, margin, &mut pix)?;
}
Some((pix, pixels))
let area =
|d: &Px| Some([u32::try_from(d.x0).ok()?, u32::try_from(d.y0).ok()?, u32::try_from(d.x1 - d.x0).ok()?, u32::try_from(d.y1 - d.y0).ok()?]);
let areas = if dx == 0 && dy == 0 { damage.iter().map(area).collect() } else { None };
Some((pix, pixels, areas))
}
/// Move the image's content by `(-dx, -dy)` pixels in place (what was at `(x, y)` goes to
+41
View File
@@ -65,6 +65,47 @@ fn a_clip_edge_on_a_pixel_boundary_clips_the_same_in_every_render() {
assert_same(&pix, &render_view(&smaller, page, &shown, &opts).unwrap(), &format!("lod {lod}"));
}
}
/// What a patched render reports as changed ([`Retained::patched`]) takes in every pixel that
/// differs from the image before: whoever holds that image needs no more to have the new one.
#[test]
fn a_patched_render_says_where_it_differs_from_the_one_before() {
let mut d = Document::new("patched");
let page = d.first_page().unwrap();
let back = d.create(page, NodeKind::Rectangle, "Back", 0.0, 0.0, 200.0, 140.0).unwrap();
d.get_mut(back).unwrap().fills = vec![Paint::solid(Color::from_hex("F4F6F5").unwrap())];
let shape = d.create(page, NodeKind::Ellipse { start: 0.0, sweep: std::f64::consts::TAU, inner: 0.0 }, "Shape", 30.0, 30.0, 72.0, 49.0).unwrap();
d.get_mut(shape).unwrap().fills = vec![Paint::solid(Color::from_hex("7FAE9C").unwrap())];
let v = View { origin: (0.0, 0.0), scale: 3.0, width: 600, height: 400 };
let doc = Arc::new(d);
let mut r = Retained::default();
r.render(&doc, page, &v, &Options::default()).unwrap();
assert!(r.patched().is_none(), "a full render");
let before = r.image().unwrap().clone();
let mut d2 = (*doc).clone();
d2.get_mut(shape).unwrap().height = 30.0;
let d2 = Arc::new(d2);
let (_, after, work) = r.render(&d2, page, &v, &Options::default()).unwrap();
let after = after.clone();
let areas = r.patched().expect("patched in place").to_vec();
let Work::Partial { pixels } = work else { panic!("{work:?}") };
assert_eq!(areas.iter().map(|a| u64::from(a[2]) * u64::from(a[3])).sum::<u64>(), pixels);
let w = after.width() as usize;
let (mut differ, mut outside) = (0, 0);
for (i, (a, b)) in before.data().chunks_exact(4).zip(after.data().chunks_exact(4)).enumerate() {
if a != b {
differ += 1;
let (x, y) = ((i % w) as u32, (i / w) as u32);
outside += usize::from(!areas.iter().any(|&[ax, ay, aw, ah]| x >= ax && y >= ay && x < ax + aw && y < ay + ah));
}
}
assert!(differ > 1000 && outside == 0, "{differ} pixels differ, {outside} of them outside {areas:?}");
// The same again: nothing to hand over. A pan: every pixel moved.
r.render(&d2, page, &v, &Options::default()).unwrap();
assert_eq!(r.patched(), Some(&[][..]));
r.render(&d2, page, &View { origin: (2.0, 0.0), ..v }, &Options::default()).unwrap();
assert!(r.patched().is_none(), "a pan");
}
/// A closed zigzag of `2 * teeth + 2` points, 240 × 120 units at (20, 20): a ridge.
fn ridge(d: &mut Document, page: NodeId, teeth: usize) -> NodeId {
let mut pts = vec![figcraft_geom::Point::new(0.0, 120.0)];
+54 -8
View File
@@ -65,6 +65,9 @@ pub struct CanvasState {
tex_skipped: bool,
/// The request the texture answers ([`crate::render_worker::Done::seq`]).
tex_seq: u64,
/// Which of the worker's images the texture holds ([`render_worker::Done::frame`]), when it
/// is one of them: what the next render may hand over patches of.
tex_frame: Option<u64>,
/// Refined images of the files and pages shown before, newest first: switching back to one
/// shows its image at once while it renders again, instead of a blank canvas (and, where
/// renders are slow, a coarse preview).
@@ -154,6 +157,7 @@ impl Default for CanvasState {
tex_coarse: false,
tex_skipped: false,
tex_seq: 0,
tex_frame: None,
kept: Vec::new(),
surround: None,
submitted: None,
@@ -191,6 +195,20 @@ struct Kept {
seq: u64,
}
/// `part` put on `image` at (x, y) `at`, as [`egui::TextureHandle::set_partial`] puts it on the
/// texture; rows that don't lie in the image are left out.
fn put_patch(image: &mut egui::ColorImage, at: [usize; 2], part: &egui::ColorImage) {
let (w, [x, y]) = (image.size[0], at);
for (r, row) in part.pixels.chunks(part.size[0].max(1)).enumerate() {
let start = (y + r) * w + x;
if x + row.len() <= w
&& let Some(into) = image.pixels.get_mut(start..start + row.len())
{
into.copy_from_slice(row);
}
}
}
impl CanvasState {
/// When the file or page shown is no longer the one the texture is of, set the texture aside
/// (if refined) and bring back the image kept for `shown`, if any. Images of files that are no
@@ -206,6 +224,8 @@ impl CanvasState {
self.kept.insert(0, Kept { texture, view, of, seq: self.tex_seq });
}
self.tex_coarse = false;
// The worker's image is of the other file or page: this texture is none of its.
self.tex_frame = None;
self.tex_skipped = false;
if let Some(k) = back {
(self.texture, self.tex_view, self.tex_of, self.tex_seq) = (Some(k.texture), Some(k.view), Some(k.of), k.seq);
@@ -221,6 +241,31 @@ impl CanvasState {
self.kept.retain(|k| open(k.of.0));
}
/// Put a finished render's pixels on the texture, and on the copy kept of it
/// ([`Self::pixel_under`] reads that, so the colour it gives is the one shown).
fn take_pixels(&mut self, ctx: &egui::Context, pixels: render_worker::Pixels, filter: egui::TextureOptions) {
match pixels {
render_worker::Pixels::Whole(image) => {
let image = Arc::new(image);
match &mut self.texture {
Some(t) => t.set(Arc::clone(&image), filter),
None => self.texture = Some(ctx.load_texture("figcraft-canvas", Arc::clone(&image), filter)),
}
self.tex_pixels = Some(image);
}
// Patches of the image the texture holds (the worker was told which).
render_worker::Pixels::Patches(parts) => {
let Some(t) = &mut self.texture else { return };
for (at, part) in parts {
if let Some(kept) = &mut self.tex_pixels {
put_patch(Arc::make_mut(kept), at, &part);
}
t.set_partial(at, part, filter);
}
}
}
}
pub(crate) fn pixel_under(&self, p: Point, of: Option<(u64, NodeId)>, page: Color32) -> Option<Color32> {
let (image, v) = (self.tex_pixels.as_ref()?, self.tex_view.as_ref()?);
if of.is_none() || self.tex_of != of {
@@ -396,6 +441,9 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok();
let docs = &app.session.docs;
app.canvas.switch_texture(shown, |uid| docs.iter().any(|d| d.uid == uid));
// The browser's worker hands over only what changed of the image the texture holds.
#[cfg(target_arch = "wasm32")]
worker.texture_holds(app.canvas.tex_frame.filter(|_| app.canvas.texture.is_some() && app.canvas.tex_of == shown && !app.canvas.tex_coarse));
if let Some(done) = worker.poll()
&& shows(&app.canvas, &done, shown)
{
@@ -409,12 +457,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
} else {
egui::TextureOptions::LINEAR
};
let pixels = Arc::new(done.image);
match &mut app.canvas.texture {
Some(t) => t.set(Arc::clone(&pixels), filter),
None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", Arc::clone(&pixels), filter)),
}
app.canvas.tex_pixels = Some(pixels);
app.canvas.take_pixels(&ctx, done.image, filter);
app.canvas.tex_frame = (done.frame != 0 && !done.coarse).then_some(done.frame);
let done_at = done.at;
let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0);
if done.coarse {
@@ -429,17 +473,19 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
app.canvas.tex_seq = done.seq;
drag_sprite::arrived(&mut app.canvas, done_at, done.coarse);
}
// The image around the view always comes whole (nothing tells its worker what is held).
if let Some(around) = worker.surround()
&& shown == Some((around.uid, around.page))
&& let render_worker::Pixels::Whole(image) = around.image
{
let of = (around.uid, around.page);
match &mut app.canvas.surround {
Some((t, view, at)) => {
t.set(around.image, egui::TextureOptions::LINEAR);
t.set(image, egui::TextureOptions::LINEAR);
(*view, *at) = (around.view, of);
}
None => {
let t = ctx.load_texture("figcraft-canvas-surround", around.image, egui::TextureOptions::LINEAR);
let t = ctx.load_texture("figcraft-canvas-surround", image, egui::TextureOptions::LINEAR);
app.canvas.surround = Some((t, around.view, of));
}
}
+130 -29
View File
@@ -77,9 +77,33 @@ pub struct Job {
pub at: Instant,
}
/// What a finished render hands the canvas for its texture.
pub enum Pixels {
/// The whole image.
Whole(egui::ColorImage),
/// The parts that differ from the image the canvas said its texture holds
/// ([`Inline::texture_holds`]): each goes at its position (x, y) in that texture. An edit
/// redraws a part of the view; converting and uploading all of it again cost more than
/// drawing the part.
Patches(Vec<([usize; 2], egui::ColorImage)>),
}
impl Pixels {
/// The whole image, when that is what this is.
pub fn whole(&self) -> Option<&egui::ColorImage> {
match self {
Pixels::Whole(image) => Some(image),
Pixels::Patches(_) => None,
}
}
}
pub struct Done {
/// The image, ready for a texture (converted off the UI thread).
pub image: egui::ColorImage,
pub image: Pixels,
/// Which image of the worker's this is, numbered as they are drawn (0: a preview, or a
/// worker that doesn't number them): what the canvas reports back as its texture's.
pub frame: u64,
/// The view the image shows (the requested one snapped outwards to whole device pixels).
pub view: View,
pub ms: f64,
@@ -99,15 +123,39 @@ pub struct Done {
/// A render of a document in `profile` as a texture image for the screen (sRGB).
pub fn screen_image(pix: &Pixmap, profile: ColorProfile) -> egui::ColorImage {
let size = [pix.width() as usize, pix.height() as usize];
screen_pixels([pix.width() as usize, pix.height() as usize], pix.data(), profile)
}
/// [`screen_image`] of `size` premultiplied RGBA pixels.
fn screen_pixels(size: [usize; 2], rgba: &[u8], profile: ColorProfile) -> egui::ColorImage {
if profile.is_srgb() {
return egui::ColorImage::from_rgba_premultiplied(size, pix.data());
return egui::ColorImage::from_rgba_premultiplied(size, rgba);
}
let mut data = pix.data().to_vec();
let mut data = rgba.to_vec();
profile.conversion_to(ColorProfile::Srgb).apply_pixels(&mut data);
egui::ColorImage::from_rgba_premultiplied(size, &data)
}
/// The areas `[x, y, width, height]` of `pix` as texture images at their positions; `None` when
/// one doesn't lie in it.
fn screen_patches(pix: &Pixmap, areas: &[[u32; 4]], profile: ColorProfile) -> Option<Vec<([usize; 2], egui::ColorImage)>> {
let row = pix.width() as usize * 4;
areas
.iter()
.map(|&[x, y, w, h]| {
let (x, y, w, h) = (x as usize, y as usize, w as usize, h as usize);
if w == 0 || h == 0 || x + w > pix.width() as usize || y + h > pix.height() as usize {
return None;
}
let mut rgba = Vec::with_capacity(w * h * 4);
for r in y..y + h {
rgba.extend_from_slice(pix.data().get(r * row + x * 4..r * row + (x + w) * 4)?);
}
Some(([x, y], screen_pixels([w, h], &rgba, profile)))
})
.collect()
}
/// Soft proof: grey diagonal stripes over the pixels whose colours sRGB can't show.
fn mark_outside_srgb(image: &mut egui::ColorImage, pix: &Pixmap, profile: ColorProfile) {
let w = image.size[0].max(1);
@@ -138,16 +186,25 @@ fn options(job: &Job) -> figcraft_render::Options {
fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option<Done> {
let t0 = Instant::now();
let (view, pix, work) = retained.render(&job.doc, job.page, view, &options(job))?;
Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse))
Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, coarse, None))
}
/// The image `pix` of `view`, rendered for `job` in `ms`.
fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool) -> Done {
let mut image = screen_image(pix, job.doc.color_profile);
if job.proof {
mark_outside_srgb(&mut image, pix, job.doc.color_profile);
}
Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 }
/// The image `pix` of `view`, rendered for `job` in `ms`. With `patched`, only those areas of it
/// (see [`Pixels::Patches`]): the caller knows the canvas holds the rest. A soft proof stripes the
/// whole image, so it is always handed over whole.
fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool, patched: Option<&[[u32; 4]]>) -> Done {
let patches = patched.filter(|_| !job.proof).and_then(|areas| screen_patches(pix, areas, job.doc.color_profile));
let image = match patches {
Some(parts) => Pixels::Patches(parts),
None => {
let mut image = screen_image(pix, job.doc.color_profile);
if job.proof {
mark_outside_srgb(&mut image, pix, job.doc.color_profile);
}
Pixels::Whole(image)
}
};
Done { image, frame: 0, view, ms, work, uid: job.uid, page: job.page, coarse, skipped: !job.skip.is_empty(), at: job.at, seq: 0 }
}
/// The coarse image around the view is this many views wide and tall, centred on it.
@@ -213,7 +270,7 @@ impl Surround {
let t0 = Instant::now();
let d = guarded(&mut self.retained, |r| {
let (snapped, pix, work) = r.render(&job.doc, job.page, &view, &options(job))?;
(!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true))
(!(same && work == Work::Reused)).then(|| done(job, snapped, pix, work, t0.elapsed().as_secs_f64() * 1000.0, true, None))
});
if d.is_some() {
self.of = Some((job.uid, job.page, view, job.proof));
@@ -243,6 +300,11 @@ pub struct Renders {
/// A full render being drawn band by band (the browser): the job it was started for, the
/// font generation then, the bands and the time they took so far.
steps: Option<Stepping>,
/// The number of the image `full` keeps: every image drawn there gets the next one
/// ([`Done::frame`]), handed to the canvas or not.
frame: u64,
/// Whether that image was handed over with a soft proof's stripes ([`Job::proof`]).
frame_proofed: bool,
#[cfg(test)]
refine_gate: Option<RefineGate>,
}
@@ -314,6 +376,8 @@ impl Renders {
full_ms: 0.0,
preview_after_ms: ms,
steps: None,
frame: 0,
frame_proofed: false,
#[cfg(test)]
refine_gate: None,
}
@@ -389,6 +453,13 @@ impl Renders {
done
}
/// `d`, an image drawn in `full` just now for a job with soft proof `proofed`, numbered.
fn numbered(&mut self, d: Done, proofed: bool) -> Done {
self.frame += 1;
self.frame_proofed = proofed;
Done { frame: self.frame, ..d }
}
/// The image of `job`'s view, built on the kept one where it can be.
pub fn refine(&mut self, job: &Job) -> Option<Done> {
let done = guarded(&mut self.full, |r| run(job, &job.view, r, false));
@@ -397,6 +468,7 @@ impl Renders {
Some(gate) => gate(job, done),
None => done,
};
let done = done.map(|d| self.numbered(d, job.proof));
if let Some(d) = &done {
self.keep(job, d);
if d.work == Work::Full {
@@ -408,7 +480,10 @@ impl Renders {
/// [`Self::refine`] for about `budget_ms` at a time (the browser): a full render is drawn band by
/// band over several calls, the kept image (re-projected) or the preview showing meanwhile.
pub fn refine_for(&mut self, job: &Job, budget_ms: f64) -> Refined {
///
/// `holds` is the number of the image the canvas's texture holds ([`Done::frame`]), if it is
/// one of these: a render that only patches that image hands over the patches.
pub fn refine_for(&mut self, job: &Job, budget_ms: f64, holds: Option<u64>) -> Refined {
let t0 = Instant::now();
if let Some(s) = self.steps.as_ref()
&& !same_settings(&s.job, job)
@@ -419,7 +494,7 @@ impl Renders {
self.steps = None;
}
if self.steps.is_none()
&& let Some(r) = self.begin(job, t0, None)
&& let Some(r) = self.begin(job, t0, None, holds)
{
return r;
}
@@ -444,14 +519,15 @@ impl Renders {
self.full_ms = spent;
// The image of the job it was started for: its document's colour profile, its
// proof setting and its request time.
let drawn = done(&drawn_for, view, pix, Work::Full, spent, false);
let drawn = done(&drawn_for, view, pix, Work::Full, spent, false, None);
let drawn = self.numbered(drawn, drawn_for.proof);
// Drawn for this very request: shown, done. Otherwise kept, then started on like
// any render: an edit, a pan or images that came meanwhile are patched in, or it
// is drawn again in steps (never all at once here), this one shown till then.
if same_request(&drawn_for, fonts, job) {
return Refined::Done(self.finished(job, Some(drawn)));
}
self.begin(job, t0, Some(drawn)).unwrap_or(Refined::More)
self.begin(job, t0, Some(drawn), holds).unwrap_or(Refined::More)
}
Err(_) => {
self.steps = None;
@@ -464,18 +540,30 @@ impl Renders {
/// Start `job` on the kept image: done when it is reused or patched, `None` when a full render
/// is now drawn in steps. `drawn` is the kept image just drawn in steps: what a reuse shows,
/// else shown while it is drawn again.
fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option<Done>) -> Option<Refined> {
fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option<Done>, holds: Option<u64>) -> Option<Refined> {
// The snapped view may be a row taller.
let rows = job.view.height.saturating_add(1).div_ceil(MAX_BANDS).max(MIN_BAND_ROWS);
let begun =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match self.full.begin(&job.doc, job.page, &job.view, &options(job), rows) {
Some(Begun::Done(view, pix, work)) => Err(Box::new(match drawn.take() {
Some(d) if work == Work::Reused => Some(d),
_ => Some(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false)),
})),
Some(Begun::Steps(steps)) => Ok(steps),
None => Err(Box::new(None)),
}));
// The canvas holds the image this render starts from: one that only patches it hands
// over the patches.
// Not when that image was handed over with a soft proof's stripes on it: the renderer's
// image has none, so patches of it (none at all, when only the proof was turned off)
// would leave them on the texture.
let held = holds.is_some_and(|f| f == self.frame) && !self.frame_proofed;
let full = &mut self.full;
let begun = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let (view, work) = match full.begin(&job.doc, job.page, &job.view, &options(job), rows) {
Some(Begun::Done(view, _, work)) => (view, work),
Some(Begun::Steps(steps)) => return Ok(steps),
None => return Err(Box::new(None)),
};
Err(Box::new(match drawn.take() {
Some(d) if work == Work::Reused => Some((d, false)),
_ => full.image().map(|pix| {
let patched = full.patched().filter(|_| held);
(done(job, view, pix, work, t0.elapsed().as_secs_f64() * 1000.0, false, patched), true)
}),
}))
}));
match begun {
Ok(Ok(steps)) => {
// A pan or an edit at this zoom builds on this render: no preview for it.
@@ -486,7 +574,11 @@ impl Renders {
Refined::Shown(d)
})
}
Ok(Err(d)) => Some(Refined::Done(self.finished(job, *d))),
Ok(Err(d)) => {
// An image drawn now gets its number; one drawn in steps just before has it.
let d = d.map(|(d, new)| if new { self.numbered(d, job.proof) } else { d });
Some(Refined::Done(self.finished(job, d)))
}
Err(_) => {
self.full.clear();
Some(Refined::Done(None))
@@ -768,6 +860,8 @@ pub struct Inline {
/// The wait for the pending job's preview.
wait: std::time::Duration,
renders: Renders,
/// See [`Self::texture_holds`].
holds: Option<u64>,
}
#[cfg(target_arch = "wasm32")]
@@ -789,6 +883,7 @@ impl Inline {
settle,
wait: settle,
renders: Renders::default(),
holds: None,
}
}
/// Previewing when renders from scratch take at least `ms` (tests: 0, whatever the machine).
@@ -812,6 +907,12 @@ impl Inline {
pub fn surround(&mut self) -> Option<Done> {
None
}
/// Tell the worker which of its images the canvas's texture holds ([`Done::frame`]; `None`:
/// none of them, or not for sure). The next image comes as patches of that one when that is
/// all that changed ([`Pixels::Patches`]); without this, every image comes whole.
pub fn texture_holds(&mut self, frame: Option<u64>) {
self.holds = frame;
}
pub fn poll(&mut self) -> Option<Done> {
self.poll_at(Instant::now())
}
@@ -836,7 +937,7 @@ impl Inline {
}
}
let job = self.pending.as_ref()?;
match self.renders.refine_for(job, STEP_MS) {
match self.renders.refine_for(job, STEP_MS, self.holds) {
Refined::Done(d) => {
self.pending = None;
d.map(|d| answering(d, self.submitted))
+115 -15
View File
@@ -20,9 +20,15 @@ use super::{CanvasState, shows};
use figcraft_render::Retained;
use crate::render_worker::{
Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now,
Done, Inline, Job, PREVIEW_AFTER_MS, PREVIEW_FACTOR, Pixels, Refined, Renders, SETTLE_MS, Worker, better, coarse_view, preview_with, render_now,
};
/// The whole image a render handed over (these all are: nothing here tells the worker what the
/// canvas holds).
fn whole(d: &Done) -> &egui::ColorImage {
d.image.whole().expect("a whole image")
}
/// A page of ellipses with a rectangle on top; the session and the rectangle. The system fonts are
/// scanned first (once per process, and a concurrent caller waits for it): the scan another test
/// starts bumps the global font generation, and a render kept from before it is stale, so a pan
@@ -93,17 +99,17 @@ pub(super) fn job(doc: &Arc<Document>, page: NodeId, uid: u64, view: View) -> Jo
/// Every pixel of `a` and `b` alike.
fn same_pixels(a: &Done, b: &Done) -> bool {
a.image.size == b.image.size && a.image.pixels == b.image.pixels
whole(a).size == whole(b).size && whole(a).pixels == whole(b).pixels
}
/// The same image up to where render bands meet ([`figcraft_render::Steps`] and the desktop's
/// parallel bands cut the view in different places): on each row, under a quarter of a level on
/// average and at most one pixel in twenty off.
fn close_pixels(a: &Done, b: &Done) -> bool {
let [w, h] = a.image.size;
a.image.size == b.image.size
let [w, h] = whole(a).size;
whole(a).size == whole(b).size
&& (0..h).all(|y| {
let row = |d: &Done| d.image.pixels[y * w..(y + 1) * w].to_vec();
let row = |d: &Done| whole(d).pixels[y * w..(y + 1) * w].to_vec();
let (ra, rb) = (row(a), row(b));
let diffs: Vec<u32> =
ra.iter().zip(&rb).map(|(p, q)| p.to_array().iter().zip(q.to_array()).map(|(x, y)| u32::from(x.abs_diff(y))).sum()).collect();
@@ -135,7 +141,7 @@ fn refined_at(w: &mut Inline, now: Instant) -> Option<Done> {
/// Refine `job` through `r` with no time to spare (a band a call); the image and how many calls.
fn stepped(r: &mut Renders, job: &Job) -> (Option<Done>, usize) {
for n in 1..1000 {
match r.refine_for(job, 0.0) {
match r.refine_for(job, 0.0, None) {
Refined::Done(d) => return (d, n),
Refined::Shown(_) | Refined::More => {}
}
@@ -162,7 +168,7 @@ fn a_zoom_out_previews_the_whole_view_then_refines_to_a_fresh_render() {
let p = r.preview(&out).expect("a preview first");
assert!(p.coarse && (p.uid, p.page) == (ds.uid, ds.page));
assert!(covers(&p.view, &out.view), "the preview shows the whole view asked for");
let pixels = |d: &Done| d.image.size[0] * d.image.size[1];
let pixels = |d: &Done| whole(d).size[0] * whole(d).size[1];
let fresh = render_now(&out).unwrap();
assert!(
(pixels(&p) as f64) * PREVIEW_FACTOR * PREVIEW_FACTOR < 1.5 * pixels(&fresh) as f64,
@@ -660,7 +666,7 @@ fn the_browser_draws_a_full_render_band_by_band() {
assert!(n > 2 && !r.stepping(), "several calls, then done ({n})");
assert!(close_pixels(&d, &render_now(&at(300.0)).unwrap()));
// Kept: a pan now patches it at once.
assert!(matches!(r.refine_for(&at(320.0), 0.0), Refined::Done(Some(d)) if d.work != Work::Full));
assert!(matches!(r.refine_for(&at(320.0), 0.0, None), Refined::Done(Some(d)) if d.work != Work::Full));
}
#[test]
@@ -670,14 +676,14 @@ fn a_pan_while_drawing_finishes_the_render_then_patches_it_and_a_zoom_drops_it()
let ds = s.ds().unwrap();
let at = |x, scale| job(&ds.doc, ds.page, ds.uid, view(x, scale));
let mut r = Renders::default();
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More));
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More));
// Panned meanwhile: the same render goes on, and what comes is the panned view.
let (d, _) = stepped(&mut r, &at(330.0, 1.0));
let d = d.expect("drawn");
assert!(close_pixels(&d, &render_now(&at(330.0, 1.0)).unwrap()), "the panned view");
// Zoomed meanwhile: the render under way is dropped for one of the new zoom.
let mut r = Renders::default();
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0), Refined::More));
assert!(matches!(r.refine_for(&at(300.0, 1.0), 0.0, None), Refined::More));
let (d, _) = stepped(&mut r, &at(300.0, 2.0));
assert_eq!(d.expect("drawn").view.scale, 2.0);
}
@@ -691,7 +697,7 @@ fn an_edit_while_drawing_shows_in_what_comes() {
(ds.doc.clone(), ds.page, ds.uid)
};
let mut r = Renders::default();
assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0), Refined::More));
assert!(matches!(r.refine_for(&job(&doc, page, uid, v.clone()), 0.0, None), Refined::More));
// Edited meanwhile, the view unchanged: the render goes on and what comes shows the edit.
s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 400, "height": 400})).unwrap();
let edited = job(&s.ds().unwrap().doc, page, uid, v);
@@ -705,11 +711,11 @@ fn a_render_overtaken_by_a_long_pan_is_shown_then_drawn_again() {
let s = slow_scene(std::slice::from_ref(&v), 3.0 * PREVIEW_AFTER_MS);
let ds = s.ds().unwrap();
let mut r = Renders::default();
assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0), Refined::More));
assert!(matches!(r.refine_for(&job(&ds.doc, ds.page, ds.uid, v.clone()), 0.0, None), Refined::More));
// Panned more than a view meanwhile: nothing to patch. What was drawn shows, then the new view.
let far = job(&ds.doc, ds.page, ds.uid, view_at((1500.0, 200.0), 1.0, 600, 600));
let mut shown = vec![];
let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0) {
let last = (0..1000).find_map(|_| match r.refine_for(&far, 0.0, None) {
Refined::More => None,
Refined::Shown(d) => {
shown.push(d);
@@ -751,7 +757,7 @@ fn a_change_of_options_while_drawing_drops_the_render() {
outlined.outline = true;
let (_, alone) = stepped(&mut Renders::default(), &outlined);
let mut r = Renders::default();
assert!(matches!(r.refine_for(&plain, 0.0), Refined::More));
assert!(matches!(r.refine_for(&plain, 0.0, None), Refined::More));
let (d, n) = stepped(&mut r, &outlined);
assert!(d.is_some_and(|d| !d.coarse));
assert!(n <= alone + 1, "the old render's bands are dropped: {n} calls against {alone} alone");
@@ -768,10 +774,88 @@ fn a_render_dropped_while_drawing_leaves_its_time_as_the_measure() {
let at = |scale| job(&ds.doc, ds.page, ds.uid, view(scale));
// Previews once renders have taken any time at all: a band has, where no measure (0 ms) hasn't.
let mut r = Renders::with_threshold(1e-9);
assert!(matches!(r.refine_for(&at(1.0), 0.0), Refined::More));
assert!(matches!(r.refine_for(&at(1.0), 0.0, None), Refined::More));
assert!(r.preview(&at(2.0)).is_some(), "the zoom gets a preview by the dropped render's measure");
}
/// `parts` put on `image` at their positions, as the canvas puts them on its texture.
fn patched(image: &egui::ColorImage, parts: &[([usize; 2], egui::ColorImage)]) -> egui::ColorImage {
let mut out = image.clone();
let w = out.size[0];
for ([x, y], part) in parts {
for (r, row) in part.pixels.chunks(part.size[0]).enumerate() {
out.pixels[(y + r) * w + x..(y + r) * w + x + row.len()].copy_from_slice(row);
}
}
out
}
/// An edit redraws a part of the view. Told which image the canvas holds, the worker hands over
/// that part only; put on that image, it makes the new one. Converting and uploading the whole
/// image again after every edit cost more than drawing the part.
#[test]
fn an_edit_hands_over_only_what_changed_of_the_image_the_canvas_holds() {
let (mut s, rect) = document();
let view = view_at((300.0, 250.0), 1.0, 700, 600);
let now = |s: &Session| {
let ds = s.ds().unwrap();
job(&ds.doc, ds.page, ds.uid, view.clone())
};
let widen = |s: &mut Session, w: u32| s.execute("node.set", &json!({"id": rect, "width": w})).unwrap();
let mut r = Renders::default();
let first = stepped(&mut r, &now(&s)).0.expect("drawn");
assert_ne!(first.frame, 0, "a numbered image");
// Not told what the canvas holds: the whole image.
widen(&mut s, 280);
let Refined::Done(Some(second)) = r.refine_for(&now(&s), 0.0, None) else { panic!("a patch is done at once") };
assert!(matches!(second.work, Work::Partial { .. }) && second.image.whole().is_some());
// Told it holds that image: the changed part only, and with it the canvas has the new image.
widen(&mut s, 240);
let Refined::Done(Some(third)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") };
let Pixels::Patches(parts) = &third.image else { panic!("patches of the image the canvas holds") };
let handed: usize = parts.iter().map(|(_, p)| p.pixels.len()).sum();
let all = whole(&second).pixels.len();
assert!(handed > 0 && handed * 4 < all, "{handed} of {all} pixels handed over");
let fresh = stepped(&mut Renders::default(), &now(&s)).0.expect("drawn");
let have = Done { image: Pixels::Whole(patched(whole(&second), parts)), ..render_now(&now(&s)).unwrap() };
assert!(close_pixels(&have, &fresh), "the patched image is the new one");
assert!(!close_pixels(&second, &fresh), "and the one before it is not");
// A canvas that holds an older image (it showed none of the last) gets the whole one.
widen(&mut s, 200);
let Refined::Done(Some(fourth)) = r.refine_for(&now(&s), 0.0, Some(second.frame)) else { panic!("a patch is done at once") };
assert!(fourth.image.whole().is_some(), "whole for a canvas an image behind");
// Nothing changed: nothing to hand over.
let Refined::Done(Some(same)) = r.refine_for(&now(&s), 0.0, Some(fourth.frame)) else { panic!("reused at once") };
assert!(matches!(&same.image, Pixels::Patches(parts) if parts.is_empty()) && same.work == Work::Reused);
// A pan moves every pixel: whole.
let ds = s.ds().unwrap();
let panned = job(&ds.doc, ds.page, ds.uid, view_at((320.0, 250.0), 1.0, 700, 600));
let Refined::Done(Some(moved)) = r.refine_for(&panned, 0.0, Some(same.frame)) else { panic!("a pan is patched at once") };
assert!(moved.image.whole().is_some(), "whole after a pan");
}
/// A soft proof stripes the image handed over, not the renderer's own. With the proof turned off
/// and nothing else changed, the renderer has nothing to redraw: the canvas still gets the whole
/// image, or the stripes would stay on its texture.
#[test]
fn turning_soft_proof_off_hands_over_the_whole_image() {
let (mut s, rect) = document();
let view = view_at((300.0, 250.0), 1.0, 700, 600);
let now = |s: &Session, proof: bool| {
let ds = s.ds().unwrap();
Job { proof, ..job(&ds.doc, ds.page, ds.uid, view.clone()) }
};
let mut r = Renders::default();
let proofed = stepped(&mut r, &now(&s, true)).0.expect("drawn");
assert!(proofed.image.whole().is_some());
let Refined::Done(Some(plain)) = r.refine_for(&now(&s, false), 0.0, Some(proofed.frame)) else { panic!("reused at once") };
assert!(plain.image.whole().is_some(), "the whole image without the stripes");
// From there on, edits are patches again.
s.execute("node.set", &json!({"id": rect, "width": 240})).unwrap();
let Refined::Done(Some(edited)) = r.refine_for(&now(&s, false), 0.0, Some(plain.frame)) else { panic!("a patch is done at once") };
assert!(matches!(&edited.image, Pixels::Patches(parts) if !parts.is_empty()));
}
fn until_late_preview_of(w: &mut Worker, seq: u64) -> Vec<(u64, bool)> {
let start = std::time::Instant::now();
let mut got = vec![];
@@ -825,3 +909,19 @@ fn a_zoom_in_after_a_late_preview_left_on_screen_is_measured_from_that_preview()
got.extend(until_idle(&mut w));
assert_eq!(got, [(3, true), (3, false)], "the 1x image is gone from the screen: the zoom in gets its late preview");
}
/// The canvas keeps a copy of its texture's pixels for the eyedropper. Patches put on the texture
/// go on that copy too: a colour picked where an edit redrew is the one shown, not the one before.
#[test]
fn the_colour_read_from_the_canvas_is_the_patched_one() {
let ctx = egui::Context::default();
let (red, blue) = (egui::Color32::from_rgb(255, 0, 0), egui::Color32::from_rgb(0, 0, 255));
let of = Some((1, NodeId(1)));
let mut canvas = CanvasState { tex_view: Some(view_at((20.0, 15.0), 1.0, 40, 30)), tex_of: of, ..Default::default() };
let under = |c: &CanvasState, x: f64, y: f64| c.pixel_under(figcraft_geom::Point::new(x, y), of, egui::Color32::WHITE);
let filter = egui::TextureOptions::NEAREST;
canvas.take_pixels(&ctx, Pixels::Whole(egui::ColorImage::filled([40, 30], red)), filter);
assert_eq!(under(&canvas, 12.5, 8.5), Some(red));
canvas.take_pixels(&ctx, Pixels::Patches(vec![([10, 5], egui::ColorImage::filled([6, 4], blue))]), filter);
assert_eq!((under(&canvas, 12.5, 8.5), under(&canvas, 9.5, 8.5), under(&canvas, 12.5, 9.5)), (Some(blue), Some(red), Some(red)));
}
+10 -1
View File
File diff suppressed because one or more lines are too long