-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGridMesh.cpp
More file actions
74 lines (64 loc) · 1.95 KB
/
GridMesh.cpp
File metadata and controls
74 lines (64 loc) · 1.95 KB
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
#include <cassert>
#include "GridMesh.h"
GridMesh::GridMesh(uint xDivs, uint yDivs) :
m_xDivs(xDivs),
m_yDivs(yDivs),
m_numIndices((xDivs - 1) * (yDivs - 1) * 6),
m_vbo(0),
m_ibo(0),
m_vao(0),
m_aabb(glm::vec3(0.0f), glm::vec3(1.0f))
{
assert(xDivs >= 2 && yDivs >= 2);
// using ushort for ibo
assert(xDivs * yDivs * 2 <= (1u << 16));
size_t vboSize = xDivs * yDivs * 2 * sizeof(float);
size_t iboSize = m_numIndices * sizeof(ushort);
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
float* vboData = new float[xDivs * yDivs * 2];
size_t i = 0;
for (uint y = 0; y < yDivs; ++y) {
for (uint x = 0; x < xDivs; ++x) {
vboData[i++] = x / float(xDivs - 1);
vboData[i++] = y / float(yDivs - 1);
}
}
glGenBuffers(1, &m_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, vboSize, (void*)vboData, GL_STATIC_DRAW);
delete[] vboData;
ushort* iboData = new ushort[m_numIndices];
i = 0;
for (uint x = 0; x + 1 < xDivs; ++x) {
for (uint y = 0; y + 1 < yDivs; ++y) {
// 1st triangle
iboData[i++] = (y + 1) * xDivs + x;
iboData[i++] = y * xDivs + x;
iboData[i++] = (y + 1) * xDivs + (x + 1);
// 2nd triangle
iboData[i++] = y * xDivs + x;
iboData[i++] = y * xDivs + (x + 1);
iboData[i++] = (y + 1) * xDivs + (x + 1);
}
}
glGenBuffers(1, &m_ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, iboSize, (void*)iboData, GL_STATIC_DRAW);
delete[] iboData;
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0); // unbind vao first so it remembers buffer
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void GridMesh::draw() {
glBindVertexArray(m_vao);
glDrawElements(GL_TRIANGLES, m_numIndices, GL_UNSIGNED_SHORT, (void*)0);
glBindVertexArray(0);
}
GridMesh::~GridMesh() {
glDeleteVertexArrays(1, &m_vao);
glDeleteBuffers(1, &m_vbo);
glDeleteBuffers(1, &m_ibo);
}