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
use crate::vertex::Vertex2D;
use crate::opengl::*;
use crate::graphics;
use crate::sys::Quad;
use std::mem;

#[derive(Debug, Copy, Clone)]
pub enum DataType {
    Byte = gl::BYTE as isize,
    // UByte = gl::UBYTE as isize,
    Short = gl::SHORT as isize,
    // UShort = gl::USHORT as isize,
    Int = gl::INT as isize,
    // UInt = gl::UINT as isize,
    Float = gl::FLOAT as isize
}

#[derive(Debug, Copy, Clone)]
pub enum DrawPrimitive {
    Points = gl::POINTS as isize,
    Lines = gl::LINES as isize,
    LineLoop = gl::LINE_LOOP as isize,
    LineStrip = gl::LINE_STRIP as isize,
    Triangles = gl::TRIANGLES as isize,
    TriangleStrip = gl::TRIANGLE_STRIP as isize,
    Quads = gl::QUADS as isize,
}

#[derive(Debug, Copy, Clone)]
pub enum DrawUsage {
    Static = gl::STATIC_DRAW as isize, 
    Dynamic = gl::DYNAMIC_DRAW as isize, 
    Stream = gl::STREAM_DRAW as isize
}

#[derive(Debug, Copy, Clone)]
pub enum BufferAccess {
    ReadOnly = gl::READ_ONLY as isize,
    WriteOnly = gl::WRITE_ONLY as isize,
    ReadWrite = gl::READ_WRITE as isize
}

#[derive(Debug, Copy, Clone)]
pub struct VertexAttribute {
    pub buffer_index: u32,
    pub elem_count: u32,
    pub is_instanced: bool,
    pub dtype: DataType,
    pub offset: usize,
    pub stride: usize
}

impl Default for VertexAttribute {
    fn default() -> Self {
        VertexAttribute {
            buffer_index: 0, elem_count: 0, is_instanced: false,
            dtype: DataType::Float, offset: 0, stride: 0
        }
    }
}

pub struct ElementBuffer {
    id: u32,
    pub count: u32
}

impl ElementBuffer {
    pub fn new(indicies: &[u32]) -> Self {
        ElementBuffer::new_with_draw(indicies, DrawUsage::Static)
    }

    pub fn new_with_draw(indicies: &[u32], usage: DrawUsage) -> Self {
        let eb = ElementBuffer {
            id: gl_gen_buffer(),
            count: indicies.len() as u32
        };
        eb.apply();

        unsafe {
            opengl().BufferData(gl::ELEMENT_ARRAY_BUFFER, (eb.count * mem::size_of::<u32>() as u32) as isize, indicies.as_ptr() as *const _, usage as u32)
        }
        eb
    }

    pub fn new_quad(count: u32) -> Self {
        let mut indicies: Vec<u32> = vec![0, count];
        let itr_range = 0..(indicies.len() / 6);

        for i in itr_range {
            let quad_index = i * 6;
            let vert_index = (i * 4) as u32;

            indicies[quad_index + 0] = vert_index + 0;
            indicies[quad_index + 1] = vert_index + 1;
            indicies[quad_index + 2] = vert_index + 2;

            indicies[quad_index + 3] = vert_index + 3;
            indicies[quad_index + 4] = vert_index + 4;
            indicies[quad_index + 5] = vert_index + 5;
        }

        ElementBuffer::new(indicies.as_slice())
    }

    pub fn apply(&self) {
        unsafe {
            opengl().BindBuffer(gl::ELEMENT_ARRAY_BUFFER, self.id)
        }
    }

    pub fn unbind(&self) {
        gl_unbind_element_buffer();
    }
}

pub struct RenderBuffer {
    id: u32
}

impl RenderBuffer {
    pub fn new(width: i32, height: i32) -> Self {
        let id = gl_gen_buffer();
        let rb = RenderBuffer { id };
        rb.apply();

        unsafe {
            opengl().RenderbufferStorage(gl::RENDERBUFFER, gl::DEPTH24_STENCIL8, width, height);
        };
        rb
    }

    pub fn apply(&self) {
        unsafe { opengl().BindBuffer(gl::RENDERBUFFER, self.id) };
    }
}

pub struct FrameBuffer {
    id: u32
}

impl FrameBuffer {
    pub fn new() -> Self {
        unsafe {
            let mut id = mem::zeroed();
            opengl().GenFramebuffers(1, &mut id);
            let fb = FrameBuffer { id };
            FrameBuffer::apply(&fb);
            return fb;
        }
    }

    pub fn apply(fb: &FrameBuffer) {
        unsafe {
            opengl().BindFramebuffer(gl::FRAMEBUFFER, fb.id)
        };
    }

    pub fn unbind() {
        unsafe {
            opengl().BindFramebuffer(gl::FRAMEBUFFER, 0)
        };
    }

    pub fn attach_render_buffer(&self, rb: &RenderBuffer) {
        FrameBuffer::apply(self);
        unsafe {
            opengl().FramebufferRenderbuffer(gl::FRAMEBUFFER, gl::DEPTH_STENCIL_ATTACHMENT, gl::RENDERBUFFER, rb.id)
        };
    }

    pub fn attach_texture(&self, texture: &graphics::Texture) {
        self.attach_texture_n(texture, 0);
    }

    pub fn attach_texture_n(&self, texture: &graphics::Texture, attachment_num: u32) {
        FrameBuffer::apply(self);
        unsafe {
            opengl().FramebufferTexture2D(gl::FRAMEBUFFER, gl::COLOR_ATTACHMENT0 + attachment_num, gl::TEXTURE_2D, texture.id(), 0);
        }
    }
}

pub struct VertexBuffer {
    id: u32,
    size_bytes: usize,
    vert_count: u32,
    pub draw_prim: DrawPrimitive,
    // TODO :: Ideally we should have this vertex attribute layout
    //         on a VAO, since its entire purpose is to store layout data for buffers... lol
    //         Move this to VAO
    pub layout: Vec<VertexAttribute>
}

// TODO :: Make this act like more like an actual buffer (have checks for overflow, ect)
impl VertexBuffer {


    /**
     * Returns VertexBuffer with default quad verts put into an OpenGL VBO instead of a runtime array
     */
    pub fn new_as_quad(useage: DrawUsage) -> Self {
        Self::new_with_prim(&Quad::default_verts(), useage, DrawPrimitive::TriangleStrip)
    }

    pub fn zeroed<T>(count: u32, usage: DrawUsage, draw_prim: DrawPrimitive) -> Self {
        let type_size = mem::size_of::<T>() as u32;
        let id = gl_gen_buffer();
        let size_bytes = (type_size * count) as isize;
        
        gl_bind_array_buffer(id);

        unsafe { opengl().BufferData(gl::ARRAY_BUFFER, size_bytes, 0 as *const _, usage as u32) };

        VertexBuffer {
            id, size_bytes: size_bytes as usize, vert_count: count, draw_prim, layout: Self::vertex2d_attributes()
        }
    }

    pub fn vertex2d_attributes() -> Vec<VertexAttribute> {
        
        let vert_size = std::mem::size_of::<Vertex2D>();
        // let uv_offset = 
        let mut attr = vec![VertexAttribute::default(); 3];
        attr[0] = VertexAttribute { buffer_index: 0, elem_count: 3, dtype: DataType::Float, stride: vert_size, offset: 0, is_instanced: false };
        attr[1] = VertexAttribute { buffer_index: 1, elem_count: 2, dtype: DataType::Float, stride: vert_size, offset: crate::memory_offset!(Vertex2D, text_coord), is_instanced: false };
        attr[2] = VertexAttribute { buffer_index: 2, elem_count: 4, dtype: DataType::Float, stride: vert_size, offset: crate::memory_offset!(Vertex2D, color), is_instanced: false };
        attr
        
    }

    /**
     * Uses default Float Datatype
    */
    pub fn new<T>(verts: &[T], usage: DrawUsage) -> Self {
        VertexBuffer::new_with_prim(verts, usage, DrawPrimitive::Triangles)
    }

    pub fn new_with_prim<T>(verts: &[T], usage: DrawUsage, draw_prim: DrawPrimitive) -> Self {
        let id = gl_gen_buffer();
        let size_bytes = mem::size_of::<T>() * verts.len();

        let mut vb = VertexBuffer {
            id, size_bytes, draw_prim, vert_count: verts.len() as u32, layout: Self::vertex2d_attributes()
        };
        vb.alloc(verts, usage);

        vb
    }
  
    /**
     * Uses default Float Datatype
    */
    pub fn alloc<T>(&mut self, verts: &[T], usage: DrawUsage) {
        self.apply();
        self.size_bytes = verts.len() * mem::size_of::<T>();
        self.vert_count = verts.len() as u32;

        unsafe { 
            opengl().BufferData(gl::ARRAY_BUFFER, self.size_bytes as isize, verts.as_ptr() as *const _, usage as u32) 
        };
    }

    pub fn write<T>(&self, verts: &[T],  offset: isize) {
        self.apply();
        unsafe {
            opengl().BufferSubData(gl::ARRAY_BUFFER, offset, (mem::size_of::<T>() * verts.len()) as isize, verts.as_ptr() as *const _)
        }
    }

    pub fn copy_data(&self, other: &VertexBuffer, read_offset: isize, write_offset: isize, size: isize) {
        let gl = opengl();
        unsafe { 
            gl.BindBuffer(gl::COPY_READ_BUFFER, other.id);
            gl.BindBuffer(gl::COPY_WRITE_BUFFER, self.id);
            gl.CopyBufferSubData(gl::COPY_READ_BUFFER, gl::COPY_WRITE_BUFFER, read_offset, write_offset, size);
        }
    }

    pub fn vert_count(&self) -> u32 { self.vert_count }

    pub unsafe fn map_buffer(&self, access: BufferAccess) -> *mut std::ffi::c_void {
        self.apply();
        opengl().MapBuffer(gl::ARRAY_BUFFER, access as u32)
    }

    pub unsafe fn unmap(&self) {
        self.apply();
        opengl().UnmapBuffer(gl::ARRAY_BUFFER);
    }

    pub fn apply(&self) {
        gl_bind_array_buffer(self.id)
    }

    pub fn unbind(&self) {
        gl_bind_array_buffer(0);
    }

}

pub struct VAO {
    id: u32
}

impl VAO {

    pub fn new() -> Self {
        VAO {
            id: gl_gen_vertex_array()
        }
    }

    pub fn set_buffer_layout(&self, buffer: &VertexBuffer) {
        self.apply();
        buffer.apply();

        let gl = opengl();
        for attrib in buffer.layout.iter() {
            unsafe {
                gl.VertexAttribPointer(
                    attrib.buffer_index, attrib.elem_count as i32, 
                    attrib.dtype as u32, gl::FALSE, attrib.stride as i32, 
                    attrib.offset as *const _
                );
                gl.EnableVertexAttribArray(attrib.buffer_index);
                gl.VertexAttribDivisor(attrib.buffer_index, if attrib.is_instanced { 1 } else { 0 });
            }
        }
        buffer.unbind();
        self.unbind();
    }

    pub fn apply(&self) {
        gl_bind_vertex_array(self.id);
    }

    pub fn unbind(&self) {
        gl_bind_vertex_array(0);
    }
}

impl Drop for ElementBuffer {

    fn drop(&mut self) { 
        gl_delete_buffer(self.id);
    }
}

impl Drop for RenderBuffer {

    fn drop(&mut self) { 
        unsafe { opengl().DeleteRenderbuffers(1, &self.id) }
    }
}

impl Drop for FrameBuffer {

    fn drop(&mut self) { 
        unsafe { opengl().DeleteFramebuffers(1, &self.id) }
    }
}

impl Drop for VertexBuffer {

    fn drop(&mut self) { 
        gl_delete_buffer(self.id)
    }
}

impl Drop for VAO {
    
    fn drop(&mut self) { 
        gl_delete_buffer(self.id)
    }
}

pub fn set_vertex_layout(buffer: &VertexBuffer, attribs: &[VertexAttribute]) {
let gl = opengl();
    buffer.apply();

   
}