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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//! Wrapper for an OpenGL buffer object.

use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;

#[path = "../error.rs"]
mod error;

struct GLHandle {
    handle: GLuint
}

impl GLHandle {
    pub fn new(handle: GLuint) -> GLHandle {
        GLHandle {
            handle: handle
        }
    }

    pub fn handle(&self) -> GLuint {
        self.handle
    }
}

impl Drop for GLHandle {
    fn drop(&mut self) {
        unsafe {
            verify!(gl::DeleteBuffers(1, &self.handle))
        }
    }
}

// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVec<T> {
    trash:      bool,
    len:        usize,
    buf_type:   BufferType,
    alloc_type: AllocationType,
    handle:     Option<(usize, GLHandle)>,
    data:       Option<Vec<T>>,
}

// FIXME: implement Clone

impl<T: GLPrimitive> GPUVec<T> {
    /// Creates a new `GPUVec` that is not yet uploaded to the GPU.
    pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVec<T> {
        GPUVec {
            trash:      true,
            len:        data.len(),
            buf_type:   buf_type,
            alloc_type: alloc_type,
            handle:     None,
            data:       Some(data)
        }
    }

    /// The length of this vector.
    #[inline]
    pub fn len(&self) -> usize {
        if self.trash {
            match self.data {
                Some(ref d) => d.len(),
                None        => panic!("This should never happend.")

            }
        }
        else {
            self.len
        }
    }

    /// Mutably accesses the vector if it is available on RAM.
    ///
    /// This method will mark this vector as `trash`.
    #[inline]
    pub fn data_mut(&mut self) -> &mut Option<Vec<T>> {
        self.trash = true;

        &mut self.data
    }

    /// Immutably accesses the vector if it is available on RAM.
    #[inline]
    pub fn data(&self) -> &Option<Vec<T>> {
        &self.data
    }

    /// Returns `true` if this vector is already uploaded to the GPU.
    #[inline]
    pub fn is_on_gpu(&self) -> bool {
        self.handle.is_some()
    }

    /// Returns `true` if the cpu data and gpu data are out of sync.
    #[inline]
    pub fn trash(&self) -> bool {
        self.trash
    }

    /// Returns `true` if this vector is available on RAM.
    ///
    /// Note that a `GPUVec` may be both on RAM and on the GPU.
    #[inline]
    pub fn is_on_ram(&self) -> bool {
        self.data.is_some()
    }

    /// Loads the vector from the RAM to the GPU.
    ///
    /// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
    #[inline]
    pub fn load_to_gpu(&mut self) {
        if !self.is_on_gpu() {
            let buf_type   = self.buf_type;
            let alloc_type = self.alloc_type;
            let len        = &mut self.len;

            self.handle = self.data.as_ref().map(|d| {
                *len = d.len();
                (d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
            });
        }
        else if self.trash() {
            for d in self.data.iter() {
                self.len = d.len();

                match self.handle {
                    None => { },
                    Some((ref mut len, ref handle)) => {
                        let handle = handle.handle();

                        *len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
                    }
                }
            }
        }

        self.trash = false;
    }

    /// Binds this vector to the appropriate gpu array.
    ///
    /// This does not associate this buffer with any shader attribute.
    #[inline]
    pub fn bind(&mut self) {
        self.load_to_gpu();

        let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
        verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
    }

    /// Unbind this vector to the corresponding gpu buffer.
    #[inline]
    pub fn unbind(&mut self) {
        if self.is_on_gpu() {
            verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
        }
    }

    /// Loads the vector from the GPU to the RAM.
    ///
    /// If the vector is not available on the GPU or already loaded to the RAM, nothing will
    /// happen.
    #[inline]
    pub fn load_to_ram(&mut self) {
        if !self.is_on_ram() && self.is_on_gpu() {
            assert!(!self.trash);
            let     handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
            let mut data   = Vec::with_capacity(self.len);

            unsafe { data.set_len(self.len) };
            download_buffer(handle, self.buf_type, &mut data[..]);
            self.data = Some(data);
        }
    }

    /// Unloads this resource from the GPU.
    #[inline]
    pub fn unload_from_gpu(&mut self) {
        let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
        self.len    = self.len();
        self.handle = None;
        self.trash  = false;
    }

    /// Removes this resource from the RAM.
    ///
    /// This is useful to save memory for vectors required on the GPU only.
    #[inline]
    pub fn unload_from_ram(&mut self) {
        if self.trash && self.is_on_gpu() {
            self.load_to_gpu();
        }

        self.data = None;
    }
}

impl<T: Clone + GLPrimitive> GPUVec<T> {
    /// Returns this vector as an owned vector if it is available on RAM.
    ///
    /// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
    /// make the data accessible.
    #[inline]
    pub fn to_owned(&self) -> Option<Vec<T>> {
        self.data.as_ref().map(|d| d.clone())
    }
}

/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
    /// An array buffer bindable to a gl::ARRAY_BUFFER.
    Array,
    /// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
    ElementArray
}

impl BufferType {
    #[inline]
    fn to_gl(&self) -> GLuint {
        match *self {
            BufferType::Array        => gl::ARRAY_BUFFER,
            BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
        }
    }
}

/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
    /// STATIC_DRAW allocation type.
    StaticDraw,
    /// DYNAMIC_DRAW allocation type.
    DynamicDraw,
    /// STREAM_DRAW allocation type.
    StreamDraw
}

impl AllocationType {
    #[inline]
    fn to_gl(&self) -> GLuint {
        match *self {
            AllocationType::StaticDraw  => gl::STATIC_DRAW,
            AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
            AllocationType::StreamDraw  => gl::STREAM_DRAW
        }
    }
}

/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf:             &[T],
                                     buf_type:        BufferType,
                                     allocation_type: AllocationType)
                                     -> GLuint {
    // Upload values of vertices
    let mut buf_id: GLuint = 0;

    unsafe {
        verify!(gl::GenBuffers(1, &mut buf_id));
        let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
    }

    buf_id
}

/// Downloads a buffer from the gpu.
///
/// 
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
    unsafe {
        verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
        verify!(gl::GetBufferSubData(
                buf_type.to_gl(),
                0,
                (out.len() * mem::size_of::<T>()) as GLsizeiptr,
                mem::transmute(&out[0])));
    }
}

/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf:                 &[T],
                                     gpu_buf_len:         usize,
                                     gpu_buf_id:          GLuint,
                                     gpu_buf_type:        BufferType,
                                     gpu_allocation_type: AllocationType)
                                     -> usize {
    unsafe {
        verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));

        if buf.len() < gpu_buf_len {
            verify!(gl::BufferSubData(
                    gpu_buf_type.to_gl(),
                    0,
                    (buf.len() * mem::size_of::<T>()) as GLsizeiptr,
                    mem::transmute(&buf[0])));

            gpu_buf_len
        }
        else {
            verify!(gl::BufferData(
                    gpu_buf_type.to_gl(),
                    (buf.len() * mem::size_of::<T>()) as GLsizeiptr,
                    mem::transmute(&buf[0]),
                    gpu_allocation_type.to_gl()));

            buf.len()
        }
    }
}