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
|
use std::marker::PhantomData;
use std::mem::size_of_val;
use crate::opengl::currently_bound::CurrentlyBound;
#[derive(Debug)]
pub struct Buffer<Item, ModeT: Mode>
{
buffer: gl::types::GLuint,
_item_pd: PhantomData<Item>,
_mode_pd: PhantomData<ModeT>,
}
impl<Item, ModeT: Mode> Buffer<Item, ModeT>
{
pub fn new() -> Self
{
let mut buffer = gl::types::GLuint::default();
unsafe {
gl::GenBuffers(1, &mut buffer);
};
Self {
buffer,
_item_pd: PhantomData,
_mode_pd: PhantomData,
}
}
#[allow(clippy::inline_always)]
#[inline(always)]
pub fn bind(&self, cb: impl FnOnce(CurrentlyBound<'_, Self>))
{
unsafe {
gl::BindBuffer(ModeT::GL_ENUM, self.buffer);
}
// SAFETY: The buffer object is bound above
let currently_bound = unsafe { CurrentlyBound::new() };
cb(currently_bound);
}
/// Stores items in the currently bound buffer.
pub fn store(_currently_bound: &CurrentlyBound<Self>, items: &[Item], usage: Usage)
{
unsafe {
#[allow(clippy::cast_possible_wrap)]
gl::BufferData(
ModeT::GL_ENUM,
size_of_val(items) as gl::types::GLsizeiptr,
items.as_ptr().cast(),
usage.into_gl(),
);
}
}
}
impl<Item, ModeT: Mode> Drop for Buffer<Item, ModeT>
{
fn drop(&mut self)
{
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
unsafe {
gl::DeleteBuffers(1, &self.buffer);
}
}
}
/// Buffer usage.
#[derive(Debug)]
#[allow(dead_code)]
pub enum Usage
{
/// The buffer data is set only once and used by the GPU at most a few times.
Stream,
/// The buffer data is set only once and used many times.
Static,
/// The buffer data is changed a lot and used many times.
Dynamic,
}
impl Usage
{
fn into_gl(self) -> gl::types::GLenum
{
match self {
Self::Stream => gl::STREAM_DRAW,
Self::Static => gl::STATIC_DRAW,
Self::Dynamic => gl::DYNAMIC_DRAW,
}
}
}
/// Buffer mode.
pub trait Mode
{
#[doc(hidden)]
const GL_ENUM: gl::types::GLenum;
}
/// Array buffer kind.
#[derive(Debug)]
pub struct ArrayKind;
impl Mode for ArrayKind
{
const GL_ENUM: gl::types::GLenum = gl::ARRAY_BUFFER;
}
/// Element array buffer kind.
#[derive(Debug)]
pub struct ElementArrayKind;
impl Mode for ElementArrayKind
{
const GL_ENUM: gl::types::GLenum = gl::ELEMENT_ARRAY_BUFFER;
}
|