Skip to main content

tilo_render_protocol/
frame.rs

1//! One frame of one surface, as it sits in the ring.
2//!
3//! ```text
4//! header   u32 magic "TRF1", u16 version, u16 flags, u32 record length,
5//!          u32 surface, u64 sequence, u32 width, u32 height,
6//!          4 × f32 base colour (premultiplied-free sRGB, alpha last)
7//! sections u16 kind, u16 section flags, u32 length, payload, zero padding to 4
8//! ```
9//!
10//! A section whose kind the reader does not know is skipped when its sender
11//! set [`SECTION_OPTIONAL`], and refuses the frame otherwise: a later step can
12//! add scene annotations as optional sections that older services ignore,
13//! and service-run motion as required ones that only a service which
14//! announced them in its hello receives.
15//!
16//! Sections of version 1:
17//!
18//! - [`SECTION_DAMAGE`]: rectangles of the surface that changed since the
19//!   previous frame, in pixels. With the header's [`FRAME_FULL`] the whole
20//!   surface did. With its [`FRAME_DAMAGE_ONLY`] the scene holds only what
21//!   that damage needs, and is never drawn beyond it.
22//! - [`SECTION_SCROLL_COPY`]: copies within the retained surface, in order,
23//!   before the damage is repainted (what a scroll keeps).
24//! - [`SECTION_LAYER`]: a layer's new content, transform, opacity and clip;
25//!   or that it keeps its content; or that it is gone. Layers not named keep
26//!   everything.
27//! - [`SECTION_ORDER`]: the order layers draw in, bottom first. Without it
28//!   the previous order holds; new layers go on top.
29//! - [`SECTION_BACKDROP`]: a floating surface's blurred backdrop: the
30//!   placeholder image the scene draws, where, how blurred, and the scene
31//!   composed below it.
32
33use crate::bytes::{Reader, Writer};
34use crate::scene::{self, ResourceIds, Resources};
35use crate::validate::{SceneCost, validate};
36use crate::{ImageId, LayerId, Limits, SurfaceId, WireError};
37use vello_encoding::{Encoding, Transform};
38
39const MAGIC: u32 = u32::from_le_bytes(*b"TRF1");
40const HEADER_BYTES: usize = 48;
41
42/// The whole surface changed: repaint all of it.
43pub const FRAME_FULL: u16 = 1;
44
45/// The scene holds only what the frame's damage needs (an app leaves out what the pixels it
46/// presented last still show): a service that would have to draw more of it than that damage
47/// refuses the frame ([`crate::control::Refusal::DamageOnly`]) and the app sends it whole.
48pub const FRAME_DAMAGE_ONLY: u16 = 2;
49
50/// A reader that does not know this section's kind skips it.
51pub const SECTION_OPTIONAL: u16 = 1;
52
53pub const SECTION_DAMAGE: u16 = 1;
54pub const SECTION_SCROLL_COPY: u16 = 2;
55pub const SECTION_LAYER: u16 = 3;
56pub const SECTION_ORDER: u16 = 4;
57pub const SECTION_BACKDROP: u16 = 5;
58
59/// A rectangle in surface pixels, `x0 <= x1`, `y0 <= y1`.
60#[derive(Clone, Copy, Debug, PartialEq)]
61pub struct Rect {
62    pub x0: f32,
63    pub y0: f32,
64    pub x1: f32,
65    pub y1: f32,
66}
67
68impl Rect {
69    fn valid(&self) -> bool {
70        [self.x0, self.y0, self.x1, self.y1]
71            .iter()
72            .all(|value| value.is_finite() && value.abs() <= crate::validate::MAX_COORDINATE)
73            && self.x0 <= self.x1
74            && self.y0 <= self.y1
75    }
76}
77
78/// A copy within the retained surface: the source rectangle and how far it
79/// moves, in pixels.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct ScrollCopy {
82    pub x: u32,
83    pub y: u32,
84    pub width: u32,
85    pub height: u32,
86    pub dx: i32,
87    pub dy: i32,
88}
89
90/// What a frame does to one layer.
91#[derive(Clone)]
92pub enum LayerChange {
93    Content(Box<Encoding>),
94    /// The content stays; the properties change.
95    Keep,
96    /// The layer is gone.
97    Remove,
98}
99
100#[derive(Clone)]
101pub struct LayerUpdate {
102    pub id: LayerId,
103    pub change: LayerChange,
104    /// Placed by this transform.
105    pub transform: Transform,
106    /// Drawn at this opacity, `0..=1`.
107    pub opacity: f32,
108    /// Clipped to this rectangle, in surface pixels.
109    pub clip: Option<Rect>,
110}
111
112impl LayerUpdate {
113    /// Layer `id` with new `content`, untransformed, opaque, unclipped.
114    #[must_use]
115    pub fn content(id: LayerId, content: Encoding) -> Self {
116        Self {
117            id,
118            change: LayerChange::Content(Box::new(content)),
119            transform: Transform::IDENTITY,
120            opacity: 1.0,
121            clip: None,
122        }
123    }
124}
125
126/// A floating surface's blurred backdrop.
127#[derive(Clone)]
128pub struct Backdrop {
129    /// The placeholder image the frame draws, which the service replaces
130    /// with the blur.
131    pub image: ImageId,
132    /// Where the placeholder lands, in surface pixels.
133    pub rect: Rect,
134    /// Blur standard deviation, in surface pixels.
135    pub blur_px: f32,
136    /// The sampling the surface asked for, after the blur: `0` smooth, `1`
137    /// at one colour per cell of `cell_px` (a surface shown as pixels).
138    pub sampling: u8,
139    /// The cell's side in surface pixels, where `sampling` is blocky; `0`
140    /// otherwise.
141    pub cell_px: f32,
142    /// The lens the backdrop is bent through, in surface pixels: the
143    /// displacement at the rim (`0` bends nothing), the band it eases
144    /// across, the rounded rect's corner radius, and the fraction red and
145    /// blue are set apart by.
146    pub refraction: [f32; 4],
147    /// The relative luminances, darkest and lightest, what shows through
148    /// is compressed into so text over the surface stays legible, and the
149    /// surface ground's, which shows as it is; `0`, `1` compresses nothing.
150    pub legible: [f32; 3],
151    /// What the backdrop shows where nothing below covers it.
152    pub ground: [f32; 4],
153    /// The theme's material stage the service runs over the blurred backdrop: its WGSL, which the
154    /// service checks before it compiles it, and its uniforms. `None` shows the backdrop as it is.
155    pub stage: Option<BackdropStage>,
156    /// Everything composed below the surface.
157    pub below: Encoding,
158}
159
160/// A material stage as a frame carries it.
161#[derive(Clone, Debug, PartialEq)]
162pub struct BackdropStage {
163    pub wgsl: String,
164    pub uniforms: [f32; STAGE_FLOATS],
165}
166
167/// How many numbers a stage's uniforms hold.
168pub const STAGE_FLOATS: usize = 40;
169
170/// The most WGSL a stage may carry, bytes.
171pub const MAX_STAGE_SOURCE: usize = 16 * 1024;
172
173/// A frame record, decoded.
174#[derive(Clone)]
175pub struct Frame {
176    pub surface: SurfaceId,
177    pub sequence: u64,
178    pub width: u32,
179    pub height: u32,
180    pub base_color: [f32; 4],
181    pub full: bool,
182    /// The scene holds only what the damage needs ([`FRAME_DAMAGE_ONLY`]).
183    pub damage_only: bool,
184    pub damage: Vec<Rect>,
185    pub scroll_copies: Vec<ScrollCopy>,
186    pub layers: Vec<LayerUpdate>,
187    pub order: Option<Vec<LayerId>>,
188    pub backdrops: Vec<Backdrop>,
189}
190
191/// Writes a frame record; [`FrameWriter::finish`] fills in its length.
192pub struct FrameWriter<'a> {
193    out: &'a mut Vec<u8>,
194    start: usize,
195}
196
197impl<'a> FrameWriter<'a> {
198    /// Start a record for `surface` at the end of `out`.
199    pub fn new(
200        out: &'a mut Vec<u8>,
201        (surface, sequence): (SurfaceId, u64),
202        (width, height): (u32, u32),
203        base_color: [f32; 4],
204        full: bool,
205    ) -> Self {
206        let start = out.len();
207        let mut w = Writer::new(out);
208        w.u32(MAGIC);
209        w.u16(crate::PROTOCOL_VERSION);
210        w.u16(if full { FRAME_FULL } else { 0 });
211        w.u32(0);
212        w.u32(surface.0);
213        w.u64(sequence);
214        w.u32(width);
215        w.u32(height);
216        for value in base_color {
217            w.f32(value);
218        }
219        Self { out, start }
220    }
221
222    /// The scene holds only what this frame's damage needs ([`FRAME_DAMAGE_ONLY`]).
223    pub fn damage_only(&mut self) {
224        let at = self.start.saturating_add(6);
225        if let Some(flags) = self
226            .out
227            .get_mut(at..at.saturating_add(2))
228            .and_then(|flags| <&mut [u8; 2]>::try_from(flags).ok())
229        {
230            *flags = (u16::from_le_bytes(*flags) | FRAME_DAMAGE_ONLY).to_le_bytes();
231        }
232    }
233
234    fn section(
235        &mut self,
236        kind: u16,
237        body: impl FnOnce(&mut Writer<'_>) -> Result<(), WireError>,
238    ) -> Result<(), WireError> {
239        let mut w = Writer::new(self.out);
240        w.u16(kind);
241        w.u16(0);
242        let length_at = w.len();
243        w.u32(0);
244        let body_start = w.len();
245        body(&mut w)?;
246        let length = w.len().checked_sub(body_start).ok_or(WireError::Overflow)?;
247        w.patch_u32(
248            length_at,
249            u32::try_from(length).map_err(|_| WireError::Overflow)?,
250        )?;
251        w.align4(length);
252        Ok(())
253    }
254
255    /// The rectangles that changed.
256    pub fn damage(&mut self, rects: &[Rect]) -> Result<(), WireError> {
257        if rects.is_empty() {
258            return Ok(());
259        }
260        self.section(SECTION_DAMAGE, |w| {
261            w.count(rects.len())?;
262            for rect in rects {
263                for value in [rect.x0, rect.y0, rect.x1, rect.y1] {
264                    w.f32(value);
265                }
266            }
267            Ok(())
268        })
269    }
270
271    /// The copies a scroll keeps, in order.
272    pub fn scroll_copies(&mut self, copies: &[ScrollCopy]) -> Result<(), WireError> {
273        if copies.is_empty() {
274            return Ok(());
275        }
276        self.section(SECTION_SCROLL_COPY, |w| {
277            w.count(copies.len())?;
278            for copy in copies {
279                for value in [copy.x, copy.y, copy.width, copy.height] {
280                    w.u32(value);
281                }
282                w.i32(copy.dx);
283                w.i32(copy.dy);
284            }
285            Ok(())
286        })
287    }
288
289    /// One layer's change; its content's resources are registered through
290    /// `ids`.
291    pub fn layer(
292        &mut self,
293        layer: &LayerUpdate,
294        ids: &mut dyn ResourceIds,
295    ) -> Result<(), WireError> {
296        self.section(SECTION_LAYER, |w| {
297            w.u32(layer.id.0);
298            let (op, content) = match &layer.change {
299                LayerChange::Content(content) => (0_u32, Some(content)),
300                LayerChange::Keep => (1, None),
301                LayerChange::Remove => (2, None),
302            };
303            w.u32(op | if layer.clip.is_some() { 1 << 8 } else { 0 });
304            for value in layer
305                .transform
306                .matrix
307                .iter()
308                .chain(&layer.transform.translation)
309            {
310                w.f32(*value);
311            }
312            w.f32(layer.opacity);
313            let clip = layer.clip.unwrap_or(Rect {
314                x0: 0.0,
315                y0: 0.0,
316                x1: 0.0,
317                y1: 0.0,
318            });
319            for value in [clip.x0, clip.y0, clip.x1, clip.y1] {
320                w.f32(value);
321            }
322            if let Some(content) = content {
323                scene::encode(content, ids, w.vec())?;
324            }
325            Ok(())
326        })
327    }
328
329    /// Layer `id`'s new content, untransformed, opaque, unclipped: what a
330    /// toolkit frame sends for its root layer, without copying the encoding.
331    pub fn content(
332        &mut self,
333        id: LayerId,
334        content: &Encoding,
335        ids: &mut dyn ResourceIds,
336    ) -> Result<(), WireError> {
337        self.section(SECTION_LAYER, |w| {
338            w.u32(id.0);
339            w.u32(0);
340            for value in [1.0_f32, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0] {
341                w.f32(value);
342            }
343            scene::encode(content, ids, w.vec())?;
344            Ok(())
345        })
346    }
347
348    /// The order layers draw in, bottom first.
349    pub fn order(&mut self, order: &[LayerId]) -> Result<(), WireError> {
350        self.section(SECTION_ORDER, |w| {
351            w.count(order.len())?;
352            for id in order {
353                w.u32(id.0);
354            }
355            Ok(())
356        })
357    }
358
359    /// A floating surface's backdrop.
360    pub fn backdrop(
361        &mut self,
362        backdrop: &Backdrop,
363        ids: &mut dyn ResourceIds,
364    ) -> Result<(), WireError> {
365        self.section(SECTION_BACKDROP, |w| {
366            w.u32(backdrop.image.0);
367            let rect = backdrop.rect;
368            for value in [
369                rect.x0,
370                rect.y0,
371                rect.x1,
372                rect.y1,
373                backdrop.blur_px,
374                backdrop.cell_px,
375            ] {
376                w.f32(value);
377            }
378            for value in backdrop.refraction.into_iter().chain(backdrop.legible) {
379                w.f32(value);
380            }
381            w.u8(backdrop.sampling);
382            for value in backdrop.ground {
383                w.f32(value);
384            }
385            match &backdrop.stage {
386                Some(stage) => {
387                    let len = u32::try_from(stage.wgsl.len())
388                        .map_err(|_| WireError::Invalid("backdrop stage"))?;
389                    w.u32(len);
390                    w.bytes(stage.wgsl.as_bytes());
391                    for value in stage.uniforms {
392                        w.f32(value);
393                    }
394                }
395                None => w.u32(0),
396            }
397            scene::encode(&backdrop.below, ids, w.vec())?;
398            Ok(())
399        })
400    }
401
402    /// A section of a kind this crate does not write (a later step's), as
403    /// raw bytes.
404    pub fn raw_section(
405        &mut self,
406        kind: u16,
407        optional: bool,
408        payload: &[u8],
409    ) -> Result<(), WireError> {
410        let mut w = Writer::new(self.out);
411        w.u16(kind);
412        w.u16(if optional { SECTION_OPTIONAL } else { 0 });
413        w.count(payload.len())?;
414        w.bytes(payload);
415        w.align4(payload.len());
416        Ok(())
417    }
418
419    /// Close the record and return its length.
420    pub fn finish(self) -> Result<usize, WireError> {
421        let length = self
422            .out
423            .len()
424            .checked_sub(self.start)
425            .ok_or(WireError::Overflow)?;
426        let at = self.start.checked_add(8).ok_or(WireError::Overflow)?;
427        Writer::new(self.out)
428            .patch_u32(at, u32::try_from(length).map_err(|_| WireError::Overflow)?)?;
429        Ok(length)
430    }
431}
432
433/// A frame, read and validated, with what it costs to draw.
434pub struct Checked {
435    pub frame: Frame,
436    pub cost: SceneCost,
437}
438
439/// Read one frame record from `bytes` (exactly one record) and validate
440/// every scene in it against `limits`. Every byte is read once.
441///
442/// # Errors
443///
444/// The first thing wrong with the record.
445pub fn read(
446    bytes: &[u8],
447    resources: &dyn Resources,
448    limits: &Limits,
449) -> Result<Checked, WireError> {
450    if bytes.len() > limits.frame_bytes as usize {
451        return Err(WireError::OverLimit("frame bytes"));
452    }
453    let mut r = Reader::new(bytes);
454    if r.u32()? != MAGIC {
455        return Err(WireError::Malformed("not a frame record"));
456    }
457    if r.u16()? != crate::PROTOCOL_VERSION {
458        return Err(WireError::Malformed("frame version"));
459    }
460    let flags = r.u16()?;
461    if flags & !(FRAME_FULL | FRAME_DAMAGE_ONLY) != 0 {
462        return Err(WireError::Malformed("frame flags"));
463    }
464    if r.u32()? as usize != bytes.len() {
465        return Err(WireError::Malformed("frame length"));
466    }
467    let mut frame = Frame {
468        surface: SurfaceId(r.u32()?),
469        sequence: r.u64()?,
470        width: r.u32()?,
471        height: r.u32()?,
472        base_color: [r.f32()?, r.f32()?, r.f32()?, r.f32()?],
473        full: flags & FRAME_FULL != 0,
474        damage_only: flags & FRAME_DAMAGE_ONLY != 0,
475        damage: Vec::new(),
476        scroll_copies: Vec::new(),
477        layers: Vec::new(),
478        order: None,
479        backdrops: Vec::new(),
480    };
481    debug_assert_eq!(bytes.len().saturating_sub(r.remaining()), HEADER_BYTES);
482    if frame.width == 0
483        || frame.height == 0
484        || frame.width > limits.surface_edge
485        || frame.height > limits.surface_edge
486    {
487        return Err(WireError::OverLimit("surface size"));
488    }
489    if !frame.base_color.iter().all(|value| value.is_finite()) {
490        return Err(WireError::Invalid("base colour"));
491    }
492    let mut cost = SceneCost::default();
493    while !r.is_empty() {
494        let kind = r.u16()?;
495        let section_flags = r.u16()?;
496        let length = r.u32()? as usize;
497        let payload = r.take(length)?;
498        r.align4(length)?;
499        if section_flags & !SECTION_OPTIONAL != 0 {
500            return Err(WireError::Malformed("section flags"));
501        }
502        let mut body = Reader::new(payload);
503        match kind {
504            SECTION_DAMAGE => read_damage(&mut body, &mut frame, limits)?,
505            SECTION_SCROLL_COPY => read_copies(&mut body, &mut frame, limits)?,
506            SECTION_LAYER => {
507                if frame.layers.len() >= limits.layers as usize {
508                    return Err(WireError::OverLimit("layers"));
509                }
510                let (layer, layer_cost) = read_layer(&mut body, resources, limits)?;
511                cost = cost.plus(layer_cost);
512                frame.layers.push(layer);
513            }
514            SECTION_ORDER => {
515                let count = body.count(4)?;
516                if count > limits.layers as usize || frame.order.is_some() {
517                    return Err(WireError::OverLimit("layer order"));
518                }
519                let order = (0..count)
520                    .map(|_| body.u32().map(LayerId))
521                    .collect::<Result<Vec<_>, _>>()?;
522                frame.order = Some(order);
523            }
524            SECTION_BACKDROP => {
525                if frame.backdrops.len() >= limits.backdrops as usize {
526                    return Err(WireError::OverLimit("backdrops"));
527                }
528                let (backdrop, below_cost) = read_backdrop(&mut body, resources, limits)?;
529                cost = cost.plus(below_cost);
530                frame.backdrops.push(backdrop);
531            }
532            _ if section_flags & SECTION_OPTIONAL != 0 => continue,
533            _ => return Err(WireError::UnknownSection(kind)),
534        }
535        if !body.is_empty() {
536            return Err(WireError::Malformed("bytes after a section"));
537        }
538    }
539    cost.check(limits)?;
540    Ok(Checked { frame, cost })
541}
542
543fn read_damage(r: &mut Reader<'_>, frame: &mut Frame, limits: &Limits) -> Result<(), WireError> {
544    let count = r.count(16)?;
545    if count.saturating_add(frame.damage.len()) > limits.rects as usize {
546        return Err(WireError::OverLimit("damage rectangles"));
547    }
548    for _ in 0..count {
549        let rect = Rect {
550            x0: r.f32()?,
551            y0: r.f32()?,
552            x1: r.f32()?,
553            y1: r.f32()?,
554        };
555        if !rect.valid() {
556            return Err(WireError::Invalid("damage rectangle"));
557        }
558        frame.damage.push(rect);
559    }
560    Ok(())
561}
562
563fn read_copies(r: &mut Reader<'_>, frame: &mut Frame, limits: &Limits) -> Result<(), WireError> {
564    let count = r.count(24)?;
565    if count.saturating_add(frame.scroll_copies.len()) > limits.rects as usize {
566        return Err(WireError::OverLimit("scroll copies"));
567    }
568    for _ in 0..count {
569        let copy = ScrollCopy {
570            x: r.u32()?,
571            y: r.u32()?,
572            width: r.u32()?,
573            height: r.u32()?,
574            dx: r.i32()?,
575            dy: r.i32()?,
576        };
577        let inside = |origin: u32, extent: u32, delta: i32, limit: u32| {
578            origin.checked_add(extent).is_some_and(|end| end <= limit)
579                && origin
580                    .checked_add_signed(delta)
581                    .and_then(|moved| moved.checked_add(extent))
582                    .is_some_and(|end| end <= limit)
583        };
584        if copy.width == 0
585            || copy.height == 0
586            || !inside(copy.x, copy.width, copy.dx, frame.width)
587            || !inside(copy.y, copy.height, copy.dy, frame.height)
588        {
589            return Err(WireError::Invalid("scroll copy outside the surface"));
590        }
591        frame.scroll_copies.push(copy);
592    }
593    Ok(())
594}
595
596fn read_encoding(
597    r: &mut Reader<'_>,
598    resources: &dyn Resources,
599    limits: &Limits,
600) -> Result<(Encoding, SceneCost), WireError> {
601    let bytes = r.take(r.remaining())?;
602    let encoding = scene::decode(bytes, resources)?;
603    let cost = validate(&encoding, limits)?;
604    Ok((encoding, cost))
605}
606
607fn read_layer(
608    r: &mut Reader<'_>,
609    resources: &dyn Resources,
610    limits: &Limits,
611) -> Result<(LayerUpdate, SceneCost), WireError> {
612    let id = LayerId(r.u32()?);
613    let op = r.u32()?;
614    if op & !0x1ff != 0 {
615        return Err(WireError::Malformed("layer op"));
616    }
617    let transform = Transform {
618        matrix: [r.f32()?, r.f32()?, r.f32()?, r.f32()?],
619        translation: [r.f32()?, r.f32()?],
620    };
621    let opacity = r.f32()?;
622    let clip = Rect {
623        x0: r.f32()?,
624        y0: r.f32()?,
625        x1: r.f32()?,
626        y1: r.f32()?,
627    };
628    let finite = transform
629        .matrix
630        .iter()
631        .chain(&transform.translation)
632        .all(|value| value.is_finite() && value.abs() <= crate::validate::MAX_COORDINATE);
633    if !finite || !(0.0..=1.0).contains(&opacity) || !clip.valid() {
634        return Err(WireError::Invalid("layer properties"));
635    }
636    let (change, cost) = match op & 0xff {
637        0 => {
638            let (content, cost) = read_encoding(r, resources, limits)?;
639            (LayerChange::Content(Box::new(content)), cost)
640        }
641        1 => (LayerChange::Keep, SceneCost::default()),
642        2 => (LayerChange::Remove, SceneCost::default()),
643        _ => return Err(WireError::Malformed("layer op")),
644    };
645    Ok((
646        LayerUpdate {
647            id,
648            change,
649            transform,
650            opacity,
651            clip: (op & (1 << 8) != 0).then_some(clip),
652        },
653        cost,
654    ))
655}
656
657fn read_backdrop(
658    r: &mut Reader<'_>,
659    resources: &dyn Resources,
660    limits: &Limits,
661) -> Result<(Backdrop, SceneCost), WireError> {
662    let image = ImageId(r.u32()?);
663    if resources.image(image).is_none() {
664        return Err(WireError::UnknownResource("a backdrop image"));
665    }
666    let rect = Rect {
667        x0: r.f32()?,
668        y0: r.f32()?,
669        x1: r.f32()?,
670        y1: r.f32()?,
671    };
672    let blur_px = r.f32()?;
673    let cell_px = r.f32()?;
674    let refraction = [r.f32()?, r.f32()?, r.f32()?, r.f32()?];
675    let legible = [r.f32()?, r.f32()?, r.f32()?];
676    let sampling = r.u8()?;
677    let ground = [r.f32()?, r.f32()?, r.f32()?, r.f32()?];
678    let stage_len = r.u32()? as usize;
679    let stage = if stage_len == 0 {
680        None
681    } else {
682        if stage_len > MAX_STAGE_SOURCE {
683            return Err(WireError::Invalid("backdrop stage"));
684        }
685        let wgsl = std::str::from_utf8(r.take(stage_len)?)
686            .map_err(|_| WireError::Invalid("backdrop stage"))?
687            .to_owned();
688        let mut uniforms = [0.0; STAGE_FLOATS];
689        for value in &mut uniforms {
690            *value = r.f32()?;
691            if !value.is_finite() {
692                return Err(WireError::Invalid("backdrop stage"));
693            }
694        }
695        Some(BackdropStage { wgsl, uniforms })
696    };
697    let valid = rect.valid()
698        && blur_px.is_finite()
699        && (0.0..=4096.0).contains(&blur_px)
700        && sampling <= 1
701        && cell_px.is_finite()
702        && (0.0..=4096.0).contains(&cell_px)
703        && refraction
704            .iter()
705            .all(|value| value.is_finite() && (0.0..=4096.0).contains(value))
706        && legible
707            .iter()
708            .all(|value| value.is_finite() && (0.0..=1.0).contains(value))
709        && legible[0] <= legible[1]
710        && (legible[0]..=legible[1]).contains(&legible[2])
711        && ground.iter().all(|value| value.is_finite());
712    if !valid {
713        return Err(WireError::Invalid("backdrop"));
714    }
715    let (below, cost) = read_encoding(r, resources, limits)?;
716    Ok((
717        Backdrop {
718            image,
719            rect,
720            blur_px,
721            sampling,
722            cell_px,
723            refraction,
724            legible,
725            ground,
726            stage,
727            below,
728        },
729        cost,
730    ))
731}