Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(rendering): text enter/exit animations, alignment, spacing, and shadow

Richie McIlroyb06a3065e25a
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
index abb07188d..e4a94b62f 100644
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@ -1,3 +1,4 @@
+use cap_project::TextAlign;
use glyphon::cosmic_text::Align;
use glyphon::{
Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, Style,
@@ -17,6 +18,24 @@ pub struct TextLayer {
buffers: Vec<Buffer>,
}
+struct AreaSpec {
+ bounds: TextBounds,
+ left: f32,
+ top: f32,
+ scale: f32,
+ color: Color,
+ shadow: Option<(f32, f32, Color)>,
+}
+
+fn shift_bounds(bounds: TextBounds, dx: f32, dy: f32) -> TextBounds {
+ TextBounds {
+ left: bounds.left + dx.floor() as i32,
+ top: bounds.top + dy.floor() as i32,
+ right: bounds.right + dx.ceil() as i32,
+ bottom: bounds.bottom + dy.ceil() as i32,
+ }
+}
+
impl TextLayer {
pub fn new(device: &Device, queue: &Queue) -> Self {
let font_system = super::new_font_system();
@@ -50,7 +69,7 @@ impl TextLayer {
) {
self.buffers.clear();
self.buffers.reserve(texts.len());
- let mut text_area_data = Vec::with_capacity(texts.len());
+ let mut specs = Vec::with_capacity(texts.len());
for text in texts {
let alpha = text.color[3].clamp(0.0, 1.0) * text.opacity.clamp(0.0, 1.0);
@@ -67,18 +86,23 @@ impl TextLayer {
// Shape with a little more width than the editor-measured box:
// the webview and cosmic-text can disagree by a few pixels per
// line, and without slack a line that fit in the editor wraps in
- // the render. The room is split evenly so centered lines stay
- // centered. Boxes already spanning the frame keep their exact
- // width — there the editor genuinely wrapped too.
+ // the render. The room is placed so the aligned edge stays put —
+ // split for centered text, after for left, before for right.
+ // Boxes already spanning the frame keep their exact width — there
+ // the editor genuinely wrapped too.
let output_width = (output_size.0 as f32).max(1.0);
let wrap_width = if width < output_width * 0.98 {
(width * 1.05 + 4.0).min(output_width.max(width))
} else {
width
};
- let wrap_dx = (wrap_width - width) / 2.0;
+ let origin_dx = match text.align {
+ TextAlign::Left => 0.0,
+ TextAlign::Center => (wrap_width - width) / 2.0,
+ TextAlign::Right => wrap_width - width,
+ };
- let metrics = Metrics::new(text.font_size, text.font_size * 1.2);
+ let metrics = Metrics::new(text.font_size, text.font_size * text.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
// The box only constrains wrapping; height is unbounded so every
// line is laid out even when the configured box is a little
@@ -99,15 +123,22 @@ impl TextLayer {
},
};
let weight = Weight(text.font_weight.round().clamp(100.0, 900.0) as u16);
- let attrs = Attrs::new()
+ // Glyph color comes from each area's default_color (not Attrs) so
+ // the shadow pass can re-tint the same shaped buffer.
+ let mut attrs = Attrs::new()
.family(family)
- .color(color)
.weight(weight)
.style(if text.italic {
Style::Italic
} else {
Style::Normal
});
+ if text.letter_spacing != 0.0 {
+ // cosmic-text adds letter_spacing to the em-relative glyph
+ // advance and multiplies by font size at layout (shape.rs), so
+ // the attr is in em — convert from our px value.
+ attrs = attrs.letter_spacing(text.letter_spacing / text.font_size.max(1.0));
+ }
buffer.set_text(
&mut self.font_system,
@@ -116,42 +147,85 @@ impl TextLayer {
Shaping::Advanced,
);
+ let align = match text.align {
+ TextAlign::Left => Align::Left,
+ TextAlign::Center => Align::Center,
+ TextAlign::Right => Align::Right,
+ };
for line in buffer.lines.iter_mut() {
- line.set_align(Some(Align::Center));
+ line.set_align(Some(align));
}
buffer.shape_until_scroll(&mut self.font_system, false);
+ let laid_out_height = buffer.layout_runs().count() as f32 * metrics.line_height;
+
+ // Animation transform: uniform scale about the box center plus a
+ // translation, applied to the buffer origin and clip bounds (the
+ // glyph layout itself is scaled by TextArea::scale from that
+ // origin).
+ let cx = (text.bounds[0] + text.bounds[2]) / 2.0;
+ let cy = (text.bounds[1] + text.bounds[3]) / 2.0;
+ let scale = text.scale.max(0.01);
+ let tx = |x: f32| cx + (x - cx) * scale + text.offset[0];
+ let ty = |y: f32| cy + (y - cy) * scale + text.offset[1];
+
+ let origin_left = tx(text.bounds[0] - origin_dx);
+ let origin_top = ty(text.bounds[1]);
+
// Clip horizontally at the (slack-expanded) wrap box, but extend
// the bottom to the laid-out text height so descenders and extra
// lines never get cut off; glyphon intersects these bounds with
// the viewport.
- let laid_out_height = buffer.layout_runs().count() as f32 * metrics.line_height;
let bounds = TextBounds {
- left: (text.bounds[0] - wrap_dx).floor() as i32,
- top: text.bounds[1].floor() as i32,
- right: (text.bounds[0] + width + wrap_dx).ceil() as i32,
- bottom: (text.bounds[1] + height.max(laid_out_height)).ceil() as i32,
+ left: origin_left.floor() as i32,
+ top: origin_top.floor() as i32,
+ right: tx(text.bounds[0] - origin_dx + wrap_width).ceil() as i32,
+ bottom: ty(text.bounds[1] + height.max(laid_out_height)).ceil() as i32,
};
+ let shadow = (text.shadow > 0.0).then(|| {
+ let dx = text.font_size * scale * 0.02;
+ let dy = text.font_size * scale * 0.055;
+ let shadow_alpha = alpha * text.shadow.clamp(0.0, 1.0) * 0.85;
+ (dx, dy, Color::rgba(0, 0, 0, (shadow_alpha * 255.0) as u8))
+ });
+
self.buffers.push(buffer);
- // The buffer origin shifts left by the slack so centered lines
- // stay centered on the box.
- text_area_data.push((bounds, text.bounds[0] - wrap_dx, text.bounds[1], color));
+ specs.push(AreaSpec {
+ bounds,
+ left: origin_left,
+ top: origin_top,
+ scale,
+ color,
+ shadow,
+ });
}
let text_areas = self
.buffers
.iter()
- .zip(text_area_data)
- .map(|(buffer, (bounds, left, top, color))| TextArea {
- buffer,
- left,
- top,
- scale: 1.0,
- bounds,
- default_color: color,
- custom_glyphs: &[],
+ .zip(&specs)
+ .flat_map(|(buffer, spec)| {
+ let shadow_area = spec.shadow.map(|(dx, dy, shadow_color)| TextArea {
+ buffer,
+ left: spec.left + dx,
+ top: spec.top + dy,
+ scale: spec.scale,
+ bounds: shift_bounds(spec.bounds, dx, dy),
+ default_color: shadow_color,
+ custom_glyphs: &[],
+ });
+ let main_area = TextArea {
+ buffer,
+ left: spec.left,
+ top: spec.top,
+ scale: spec.scale,
+ bounds: spec.bounds,
+ default_color: spec.color,
+ custom_glyphs: &[],
+ };
+ shadow_area.into_iter().chain(std::iter::once(main_area))
})
.collect::<Vec<_>>();
diff --git a/crates/rendering/src/text.rs b/crates/rendering/src/text.rs
index 5fb66bd61..29bd89046 100644
--- a/crates/rendering/src/text.rs
+++ b/crates/rendering/src/text.rs
@@ -1,4 +1,4 @@
-use cap_project::{TextSegment, XY};
+use cap_project::{TextAlign, TextAnimation, TextSegment, XY};
/// Text font sizes are authored against a 1080p-tall reference frame and
/// scaled to the output height, so a project renders identically at every
@@ -19,6 +19,17 @@ pub struct PreparedText {
pub font_weight: f32,
pub italic: bool,
pub opacity: f32,
+ pub align: TextAlign,
+ /// Output px, already scaled from the 1080p reference.
+ pub letter_spacing: f32,
+ /// Multiplier of `font_size`.
+ pub line_height: f32,
+ /// 0..1 drop-shadow strength; 0 disables the shadow pass.
+ pub shadow: f32,
+ /// Animation translation in output px, applied to the whole block.
+ pub offset: [f32; 2],
+ /// Animation scale about the box center.
+ pub scale: f32,
}
fn parse_color(hex: &str) -> [f32; 4] {
@@ -36,6 +47,100 @@ fn parse_color(hex: &str) -> [f32; 4] {
[1.0, 1.0, 1.0, 1.0]
}
+fn ease_out_cubic(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ 1.0 - (1.0 - t).powi(3)
+}
+
+fn ease_out_back(t: f32) -> f32 {
+ let t = t.clamp(0.0, 1.0);
+ let c1 = 1.70158;
+ let c3 = c1 + 1.0;
+ let p = t - 1.0;
+ 1.0 + c3 * p * p * p + c1 * p * p
+}
+
+const POP_MIN_SCALE: f32 = 0.8;
+
+#[derive(Debug, Clone, Copy)]
+struct AnimSample {
+ alpha: f32,
+ offset: [f32; 2],
+ scale: f32,
+ /// Fraction of characters visible (typewriter); 1 for other styles.
+ reveal: f32,
+}
+
+const ANIM_REST: AnimSample = AnimSample {
+ alpha: 1.0,
+ offset: [0.0, 0.0],
+ scale: 1.0,
+ reveal: 1.0,
+};
+
+/// `progress` runs 0 → 1 toward fully visible for both edges: time since
+/// start over the enter duration, time until end over the exit duration.
+/// `direction` is +1 entering and -1 exiting so slides continue through the
+/// text's resting position (enter from below, exit above) instead of
+/// retracing themselves.
+fn sample_animation(
+ style: TextAnimation,
+ progress: f32,
+ direction: f32,
+ slide_px: f32,
+) -> AnimSample {
+ if progress >= 1.0 {
+ return ANIM_REST;
+ }
+ let eased = ease_out_cubic(progress);
+
+ match style {
+ TextAnimation::None => ANIM_REST,
+ TextAnimation::Fade => AnimSample {
+ alpha: eased,
+ ..ANIM_REST
+ },
+ TextAnimation::SlideUp => AnimSample {
+ alpha: eased,
+ offset: [0.0, direction * (1.0 - eased) * slide_px],
+ ..ANIM_REST
+ },
+ TextAnimation::SlideDown => AnimSample {
+ alpha: eased,
+ offset: [0.0, -direction * (1.0 - eased) * slide_px],
+ ..ANIM_REST
+ },
+ TextAnimation::Pop => AnimSample {
+ alpha: eased,
+ scale: POP_MIN_SCALE + (1.0 - POP_MIN_SCALE) * ease_out_back(progress),
+ ..ANIM_REST
+ },
+ TextAnimation::Typewriter => AnimSample {
+ reveal: progress,
+ ..ANIM_REST
+ },
+ }
+}
+
+fn edge_progress(elapsed: f64, duration: f64) -> f32 {
+ if duration <= 0.0 {
+ 1.0
+ } else {
+ (elapsed / duration).clamp(0.0, 1.0) as f32
+ }
+}
+
+/// Truncates to the first `ceil(reveal * chars)` characters on a char
+/// boundary, so the typewriter reveal never splits a code point.
+fn reveal_content(content: &str, reveal: f32) -> String {
+ if reveal >= 1.0 {
+ return content.to_string();
+ }
+ let total = content.chars().count();
+ let visible = ((total as f32) * reveal.max(0.0)).ceil() as usize;
+ content.chars().take(visible).collect()
+}
+
pub fn prepare_texts(
output_size: XY<u32>,
frame_time: f64,
@@ -77,30 +182,170 @@ pub fn prepare_texts(
let right = left + width;
let bottom = top + height;
- let fade_duration = segment.fade_duration.max(0.0);
- let opacity = if fade_duration > 0.0 {
- let time_since_start = (frame_time - segment.start).max(0.0);
- let time_until_end = (segment.end - frame_time).max(0.0);
+ let font_size = segment.font_size.clamp(MIN_FONT_SIZE, MAX_FONT_SIZE) * height_scale;
+ let slide_px = font_size * 0.5;
+
+ let enter = sample_animation(
+ segment.animation_in,
+ edge_progress(frame_time - segment.start, segment.animation_in_duration),
+ 1.0,
+ slide_px,
+ );
+ let exit = sample_animation(
+ segment.animation_out,
+ edge_progress(segment.end - frame_time, segment.animation_out_duration),
+ -1.0,
+ slide_px,
+ );
- let fade_in = (time_since_start / fade_duration).min(1.0);
- let fade_out = (time_until_end / fade_duration).min(1.0);
+ let opacity = segment.opacity.clamp(0.0, 1.0) * enter.alpha * exit.alpha;
+ if opacity <= 0.0 {
+ continue;
+ }
- (fade_in * fade_out) as f32
- } else {
- 1.0
- };
+ let reveal = enter.reveal.min(exit.reveal);
+ let content = reveal_content(&segment.content, reveal);
+ if content.is_empty() {
+ continue;
+ }
prepared.push(PreparedText {
- content: segment.content.clone(),
+ content,
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
font_family: segment.font_family.clone(),
- font_size: segment.font_size.clamp(MIN_FONT_SIZE, MAX_FONT_SIZE) * height_scale,
+ font_size,
font_weight: segment.font_weight,
italic: segment.italic,
opacity,
+ align: segment.align,
+ letter_spacing: segment.letter_spacing.clamp(-24.0, 240.0) * height_scale,
+ line_height: segment.line_height.clamp(0.5, 3.0),
+ shadow: segment.shadow.clamp(0.0, 1.0),
+ offset: [
+ enter.offset[0] + exit.offset[0],
+ enter.offset[1] + exit.offset[1],
+ ],
+ scale: (enter.scale * exit.scale).max(0.01),
});
}
prepared
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_project::{TextAnimation, TextLayout};
+
+ fn segment(animation_in: TextAnimation, animation_out: TextAnimation) -> TextSegment {
+ TextSegment {
+ start: 0.0,
+ end: 10.0,
+ track: 0,
+ enabled: true,
+ content: "Hello".to_string(),
+ center: XY::new(0.5, 0.5),
+ size: XY::new(0.35, 0.2),
+ font_family: "sans-serif".to_string(),
+ font_size: 48.0,
+ font_weight: 700.0,
+ italic: false,
+ color: "#ffffff".to_string(),
+ fade_duration: 0.15,
+ align: TextAlign::Center,
+ letter_spacing: 0.0,
+ line_height: 1.2,
+ opacity: 1.0,
+ shadow: 0.0,
+ animation_in,
+ animation_out,
+ animation_in_duration: 1.0,
+ animation_out_duration: 1.0,
+ layout: TextLayout::Overlay,
+ layout_transition: 0.5,
+ }
+ }
+
+ fn prepare_one(seg: TextSegment, time: f64) -> Option<PreparedText> {
+ prepare_texts(XY::new(1920, 1080), time, &[seg], &[])
+ .into_iter()
+ .next()
+ }
+
+ #[test]
+ fn resting_text_has_identity_animation_state() {
+ let text = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 5.0).unwrap();
+ assert_eq!(text.opacity, 1.0);
+ assert_eq!(text.offset, [0.0, 0.0]);
+ assert_eq!(text.scale, 1.0);
+ assert_eq!(text.content, "Hello");
+ }
+
+ #[test]
+ fn fade_ramps_in_and_out() {
+ let early = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 0.25).unwrap();
+ assert!(early.opacity > 0.0 && early.opacity < 1.0);
+
+ let late = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 9.75).unwrap();
+ assert!(late.opacity > 0.0 && late.opacity < 1.0);
+ }
+
+ #[test]
+ fn slide_up_enters_from_below_and_exits_above() {
+ let entering = prepare_one(
+ segment(TextAnimation::SlideUp, TextAnimation::SlideUp),
+ 0.25,
+ )
+ .unwrap();
+ assert!(entering.offset[1] > 0.0);
+
+ let exiting = prepare_one(
+ segment(TextAnimation::SlideUp, TextAnimation::SlideUp),
+ 9.75,
+ )
+ .unwrap();
+ assert!(exiting.offset[1] < 0.0);
+ }
+
+ #[test]
+ fn pop_scales_up_from_min() {
+ let entering = prepare_one(segment(TextAnimation::Pop, TextAnimation::None), 0.05).unwrap();
+ assert!(entering.scale < 1.0);
+ assert!(entering.scale >= POP_MIN_SCALE);
+ }
+
+ #[test]
+ fn typewriter_reveals_characters_over_time() {
+ let seg = segment(TextAnimation::Typewriter, TextAnimation::None);
+ let mid = prepare_one(seg.clone(), 0.5).unwrap();
+ assert!(mid.content.len() < "Hello".len());
+ assert!(mid.content.starts_with(&seg.content[..1]));
+ assert_eq!(mid.opacity, 1.0);
+
+ let done = prepare_one(seg, 2.0).unwrap();
+ assert_eq!(done.content, "Hello");
+ }
+
+ #[test]
+ fn typewriter_start_renders_nothing() {
+ assert!(
+ prepare_one(segment(TextAnimation::Typewriter, TextAnimation::None), 0.0).is_none()
+ );
+ }
+
+ #[test]
+ fn none_animation_shows_instantly() {
+ let text = prepare_one(segment(TextAnimation::None, TextAnimation::None), 0.0).unwrap();
+ assert_eq!(text.opacity, 1.0);
+ assert_eq!(text.scale, 1.0);
+ }
+
+ #[test]
+ fn segment_opacity_multiplies_animation_alpha() {
+ let mut seg = segment(TextAnimation::None, TextAnimation::None);
+ seg.opacity = 0.5;
+ let text = prepare_one(seg, 5.0).unwrap();
+ assert_eq!(text.opacity, 0.5);
+ }
+}