1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use {
crate::{
buffer::BufferView,
render::State,
topology::{Topology, TriangleList},
vertex::{self, Vertex},
},
std::{borrow::Cow, marker::PhantomData, sync::Arc},
wgpu::{Buffer, Queue},
};
/// A data struct for a mesh creation.
#[derive(Clone)]
pub struct Data<'a, V, T = TriangleList>
where
T: Topology,
{
verts: &'a [V],
indxs: Option<Cow<'a, [T::Face]>>,
}
impl<'a, V, T> Data<'a, V, T>
where
T: Topology,
{
/// Creates a new [`MeshData`](crate::MeshData) from given vertices.
pub fn from_verts(verts: &'a [V]) -> Self {
Self { verts, indxs: None }
}
}
impl<'a, V> Data<'a, V> {
/// Creates a new [`MeshData`](crate::MeshData) from given vertices and indices.
///
/// # Errors
/// Will return
/// - [`MeshError::TooManyVertices`](crate::error::MeshError::TooManyVertices)
/// if vertices length doesn't fit in `u16`.
/// - [`MeshError::WrongIndex`](crate::error::MeshError::WrongIndex)
/// if the vertex index is out of bounds of the vertex slice.
pub fn new(verts: &'a [V], indxs: &'a [[u16; 3]]) -> Result<Self, Error> {
let len: u16 = verts.len().try_into().map_err(|_| Error::TooManyVertices)?;
if indxs.iter().flatten().any(|&i| i >= len) {
return Err(Error::WrongIndex);
}
Ok(Self {
verts,
indxs: Some(Cow::Borrowed(indxs)),
})
}
/// Creates a new [`MeshData`](crate::MeshData) from given quadrangles.
///
/// # Errors
/// Will return
/// - [`MeshError::TooManyVertices`](crate::error::MeshError::TooManyVertices)
/// if vertices length doesn't fit in `u16`.
pub fn from_quads(verts: &'a [[V; 4]]) -> Result<Self, Error> {
use std::slice;
let new_len = verts.len() * 4;
let len: u16 = new_len.try_into().map_err(|_| Error::TooManyVertices)?;
Ok(Self {
verts: unsafe { slice::from_raw_parts(verts.as_ptr().cast(), new_len) },
indxs: Some(
(0..len)
.step_by(4)
.flat_map(|i| [[i, i + 1, i + 2], [i, i + 2, i + 3]])
.collect(),
),
})
}
}
/// An error returned from the [`MeshData`](crate::MeshData) constructors.
#[derive(Debug)]
pub enum Error {
/// Vertices length doesn't fit in `u16`.
TooManyVertices,
/// The vertex index is out of bounds of the vertex slice.
WrongIndex,
}
/// The mesh object.
pub struct Mesh<V, T = TriangleList> {
verts: Buffer,
indxs: Option<Buffer>,
queue: Arc<Queue>,
ty: PhantomData<(V, T)>,
}
impl<V, T> Mesh<V, T> {
pub(crate) fn new(data: &Data<V, T>, state: &State) -> Self
where
V: Vertex,
T: Topology,
{
use wgpu::{
util::{BufferInitDescriptor, DeviceExt},
BufferUsages,
};
let device = state.device();
Self {
verts: device.create_buffer_init(&BufferInitDescriptor {
label: Some("vertex buffer"),
contents: vertex::verts_as_bytes(data.verts),
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
}),
indxs: data.indxs.as_deref().map(|indxs| {
device.create_buffer_init(&BufferInitDescriptor {
label: Some("index buffer"),
contents: bytemuck::cast_slice(indxs),
usage: BufferUsages::INDEX | BufferUsages::COPY_DST,
})
}),
queue: Arc::clone(state.queue()),
ty: PhantomData,
}
}
/// Updates the mesh with a new [data](`Data`).
///
/// # Errors
/// Will return
/// - [`MeshUpdateError::VertexSize`](crate::error::MeshUpdateError::VertexSize)
/// if a slice of vertices is passed with a wrong length.
/// - [`MeshUpdateError::IndexSize`](crate::error::MeshUpdateError::IndexSize)
/// if a slice of indices is passed with a wrong length.
/// - [`MeshUpdateError::NoIndices`](crate::error::MeshUpdateError::NoIndices)
/// if no indices are passed but they are required.
pub fn update(&mut self, data: &Data<V, T>) -> Result<(), UpdateError>
where
V: Vertex,
T: Topology,
{
let verts = data.verts;
if self.verts.size() != verts.len() as u64 {
return Err(UpdateError::VertexSize);
}
if let Some(indxs) = &data.indxs {
let buf = self.indxs.as_ref().ok_or(UpdateError::NoIndices)?;
if buf.size() != indxs.len() as u64 {
return Err(UpdateError::IndexSize);
}
self.queue.write_buffer(buf, 0, bytemuck::cast_slice(indxs));
}
self.queue
.write_buffer(&self.verts, 0, vertex::verts_as_bytes(verts));
Ok(())
}
/// Updates the mesh with new vertices.
///
/// # Errors
/// Will return
/// - [`MeshUpdateError::VertexSize`](crate::error::MeshUpdateError::VertexSize)
/// if a slice of vertices is passed with a length longer than the length of the mesh.
pub fn update_verts(&mut self, verts: &[V]) -> Result<(), UpdateError>
where
V: Vertex,
T: Topology,
{
if self.verts.size() < verts.len() as u64 {
return Err(UpdateError::VertexSize);
}
self.queue
.write_buffer(&self.verts, 0, vertex::verts_as_bytes(verts));
Ok(())
}
pub(crate) fn buffer(&self, limit: Option<u32>) -> MeshBuffer
where
T: Topology,
{
let limit = limit.map(|n| n * T::N as u32);
MeshBuffer {
verts: BufferView::new::<V>(&self.verts, limit),
indxs: self
.indxs
.as_ref()
.map(|buf| BufferView::new::<u16>(buf, limit)),
}
}
}
/// An error returned from the [`update`](Mesh::update) function.
#[derive(Debug)]
pub enum UpdateError {
/// A slice of vertices is passed with a wrong length.
VertexSize,
/// A slice of indices is passed with a wrong length.
IndexSize,
/// No indices are passed but they are required.
NoIndices,
}
#[derive(Clone, Copy)]
pub(crate) struct MeshBuffer<'a> {
pub verts: BufferView<'a>,
pub indxs: Option<BufferView<'a>>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_quads() {
let verts = [[0, 1, 2, 3], [4, 5, 6, 7]];
let data = Data::from_quads(&verts).expect("mesh data");
let indxs = data.indxs.expect("indices");
assert_eq!(data.verts.len(), 8);
assert_eq!(indxs.len(), 4);
assert_eq!([data.verts[0], data.verts[1], data.verts[2]], indxs[0]);
assert_eq!([data.verts[0], data.verts[2], data.verts[3]], indxs[1]);
assert_eq!([data.verts[4], data.verts[5], data.verts[6]], indxs[2]);
assert_eq!([data.verts[4], data.verts[6], data.verts[7]], indxs[3]);
}
}