The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add WebAssembly engine entry points
Sina Atalayaf7be3fb8934
diff --git a/rust/engine/src/chrome.rs b/rust/engine/src/chrome.rsnew file mode 100644index 00000000..2c56226d--- /dev/null+++ b/rust/engine/src/chrome.rs@@ -0,0 +1,505 @@+//! The player's face, drawn by the engine itself: its controls as shapes and its text in manimgx's+//! fonts (see `text`), records of a 2D view in points (y up, from the bottom left) over a clear+//! background, laid over the film. So they are drawn as a film is, exactly, and need no toolkit: a+//! `Face` (what the player shows) in, a picture out, and where its controls are.++use std::collections::{HashMap, HashSet};+use std::rc::Rc;++use crate::render::{Frame, Gpu, Mat34, Player, Record, VIEW_FLOATS};+use crate::text::{Family, Fonts, Line};++/// The shapes every control is made of, uploaded once: a unit square, a unit disk, a triangle.+const SQUARE: u64 = 1;+const DISK: u64 = 2;+const TRIANGLE: u64 = 3;+/// A glyph's upload key: its font, weight and id, apart from the shapes'.+const GLYPH: u64 = 1 << 62;++const BLUE: [f32; 4] = [0.345, 0.769, 0.867, 1.0]; // manim's BLUE_C+const WHITE: [f32; 4] = [1.0; 4];+const DIM: [f32; 4] = [1.0, 1.0, 1.0, 0.55];++/// What the player shows: the face's state, as the player has it.+pub(crate) struct Face {+ pub(crate) size: (f32, f32), // points+ pub(crate) time: f64,+ pub(crate) duration: f64, // made so far, until the take ends+ pub(crate) made: f64, // the last frame made (where playing waits)+ pub(crate) playing: bool,+ pub(crate) controls: bool, // the controls show+ pub(crate) chapters: Vec<(f64, f64, String)>,+ pub(crate) hover: Option<f64>, // the pointer over the timeline, at this time+ pub(crate) rate: f64,+ pub(crate) captions: Option<bool>, // the take has captions: shown or not+ pub(crate) said: Vec<String>, // what is said now, if shown+ pub(crate) sound: Option<bool>, // the take has sound: muted or not+ pub(crate) scenes: bool, // the file has other scenes+ pub(crate) fullscreen: bool,+ pub(crate) flash: Option<String>, // what was just done+ pub(crate) status: Option<String>, // no picture yet: what the player waits for+ pub(crate) error: Option<String>,+ pub(crate) help: bool,+ pub(crate) mac: bool, // a Mac's keys (Option, not Ctrl)+}++/// A control of the face: what is there to point at.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) enum Control {+ Timeline,+ Toggle,+ Next,+ Mute,+ Captions,+ Fullscreen,+}++/// The keys, as the help lists them (the chapters' key, `{}`: Option on a Mac, Ctrl elsewhere).+const KEYS: [(&str, &str); 14] = [+ ("Space k", "play, pause"),+ ("← →", "5 seconds back, on"),+ ("j l", "10 seconds back, on"),+ (", .", "a frame back, on (paused)"),+ ("{} ← →", "the play before, after"),+ ("0 … 9", "a tenth of the way in"),+ ("Home End", "the start, the end"),+ ("< >", "slower, faster"),+ ("↑ ↓", "louder, quieter"),+ ("m", "mute"),+ ("c", "captions"),+ ("f", "full screen"),+ ("N P", "the file's next, previous scene"),+ ("?", "these keys"),+];++/// A text set: its glyphs (upload key, curves, placement from font units to points, y up, from+/// its first baseline's start), and its extent from there: left, right, top, bottom.+pub(crate) struct Label {+ glyphs: Vec<(u64, u32, [f32; 6])>,+ pub(crate) bounds: [f32; 4],+}++impl Label {+ pub(crate) fn width(&self) -> f32 {+ self.bounds[1] - self.bounds[0]+ }+}++pub(crate) struct Chrome {+ pub(crate) player: Player,+ fonts: Rc<Fonts>,+ labels: HashMap<String, Rc<Label>>, // those the last layouts drew+ breaks: HashMap<String, Rc<Vec<String>>>, // the lines of the captions they drew+ used: HashSet<String>, // those this layout draws+ curves: HashMap<u64, u32>, // the paths uploaded: their curves+ records: Vec<Record>,+ zones: Vec<([f32; 4], Control)>, // where the controls laid out are (points: x0, y0, x1, y1)+ pub(crate) scale: f32, // pixels per point+}++/// `a` then `b` (affine maps as six numbers: x' = a·x + c·y + e, y' = b·x + d·y + f).+fn then(a: [f32; 6], b: [f32; 6]) -> [f32; 6] {+ [+ b[0] * a[0] + b[2] * a[1],+ b[1] * a[0] + b[3] * a[1],+ b[0] * a[2] + b[2] * a[3],+ b[1] * a[2] + b[3] * a[3],+ b[0] * a[4] + b[2] * a[5] + b[4],+ b[1] * a[4] + b[3] * a[5] + b[5],+ ]+}++fn matrix([a, b, c, d, e, f]: [f32; 6]) -> Mat34 {+ [[a, c, 0.0, e], [b, d, 0.0, f], [0.0, 0.0, 1.0, 0.0]]+}++/// A path as the player takes it, from cubic points (x, y, z; four per curve): its subpaths+/// broken where a curve does not start where the last ended, closed where one ends where it+/// began; and the centroid and Newell area vector of its control points.+fn path(points: &[[f64; 3]]) -> (Vec<u8>, Vec<u8>, [f32; 6]) {+ let curves = points.len() / 4;+ let near = |p: [f64; 3], q: [f64; 3]| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6;+ let mut subpaths: Vec<[u32; 4]> = Vec::new();+ let mut start = 0;+ for i in 1..=curves {+ if i == curves || !near(points[4 * i], points[4 * i - 1]) {+ let closed = near(points[4 * start], points[4 * i - 1]);+ subpaths.push([start as u32, i as u32, closed as u32, 0]);+ start = i;+ }+ }+ let n = points.len().max(1) as f64;+ let centroid = [0, 1, 2].map(|k| points.iter().map(|p| p[k]).sum::<f64>() / n);+ let mut area = [0.0f64; 3];+ for (p, q) in points.iter().zip(points.iter().cycle().skip(1)) {+ area[0] += (p[1] - q[1]) * (p[2] + q[2]);+ area[1] += (p[2] - q[2]) * (p[0] + q[0]);+ area[2] += (p[0] - q[0]) * (p[1] + q[1]);+ }+ let summary = [centroid[0], centroid[1], centroid[2], area[0], area[1], area[2]].map(|x| x as f32);+ (bytemuck::cast_slice(points).to_vec(), bytemuck::cast_slice(&subpaths).to_vec(), summary)+}++/// Cubic points of a polygon's edges (straight curves), closed.+fn polygon(corners: &[[f64; 2]]) -> Vec<[f64; 3]> {+ let mut points = Vec::with_capacity(4 * corners.len());+ for (i, &a) in corners.iter().enumerate() {+ let b = corners[(i + 1) % corners.len()];+ for t in [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0] {+ points.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]), 0.0]);+ }+ }+ points+}++/// Cubic points of the unit circle: four quarter arcs.+fn circle() -> Vec<[f64; 3]> {+ let k = 0.552_284_749_830_793_6; // 4/3 · (√2 − 1)+ let mut points = Vec::new();+ for (c, s) in [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)] {+ // from (c, s) a quarter turn on, to (−s, c): its tangents' handles k long+ points.extend([[c, s, 0.0], [c - k * s, s + k * c, 0.0], [-s + k * c, c + k * s, 0.0], [-s, c, 0.0]]);+ }+ points+}++/// "m:ss.t": a time in minutes, seconds and tenths.+pub(crate) fn stamp(t: f64) -> String {+ let tenths = (t.max(0.0) * 10.0 + 1e-6).floor() as u64;+ format!("{}:{:02}.{}", tenths / 600, tenths / 10 % 60, tenths % 10)+}++impl Chrome {+ pub(crate) fn new(fonts: Rc<Fonts>) -> Self {+ let mut player = Player::new(1, 1, 4);+ let shapes = [(SQUARE, polygon(&[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])), (DISK, circle()), (TRIANGLE, polygon(&[[0.0, 0.0], [1.0, 0.5], [0.0, 1.0]]))];+ let mut curves = HashMap::new();+ for (key, points) in shapes {+ let (data, subpaths, summary) = path(&points);+ player.add_path(key, &data, &subpaths, summary).expect("a control's shape");+ curves.insert(key, (points.len() / 4) as u32);+ }+ Self { player, fonts, labels: HashMap::new(), breaks: HashMap::new(), used: HashSet::new(), curves, records: Vec::new(), zones: Vec::new(), scale: 1.0 }+ }++ /// Shape `key` placed by `m` (points), in `rgba`.+ fn shape(&mut self, key: u64, m: [f32; 6], rgba: [f32; 4]) {+ let s = self.scale;+ self.records.push(Record::filled(key, self.curves[&key], matrix(then(m, [s, 0.0, 0.0, s, 0.0, 0.0])), rgba));+ }++ fn rect(&mut self, x: f32, y: f32, w: f32, h: f32, rgba: [f32; 4]) {+ self.shape(SQUARE, [w, 0.0, 0.0, h, x, y], rgba);+ }++ fn disk(&mut self, x: f32, y: f32, r: f32, rgba: [f32; 4]) {+ self.shape(DISK, [r, 0.0, 0.0, r, x, y], rgba);+ }++ /// A triangle in the box (x, y, w, h) pointing right (w < 0: left).+ fn triangle(&mut self, x: f32, y: f32, w: f32, h: f32, rgba: [f32; 4]) {+ self.shape(TRIANGLE, [w, 0.0, 0.0, h, x, y], rgba);+ }++ /// The control at (x, y) points, as the last layout placed them.+ pub(crate) fn control(&self, x: f32, y: f32) -> Option<Control> {+ self.zones.iter().rev().find(|(r, _)| (r[0]..r[2]).contains(&x) && (r[1]..r[3]).contains(&y)).map(|(_, c)| *c)+ }++ /// The label of `lines` (each placed at its offset, points), set once and kept while the+ /// layouts draw it, under `name`.+ fn label(&mut self, name: String, lines: impl FnOnce(&Fonts) -> Vec<(Line, f32, f32, f32)>) -> Result<Rc<Label>, String> {+ self.used.insert(name.clone());+ if let Some(label) = self.labels.get(&name) {+ return Ok(label.clone());+ }+ let mut glyphs = Vec::new();+ let mut bounds = [f32::MAX, f32::MIN, f32::MIN, f32::MAX];+ for (line, x, y, size) in lines(&self.fonts) {+ bounds = [bounds[0].min(x), bounds[1].max(x + line.width), bounds[2].max(y + 0.75 * size), bounds[3].min(y - 0.25 * size)];+ for g in &line.glyphs {+ let key = GLYPH | u64::from(g.font) << 17 | u64::from(g.bold) << 16 | u64::from(g.id);+ if !self.curves.contains_key(&key) {+ let points = self.fonts.outline(g.font, g.bold, g.id);+ self.curves.insert(key, (points.len() / 4) as u32);+ if !points.is_empty() {+ let (data, subpaths, summary) = path(&points);+ self.player.add_path(key, &data, &subpaths, summary)?;+ }+ }+ // a space has no outline+ if self.curves[&key] > 0 {+ glyphs.push((key, self.curves[&key], [g.scale, 0.0, 0.0, g.scale, x + g.x, y + g.y]));+ }+ }+ }+ if bounds[0] > bounds[1] {+ bounds = [0.0; 4];+ }+ let label = Rc::new(Label { glyphs, bounds });+ self.labels.insert(name, label.clone());+ Ok(label)+ }++ /// `text`, a line in Noto Sans at `size` points (its digits all one width).+ fn sans(&mut self, size: f32, text: &str) -> Result<Rc<Label>, String> {+ self.label(format!("sans {size} {text}"), |fonts| vec![(fonts.line(text, Family::Sans, size, false, true), 0.0, 0.0, size)])+ }++ /// `text` as it is, its lines and spaces, in DejaVu Sans Mono at `size` points.+ fn mono(&mut self, size: f32, text: &str) -> Result<Rc<Label>, String> {+ self.label(format!("mono {size} {text}"), |fonts| {+ let lead = 1.45 * size;+ text.lines().enumerate().map(|(i, line)| (fonts.line(&line.replace('\t', " "), Family::Mono, size, false, false), 0.0, -lead * i as f32, size)).collect()+ })+ }++ /// `text` in lines no wider than `width` points (broken between words), in Noto Sans: its+ /// breaks found once, and kept while the layouts draw them.+ fn wrapped(&mut self, size: f32, text: &str, width: f32) -> Result<Vec<Rc<Label>>, String> {+ let name = format!("wrap {size} {width} {text}");+ self.used.insert(name.clone());+ let fonts = &self.fonts;+ let lines = self+ .breaks+ .entry(name)+ .or_insert_with(|| {+ let mut lines = Vec::new();+ for paragraph in text.lines() {+ let mut line = String::new();+ for word in paragraph.split(' ') {+ let longer = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") };+ if !line.is_empty() && fonts.line(&longer, Family::Sans, size, false, true).width > width {+ lines.push(std::mem::replace(&mut line, word.to_owned()));+ } else {+ line = longer;+ }+ }+ lines.push(line);+ }+ Rc::new(lines)+ })+ .clone();+ lines.iter().map(|line| self.sans(size, line)).collect()+ }++ /// The keys, as a table: each key bold and to the right, what it does to the left.+ fn keys(&mut self, mac: bool) -> Result<Rc<Label>, String> {+ let chapter = if mac { "Option" } else { "Ctrl" };+ self.label(format!("keys {mac}"), |fonts| {+ let (size, row, gap) = (13.0, 21.0, 16.0);+ let keys: Vec<Line> = KEYS.iter().map(|(k, _)| fonts.line(&k.replace("{}", chapter), Family::Sans, size, true, false)).collect();+ let column = keys.iter().map(|l| l.width).fold(0.0, f32::max);+ let mut lines = Vec::new();+ for (i, (key, (_, what))) in keys.into_iter().zip(KEYS).enumerate() {+ let y = -row * i as f32;+ lines.push((fonts.line(what, Family::Sans, size, false, false), column + gap, y, size));+ let x = column - key.width;+ lines.push((key, x, y, size));+ }+ lines+ })+ }++ /// Draw `label` with its first baseline starting at (x, y) (points), in `rgba`.+ fn text(&mut self, label: &Label, x: f32, y: f32, rgba: [f32; 4]) {+ let s = self.scale;+ let to_pixels = [s, 0.0, 0.0, s, x * s, y * s];+ for &(key, curves, placement) in &label.glyphs {+ self.records.push(Record::filled(key, curves, matrix(then(placement, to_pixels)), rgba));+ }+ }++ /// Lay out `face`: the records to draw, and where its controls are. Whether there is anything+ /// over the film.+ pub(crate) fn lay_out(&mut self, face: &Face) -> Result<bool, String> {+ self.records.clear();+ self.zones.clear();+ self.used.clear();+ self.draw(face)?;+ // the texts it no longer draws go (a time shown once is not kept)+ let used = &self.used;+ self.labels.retain(|name, _| used.contains(name));+ self.breaks.retain(|name, _| used.contains(name));+ Ok(!self.records.is_empty())+ }++ fn draw(&mut self, face: &Face) -> Result<(), String> {+ let (w, h) = face.size;+ if let Some(status) = &face.status {+ let label = self.sans(15.0, status)?;+ self.text(&label, (w - label.width()) / 2.0, h / 2.0, [1.0, 1.0, 1.0, 0.7]);+ }+ if face.controls {+ self.controls(face)?;+ }+ // what is said now, over the picture, above the controls when they show+ let mut y = if face.controls { 76.0 } else { 24.0 };+ for said in face.said.iter().rev() {+ for label in self.wrapped(20.0, said, w - 64.0)?.iter().rev() {+ let x = (w - label.width()) / 2.0;+ self.rect(x - 8.0, y - 8.0, label.width() + 16.0, 32.0, [0.03, 0.03, 0.03, 0.75]);+ self.text(label, x, y, WHITE);+ y += 36.0;+ }+ }+ if let Some(flash) = &face.flash {+ let label = self.sans(18.0, flash)?;+ let x = (w - label.width()) / 2.0;+ self.rect(x - 14.0, h * 0.86 - 12.0, label.width() + 28.0, 40.0, [0.0, 0.0, 0.0, 0.55]);+ self.text(&label, x, h * 0.86, WHITE);+ }+ if let Some(error) = &face.error {+ // the scene's error, over its last good picture+ self.rect(0.0, 0.0, w, h, [0.08, 0.0, 0.0, 0.82]);+ let label = self.mono(12.0, error)?;+ self.text(&label, 20.0, h - 28.0, [1.0, 0.706, 0.706, 1.0]);+ }+ if face.help {+ let label = self.keys(face.mac)?;+ let (bw, bh) = (label.width() + 48.0, label.bounds[2] - label.bounds[3] + 36.0);+ let (x, y) = ((w - bw) / 2.0, (h - bh) / 2.0);+ self.rect(x, y, bw, bh, [0.13, 0.13, 0.13, 0.95]);+ self.text(&label, x + 24.0 - label.bounds[0], y + bh - 18.0 - label.bounds[2], WHITE);+ }+ Ok(())+ }++ /// The controls: a shade; the timeline in chapters (made, played); play or pause, the next+ /// scene, the sound, the time, the chapter; the rate, the captions, full screen; over the+ /// timeline, the time there.+ fn controls(&mut self, face: &Face) -> Result<(), String> {+ let (w, _) = face.size;+ for k in 0..16 {+ let a = 0.6 * (1.0 - k as f32 / 16.0).powi(2);+ self.rect(0.0, 5.0 * k as f32, w, 5.0, [0.0, 0.0, 0.0, a]);+ }+ let (left, right, height) = timeline(face.size);+ self.zones.push(([left - 6.0, height - 10.0, right + 6.0, height + 10.0], Control::Timeline));+ let x = |s: f64| left + (right - left) * if face.duration > 0.0 { (s / face.duration) as f32 } else { 0.0 };+ let thick = if face.hover.is_some() { 5.0 } else { 3.0 };+ let spans: Vec<(f64, f64)> = if face.chapters.len() > 1 { face.chapters.iter().map(|c| (c.0, c.1)).collect() } else { vec![(0.0, face.duration)] };+ for (a, b) in spans {+ let (x0, x1) = (x(a) + if a > 0.0 { 1.0 } else { 0.0 }, x(b) - if b < face.duration { 1.0 } else { 0.0 });+ if x1 <= x0 {+ continue;+ }+ let y = height - thick / 2.0;+ self.rect(x0, y, x1 - x0, thick, [1.0, 1.0, 1.0, 0.3]);+ let made = x(face.made.clamp(a, b)).min(x1);+ if made > x0 {+ self.rect(x0, y, made - x0, thick, [1.0, 1.0, 1.0, 0.25]);+ }+ let played = x(face.time.clamp(a, b)).min(x1);+ if played > x0 {+ self.rect(x0, y, played - x0, thick, BLUE);+ }+ }+ if face.hover.is_some() {+ self.disk(x(face.time), height, 6.5, BLUE);+ }+ // the row, a button's place 32 points square each, from the left+ let mut at = 6.0;+ let mut button = |chrome: &mut Chrome, control: Control| {+ chrome.zones.push(([at, 5.0, at + 32.0, 37.0], control));+ at += 32.0;+ at - 32.0+ };+ let b = button(self, Control::Toggle);+ if face.playing {+ self.rect(b + 10.0, 14.0, 4.0, 14.0, WHITE);+ self.rect(b + 18.0, 14.0, 4.0, 14.0, WHITE);+ } else {+ self.triangle(b + 10.0, 14.0, 13.0, 14.0, WHITE);+ }+ if face.scenes {+ let b = button(self, Control::Next);+ self.triangle(b + 9.0, 15.0, 10.0, 12.0, WHITE);+ self.rect(b + 20.0, 15.0, 2.5, 12.0, WHITE);+ }+ if let Some(muted) = face.sound {+ let b = button(self, Control::Mute);+ self.rect(b + 8.0, 17.5, 4.0, 7.0, WHITE);+ self.triangle(b + 18.0, 13.0, -9.0, 16.0, WHITE);+ if muted {+ let (c, s) = (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2);+ // a stroke across it, 2 by 18 points, turned an eighth+ self.shape(SQUARE, [2.0 * c, 2.0 * s, -18.0 * s, 18.0 * c, b + 22.0, 14.0], WHITE);+ } else {+ self.rect(b + 20.5, 18.0, 2.0, 6.0, DIM);+ self.rect(b + 24.0, 16.0, 2.0, 10.0, DIM);+ }+ }+ let label = self.sans(13.0, &format!("{} / {}", stamp(face.time), stamp(face.duration)))?;+ let after = at + 8.0;+ self.text(&label, after, 16.0, WHITE);+ let chapter = face.chapters.iter().rev().find(|c| c.0 <= face.time + 1e-6);+ if let Some((_, _, title)) = chapter {+ let title = self.sans(13.0, &format!("• {title}"))?;+ self.text(&title, after + label.width() + 14.0, 16.0, [1.0, 1.0, 1.0, 0.85]);+ }+ // from the right+ let mut edge = w - 6.0;+ let mut button = |chrome: &mut Chrome, control: Control| {+ edge -= 32.0;+ chrome.zones.push(([edge, 5.0, edge + 32.0, 37.0], control));+ edge+ };+ let b = button(self, Control::Fullscreen);+ // four corners of a 14-point square, each two arms 5 long and 2 thick: their angle at the+ // square's corner (at a point inside it, its arms out to the edges, when full screen)+ let (arm, thick) = (5.0, 2.0);+ let bar = |chrome: &mut Chrome, (x0, y0): (f32, f32), (x1, y1): (f32, f32)| chrome.rect(x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs(), WHITE);+ for (cx, cy, sx, sy) in [(b + 9.0, 14.0, 1.0, 1.0), (b + 23.0, 14.0, -1.0, 1.0), (b + 9.0, 28.0, 1.0, -1.0), (b + 23.0, 28.0, -1.0, -1.0)] {+ let (vx, vy, out) = if face.fullscreen { (cx + sx * arm, cy + sy * arm, -1.0) } else { (cx, cy, 1.0) };+ bar(self, (vx, vy), (vx + out * sx * arm, vy + out * sy * thick));+ bar(self, (vx, vy), (vx + out * sx * thick, vy + out * sy * arm));+ }+ if let Some(on) = face.captions {+ let b = button(self, Control::Captions);+ let label = self.label("cc".into(), |fonts| vec![(fonts.line("CC", Family::Sans, 12.0, true, false), 0.0, 0.0, 12.0)])?;+ self.text(&label, b + (32.0 - label.width()) / 2.0, 16.5, if on { BLUE } else { DIM });+ }+ if (face.rate - 1.0).abs() > 1e-9 {+ let label = self.sans(13.0, &format!("{}×", face.rate))?;+ self.text(&label, edge - 6.0 - label.width(), 16.0, WHITE);+ }+ if let Some(at) = face.hover {+ let title = face.chapters.iter().rev().find(|c| c.0 <= at + 1e-6).filter(|_| face.chapters.len() > 1);+ let words = title.map_or_else(|| stamp(at), |c| format!("{} · {}", c.2, stamp(at)));+ let label = self.sans(12.0, &words)?;+ let lx = (x(at) - label.width() / 2.0).min(w - label.width() - 10.0).max(10.0);+ self.rect(lx - 6.0, height + 12.0, label.width() + 12.0, 22.0, [0.0, 0.0, 0.0, 0.7]);+ self.text(&label, lx, height + 18.0, WHITE);+ }+ Ok(())+ }++ /// Draw what was laid out at `size` (pixels) into the chrome's frame: the commands.+ pub(crate) fn encode(&mut self, gpu: &mut Gpu, size: (u32, u32)) -> Result<wgpu::CommandEncoder, String> {+ if (self.player.width, self.player.height) != size {+ (self.player.width, self.player.height, self.player.targets) = (size.0, size.1, None);+ }+ let (w, h) = (size.0 as f32, size.1 as f32);+ // pixels, y up: x ∈ [0, w] → [−1, 1], y ∈ [0, h] → [−1, 1] (WGSL: column-major); a+ // clear background+ let mut view = vec![0.0f32; VIEW_FLOATS + 4];+ let projection = [[2.0 / w, 0.0, 0.0, -1.0], [0.0, 2.0 / h, 0.0, -1.0], [0.0, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 1.0]];+ for (r, row) in projection.iter().enumerate() {+ for (c, value) in row.iter().enumerate() {+ view[c * 4 + r] = *value;+ view[16 + c * 4 + r] = *value;+ }+ }+ view[32..36].copy_from_slice(&[w, h, 1.0, 1.0]);+ view[40..44].copy_from_slice(&[0.0, 0.0, 1.0, 0.0]);+ let frame = Frame { key: 0, width: size.0, height: size.1, view, records: self.records.clone() };+ let (encoder, _, _) = self.player.encode(gpu, &[frame])?;+ Ok(encoder)+ }+}++/// The timeline's place in a face of `size` points: its left and right ends, its height.+pub(crate) fn timeline(size: (f32, f32)) -> (f32, f32, f32) {+ (12.0, size.0 - 12.0, 44.0)+}diff --git a/rust/engine/src/typeset.rs b/rust/engine/src/typeset.rsindex b21f49e4..c05226da 100644--- a/rust/engine/src/typeset.rs+++ b/rust/engine/src/typeset.rs@@ -1,7 +1,7 @@//! Typst as a library: a document in, its layout out, read straight off Typst's frames. Every//! glyph comes with its outline's key, its placement, its paint and the source bytes it draws-//! (its cluster, through its span); every shape as cubic curves; every labelled group as the-//! items inside it.+//! (its cluster, through its span); every shape as cubic curves; each item with the source node+//! it came from; every labelled group as the items inside it.//!//! Coordinates: a glyph's placement maps its outline (font units, y up) to the page in points//! with y up (Typst's page is y down; the flip is folded in here). Shapes come in page points,@@ -13,8 +13,9 @@ use std::sync::{Arc, Mutex, OnceLock};use typst::diag::{FileError, FileResult, Severity, SourceDiagnostic};use typst::foundations::{Bytes, Datetime, Duration};+use typst::introspection::{Location, Tag};use typst::layout::{Abs, Frame, FrameItem, Point, Transform};-use typst::syntax::{FileId, RootedPath, Source, SyntaxKind, VirtualPath, VirtualRoot};+use typst::syntax::{FileId, RootedPath, Source, Span, SyntaxKind, VirtualPath, VirtualRoot};use typst::text::{Font, FontBook, FontInstance};use typst::utils::LazyHash;use typst::visualize::{Curve, CurveItem, FixedStroke, Geometry, Paint};@@ -25,11 +26,12 @@ use typst_layout::PagedDocument;use unicode_segmentation::UnicodeSegmentation;/// One item's row: kind, key, placement (6), fill (4), stroke (4), stroke width, advance, and-/// where a glyph came from: its node in the source (start, end), the bytes of the node's text its-/// cluster draws (start, end) and the node's kind (`NODE_*`).+/// where the item came from (see `Walk::origin`): its node in the source (start, end), the bytes+/// of the node's text a glyph's cluster draws (start, end) and the node's kind (`NODE_*`).const ROW: usize = 23;-/// A glyph's node: none (not from the main source), markup text (its text is its source), a-/// string literal (its text is the string's value), or another node (an escape, a shorthand…).+/// An item's node: none (nothing in the main source made it), markup text (its text is its+/// source), a string literal (its text is the string's value), or another node (an escape, a+/// shorthand, an element around the item…).const NODE_NONE: f64 = 0.0;const NODE_TEXT: f64 = 1.0;const NODE_STR: f64 = 2.0;@@ -330,6 +332,9 @@ struct Walk<'a> {shapes: Vec<Vec<f64>>,labels: Vec<(String, Vec<usize>)>,open: Vec<usize>, // the labelled groups the walk is inside+ // the elements the walk is inside, by their tags (an equation, a labelled element…), the+ // innermost last+ around: Vec<(Location, Span)>,}impl Walk<'_> {@@ -341,22 +346,32 @@ impl Walk<'_> {self.rows.extend_from_slice(&row);}- /// Where a glyph came from: its node's source range, the bytes of the node's text its- /// cluster draws (`offset`, and `len` more) and the node's kind.- fn origin(&self, span: typst::syntax::Span, offset: u16, len: usize) -> [f64; 5] {- let node = (span.id() == Some(self.doc.main.id()))- .then(|| self.doc.main.find(span))- .flatten();- let Some(node) = node else {- return [-1.0, -1.0, -1.0, -1.0, NODE_NONE];+ /// Where an item came from: the main source's node that made it, its range and kind. That+ /// is its own (its span's) if the main source has it; else the innermost element around it+ /// that the main source has, so a mark a package drew (mitex's fraction bar or radical) is+ /// the equation's that holds it. For a glyph from its own node, `cluster` (its offset in the+ /// node's text, and its length) gives the bytes it draws; -1, -1 otherwise.+ fn origin(&self, span: Span, cluster: Option<(u16, usize)>) -> [f64; 5] {+ let main = |span: Span| {+ (span.id() == Some(self.doc.main.id())).then(|| self.doc.main.find(span)).flatten()+ };+ let (node, cluster) = match main(span) {+ Some(node) => (node, cluster),+ None => match self.around.iter().rev().find_map(|&(_, span)| main(span)) {+ Some(node) => (node, None),+ None => return [-1.0, -1.0, -1.0, -1.0, NODE_NONE],+ },};let kind = match node.kind() {SyntaxKind::Text => NODE_TEXT,SyntaxKind::Str => NODE_STR,_ => NODE_OTHER,};- let (range, start) = (node.range(), usize::from(offset));- [range.start as f64, range.end as f64, start as f64, (start + len) as f64, kind]+ let (from, to) = cluster.map_or((-1.0, -1.0), |(offset, len)| {+ let start = usize::from(offset);+ (start as f64, (start + len) as f64)+ });+ [node.range().start as f64, node.range().end as f64, from, to, kind]}fn frame(&mut self, frame: &Frame, ts: Transform) {@@ -393,7 +408,7 @@ impl Walk<'_> {typst::layout::Ratio::new(-scale),));let [node_start, node_end, from, to, kind] =- self.origin(glyph.span.0, glyph.span.1, glyph.range().len());+ self.origin(glyph.span.0, Some((glyph.span.1, glyph.range().len())));let [a, b, c, d, e, f] = affine(placement);let advance = glyph.x_advance.get() * text.font.units_per_em();self.item([@@ -410,7 +425,7 @@ impl Walk<'_> {y += glyph.y_advance.at(text.size);}}- FrameItem::Shape(shape, _) => {+ FrameItem::Shape(shape, span) => {let curve = match &shape.geometry {Geometry::Line(to) => {let mut c = Curve::new();@@ -427,16 +442,26 @@ impl Walk<'_> {}let fill = shape.fill.as_ref().map_or([-1.0; 4], rgba);let (stroke, width) = stroke(&shape.stroke);+ let [node_start, node_end, from, to, kind] = self.origin(*span, None);let index = self.shapes.len() as f64;self.shapes.push(points);self.item([SHAPE, index, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,fill[0], fill[1], fill[2], fill[3],stroke[0], stroke[1], stroke[2], stroke[3],- width, 0.0, -1.0, -1.0, -1.0, -1.0, NODE_NONE,+ width, 0.0, node_start, node_end, from, to, kind,]);}- FrameItem::Image(..) | FrameItem::Link(..) | FrameItem::Tag(..) => {}+ FrameItem::Tag(tag @ Tag::Start(elem, _)) => {+ self.around.push((tag.location(), elem.span()));+ }+ FrameItem::Tag(tag @ Tag::End(..)) => {+ let location = tag.location();+ if let Some(i) = self.around.iter().rposition(|&(at, _)| at == location) {+ self.around.remove(i);+ }+ }+ FrameItem::Image(..) | FrameItem::Link(..) => {}}}}@@ -542,8 +567,14 @@ pub fn typeset(source: String, font_paths: &[String], packages: Option<&str>) ->}let document = compiled.map_err(|errors| message(&errors, &doc))?;let page = document.pages().first().ok_or("Typst produced no page")?;- let mut walk =- Walk { doc: &doc, rows: Vec::new(), shapes: Vec::new(), labels: Vec::new(), open: Vec::new() };+ let mut walk = Walk {+ doc: &doc,+ rows: Vec::new(),+ shapes: Vec::new(),+ labels: Vec::new(),+ open: Vec::new(),+ around: Vec::new(),+ };walk.frame(&page.frame, Transform::identity());Ok((walk.rows, walk.shapes, walk.labels, system))}diff --git a/rust/engine/src/web.rs b/rust/engine/src/web.rsnew file mode 100644index 00000000..773e9483--- /dev/null+++ b/rust/engine/src/web.rs@@ -0,0 +1,206 @@+//! The player in the browser (WebAssembly, WebGPU): manimgx's player (see `player`) on a page's+//! canvas, the same as in a window. The page's element (`browser`) hands on what its viewer+//! does, in the web's own words, draws it when it is due (`wake`, `draw`) and does what it asks+//! (`asks`); its director's takes come from Pyodide, in a worker (`feed`).++use std::cell::RefCell;+use std::rc::Rc;++use wasm_bindgen::prelude::*;++use crate::player::{self, Ask, Cursor, Modifiers, Screen, Wake};+use crate::render::{GPU, Gpu, with_gpu};+use crate::text::Fonts;++thread_local! {+ // the fonts every player's face is set in+ static FONTS: RefCell<Option<Rc<Fonts>>> = const { RefCell::new(None) };+}++#[wasm_bindgen(start)]+fn start() {+ console_error_panic_hook::set_once();+}++fn error(e: impl std::fmt::Display) -> JsError {+ JsError::new(&e.to_string())+}++/// Bring the GPU up, and take the fonts the players' faces are set in (each a font file's+/// bytes): once, before a player is made.+#[wasm_bindgen]+pub async fn init(fonts: Vec<js_sys::Uint8Array>) -> Result<(), JsError> {+ if GPU.with_borrow(Option::is_none) {+ let gpu = Gpu::new().await.map_err(error)?;+ GPU.with_borrow_mut(|slot| *slot = Some(gpu));+ }+ if FONTS.with_borrow(Option::is_none) {+ let files = fonts.iter().map(|f| &*Box::leak(f.to_vec().into_boxed_slice()));+ let fonts = Rc::new(Fonts::new(files));+ FONTS.with_borrow_mut(|slot| *slot = Some(fonts));+ }+ Ok(())+}++/// manimgx's player, on a canvas.+#[wasm_bindgen]+pub struct Player {+ player: player::Player,+}++#[wasm_bindgen]+impl Player {+ /// A player on `canvas` (at its size, pixels), from `time` seconds, playing or paused; `mac`:+ /// its viewer's keys are a Mac's.+ #[wasm_bindgen(constructor)]+ pub fn new(canvas: web_sys::HtmlCanvasElement, time: f64, playing: bool, mac: bool) -> Result<Player, JsError> {+ let fonts = FONTS.with_borrow(Clone::clone).ok_or_else(|| error("init() first"))?;+ let size = (canvas.width(), canvas.height());+ let screen = with_gpu(|gpu| {+ let surface = gpu.instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas)).map_err(|e| e.to_string())?;+ Screen::new(gpu, surface, size)+ })+ .and_then(|s| s)+ .map_err(error)?;+ Ok(Player { player: player::Player::new(screen, fonts, player::Options { time, playing, mac }) })+ }++ /// Take in the next bytes of its director's stream.+ pub fn feed(&mut self, bytes: &[u8]) -> Result<(), JsError> {+ self.player.feed(bytes).map_err(error)+ }++ /// A key pressed, as `KeyboardEvent` has it. Whether the player took it.+ pub fn key(&mut self, key: &str, ctrl: bool, alt: bool, meta: bool) -> bool {+ self.player.key(key, Modifiers { ctrl, alt, meta })+ }++ /// The pointer moved to (x, y), pixels from the canvas's top left.+ pub fn pointer(&mut self, x: f64, y: f64) {+ self.player.pointer(x, y);+ }++ /// The pointer pressed (a finger, if `touch`) at (x, y), pixels from the canvas's top left.+ /// Whether the player took it.+ pub fn press(&mut self, x: f64, y: f64, touch: bool) -> bool {+ self.player.press(x, y, touch)+ }++ /// The pointer let go. Whether the player took it.+ pub fn release(&mut self) -> bool {+ self.player.release()+ }++ /// The pointer left the canvas.+ pub fn leave(&mut self) {+ self.player.leave();+ }++ /// The press was called off (`pointercancel`: a finger's pan scrolled the page).+ pub fn cancel(&mut self) {+ self.player.cancel();+ }++ /// A wheel turned by (dx, dy) points, as `WheelEvent` has it. Whether the player took it.+ pub fn wheel(&mut self, dx: f64, dy: f64) -> bool {+ self.player.wheel(dx, dy)+ }++ /// The canvas's size on the page, pixels (the screen's own), and its pixels per point.+ pub fn resize(&mut self, width: u32, height: u32, scale: f32) {+ self.player.resize(width, height, scale);+ }++ /// The canvas scrolled out of sight (or its page hidden), or into it.+ pub fn hide(&mut self, hidden: bool) {+ self.player.hide(hidden);+ }++ /// The player is full screen now, or not.+ pub fn fullscreen(&mut self, on: bool) {+ self.player.fullscreen(on);+ }++ /// When to draw it next: 0, at the next animation frame; milliseconds from now; −1, once+ /// something happens.+ pub fn wake(&mut self) -> Result<f64, JsError> {+ Ok(match self.player.wake().map_err(error)? {+ Wake::Now => 0.0,+ Wake::At(at) => at.saturating_duration_since(web_time::Instant::now()).as_secs_f64() * 1000.0,+ Wake::Idle => -1.0,+ })+ }++ /// Draw it now.+ pub fn draw(&mut self) -> Result<(), JsError> {+ self.player.draw(|| {}).map_err(error)+ }++ /// What it asks of the page since it was last asked, in turn: `["scene", name]` (its director+ /// to run the file's scene of that name), `["fullscreen", on]`.+ pub fn asks(&mut self) -> js_sys::Array {+ self.player+ .asks()+ .into_iter()+ .map(|ask| -> JsValue {+ match ask {+ Ask::Scene(name) => js_sys::Array::of2(&"scene".into(), &name.into()).into(),+ Ask::Fullscreen(on) => js_sys::Array::of2(&"fullscreen".into(), &on.into()).into(),+ }+ })+ .collect()+ }++ /// The cursor over it, as CSS names it.+ #[wasm_bindgen(getter)]+ pub fn cursor(&self) -> String {+ match self.player.cursor() {+ Cursor::Arrow => "default",+ Cursor::Hand => "pointer",+ Cursor::Hidden => "none",+ }+ .into()+ }++ /// The time shown, seconds.+ #[wasm_bindgen(getter)]+ pub fn time(&self) -> f64 {+ self.player.time()+ }++ #[wasm_bindgen(setter)]+ pub fn set_time(&mut self, t: f64) {+ self.player.seek(t);+ }++ /// The film's length so far, seconds.+ #[wasm_bindgen(getter)]+ pub fn duration(&self) -> f64 {+ self.player.duration()+ }++ #[wasm_bindgen(getter)]+ pub fn playing(&self) -> bool {+ self.player.playing()+ }++ pub fn play(&mut self) {+ self.player.play();+ }++ pub fn pause(&mut self) {+ self.player.pause();+ }++ /// The scene it plays, as its director named it.+ #[wasm_bindgen(getter)]+ pub fn scene(&self) -> Option<String> {+ self.player.scene().map(str::to_owned)+ }++ /// The film's own size, its frames' (pixels): [width, height]; none before its first take.+ #[wasm_bindgen(getter)]+ pub fn film(&self) -> Option<Vec<u32>> {+ self.player.film().map(|(w, h)| vec![w, h])+ }+}