Skip to main content

cranpose_render_pixels/
sprites.rs

1//! The scene as sprites for a GPU compositor other than wgpu: SpriteKit on
2//! watchOS, which gives an app no Metal of its own.
3//!
4//! Every item becomes one quad in device pixels, drawn in order, cut to the
5//! whole pixels its clip leaves, as the rasterizer cuts it. The shapes the
6//! compositor's shader covers -- filled and stroked rounded rects, arcs and
7//! lines, painted with a solid colour or a two-colour gradient -- travel as
8//! numbers. Everything else is drawn here, once, by the rasterizer into a
9//! texture of its own, which is kept while the item stays the same: moving it
10//! by whole pixels moves the quad and keeps the texture.
11//!
12//! A sprite is [`SPRITE_FLOATS`] numbers; [`field`] names where each part
13//! starts. Positions are device pixels with the origin at the top left.
14
15use std::{fmt::Write as _, hash::Hasher};
16
17use cranpose_render_common::{
18    brush_sampling::color_to_rgba,
19    graph_scene::RenderDiagnostics,
20    layer_shadow::{ShadowHole, ShadowRRect},
21};
22use cranpose_ui_graphics::{
23    BlendMode, Brush, Color, FxHashMap, FxHasher, Point, Rect, StrokeCap, StrokeJoin, TileMode,
24    whole,
25};
26
27use crate::{
28    draw::{
29        ClipBounds, RenderItem, ShapeCoverage, Target, TextRaster, clip_rect_to_window, draw_item,
30        place_shape, snap_delta_for_anchor,
31    },
32    scene::{DrawShape, ImageDraw, RasterScene, ShadowDraw, TextDraw},
33};
34
35/// How many numbers make one sprite.
36pub const SPRITE_FLOATS: usize = 36;
37
38/// Where each part of a sprite starts, and what it holds.
39pub mod field {
40    /// The quad: x, y, width, height.
41    pub const FRAME: usize = 0;
42    /// What the quad holds ([`super::SpriteKind`]), the texture it shows
43    /// (0 for none), how it blends (0 source over, 1 destination out) and its
44    /// brush (0 solid, 1 linear, 2 radial, 3 sweep).
45    pub const KIND: usize = 4;
46    /// The geometry, by kind. A texture: the rect the whole texture covers.
47    /// A fill or a stroke: the rect. An arc: centre x and y, inner and outer
48    /// radius. A line: start x and y, end x and y.
49    pub const GEOMETRY: usize = 8;
50    /// A fill or a stroke: the corner radii, top-left, top-right,
51    /// bottom-right, bottom-left. An arc: start angle, sweep, cap (0 butt,
52    /// 1 round, 2 square). A line: half width, cap.
53    pub const DETAIL: usize = 12;
54    /// A fill: whether its corners are rounded (1) or not (0). A stroke: half
55    /// width and join (0 miter, 1 round, 2 bevel). Third: a gradient's tile
56    /// mode (0 clamp, 1 repeated, 2 mirror, 3 decal).
57    pub const STROKE: usize = 16;
58    /// The brush's first colour, straight RGBA.
59    pub const COLOR: usize = 20;
60    /// A gradient's second colour, straight RGBA.
61    pub const COLOR_END: usize = 24;
62    /// A gradient's geometry: linear start x, y and end x, y; radial centre
63    /// x, y and radius; sweep centre x, y.
64    pub const GRADIENT: usize = 28;
65    /// A gradient's two stops, then the origin its dither is measured from.
66    pub const STOPS: usize = 32;
67}
68
69/// What one sprite holds.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71#[repr(u8)]
72pub enum SpriteKind {
73    /// A texture that the rasterizer drew for the item.
74    Texture = 0,
75    /// A filled rounded rectangle.
76    Fill = 1,
77    /// A stroked rounded rectangle.
78    Stroke = 2,
79    /// A circular arc band.
80    Arc = 3,
81    /// A stroked line segment.
82    Line = 4,
83}
84
85/// A texture the compositor has not seen yet: premultiplied RGBA8, row by
86/// row from the top.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct TextureUpload {
89    /// Handle of the texture. Sprites name it, and `releases` lists it once it is dropped.
90    pub id: u32,
91    /// Texture width in pixels.
92    pub width: u32,
93    /// Texture height in pixels.
94    pub height: u32,
95    /// Premultiplied RGBA8 pixels, row by row from the top: `width` times `height` times four
96    /// bytes.
97    pub pixels: Vec<u8>,
98}
99
100/// One frame of sprites, and the textures they use. It keeps its textures
101/// from frame to frame: compose into the same one every frame.
102#[derive(Default)]
103pub struct SpriteFrame {
104    /// The scene the last frame composed, whose storage the next one reuses.
105    pub(crate) scene: RasterScene,
106    sprites: Vec<f32>,
107    uploads: Vec<TextureUpload>,
108    releases: Vec<u32>,
109    textures: FxHashMap<u64, CachedTexture>,
110    next_texture: u32,
111    generation: u64,
112}
113
114struct CachedTexture {
115    id: u32,
116    /// Where the texture sits for the item at its canonical place.
117    placement: Rect,
118    last_used: u64,
119}
120
121/// Frames a texture outlives the last item that showed it, so an item that
122/// blinks does not draw itself again each time it comes back.
123const TEXTURE_RETENTION_FRAMES: u64 = 60;
124
125impl SpriteFrame {
126    /// The sprites, [`SPRITE_FLOATS`] numbers each, in drawing order.
127    pub fn sprites(&self) -> &[f32] {
128        &self.sprites
129    }
130
131    /// Number of sprites in the frame.
132    pub fn sprite_count(&self) -> usize {
133        self.sprites.len() / SPRITE_FLOATS
134    }
135
136    /// Textures first used this frame.
137    pub fn uploads(&self) -> &[TextureUpload] {
138        &self.uploads
139    }
140
141    /// Textures no sprite has used for a while; the compositor drops them.
142    pub fn releases(&self) -> &[u32] {
143        &self.releases
144    }
145
146    pub(crate) fn compose(
147        &mut self,
148        scene: &RasterScene,
149        width: u32,
150        height: u32,
151        diagnostics: &RenderDiagnostics,
152        text: &TextRaster,
153    ) {
154        self.sprites.clear();
155        self.uploads.clear();
156        self.releases.clear();
157        self.generation += 1;
158        let screen = ClipBounds {
159            min_x: 0,
160            min_y: 0,
161            max_x: width as i32,
162            max_y: height as i32,
163        };
164        for &item in &scene.order {
165            if let RenderItem::Shape(index) = item
166                && let Some(sprite) = shape_sprite(&scene.shapes[index], screen)
167            {
168                self.sprites.extend_from_slice(&sprite);
169                continue;
170            }
171            self.texture_sprite(scene, item, screen, diagnostics, text);
172        }
173        let generation = self.generation;
174        let releases = &mut self.releases;
175        self.textures.retain(|_, texture| {
176            let keep = generation - texture.last_used <= TEXTURE_RETENTION_FRAMES;
177            if !keep {
178                releases.push(texture.id);
179            }
180            keep
181        });
182    }
183
184    /// Shows `item` from a texture the rasterizer drew it into, drawing it
185    /// first if no texture holds it at its canonical place.
186    fn texture_sprite(
187        &mut self,
188        scene: &RasterScene,
189        item: RenderItem,
190        screen: ClipBounds,
191        diagnostics: &RenderDiagnostics,
192        text: &TextRaster,
193    ) {
194        let Some((canonical, offset, clip)) = Canonical::of(scene, item) else {
195            return;
196        };
197        let key = canonical.key();
198        let generation = self.generation;
199        let (id, placement) = match self.textures.get_mut(&key) {
200            Some(texture) => {
201                texture.last_used = generation;
202                (texture.id, texture.placement)
203            }
204            None => {
205                let Some((placement, pixels)) = canonical.rasterize(diagnostics, text) else {
206                    return;
207                };
208                self.next_texture = self.next_texture.wrapping_add(1).max(1);
209                let id = self.next_texture;
210                self.uploads.push(TextureUpload {
211                    id,
212                    width: placement.width as u32,
213                    height: placement.height as u32,
214                    pixels,
215                });
216                self.textures.insert(
217                    key,
218                    CachedTexture {
219                        id,
220                        placement,
221                        last_used: generation,
222                    },
223                );
224                (id, placement)
225            }
226        };
227        let placement = placement.translate(offset.x, offset.y);
228        let Some(frame) = clip_rect_to_window(placement, clip, screen) else {
229            return;
230        };
231        let mut sprite = [0.0; SPRITE_FLOATS];
232        put_frame(&mut sprite, frame);
233        sprite[field::KIND] = SpriteKind::Texture as u8 as f32;
234        sprite[field::KIND + 1] = id as f32;
235        put_rect(&mut sprite, field::GEOMETRY, placement);
236        self.sprites.extend_from_slice(&sprite);
237    }
238}
239
240fn put_frame(sprite: &mut [f32; SPRITE_FLOATS], frame: ClipBounds) {
241    sprite[field::FRAME] = frame.min_x as f32;
242    sprite[field::FRAME + 1] = frame.min_y as f32;
243    sprite[field::FRAME + 2] = (frame.max_x - frame.min_x) as f32;
244    sprite[field::FRAME + 3] = (frame.max_y - frame.min_y) as f32;
245}
246
247fn put_rect(sprite: &mut [f32; SPRITE_FLOATS], at: usize, rect: Rect) {
248    sprite[at..at + 4].copy_from_slice(&[rect.x, rect.y, rect.width, rect.height]);
249}
250
251fn put_color(sprite: &mut [f32; SPRITE_FLOATS], at: usize, color: Color) {
252    sprite[at..at + 4].copy_from_slice(&color_to_rgba(color));
253}
254
255fn cap_code(cap: StrokeCap) -> f32 {
256    match cap {
257        StrokeCap::Butt => 0.0,
258        StrokeCap::Round => 1.0,
259        StrokeCap::Square => 2.0,
260    }
261}
262
263fn join_code(join: StrokeJoin) -> f32 {
264    match join {
265        StrokeJoin::Miter => 0.0,
266        StrokeJoin::Round => 1.0,
267        StrokeJoin::Bevel => 2.0,
268    }
269}
270
271fn tile_code(tile_mode: TileMode) -> f32 {
272    match tile_mode {
273        TileMode::Clamp => 0.0,
274        TileMode::Repeated => 1.0,
275        TileMode::Mirror => 2.0,
276        TileMode::Decal => 3.0,
277    }
278}
279
280/// The sprite the compositor's shader draws `draw` with, or `None` when the
281/// shader does not cover it and a texture must.
282fn shape_sprite(draw: &DrawShape, screen: ClipBounds) -> Option<[f32; SPRITE_FLOATS]> {
283    let blend = match draw.blend_mode {
284        BlendMode::DstOut => 1.0,
285        _ => 0.0,
286    };
287    let placed = place_shape(draw)?;
288    let mut sprite = [0.0; SPRITE_FLOATS];
289    match placed.coverage {
290        ShapeCoverage::Fill { rect, radii } => {
291            sprite[field::KIND] = SpriteKind::Fill as u8 as f32;
292            put_rect(&mut sprite, field::GEOMETRY, rect);
293            if let Some(radii) = radii {
294                sprite[field::DETAIL..field::DETAIL + 4].copy_from_slice(&[
295                    radii.top_left,
296                    radii.top_right,
297                    radii.bottom_right,
298                    radii.bottom_left,
299                ]);
300                sprite[field::STROKE] = 1.0;
301            }
302        }
303        ShapeCoverage::Stroke {
304            rect,
305            radii,
306            half_width,
307            join,
308        } => {
309            sprite[field::KIND] = SpriteKind::Stroke as u8 as f32;
310            put_rect(&mut sprite, field::GEOMETRY, rect);
311            let radii = radii.unwrap_or_default();
312            sprite[field::DETAIL..field::DETAIL + 4].copy_from_slice(&[
313                radii.top_left,
314                radii.top_right,
315                radii.bottom_right,
316                radii.bottom_left,
317            ]);
318            sprite[field::STROKE] = half_width;
319            sprite[field::STROKE + 1] = join_code(join);
320        }
321        ShapeCoverage::Arc(arc) => {
322            sprite[field::KIND] = SpriteKind::Arc as u8 as f32;
323            sprite[field::GEOMETRY..field::GEOMETRY + 4].copy_from_slice(&[
324                arc.center.x,
325                arc.center.y,
326                arc.inner_radius,
327                arc.outer_radius,
328            ]);
329            sprite[field::DETAIL..field::DETAIL + 3].copy_from_slice(&[
330                arc.start_angle,
331                arc.sweep_angle,
332                cap_code(arc.cap),
333            ]);
334        }
335        ShapeCoverage::Line(line) => {
336            sprite[field::KIND] = SpriteKind::Line as u8 as f32;
337            sprite[field::GEOMETRY..field::GEOMETRY + 4].copy_from_slice(&[
338                line.start.x,
339                line.start.y,
340                line.end.x,
341                line.end.y,
342            ]);
343            sprite[field::DETAIL] = line.half_width;
344            sprite[field::DETAIL + 1] = cap_code(line.cap);
345        }
346        ShapeCoverage::Trapezoid(_) => return None,
347    }
348    put_brush(&mut sprite, &draw.brush, placed.rect)?;
349    sprite[field::KIND + 2] = blend;
350    let frame = clip_rect_to_window(placed.coverage.reach(placed.rect), draw.clip, screen)?;
351    put_frame(&mut sprite, frame);
352    // The dither's origin, which the shader measures pixels from.
353    sprite[field::STOPS + 2] = placed.dither_origin.x;
354    sprite[field::STOPS + 3] = placed.dither_origin.y;
355    Some(sprite)
356}
357
358/// Writes the brush the shader paints with, resolved against `rect` as the
359/// rasterizer resolves it; `None` for a gradient of more than two colours.
360fn put_brush(sprite: &mut [f32; SPRITE_FLOATS], brush: &Brush, rect: Rect) -> Option<()> {
361    let two_colours = |colors: &[Color], stops: Option<&[f32]>| match (colors, stops) {
362        ([only], _) => Some((*only, *only, [0.0, 1.0])),
363        ([start, end], Some([from, to])) => Some((*start, *end, [*from, *to])),
364        ([start, end], _) => Some((*start, *end, [0.0, 1.0])),
365        _ => None,
366    };
367    let resolve = |origin: f32, extent: f32, value: f32| {
368        if value.is_finite() {
369            origin + value
370        } else if value.is_sign_positive() {
371            origin + extent
372        } else {
373            origin
374        }
375    };
376    let (code, (start, end, stops), gradient, tile) = match brush {
377        Brush::Solid(color) => (0.0, (*color, *color, [0.0, 1.0]), [0.0; 4], TileMode::Clamp),
378        Brush::LinearGradient {
379            colors,
380            stops,
381            start,
382            end,
383            tile_mode,
384        } => (
385            1.0,
386            two_colours(colors, stops.as_deref())?,
387            [
388                resolve(rect.x, rect.width, start.x),
389                resolve(rect.y, rect.height, start.y),
390                resolve(rect.x, rect.width, end.x),
391                resolve(rect.y, rect.height, end.y),
392            ],
393            *tile_mode,
394        ),
395        Brush::RadialGradient {
396            colors,
397            stops,
398            center,
399            radius,
400            tile_mode,
401        } => (
402            2.0,
403            two_colours(colors, stops.as_deref())?,
404            [
405                rect.x + center.x,
406                rect.y + center.y,
407                radius.max(f32::EPSILON),
408                0.0,
409            ],
410            *tile_mode,
411        ),
412        Brush::SweepGradient {
413            colors,
414            stops,
415            center,
416        } => (
417            3.0,
418            two_colours(colors, stops.as_deref())?,
419            [rect.x + center.x, rect.y + center.y, 0.0, 0.0],
420            TileMode::Clamp,
421        ),
422    };
423    sprite[field::KIND + 3] = code;
424    put_color(sprite, field::COLOR, start);
425    put_color(sprite, field::COLOR_END, end);
426    sprite[field::GRADIENT..field::GRADIENT + 4].copy_from_slice(&gradient);
427    sprite[field::STOPS] = stops[0];
428    sprite[field::STOPS + 1] = stops[1];
429    sprite[field::STROKE + 2] = tile_code(tile);
430    Some(())
431}
432
433/// An item moved to its canonical place: shifted by whole pixels so its own
434/// rect starts within the first pixel, with no clip. Two frames that show the
435/// same item at whole-pixel distances share one canonical item.
436enum Canonical {
437    Shape(DrawShape),
438    Image(ImageDraw),
439    Text(TextDraw),
440    Shadow(ShadowDraw),
441}
442
443impl Canonical {
444    /// The canonical item, the whole-pixel shift back to where `item` is,
445    /// and its clip.
446    fn of(scene: &RasterScene, item: RenderItem) -> Option<(Self, Point, Option<Rect>)> {
447        let (origin, clip) = match item {
448            RenderItem::Shape(index) => {
449                let draw = &scene.shapes[index];
450                (Point::new(draw.rect.x, draw.rect.y), draw.clip)
451            }
452            RenderItem::Image(index) => {
453                let draw = &scene.images[index];
454                (Point::new(draw.rect.x, draw.rect.y), draw.clip)
455            }
456            RenderItem::Text(index) => {
457                let draw = &scene.texts[index];
458                (Point::new(draw.rect.x, draw.rect.y), draw.clip)
459            }
460            RenderItem::Shadow(index) => {
461                let draw = &scene.shadows[index];
462                let snap = draw
463                    .snap_anchor
464                    .map(snap_delta_for_anchor)
465                    .unwrap_or_default();
466                (
467                    Point::new(draw.shadow.bounds.x, draw.shadow.bounds.y),
468                    draw.clip.map(|clip| clip.translate(snap.x, snap.y)),
469                )
470            }
471        };
472        if !(origin.x.is_finite() && origin.y.is_finite()) {
473            return None;
474        }
475        let shift = Point::new(whole::floor(origin.x), whole::floor(origin.y));
476        let (dx, dy) = (-shift.x, -shift.y);
477        let canonical = match item {
478            RenderItem::Shape(index) => Self::Shape(scene.shapes[index].translated(dx, dy)),
479            RenderItem::Image(index) => Self::Image(scene.images[index].translated(dx, dy)),
480            RenderItem::Text(index) => Self::Text(scene.texts[index].translated(dx, dy)),
481            RenderItem::Shadow(index) => Self::Shadow(scene.shadows[index].translated(dx, dy)),
482        };
483        Some((canonical, shift, clip))
484    }
485
486    /// A hash of everything that decides the canonical item's pixels.
487    fn key(&self) -> u64 {
488        let mut hasher = HashWriter(FxHasher::default());
489        // A text's and a shadow's fields are hashed as numbers. A shape's and
490        // an image's `Debug` forms name every field, positions included; an
491        // image's pixels are named by the bitmap's id instead of printed.
492        let _ = match self {
493            Self::Text(draw) => {
494                hash_text(&mut hasher.0, draw);
495                Ok(())
496            }
497            Self::Shadow(draw) => {
498                hash_shadow(&mut hasher.0, draw);
499                Ok(())
500            }
501            Self::Shape(draw) => write!(hasher, "shape {draw:?}"),
502            Self::Image(draw) => {
503                write!(
504                    hasher,
505                    "image {} {:?} {:?} {} {:?} {:?} {:?} {:?} {:?}",
506                    draw.image.id(),
507                    draw.rect,
508                    draw.snap_anchor,
509                    draw.alpha,
510                    draw.color_filter,
511                    draw.sampling,
512                    draw.blend_mode,
513                    draw.src_rect,
514                    draw.transform,
515                )
516            }
517        };
518        hasher.0.finish()
519    }
520
521    /// Draws the canonical item into a texture of the whole pixels it
522    /// reaches: where the texture sits and its premultiplied pixels.
523    fn rasterize(
524        self,
525        diagnostics: &RenderDiagnostics,
526        text: &TextRaster,
527    ) -> Option<(Rect, Vec<u8>)> {
528        let mut scene = RasterScene::new();
529        let item = match self {
530            Self::Text(draw) => return rasterize_text(&draw, text),
531            Self::Shape(draw) => {
532                scene.shapes.push(draw);
533                RenderItem::Shape(0)
534            }
535            Self::Image(draw) => {
536                scene.images.push(draw);
537                RenderItem::Image(0)
538            }
539            Self::Shadow(draw) => {
540                scene.shadows.push(draw);
541                RenderItem::Shadow(0)
542            }
543        };
544        let reach = scene.item_reach(item)?;
545        let window = clip_rect_to_window(
546            reach,
547            None,
548            ClipBounds {
549                min_x: i32::MIN / 4,
550                min_y: i32::MIN / 4,
551                max_x: i32::MAX / 4,
552                max_y: i32::MAX / 4,
553            },
554        )?;
555        let width = (window.max_x - window.min_x) as u32;
556        let height = (window.max_y - window.min_y) as u32;
557        let mut pixels = vec![0u8; width as usize * height as usize * 4];
558        let mut target = Target {
559            pixels: pixels.as_chunks_mut::<4>().0,
560            left: window.min_x,
561            top: window.min_y,
562            width,
563            height,
564        };
565        draw_item(&mut target, &scene, item, diagnostics, text);
566        Some((
567            Rect {
568                x: window.min_x as f32,
569                y: window.min_y as f32,
570                width: width as f32,
571                height: height as f32,
572            },
573            pixels,
574        ))
575    }
576}
577
578/// Text drawn as the rasterizer draws it, into its own premultiplied image.
579fn rasterize_text(draw: &TextDraw, text: &TextRaster) -> Option<(Rect, Vec<u8>)> {
580    let (text, rect) = crate::draw::rasterize_text(draw, text)?;
581    let mut pixels = text.pixels;
582    // `(c * a + 127) / 255` for each channel, in 16-bit lanes with no
583    // division and no branch, so that a vector unit takes several pixels at
584    // once: for every `x` up to 65,152, `x / 255` is
585    // `(x + 1 + (x >> 8)) >> 8`.
586    for pixel in pixels.as_chunks_mut::<4>().0 {
587        let alpha = u16::from(pixel[3]);
588        for channel in &mut pixel[..3] {
589            let x = u16::from(*channel) * alpha + 127;
590            *channel = ((x + 1 + (x >> 8)) >> 8) as u8;
591        }
592    }
593    Some((rect, pixels))
594}
595
596// A text's draw: its numbers, and the render hashes of its string and style,
597// which hash every setting that changes how the text looks, as the
598// renderers' text caches key on them. Formatting the draw for its `Debug`
599// form took about half of a watch frame's instructions. Every field is named,
600// so a new one does not build until it is hashed here too.
601fn hash_text(hasher: &mut FxHasher, draw: &TextDraw) {
602    let TextDraw {
603        rect,
604        snap_anchor,
605        text,
606        layout,
607        ink,
608        color,
609        text_style,
610        font_size,
611        scale,
612        clip,
613    } = draw;
614    hasher.write_u8(b't');
615    hash_rect(hasher, *rect);
616    hash_floats(hasher, &[layout.width(), layout.height()]);
617    hasher.write_u8(u8::from(
618        *ink == cranpose_render_common::text_raster::GlyphInk::Hidden,
619    ));
620    hash_point(hasher, *snap_anchor);
621    hasher.write_u64(text.render_hash());
622    hash_color(hasher, *color);
623    hasher.write_u64(text_style.render_hash());
624    hash_floats(hasher, &[*font_size, *scale]);
625    hash_clip(hasher, *clip);
626}
627
628// A shadow's draw, every field of it as numbers.
629fn hash_shadow(hasher: &mut FxHasher, draw: &ShadowDraw) {
630    let ShadowDraw {
631        shadow:
632            ShadowRRect {
633                bounds,
634                radii,
635                umbra_inset,
636                distance_correction,
637                hole,
638            },
639        snap_anchor,
640        color,
641        clip,
642    } = draw;
643    hasher.write_u8(b's');
644    hash_rect(hasher, *bounds);
645    hash_floats(hasher, radii);
646    hash_floats(hasher, &[*umbra_inset, *distance_correction]);
647    match hole {
648        Some(ShadowHole { inset, radius }) => {
649            hasher.write_u8(1);
650            hash_floats(hasher, &[*inset, *radius]);
651        }
652        None => hasher.write_u8(0),
653    }
654    hash_point(hasher, *snap_anchor);
655    hash_color(hasher, *color);
656    hash_clip(hasher, *clip);
657}
658
659fn hash_floats(hasher: &mut FxHasher, values: &[f32]) {
660    for value in values {
661        hasher.write_u32(value.to_bits());
662    }
663}
664
665fn hash_color(hasher: &mut FxHasher, color: Color) {
666    hash_floats(hasher, &[color.0, color.1, color.2, color.3]);
667}
668
669fn hash_clip(hasher: &mut FxHasher, clip: Option<Rect>) {
670    match clip {
671        Some(clip) => {
672            hasher.write_u8(1);
673            hash_rect(hasher, clip);
674        }
675        None => hasher.write_u8(0),
676    }
677}
678
679fn hash_rect(hasher: &mut FxHasher, rect: Rect) {
680    hash_floats(hasher, &[rect.x, rect.y, rect.width, rect.height]);
681}
682
683fn hash_point(hasher: &mut FxHasher, point: Option<Point>) {
684    match point {
685        Some(point) => {
686            hasher.write_u8(1);
687            hash_floats(hasher, &[point.x, point.y]);
688        }
689        None => hasher.write_u8(0),
690    }
691}
692
693struct HashWriter(FxHasher);
694
695impl std::fmt::Write for HashWriter {
696    fn write_str(&mut self, text: &str) -> std::fmt::Result {
697        self.0.write(text.as_bytes());
698        Ok(())
699    }
700}
701
702#[cfg(test)]
703#[path = "tests/sprites_tests.rs"]
704mod tests;