1use core::hash::{Hash, Hasher};
2
3use blit::{FrameSlice, HasFrameStore, LogicalPoint, LogicalRect, Paint};
4
5use crate::{
6 color::Color,
7 display_list::{Compare, DisplayList},
8};
9
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Mesh<'a> {
12 pub vertices: &'a [MeshVertex],
13 pub indices: &'a [u32],
14}
15
16impl Mesh<'_> {
17 pub fn paint<C: HasFrameStore + Paint<FrameMesh, Scalar = f32>>(self, bounds: LogicalRect, context: &mut C) {
19 if self.indices.is_empty() || !self.is_valid() {
20 return;
21 }
22 let stored = FrameMesh {
23 vertices: context.store_mut().slice_from(self.vertices),
24 indices: context.store_mut().slice_from(self.indices),
25 };
26 context.paint(bounds, &stored);
27 }
28
29 pub fn is_valid(&self) -> bool {
30 self.indices.len().is_multiple_of(3)
31 && self.indices.iter().all(|index| (*index as usize) < self.vertices.len())
32 && self
33 .vertices
34 .iter()
35 .all(|vertex| vertex.position.x.is_finite() && vertex.position.y.is_finite())
36 }
37}
38
39impl Hash for Mesh<'_> {
40 fn hash<H: Hasher>(&self, state: &mut H) {
41 self.vertices.hash(state);
42 self.indices.hash(state);
43 }
44}
45
46#[derive(Clone, Copy)]
48pub struct FrameMesh {
49 pub vertices: FrameSlice<MeshVertex>,
50 pub indices: FrameSlice<u32>,
51}
52
53impl FrameMesh {
54 pub fn view<'a>(&self, list: &'a DisplayList) -> Mesh<'a> {
55 Mesh {
56 vertices: list.store().view(self.vertices),
57 indices: list.store().view(self.indices),
58 }
59 }
60}
61
62impl Compare for FrameMesh {
63 fn equal(a: &Self, left: &DisplayList, b: &Self, right: &DisplayList) -> bool {
64 a.view(left) == b.view(right)
65 }
66
67 fn hash(input: &Self, list: &DisplayList, state: &mut impl Hasher) {
68 input.view(list).hash(state);
69 }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct MeshVertex {
74 pub position: LogicalPoint,
75 pub color: Color,
76}
77
78impl MeshVertex {
79 pub const fn new(x: f32, y: f32, color: Color) -> Self {
80 Self {
81 position: LogicalPoint { x, y },
82 color,
83 }
84 }
85}
86
87impl Hash for MeshVertex {
88 fn hash<H: Hasher>(&self, state: &mut H) {
89 [self.position.x, self.position.y]
90 .map(|value| if value == 0.0 { 0 } else { value.to_bits() })
91 .hash(state);
92 self.color.hash(state);
93 }
94}