labyrinth

view src/mesh.c @ 5:c8826e5ebec1

- changed every data loading function to return dummy objects instead of failing - fixed mistake in AndroidManifest.xml
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 01 May 2015 05:58:41 +0300
parents 45b91185b298
children
line source
1 #include <stdlib.h>
2 #include <assert.h>
3 #include "opengl.h"
4 #include "mesh.h"
5 #include "objfile.h"
7 static struct vec3 def_verts[] = {
8 {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, -1, 1}, {1, 1, 1}, {-1, 1, 1},
9 {1, -1, 1}, {1, -1, -1}, {1, 1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1},
10 {1, -1, -1}, {-1, -1, -1}, {-1, 1, -1}, {1, -1, -1}, {-1, 1, -1}, {1, 1, -1},
11 {-1, -1, -1}, {-1, -1, 1}, {-1, 1, 1}, {-1, -1, -1}, {-1, 1, 1}, {-1, 1, -1}
12 };
13 #define FACEATTR(x, y, z) {x, y, z}, {x, y, z}, {x, y, z}, {x, y, z}, {x, y, z}, {x, y, z}
14 static struct vec3 def_norm[] = {
15 FACEATTR(0, 0, 1),
16 FACEATTR(1, 0, 0),
17 FACEATTR(0, 0, -1),
18 FACEATTR(-1, 0, 0)
19 };
20 static struct vec3 def_tc[] = {
21 {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 0}, {1, 1, 0}, {0, 1, 0},
22 {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 0}, {1, 1, 0}, {0, 1, 0},
23 {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 0}, {1, 1, 0}, {0, 1, 0},
24 {0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 0, 0}, {1, 1, 0}, {0, 1, 0}
25 };
27 static struct mesh def_mesh = {
28 def_verts, def_norm, def_tc,
29 sizeof def_verts / sizeof *def_verts
30 };
32 /* use objfile to load mesh data (vertices, normals, and texcoords)
33 * from a wavefront|OBJ file.
34 */
35 struct mesh *load_mesh(const char *fname)
36 {
37 int i;
38 struct mesh *m;
39 struct objfile *obj;
41 if(!(obj = objf_load(fname))) {
42 return &def_mesh;
43 }
44 m = malloc(sizeof *m);
45 m->num_verts = objf_vertex_count(obj);
47 m->vert = malloc(m->num_verts * sizeof *m->vert);
48 m->norm = malloc(m->num_verts * sizeof *m->norm);
49 m->tc = malloc(m->num_verts * sizeof *m->tc);
51 for(i=0; i<m->num_verts; i++) {
52 float *v = objf_vertex(obj, i);
53 float *n = objf_normal(obj, i);
54 float *t = objf_texcoord(obj, i);
56 m->vert[i].x = v[0];
57 m->vert[i].y = v[1];
58 m->vert[i].z = v[2];
60 m->norm[i].x = n[0];
61 m->norm[i].y = n[1];
62 m->norm[i].z = n[2];
64 m->tc[i].x = t[0];
65 m->tc[i].y = t[1];
66 }
67 objf_free(obj);
68 return m;
69 }
71 void free_mesh(struct mesh *m)
72 {
73 if(m && m != &def_mesh) {
74 free(m->vert);
75 free(m->norm);
76 free(m->tc);
77 free(m);
78 }
79 }
81 void render_mesh(struct mesh *m)
82 {
83 glEnableClientState(GL_VERTEX_ARRAY);
84 glEnableClientState(GL_NORMAL_ARRAY);
85 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
87 glVertexPointer(3, GL_FLOAT, 0, m->vert);
88 glNormalPointer(GL_FLOAT, 0, m->norm);
89 glTexCoordPointer(2, GL_FLOAT, 0, m->tc);
91 glDrawArrays(GL_TRIANGLES, 0, m->num_verts);
93 glDisableClientState(GL_VERTEX_ARRAY);
94 glDisableClientState(GL_NORMAL_ARRAY);
95 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
96 }