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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use gl::types::*;
use std::marker::PhantomData;
use std::cell::RefCell;
use std::rc::Rc;
use std::marker;
use std::slice;
use std::mem;
use ::Result;
use state::StateRef;
use crate::{Error, gl};

use super::buffer::{Buffer, Builder};
#[cfg(all(not(feature = "gles"), not(feature="webgl")))]
use super::shared_storage::SharedBufferStorage;
#[cfg(not(feature="webgl"))]
use super::map::*;
use super::traits::*;
use super::range::Range;

// TODO: Mapping shared buffers in general can be problematic cause they could be mapped twice
// mostly when mapping ranges. Perhaps there could be a special clone of a SharedBuffer that
// allowed mapping but can only be cloned once. Perhaps on construction

/// Wrapper around a Buffer with internal reference counting
///
/// Useful for example when the same buffer or ranges of the same buffer are to be used in
/// different VAOs
#[derive(Debug, Eq, PartialEq)]
pub struct SharedBuffer<T>{
    buffer: Rc<RefCell<Buffer<u8>>>,
    marker: marker::PhantomData<T>,
}

impl<T> Clone for SharedBuffer<T>{
    fn clone(&self) -> SharedBuffer<T>{
        SharedBuffer{
            buffer: self.buffer.clone(),
            marker: PhantomData,
        }
    }
}


fn to_u8<T>(data: &[T]) -> &[u8]{
    let bytes = data.len() * mem::size_of::<T>();
    unsafe{ slice::from_raw_parts(data.as_ptr() as *const u8, bytes) }
}

#[cfg(not(feature="webgl"))]
fn to_t<T>(data: &[u8]) -> &[T]{
    let len = data.len() / mem::size_of::<T>();
    unsafe{ slice::from_raw_parts(data.as_ptr() as *const T, len) }
}

#[cfg(not(feature="webgl"))]
fn to_t_mut<T>(data: &mut [u8]) -> &mut [T]{
    let len = data.len() / mem::size_of::<T>();
    unsafe{ slice::from_raw_parts_mut(data.as_mut_ptr() as *mut T, len) }
}

pub struct SharedBuilder<'a>(pub(crate) &'a StateRef);

impl<'a> SharedBuilder<'a>{
    #[cfg(not(feature="webgl"))]
    pub fn create<T>(&self, len: usize, usage: GLenum) -> Result<SharedBuffer<T>>{
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).create(len, usage)?)),
            marker: PhantomData,
        })
    }

    /// Creates a new buffer and allocates it with enough capacity to hold `len` elements of type `T`
    ///
    /// equivalent to glGenBuffers/glCreateBuffers + gl(Named)BufferData.
    /// target specifies the target to which to bind the buffer before creation. This is
    /// only useful with no DSA where in certain platforms you can't change the target initially
    /// bound
    pub fn create_target<T>(&self, len: usize, usage: GLenum, target: GLenum) -> Result<SharedBuffer<T>>{
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).create_target(len * mem::size_of::<T>(), usage, target)?)),
            marker: PhantomData
        })
    }

    #[cfg(not(feature="webgl"))]
    pub fn empty<T>(&self) -> Result<SharedBuffer<T>>{
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).empty()?)),
            marker: PhantomData
        })
    }

    pub fn empty_target<T>(&self, target: GLenum) -> Result<SharedBuffer<T>>{
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).empty_target(target)?)),
            marker: PhantomData
        })
    }

    #[cfg(not(feature="webgl"))]
    pub fn from_data<T: 'static>(&self, data: &[T], usage: GLenum) -> Result<SharedBuffer<T>>{
        let u8_data = to_u8(data);
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).from_data(u8_data, usage)?)),
            marker: PhantomData
        })
    }

    pub fn from_data_target<T: 'static>(&self, data: &[T], usage: GLenum, target: GLenum) -> Result<SharedBuffer<T>>{
        let u8_data = to_u8(data);
        Ok(SharedBuffer{
            buffer: Rc::new(RefCell::new(Builder(self.0).from_data_target(u8_data, usage, target)?)),
            marker: PhantomData
        })
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn create_immutable<T>(&self, len: usize, flags: GLbitfield) -> Result<SharedBufferStorage<T>>
    where T: 'static
    {
        Builder(self.0)
            .create_immutable(len, flags)
            .map(SharedBufferStorage::from)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn create_immutable_target<T>(&self, len: usize, flags: GLbitfield, target: GLenum) -> Result<SharedBufferStorage<T>>
    where T: 'static
    {
        Builder(self.0)
            .create_immutable_target(len * mem::size_of::<T>(), flags, target)
            .map(SharedBufferStorage::from)
    }

    #[cfg(all(not(feature = "gles"), not(feature="webgl")))]
    pub fn immutable_from_data<T>(&self, data: &[T], flags: GLbitfield) -> Result<SharedBufferStorage<T>>
    where T: 'static
    {
        Builder(self.0)
            .immutable_from_data(data, flags)
            .map(SharedBufferStorage::from)
    }
}

impl<T: 'static> SharedBuffer<T>{
    // pub fn bind(&self, target: GLenum){
	// 	self.buffer.borrow().bind(target)
    // }

    // pub fn unbind(&self, target: GLenum){
	// 	self.buffer.borrow().unbind(target)
    // }

    // pub fn bind_base(&self, target: GLenum, index: GLuint){
	// 	self.buffer.borrow().bind_base(target, index)
    // }

    // pub fn unbind_base(&self, target: GLenum, index: GLuint){
	// 	self.buffer.borrow().unbind_base(target, index)
    // }

    pub fn load(&mut self, data: &[T], usage: GLenum){
        let u8_data = to_u8(data);
        (*self.buffer).borrow_mut().load(u8_data, usage);
    }

    /// Loads the passed data into the buffer (re)allocating it to an specific target
    ///
    /// see: gl(Named)BufferData
    pub fn load_target(&mut self, data: &[T], usage: GLenum, target: GLenum){
        let u8_data = to_u8(data);
        (*self.buffer).borrow_mut().load_target(u8_data, usage, target);
    }

    /// Reserves len amount of memory into the buffer (re)allocating it
    ///
    /// see: gl(Named)BufferData
    pub fn reserve(&mut self, len: usize, usage: GLenum){
        (*self.buffer).borrow_mut().reserve(len * mem::size_of::<T>(), usage);
    }

    /// Reserves len amount of memory into the buffer (re)allocating it to an specific target
    ///
    /// see: gl(Named)BufferData
    pub fn reserve_target(&mut self, len: usize, usage: GLenum, target: GLenum){
        (*self.buffer).borrow_mut().reserve_target(len * mem::size_of::<T>(), usage, target);
    }

    pub fn update(&mut self, data: &[T]){
        let u8_data = to_u8(data);
        (*self.buffer).borrow_mut().update(u8_data);
    }

    #[cfg(not(feature="webgl"))]
    pub fn with_map_read<F: FnMut(&[T])>(&self, flags: MapReadFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow_mut().with_map_read(flags, |u8_data| f(to_t(u8_data)))
    }

    #[cfg(not(feature="webgl"))]
    /// Unsafe cause reading from the mutable slice is undefined behaviour
    pub unsafe fn map_write<F: FnMut(&mut [T])>(&mut self, flags: MapWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow_mut()
            .map_write(flags)
            .map(|mut m| f(to_t_mut(m.data_mut())))
    }

    #[cfg(not(feature="webgl"))]
    pub fn map_read_write<F: FnMut(&mut [T])>(&mut self, flags: MapReadWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow_mut()
            .map_read_write(flags)
            .map(|mut m| f(to_t_mut(m.data_mut())))
    }

    pub fn copy_to<U,B:BufferRange<U> + WithBackendMut>(&self, dst: &mut B){
        (*self.buffer).borrow().copy_to(dst);
    }

    pub fn len(&self) -> usize{
        (*self.buffer).borrow().len() / mem::size_of::<T>()
    }

    pub fn is_empty(&self) -> bool{
        (*self.buffer).borrow().is_empty()
    }

    pub fn capacity(&self) -> usize{
        (*self.buffer).borrow().capacity() / mem::size_of::<T>()
    }

    pub fn bytes(&self) -> usize{
        (*self.buffer).borrow().bytes()
    }

    pub fn capacity_bytes(&self) -> usize{
        (*self.buffer).borrow().capacity_bytes()
    }

    pub fn id(&self) -> GLuint{
        (*self.buffer).borrow().id()
    }

    pub fn stride(&self) -> usize{
        (*self.buffer).borrow().stride()
    }

    pub fn range<R: InputRange>(&self, range: R) -> Range<T, SharedBuffer<T>, SharedBuffer<T>>{
        Range{
            buffer: self.clone(),
            range: range.to_range(self),
            marker_type: PhantomData,
            marker_buffer: PhantomData,
        }
    }

    /// Get a mutable range from the buffer
    ///
    /// Useful to do operations on portions of the buffer
    ///
    /// Panics if the range is out of bounds
    pub fn range_mut<R: InputRange>(&mut self, range: R) -> Range<T, SharedBuffer<T>, SharedBuffer<T>>{
        Range{
            range: range.to_range(self),
            buffer: self.clone(),
            marker_type: PhantomData,
            marker_buffer: PhantomData,
        }
    }
}

impl SharedBuffer<u8>{
    pub fn cast<T>(self) -> SharedBuffer<T>{
        SharedBuffer{
            buffer: self.buffer,
            marker: PhantomData,
        }
    }
}

impl<T: 'static> Cast<T> for SharedBuffer<u8>{
    type CastTo = SharedBuffer<T>;
    fn cast(self) -> SharedBuffer<T>{
        SharedBuffer {
            buffer: self.buffer,
            marker: PhantomData,
        }
    }
}


impl<T: 'static> TypedBuffer<T> for SharedBuffer<T>{
    fn id(&self) -> GLuint{
        (*self).id()
    }

    fn len(&self) -> usize{
        (*self).len()
    }

    fn capacity(&self) -> usize{
        (*self).capacity()
    }

    #[cfg(not(feature="webgl"))]
    fn with_map_read<F: FnMut(&[T])>(&self, flags: MapReadFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow().with_map_read(flags, |u8_data| f(to_t(u8_data)))
    }

    fn copy_to<U,B:BufferRange<U> + WithBackendMut>(&self, dst: &mut B){
        self.copy_to(dst)
    }

    #[cfg(not(feature="webgl"))]
    unsafe fn unmap(&self){
        self.buffer.borrow().unmap()
    }
}

impl<'a, T: 'static> TypedBufferMut<T> for SharedBuffer<T> {
    #[cfg(not(feature="webgl"))]
    unsafe fn with_map_write<F: FnMut(&mut [T])>(&mut self,flags: MapWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow_mut()
            .map_write(flags)
            .map(|mut m| f(to_t_mut(m.data_mut())))
    }

    #[cfg(not(feature="webgl"))]
    fn with_map_read_write<F: FnMut(&mut [T])>(&mut self, flags: MapReadWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer).borrow_mut()
            .map_read_write(flags)
            .map(|mut m| f(to_t_mut(m.data_mut())))
    }
}

impl<T: 'static> BufferRange<T> for SharedBuffer<T>{
    fn start(&self) -> usize{
        0
    }

    fn end(&self) -> usize{
        self.len()
    }

    fn into_range<R: InputRange>(self, range: R) -> super::Range<T, Self, Self> where Self: Sized{
        Range{
            range: range.to_range(&self),
            buffer: self,
            marker_type: PhantomData,
            marker_buffer: PhantomData,
        }
    }
}

impl<T:'static> BufferRangeMut<T> for SharedBuffer<T>{
    fn update(&mut self, data: &[T]){
        self.update(data);
    }
}

impl<T> WithBackend for SharedBuffer<T>{
    fn with_backend<F:FnMut(&dyn Backend)->R, R>(&self, f:F) -> R{
        (*self.buffer).borrow().with_backend(f)
    }
}

impl<T> WithBackendMut for SharedBuffer<T>{
    fn with_backend_mut<F:FnMut(&mut dyn Backend)->R, R>(&mut self, f:F) -> R{
        (*self.buffer).borrow_mut().with_backend_mut(f)
    }
}

#[cfg(not(feature="webgl"))]
impl<T> WithMapRange<T> for SharedBuffer<T>{
    fn with_map_range_read<F: FnMut(&[T])>(&self, offset: usize, length: usize, flags: MapReadFlags, mut f: F) -> Result<()>{
        (*self.buffer)
            .borrow()
            .with_map_range_read(offset, length, flags, |u8_data| f(to_t(u8_data)))
    }
}

#[cfg(not(feature="webgl"))]
impl<T> WithMapRangeMut<T> for SharedBuffer<T>{
    unsafe fn with_map_range_write<F: FnMut(&mut [T])>(&mut self, offset: usize, length: usize, flags: MapWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer)
            .borrow_mut()
            .with_map_range_write(offset, length, flags, |u8_data| f(to_t_mut(u8_data)))
    }

    fn with_map_range_read_write<F: FnMut(&mut [T])>(&mut self, offset: usize, length: usize, flags: MapReadWriteFlags, mut f: F) -> Result<()>{
        (*self.buffer)
            .borrow_mut()
            .with_map_range_read_write(offset, length, flags, |u8_data| f(to_t_mut(u8_data)))
    }
}

impl<T: 'static> From<Buffer<T>> for SharedBuffer<T>{
    fn from(buffer: Buffer<T>) -> SharedBuffer<T>{
        let buffer = Buffer{
            len: buffer.bytes(),
            reserved: buffer.capacity_bytes(),
            backend: buffer.backend,
            marker: marker::PhantomData,
        };
        SharedBuffer{
            buffer: Rc::new(RefCell::new(buffer)),
            marker: PhantomData,
        }
    }
}

impl<'a, T: 'static> TypedBuffer<T> for &SharedBuffer<T>{
    fn id(&self) -> GLuint{
        (*self).id()
    }

    fn len(&self) -> usize{
        (*self).len()
    }

    fn capacity(&self) -> usize{
        (*self).capacity()
    }

    #[cfg(not(feature="webgl"))]
    fn with_map_read<F: FnMut(&[T])>(&self, flags: MapReadFlags, f: F) -> Result<()>{
        (*self).with_map_read(flags, f)
    }

    fn copy_to<U, BB:BufferRange<U> + WithBackendMut>(&self, dst: &mut BB) where Self: Sized{
        (*self).copy_to(dst)
    }

    #[cfg(not(feature="webgl"))]
    unsafe fn unmap(&self){
        (*self).unmap()
    }
}

impl<'a, T: 'static> BufferRange<T> for &SharedBuffer<T>{
    fn start(&self) -> usize{
        0
    }

    fn end(&self) -> usize{
        (*self).len()
    }

    fn into_range<R: InputRange>(self, range: R) -> super::Range<T, Self, Self> where Self: Sized{
        Range{
            range: range.to_range(&self),
            buffer: self,
            marker_type: PhantomData,
            marker_buffer: PhantomData,
        }
    }
}


#[cfg(not(feature="webgl"))]
impl<'a, T> MapRange<T> for SharedBuffer<T>{
    fn map_range_read(&mut self, offset: usize, length: usize, flags: MapReadFlags) -> Result<MapRead<T, Self>>{
        if offset + length > self.capacity() {
            return Err(Error::new(::ErrorKind::OutOfBounds,None));
        }
        let bytes_offset = offset * mem::size_of::<T>();
        let length_offset = length  * mem::size_of::<T>();
        let data = unsafe{ self.buffer.borrow().backend.map_range(
            bytes_offset as GLintptr,
            length_offset as GLsizeiptr,
            gl::MAP_READ_BIT | flags.bits()
        ) };
        if data.is_null() {
            Err(Error::new(::ErrorKind::MapError,None))
        }else{
            unsafe{
                let slice = slice::from_raw_parts(data as *const T, length); // TODO: Map as len for read?
                Ok(MapRead{
                    map: slice,
                    buffer: self
                })
            }
        }
    }
}

#[cfg(not(feature = "webgl"))]
impl<'a, T> MapRangeMut<T> for SharedBuffer<T>{
    fn map_range_write(&mut self, offset: usize, length: usize, flags: MapWriteFlags) -> Result<MapWrite<T, Self>>{
        if offset + length > self.capacity() {
            return Err(Error::new(::ErrorKind::OutOfBounds,None));
        }
        let bytes_offset = offset * mem::size_of::<T>();
        let length_offset = length  * mem::size_of::<T>();
        let data = unsafe{ self.buffer.borrow().backend.map_range(
            bytes_offset as GLintptr,
            length_offset as GLsizeiptr,
            gl::MAP_WRITE_BIT | flags.bits()
        ) };
        if data.is_null(){
            Err(Error::new(::ErrorKind::MapError,None))
        }else{
            unsafe{
                let slice = slice::from_raw_parts_mut(data as *mut T, length); // TODO: Map as len for read?
                Ok(MapWrite{
                    map: slice,
                    dropper: MapDropper{ buffer: self }
                })
            }
        }
    }

    fn map_range_read_write(&mut self, offset: usize, length: usize, flags: MapReadWriteFlags) -> Result<MapReadWrite<T, Self>>{
        if offset + length > self.capacity(){
            return Err(Error::new(::ErrorKind::OutOfBounds,None));
        }
        let bytes_offset = offset * mem::size_of::<T>();
        let length_offset = length  * mem::size_of::<T>();
        let data = unsafe{ self.buffer.borrow().backend.map_range(
            bytes_offset as GLintptr,
            length_offset as GLsizeiptr,
            gl::MAP_READ_BIT | gl::MAP_WRITE_BIT | flags.bits()
        ) };
        if data.is_null(){
            Err(Error::new(::ErrorKind::MapError,None))
        }else{
            unsafe{
                let slice = slice::from_raw_parts_mut(data as *mut T, length); // TODO: Map as len for read?
                Ok(MapReadWrite{
                    map: slice,
                    dropper: MapDropper{buffer: self}
                })
            }
        }
    }
}