cspr ?
[eradicate] / src / 3dgfx / meshload.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <assert.h>
5 #include "mesh.h"
6 #include "dynarr.h"
7 #include "rbtree.h"
8 #include "3dgfx.h"
9 #include "util.h"
10
11 typedef struct { float x, y; } vec2_t;
12 typedef struct { float x, y, z; } vec3_t;
13 typedef struct { float x, y, z, w; } vec4_t;
14
15
16 struct vertex_pos_color {
17         float x, y, z;
18         float r, g, b, a;
19 };
20
21 struct facevertex {
22         int vidx, tidx, nidx;
23 };
24
25 static char *clean_line(char *s);
26 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn);
27 static int cmp_facevert(const void *ap, const void *bp);
28 static void free_rbnode_key(struct rbnode *n, void *cls);
29
30 /* merge of different indices per attribute happens during face processing.
31  *
32  * A triplet of (vertex index/texcoord index/normal index) is used as the key
33  * to search in a balanced binary search tree for vertex buffer index assigned
34  * to the same triplet if it has been encountered before. That index is
35  * appended to the index buffer.
36  *
37  * If a particular triplet has not been encountered before, a new g3d_vertex is
38  * appended to the vertex buffer. The index of this new vertex is appended to
39  * the index buffer, and also inserted into the tree for future searches.
40  */
41 int load_mesh(struct g3d_mesh *mesh, const char *fname)
42 {
43         int i, line_num = 0, result = -1;
44         int found_quad = 0;
45         FILE *fp = 0;
46         char buf[256];
47         struct vertex_pos_color *varr = 0;
48         vec3_t *narr = 0;
49         vec2_t *tarr = 0;
50         struct rbtree *rbtree = 0;
51
52         if(!(fp = fopen(fname, "rb"))) {
53                 fprintf(stderr, "load_mesh: failed to open file: %s\n", fname);
54                 goto err;
55         }
56
57         if(!(rbtree = rb_create(cmp_facevert))) {
58                 fprintf(stderr, "load_mesh: failed to create facevertex binary search tree\n");
59                 goto err;
60         }
61         rb_set_delete_func(rbtree, free_rbnode_key, 0);
62
63         if(!(mesh->varr = dynarr_alloc(0, sizeof *mesh->varr)) ||
64                         !(mesh->iarr = dynarr_alloc(0, sizeof *mesh->iarr))) {
65                 fprintf(stderr, "load_mesh: failed to allocate resizable mesh arrays\n");
66                 goto err;
67         }
68         if(!(varr = dynarr_alloc(0, sizeof *varr)) ||
69                         !(narr = dynarr_alloc(0, sizeof *narr)) ||
70                         !(tarr = dynarr_alloc(0, sizeof *tarr))) {
71                 fprintf(stderr, "load_mesh: failed to allocate resizable vertex array\n");
72                 goto err;
73         }
74
75         while(fgets(buf, sizeof buf, fp)) {
76                 char *line = clean_line(buf);
77                 ++line_num;
78
79                 if(!*line) continue;
80
81                 switch(line[0]) {
82                 case 'v':
83                         if(isspace(line[1])) {
84                                 /* vertex */
85                                 struct vertex_pos_color v;
86                                 int num;
87
88                                 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);
89                                 if(num < 3) {
90                                         fprintf(stderr, "%s:%d: invalid vertex definition: \"%s\"\n", fname, line_num, line);
91                                         goto err;
92                                 }
93                                 switch(num) {
94                                 case 3:
95                                         v.r = 1.0f;
96                                 case 4:
97                                         v.g = 1.0f;
98                                 case 5:
99                                         v.b = 1.0f;
100                                 case 6:
101                                         v.a = 1.0f;
102                                 }
103                                 if(!(varr = dynarr_push(varr, &v))) {
104                                         fprintf(stderr, "load_mesh: failed to resize vertex buffer\n");
105                                         goto err;
106                                 }
107
108                         } else if(line[1] == 't' && isspace(line[2])) {
109                                 /* texcoord */
110                                 vec2_t tc;
111                                 if(sscanf(line + 3, "%f %f", &tc.x, &tc.y) != 2) {
112                                         fprintf(stderr, "%s:%d: invalid texcoord definition: \"%s\"\n", fname, line_num, line);
113                                         goto err;
114                                 }
115                                 if(!(tarr = dynarr_push(tarr, &tc))) {
116                                         fprintf(stderr, "load_mesh: failed to resize texcoord buffer\n");
117                                         goto err;
118                                 }
119
120                         } else if(line[1] == 'n' && isspace(line[2])) {
121                                 /* normal */
122                                 vec3_t norm;
123                                 if(sscanf(line + 3, "%f %f %f", &norm.x, &norm.y, &norm.z) != 3) {
124                                         fprintf(stderr, "%s:%d: invalid normal definition: \"%s\"\n", fname, line_num, line);
125                                         goto err;
126                                 }
127                                 if(!(narr = dynarr_push(narr, &norm))) {
128                                         fprintf(stderr, "load_mesh: failed to resize normal buffer\n");
129                                         goto err;
130                                 }
131                         }
132                         break;
133
134                 case 'f':
135                         if(isspace(line[1])) {
136                                 /* face */
137                                 char *ptr = line + 2;
138                                 struct facevertex fv;
139                                 struct rbnode *node;
140                                 int vsz = dynarr_size(varr);
141                                 int tsz = dynarr_size(tarr);
142                                 int nsz = dynarr_size(narr);
143
144                                 for(i=0; i<4; i++) {
145                                         if(!(ptr = parse_face_vert(ptr, &fv, vsz, tsz, nsz))) {
146                                                 if(i < 3 || found_quad) {
147                                                         fprintf(stderr, "%s:%d: invalid face definition: \"%s\"\n", fname, line_num, line);
148                                                         goto err;
149                                                 } else {
150                                                         break;
151                                                 }
152                                         }
153
154                                         if((node = rb_find(rbtree, &fv))) {
155                                                 uint16_t idx = (int)(intptr_t)node->data;
156                                                 if(!(mesh->iarr = dynarr_push(mesh->iarr, &idx))) {
157                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
158                                                         goto err;
159                                                 }
160                                         } else {
161                                                 uint16_t newidx = dynarr_size(mesh->varr);
162                                                 struct g3d_vertex v;
163                                                 struct facevertex *newfv;
164
165                                                 v.x = varr[fv.vidx].x;
166                                                 v.y = varr[fv.vidx].y;
167                                                 v.z = varr[fv.vidx].z;
168                                                 v.w = 1.0f;
169                                                 v.r = cround64(varr[fv.vidx].r * 255.0);
170                                                 v.g = cround64(varr[fv.vidx].g * 255.0);
171                                                 v.b = cround64(varr[fv.vidx].b * 255.0);
172                                                 v.a = cround64(varr[fv.vidx].a * 255.0);
173                                                 if(fv.tidx >= 0) {
174                                                         v.u = tarr[fv.tidx].x;
175                                                         v.v = tarr[fv.tidx].y;
176                                                 } else {
177                                                         v.u = v.x;
178                                                         v.v = v.y;
179                                                 }
180                                                 if(fv.nidx >= 0) {
181                                                         v.nx = narr[fv.nidx].x;
182                                                         v.ny = narr[fv.nidx].y;
183                                                         v.nz = narr[fv.nidx].z;
184                                                 } else {
185                                                         v.nx = v.ny = 0.0f;
186                                                         v.nz = 1.0f;
187                                                 }
188
189                                                 if(!(mesh->varr = dynarr_push(mesh->varr, &v))) {
190                                                         fprintf(stderr, "load_mesh: failed to resize combined vertex array\n");
191                                                         goto err;
192                                                 }
193                                                 if(!(mesh->iarr = dynarr_push(mesh->iarr, &newidx))) {
194                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
195                                                         goto err;
196                                                 }
197
198                                                 if((newfv = malloc(sizeof *newfv))) {
199                                                         *newfv = fv;
200                                                 }
201                                                 if(!newfv || rb_insert(rbtree, newfv, (void*)(intptr_t)newidx) == -1) {
202                                                         fprintf(stderr, "load_mesh: failed to insert facevertex to the binary search tree\n");
203                                                         goto err;
204                                                 }
205                                         }
206                                 }
207                                 if(i > 3) found_quad = 1;
208                         }
209                         break;
210
211                 default:
212                         break;
213                 }
214         }
215
216         mesh->prim = found_quad ? G3D_QUADS : G3D_TRIANGLES;
217         mesh->vcount = dynarr_size(mesh->varr);
218         mesh->icount = dynarr_size(mesh->iarr);
219         mesh->varr = dynarr_finalize(mesh->varr);
220         mesh->iarr = dynarr_finalize(mesh->iarr);
221         result = 0;     /* success */
222
223         printf("loaded %s mesh: %s: %d vertices, %d faces\n", found_quad ? "quad" : "triangle",
224                         fname, mesh->vcount, mesh->icount / mesh->prim);
225
226 err:
227         if(fp) fclose(fp);
228         dynarr_free(varr);
229         dynarr_free(narr);
230         dynarr_free(tarr);
231         if(result == -1) {
232                 dynarr_free(mesh->varr);
233                 dynarr_free(mesh->iarr);
234         }
235         rb_free(rbtree);
236         return result;
237 }
238
239 int save_mesh(struct g3d_mesh *mesh, const char *fname)
240 {
241         int i, fvcount;
242         FILE *fp;
243
244         if(!(fp = fopen(fname, "wb"))) {
245                 fprintf(stderr, "save_mesh: failed to open %s for writing\n", fname);
246                 return -1;
247         }
248         fprintf(fp, "# Wavefront OBJ file shoved in your FACE by Mindlapse. Deal with it\n");
249
250         for(i=0; i<mesh->vcount; i++) {
251                 struct g3d_vertex *v = mesh->varr + i;
252                 fprintf(fp, "v %f %f %f %f %f %f %f\n", v->x, v->y, v->z, v->r / 255.0f, v->g / 255.0f,
253                                 v->b / 255.0f, v->a / 255.0f);
254         }
255         for(i=0; i<mesh->vcount; i++) {
256                 fprintf(fp, "vn %f %f %f\n", mesh->varr[i].nx, mesh->varr[i].ny, mesh->varr[i].nz);
257         }
258         for(i=0; i<mesh->vcount; i++) {
259                 fprintf(fp, "vt %f %f\n", mesh->varr[i].u, mesh->varr[i].v);
260         }
261
262         fvcount = mesh->prim;
263         for(i=0; i<mesh->icount; i++) {
264                 int idx = mesh->iarr[i] + 1;
265
266                 if(fvcount == mesh->prim) {
267                         fprintf(fp, "\nf");
268                         fvcount = 0;
269                 }
270                 fprintf(fp, " %d/%d/%d", idx, idx, idx);
271                 ++fvcount;
272         }
273         fprintf(fp, "\n");
274
275         fclose(fp);
276         return 0;
277 }
278
279 static char *clean_line(char *s)
280 {
281         char *end;
282
283         while(*s && isspace(*s)) ++s;
284         if(!*s) return 0;
285
286         end = s;
287         while(*end && *end != '#') ++end;
288         *end = 0;
289
290         while(end > s && isspace(*end)) --end;
291         *end = 0;
292
293         return s;
294 }
295
296 static char *parse_idx(char *ptr, int *idx, int arrsz)
297 {
298         char *endp;
299         int val = strtol(ptr, &endp, 10);
300         if(endp == ptr) return 0;
301
302         if(val < 0) {   /* convert negative indices */
303                 *idx = arrsz + val;
304         } else {
305                 *idx = val - 1; /* indices in obj are 1-based */
306         }
307         return endp;
308 }
309
310 /* possible face-vertex definitions:
311  * 1. vertex
312  * 2. vertex/texcoord
313  * 3. vertex//normal
314  * 4. vertex/texcoord/normal
315  */
316 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn)
317 {
318         if(!(ptr = parse_idx(ptr, &fv->vidx, numv)))
319                 return 0;
320         if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
321
322         if(*++ptr == '/') {     /* no texcoord */
323                 fv->tidx = -1;
324                 ++ptr;
325         } else {
326                 if(!(ptr = parse_idx(ptr, &fv->tidx, numt)))
327                         return 0;
328                 if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
329                 ++ptr;
330         }
331
332         if(!(ptr = parse_idx(ptr, &fv->nidx, numn)))
333                 return 0;
334         return (!*ptr || isspace(*ptr)) ? ptr : 0;
335 }
336
337 static int cmp_facevert(const void *ap, const void *bp)
338 {
339         const struct facevertex *a = ap;
340         const struct facevertex *b = bp;
341
342         if(a->vidx == b->vidx) {
343                 if(a->tidx == b->tidx) {
344                         return a->nidx - b->nidx;
345                 }
346                 return a->tidx - b->tidx;
347         }
348         return a->vidx - b->vidx;
349 }
350
351 static void free_rbnode_key(struct rbnode *n, void *cls)
352 {
353         free(n->key);
354 }