Skip to main content

tilo_render_protocol/
scene.rs

1//! A vello [`Encoding`] as bytes, with fonts and images by id.
2//!
3//! The streams go over as they are — path tags, path data, draw tags, draw
4//! data, transforms and styles are already plain words — and so do the late
5//! bound resources, except that a glyph run names its font and an image patch
6//! its image by the [`FontId`]/[`ImageId`] the app registered them under.
7//! Decoding reads every byte once into a fresh [`Encoding`]: a record in
8//! shared memory that the app keeps writing to is copied, not revisited, so
9//! what [`crate::validate`] checks is what the GPU later sees.
10//!
11//! Layout, all little-endian, every section padded to four bytes:
12//!
13//! ```text
14//! counts      16 × u32  path tags, path data, draw tags, draw data,
15//!                       transforms, styles, patches, color stops, glyphs,
16//!                       glyph runs, coords, n_paths, n_path_segments,
17//!                       n_clips, n_open_clips, flags
18//! path tags   u8 each
19//! path data   u32 each
20//! draw tags   u32 each
21//! draw data   u32 each
22//! transforms  6 × f32 each
23//! styles      2 × u32 each
24//! patches     5 × u32 each: kind, then its fields
25//! stops       f32 offset, u8 colour space, u8 missing, u16 0, 4 × f32
26//! glyphs      u32 id, f32 x, f32 y
27//! glyph runs  see `write_glyph_run`
28//! coords      i16 each
29//! ```
30
31use peniko::color::{ColorSpaceTag, DynamicColor, Flags, Missing};
32use peniko::kurbo::{Cap, Diagonal2, Join, Stroke};
33use peniko::{ColorStop, Extend, Fill, FontData, ImageData, Style as BrushStyle};
34use vello_encoding::{
35    DrawTag, Encoding, FontEmbolden, Glyph, GlyphRun, Patch, PathTag, StreamOffsets, Style,
36    Transform,
37};
38
39use crate::bytes::{Reader, Writer};
40use crate::{FontId, ImageId, WireError};
41
42/// What an app's encoder asks of its resource registry: the id a font or an
43/// image goes by on this connection, registering it on first sight.
44pub trait ResourceIds {
45    /// The id `font` is registered under.
46    fn font(&mut self, font: &FontData) -> Result<FontId, WireError>;
47
48    /// The id `image` is registered under.
49    fn image(&mut self, image: &ImageData) -> Result<ImageId, WireError>;
50}
51
52/// What the service's decoder needs: the font and image an id stands for on
53/// this connection. `None` for an id the connection never registered.
54pub trait Resources {
55    fn font(&self, id: FontId) -> Option<FontData>;
56    fn image(&self, id: ImageId) -> Option<ImageData>;
57}
58
59const PATCH_RAMP: u32 = 0;
60const PATCH_GLYPH_RUN: u32 = 1;
61const PATCH_IMAGE: u32 = 2;
62
63const RUN_GLYPH_TRANSFORM: u32 = 1;
64const RUN_BRUSH_TRANSFORM: u32 = 2;
65const RUN_HINT: u32 = 4;
66
67const STYLE_FILL_NONZERO: u32 = 0;
68const STYLE_FILL_EVEN_ODD: u32 = 1;
69const STYLE_STROKE: u32 = 2;
70
71/// Dashes one stroked glyph run may carry.
72pub const MAX_DASHES: usize = 64;
73
74const PATCH_BYTES: usize = 20;
75const STOP_BYTES: usize = 24;
76const GLYPH_BYTES: usize = 12;
77/// The fixed part of a glyph run; a stroke's dashes follow it.
78const RUN_FIXED_BYTES: usize =
79    4 + 24 + 4 + 24 + 24 + 4 + 8 + 8 + 4 + 8 + 8 + 8 + 8 + 24 + 4 + 8 + 4 + 8 + 8 + 4;
80
81/// Append `encoding` to `out`.
82///
83/// # Errors
84///
85/// When a resource cannot be registered or a count does not fit the wire.
86pub fn encode(
87    encoding: &Encoding,
88    ids: &mut dyn ResourceIds,
89    out: &mut Vec<u8>,
90) -> Result<(), WireError> {
91    let res = &encoding.resources;
92    let mut w = Writer::new(out);
93    for count in [
94        encoding.path_tags.len(),
95        encoding.path_data.len(),
96        encoding.draw_tags.len(),
97        encoding.draw_data.len(),
98        encoding.transforms.len(),
99        encoding.styles.len(),
100        res.patches.len(),
101        res.color_stops.len(),
102        res.glyphs.len(),
103        res.glyph_runs.len(),
104        res.normalized_coords.len(),
105    ] {
106        w.count(count)?;
107    }
108    for value in [
109        encoding.n_paths,
110        encoding.n_path_segments,
111        encoding.n_clips,
112        encoding.n_open_clips,
113        encoding.flags,
114    ] {
115        w.u32(value);
116    }
117    for tag in &encoding.path_tags {
118        w.u8(tag.0);
119    }
120    w.align4(encoding.path_tags.len());
121    for word in &encoding.path_data {
122        w.u32(*word);
123    }
124    for tag in &encoding.draw_tags {
125        w.u32(tag.0);
126    }
127    for word in &encoding.draw_data {
128        w.u32(*word);
129    }
130    for transform in &encoding.transforms {
131        write_transform(&mut w, transform);
132    }
133    for style in &encoding.styles {
134        w.u32(style.flags_and_miter_limit);
135        w.f32(style.line_width);
136    }
137    for patch in &res.patches {
138        match patch {
139            Patch::Ramp {
140                draw_data_offset,
141                stops,
142                extend,
143            } => {
144                w.u32(PATCH_RAMP);
145                w.count(*draw_data_offset)?;
146                w.count(stops.start)?;
147                w.count(stops.end)?;
148                w.u32(*extend as u32);
149            }
150            Patch::GlyphRun { index } => {
151                w.u32(PATCH_GLYPH_RUN);
152                w.count(*index)?;
153                w.u32(0);
154                w.u32(0);
155                w.u32(0);
156            }
157            Patch::Image {
158                draw_data_offset,
159                image,
160            } => {
161                let id = ids.image(image)?;
162                w.u32(PATCH_IMAGE);
163                w.count(*draw_data_offset)?;
164                w.u32(id.0);
165                w.u32(0);
166                w.u32(0);
167            }
168        }
169    }
170    for stop in &res.color_stops {
171        write_stop(&mut w, stop);
172    }
173    for glyph in &res.glyphs {
174        w.u32(glyph.id);
175        w.f32(glyph.x);
176        w.f32(glyph.y);
177    }
178    for run in &res.glyph_runs {
179        let font = ids.font(&run.font)?;
180        write_glyph_run(&mut w, run, font)?;
181    }
182    for coord in &res.normalized_coords {
183        w.i16(*coord);
184    }
185    w.align4(res.normalized_coords.len().saturating_mul(2));
186    Ok(())
187}
188
189fn write_transform(w: &mut Writer<'_>, transform: &Transform) {
190    for value in transform.matrix {
191        w.f32(value);
192    }
193    for value in transform.translation {
194        w.f32(value);
195    }
196}
197
198fn write_stop(w: &mut Writer<'_>, stop: &ColorStop) {
199    w.f32(stop.offset);
200    w.u8(stop.color.cs as u8);
201    let missing = stop.color.flags.missing();
202    let mut bits = 0_u8;
203    for ix in 0..4_u8 {
204        if missing.contains(usize::from(ix)) {
205            bits |= 1 << ix;
206        }
207    }
208    w.u8(bits);
209    w.u16(0);
210    for value in stop.color.components {
211        w.f32(value);
212    }
213}
214
215fn write_glyph_run(w: &mut Writer<'_>, run: &GlyphRun, font: FontId) -> Result<(), WireError> {
216    w.u32(font.0);
217    write_transform(w, &run.transform);
218    let mut flags = 0;
219    if run.glyph_transform.is_some() {
220        flags |= RUN_GLYPH_TRANSFORM;
221    }
222    if run.brush_transform.is_some() {
223        flags |= RUN_BRUSH_TRANSFORM;
224    }
225    if run.hint {
226        flags |= RUN_HINT;
227    }
228    w.u32(flags);
229    write_transform(w, &run.glyph_transform.unwrap_or(Transform::IDENTITY));
230    write_transform(w, &run.brush_transform.unwrap_or(Transform::IDENTITY));
231    w.f32(run.font_size);
232    w.f64(run.font_embolden.amount.xx);
233    w.f64(run.font_embolden.amount.yy);
234    w.u32(join_bits(run.font_embolden.join));
235    w.f64(run.font_embolden.miter_limit);
236    w.f64(run.font_embolden.tolerance);
237    w.count(run.normalized_coords.start)?;
238    w.count(run.normalized_coords.end)?;
239    w.count(run.glyphs.start)?;
240    w.count(run.glyphs.end)?;
241    let offsets = &run.stream_offsets;
242    for offset in [
243        offsets.path_tags,
244        offsets.path_data,
245        offsets.draw_tags,
246        offsets.draw_data,
247        offsets.transforms,
248        offsets.styles,
249    ] {
250        w.count(offset)?;
251    }
252    match &run.style {
253        BrushStyle::Fill(Fill::NonZero) => write_stroke(w, STYLE_FILL_NONZERO, &Stroke::new(0.0)),
254        BrushStyle::Fill(Fill::EvenOdd) => write_stroke(w, STYLE_FILL_EVEN_ODD, &Stroke::new(0.0)),
255        BrushStyle::Stroke(stroke) => write_stroke(w, STYLE_STROKE, stroke),
256    }
257}
258
259fn write_stroke(w: &mut Writer<'_>, kind: u32, stroke: &Stroke) -> Result<(), WireError> {
260    w.u32(kind);
261    w.f64(stroke.width);
262    w.u32(
263        join_bits(stroke.join)
264            | (cap_bits(stroke.start_cap) << 8)
265            | (cap_bits(stroke.end_cap) << 16),
266    );
267    w.f64(stroke.miter_limit);
268    w.f64(stroke.dash_offset);
269    if stroke.dash_pattern.len() > MAX_DASHES {
270        return Err(WireError::OverLimit("dashes of a stroked glyph run"));
271    }
272    w.count(stroke.dash_pattern.len())?;
273    for dash in &stroke.dash_pattern {
274        w.f64(*dash);
275    }
276    Ok(())
277}
278
279fn join_bits(join: Join) -> u32 {
280    match join {
281        Join::Bevel => 0,
282        Join::Miter => 1,
283        Join::Round => 2,
284    }
285}
286
287fn cap_bits(cap: Cap) -> u32 {
288    match cap {
289        Cap::Butt => 0,
290        Cap::Square => 1,
291        Cap::Round => 2,
292    }
293}
294
295fn join_from(bits: u32) -> Result<Join, WireError> {
296    match bits {
297        0 => Ok(Join::Bevel),
298        1 => Ok(Join::Miter),
299        2 => Ok(Join::Round),
300        _ => Err(WireError::Malformed("join")),
301    }
302}
303
304fn cap_from(bits: u32) -> Result<Cap, WireError> {
305    match bits {
306        0 => Ok(Cap::Butt),
307        1 => Ok(Cap::Square),
308        2 => Ok(Cap::Round),
309        _ => Err(WireError::Malformed("cap")),
310    }
311}
312
313fn extend_from(bits: u32) -> Result<Extend, WireError> {
314    match bits {
315        0 => Ok(Extend::Pad),
316        1 => Ok(Extend::Repeat),
317        2 => Ok(Extend::Reflect),
318        _ => Err(WireError::Malformed("extend")),
319    }
320}
321
322fn color_space_from(bits: u8) -> Result<ColorSpaceTag, WireError> {
323    Ok(match bits {
324        0 => ColorSpaceTag::Srgb,
325        1 => ColorSpaceTag::LinearSrgb,
326        2 => ColorSpaceTag::Lab,
327        3 => ColorSpaceTag::Lch,
328        4 => ColorSpaceTag::Hsl,
329        5 => ColorSpaceTag::Hwb,
330        6 => ColorSpaceTag::Oklab,
331        7 => ColorSpaceTag::Oklch,
332        8 => ColorSpaceTag::DisplayP3,
333        9 => ColorSpaceTag::A98Rgb,
334        10 => ColorSpaceTag::ProphotoRgb,
335        11 => ColorSpaceTag::Rec2020,
336        12 => ColorSpaceTag::AcesCg,
337        13 => ColorSpaceTag::XyzD50,
338        14 => ColorSpaceTag::XyzD65,
339        15 => ColorSpaceTag::Aces2065_1,
340        _ => return Err(WireError::Malformed("colour space")),
341    })
342}
343
344/// The counts at the head of an encoding, as read.
345struct Counts {
346    path_tags: usize,
347    path_data: usize,
348    draw_tags: usize,
349    draw_data: usize,
350    transforms: usize,
351    styles: usize,
352    patches: usize,
353    stops: usize,
354    glyphs: usize,
355    runs: usize,
356    coords: usize,
357}
358
359/// Read one encoding written by [`encode`], resolving its ids through
360/// `resources`. Only the record's shape is checked here (every count backed
361/// by bytes, every enumeration known, every id registered); whether it is
362/// safe to draw is [`crate::validate::validate`]'s question.
363pub fn decode(bytes: &[u8], resources: &dyn Resources) -> Result<Encoding, WireError> {
364    let mut r = Reader::new(bytes);
365    let mut header = [0_usize; 11];
366    for slot in &mut header {
367        *slot = usize::try_from(r.u32()?).map_err(|_| WireError::Overflow)?;
368    }
369    let [
370        path_tags,
371        path_data,
372        draw_tags,
373        draw_data,
374        transforms,
375        styles,
376        patches,
377        stops,
378        glyphs,
379        runs,
380        coords,
381    ] = header;
382    let counts = Counts {
383        path_tags,
384        path_data,
385        draw_tags,
386        draw_data,
387        transforms,
388        styles,
389        patches,
390        stops,
391        glyphs,
392        runs,
393        coords,
394    };
395    let mut encoding = Encoding::new();
396    encoding.n_paths = r.u32()?;
397    encoding.n_path_segments = r.u32()?;
398    encoding.n_clips = r.u32()?;
399    encoding.n_open_clips = r.u32()?;
400    encoding.flags = r.u32()?;
401    check_backed(&counts, r.remaining())?;
402    read_streams(&mut r, &counts, &mut encoding)?;
403    read_resources(&mut r, &counts, resources, &mut encoding)?;
404    if !r.is_empty() {
405        return Err(WireError::Malformed("bytes after the encoding"));
406    }
407    Ok(encoding)
408}
409
410/// Every count backed by bytes before anything is reserved, so a hostile
411/// header cannot make the service allocate what the record does not carry.
412fn check_backed(counts: &Counts, remaining: usize) -> Result<(), WireError> {
413    let fixed = [
414        (counts.path_tags, 1),
415        (counts.path_data, 4),
416        (counts.draw_tags, 4),
417        (counts.draw_data, 4),
418        (counts.transforms, 24),
419        (counts.styles, 8),
420        (counts.patches, PATCH_BYTES),
421        (counts.stops, STOP_BYTES),
422        (counts.glyphs, GLYPH_BYTES),
423        (counts.runs, RUN_FIXED_BYTES),
424        (counts.coords, 2),
425    ];
426    let mut total = 0_usize;
427    for (count, size) in fixed {
428        let bytes = count.checked_mul(size).ok_or(WireError::Overflow)?;
429        total = total.checked_add(bytes).ok_or(WireError::Overflow)?;
430    }
431    if total > remaining {
432        return Err(WireError::Truncated);
433    }
434    Ok(())
435}
436
437fn read_transform(r: &mut Reader<'_>) -> Result<Transform, WireError> {
438    Ok(Transform {
439        matrix: [r.f32()?, r.f32()?, r.f32()?, r.f32()?],
440        translation: [r.f32()?, r.f32()?],
441    })
442}
443
444fn read_streams(
445    r: &mut Reader<'_>,
446    counts: &Counts,
447    encoding: &mut Encoding,
448) -> Result<(), WireError> {
449    encoding.path_tags = r
450        .take(counts.path_tags)?
451        .iter()
452        .map(|tag| PathTag(*tag))
453        .collect();
454    r.align4(counts.path_tags)?;
455    encoding.path_data = (0..counts.path_data)
456        .map(|_| r.u32())
457        .collect::<Result<_, _>>()?;
458    encoding.draw_tags = (0..counts.draw_tags)
459        .map(|_| r.u32().map(DrawTag))
460        .collect::<Result<_, _>>()?;
461    encoding.draw_data = (0..counts.draw_data)
462        .map(|_| r.u32())
463        .collect::<Result<_, _>>()?;
464    encoding.transforms = (0..counts.transforms)
465        .map(|_| read_transform(r))
466        .collect::<Result<_, _>>()?;
467    encoding.styles = (0..counts.styles)
468        .map(|_| {
469            Ok(Style {
470                flags_and_miter_limit: r.u32()?,
471                line_width: r.f32()?,
472            })
473        })
474        .collect::<Result<_, WireError>>()?;
475    Ok(())
476}
477
478fn index(value: u32) -> Result<usize, WireError> {
479    usize::try_from(value).map_err(|_| WireError::Overflow)
480}
481
482fn read_resources(
483    r: &mut Reader<'_>,
484    counts: &Counts,
485    resources: &dyn Resources,
486    encoding: &mut Encoding,
487) -> Result<(), WireError> {
488    let res = &mut encoding.resources;
489    res.patches = (0..counts.patches)
490        .map(|_| read_patch(r, resources))
491        .collect::<Result<_, _>>()?;
492    res.color_stops = (0..counts.stops)
493        .map(|_| read_stop(r))
494        .collect::<Result<_, _>>()?;
495    res.glyphs = (0..counts.glyphs)
496        .map(|_| {
497            Ok(Glyph {
498                id: r.u32()?,
499                x: r.f32()?,
500                y: r.f32()?,
501            })
502        })
503        .collect::<Result<_, WireError>>()?;
504    res.glyph_runs = (0..counts.runs)
505        .map(|_| read_glyph_run(r, resources))
506        .collect::<Result<_, _>>()?;
507    res.normalized_coords = (0..counts.coords)
508        .map(|_| r.i16())
509        .collect::<Result<_, _>>()?;
510    r.align4(counts.coords.saturating_mul(2))?;
511    Ok(())
512}
513
514fn read_patch(r: &mut Reader<'_>, resources: &dyn Resources) -> Result<Patch, WireError> {
515    let kind = r.u32()?;
516    let [w0, w1, w2, w3] = [r.u32()?, r.u32()?, r.u32()?, r.u32()?];
517    match kind {
518        PATCH_RAMP => Ok(Patch::Ramp {
519            draw_data_offset: index(w0)?,
520            stops: index(w1)?..index(w2)?,
521            extend: extend_from(w3)?,
522        }),
523        PATCH_GLYPH_RUN if (w1, w2, w3) == (0, 0, 0) => Ok(Patch::GlyphRun { index: index(w0)? }),
524        PATCH_IMAGE if (w2, w3) == (0, 0) => Ok(Patch::Image {
525            draw_data_offset: index(w0)?,
526            image: resources
527                .image(ImageId(w1))
528                .ok_or(WireError::UnknownResource("an image"))?,
529        }),
530        _ => Err(WireError::Malformed("patch")),
531    }
532}
533
534fn read_stop(r: &mut Reader<'_>) -> Result<ColorStop, WireError> {
535    let offset = r.f32()?;
536    let cs = color_space_from(r.u8()?)?;
537    let bits = r.u8()?;
538    if bits & !0xf != 0 || r.u16()? != 0 {
539        return Err(WireError::Malformed("colour stop"));
540    }
541    let mut missing = Missing::EMPTY;
542    for ix in 0..4_u8 {
543        if bits & (1 << ix) != 0 {
544            missing.insert(usize::from(ix));
545        }
546    }
547    let components = [r.f32()?, r.f32()?, r.f32()?, r.f32()?];
548    Ok(ColorStop {
549        offset,
550        color: DynamicColor {
551            cs,
552            flags: Flags::from_missing(missing),
553            components,
554        },
555    })
556}
557
558fn read_glyph_run(r: &mut Reader<'_>, resources: &dyn Resources) -> Result<GlyphRun, WireError> {
559    let font = resources
560        .font(FontId(r.u32()?))
561        .ok_or(WireError::UnknownResource("a font"))?;
562    let transform = read_transform(r)?;
563    let flags = r.u32()?;
564    if flags & !(RUN_GLYPH_TRANSFORM | RUN_BRUSH_TRANSFORM | RUN_HINT) != 0 {
565        return Err(WireError::Malformed("glyph run flags"));
566    }
567    let glyph_transform = read_transform(r)?;
568    let brush_transform = read_transform(r)?;
569    let font_size = r.f32()?;
570    let amount = Diagonal2 {
571        xx: r.f64()?,
572        yy: r.f64()?,
573    };
574    let embolden = FontEmbolden::new(amount)
575        .with_join(join_from(r.u32()?)?)
576        .with_miter_limit(r.f64()?)
577        .with_tolerance(r.f64()?);
578    let normalized_coords = index(r.u32()?)?..index(r.u32()?)?;
579    let glyphs = index(r.u32()?)?..index(r.u32()?)?;
580    let stream_offsets = StreamOffsets {
581        path_tags: index(r.u32()?)?,
582        path_data: index(r.u32()?)?,
583        draw_tags: index(r.u32()?)?,
584        draw_data: index(r.u32()?)?,
585        transforms: index(r.u32()?)?,
586        styles: index(r.u32()?)?,
587    };
588    let style = read_style(r)?;
589    Ok(GlyphRun {
590        font,
591        transform,
592        glyph_transform: (flags & RUN_GLYPH_TRANSFORM != 0).then_some(glyph_transform),
593        brush_transform: (flags & RUN_BRUSH_TRANSFORM != 0).then_some(brush_transform),
594        font_size,
595        font_embolden: embolden,
596        hint: flags & RUN_HINT != 0,
597        normalized_coords,
598        style,
599        glyphs,
600        stream_offsets,
601        // The wire carries outlines' glyphs only.
602        text: None,
603    })
604}
605
606fn read_style(r: &mut Reader<'_>) -> Result<BrushStyle, WireError> {
607    let kind = r.u32()?;
608    let width = r.f64()?;
609    let bits = r.u32()?;
610    let miter_limit = r.f64()?;
611    let dash_offset = r.f64()?;
612    let dashes = r.count(8)?;
613    if dashes > MAX_DASHES {
614        return Err(WireError::OverLimit("dashes of a stroked glyph run"));
615    }
616    let pattern = (0..dashes)
617        .map(|_| r.f64())
618        .collect::<Result<Vec<_>, _>>()?;
619    if bits & !0x00ff_ffff != 0 {
620        return Err(WireError::Malformed("stroke"));
621    }
622    match kind {
623        STYLE_FILL_NONZERO | STYLE_FILL_EVEN_ODD => {
624            if dashes != 0 {
625                return Err(WireError::Malformed("a fill with dashes"));
626            }
627            Ok(BrushStyle::Fill(if kind == STYLE_FILL_NONZERO {
628                Fill::NonZero
629            } else {
630                Fill::EvenOdd
631            }))
632        }
633        STYLE_STROKE => {
634            let mut stroke = Stroke::new(width)
635                .with_join(join_from(bits & 0xff)?)
636                .with_start_cap(cap_from((bits >> 8) & 0xff)?)
637                .with_end_cap(cap_from((bits >> 16) & 0xff)?)
638                .with_miter_limit(miter_limit);
639            if !pattern.is_empty() {
640                stroke = stroke.with_dashes(dash_offset, pattern);
641            }
642            Ok(BrushStyle::Stroke(stroke))
643        }
644        _ => Err(WireError::Malformed("glyph run style")),
645    }
646}