Skip to main content

mln_engine/draw/
indexes.rs

1//! The indexes of draws. A draw owns indexes of its own ([`Indexes`]), and
2//! holds those it shares with other draws, such as a tile's bucket's or a
3//! layer's quad, in the context's store ([`SharedIndexes`]). The first
4//! draw's upload writes them to a buffer of the context's `Gpu`, freeing
5//! their data.
6
7use mln_gfx::gpu::{BufferId, BufferUsage, Gpu, GpuError};
8#[cfg(target_family = "wasm")]
9use mln_wire::host_bytes::HostBytes;
10
11use crate::draw::buffer::Buffer;
12use crate::draw::context::Context;
13use crate::draw::owned::Held;
14use crate::draw::resources::Device;
15pub(crate) use crate::draw::store::SharedIndexes;
16
17/// The indexes before their upload.
18enum IndexData {
19    Vec(Vec<u16>),
20    /// The indexes in the JS array they arrived in, which the upload
21    /// writes from there.
22    #[cfg(target_family = "wasm")]
23    Host(HostBytes),
24}
25
26/// Where the indexes are.
27enum Place {
28    Data(IndexData),
29    Buffer(Buffer),
30}
31
32/// Indexes, which don't change once made: an upload moves them into their
33/// buffer.
34pub struct Indexes {
35    len: usize,
36    place: Place,
37}
38
39impl Indexes {
40    /// Indexes holding `indexes`.
41    #[must_use]
42    pub fn new(indexes: Vec<u16>) -> Indexes {
43        Indexes { len: indexes.len(), place: Place::Data(IndexData::Vec(indexes)) }
44    }
45
46    /// Indexes holding the indexes in a JS array.
47    #[cfg(target_family = "wasm")]
48    #[must_use]
49    pub(crate) fn from_host(indexes: HostBytes) -> Indexes {
50        debug_assert!(indexes.len().is_multiple_of(size_of::<u16>()));
51        Indexes { len: indexes.len() / size_of::<u16>(), place: Place::Data(IndexData::Host(indexes)) }
52    }
53
54    /// The number of indexes, which stays once the upload freed them.
55    #[must_use]
56    pub(crate) fn len(&self) -> usize {
57        self.len
58    }
59
60    /// Whether the CPU copy of the indexes is still there.
61    #[must_use]
62    pub(crate) fn has_data(&self) -> bool {
63        matches!(self.place, Place::Data(_))
64    }
65
66    /// The buffer of the indexes, once uploaded.
67    #[must_use]
68    fn buffer(&self) -> Option<BufferId> {
69        match &self.place {
70            Place::Buffer(buffer) => Some(buffer.id()),
71            Place::Data(_) => None,
72        }
73    }
74
75    /// Writes the indexes to a buffer of `gpu` through `device`, unless
76    /// they have one, and frees them. Indexes that fail to upload stay for
77    /// the next try.
78    pub(crate) fn upload(&mut self, gpu: &mut dyn Gpu, device: &mut Device) -> Result<(), GpuError> {
79        let Place::Data(data) = &self.place else {
80            return Ok(());
81        };
82        let buffer = match data {
83            IndexData::Vec(indexes) => device.buffer(gpu, BufferUsage::Index, bytemuck::cast_slice(indexes))?,
84            #[cfg(target_family = "wasm")]
85            IndexData::Host(bytes) => device.buffer_from_host(gpu, BufferUsage::Index, bytes)?,
86        };
87        self.place = Place::Buffer(buffer);
88        Ok(())
89    }
90}
91
92/// The indexes a draw binds: its own, or those it shares through the
93/// context's store.
94pub enum DrawIndexes {
95    Own(Indexes),
96    Shared(SharedIndexes),
97}
98
99impl From<Indexes> for DrawIndexes {
100    fn from(indexes: Indexes) -> DrawIndexes {
101        DrawIndexes::Own(indexes)
102    }
103}
104
105impl From<SharedIndexes> for DrawIndexes {
106    fn from(indexes: SharedIndexes) -> DrawIndexes {
107        DrawIndexes::Shared(indexes)
108    }
109}
110
111impl DrawIndexes {
112    /// The draw's own indexes holding `indexes`.
113    #[must_use]
114    pub fn new(indexes: Vec<u16>) -> DrawIndexes {
115        DrawIndexes::Own(Indexes::new(indexes))
116    }
117
118    /// The indexes, the draw's own or the store's.
119    fn indexes<'a>(&'a self, context: &'a Context) -> Option<&'a Indexes> {
120        match self {
121            DrawIndexes::Own(indexes) => Some(indexes),
122            DrawIndexes::Shared(shared) => context.indexes(shared),
123        }
124    }
125
126    /// The number of indexes, which stays once the upload freed them.
127    #[must_use]
128    pub fn len(&self, context: &Context) -> usize {
129        self.indexes(context).map_or(0, Indexes::len)
130    }
131
132    /// Whether the CPU copy of the indexes is still there.
133    pub fn has_data(&self, context: &Context) -> bool {
134        self.indexes(context).is_some_and(Indexes::has_data)
135    }
136
137    /// Writes the indexes to a buffer of `gpu`, unless they have one.
138    pub fn upload(&mut self, gpu: &mut dyn Gpu, context: &mut Context) -> Result<(), GpuError> {
139        match self {
140            DrawIndexes::Own(indexes) => indexes.upload(gpu, context.device()),
141            DrawIndexes::Shared(shared) => context.upload_indexes(gpu, shared),
142        }
143    }
144
145    /// The buffer of the indexes, once uploaded.
146    #[must_use]
147    pub fn buffer(&self, context: &Context) -> Option<BufferId> {
148        self.indexes(context).and_then(Indexes::buffer)
149    }
150
151    /// What geometry made of the indexes holds: the store's indexes, which
152    /// other draws share. The draw keeps its own.
153    pub(crate) fn held(&self) -> Option<Held> {
154        match self {
155            DrawIndexes::Own(_) => None,
156            DrawIndexes::Shared(shared) => Some(Held::Indexes(shared.clone())),
157        }
158    }
159}