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
extern crate glium;
use glium::buffer::{BufferMutSlice, BufferSlice};
use glium::vertex::{Vertex, VertexBuffer, VertexBufferAny, VerticesSource};
use std::any::TypeId;
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Deref;
pub struct TypedVertexBufferAny {
type_id: TypeId,
buffer: VertexBufferAny,
}
impl TypedVertexBufferAny {
pub fn as_typed_slice<T: Vertex + Send + 'static>(
&self,
) -> Result<BufferSlice<[T]>, IncorrectTypeError> {
if self.type_id == TypeId::of::<T>() {
Ok(unsafe { self.buffer.deref().as_typed_slice() })
} else {
Err(IncorrectTypeError)
}
}
pub fn as_typed_slice_mut<T: Vertex + Send + 'static>(
&mut self,
) -> Result<BufferMutSlice<[T]>, IncorrectTypeError> {
if self.type_id == TypeId::of::<T>() {
Ok(unsafe { self.buffer.as_typed_slice_mut() })
} else {
Err(IncorrectTypeError)
}
}
}
impl<T> From<VertexBuffer<T>> for TypedVertexBufferAny
where
T: Vertex + Send + 'static,
{
fn from(buffer: VertexBuffer<T>) -> TypedVertexBufferAny {
TypedVertexBufferAny {
type_id: TypeId::of::<T>(),
buffer: buffer.into(),
}
}
}
impl<'a> Into<VerticesSource<'a>> for &'a TypedVertexBufferAny {
fn into(self) -> VerticesSource<'a> {
(&self.buffer).into()
}
}
#[derive(Copy, Clone, Debug)]
pub struct IncorrectTypeError;
impl Error for IncorrectTypeError {}
impl Display for IncorrectTypeError {
fn fmt(&self, formatter: &mut Formatter) -> FmtResult {
write!(formatter, "incorrect buffer type")
}
}