3a1fc7011f5b8d6963f0d5598c6160eebc97ee62
[dosdemo] / tools / ropesim / src / meshload.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <assert.h>
5 #include "cmesh.h"
6
7 #ifdef USE_ASSIMP
8 #include <assimp/cimport.h>
9 #include <assimp/postprocess.h>
10 #include <assimp/mesh.h>
11 #include <assimp/scene.h>
12 #include <assimp/types.h>
13 #else
14 #include "dynarr.h"
15 #include "rbtree.h"
16 #endif
17
18
19 #ifdef USE_ASSIMP
20
21 static int add_mesh(struct cmesh *mesh, struct aiMesh *aimesh);
22
23 #define AIPPFLAGS \
24         (aiProcess_JoinIdenticalVertices | aiProcess_PreTransformVertices | \
25          aiProcess_Triangulate | aiProcess_SortByPType | aiProcess_FlipUVs)
26
27 int cmesh_load(struct cmesh *mesh, const char *fname)
28 {
29         int i;
30         const struct aiScene *aiscn;
31
32         if(!(aiscn = aiImportFile(fname, AIPPFLAGS))) {
33                 fprintf(stderr, "failed to open mesh file: %s\n", fname);
34                 return -1;
35         }
36
37         for(i=0; i<(int)aiscn->mNumMeshes; i++) {
38                 add_mesh(mesh, aiscn->mMeshes[i]);
39         }
40
41         aiReleaseImport(aiscn);
42         return 0;
43 }
44
45 static int add_mesh(struct cmesh *mesh, struct aiMesh *aim)
46 {
47         int i, j, voffs, foffs;
48
49         voffs = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
50         foffs = cmesh_poly_count(mesh);
51
52         for(i=0; i<aim->mNumVertices; i++) {
53                 struct aiVector3D *v = aim->mVertices + i;
54                 cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, v->x, v->y, v->z);
55
56                 if(aim->mNormals) {
57                         v = aim->mNormals + i;
58                         cmesh_push_attrib3f(mesh, CMESH_ATTR_NORMAL, v->x, v->y, v->z);
59                 }
60                 if(aim->mTangents) {
61                         v = aim->mTangents + i;
62                         cmesh_push_attrib3f(mesh, CMESH_ATTR_TANGENT, v->x, v->y, v->z);
63                 }
64                 if(aim->mColors[0]) {
65                         struct aiColor4D *col = aim->mColors[0] + i;
66                         cmesh_push_attrib4f(mesh, CMESH_ATTR_COLOR, col->r, col->g, col->b, col->a);
67                 }
68                 if(aim->mTextureCoords[0]) {
69                         v = aim->mTextureCoords[0] + i;
70                         cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, v->x, v->y);
71                 }
72                 if(aim->mTextureCoords[1]) {
73                         v = aim->mTextureCoords[1] + i;
74                         cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD2, v->x, v->y);
75                 }
76         }
77
78         if(aim->mFaces) {
79                 for(i=0; i<aim->mNumFaces; i++) {
80                         assert(aim->mFaces[i].mNumIndices == 3);
81                         for(j=0; j<3; j++) {
82                                 cmesh_push_index(mesh, aim->mFaces[i].mIndices[j] + voffs);
83                         }
84                 }
85                 cmesh_submesh(mesh, aim->mName.data, foffs, aim->mNumFaces);
86         }
87         return 0;
88 }
89
90 #else
91
92 struct vertex_pos {
93         float x, y, z;
94 };
95
96 struct facevertex {
97         int vidx, tidx, nidx;
98 };
99
100 static char *clean_line(char *s);
101 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn);
102 static int cmp_facevert(const void *ap, const void *bp);
103 static void free_rbnode_key(struct rbnode *n, void *cls);
104
105 /* merge of different indices per attribute happens during face processing.
106  *
107  * A triplet of (vertex index/texcoord index/normal index) is used as the key
108  * to search in a balanced binary search tree for vertex buffer index assigned
109  * to the same triplet if it has been encountered before. That index is
110  * appended to the index buffer.
111  *
112  * If a particular triplet has not been encountered before, a new vertex is
113  * appended to the vertex buffer. The index of this new vertex is appended to
114  * the index buffer, and also inserted into the tree for future searches.
115  */
116 int cmesh_load(struct cmesh *mesh, const char *fname)
117 {
118         int i, line_num = 0, result = -1;
119         int found_quad = 0;
120         FILE *fp = 0;
121         char buf[256];
122         struct vertex_pos *varr = 0;
123         cgm_vec3 *narr = 0;
124         cgm_vec2 *tarr = 0;
125         struct rbtree *rbtree = 0;
126         char *subname = 0;
127         int substart = 0, subcount = 0;
128
129         if(!(fp = fopen(fname, "rb"))) {
130                 fprintf(stderr, "load_mesh: failed to open file: %s\n", fname);
131                 goto err;
132         }
133
134         if(!(rbtree = rb_create(cmp_facevert))) {
135                 fprintf(stderr, "load_mesh: failed to create facevertex binary search tree\n");
136                 goto err;
137         }
138         rb_set_delete_func(rbtree, free_rbnode_key, 0);
139
140         if(!(varr = dynarr_alloc(0, sizeof *varr)) ||
141                         !(narr = dynarr_alloc(0, sizeof *narr)) ||
142                         !(tarr = dynarr_alloc(0, sizeof *tarr))) {
143                 fprintf(stderr, "load_mesh: failed to allocate resizable vertex array\n");
144                 goto err;
145         }
146
147         while(fgets(buf, sizeof buf, fp)) {
148                 char *line = clean_line(buf);
149                 ++line_num;
150
151                 if(!*line) continue;
152
153                 switch(line[0]) {
154                 case 'v':
155                         if(isspace(line[1])) {
156                                 /* vertex */
157                                 struct vertex_pos v;
158                                 int num;
159
160                                 num = sscanf(line + 2, "%f %f %f", &v.x, &v.y, &v.z);
161                                 if(num < 3) {
162                                         fprintf(stderr, "%s:%d: invalid vertex definition: \"%s\"\n", fname, line_num, line);
163                                         goto err;
164                                 }
165                                 if(!(varr = dynarr_push(varr, &v))) {
166                                         fprintf(stderr, "load_mesh: failed to resize vertex buffer\n");
167                                         goto err;
168                                 }
169
170                         } else if(line[1] == 't' && isspace(line[2])) {
171                                 /* texcoord */
172                                 cgm_vec2 tc;
173                                 if(sscanf(line + 3, "%f %f", &tc.x, &tc.y) != 2) {
174                                         fprintf(stderr, "%s:%d: invalid texcoord definition: \"%s\"\n", fname, line_num, line);
175                                         goto err;
176                                 }
177                                 tc.y = 1.0f - tc.y;
178                                 if(!(tarr = dynarr_push(tarr, &tc))) {
179                                         fprintf(stderr, "load_mesh: failed to resize texcoord buffer\n");
180                                         goto err;
181                                 }
182
183                         } else if(line[1] == 'n' && isspace(line[2])) {
184                                 /* normal */
185                                 cgm_vec3 norm;
186                                 if(sscanf(line + 3, "%f %f %f", &norm.x, &norm.y, &norm.z) != 3) {
187                                         fprintf(stderr, "%s:%d: invalid normal definition: \"%s\"\n", fname, line_num, line);
188                                         goto err;
189                                 }
190                                 if(!(narr = dynarr_push(narr, &norm))) {
191                                         fprintf(stderr, "load_mesh: failed to resize normal buffer\n");
192                                         goto err;
193                                 }
194                         }
195                         break;
196
197                 case 'f':
198                         if(isspace(line[1])) {
199                                 /* face */
200                                 char *ptr = line + 2;
201                                 struct facevertex fv;
202                                 struct rbnode *node;
203                                 int vsz = dynarr_size(varr);
204                                 int tsz = dynarr_size(tarr);
205                                 int nsz = dynarr_size(narr);
206
207                                 for(i=0; i<4; i++) {
208                                         if(!(ptr = parse_face_vert(ptr, &fv, vsz, tsz, nsz))) {
209                                                 if(i < 3 || found_quad) {
210                                                         fprintf(stderr, "%s:%d: invalid face definition: \"%s\"\n", fname, line_num, line);
211                                                         goto err;
212                                                 } else {
213                                                         break;
214                                                 }
215                                         }
216
217                                         if((node = rb_find(rbtree, &fv))) {
218                                                 unsigned int idx = (unsigned int)node->data;
219                                                 assert(idx < cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX));
220                                                 if(cmesh_push_index(mesh, idx) == -1) {
221                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
222                                                         goto err;
223                                                 }
224                                                 subcount++;     /* inc number of submesh indices, in case we have submeshes */
225                                         } else {
226                                                 unsigned int newidx = cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX);
227                                                 struct facevertex *newfv;
228                                                 struct vertex_pos *vptr = varr + fv.vidx;
229
230                                                 if(cmesh_push_attrib3f(mesh, CMESH_ATTR_VERTEX, vptr->x, vptr->y, vptr->z) == -1) {
231                                                         fprintf(stderr, "load_mesh: failed to resize vertex array\n");
232                                                         goto err;
233                                                 }
234                                                 if(fv.nidx >= 0) {
235                                                         float nx = narr[fv.nidx].x;
236                                                         float ny = narr[fv.nidx].y;
237                                                         float nz = narr[fv.nidx].z;
238                                                         if(cmesh_push_attrib3f(mesh, CMESH_ATTR_NORMAL, nx, ny, nz) == -1) {
239                                                                 fprintf(stderr, "load_mesh: failed to resize normal array\n");
240                                                                 goto err;
241                                                         }
242                                                 }
243                                                 if(fv.tidx >= 0) {
244                                                         float tu = tarr[fv.tidx].x;
245                                                         float tv = tarr[fv.tidx].y;
246                                                         if(cmesh_push_attrib2f(mesh, CMESH_ATTR_TEXCOORD, tu, tv) == -1) {
247                                                                 fprintf(stderr, "load_mesh: failed to resize texcoord array\n");
248                                                                 goto err;
249                                                         }
250                                                 }
251
252                                                 if(cmesh_push_index(mesh, newidx) == -1) {
253                                                         fprintf(stderr, "load_mesh: failed to resize index array\n");
254                                                         goto err;
255                                                 }
256                                                 subcount++;     /* inc number of submesh indices, in case we have submeshes */
257
258                                                 if((newfv = malloc(sizeof *newfv))) {
259                                                         *newfv = fv;
260                                                 }
261                                                 if(!newfv || rb_insert(rbtree, newfv, (void*)newidx) == -1) {
262                                                         fprintf(stderr, "load_mesh: failed to insert facevertex to the binary search tree\n");
263                                                         goto err;
264                                                 }
265                                         }
266                                 }
267                                 if(i > 3) found_quad = 1;
268                         }
269                         break;
270
271                 case 'o':
272                         if(subcount > 0) {
273                                 printf("adding submesh: %s\n", subname);
274                                 cmesh_submesh(mesh, subname, substart / 3, subcount / 3);
275                         }
276                         free(subname);
277                         if((subname = malloc(strlen(line)))) {
278                                 strcpy(subname, clean_line(line + 2));
279                         }
280                         substart += subcount;
281                         subcount = 0;
282                         break;
283
284                 default:
285                         break;
286                 }
287         }
288
289         if(subcount > 0) {
290                 /* don't add the final submesh if we never found another. an obj file with a
291                  * single 'o' for the whole list of faces, is a single mesh without submeshes
292                  */
293                 if(cmesh_submesh_count(mesh) > 0) {
294                         printf("adding submesh: %s\n", subname);
295                         cmesh_submesh(mesh, subname, substart / 3, subcount / 3);
296                 } else {
297                         /* ... but use the 'o' name as the name of the mesh instead of the filename */
298                         if(subname && *subname) {
299                                 cmesh_set_name(mesh, subname);
300                         }
301                 }
302         }
303
304         result = 0;     /* success */
305
306         printf("loaded %s mesh: %s (%d submeshes): %d vertices, %d faces\n",
307                         found_quad ? "quad" : "triangle", fname, cmesh_submesh_count(mesh),
308                         cmesh_attrib_count(mesh, CMESH_ATTR_VERTEX), cmesh_poly_count(mesh));
309
310 err:
311         if(fp) fclose(fp);
312         dynarr_free(varr);
313         dynarr_free(narr);
314         dynarr_free(tarr);
315         rb_free(rbtree);
316         free(subname);
317         return result;
318 }
319
320
321 static char *clean_line(char *s)
322 {
323         char *end;
324
325         while(*s && isspace(*s)) ++s;
326         if(!*s) return 0;
327
328         end = s;
329         while(*end && *end != '#') ++end;
330         *end-- = 0;
331
332         while(end > s && isspace(*end)) {
333                 *end-- = 0;
334         }
335
336         return s;
337 }
338
339 static char *parse_idx(char *ptr, int *idx, int arrsz)
340 {
341         char *endp;
342         int val = strtol(ptr, &endp, 10);
343         if(endp == ptr) return 0;
344
345         if(val < 0) {   /* convert negative indices */
346                 *idx = arrsz + val;
347         } else {
348                 *idx = val - 1; /* indices in obj are 1-based */
349         }
350         return endp;
351 }
352
353 /* possible face-vertex definitions:
354  * 1. vertex
355  * 2. vertex/texcoord
356  * 3. vertex//normal
357  * 4. vertex/texcoord/normal
358  */
359 static char *parse_face_vert(char *ptr, struct facevertex *fv, int numv, int numt, int numn)
360 {
361         if(!(ptr = parse_idx(ptr, &fv->vidx, numv)))
362                 return 0;
363         if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
364
365         if(*++ptr == '/') {     /* no texcoord */
366                 fv->tidx = -1;
367                 ++ptr;
368         } else {
369                 if(!(ptr = parse_idx(ptr, &fv->tidx, numt)))
370                         return 0;
371                 if(*ptr != '/') return (!*ptr || isspace(*ptr)) ? ptr : 0;
372                 ++ptr;
373         }
374
375         if(!(ptr = parse_idx(ptr, &fv->nidx, numn)))
376                 return 0;
377         return (!*ptr || isspace(*ptr)) ? ptr : 0;
378 }
379
380 static int cmp_facevert(const void *ap, const void *bp)
381 {
382         const struct facevertex *a = ap;
383         const struct facevertex *b = bp;
384
385         if(a->vidx == b->vidx) {
386                 if(a->tidx == b->tidx) {
387                         return a->nidx - b->nidx;
388                 }
389                 return a->tidx - b->tidx;
390         }
391         return a->vidx - b->vidx;
392 }
393
394 static void free_rbnode_key(struct rbnode *n, void *cls)
395 {
396         free(n->key);
397 }
398 #endif