Skip to main content

alpha2_engine/
text.rs

1//! Text rendering for captions, text generators and layouts, rasterized by the portable text host.
2//!
3//! The engine draws text from host-registered font bytes, so browser preview and native export
4//! draw identical pixels given the same fonts. A host keeps one [`TextTextures`] beside its frame
5//! provider, calls [`TextTextures::prepare`] before each frame, and answers
6//! [`crate::FrameProvider::text`] from it.
7
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU64, Ordering};
12
13use alpha2_eval::{FrameDesc, GeneratorPlan, LayoutPlan, StepOp};
14use alpha2_layout::{
15    PictureSize, ShadowPixels, TextAnimation, TextBounds, TextDraw, animated_text_key, shaped_key,
16    text_draw,
17};
18use alpha2_model::{Generator, TextContent, TextStyle};
19use alpha2_render::{
20    CpuImage, CpuRenderer, CpuSource, RenderCacheKey, RenderError, RenderSize, Renderer,
21    SourceView, UploadTexture,
22};
23use alpha2_text::{ShapedText, TextFont, TextRasterError, TextRasterRequest, TextRasterizer};
24
25use crate::layout::PreparedLayout;
26
27pub(crate) fn picture(size: RenderSize) -> PictureSize {
28    PictureSize::new(size.width, size.height).expect("a render size is a picture size")
29}
30
31/// High 64 bits of a text cache key before the font set is added. Never zero, so text keys never
32/// collide with host source keys ([`RenderCacheKey::source`]).
33const TEXT_CACHE_DOMAIN: u64 = 0x6361_7074_696f_6e73;
34
35/// Next font set identity; every store and every added font takes a new one.
36static NEXT_FONT_SET: AtomicU64 = AtomicU64::new(1);
37
38/// Rasterized texts kept between frames, beyond those of the current frame.
39const RETAINED_TEXTS: usize = 16;
40
41/// Resolved layouts kept between frames, beyond those of the current frame.
42const RETAINED_LAYOUTS: usize = 8;
43
44/// Shaped texts kept for layout (LRU).
45const RETAINED_SHAPED: usize = 256;
46
47/// Where [`TextTextures`] keeps rasterized pixels: a GPU texture or CPU memory.
48pub trait TextUpload {
49    /// Stores tightly packed premultiplied sRGB-encoded RGBA of `size` as a text source.
50    ///
51    /// # Errors
52    /// Returns [`RenderError::InvalidImageData`] when `rgba8` does not match `size`, or an upload
53    /// failure.
54    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError>;
55}
56
57/// The pixels of one prepared text.
58#[derive(Debug)]
59pub struct TextPixels(TextStorage);
60
61#[derive(Debug)]
62enum TextStorage {
63    Gpu(UploadTexture),
64    Cpu(CpuSource),
65}
66
67impl TextPixels {
68    fn view(&self) -> SourceView<'_> {
69        match &self.0 {
70            TextStorage::Gpu(texture) => SourceView::from(texture),
71            TextStorage::Cpu(source) => SourceView::cpu(source),
72        }
73    }
74}
75
76impl TextUpload for Renderer {
77    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
78        self.upload_rgba8(size, rgba8)
79            .map(|texture| TextPixels(TextStorage::Gpu(texture)))
80    }
81}
82
83impl TextUpload for CpuRenderer {
84    fn upload_text(&self, size: RenderSize, rgba8: &[u8]) -> Result<TextPixels, RenderError> {
85        let picture = CpuImage::from_premultiplied_rgba8(size, rgba8)?;
86        Ok(TextPixels(TextStorage::Cpu(CpuSource::image(Arc::new(
87            picture,
88        )))))
89    }
90}
91
92/// One prepared text: its texture, pixel size and layout box position.
93#[derive(Clone, Copy, Debug)]
94pub struct TextTexture<'a> {
95    /// Premultiplied, sRGB-encoded RGBA, as every source texture.
96    pub texture: SourceView<'a>,
97    /// Width in pixels.
98    pub width: u32,
99    /// Height in pixels.
100    pub height: u32,
101    /// Per-axis pixel margin around the decorated text for overflowing ink (such as accents).
102    /// Placement ignores it, so such ink never moves the text.
103    pub margin: [u32; 2],
104    /// Result cache key for this texture, or `None` to bypass the cache. Like
105    /// [`crate::FrameProvider::source_key`], it promises the pixels depend on nothing else.
106    pub cache_key: Option<RenderCacheKey>,
107    /// Background boxes as a separate texture (with its cache key) when the text has both boxes
108    /// and shadows, since shadows lie between them. `texture` then holds no boxes.
109    pub background: Option<(SourceView<'a>, Option<RenderCacheKey>)>,
110    /// Glyph shadows, first on top, in picture pixels.
111    pub shadows: &'a [ShadowPixels],
112}
113
114/// Why text could not be prepared.
115#[derive(Clone, Debug, Eq, PartialEq)]
116#[non_exhaustive]
117pub enum TextError {
118    /// The text host refused: no fonts, a malformed font, or a text too large to rasterize.
119    Raster(TextRasterError),
120    /// The rasterized text could not be uploaded.
121    Render(RenderError),
122}
123
124impl fmt::Display for TextError {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Self::Raster(TextRasterError::NoFonts) => {
128                formatter.write_str("the project shows text, but no fonts were registered")
129            }
130            Self::Raster(error) => write!(formatter, "text failed: {error}"),
131            Self::Render(error) => write!(formatter, "text upload failed: {error}"),
132        }
133    }
134}
135
136impl std::error::Error for TextError {}
137
138struct TextEntry {
139    texture: Arc<TextPixels>,
140    background: Option<Arc<TextPixels>>,
141    shadows: Vec<ShadowPixels>,
142    /// Pixel identity: the static key, mixed with the animator state hash when animated, so
143    /// identical animation moments share pixels and cache entries.
144    content: u64,
145    width: u32,
146    height: u32,
147    margin: [u32; 2],
148    /// Where the layout box's top-left corner lies in the texture.
149    corner: [u32; 2],
150    last_used: u64,
151}
152
153/// A layout resolved at one size, with its text requests for re-rasterizing evicted texts.
154struct LayoutEntry {
155    prepared: Arc<PreparedLayout>,
156    requests: Vec<(u64, TextDraw)>,
157    last_used: u64,
158}
159
160struct ShapedEntry {
161    shaped: Arc<ShapedText>,
162    last_used: u64,
163}
164
165/// Fonts and the texts rasterized with them, keyed by content and render size.
166pub struct TextTextures {
167    rasterizer: TextRasterizer,
168    /// Font set identity from [`NEXT_FONT_SET`].
169    font_set: u64,
170    entries: HashMap<u64, TextEntry>,
171    /// Resolved layouts by [`layout_key`].
172    layouts: HashMap<u128, LayoutEntry>,
173    /// Texts shaped for layout, by [`shaped_key`].
174    shaped: HashMap<u64, ShapedEntry>,
175    /// Layout resolutions so far (a static layout resolves once).
176    resolves: u64,
177    frame: u64,
178}
179
180impl fmt::Debug for TextTextures {
181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        formatter
183            .debug_struct("TextTextures")
184            .field("fonts", &self.rasterizer.font_count())
185            .field("texts", &self.entries.len())
186            .field("layouts", &self.layouts.len())
187            .finish_non_exhaustive()
188    }
189}
190
191impl Default for TextTextures {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl TextTextures {
198    /// No fonts and no texts.
199    #[must_use]
200    pub fn new() -> Self {
201        Self {
202            rasterizer: TextRasterizer::empty(),
203            font_set: NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed),
204            entries: HashMap::new(),
205            layouts: HashMap::new(),
206            shaped: HashMap::new(),
207            resolves: 0,
208            frame: 0,
209        }
210    }
211
212    /// Appends an `OpenType` font to the fallback stack and drops rasterized texts.
213    ///
214    /// # Errors
215    /// Returns [`TextError::Raster`] for malformed font bytes.
216    pub fn add_font(
217        &mut self,
218        family: impl Into<String>,
219        bytes: impl Into<Arc<[u8]>>,
220        face_index: u32,
221    ) -> Result<(), TextError> {
222        self.rasterizer
223            .add_font(TextFont {
224                family: family.into(),
225                bytes: bytes.into(),
226                face_index,
227            })
228            .map_err(TextError::Raster)?;
229        self.entries.clear();
230        self.layouts.clear();
231        self.shaped.clear();
232        self.font_set = NEXT_FONT_SET.fetch_add(1, Ordering::Relaxed);
233        Ok(())
234    }
235
236    /// Fonts in the fallback stack.
237    #[must_use]
238    pub fn font_count(&self) -> usize {
239        self.rasterizer.font_count()
240    }
241
242    /// Requested families no registered font has, sorted
243    /// ([`alpha2_text::TextRasterizer::unmatched_families`]).
244    #[must_use]
245    pub fn unmatched_font_families(&self) -> Vec<String> {
246        self.rasterizer.unmatched_families()
247    }
248
249    /// Rasterizes and uploads every text and resolves every layout `frame` shows at `size` that is
250    /// not already held, evicting the least recently shown beyond a small number.
251    ///
252    /// # Errors
253    /// Returns [`TextError`] when a text cannot be rasterized or uploaded;
254    /// with no fonts registered, only if the frame shows one.
255    pub fn prepare(
256        &mut self,
257        renderer: &dyn TextUpload,
258        frame: &FrameDesc,
259        size: RenderSize,
260    ) -> Result<(), TextError> {
261        self.frame += 1;
262        let picture = picture(size);
263        for text in frame_texts(frame) {
264            let key = animated_text_key(text.content, text.style, picture, text.time);
265            if let Some(entry) = self.entries.get_mut(&key) {
266                entry.last_used = self.frame;
267                continue;
268            }
269            let content = text.content.text();
270            let frame_number = self.frame;
271            let fitted = alpha2_layout::fit_text(&content, text.style, picture, |request| {
272                self.shape(request, frame_number)
273            })
274            .map_err(TextError::Raster)?;
275            let mut draw = text_draw(&content, text.style, picture, key, fitted.font_pixels);
276            if !text.style.animators.is_empty() {
277                draw.animation = Some(TextAnimation {
278                    animators: alpha2_eval::sample_text_animators(&text.style.animators, text.time),
279                    runs: text.content.runs().to_vec(),
280                    time: text.time,
281                });
282            }
283            self.rasterize(renderer, key, &draw)?;
284        }
285        for (plan, time) in frame_layouts(frame) {
286            self.prepare_layout(renderer, plan, time, size)?;
287        }
288        while self.layouts.len() > RETAINED_LAYOUTS {
289            let Some(oldest) = self
290                .layouts
291                .iter()
292                .filter(|(_, entry)| entry.last_used < self.frame)
293                .min_by_key(|(_, entry)| entry.last_used)
294                .map(|(key, _)| *key)
295            else {
296                break;
297            };
298            self.layouts.remove(&oldest);
299        }
300        while self.entries.len() > RETAINED_TEXTS {
301            let Some(oldest) = self
302                .entries
303                .iter()
304                .filter(|(_, entry)| entry.last_used < self.frame)
305                .min_by_key(|(_, entry)| entry.last_used)
306                .map(|(key, _)| *key)
307            else {
308                break;
309            };
310            self.entries.remove(&oldest);
311        }
312        Ok(())
313    }
314
315    fn rasterize(
316        &mut self,
317        renderer: &dyn TextUpload,
318        key: u64,
319        draw: &TextDraw,
320    ) -> Result<(), TextError> {
321        let request = &draw.request;
322        let states = draw.states(&self.rasterizer).map_err(TextError::Raster)?;
323        let content = match &states {
324            // Identical animation moments share pixels; an all-identity state (hash 0) matches the
325            // static text.
326            Some((_, hash)) => {
327                let content = match *hash {
328                    0 => text_key_of(request),
329                    hash => mix_key(text_key_of(request), hash),
330                };
331                if let Some(held) = self.entries.values().find(|entry| entry.content == content) {
332                    let shared = TextEntry {
333                        texture: Arc::clone(&held.texture),
334                        background: held.background.clone(),
335                        shadows: draw.shadows.clone(),
336                        content,
337                        width: held.width,
338                        height: held.height,
339                        margin: held.margin,
340                        corner: held.corner,
341                        last_used: self.frame,
342                    };
343                    self.entries.insert(key, shared);
344                    return Ok(());
345                }
346                content
347            }
348            None => key,
349        };
350        let raster = match &states {
351            Some((states, hash)) if *hash != 0 => self
352                .rasterizer
353                .rasterize_animated(request, states)
354                .map_err(TextError::Raster)?,
355            _ => self
356                .rasterizer
357                .rasterize(request)
358                .map_err(TextError::Raster)?,
359        };
360        // Each text is rasterized once per key; keep no copy.
361        self.rasterizer.invalidate(key);
362        let texture_size = &raster.descriptor.texture;
363        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
364        let corner =
365            [raster.descriptor.layout_x, raster.descriptor.layout_y].map(|corner| corner as u32);
366        // The margin holds only overflowing ink and takes no part in placement.
367        let margin = corner.map(|corner| corner.saturating_sub(request.decoration_margin()));
368        let size =
369            RenderSize::new(texture_size.width, texture_size.height).map_err(TextError::Render)?;
370        let texture = renderer
371            .upload_text(size, &raster.pixels.rgba8)
372            .map_err(TextError::Render)?;
373        let background = raster
374            .background
375            .as_deref()
376            .map(|rgba8| renderer.upload_text(size, rgba8))
377            .transpose()
378            .map_err(TextError::Render)?;
379        // Pixels are `Send` on native targets, where hosts move the store between threads; wasm
380        // is single-threaded.
381        #[cfg_attr(target_arch = "wasm32", allow(clippy::arc_with_non_send_sync))]
382        let (texture, background) = (Arc::new(texture), background.map(Arc::new));
383        self.entries.insert(
384            key,
385            TextEntry {
386                texture,
387                background,
388                shadows: draw.shadows.clone(),
389                content,
390                width: texture_size.width,
391                height: texture_size.height,
392                margin,
393                corner,
394                last_used: self.frame,
395            },
396        );
397        Ok(())
398    }
399
400    /// Resolves `plan` at `time` and `size` and rasterizes its texts. A held layout only
401    /// re-rasterizes evicted texts.
402    fn prepare_layout(
403        &mut self,
404        renderer: &dyn TextUpload,
405        plan: &LayoutPlan,
406        time: alpha2_time::MediaTime,
407        size: RenderSize,
408    ) -> Result<(), TextError> {
409        let evaluated = plan.evaluate(time);
410        let key = layout_key(evaluated.key, size);
411        if let Some(entry) = self.layouts.get_mut(&key) {
412            entry.last_used = self.frame;
413            let requests = entry.requests.clone();
414            for (text, request) in &requests {
415                match self.entries.get_mut(text) {
416                    Some(held) => held.last_used = self.frame,
417                    None => self.rasterize(renderer, *text, request)?,
418                }
419            }
420            return Ok(());
421        }
422        self.resolves += 1;
423        let frame = self.frame;
424        let picture = picture(size);
425        let shaped =
426            alpha2_layout::shape_texts(&evaluated, picture, |request| self.shape(request, frame))
427                .map_err(TextError::Raster)?;
428        let mut resolved = alpha2_layout::resolve(&evaluated, picture, &shaped);
429        alpha2_layout::fit_texts(&evaluated, &mut resolved, picture, |request| {
430            self.shape(request, frame)
431        })
432        .map_err(TextError::Raster)?;
433        let (texts, requests) = alpha2_layout::layout_texts(&evaluated, &resolved, picture);
434        let mut boxes = Vec::with_capacity(texts.len());
435        for text in &texts {
436            boxes.push(match text {
437                None => None,
438                Some(text_key) => {
439                    let draw = &requests
440                        .iter()
441                        .find(|(key, _)| key == text_key)
442                        .expect("a request per text")
443                        .1;
444                    match self.entries.get_mut(text_key) {
445                        Some(held) => held.last_used = self.frame,
446                        None => self.rasterize(renderer, *text_key, draw)?,
447                    }
448                    let entry = &self.entries[text_key];
449                    Some(crate::layout::paint::TextBox {
450                        corner: entry.corner,
451                        size: [entry.width, entry.height],
452                    })
453                }
454            });
455        }
456        let items = crate::layout::paint::paint_list(&evaluated, &resolved, size, &boxes);
457        self.layouts.insert(
458            key,
459            LayoutEntry {
460                prepared: Arc::new(PreparedLayout { items, texts }),
461                requests,
462                last_used: self.frame,
463            },
464        );
465        Ok(())
466    }
467
468    fn shape(
469        &mut self,
470        request: &TextRasterRequest,
471        frame: u64,
472    ) -> Result<Arc<ShapedText>, TextRasterError> {
473        let key = shaped_key(request);
474        if let Some(entry) = self.shaped.get_mut(&key) {
475            entry.last_used = frame;
476            return Ok(Arc::clone(&entry.shaped));
477        }
478        let shaped = Arc::new(self.rasterizer.shape(request)?);
479        if self.shaped.len() >= RETAINED_SHAPED
480            && let Some(oldest) = self
481                .shaped
482                .iter()
483                .min_by_key(|(_, entry)| entry.last_used)
484                .map(|(key, _)| *key)
485        {
486            self.shaped.remove(&oldest);
487        }
488        self.shaped.insert(
489            key,
490            ShapedEntry {
491                shaped: Arc::clone(&shaped),
492                last_used: frame,
493            },
494        );
495        Ok(shaped)
496    }
497
498    /// Layout resolutions so far, held or not.
499    #[cfg(test)]
500    #[must_use]
501    pub(crate) const fn layout_resolves(&self) -> u64 {
502        self.resolves
503    }
504
505    /// The prepared layout with `key`, as [`layout_key`] names it.
506    #[must_use]
507    pub fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
508        self.layouts
509            .get(&key)
510            .map(|entry| Arc::clone(&entry.prepared))
511    }
512
513    /// [`crate::measure_layout`] with these fonts.
514    ///
515    /// # Errors
516    /// Returns [`TextError::Raster`] as [`Self::prepare`] would.
517    pub fn measure_layout(
518        &self,
519        root: &alpha2_model::LayoutNode,
520        time: alpha2_time::MediaTime,
521        size: RenderSize,
522        canvas: (u32, u32),
523    ) -> Result<crate::LayoutBounds, TextError> {
524        crate::measure_layout(&self.rasterizer, root, time, picture(size), canvas)
525            .map_err(TextError::Raster)
526    }
527
528    /// [`Self::prepare`] for `project` at `time`; skips evaluation when the project draws no text
529    /// ([`crate::EngineProject::draws_text`]).
530    ///
531    /// # Errors
532    /// Returns [`crate::EngineError::Evaluate`] or
533    /// [`crate::EngineError::Text`].
534    pub fn prepare_at(
535        &mut self,
536        renderer: &dyn TextUpload,
537        project: &crate::EngineProject,
538        time: alpha2_time::MediaTime,
539        size: RenderSize,
540    ) -> Result<(), crate::EngineError> {
541        if !project.draws_text() {
542            return Ok(());
543        }
544        let frame = project.evaluate(time)?;
545        self.prepare(renderer, &frame, size)
546            .map_err(crate::EngineError::Text)
547    }
548
549    /// [`crate::measure_text`] with these fonts.
550    ///
551    /// # Errors
552    /// Returns [`TextError::Raster`] as [`Self::prepare`] would for the text.
553    pub fn measure(
554        &self,
555        text: &str,
556        style: &TextStyle,
557        size: RenderSize,
558    ) -> Result<TextBounds, TextError> {
559        crate::measure_text(&self.rasterizer, text, style, picture(size)).map_err(TextError::Raster)
560    }
561
562    /// The prepared text with `key`, as [`crate::text_key`] names it.
563    #[must_use]
564    pub fn get(&self, key: u64) -> Option<TextTexture<'_>> {
565        self.entries.get(&key).map(|entry| TextTexture {
566            texture: entry.texture.view(),
567            width: entry.width,
568            height: entry.height,
569            margin: entry.margin,
570            cache_key: Some(self.cache_key(entry.content)),
571            background: entry.background.as_ref().map(|background| {
572                (
573                    background.view(),
574                    Some(self.background_cache_key(entry.content)),
575                )
576            }),
577            shadows: &entry.shadows,
578        })
579    }
580
581    /// Result cache key of text `key`: font set and domain in the high half, text in the low.
582    fn cache_key(&self, key: u64) -> RenderCacheKey {
583        let high = TEXT_CACHE_DOMAIN ^ self.font_set;
584        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
585    }
586
587    /// [`Self::cache_key`] in a separate domain for the background plane.
588    fn background_cache_key(&self, key: u64) -> RenderCacheKey {
589        let high = (TEXT_CACHE_DOMAIN ^ self.font_set) ^ (1 << 62);
590        RenderCacheKey::from_value((u128::from(high) << 64) | u128::from(key))
591    }
592}
593
594/// A text a frame may draw, with the time its animators are keyed in.
595#[derive(Copy, Clone, Debug)]
596pub(crate) struct FrameText<'f> {
597    pub(crate) content: &'f TextContent,
598    pub(crate) style: &'f TextStyle,
599    pub(crate) time: alpha2_time::MediaTime,
600}
601
602/// Every text `frame` may draw: captions, then text generators of drawn clips. Duplicates repeat.
603pub(crate) fn frame_texts<'f>(frame: &'f FrameDesc<'_>) -> impl Iterator<Item = FrameText<'f>> {
604    let captions = frame.captions.iter().map(|caption| FrameText {
605        content: caption.text,
606        style: caption.style,
607        time: caption.local_time,
608    });
609    let generators = frame
610        .visual
611        .iter()
612        .filter(|clip| frame.draws(clip))
613        .flat_map(|clip| {
614            let own = clip
615                .generator
616                .map(|generator| (generator, clip.source_time));
617            let steps = clip
618                .composition
619                .iter()
620                .chain(&clip.source_composition)
621                .flat_map(|composition| {
622                    let time = composition.time();
623                    composition
624                        .plan()
625                        .steps
626                        .iter()
627                        .filter_map(move |step| match &step.op {
628                            StepOp::Generator {
629                                generator, start, ..
630                            } => Some((generator, generator_time(step.time(time), *start))),
631                            _ => None,
632                        })
633                });
634            own.into_iter().chain(steps)
635        })
636        .filter_map(|(generator, time)| match generator {
637            Generator::Text { text, style } => Some(FrameText {
638                content: text,
639                style,
640                time,
641            }),
642            _ => None,
643        });
644    captions.chain(generators)
645}
646
647/// A composition generator step's picture time: step time plus start.
648pub(crate) const fn generator_time(
649    step: alpha2_time::MediaTime,
650    start: alpha2_time::MediaTime,
651) -> alpha2_time::MediaTime {
652    alpha2_time::MediaTime(step.ticks().saturating_add(start.ticks()))
653}
654
655/// `key` mixed with an animation's state `hash`: FNV-1a, never zero.
656fn mix_key(key: u64, hash: u64) -> u64 {
657    let mut mixed = key;
658    for byte in hash.to_le_bytes() {
659        mixed = (mixed ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3);
660    }
661    mixed.max(1)
662}
663
664/// Key for `request` without animators, from every field but the content version.
665fn text_key_of(request: &TextRasterRequest) -> u64 {
666    alpha2_layout::layout_text_key(
667        &TextRasterRequest {
668            content_version: 1,
669            ..request.clone()
670        },
671        &[],
672        &[],
673    )
674}
675
676/// A host's frame provider combined with its text store.
677pub struct FramesWithText<'a> {
678    frames: &'a dyn crate::FrameProvider,
679    texts: &'a TextTextures,
680}
681
682impl<'a> FramesWithText<'a> {
683    /// `frames` with the texts `texts` holds.
684    #[must_use]
685    pub fn new(frames: &'a dyn crate::FrameProvider, texts: &'a TextTextures) -> Self {
686        Self { frames, texts }
687    }
688}
689
690impl crate::FrameProvider for FramesWithText<'_> {
691    fn texture_for(
692        &self,
693        source: &alpha2_media::SourceId,
694        time: alpha2_time::MediaTime,
695    ) -> Option<SourceView<'_>> {
696        self.frames.texture_for(source, time)
697    }
698
699    fn pending_source_work(
700        &self,
701        source: &alpha2_media::SourceId,
702        time: alpha2_time::MediaTime,
703    ) -> Option<&alpha2_render::PendingSourceWork> {
704        self.frames.pending_source_work(source, time)
705    }
706
707    fn source_key(
708        &self,
709        source: &alpha2_media::SourceId,
710        time: alpha2_time::MediaTime,
711    ) -> Option<alpha2_render::RenderCacheKey> {
712        self.frames.source_key(source, time)
713    }
714
715    fn text(&self, key: u64) -> Option<TextTexture<'_>> {
716        self.texts.get(key)
717    }
718
719    fn layout(&self, key: u128) -> Option<Arc<PreparedLayout>> {
720        self.texts.layout(key)
721    }
722}
723
724/// Every layout `frame` may draw, with its picture time.
725pub(crate) fn frame_layouts<'f>(
726    frame: &'f FrameDesc<'_>,
727) -> impl Iterator<Item = (&'f LayoutPlan, alpha2_time::MediaTime)> {
728    frame
729        .visual
730        .iter()
731        .filter(|clip| frame.draws(clip))
732        .flat_map(|clip| {
733            let own = clip
734                .plan
735                .and_then(GeneratorPlan::layout)
736                .map(|plan| (plan, clip.source_time));
737            let steps = clip
738                .composition
739                .iter()
740                .chain(&clip.source_composition)
741                .flat_map(|composition| {
742                    let time = composition.time();
743                    composition
744                        .plan()
745                        .steps
746                        .iter()
747                        .filter_map(move |step| match &step.op {
748                            StepOp::Generator {
749                                plan: Some(plan),
750                                start,
751                                ..
752                            } => plan.layout().map(|plan| {
753                                (
754                                    plan,
755                                    alpha2_time::MediaTime(
756                                        step.time(time).ticks().saturating_add(start.ticks()),
757                                    ),
758                                )
759                            }),
760                            _ => None,
761                        })
762                });
763            own.into_iter().chain(steps)
764        })
765}
766
767/// A layout's identity at a render size. Equal keys draw alike with the same fonts.
768#[must_use]
769pub fn layout_key(evaluated: u128, size: RenderSize) -> u128 {
770    let mut hash = alpha2_geometry::StableHash::new();
771    hash.bytes(b"layout");
772    hash.bytes(&evaluated.to_le_bytes());
773    hash.u32(size.width);
774    hash.u32(size.height);
775    hash.finish()
776}