motion-canvas-rs 0.2.4

A high-performance vector animation engine inspired by Motion Canvas, built on Vello and Typst.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#![allow(deprecated)]

use crate::assets::font_manager::FontManager;
use crate::core::animation::{Node, Paint, Signal};
use glam::Vec2;
use kurbo::{Affine, BezPath, Shape};
use peniko::{Brush, Color, Fill};
use skrifa::instance::{LocationRef, Size};
use skrifa::MetadataProvider;
use std::collections::HashMap;
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[cfg(feature = "runtime")]
use vello::Scene;

static GLOBAL_TEXT_CACHE: LazyLock<Mutex<HashMap<TextCacheKey, Arc<Vec<(Affine, BezPath)>>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

const DEFAULT_FONT_SIZE: f32 = 32.0;
const DEFAULT_COLOR: Color = Color::WHITE;
const DEFAULT_OPACITY: f32 = 1.0;
const DEFAULT_FONT_FAMILY: &str = "JetBrains Mono";
const FONT_FALLBACKS: &[&str] = &["Inter", "Arial", "sans-serif"];
const ADVANCE_FALLBACK_FACTOR: f32 = 0.6;

/// Horizontal alignment options for text within a `TextNode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TextAlign {
    /// Align text to the left edge.
    Left,
    /// Align text to the center.
    Center,
    /// Align text to the right edge.
    Right,
}

impl crate::core::animation::tween::Tweenable for TextAlign {
    fn interpolate(a: &Self, b: &Self, t: f32) -> Self {
        if t >= 1.0 {
            return *b;
        }
        *a
    }

    fn state_hash(&self) -> u64 {
        *self as u64
    }
}

impl Default for TextAlign {
    fn default() -> Self {
        Self::Center
    }
}

#[derive(Hash, Eq, PartialEq)]
struct TextCacheKey {
    text: String,
    font_size_bits: u32,
    font_family: String,
    text_align: TextAlign,
}

/// A visual node that renders vectorized text using system or embedded fonts.
///
/// `TextNode` supports multi-line text, custom font sizes, colors, and alignments.
/// It uses a global cache to optimize the rendering of frequently used text strings.
///
/// ### Example
/// ```rust
/// # use motion_canvas_rs::prelude::*;
/// let text = TextNode::default()
///     .with_position(Vec2::new(640.0, 360.0))
///     .with_text("Hello World")
///     .with_font_size(48.0)
///     .with_fill(Color::WHITE)
///     .with_font("Inter")
///     .with_text_align(TextAlign::Center);
/// ```
pub struct TextNode {
    /// The absolute position of the text's center (before anchor adjustment).
    pub position: Signal<Vec2>,
    /// Rotation in radians.
    pub rotation: Signal<f32>,
    /// Scaling factor for the text.
    pub scale: Signal<Vec2>,
    /// The string content to display.
    pub text: Signal<String>,
    /// The font size in pixels.
    pub font_size: Signal<f32>,
    /// The solid color used to fill the text.
    /// **Deprecated**: prefer `fill_paint` which supports both solid colors and gradients.
    #[deprecated(since = "0.2.3", note = "use fill_paint instead")]
    pub fill_color: Signal<Color>,
    /// The paint (color or gradient) used to fill the text.
    pub fill_paint: Signal<Paint>,
    /// Opacity from 0.0 (transparent) to 1.0 (opaque).
    pub opacity: Signal<f32>,
    /// The relative transformation origin. (-1,-1) is top-left, (0,0) is center, (1,1) is bottom-right.
    pub anchor: Signal<Vec2>,
    /// The horizontal alignment of the text lines.
    pub text_align: Signal<TextAlign>,
    /// The preferred font family name.
    pub font_family: String,
    cache: Arc<Mutex<Option<Arc<Vec<(Affine, BezPath)>>>>>,
    /// Blur radius signal.
    pub blur: Signal<f32>,
}

impl Default for TextNode {
    fn default() -> Self {
        Self {
            position: Signal::new(Vec2::ZERO),
            rotation: Signal::new(0.0),
            scale: Signal::new(Vec2::ONE),
            text: Signal::new("".to_string()),
            font_size: Signal::new(DEFAULT_FONT_SIZE),
            fill_color: Signal::new(DEFAULT_COLOR),
            fill_paint: Signal::new(Paint::None),
            opacity: Signal::new(DEFAULT_OPACITY),
            anchor: Signal::new(Vec2::ZERO),
            text_align: Signal::new(TextAlign::Center),
            font_family: DEFAULT_FONT_FAMILY.to_string(),
            cache: Arc::new(Mutex::new(None)),
            blur: Signal::new(crate::core::filters::DEFAULT_BLUR),
        }
    }
}

impl TextNode {
    /// Creates a new text node with given position, content, size, and color.
    pub fn new(position: Vec2, text: &str, size: f32, color: Color) -> Self {
        Self::default()
            .with_position(position)
            .with_text(text)
            .with_font_size(size)
            .with_fill(color)
    }

    /// Sets the absolute position of the text.
    pub fn with_position(mut self, position: Vec2) -> Self {
        self.position = Signal::new(position);
        self
    }

    /// Sets the rotation of the text in radians.
    pub fn with_rotation(mut self, angle: f32) -> Self {
        self.rotation = Signal::new(angle);
        self
    }

    /// Sets a uniform scale factor for both axes.
    pub fn with_scale(mut self, scale: f32) -> Self {
        self.scale = Signal::new(Vec2::splat(scale));
        self
    }

    /// Sets non-uniform scaling factors for X and Y axes.
    pub fn with_scale_xy(mut self, scale: Vec2) -> Self {
        self.scale = Signal::new(scale);
        self
    }

    /// Sets the opacity of the text (0.0 to 1.0).
    pub fn with_opacity(mut self, opacity: f32) -> Self {
        self.opacity = Signal::new(opacity);
        self
    }

    /// Sets the font family to be used for rendering.
    pub fn with_font(mut self, family: &str) -> Self {
        self.font_family = family.to_string();
        self
    }

    /// Sets the string content.
    pub fn with_text(mut self, text: &str) -> Self {
        self.text = Signal::new(text.to_string());
        self
    }

    /// Sets the font size in pixels.
    pub fn with_font_size(mut self, size: f32) -> Self {
        self.font_size = Signal::new(size);
        self
    }

    /// Sets the fill paint (color or gradient).
    pub fn with_fill(mut self, paint: impl Into<Paint>) -> Self {
        let p = paint.into();
        if let Paint::Solid(color) = p {
            self.fill_color = Signal::new(color);
        }
        self.fill_paint = Signal::new(p);
        self
    }

    /// Sets the horizontal alignment.
    pub fn with_text_align(mut self, align: TextAlign) -> Self {
        self.text_align = Signal::new(align);
        self
    }

    /// Sets the relative transformation origin (anchor).
    /// (-1, -1) is top-left, (0, 0) is center, (1, 1) is bottom-right.
    pub fn with_anchor(mut self, anchor: Vec2) -> Self {
        self.anchor = Signal::new(anchor);
        self
    }
}

impl Clone for TextNode {
    fn clone(&self) -> Self {
        Self {
            position: self.position.clone(),
            rotation: self.rotation.clone(),
            scale: self.scale.clone(),
            text: self.text.clone(),
            font_size: self.font_size.clone(),
            fill_color: self.fill_color.clone(),
            fill_paint: self.fill_paint.clone(),
            opacity: self.opacity.clone(),
            anchor: self.anchor.clone(),
            text_align: self.text_align.clone(),
            font_family: self.font_family.clone(),
            cache: self.cache.clone(),
            blur: self.blur.clone(),
        }
    }
}

struct PathSink<'a>(&'a mut BezPath);

impl<'a> skrifa::outline::OutlinePen for PathSink<'a> {
    fn move_to(&mut self, x: f32, y: f32) {
        self.0.move_to((x as f64, y as f64));
    }
    fn line_to(&mut self, x: f32, y: f32) {
        self.0.line_to((x as f64, y as f64));
    }
    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
        self.0
            .quad_to((cx0 as f64, cy0 as f64), (x as f64, y as f64));
    }
    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        self.0.curve_to(
            (cx0 as f64, cy0 as f64),
            (cx1 as f64, cy1 as f64),
            (x as f64, y as f64),
        );
    }
    fn close(&mut self) {
        self.0.close_path();
    }
}

impl crate::core::filters::Blur for TextNode {
    fn with_blur(mut self, radius: f32) -> Self {
        self.blur = Signal::new(radius);
        self
    }
}

impl Node for TextNode {
    #[cfg(feature = "runtime")]
    fn render(&self, scene: &mut Scene, parent_transform: Affine, parent_opacity: f32) {
        let blur_radius = self.blur.get().max(0.0);
        let opacity = self.opacity.get();
        let combined_opacity = parent_opacity * opacity;

        crate::core::filters::apply_blur_filter(
            scene,
            blur_radius,
            combined_opacity,
            |scene, target_opacity| {
                let text = self.text.get();
                let size = self.font_size.get();
                let color = self.fill_color.get();

                let pos = self.position.get();
                let rot = self.rotation.get();
                let sc = self.scale.get();
                let anchor = self.anchor.get();
                let text_align = self.text_align.get();

                let key = TextCacheKey {
                    text: text.clone(),
                    font_size_bits: size.to_bits(),
                    font_family: self.font_family.clone(),
                    text_align,
                };

                // 1. Check global cache
                let mut global = GLOBAL_TEXT_CACHE.lock().unwrap();
                if let Some(paths) = global.get(&key) {
                    let mut local = self.cache.lock().unwrap();
                    *local = Some(paths.clone());
                } else {
                    // 3. Rebuild
                    let mut paths = Vec::new();
                    let mut fallback_list = vec![self.font_family.as_str(), DEFAULT_FONT_FAMILY];
                    fallback_list.extend_from_slice(FONT_FALLBACKS);

                    if let Some(font_data) = FontManager::get_font_with_fallback(&fallback_list) {
                        let font_ref = FontManager::get_font_ref(&font_data);
                        let charmap = font_ref.charmap();
                        let outlines = font_ref.outline_glyphs();

                        let lines: Vec<&str> = text.split('\n').collect();
                        let line_height = size * 1.2;

                        // Measure line widths
                        let mut line_widths = Vec::with_capacity(lines.len());
                        for line in &lines {
                            let mut width = 0.0;
                            for c in line.chars() {
                                let glyph_id = charmap.map(c).unwrap_or_default();
                                let mut advance = (size * ADVANCE_FALLBACK_FACTOR) as f64;
                                if let Some(metrics) = font_ref
                                    .glyph_metrics(Size::new(size), LocationRef::default())
                                    .advance_width(glyph_id)
                                {
                                    advance = metrics as f64;
                                }
                                width += advance;
                            }
                            line_widths.push(width);
                        }

                        let max_width = line_widths.iter().copied().fold(0.0f64, f64::max);
                        let mut y_offset = 0.0;

                        for (i, line) in lines.iter().enumerate() {
                            let line_width = line_widths[i];
                            let mut x_offset = match text_align {
                                TextAlign::Left => 0.0,
                                TextAlign::Center => (max_width - line_width) / 2.0,
                                TextAlign::Right => max_width - line_width,
                            };

                            for c in line.chars() {
                                let glyph_id = charmap.map(c).unwrap_or_default();
                                let mut pb = BezPath::new();
                                let mut advance = (size * ADVANCE_FALLBACK_FACTOR) as f64;

                                if let Some(glyph) = outlines.get(glyph_id) {
                                    let mut sink = PathSink(&mut pb);
                                    let font_size = Size::new(size);
                                    let _ = glyph.draw(font_size, &mut sink);

                                    if let Some(metrics) = font_ref
                                        .glyph_metrics(font_size, LocationRef::default())
                                        .advance_width(glyph_id)
                                    {
                                        advance = metrics as f64;
                                    }
                                }

                                let base_transform =
                                    Affine::translate((x_offset, size as f64 + y_offset as f64))
                                        * Affine::scale_non_uniform(1.0, -1.0);
                                paths.push((base_transform, pb));
                                x_offset += advance;
                            }
                            y_offset += line_height;
                        }
                    }
                    let arc_paths = Arc::new(paths);
                    global.insert(key, arc_paths.clone());
                    let mut local = self.cache.lock().unwrap();
                    *local = Some(arc_paths);
                }

                let cache_guard = self.cache.lock().unwrap();
                let Some(c) = cache_guard.as_ref() else {
                    return;
                };

                // Calculate bounding box for centering and anchor
                let mut min_x = f64::MAX;
                let mut min_y = f64::MAX;
                let mut max_x = f64::MIN;
                let mut max_y = f64::MIN;

                for (glyph_transform, pb) in c.as_ref() {
                    let bounds = pb.bounding_box();
                    let p0 = *glyph_transform * vello::kurbo::Point::new(bounds.x0, bounds.y0);
                    let p1 = *glyph_transform * vello::kurbo::Point::new(bounds.x1, bounds.y1);
                    min_x = min_x.min(p0.x).min(p1.x);
                    min_y = min_y.min(p0.y).min(p1.y);
                    max_x = max_x.max(p0.x).max(p1.x);
                    max_y = max_y.max(p0.y).max(p1.y);
                }

                let size_vec = if min_x == f64::MAX {
                    Vec2::ZERO
                } else {
                    Vec2::new((max_x - min_x) as f32, (max_y - min_y) as f32)
                };

                let center_offset = if min_x == f64::MAX {
                    Vec2::ZERO
                } else {
                    Vec2::new((min_x + max_x) as f32 * 0.5, (min_y + max_y) as f32 * 0.5)
                };

                let anchor_offset = anchor * size_vec * 0.5;

                let local_transform = Affine::translate((pos.x as f64, pos.y as f64))
                    * Affine::rotate(rot as f64)
                    * Affine::scale_non_uniform(sc.x as f64, sc.y as f64)
                    * Affine::translate((-anchor_offset.x as f64, -anchor_offset.y as f64))
                    * Affine::translate((-center_offset.x as f64, -center_offset.y as f64));

                let root_transform = parent_transform * local_transform;
                let brush = match self.fill_paint.get() {
                    Paint::None => {
                        let mut render_color = color;
                        render_color.a = (color.a as f32 * target_opacity).clamp(0.0, 255.0) as u8;
                        Brush::Solid(render_color)
                    }
                    paint => paint.to_brush_with_opacity(target_opacity),
                };
                for (glyph_transform, pb) in c.as_ref() {
                    scene.fill(
                        Fill::NonZero,
                        root_transform * *glyph_transform,
                        &brush,
                        None,
                        pb,
                    );
                }
            },
        );
    }
    fn update(&mut self, _dt: Duration) {}
    fn state_hash(&self) -> u64 {
        use crate::assets::hash::Hasher;
        let mut h = Hasher::new();
        h.update_u64(self.position.state_hash());
        h.update_u64(self.rotation.state_hash());
        h.update_u64(self.scale.state_hash());
        h.update_u64(self.text.state_hash());
        h.update_u64(self.font_size.state_hash());
        h.update_u64(self.fill_color.state_hash());
        h.update_u64(self.fill_paint.state_hash());
        h.update_u64(self.opacity.state_hash());
        h.update_u64(self.anchor.state_hash());
        h.update_u64(self.text_align.state_hash());
        h.update_bytes(self.font_family.as_bytes());
        h.update_u64(self.blur.state_hash());
        h.finish()
    }

    fn clone_node(&self) -> Box<dyn Node> {
        Box::new(self.clone())
    }

    fn reset(&mut self) {
        self.position.reset();
        self.rotation.reset();
        self.scale.reset();
        self.text.reset();
        self.font_size.reset();
        self.fill_color.reset();
        self.fill_paint.reset();
        self.opacity.reset();
        self.anchor.reset();
        self.text_align.reset();
        self.blur.reset();
    }
}