diff --git a/crates/render/src/retained.rs b/crates/render/src/retained.rs index e8a711fc6..7e24f30fc 100644 --- a/crates/render/src/retained.rs +++ b/crates/render/src/retained.rs @@ -195,12 +195,28 @@ impl Steps { #[derive(Default)] pub struct Retained { last: Option, + /// See [`Self::patched`]. + patched: Option>, } 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, page: NodeId, view: &View, opts: &Options) -> Option { + 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); @@ -387,8 +405,18 @@ fn changed_areas(doc: &Document, page: NodeId, id: NodeId, out: &mut Vec) } /// 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, 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, + page: NodeId, + view: &View, + px: (i64, i64), + opts: &Options, + s: &Sensitive, +) -> Option<(Pixmap, u64, Option>)> { 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 { @@ -445,7 +473,7 @@ fn patch(last: Frame, doc: &Arc, page: NodeId, view: &View, px: (i64, } let mut damage: Vec = 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 = s.areas.iter().chain(last.sensitive.areas.iter()).filter_map(|r| to_px(*r, view.scale, px)).collect(); @@ -480,7 +508,10 @@ fn patch(last: Frame, doc: &Arc, 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 diff --git a/crates/render/src/retained_edit_tests.rs b/crates/render/src/retained_edit_tests.rs index 38c4c3013..71723a870 100644 --- a/crates/render/src/retained_edit_tests.rs +++ b/crates/render/src/retained_edit_tests.rs @@ -65,3 +65,43 @@ 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::(), 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"); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3d3f05082..0c21d5e8f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -59,6 +59,9 @@ pub struct CanvasState { pub tex_coarse: 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, /// 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). @@ -109,6 +112,7 @@ impl Default for CanvasState { tex_of: None, tex_coarse: false, tex_seq: 0, + tex_frame: None, kept: Vec::new(), surround: None, submitted: None, @@ -157,6 +161,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; 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); } @@ -319,6 +325,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) { @@ -332,10 +341,18 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { } else { egui::TextureOptions::LINEAR }; - match &mut app.canvas.texture { - Some(t) => t.set(done.image, filter), - None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)), + match (done.image, &mut app.canvas.texture) { + (render_worker::Pixels::Whole(image), Some(t)) => t.set(image, filter), + (render_worker::Pixels::Whole(image), None) => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", image, filter)), + // Patches of the image the texture holds (the worker was told which). + (render_worker::Pixels::Patches(parts), Some(t)) => { + for (at, image) in parts { + t.set_partial(at, image, filter); + } + } + (render_worker::Pixels::Patches(_), None) => {} } + app.canvas.tex_frame = (done.frame != 0 && !done.coarse).then_some(done.frame); let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0); if done.coarse { app.canvas.preview_latency_ms = latency; @@ -347,17 +364,19 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { app.canvas.tex_coarse = done.coarse; app.canvas.tex_seq = done.seq; } + // 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)); } } diff --git a/crates/ui-egui/src/canvas/render_worker.rs b/crates/ui-egui/src/canvas/render_worker.rs index c0fc8f312..54d4222d1 100644 --- a/crates/ui-egui/src/canvas/render_worker.rs +++ b/crates/ui-egui/src/canvas/render_worker.rs @@ -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, @@ -97,15 +121,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> { + 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); @@ -136,16 +184,25 @@ fn options(job: &Job) -> figcraft_render::Options { fn run(job: &Job, view: &View, retained: &mut Retained, coarse: bool) -> Option { 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, 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, at: job.at, seq: 0 } } /// The coarse image around the view is this many views wide and tall, centred on it. @@ -211,7 +268,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)); @@ -240,6 +297,9 @@ 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, + /// 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, } /// A full render drawn in steps and what it is of: a newer job of the same file, page, zoom, size @@ -298,7 +358,7 @@ impl Default for Renders { impl Renders { /// Previews when renders from scratch take at least `ms` (tests: 0, always). pub fn with_threshold(ms: f64) -> Self { - Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None } + Self { full: Retained::default(), preview: Retained::default(), last: None, full_ms: 0.0, preview_after_ms: ms, steps: None, frame: 0 } } /// Whether `job` is a render from scratch: the kept image is of another zoom, page or file, or @@ -332,9 +392,15 @@ impl Renders { preview_with(job, &mut self.preview) } + /// `d`, an image drawn in `full` just now, numbered. + fn numbered(&mut self, d: Done) -> Done { + self.frame += 1; + 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 { - let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)); + let done = guarded(&mut self.full, |r| run(job, &job.view, r, false)).map(|d| self.numbered(d)); if let Some(d) = &done { self.last = Some((job.uid, job.page, job.view.scale)); if d.work == Work::Full { @@ -346,7 +412,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) -> Refined { let t0 = Instant::now(); if let Some(s) = self.steps.as_ref() && !same_settings(&s.job, job) @@ -357,7 +426,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; } @@ -382,14 +451,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 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; @@ -402,18 +472,27 @@ 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) -> Option { + fn begin(&mut self, job: &Job, t0: Instant, mut drawn: Option, holds: Option) -> Option { // 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. + let held = holds.is_some_and(|f| f == self.frame); + 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. @@ -421,7 +500,11 @@ impl Renders { self.steps = Some(Stepping { job: job.clone(), fonts: figcraft_text::layout_generation(), steps, spent: 0.0 }); drawn.map(Refined::Shown) } - 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) } else { d }); + Some(Refined::Done(self.finished(job, d))) + } Err(_) => { self.full.clear(); Some(Refined::Done(None)) @@ -687,6 +770,8 @@ pub struct Inline { /// The wait for the pending job's preview. wait: std::time::Duration, renders: Renders, + /// See [`Self::texture_holds`]. + holds: Option, } #[cfg(target_arch = "wasm32")] @@ -708,6 +793,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). @@ -731,6 +817,12 @@ impl Inline { pub fn surround(&mut self) -> Option { 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) { + self.holds = frame; + } pub fn poll(&mut self) -> Option { self.poll_at(Instant::now()) } @@ -755,7 +847,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)) diff --git a/crates/ui-egui/src/canvas/zoom_preview_tests.rs b/crates/ui-egui/src/canvas/zoom_preview_tests.rs index af9914b74..6bb032bd5 100644 --- a/crates/ui-egui/src/canvas/zoom_preview_tests.rs +++ b/crates/ui-egui/src/canvas/zoom_preview_tests.rs @@ -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, 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 = 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 { /// 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, 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, @@ -618,7 +624,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] @@ -628,14 +634,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); } @@ -649,7 +655,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); @@ -663,11 +669,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); @@ -709,7 +715,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"); @@ -726,6 +732,62 @@ 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"); +} diff --git a/docs/gaps.md b/docs/gaps.md index b45e62e81..be7adb84a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where FigCraft falls short of Figma -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-24 · **Change:** minor (gap 7: the browser uploads only what an edit changed of the canvas image; gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`, #2237); gap 10: library analytics count insertions and detachments of styles and variables; gap 6: the browser build uses team libraries and plugin directories on a server; gap 7: a pan past the canvas image shows a coarse image of the area around the view on the desktop, not the bare page colour; gap 7: the strips a pan uncovers render in parallel bands; gap 7: the desktop refines a zoom's preview once the zoom has paused; gap 1: the `.fig` export writes vector region paints (#2302); gap 13: a boolean group's corner radius (#2222); gap 24: mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); gap 10: library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; gap 6: widgets draw lines and SVG pictures (plugin API 6); gap 7: text reads only the fallback fonts it draws with; a board connector's path can be reshaped by dragging its path handles (#1710); gap 10: library analytics count insertions and show insertions and detachments over time; gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; gap 14: a collection of this file extends, following its edits at once; colour picker review fixes for text undo, fitted sidebars, moving controls and gradient variables; gap 6: plugin widgets have hover styles; gap 7: the browser draws a zoom's full render a band at a time; `.fig` import keeps the file's saved line breaks while the text and its box are unedited (#1236); FigJam outer shape outlines and sticky body fallback beside author text (#1341, #1397); Arabic draft catalog; gap 7: the browser refines a zoom's preview once the zoom has paused; gap 17: branches in live sessions, branch history entries, the list-merge rows brought up to date; gap 6: plugin widgets take text input and a property menu (plugin API 4); gap 24: board templates and tables; gap 24: a shared timer and voting sessions; gap 24: the board dot grid, connector ends dragged to re-attach, curved connectors; egui/eframe 0.37 verified for gap 18; known gaps from the #1311 review in gaps 4, 14, 15 and 16; gap 16: measurements kept on the canvas, a read-only layers panel in Dev Mode; gap 24: boards and their tail; Dev Mode tail: import lines in layer trees, compare with versions, an inspect-only canvas; gap 5: reviewed Turkish, Czech and Indonesian drafts, the Japanese draft completed; reviewed Russian catalog and integer plurals; `.fig` export: instance sizes, variables with modes, shared styles, variable-width strokes; sharing with a join code; text box sizes measured against documents re-saved by other software; live sessions per document; .fig export checked by opening written files in other software; experimental .fig export; keyboard shortcut parity suite and bindings; Simplified Chinese draft catalog; Latin American Spanish overlay; prototyping tail: gamepad triggers, widgets in prototypes, mode lookups; plugin directory on figcraft-server; Japanese and Korean draft catalogs and CJK UI fonts; plugin widgets and the plugin panel tail; French, German and Brazilian Portuguese draft catalogs; cursor chat and spotlight in live sessions; layers and assets panels behaviour suite and fixes; vector multi-edit and edit tail; dev resources links; extended collections tail; branch version history and finer list merges; comments and version history behaviour suite and fixes; canvas navigation, guides and grids behaviour suite and fixes; `.fig` import: editable vector networks, more layer kinds, variable prototype actions; `.fig` import, best effort: gap 1 down to its tail; Windows QA pass: everyday workflows on Windows 11, eight fixes incl. unsaved work kept after a crash or a forced quit; Display P3: gamut warning and soft-proof (true P3 blocked upstream); several windows; localization layer with a draft Spanish catalog; hosting figcraft-server: wss in the desktop app, server releases, deployment guide; plugin panels and settings; canvas fixes: boolean hit testing on the result, group drags, frame outlines and slices; code connect; stretch and scatter brushes, pen pressure; text on a path and pattern fills; team libraries on the server and swap library; branches: create, update from main, review and merge; animated GIF fills and TIFF images; Open recent, outlines for the selection and mask outlines: menu breadth 100%; extended collections, variables import/export, gradient stop and variant bindings: gap 14 down to its tail; the 2026-10-17 landings: `.fig` import fidelity, budgets for large files, the import report, a `.fig` copy from Save as and paste from another design app (gap 1); menus, the Actions palette, editor fixes, Selection colors and smart-selection spacing (gap 4); catalog counts re-measured (gap 5); bounded canvas pan overscan) · **Target:** Figma Design (desktop app 126.10.7) Every known shortfall against Figma, one entry each, ranked by how much it stops a Figma user from doing real work in FigCraft. Agents: pick work from the top unless the owner says otherwise. The @@ -287,6 +287,14 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe sixteenth of the pixels first, then refined. With no measure to go by (the first render, another page, a zoom after quick renders), a watchdog thread previews any such render still running after 12 ms (desktop only; the browser renders inline). +- **Landed (2026-11-24):** the browser's canvas uploads only what an edit changed of its image. + Every finished render was converted to a texture image and uploaded whole: after an edit that + redrew a part of the view, all of the view and its margin again, every frame of a drag (37 MB + for a 4112 × 2292 view). The retained renderer says where a patched image differs from the one + before (`Retained::patched`; nothing after a full render or a pan, which moves every pixel), + the browser's worker numbers its images and is told which one the canvas's texture holds, and + a render that only patches that image hands over the patches, put on the texture in place. The + desktop's render thread hands over whole images, as before. - **Landed (2026-10-29):** the browser draws a zoom's full render a band at a time (`Retained::begin`, `Steps`; at least a band a frame and at most eight bands, so a frame draws a part of the render where it drew the whole of it: 0.7–1.4 s where the render took 3.7–4.0 s in the measurement of @@ -615,6 +623,7 @@ No alpha blockers: the alpha gate in [`roadmap.md`](roadmap.md#alpha-gate) passe | Date | Change | Summary | |---|---|---| +| 2026-11-24 | minor | Gap 7: after an edit the browser converts and uploads only the redrawn areas of the canvas image to its texture, not all of it. Numbers unchanged | | 2026-11-19 | minor | Gap 24: code blocks, first step (`board.codeBlock`, `board.setLanguage`; a block is as tall as its lines and keeps its text plain code, #2237); the toolbar entry, language menu, highlighting, line numbers and `.jam` import are missing. | | 2026-11-18 | minor | Gap 10: library analytics count insertions and detachments of styles and variables; modes stay on the missing list. | | 2026-11-18 | minor | Gap 6: the plugin directory works in the browser build, so that item leaves the missing list; what's installed there lasts as long as the page. Team libraries on a server work there too. |