clray
view src/mesh.cc @ 20:63a6b46f58a0
fixed
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Mon, 09 Aug 2010 12:55:40 +0100 |
parents | 8baea9b66b50 |
children | bd6c2b25f6e7 |
line source
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <math.h>
5 #include <errno.h>
6 #include <limits.h>
7 #include <string>
8 #include <vector>
9 #include <map>
10 #include "mesh.h"
12 #ifndef PATH_MAX
13 #define PATH_MAX 512
14 #endif
16 using namespace std;
18 #define COMMANDS \
19 CMD(V), \
20 CMD(VN), \
21 CMD(VT), \
22 CMD(F), \
23 CMD(O), \
24 CMD(G), \
25 CMD(MTLLIB), \
26 CMD(USEMTL), \
27 CMD(NEWMTL), \
28 CMD(KA), \
29 CMD(KD), \
30 CMD(KS), \
31 CMD(KR), \
32 CMD(NS), \
33 CMD(NI), \
34 CMD(D), \
35 CMD(TR), \
36 CMD(MAP_KD), \
37 CMD(MAP_KS), \
38 CMD(MAP_NS), \
39 CMD(MAP_D), \
40 CMD(REFL), \
41 CMD(BUMP)
43 #define CMD(x) CMD_##x
44 enum {
45 COMMANDS,
46 CMD_UNK
47 };
48 #undef CMD
50 #define CMD(x) #x
51 static const char *cmd_names[] = {
52 COMMANDS,
53 0
54 };
55 #undef CMD
57 struct Vector3 {
58 float x, y, z;
60 Vector3() { x = y = z = 0.0; }
61 Vector3(float a, float b, float c) { x = a; y = b; z = c; }
63 void normalize() { float len = sqrt(x * x + y * y + z * z); x /= len; y /= len; z /= len; }
64 };
66 struct Vector2 {
67 float x, y;
69 Vector2() { x = y = 0.0; }
70 Vector2(float a, float b) { x = a; y = b; }
71 };
73 struct obj_face {
74 int elem;
75 int v[4], n[4], t[4];
76 };
78 struct obj_file {
79 string cur_obj, cur_mat;
80 vector<Vector3> v, vn, vt;
81 vector<obj_face> f;
82 };
84 struct obj_mat {
85 string name; // newmtl <name>
86 Vector3 ambient, diffuse, specular; // Ka, Kd, Ks
87 float shininess; // Ns
88 float ior; // Ni
89 float alpha; // d, Tr
90 float refl; // Kr (my extesnsion)
92 string tex_dif, tex_spec, tex_shin, tex_alpha; // map_Kd, map_Ks, map_Ns, map_d
93 string tex_refl; // refl -type sphere|cube file
94 string tex_bump; // bump
96 obj_mat() { reset(); }
98 void reset() {
99 ambient = diffuse = Vector3(0.5, 0.5, 0.5);
100 specular = Vector3(0.0, 0.0, 0.0);
101 name = tex_dif = tex_spec = tex_shin = tex_alpha = tex_refl = tex_bump = "";
102 shininess = 0;
103 ior = alpha = 1;
104 refl = 0.0;
105 }
106 };
108 static bool read_materials(FILE *fp, vector<obj_mat> *vmtl);
109 static Mesh *cons_mesh(obj_file *obj);
111 static int get_cmd(char *str);
112 static bool is_int(const char *str);
113 static bool is_float(const char *str);
114 static bool parse_vec(Vector3 *vec);
115 static bool parse_color(Vector3 *col);
116 static bool parse_face(obj_face *face);
117 static const char *parse_map();
119 static bool find_file(char *res, int sz, const char *fname, const char *path = ".", const char *mode = "rb");
120 static const char *dirname(const char *str);
122 static Vector3 operator -(const Vector3 &a, const Vector3 &b);
123 static Vector3 cross(const Vector3 &a, const Vector3 &b);
125 static map<string, int> matnames;
128 #define FEQ(a, b) (fabs((a) - (b)) < 1e-8)
129 bool Face::operator ==(const Face &f) const
130 {
131 for(int i=0; i<3; i++) {
132 for(int j=0; j<3; j++) {
133 if(!FEQ(v[i].pos[j], f.v[i].pos[j])) {
134 return false;
135 }
136 if(!FEQ(v[i].normal[j], f.v[i].normal[j])) {
137 return false;
138 }
139 }
140 if(!FEQ(normal[i], f.normal[i])) {
141 return false;
142 }
143 }
144 return true;
145 }
147 bool Scene::add_mesh(Mesh *m)
148 {
149 // make sure triangles have material ids
150 for(size_t i=0; i<m->faces.size(); i++) {
151 m->faces[i].matid = m->matid;
152 }
153 meshes.push_back(m);
154 return true;
155 }
157 int Scene::get_num_meshes() const
158 {
159 return (int)meshes.size();
160 }
162 int Scene::get_num_faces() const
163 {
164 int num_faces = 0;
165 for(size_t i=0; i<meshes.size(); i++) {
166 num_faces += meshes[i]->faces.size();
167 }
168 printf("get_num_faces() = %d\n", num_faces);
169 return num_faces;
170 }
172 int Scene::get_num_materials() const
173 {
174 return (int)matlib.size();
175 }
177 Material *Scene::get_materials()
178 {
179 if(matlib.empty()) {
180 return 0;
181 }
182 return &matlib[0];
183 }
185 const Material *Scene::get_materials() const
186 {
187 if(matlib.empty()) {
188 return 0;
189 }
190 return &matlib[0];
191 }
194 #define INVALID_IDX INT_MIN
196 #define SEP " \t\n\r\v"
197 #define BUF_SZ 512
199 bool Scene::load(const char *fname)
200 {
201 FILE *fp;
203 if(!(fp = fopen(fname, "rb"))) {
204 fprintf(stderr, "failed to open %s: %s\n", fname, strerror(errno));
205 return false;
206 }
208 bool res = load(fp);
209 fclose(fp);
210 return res;
211 }
213 bool Scene::load(FILE *fp)
214 {
215 static int seq;
216 char cur_name[16];
218 obj_file obj;
220 sprintf(cur_name, "default%02d.obj", seq++);
221 obj.cur_obj = cur_name;
223 int prev_cmd = 0, obj_added = 0;
224 for(;;) {
225 Vector3 vec;
226 obj_face face;
228 char line[BUF_SZ];
229 fgets(line, sizeof line, fp);
230 if(feof(fp)) {
231 break;
232 }
234 char *tok;
235 if(!(tok = strtok(line, SEP))) {
236 continue; // ignore empty lines
237 }
239 int cmd;
240 if((cmd = get_cmd(tok)) == -1) {
241 continue; // ignore unknown commands ...
242 }
244 switch(cmd) {
245 case CMD_V:
246 if(!parse_vec(&vec)) {
247 continue;
248 }
249 obj.v.push_back(vec);
250 break;
252 case CMD_VN:
253 if(!parse_vec(&vec)) {
254 continue;
255 }
256 obj.vn.push_back(vec);
257 break;
259 case CMD_VT:
260 if(!parse_vec(&vec)) {
261 continue;
262 }
263 vec.y = 1.0 - vec.y;
264 obj.vt.push_back(vec);
265 break;
267 case CMD_O:
268 case CMD_G:
269 if(prev_cmd == CMD_O || prev_cmd == CMD_G) {
270 break; // just in case we've got both of them in a row
271 }
272 /* if we have any previous data, group them up, add the object
273 * and continue with the new one...
274 */
275 if(!obj.f.empty()) {
276 Mesh *mesh = cons_mesh(&obj);
277 mesh->matid = matnames[obj.cur_mat];
278 add_mesh(mesh);
279 obj_added++;
281 obj.f.clear(); // clean the face list
282 }
283 if((tok = strtok(0, SEP))) {
284 obj.cur_obj = tok;
285 } else {
286 sprintf(cur_name, "default%02d.obj", seq++);
287 obj.cur_obj = cur_name;
288 }
289 break;
291 case CMD_MTLLIB:
292 if((tok = strtok(0, SEP))) {
293 char path[PATH_MAX];
295 sprintf(path, ".:%s", dirname(tok));
296 if(!find_file(path, PATH_MAX, tok, path)) {
297 fprintf(stderr, "material library not found: %s\n", tok);
298 continue;
299 }
301 FILE *mfile;
302 if(!(mfile = fopen(path, "rb"))) {
303 fprintf(stderr, "failed to open material library: %s\n", path);
304 continue;
305 }
307 // load all materials of the mtl file into a vector
308 vector<obj_mat> vmtl;
309 if(!read_materials(mfile, &vmtl)) {
310 continue;
311 }
312 fclose(mfile);
314 // and add them all to the scene
315 for(size_t i=0; i<vmtl.size(); i++) {
316 Material mat;
318 mat.kd[0] = vmtl[i].diffuse.x;
319 mat.kd[1] = vmtl[i].diffuse.y;
320 mat.kd[2] = vmtl[i].diffuse.z;
322 mat.ks[0] = vmtl[i].specular.x;
323 mat.ks[1] = vmtl[i].specular.y;
324 mat.ks[2] = vmtl[i].specular.z;
326 mat.kt = 1.0 - vmtl[i].alpha;
327 mat.kr = vmtl[i].refl;
328 mat.spow = vmtl[i].shininess;
330 matlib.push_back(mat);
331 matnames[vmtl[i].name] = i;
332 }
333 }
334 break;
336 case CMD_USEMTL:
337 if((tok = strtok(0, SEP))) {
338 obj.cur_mat = tok;
339 } else {
340 obj.cur_mat = "";
341 }
342 break;
344 case CMD_F:
345 if(!parse_face(&face)) {
346 continue;
347 }
349 // convert negative indices to regular indices
350 for(int i=0; i<4; i++) {
351 if(face.v[i] < 0 && face.v[i] != INVALID_IDX) {
352 face.v[i] = obj.v.size() + face.v[i];
353 }
354 if(face.n[i] < 0 && face.n[i] != INVALID_IDX) {
355 face.n[i] = obj.vn.size() + face.n[i];
356 }
357 if(face.t[i] < 0 && face.t[i] != INVALID_IDX) {
358 face.t[i] = obj.vt.size() + face.t[i];
359 }
360 }
362 // break quads into triangles if needed
363 obj.f.push_back(face);
364 if(face.elem == 4) {
365 face.v[1] = face.v[2];
366 face.n[1] = face.n[2];
367 face.t[1] = face.t[2];
369 face.v[2] = face.v[3];
370 face.n[2] = face.n[3];
371 face.t[2] = face.t[3];
373 obj.f.push_back(face);
374 }
375 break;
377 default:
378 break; // ignore unknown commands
379 }
381 prev_cmd = cmd;
382 }
384 // reached end of file...
385 if(!obj.f.empty()) {
386 Mesh *mesh = cons_mesh(&obj);
387 mesh->matid = matnames[obj.cur_mat];
388 add_mesh(mesh);
389 obj_added++;
390 }
392 return obj_added > 0;
393 }
395 static Mesh *cons_mesh(obj_file *obj)
396 {
397 Mesh *mesh;
399 // need at least one of each element
400 bool added_norm = false, added_tc = false;
401 if(obj->vn.empty()) {
402 obj->vn.push_back(Vector3(0, 0, 0));
403 added_norm = true;
404 }
405 if(obj->vt.empty()) {
406 obj->vt.push_back(Vector3(0, 0, 0));
407 added_tc = true;
408 }
410 mesh = new Mesh;
412 for(size_t i=0; i<obj->f.size(); i++) {
413 Face face;
414 Vector3 v[3];
416 for(int j=0; j<3; j++) {
417 obj_face *f = &obj->f[i];
419 face.v[j].pos[0] = v[j].x = obj->v[f->v[j]].x;
420 face.v[j].pos[1] = v[j].y = obj->v[f->v[j]].y;
421 face.v[j].pos[2] = v[j].z = obj->v[f->v[j]].z;
422 face.v[j].pos[3] = 0.0;
424 int nidx = f->n[j] < 0 ? 0 : f->n[j];
425 face.v[j].normal[0] = obj->vn[nidx].x;
426 face.v[j].normal[1] = obj->vn[nidx].y;
427 face.v[j].normal[2] = obj->vn[nidx].z;
428 face.v[j].normal[3] = 0.0;
430 int tidx = f->t[j] < 0 ? 0 : f->t[j];
431 face.v[j].tex[0] = obj->vt[tidx].x;
432 face.v[j].tex[1] = obj->vt[tidx].y;
433 }
435 Vector3 a = v[1] - v[0];
436 Vector3 b = v[2] - v[0];
437 Vector3 n = cross(a, b);
438 n.normalize();
440 face.normal[0] = n.x;
441 face.normal[1] = n.y;
442 face.normal[2] = n.z;
443 face.normal[3] = 0.0;
445 mesh->faces.push_back(face);
446 }
448 if(added_norm) {
449 obj->vn.pop_back();
450 }
451 if(added_tc) {
452 obj->vt.pop_back();
453 }
455 return mesh;
456 }
458 static bool read_materials(FILE *fp, vector<obj_mat> *vmtl)
459 {
460 obj_mat mat;
462 for(;;) {
463 char line[BUF_SZ];
464 fgets(line, sizeof line, fp);
465 if(feof(fp)) {
466 break;
467 }
469 char *tok;
470 if(!(tok = strtok(line, SEP))) {
471 continue;
472 }
474 int cmd;
475 if((cmd = get_cmd(tok)) == -1) {
476 continue;
477 }
479 switch(cmd) {
480 case CMD_NEWMTL:
481 // add the previous material, and start a new one
482 if(mat.name.length() > 0) {
483 printf("Adding material: %s\n", mat.name.c_str());
484 vmtl->push_back(mat);
485 mat.reset();
486 }
487 if((tok = strtok(0, SEP))) {
488 mat.name = tok;
489 }
490 break;
492 case CMD_KA:
493 parse_color(&mat.ambient);
494 break;
496 case CMD_KD:
497 parse_color(&mat.diffuse);
498 break;
500 case CMD_KS:
501 parse_color(&mat.specular);
502 break;
504 case CMD_KR:
505 if((tok = strtok(0, SEP)) && is_float(tok)) {
506 mat.refl = atof(tok);
507 }
508 break;
510 case CMD_NS:
511 if((tok = strtok(0, SEP)) && is_float(tok)) {
512 mat.shininess = atof(tok);
513 }
514 break;
516 case CMD_NI:
517 if((tok = strtok(0, SEP)) && is_float(tok)) {
518 mat.ior = atof(tok);
519 }
520 break;
522 case CMD_D:
523 case CMD_TR:
524 {
525 Vector3 c;
526 if(parse_color(&c)) {
527 mat.alpha = cmd == CMD_D ? c.x : 1.0 - c.x;
528 }
529 }
530 break;
532 case CMD_MAP_KD:
533 mat.tex_dif = parse_map();
534 break;
536 default:
537 break;
538 }
539 }
541 if(mat.name.length() > 0) {
542 printf("Adding material: %s\n", mat.name.c_str());
543 vmtl->push_back(mat);
544 }
545 return true;
546 }
548 static int get_cmd(char *str)
549 {
550 char *s = str;
551 while((*s = toupper(*s))) s++;
553 for(int i=0; cmd_names[i]; i++) {
554 if(strcmp(str, cmd_names[i]) == 0) {
555 return i;
556 }
557 }
558 return CMD_UNK;
559 }
561 static bool is_int(const char *str)
562 {
563 char *tmp;
564 strtol(str, &tmp, 10);
565 return tmp != str;
566 }
568 static bool is_float(const char *str)
569 {
570 char *tmp;
571 strtod(str, &tmp);
572 return tmp != str;
573 }
575 static bool parse_vec(Vector3 *vec)
576 {
577 for(int i=0; i<3; i++) {
578 char *tok;
580 if(!(tok = strtok(0, SEP)) || !is_float(tok)) {
581 if(i < 2) {
582 return false;
583 }
584 vec->z = 0.0;
585 } else {
586 float v = atof(tok);
588 switch(i) {
589 case 0:
590 vec->x = v;
591 break;
592 case 1:
593 vec->y = v;
594 break;
595 case 2:
596 vec->z = v;
597 break;
598 }
599 }
600 }
601 return true;
602 }
604 static bool parse_color(Vector3 *col)
605 {
606 for(int i=0; i<3; i++) {
607 char *tok;
609 if(!(tok = strtok(0, SEP)) || !is_float(tok)) {
610 col->y = col->z = col->x;
611 return i > 0 ? true : false;
612 }
614 float v = atof(tok);
615 switch(i) {
616 case 0:
617 col->x = v;
618 break;
619 case 1:
620 col->y = v;
621 break;
622 case 2:
623 col->z = v;
624 break;
625 }
626 }
627 return true;
628 }
630 static bool parse_face(obj_face *face)
631 {
632 char *tok[] = {0, 0, 0, 0};
633 face->elem = 0;
635 for(int i=0; i<4; i++) {
636 if((!(tok[i] = strtok(0, SEP)) || !is_int(tok[i]))) {
637 if(i < 3) return false; // less than 3 verts? not a polygon
638 } else {
639 face->elem++;
640 }
641 }
643 for(int i=0; i<4; i++) {
644 char *subtok = tok[i];
646 if(!subtok || !*subtok || !is_int(subtok)) {
647 if(i < 3) {
648 return false;
649 }
650 face->v[i] = INVALID_IDX;
651 } else {
652 face->v[i] = atoi(subtok);
653 if(face->v[i] > 0) face->v[i]--; /* convert to 0-based */
654 }
656 while(subtok && *subtok && *subtok != '/') {
657 subtok++;
658 }
659 if(subtok && *subtok && *++subtok && is_int(subtok)) {
660 face->t[i] = atoi(subtok);
661 if(face->t[i] > 0) face->t[i]--; /* convert to 0-based */
662 } else {
663 face->t[i] = INVALID_IDX;
664 }
666 while(subtok && *subtok && *subtok != '/') {
667 subtok++;
668 }
669 if(subtok && *subtok && *++subtok && is_int(subtok)) {
670 face->n[i] = atoi(subtok);
671 if(face->n[i] > 0) face->n[i]--; /* convert to 0-based */
672 } else {
673 face->n[i] = INVALID_IDX;
674 }
675 }
677 return true;
678 }
680 static const char *parse_map()
681 {
682 char *tok, *prev = 0;
684 while((tok = strtok(0, SEP))) {
685 prev = tok;
686 }
688 return prev ? prev : "";
689 }
691 static bool find_file(char *res, int sz, const char *fname, const char *path, const char *mode)
692 {
693 FILE *fp;
694 const char *beg, *end;
695 int fnamelen = strlen(fname);
697 beg = path;
698 while(beg && *beg) {
699 end = beg;
700 while(*end && *end != ':') {
701 end++;
702 }
704 int res_len = end - beg;
705 char *pathname = (char*)alloca(res_len + fnamelen + 2);
706 memcpy(pathname, beg, res_len);
707 pathname[res_len] = 0;
708 if(res_len) {
709 strcat(pathname, "/");
710 }
711 strcat(pathname, fname);
713 if((fp = fopen(pathname, mode))) {
714 fclose(fp);
715 strncpy(res, pathname, sz);
716 return true;
717 }
719 beg += res_len;
720 if(*beg == ':') beg++;
721 }
722 return false;
723 }
725 static const char *dirname(const char *str)
726 {
727 static char buf[PATH_MAX];
729 if(!str || !*str) {
730 strcpy(buf, ".");
731 } else {
732 strncpy(buf, str, PATH_MAX);
733 char *ptr = strrchr(buf, '/');
735 if(ptr && *ptr) {
736 *ptr = 0;
737 } else {
738 strcpy(buf, ".");
739 }
740 }
741 return buf;
742 }
744 static Vector3 operator -(const Vector3 &a, const Vector3 &b)
745 {
746 return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
747 }
749 static Vector3 cross(const Vector3 &a, const Vector3 &b)
750 {
751 Vector3 res;
752 res.x = a.y * b.z - a.z * b.y;
753 res.y = a.z * b.x - a.x * b.z;
754 res.z = a.x * b.y - a.y * b.x;
755 return res;
756 }