ok now it works nicely in VR
[vrtris] / src / meshload.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <assert.h>
5 #include "cmesh.h"
6 #include "dynarr.h"
7 #include "rbtree.h"
8
9 struct vertex_pos_color {
10         float x, y, z;
11         float r, g, b, a;
12 };
13
14 struct facevertex {
15         int vidx, tidx, nidx;
16 };
17
18 static char *clean_line(char *s);
19 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn);
20 static int cmp_facevert(const void *ap, const void *bp);
21 static void free_rbnode_key(struct rbnode *n, void *cls);
22
23 /* merge of different indices per attribute happens during face processing.
24  *
25  * A triplet of (vertex index/texcoord index/normal index) is used as the key
26  * to search in a balanced binary search tree for vertex buffer index assigned
27  * to the same triplet if it has been encountered before. That index is
28  * appended to the index buffer.
29  *
30  * If a particular triplet has not been encountered before, a new vertex is
31  * appended to the vertex buffer. The index of this new vertex is appended to
32  * the index buffer, and also inserted into the tree for future searches.
33  */
34 int cmesh_load(struct cmesh *mesh, const char *fname)
35 {
36         int i, line_num = 0, result = -1;
37         int found_quad = 0;
38         int found_color = 0;
39         FILE *fp = 0;
40         char buf[256];
41         struct vertex_pos_color *varr = 0;
42         cgm_vec3 *narr = 0;
43         cgm_vec2 *tarr = 0;
44         struct rbtree *rbtree = 0;
45
46         if(!(fp = fopen(fname, "rb"))) {
47                 fprintf(stderr, "load_mesh: failed to open file: %s\n", fname);
48                 goto err;
49         }
50
51         if(!(rbtree = rb_create(cmp_facevert))) {
52                 fprintf(stderr, "load_mesh: failed to create facevertex binary search tree\n");
53                 goto err;
54         }
55         rb_set_delete_func(rbtree, free_rbnode_key, 0);
56
57         if(!(varr = dynarr_alloc(0, sizeof *varr)) ||
58                         !(narr = dynarr_alloc(0, sizeof *narr)) ||
59                         !(tarr = dynarr_alloc(0, sizeof *tarr))) {
60                 fprintf(stderr, "load_mesh: failed to allocate resizable vertex array\n");
61                 goto err;
62         }
63
64         while(fgets(buf, sizeof buf, fp)) {
65                 char *line = clean_line(buf);
66                 ++line_num;
67
68                 if(!*line) continue;
69
70                 switch(line[0]) {
71                 case 'v':
72                         if(isspace(line[1])) {
73                                 /* vertex */
74                                 struct vertex_pos_color v;
75                                 int num;
76
77                                 num = sscanf(line + 2, "%f %f %f %f %f %f %f", &v.x, &v.y, &v.z, &v.r, &v.g, &v.b, &v.a);
78                                 if(num < 3) {
79                                         fprintf(stderr, "%s:%d: invalid vertex definition: \"%s\"\n", fname, line_num, line);
80                                         goto err;
81                                 }
82                                 if(num > 3) found_color = 1;
83                                 switch(num) {
84                                 case 3:
85                                         v.r = 1.0f;
86                                 case 4:
87                                         v.g = 1.0f;
88                                 case 5:
89                                         v.b = 1.0f;
90                                 case 6:
91                                         v.a = 1.0f;
92                                 }
93                                 if(!(varr = dynarr_push(varr, &v))) {
94                                         fprintf(stderr, "load_mesh: failed to resize vertex buffer\n");
95                                         goto err;
96                                 }
97
98                         } else if(line[1] == 't' && isspace(line[2])) {
99                                 /* texcoord */
100                                 cgm_vec2 tc;
101                                 if(sscanf(line + 3, "%f %f", &tc.x, &tc.y) != 2) {
102                                         fprintf(stderr, "%s:%d: invalid texcoord definition: \"%s\"\n", fname, line_num, line);
103                                         goto err;
104                                 }
105                                 if(!(tarr = dynarr_push(tarr, &tc))) {
106                                         fprintf(stderr, "load_mesh: failed to resize texcoord buffer\n");
107                                         goto err;
108                                 }
109
110                         } else if(line[1] == 'n' && isspace(line[2])) {
111                                 /* normal */
112                                 cgm_vec3 norm;
113                                 if(sscanf(line + 3, "%f %f %f", &norm.x, &norm.y, &norm.z) != 3) {
114                                         fprintf(stderr, "%s:%d: invalid normal definition: \"%s\"\n", fname, line_num, line);
115                                         goto err;
116                                 }
117                                 if(!(narr = dynarr_push(narr, &norm))) {
118                                         fprintf(stderr, "load_mesh: failed to resize normal buffer\n");
119                                         goto err;
120                                 }
121                         }
122                         break;
123
124                 case 'f':
125                         if(isspace(line[1])) {
126                                 /* face */
127                                 char *ptr = line + 2;
128                                 struct facevertex fv;
129                                 struct rbnode *node;
130                                 int vsz = dynarr_size(varr);
131                                 int tsz = dynarr_size(tarr);
132                                 int nsz = dynarr_size(narr);
133
134                                 for(i=0; i<4; i++) {
135                                         if(!(ptr = parse_face_vert(ptr, &fv, vsz, tsz, nsz))) {
136                                                 if(i < 3 || found_quad) {
137                                                         fprintf(stderr, "%s:%d: invalid face definition: \"%s\"\n", fname, line_num, line);
138                                                         goto err;
139                                                 } else {
140                                                         break;
141                                                 }
142                                         }
143
144                                         if((node = rb_find(rbtree, &fv))) {
145                                                 unsigned int idx = (unsigned int)node->data;
146                                                 assert(idx < cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX));
147                                                 if(cmesh_push_index(mesh, idx) == -1) {
148                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
149                                                         goto err;
150                                                 }
151                                         } else {
152                                                 unsigned int newidx = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
153                                                 struct facevertex *newfv;
154                                                 struct vertex_pos_color *vptr = varr + fv.vidx;
155
156                                                 if(cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, vptr->x, vptr->y, vptr->z) == -1) {
157                                                         fprintf(stderr, "load_mesh: failed to resize vertex array\n");
158                                                         goto err;
159                                                 }
160                                                 if(found_color) {
161                                                         if(cmesh_push_attrib(mesh, CMESH_ATTR_COLOR, &vptr->r) == -1) {
162                                                                 fprintf(stderr, "load_mesh: failed to resize color array\n");
163                                                                 goto err;
164                                                         }
165                                                 }
166                                                 if(fv.nidx >= 0) {
167                                                         float nx = narr[fv.nidx].x;
168                                                         float ny = narr[fv.nidx].y;
169                                                         float nz = narr[fv.nidx].z;
170                                                         if(cmesh_push_attrib3f(mesh, CMESH_ATTR_NORMAL, nx, ny, nz) == -1) {
171                                                                 fprintf(stderr, "load_mesh: failed to resize normal array\n");
172                                                                 goto err;
173                                                         }
174                                                 }
175                                                 if(fv.tidx >= 0) {
176                                                         float tu = tarr[fv.tidx].x;
177                                                         float tv = tarr[fv.tidx].y;
178                                                         if(cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, tu, tv) == -1) {
179                                                                 fprintf(stderr, "load_mesh: failed to resize texcoord array\n");
180                                                                 goto err;
181                                                         }
182                                                 }
183
184                                                 if(cmesh_push_index(mesh, newidx) == -1) {
185                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
186                                                         goto err;
187                                                 }
188
189                                                 if((newfv = malloc(sizeof *newfv))) {
190                                                         *newfv = fv;
191                                                 }
192                                                 if(!newfv || rb_insert(rbtree, newfv, (void*)newidx) == -1) {
193                                                         fprintf(stderr, "load_mesh: failed to insert facevertex to the binary search tree\n");
194                                                         goto err;
195                                                 }
196                                         }
197                                 }
198                                 if(i > 3) found_quad = 1;
199                         }
200                         break;
201
202                 default:
203                         break;
204                 }
205         }
206
207         result = 0;     /* success */
208
209         printf("loaded %s mesh: %s: %d vertices, %d faces\n", found_quad ? "quad" : "triangle",
210                         fname, cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX), cmesh_poly_count(mesh));
211
212 err:
213         if(fp) fclose(fp);
214         dynarr_free(varr);
215         dynarr_free(narr);
216         dynarr_free(tarr);
217         rb_free(rbtree);
218         return result;
219 }
220
221 static char *clean_line(char *s)
222 {
223         char *end;
224
225         while(*s && isspace(*s)) ++s;
226         if(!*s) return 0;
227
228         end = s;
229         while(*end && *end != '#') ++end;
230         *end = 0;
231
232         while(end > s && isspace(*end)) --end;
233         *end = 0;
234
235         return s;
236 }
237
238 static char *parse_idx(char *ptr, int *idx, int arrsz)
239 {
240         char *endp;
241         int val = strtol(ptr, &endp, 10);
242         if(endp == ptr) return 0;
243
244         if(val < 0) {   /* convert negative indices */
245                 *idx = arrsz + val;
246         } else {
247                 *idx = val - 1; /* indices in obj are 1-based */
248         }
249         return endp;
250 }
251
252 /* possible face-vertex definitions:
253  * 1. vertex
254  * 2. vertex/texcoord
255  * 3. vertex//normal
256  * 4. vertex/texcoord/normal
257  */
258 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn)
259 {
260         if(!(ptr = parse_idx(ptr, &fv->vidx, numv)))
261                 return 0;
262         if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
263
264         if(*++ptr == '/') {     /* no texcoord */
265                 fv->tidx = -1;
266                 ++ptr;
267         } else {
268                 if(!(ptr = parse_idx(ptr, &fv->tidx, numt)))
269                         return 0;
270                 if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
271                 ++ptr;
272         }
273
274         if(!(ptr = parse_idx(ptr, &fv->nidx, numn)))
275                 return 0;
276         return (!*ptr || isspace(*ptr)) ? ptr : 0;
277 }
278
279 static int cmp_facevert(const void *ap, const void *bp)
280 {
281         const struct facevertex *a = ap;
282         const struct facevertex *b = bp;
283
284         if(a->vidx == b->vidx) {
285                 if(a->tidx == b->tidx) {
286                         return a->nidx - b->nidx;
287                 }
288                 return a->tidx - b->tidx;
289         }
290         return a->vidx - b->vidx;
291 }
292
293 static void free_rbnode_key(struct rbnode *n, void *cls)
294 {
295         free(n->key);
296 }