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
//! The definitions of [`Vertex`], [`Mesh`] and their implementations.

use web_sys::{WebGlBuffer, WebGlVertexArrayObject};

use crate::{gl, GL};

/// The `Vertex` struct holds the data that will be later sent to WebGL in a `GL::ARRAY_BUFFER`.
/// It consists of position and color vectors, and UV co-ordinates.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct Vertex {
    /// A two component array of [`f32`], representing the position of the [`Vertex`].
    pub position: [f32; 2],
    /// A two component array of [`f32`], representing the UV co-ordinates of the [`Vertex`].
    pub uv: [f32; 2],
    /// A four component array of [`f32`], representing the color of the [`Vertex`].
    pub color: [f32; 4],
}

impl Default for Vertex {
    fn default() -> Self {
        Self {
            position: [0.0, 0.0],
            uv: [0.0, 0.0],
            color: [1.0, 1.0, 1.0, 1.0],
        }
    }
}

/// An indiced [`Mesh`], stored along with it's vertex array, index array and vertex buffer.
#[derive(Debug)]
pub struct Mesh {
    /// Vertices of the Mesh.
    ///
    /// Represented as a [`Vec`] of [`Vertex`]s.
    pub vertices: Vec<Vertex>,
    /// Indices of the Mesh.
    ///
    /// Stored as a [`Vec`] of [`u32`].
    pub indices: Vec<u32>,
    vao: WebGlVertexArrayObject,
    vbo: WebGlBuffer,
    ibo: WebGlBuffer,
}

impl Drop for Mesh {
    fn drop(&mut self) {
        use gl::Bind;
        let gl = gl::get_context();
        self.unbind(&gl);

        gl.delete_buffer(Some(&self.vbo));
        gl.delete_buffer(Some(&self.ibo));
        self.vertices.clear();
        self.indices.clear();
        gl.delete_vertex_array(Some(&self.vao));
    }
}

impl gl::Bind for Mesh {
    /// Bind the `WebGlVertexArrayObject` of the `Mesh`.
    fn bind(&self, gl: &GL) {
        gl.bind_vertex_array(Some(&self.vao));
    }
    fn unbind(&self, gl: &GL) {
        gl.bind_vertex_array(None);
    }
}

impl Mesh {
    /// Create a new [`Mesh`] with the given [`vertices`](Vertex) and indices.
    pub fn new(gl: &GL, vertices: Vec<Vertex>, indices: Vec<u32>) -> Self {
        Self {
            vertices,
            indices,
            vao: {
                let vao = gl
                    .create_vertex_array()
                    .expect("Could not create Vertex Array Object.");
                gl.bind_vertex_array(Some(&vao));
                vao
            },
            vbo: gl.create_buffer().expect("Could not create Buffer."),
            ibo: gl.create_buffer().expect("Could not create Buffer."),
        }
    }
    /// Create a new Quad mesh with a side length of 1m
    pub fn quad(gl: &GL) -> Self {
        Self::quad_with_side(gl, 1.0)
    }
    /// Create a new Quad mesh with a given side length
    pub fn quad_with_side(gl: &GL, side: f32) -> Self {
        let half = side / 2.0;
        let vertices = vec![
            Vertex {
                position: [-half, half],
                uv: [0.0, 0.0],
                ..Default::default()
            },
            Vertex {
                position: [-half, -half],
                uv: [0.0, 1.0],
                ..Default::default()
            },
            Vertex {
                position: [half, -half],
                uv: [1.0, 1.0],
                ..Default::default()
            },
            Vertex {
                position: [half, half],
                uv: [1.0, 0.0],
                ..Default::default()
            },
        ];
        let indices: Vec<u32> = vec![0, 2, 1, 0, 3, 2];
        Self::new(gl, vertices, indices)
    }

    /// Set up the vertex (vbo) and index (ibo) `WebGlBuffer` and send their data to the GPU.
    pub fn setup(&self, gl: &GL) {
        use gl::Bind;
        self.bind(gl);

        gl.bind_buffer(GL::ARRAY_BUFFER, Some(&self.vbo));
        gl.bind_buffer(GL::ELEMENT_ARRAY_BUFFER, Some(&self.ibo));

        let vertex_slice = unsafe {
            std::slice::from_raw_parts(
                self.vertices.as_ptr() as *const u8,
                self.vertices.len() * std::mem::size_of::<Vertex>(),
            )
        };
        let index_slice = unsafe {
            std::slice::from_raw_parts(
                self.indices.as_ptr() as *const u8,
                self.indices.len() * std::mem::size_of::<u32>(),
            )
        };

        gl.buffer_data_with_u8_array(GL::ARRAY_BUFFER, vertex_slice, GL::DYNAMIC_DRAW);
        gl.buffer_data_with_u8_array(GL::ELEMENT_ARRAY_BUFFER, index_slice, GL::DYNAMIC_DRAW);

        gl.vertex_attrib_pointer_with_i32(0, 2, GL::FLOAT, false, 8 * 4, 0);
        gl.vertex_attrib_pointer_with_i32(1, 2, GL::FLOAT, false, 8 * 4, 8);
        gl.vertex_attrib_pointer_with_i32(2, 4, GL::FLOAT, false, 8 * 4, 16);

        gl.enable_vertex_attrib_array(0);
        gl.enable_vertex_attrib_array(1);
        gl.enable_vertex_attrib_array(2);
    }
}