diff --git a/.github/assets/demo-organize.mp4 b/.github/assets/demo-organize.mp4 deleted file mode 100644 index bac8a5d0..00000000 Binary files a/.github/assets/demo-organize.mp4 and /dev/null differ diff --git a/.github/assets/demo-organize.webp b/.github/assets/demo-organize.webp deleted file mode 100644 index fcbe2779..00000000 Binary files a/.github/assets/demo-organize.webp and /dev/null differ diff --git a/.github/assets/demo-switch.mp4 b/.github/assets/demo-switch.mp4 index b0bc6212..0ee4f72e 100644 Binary files a/.github/assets/demo-switch.mp4 and b/.github/assets/demo-switch.mp4 differ diff --git a/.github/assets/demo-switch.webp b/.github/assets/demo-switch.webp index 64b8ac09..9d2aaf29 100644 Binary files a/.github/assets/demo-switch.webp and b/.github/assets/demo-switch.webp differ diff --git a/.github/assets/demo-themes.mp4 b/.github/assets/demo-themes.mp4 deleted file mode 100644 index 07b71adb..00000000 Binary files a/.github/assets/demo-themes.mp4 and /dev/null differ diff --git a/.github/assets/demo-themes.webp b/.github/assets/demo-themes.webp deleted file mode 100644 index 80323e96..00000000 Binary files a/.github/assets/demo-themes.webp and /dev/null differ diff --git a/crates/accshift-egui/parity/README.md b/crates/accshift-egui/parity/README.md index ce49a663..ae8c7967 100644 --- a/crates/accshift-egui/parity/README.md +++ b/crates/accshift-egui/parity/README.md @@ -5,6 +5,7 @@ Every screen of the egui app was compared, pixel by pixel, with the same screen - `scenes/*.json`, the scenes, played by the egui runner for regression shots; - `data/*.json`, the mock data the scenes run on, and `avatars/`, the mock avatars it points to; - `fragments/*.html`, the static CSS boxes of the `primitives-*` scenes; +- `recordings/*.json`, scenes with `"record"` that film the README clips frame by frame, kept out of `scenes/` so the regression run and its diff skip them; - `diff.mjs`, the pixel diff of two shot folders (Node 22+ and ffmpeg on `PATH`); - the rules below, measured on WebView2, which the egui painter follows. diff --git a/crates/accshift-egui/parity/recordings/readme-switch.json b/crates/accshift-egui/parity/recordings/readme-switch.json new file mode 100644 index 00000000..4d3344f2 --- /dev/null +++ b/crates/accshift-egui/parity/recordings/readme-switch.json @@ -0,0 +1,97 @@ +{ + "id": "readme-switch", + "scenario": "demo", + "os": "windows", + "viewport": {"width": 860, "height": 440, "scale": 1.5}, + "theme": "glass-dark", + "locale": "en", + "record": 30, + "steps": [ + {"move": [600, 340]}, + {"cursor": true}, + {"wait": 250}, + {"glide": [755, 298], "ms": 650}, + {"wait": 150}, + {"glide": [535, 152], "ms": 500}, + {"wait": 100}, + {"glide": [315, 152], "ms": 450}, + {"wait": 60}, + {"click": [315, 152]}, + {"wait": 550}, + {"shot": "armed"}, + {"click": [315, 152]}, + {"wait": 450}, + {"shot": "switching"}, + {"wait": 1100}, + {"shot": "switched"}, + {"glide": [639, 60], "ms": 600}, + {"wait": 60}, + {"click": [639, 60]}, + {"wait": 150}, + {"text": "r"}, + {"wait": 170}, + {"text": "a"}, + {"wait": 170}, + {"wait": 900}, + {"shot": "search"}, + {"key": "Backspace"}, + {"wait": 110}, + {"key": "Backspace"}, + {"wait": 450}, + {"glide": [95, 152], "ms": 650}, + {"wait": 60}, + {"click": [95, 152]}, + {"wait": 1100}, + {"shot": "folder"}, + {"glide": [35, 60], "ms": 500}, + {"wait": 60}, + {"click": [35, 60]}, + {"wait": 800}, + {"glide": [481, 18], "ms": 650}, + {"wait": 60}, + {"click": [481, 18]}, + {"wait": 700}, + {"shot": "roblox"}, + {"glide": [95, 152], "ms": 450}, + {"wait": 350}, + {"glide": [315, 152], "ms": 380}, + {"wait": 450}, + {"glide": [413, 18], "ms": 500}, + {"wait": 60}, + {"click": [413, 18]}, + {"wait": 800}, + {"glide": [816, 60], "ms": 600}, + {"wait": 60}, + {"click": [816, 60]}, + {"wait": 900}, + {"shot": "list"}, + {"glide": [300, 252], "ms": 500}, + {"wait": 60}, + {"click": [300, 252]}, + {"wait": 1300}, + {"shot": "list-selected"}, + {"glide": [790, 60], "ms": 550}, + {"wait": 60}, + {"click": [790, 60]}, + {"wait": 900}, + {"shot": "grid"}, + {"cursor": false}, + {"wait": 250}, + {"key": "Ctrl+K"}, + {"wait": 500}, + {"shot": "palette"}, + {"text": "m"}, + {"wait": 130}, + {"text": "a"}, + {"wait": 130}, + {"text": "i"}, + {"wait": 130}, + {"text": "n"}, + {"wait": 130}, + {"wait": 600}, + {"shot": "palette-typed"}, + {"key": "Enter"}, + {"wait": 1700}, + {"shot": "end"} + ] +} diff --git a/crates/accshift-egui/src/harness/mod.rs b/crates/accshift-egui/src/harness/mod.rs index b439610c..4fdf29ca 100644 --- a/crates/accshift-egui/src/harness/mod.rs +++ b/crates/accshift-egui/src/harness/mod.rs @@ -8,7 +8,9 @@ //! and scale, builds its screen, waits until the screen is ready (every //! avatar uploaded), then injects its steps as egui raw input on the wall //! clock, like the reference runner does over CDP. A `shot` reads back the -//! frame the renderer presented and writes `//.png`. +//! frame the renderer presented and writes `//.png`. A scene +//! with `record` writes every frame instead, on a clock of its own +//! (`record.rs`), for the README clips. //! //! Failures (a scene the egui side cannot render yet, a shot of the wrong //! size, a write error) are printed and counted; the process exits non-zero @@ -16,6 +18,8 @@ use std::path::PathBuf; +#[cfg(any(test, feature = "harness"))] +mod record; #[cfg(any(test, feature = "harness"))] mod scenes; #[cfg(any(test, feature = "harness"))] diff --git a/crates/accshift-egui/src/harness/record.rs b/crates/accshift-egui/src/harness/record.rs new file mode 100644 index 00000000..39139a6f --- /dev/null +++ b/crates/accshift-egui/src/harness/record.rs @@ -0,0 +1,395 @@ +//! Frame recording for a scene with `record` (frames per second): every +//! frame of the run is written as `//frame-00000.png`, on a clock +//! of its own so the frames sit exactly `1 / fps` apart whatever the machine +//! does. The README clips are assembled from them. +//! +//! egui's time is the recording's: frame `n` runs at `n / fps`, and the +//! scene's waits count on that clock. A frame is only taken once the wall +//! clock has reached it, so the app's own timers (toasts, debounces) keep in +//! step as long as the machine keeps up. The PNGs are encoded on worker +//! threads. +//! +//! Headless captures draw no pointer: a recording draws one where the scene +//! put it (shown and hidden by `cursor` steps), with a ring that fades out +//! around each press. + +use std::path::PathBuf; +use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; + +use egui::{Color32, ColorImage, Pos2}; + +/// How long the pointer takes to fade in or out, in seconds. +const CURSOR_FADE: f64 = 0.25; +/// How long a press ring takes to grow and fade, in seconds. +const RING_LIFE: f64 = 0.45; +/// Worker threads encoding PNGs. +const WRITERS: usize = 3; + +/// The pointer and press rings drawn over one frame. +#[derive(Clone, Debug, Default)] +pub struct Overlay { + /// Where the pointer is, in viewport points, and its opacity. + pub cursor: Option<(Pos2, f32)>, + /// Each live ring: its centre in viewport points and its progress, 0 to 1. + pub rings: Vec<(Pos2, f32)>, +} + +struct Job { + path: PathBuf, + image: Arc, + overlay: Overlay, + scale: f32, + /// Further names the same frame is written under (`shot` steps). + copies: Vec, +} + +/// The recording state of the running scene. +pub struct Recorder { + pub fps: f64, + /// The next frame to take. + pub frame: u64, + /// Runner clock (seconds) when the recording started. + pub start_wall: f64, + /// egui time when the recording started. + pub base_time: f64, + /// The egui time handed out last, so it never goes back. + pub last_time: f64, + pointer: Option, + /// Whether the pointer shows, and since when (recording time). + cursor: (bool, f64), + /// Press positions and their recording time. + rings: Vec<(Pos2, f64)>, + /// `shot` names asked for since the last frame. + pub shots: Vec, + tx: Option>, + workers: Vec>, + errors: Arc>>, +} + +impl Recorder { + pub fn new(fps: f64, start_wall: f64, base_time: f64) -> Self { + let (tx, rx) = sync_channel::(WRITERS * 8); + let rx = Arc::new(Mutex::new(rx)); + let errors = Arc::new(Mutex::new(Vec::new())); + let workers = (0..WRITERS) + .map(|_| { + let (rx, errors) = (Arc::clone(&rx), Arc::clone(&errors)); + std::thread::spawn(move || write_loop(&rx, &errors)) + }) + .collect(); + Self { + fps, + frame: 0, + start_wall, + base_time, + last_time: base_time, + pointer: None, + cursor: (false, f64::NEG_INFINITY), + rings: Vec::new(), + shots: Vec::new(), + tx: Some(tx), + workers, + errors, + } + } + + /// Recording time of the next frame. + pub fn frame_time(&self) -> f64 { + self.frame as f64 / self.fps + } + + pub fn pointer_to(&mut self, p: Pos2) { + self.pointer = Some(p); + } + + pub fn press(&mut self, p: Pos2, at: f64) { + self.pointer = Some(p); + self.rings.push((p, at)); + } + + pub fn show_cursor(&mut self, on: bool, at: f64) { + if self.cursor.0 != on { + self.cursor = (on, at); + } + } + + /// What to draw over the frame taken at `at`. + pub fn overlay(&mut self, at: f64) -> Overlay { + self.rings.retain(|(_, t)| at - t < RING_LIFE); + let (on, since) = self.cursor; + let fade = ((at - since) / CURSOR_FADE).clamp(0.0, 1.0) as f32; + let alpha = if on { fade } else { 1.0 - fade }; + Overlay { + cursor: self + .pointer + .filter(|_| alpha > 0.0) + .map(|p| (p, ease(alpha))), + rings: self + .rings + .iter() + .map(|&(p, t)| (p, ((at - t) / RING_LIFE) as f32)) + .collect(), + } + } + + /// Queue a frame for writing; blocks while the writers are behind. + pub fn write( + &self, + path: PathBuf, + image: Arc, + overlay: Overlay, + scale: f32, + copies: Vec, + ) { + if let Some(tx) = &self.tx { + let _ = tx.send(Job { + path, + image, + overlay, + scale, + copies, + }); + } + } + + /// Wait for every queued frame; the write errors, if any. + pub fn finish(mut self) -> Vec { + self.tx = None; + for worker in self.workers.drain(..) { + let _ = worker.join(); + } + std::mem::take(&mut *self.errors.lock().unwrap_or_else(|e| e.into_inner())) + } +} + +fn write_loop(rx: &Mutex>, errors: &Mutex>) { + loop { + let job = { + let rx = rx.lock().unwrap_or_else(|e| e.into_inner()); + rx.recv() + }; + let Ok(job) = job else { return }; + let mut image = Arc::unwrap_or_clone(job.image); + draw_overlay(&mut image, &job.overlay, job.scale); + let mut written = crate::bench::write_png(&job.path, &image); + for copy in &job.copies { + if written.is_ok() { + written = std::fs::copy(&job.path, copy) + .map(|_| ()) + .map_err(|e| e.to_string()); + } + } + if let Err(e) = written { + errors + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(format!("{}: {e}", job.path.display())); + } + } +} + +/// CSS `ease-out`-like curve for fades and the ring. +fn ease(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + 1.0 - (1.0 - t) * (1.0 - t) +} + +/// The pointer arrow, in the units of a 24-unit icon drawn 22 points wide, +/// its tip at (5, 2.5). +const ARROW: [(f32, f32); 7] = [ + (5.0, 2.5), + (5.0, 19.0), + (9.2, 15.1), + (11.8, 21.0), + (14.6, 19.7), + (12.0, 14.0), + (18.0, 13.8), +]; +const ARROW_UNIT: f32 = 22.0 / 24.0; +const ARROW_STROKE: f32 = 1.1; + +/// Draws the press rings, then the pointer with its drop shadow, over the +/// premultiplied frame. Positions are viewport points, `scale` pixels per +/// point. +pub fn draw_overlay(image: &mut ColorImage, overlay: &Overlay, scale: f32) { + for &(centre, progress) in &overlay.rings { + draw_ring(image, centre, progress, scale); + } + if let Some((tip, alpha)) = overlay.cursor { + draw_arrow(image, tip, alpha, scale); + } +} + +fn blend(image: &mut ColorImage, x: usize, y: usize, rgb: [f32; 3], alpha: f32) { + if alpha <= 0.0 { + return; + } + let [w, _] = image.size; + let px = &mut image.pixels[y * w + x]; + let a = alpha.min(1.0); + let mix = |src: f32, dst: u8| (src * 255.0 * a + f32::from(dst) * (1.0 - a)).round() as u8; + *px = Color32::from_rgba_premultiplied( + mix(rgb[0], px.r()), + mix(rgb[1], px.g()), + mix(rgb[2], px.b()), + mix(1.0, px.a()), + ); +} + +/// The 30-point ring of a press: grows from 0.4 to 1.4 times its size while +/// its 0.9 opacity goes to zero, 2 points thick at full size. +fn draw_ring(image: &mut ColorImage, centre: Pos2, progress: f32, scale: f32) { + let p = ease(progress); + let grow = 0.4 + p; + let opacity = 0.9 * (1.0 - p) * 0.85; + let outer = 15.0 * grow * scale; + let width = 2.0 * grow * scale; + let mid = outer - width / 2.0; + let (cx, cy) = (centre.x * scale, centre.y * scale); + let [w, h] = image.size; + let x0 = (cx - outer - 2.0).floor().max(0.0) as usize; + let y0 = (cy - outer - 2.0).floor().max(0.0) as usize; + let x1 = ((cx + outer + 2.0).ceil() as usize).min(w); + let y1 = ((cy + outer + 2.0).ceil() as usize).min(h); + for y in y0..y1 { + for x in x0..x1 { + let d = ((x as f32 + 0.5 - cx).hypot(y as f32 + 0.5 - cy) - mid).abs(); + let cover = (width / 2.0 + 0.5 - d).clamp(0.0, 1.0); + blend(image, x, y, [1.0; 3], cover * opacity); + } + } +} + +/// Signed distance from `p` to the arrow outline (negative inside), in the +/// arrow's units. +fn arrow_distance(px: f32, py: f32) -> f32 { + let mut inside = false; + let mut best = f32::INFINITY; + for i in 0..ARROW.len() { + let (ax, ay) = ARROW[i]; + let (bx, by) = ARROW[(i + 1) % ARROW.len()]; + if (ay > py) != (by > py) && px < (bx - ax) * (py - ay) / (by - ay) + ax { + inside = !inside; + } + let (dx, dy) = (bx - ax, by - ay); + let t = (((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + best = best.min((px - ax - t * dx).hypot(py - ay - t * dy)); + } + if inside { + -best + } else { + best + } +} + +/// `erfc(x) / 2`, the share of a Gaussian beyond `x` standard deviations +/// times `sqrt(2)`. +fn half_erfc(x: f32) -> f32 { + // Abramowitz and Stegun 7.1.26. + let z = x.abs(); + let t = 1.0 / (1.0 + 0.327_591_1 * z); + let poly = t + * (0.254_829_6 + + t * (-0.284_496_7 + t * (1.421_413_7 + t * (-1.453_152 + t * 1.061_405_4)))); + let erfc = poly * (-z * z).exp(); + if x >= 0.0 { + erfc / 2.0 + } else { + 1.0 - erfc / 2.0 + } +} + +/// The white arrow with a dark outline and a soft shadow (0 2px 3px at 55 %), +/// tip at `tip`. +fn draw_arrow(image: &mut ColorImage, tip: Pos2, alpha: f32, scale: f32) { + // Device pixels per arrow unit, and the arrow's origin in device pixels. + let k = ARROW_UNIT * scale; + let (ox, oy) = (tip.x * scale - 5.0 * k, tip.y * scale - 2.5 * k); + let [w, h] = image.size; + let pad = 8.0 * scale; + let x0 = (ox + 5.0 * k - pad).floor().max(0.0) as usize; + let y0 = (oy + 2.5 * k - pad).floor().max(0.0) as usize; + let x1 = ((ox + 18.0 * k + pad).ceil().max(0.0) as usize).min(w); + let y1 = ((oy + 21.0 * k + pad).ceil().max(0.0) as usize).min(h); + let half = ARROW_STROKE / 2.0; + let sigma = 3.0 * scale / k / 2.0; + let shadow_dy = 2.0 * scale / k; + const N: usize = 4; + for y in y0..y1 { + for x in x0..x1 { + // Shadow: the outlined shape, shifted down and blurred. + let (ux, uy) = ((x as f32 + 0.5 - ox) / k, (y as f32 + 0.5 - oy) / k); + let d = arrow_distance(ux, uy - shadow_dy) - half; + let shadow = 0.55 * half_erfc(d / (sigma * std::f32::consts::SQRT_2)); + blend(image, x, y, [0.0; 3], shadow * alpha); + // The arrow, 4x4 samples a pixel. + let (mut white, mut dark) = (0.0f32, 0.0f32); + for sy in 0..N { + for sx in 0..N { + let ux = (x as f32 + (sx as f32 + 0.5) / N as f32 - ox) / k; + let uy = (y as f32 + (sy as f32 + 0.5) / N as f32 - oy) / k; + let d = arrow_distance(ux, uy); + if d.abs() <= half { + dark += 1.0; + } else if d < 0.0 { + white += 1.0; + } + } + } + let n = (N * N) as f32; + let cover = (white + dark) / n; + if cover > 0.0 { + let lum = white / (white + dark) + (dark / (white + dark)) * (0x11 as f32 / 255.0); + blend(image, x, y, [lum; 3], cover * alpha); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn blank() -> ColorImage { + ColorImage::new([90, 90], vec![Color32::from_rgb(20, 20, 30); 90 * 90]) + } + + #[test] + fn the_cursor_is_white_inside_and_dark_on_its_edge() { + let mut image = blank(); + let overlay = Overlay { + cursor: Some((egui::pos2(20.0, 20.0), 1.0)), + rings: Vec::new(), + }; + draw_overlay(&mut image, &overlay, 1.5); + // Inside the arrow, a little below and right of the tip. + let inside = image.pixels[(20.0 * 1.5 + 12.0) as usize * 90 + (20.0 * 1.5 + 4.0) as usize]; + assert!(inside.r() > 230, "{inside:?}"); + // Left of the tip: untouched but for a faint shadow. + let left = image.pixels[30 * 90 + 20]; + assert!(left.r() <= 20, "{left:?}"); + } + + #[test] + fn a_hidden_cursor_draws_nothing_once_faded() { + let mut rec = Recorder::new(30.0, 0.0, 0.0); + rec.pointer_to(egui::pos2(10.0, 10.0)); + rec.show_cursor(true, 0.0); + assert!(rec.overlay(1.0).cursor.is_some()); + rec.show_cursor(false, 1.0); + assert!(rec.overlay(1.1).cursor.is_some()); + assert!(rec.overlay(1.0 + CURSOR_FADE).cursor.is_none()); + assert!(rec.finish().is_empty()); + } + + #[test] + fn a_ring_lives_its_life_then_goes() { + let mut rec = Recorder::new(30.0, 0.0, 0.0); + rec.press(egui::pos2(10.0, 10.0), 0.0); + assert_eq!(rec.overlay(0.2).rings.len(), 1); + assert!(rec.overlay(RING_LIFE).rings.is_empty()); + let _ = rec.finish(); + } +} diff --git a/crates/accshift-egui/src/harness/scenes.rs b/crates/accshift-egui/src/harness/scenes.rs index 004597ce..347fc9a6 100644 --- a/crates/accshift-egui/src/harness/scenes.rs +++ b/crates/accshift-egui/src/harness/scenes.rs @@ -6,6 +6,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Instant; +use super::record::{Overlay, Recorder}; use crate::app::{AppModel, MockSetup}; use crate::screens::primitives::Primitives; use crate::screens::Screen; @@ -61,6 +62,11 @@ pub enum Step { Shot(String), /// An `accshift://` URL delivered as a second launch would deliver it. DeepLink(String), + /// The pointer travels to a point over a time (seconds), eased, about + /// 60 moves a second. + Glide(Pos2, f64), + /// A recording shows or hides its drawn pointer; nothing otherwise. + Cursor(bool), } #[derive(Clone, Debug)] @@ -94,6 +100,8 @@ pub struct Scene { pub update: Option, /// The `html` fragment (resolved next to the scene file) and its text. pub html: Option<(PathBuf, String)>, + /// `record`: frames per second of a recording of the whole run. + pub record: Option, pub steps: Vec, } @@ -162,6 +170,16 @@ fn parse_step(v: &serde_json::Value) -> Result { if let Some(u) = o.get("deeplink") { return Ok(Step::DeepLink(u.as_str().ok_or_else(bad)?.to_owned())); } + if let Some(p) = o.get("glide") { + let ms = o + .get("ms") + .and_then(serde_json::Value::as_f64) + .unwrap_or(500.0); + return Ok(Step::Glide(point(p).ok_or_else(bad)?, ms / 1000.0)); + } + if let Some(on) = o.get("cursor") { + return Ok(Step::Cursor(on.as_bool().ok_or_else(bad)?)); + } // A step only the old reference side acted on: a no-op here. if o.contains_key("dom") { return Ok(Step::Wait(0.0)); @@ -242,6 +260,10 @@ pub fn load(path: &Path) -> Result { clipboard: s("clipboard").unwrap_or_default(), update: s("update"), html, + record: v + .get("record") + .and_then(serde_json::Value::as_f64) + .filter(|fps| *fps > 0.0), steps, }) } @@ -364,6 +386,7 @@ enum Op { Event(Event), Shot(String), DeepLink(String), + Cursor(bool), } fn expand(steps: &[Step]) -> Result, String> { @@ -446,6 +469,23 @@ fn expand(steps: &[Step]) -> Result, String> { } Step::Shot(name) => ops.push_back(Op::Shot(name.clone())), Step::DeepLink(url) => ops.push_back(Op::DeepLink(url.clone())), + Step::Glide(to, secs) => { + let from = pointer; + let n = (secs * 60.0).ceil().max(1.0) as usize; + for i in 1..=n { + let t = i as f32 / n as f32; + // Eased in and out, like a hand. + let e = if t < 0.5 { + 2.0 * t * t + } else { + 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0 + }; + ops.push_back(Op::Event(Event::PointerMoved(from + (*to - from) * e))); + ops.push_back(Op::Wait(secs / n as f64)); + } + pointer = *to; + } + Step::Cursor(on) => ops.push_back(Op::Cursor(*on)), } } Ok(ops) @@ -481,6 +521,14 @@ pub struct SceneRun { build: Option, /// `deeplink` URLs for the app, taken by the shell. links: Vec, + /// The recording of a `record` scene, once it runs. + record: Option, + /// The recorded frame whose screenshot is on its way: its index and + /// what to draw over it. + pending_frame: Option<(u64, Overlay)>, + /// The steps ran out on the frame in flight: the recording ends once + /// its screenshot is in. + record_ending: bool, } impl SceneRun { @@ -497,6 +545,9 @@ impl SceneRun { shot: Arc::default(), build: None, links: Vec::new(), + record: None, + pending_frame: None, + record_ending: false, } } @@ -525,11 +576,27 @@ impl SceneRun { if let Some(scene) = self.scenes.get(self.index) { fail(format!("{}: {why}", scene.id)); } + self.end_recording(); self.index += 1; self.phase = Phase::Next; self.ops.clear(); } + /// Wait for the recording's frames to be written, and report. + fn end_recording(&mut self) { + self.pending_frame = None; + let Some(rec) = self.record.take() else { + return; + }; + let (frames, fps) = (rec.frame, rec.fps); + let errors = rec.finish(); + let id = self.scenes.get(self.index).map_or("", |s| s.id.as_str()); + for e in errors { + fail(format!("{id}: {e}")); + } + println!("{id}: recorded {frames} frames at {fps} fps"); + } + /// Inject this frame's events. `ready` is the current screen's own /// readiness (avatars uploaded); nothing runs before it. pub fn feed(&mut self, ctx: &egui::Context, raw: &mut RawInput, ready: bool) { @@ -623,8 +690,16 @@ impl SceneRun { } self.phase = Phase::Running; self.wake_at = now; - self.run_ops(ctx, raw, now); + if let Some(fps) = self.scenes.get(self.index).and_then(|s| s.record) { + let base = raw.time.unwrap_or_else(|| ctx.input(|i| i.time)); + self.record = Some(Recorder::new(fps, now, base)); + self.wake_at = 0.0; + self.record_frame(ctx, raw, now); + } else { + self.run_ops(ctx, raw, now); + } } + Phase::Running if self.record.is_some() => self.record_frame(ctx, raw, now), Phase::Running => self.run_ops(ctx, raw, now), } if let Some(scene) = self.scenes.get(self.index) { @@ -632,6 +707,91 @@ impl SceneRun { } } + /// One frame of a recording: the last frame queued for writing, then, + /// once the wall clock reaches the next one, its time handed to egui, + /// the steps due by then run, and its screenshot asked for. + fn record_frame(&mut self, ctx: &egui::Context, raw: &mut RawInput, wall: f64) { + self.collect_frame(); + if self.record_ending && self.pending_frame.is_none() { + self.record_ending = false; + self.end_recording(); + self.index += 1; + self.phase = Phase::Next; + return; + } + let Some(rec) = &mut self.record else { return }; + let due = rec.start_wall + rec.frame_time(); + if self.pending_frame.is_some() || wall < due { + raw.time = Some(rec.last_time); + if self.pending_frame.is_none() { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(due - wall)); + } + return; + } + let at = rec.frame_time(); + rec.last_time = rec.base_time + at; + raw.time = Some(rec.last_time); + raw.predicted_dt = (1.0 / rec.fps) as f32; + let index = self.index; + self.run_ops(ctx, raw, at); + if self.index != index { + // The steps ran out, the last one on this frame: take it, then + // end the recording once its screenshot is in. + self.index = index; + self.phase = Phase::Running; + self.record_ending = true; + } + let Some(rec) = &mut self.record else { return }; + self.pending_frame = Some((rec.frame, rec.overlay(at))); + rec.frame += 1; + let (slot, ctx2) = (Arc::clone(&self.shot), ctx.clone()); + ctx.send_viewport_cmd(ViewportCommand::Screenshot(egui::ScreenshotCallback::new( + move |image| { + *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(image); + ctx2.request_repaint(); + }, + ))); + } + + /// Queue the recorded frame whose screenshot arrived, if any. + fn collect_frame(&mut self) { + if self.pending_frame.is_none() { + return; + } + let image = self.shot.lock().unwrap_or_else(|e| e.into_inner()).take(); + let Some(image) = image else { return }; + let Some((frame, overlay)) = self.pending_frame.take() else { + return; + }; + let (Some(scene), Some(rec)) = (self.scenes.get(self.index), &mut self.record) else { + return; + }; + let want = scene.viewport.pixels(); + if image.size != want { + fail(format!( + "{}/frame {frame}: {}x{}, expected {}x{}", + scene.id, image.size[0], image.size[1], want[0], want[1] + )); + } + let dir = self.out.join(&scene.id); + if frame == 0 { + if let Err(e) = std::fs::create_dir_all(&dir) { + fail(format!("{}: {e}", dir.display())); + } + } + let copies = std::mem::take(&mut rec.shots) + .into_iter() + .map(|name| dir.join(format!("{name}.png"))) + .collect(); + rec.write( + dir.join(format!("frame-{frame:05}.png")), + image, + overlay, + scene.viewport.scale, + copies, + ); + } + fn run_ops(&mut self, ctx: &egui::Context, raw: &mut RawInput, now: f64) { if self.pending_shot.is_some() { return; @@ -644,8 +804,18 @@ impl SceneRun { }; match op { Op::Wait(secs) => { - self.wake_at = now + secs; - return; + // A recording keeps its waits on schedule: its frames + // are whole steps of its clock, and a wait counted from + // the frame would stretch every glide. + if self.record.is_some() { + self.wake_at += secs; + if self.wake_at > now { + return; + } + } else { + self.wake_at = now + secs; + return; + } } Op::Event(e) => { let is_press = matches!(e, Event::PointerButton { pressed: true, .. }); @@ -672,11 +842,33 @@ impl SceneRun { }, e => e, }; + if let Some(rec) = &mut self.record { + match &e { + Event::PointerMoved(p) => rec.pointer_to((p.to_vec2() / k).to_pos2()), + Event::PointerButton { + pos, pressed: true, .. + } => rec.press((pos.to_vec2() / k).to_pos2(), now), + _ => {} + } + } raw.events.push(e); if is_press { return; } } + Op::Shot(name) if self.record.is_some() => { + // This frame is the shot: what follows waits for the + // next one. + if let Some(rec) = &mut self.record { + rec.shots.push(name); + } + return; + } + Op::Cursor(on) => { + if let Some(rec) = &mut self.record { + rec.show_cursor(on, now); + } + } Op::Shot(name) => { let (slot, ctx2) = (Arc::clone(&self.shot), ctx.clone()); ctx.send_viewport_cmd(ViewportCommand::Screenshot( @@ -797,4 +989,47 @@ mod tests { assert!(matches!(&ev[1], Event::Text(t) if t == "a")); assert!(key_events("Hyper+K").is_err()); } + + #[test] + fn a_glide_moves_in_eased_steps_and_lands_on_its_point() { + let steps = [ + parse_step(&serde_json::json!({ "move": [0, 0] })).unwrap(), + parse_step(&serde_json::json!({ "glide": [100, 50], "ms": 100 })).unwrap(), + parse_step(&serde_json::json!({ "cursor": false })).unwrap(), + ]; + assert_eq!(steps[1], Step::Glide(pos2(100.0, 50.0), 0.1)); + let ops = expand(&steps).unwrap(); + let moves: Vec = ops + .iter() + .filter_map(|op| match op { + Op::Event(Event::PointerMoved(p)) => Some(*p), + _ => None, + }) + .collect(); + // The first move, then 6 for 100 ms at 60 a second. + assert_eq!(moves.len(), 7); + assert_eq!(*moves.last().unwrap(), pos2(100.0, 50.0)); + // Slow, then fast, then slow. + let first = moves[1].x - moves[0].x; + let middle = moves[4].x - moves[3].x; + assert!(first < middle, "{moves:?}"); + let waited: f64 = ops + .iter() + .map(|op| if let Op::Wait(s) = op { *s } else { 0.0 }) + .sum(); + assert!((waited - 0.1).abs() < 1e-9); + assert!(matches!(ops.back(), Some(Op::Cursor(false)))); + } + + #[test] + fn record_reads_its_rate() { + let dir = std::env::temp_dir().join(format!("accshift-record-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("r.json"); + std::fs::write(&file, r#"{ "id": "r", "record": 30, "steps": [] }"#).unwrap(); + assert_eq!(load(&file).unwrap().record, Some(30.0)); + std::fs::write(&file, r#"{ "id": "r", "steps": [] }"#).unwrap(); + assert_eq!(load(&file).unwrap().record, None); + let _ = std::fs::remove_dir_all(&dir); + } }