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