-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.cpp
More file actions
128 lines (99 loc) · 2.44 KB
/
Model.cpp
File metadata and controls
128 lines (99 loc) · 2.44 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
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
#include "Model.h"
#include <iostream>
Model::~Model()
{
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
}
bool Model::Load(const char *filepath)
{
union
{
void *v;
char *u8;
unsigned short *u16;
float *f;
__fp16 *h;
} file;
unsigned filesize;
char *_file = GLWindow::LoadFile(filepath, &filesize);
file.u8 = _file;
if(filesize < 5)
{
delete [] _file;
return false;
}
char flags = *file.u8++;
indexbuffersize = *file.u16++;
vertexbuffersize = *file.u16++;
if(vertexbuffersize <= 256)
indextype = GL_UNSIGNED_BYTE;
else
indextype = GL_UNSIGNED_SHORT;
switch(flags & 3)
{
case 3: // half!
vertextype = GL_HALF_FLOAT_OES;
normaloffset = uvoffset = stride = 3 * 2;
break;
case 2: // u16!
vertextype = GL_UNSIGNED_SHORT;
normaloffset = uvoffset = stride = 3 * 2;
break;
default: // float!
vertextype = GL_FLOAT;
normaloffset = uvoffset = stride = 3 * 4;
}
if(flags & 0x80) // no normals!
hasnormals = false;
else
{
hasnormals = true;
stride += 3;
uvoffset += 3;
}
if(flags & 0x40) // no texture coordinates!
hastextures = false;
else
{
hastextures = true;
stride += 2 * 2;
}
unsigned truelength = 5 + indexbuffersize * (indextype == GL_UNSIGNED_BYTE ? 1 : 2) + stride * vertexbuffersize;
if(filesize != truelength)
{
delete [] _file;
return false;
}
char *indexbuffer = file.u8;
char *vertexbuffer = file.u8 + indexbuffersize * (indextype == GL_UNSIGNED_BYTE ? 1 : 2);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertexbuffersize * stride, (void*)vertexbuffer, GL_STATIC_DRAW);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexbuffersize * (indextype == GL_UNSIGNED_BYTE ? 1 : 2), (void*)indexbuffer, GL_STATIC_DRAW);
delete [] _file;
return true;
}
void Model::Draw()
{
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glVertexAttribPointer(0, 3, vertextype, GL_FALSE, stride, 0);
if(hastextures)
{
glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_TRUE, stride, (void*)uvoffset);
glEnableVertexAttribArray(1);
}
if(hasnormals)
{
glVertexAttribPointer(2, 3, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)normaloffset);
glEnableVertexAttribArray(2);
}
glDrawElements(GL_TRIANGLES, indexbuffersize, indextype, 0);
if(hasnormals)
glDisableVertexAttribArray(2);
if(hastextures)
glDisableVertexAttribArray(1);
}