root/OpenSceneGraph/trunk/src/osgPlugins/obj/glm.cpp @ 3314

Revision 3314, 56.3 kB (checked in by robert, 10 years ago)

Made the command buffer have 20 elements in it to protect against wrapping
around.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/*   
2 *  Wavefront .obj file format reader.
3 *
4 *  author: Nate Robins
5 *  email: ndr@pobox.com
6 *  www: http://www.pobox.com/~ndr
7 */
8
9
10/* includes */
11#include "glm.h"
12#include <math.h>
13#include <stdio.h>
14#include <string.h>
15#include <assert.h>
16#include <osg/Math>
17#include <stdlib.h>
18
19#include <osg/Math>
20
21#include <iostream>
22
23/* defines */
24#define T(x) model->triangles[(x)]
25
26
27/* enums */
28enum { X, Y, Z, W };            /* elements of a vertex */
29
30
31/* typedefs */
32
33/* _GLMnode: general purpose node
34 */
35typedef struct _GLMnode {
36  unsigned int           index;
37  GLboolean        averaged;
38  struct _GLMnode* next;
39} GLMnode;
40
41
42/* private functions */
43
44/* _glmMax: returns the maximum of two floats */
45static GLfloat
46_glmMax(GLfloat a, GLfloat b)
47{
48  if (a > b)
49    return a;
50  return b;
51}
52
53/* _glmAbs: returns the absolute value of a float */
54static GLfloat
55_glmAbs(GLfloat f)
56{
57  if (f < 0)
58    return -f;
59  return f;
60}
61
62/* _glmDot: compute the dot product of two vectors
63 *
64 * u - array of 3 GLfloats (GLfloat u[3])
65 * v - array of 3 GLfloats (GLfloat v[3])
66 */
67static GLfloat
68_glmDot(GLfloat* u, GLfloat* v)
69{
70  assert(u);
71  assert(v);
72
73  /* compute the dot product */
74  return u[X] * v[X] + u[Y] * v[Y] + u[Z] * v[Z];
75}
76
77/* _glmCross: compute the cross product of two vectors
78 *
79 * u - array of 3 GLfloats (GLfloat u[3])
80 * v - array of 3 GLfloats (GLfloat v[3])
81 * n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in
82 */
83static GLvoid
84_glmCross(GLfloat* u, GLfloat* v, GLfloat* n)
85{
86  assert(u);
87  assert(v);
88  assert(n);
89
90  /* compute the cross product (u x v for right-handed [ccw]) */
91  n[X] = u[Y] * v[Z] - u[Z] * v[Y];
92  n[Y] = u[Z] * v[X] - u[X] * v[Z];
93  n[Z] = u[X] * v[Y] - u[Y] * v[X];
94}
95
96/* _glmNormalize: normalize a vector
97 *
98 * n - array of 3 GLfloats (GLfloat n[3]) to be normalized
99 */
100static GLvoid
101_glmNormalize(GLfloat* n)
102{
103  GLfloat l;
104
105  assert(n);
106
107  /* normalize */
108  l = (GLfloat)sqrt(n[X] * n[X] + n[Y] * n[Y] + n[Z] * n[Z]);
109  n[0] /= l;
110  n[1] /= l;
111  n[2] /= l;
112}
113
114/* _glmEqual: compares two vectors and returns GL_TRUE if they are
115 * equal (within a certain threshold) or GL_FALSE if not. An epsilon
116 * that works fairly well is 0.000001.
117 *
118 * u - array of 3 GLfloats (GLfloat u[3])
119 * v - array of 3 GLfloats (GLfloat v[3])
120 */
121static GLboolean
122_glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon)
123{
124  if (_glmAbs(u[0] - v[0]) < epsilon &&
125      _glmAbs(u[1] - v[1]) < epsilon &&
126      _glmAbs(u[2] - v[2]) < epsilon)
127  {
128    return GL_TRUE;
129  }
130  return GL_FALSE;
131}
132
133/* _glmWeldVectors: eliminate (weld) vectors that are within an
134 * epsilon of each other.
135 *
136 * vectors    - array of GLfloat[3]'s to be welded
137 * numvectors - number of GLfloat[3]'s in vectors
138 * epsilon    - maximum difference between vectors
139 *
140 */
141GLfloat*
142_glmWeldVectors(GLfloat* vectors, unsigned int* numvectors, GLfloat epsilon)
143{
144  GLfloat* copies;
145  unsigned int   copied;
146  unsigned int   i, j;
147
148  copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1));
149  memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1)));
150
151  copied = 1;
152  for (i = 1; i <= *numvectors; i++) {
153    for (j = 1; j <= copied; j++) {
154      if (_glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) {
155    goto duplicate;
156      }
157    }
158
159    /* must not be any duplicates -- add to the copies array */
160    copies[3 * copied + 0] = vectors[3 * i + 0];
161    copies[3 * copied + 1] = vectors[3 * i + 1];
162    copies[3 * copied + 2] = vectors[3 * i + 2];
163    j = copied;                /* pass this along for below */
164    copied++;
165
166  duplicate:
167    /* set the first component of this vector to point at the correct
168       index into the new copies array */
169    vectors[3 * i + 0] = (GLfloat)j;
170  }
171
172  *numvectors = copied-1;
173  return copies;
174}
175
176/* _glmFindGroup: Find a group in the model
177 */
178GLMgroup*
179_glmFindGroup(GLMmodel* model, char* name)
180{
181  GLMgroup* group;
182
183  assert(model);
184
185  group = model->groups;
186  while(group) {
187    if (!strcmp(name, group->name))
188      break;
189    group = group->next;
190  }
191
192  return group;
193}
194
195/* _glmAddGroup: Add a group to the model
196 */
197GLMgroup*
198_glmAddGroup(GLMmodel* model, char* name)
199{
200  GLMgroup* group;
201
202  group = _glmFindGroup(model, name);
203  if (!group) {
204    group = (GLMgroup*)malloc(sizeof(GLMgroup));
205    group->init();
206    group->name = strdup(name);
207    group->material = 0;
208    group->numtriangles = 0;
209    group->triangles = NULL;
210    group->hastexcoords = false;
211    group->next = model->groups;
212    model->groups = group;
213    model->numgroups++;
214
215    std::cout<<"_glmAddGroup="<<name<<std::endl;
216  }
217
218  return group;
219}
220
221/* _glmFindGroup: Find a material in the model
222 */
223unsigned int
224_glmFindMaterial(GLMmodel* model, char* name)
225{
226  unsigned int i;
227
228  for (i = 0; i < model->nummaterials; i++) {
229    if (!strcmp(model->materials[i].name, name))
230      goto found;
231  }
232
233  /* didn't find the name, so set it as the default material */
234  fprintf(stderr,"_glmFindMaterial():  can't find material \"%s\".\n", name);
235  i = 0;
236
237found:
238  return i;
239}
240
241
242/* _glmDirName: return the directory given a path
243 *
244 * path - filesystem path
245 *
246 * The return value should be free'd.
247 */
248static char*
249_glmDirName(char* path)
250{
251  char* dir;
252  char* s;
253  char* s2;
254
255  dir = strdup(path);
256
257  s = strrchr(dir, '/');
258  s2 = strrchr(dir, '\\');    // also look for backslashes
259  if (s2 > s)                // take whichever is later
260      s = s2;
261
262  if (s)
263    s[1] = '\0';
264  else
265    dir[0] = '\0';
266
267  return dir;
268}
269
270
271/* _glmReadMTLTextureOptions: parses the given line for texture options
272 * and applies the options to the given model/material
273 *
274 * model         - properly initialized GLMmodel structure
275 * materialIndex - the material affected in the given model
276 * line          - white-space separated options
277 */
278GLvoid
279_glmReadMTLTextureOptions(GLMmodel* model, unsigned int materialIndex, char* line)
280{
281  char *token;
282  char seps[] = " \t\n\r\f\v";
283  token = ::strtok(line, seps);
284  while(NULL != token)
285  {
286    switch(token[0])
287    {
288      case '-':
289        switch(token[1])
290        {
291          // Scaling:  -s <uScale> <vScale>
292          case 's':
293            float uScale, vScale;
294            token = ::strtok(NULL, seps);
295            uScale = token ? (float)::atof(token) : 1.0f;
296
297            token = ::strtok(NULL, seps);
298            vScale = token ? (float)::atof(token) : 1.0f;
299
300            if ((0.0f != uScale) && (0.0f != vScale))
301            {
302              uScale = 1.0f / uScale;
303              vScale = 1.0f / vScale;
304              model->materials[materialIndex].textureUScale = uScale;
305              model->materials[materialIndex].textureVScale = vScale;
306            }
307            break;
308
309          // Offset:  -o <uOffset> <vOffset>
310          case 'o':
311            float uOffset, vOffset;
312            token = ::strtok(NULL, seps);
313            uOffset = token ? (float)::atof(token) : 0.0f;
314
315            token = ::strtok(NULL, seps);
316            vOffset = token ? (float)::atof(token) : 0.0f;
317
318            model->materials[materialIndex].textureUOffset = uOffset;
319            model->materials[materialIndex].textureVOffset = vOffset;
320            break;
321
322          // These options are not handled - so just advance to the next
323          // valid token
324          // ==================================================================
325          //
326
327          // Clamping:  -clamp <on|off>
328          case 'c':
329            token = ::strtok(NULL, seps);
330            break;
331
332          // Bias and gain:  -mm <bias> <gain>
333          case 'm':
334          // Turbulence/Noise:  -t <uNoise> <vNoise>
335          case 't':
336            token = ::strtok(NULL, seps);
337            token = ::strtok(NULL, seps);
338            break;
339
340          default:
341            break;
342        }
343        break;
344
345      // Image filename
346      default:
347        if (0 != strlen(token))
348        {
349          model->materials[materialIndex].textureName = strdup(token);
350        }
351    }
352
353    // Advance to the next token
354    token = ::strtok(NULL, seps);
355  }
356}
357
358
359/* _glmReadMTL: read a wavefront material library file
360 *
361 * model - properly initialized GLMmodel structure
362 * name  - name of the material library
363 */
364static GLvoid
365_glmReadMTL(GLMmodel* model, char* name)
366{
367  FILE* file;
368  char* dir;
369  char* filename;
370  char  buf[128];
371  unsigned int nummaterials, i;
372
373  dir = _glmDirName(model->pathname);
374  filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 1));
375  strcpy(filename, dir);
376  strcat(filename, name);
377  free(dir);
378
379  /* open the file */
380  file = fopen(filename, "r");
381  if (!file) {
382    fprintf(stderr, "_glmReadMTL() failed: can't open material file \"%s\".\n",
383        filename);
384    return;
385  }
386  free(filename);
387
388  /* count the number of materials in the file */
389  nummaterials = 1;
390  while(fscanf(file, "%s", buf) != EOF) {
391    switch(buf[0]) {
392    case '#':                /* comment */
393      /* eat up rest of line */
394      fgets(buf, sizeof(buf), file);
395      break;
396    case 'n':                /* newmtl */
397      fgets(buf, sizeof(buf), file);
398      nummaterials++;
399      sscanf(buf, "%s %s", buf, buf);
400      break;
401    default:
402      /* eat up rest of line */
403      fgets(buf, sizeof(buf), file);
404      break;
405    }
406  }
407
408  rewind(file);
409
410  /* allocate memory for the materials */
411  model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * nummaterials);
412  model->nummaterials = nummaterials;
413
414  /* set the default material */
415  for (i = 0; i < nummaterials; i++) {
416    model->materials[i].init();
417    model->materials[i].name = NULL;
418    model->materials[i].shininess = 0.0f;
419    model->materials[i].diffuse[0] = 0.8f;
420    model->materials[i].diffuse[1] = 0.8f;
421    model->materials[i].diffuse[2] = 0.8f;
422    model->materials[i].diffuse[3] = 1.0f;
423    model->materials[i].ambient[0] = 0.2f;
424    model->materials[i].ambient[1] = 0.2f;
425    model->materials[i].ambient[2] = 0.2f;
426    model->materials[i].ambient[3] = 1.0f;
427    model->materials[i].specular[0] = 0.0f;
428    model->materials[i].specular[1] = 0.0f;
429    model->materials[i].specular[2] = 0.0f;
430    model->materials[i].textureName = NULL;
431    model->materials[i].textureReflection = false;
432    model->materials[i].textureUScale = 1.0f;
433    model->materials[i].textureVScale = 1.0f;
434    model->materials[i].textureUOffset = 0.0f;
435    model->materials[i].textureVOffset = 0.0f;
436    model->materials[i].alpha = 1.0f;
437  }
438  model->materials[0].name = strdup("default");
439
440  /* now, read in the data */
441  nummaterials = 0;
442  while(fscanf(file, "%s", buf) != EOF) {
443    switch(buf[0]) {
444    case '#':                /* comment */
445      /* eat up rest of line */
446      fgets(buf, sizeof(buf), file);
447      break;
448    case 'n':                /* newmtl */
449      fgets(buf, sizeof(buf), file);
450      sscanf(buf, "%s %s", buf, buf);
451      nummaterials++;
452      model->materials[nummaterials].name = strdup(buf);
453      break;
454    case 'N':
455      fscanf(file, "%f", &model->materials[nummaterials].shininess);
456      /* wavefront shininess is from [0, 1000], so scale for OpenGL */
457      model->materials[nummaterials].shininess /= 1000.0;
458      model->materials[nummaterials].shininess *= 128.0;
459      break;
460    case 'd':
461      fscanf(file, "%f", &model->materials[nummaterials].alpha);
462      break;
463    case 'K':
464      switch(buf[1]) {
465      case 'd':
466    fscanf(file, "%f %f %f",
467           &model->materials[nummaterials].diffuse[0],
468           &model->materials[nummaterials].diffuse[1],
469           &model->materials[nummaterials].diffuse[2]);
470    break;
471      case 's':
472    fscanf(file, "%f %f %f",
473           &model->materials[nummaterials].specular[0],
474           &model->materials[nummaterials].specular[1],
475           &model->materials[nummaterials].specular[2]);
476    break;
477      case 'a':
478    fscanf(file, "%f %f %f",
479           &model->materials[nummaterials].ambient[0],
480           &model->materials[nummaterials].ambient[1],
481           &model->materials[nummaterials].ambient[2]);
482    break;
483      default:
484    /* eat up rest of line */
485    fgets(buf, sizeof(buf), file);
486    break;
487      }
488      break;
489     
490    default:
491   
492      /* added by RO */
493      if (strcmp(buf,"map_Kd")==0)
494      {
495        fgets(buf, sizeof(buf), file);
496        _glmReadMTLTextureOptions(model, nummaterials, buf);
497      }
498      else if (strcmp(buf,"refl")==0)
499      {
500        model->materials[nummaterials].textureReflection = true;
501      }
502      else
503      {
504        /* eat up rest of line */
505        fgets(buf, sizeof(buf), file);
506      }
507      break;
508    }
509  }
510  fclose(file);
511}
512
513/* _glmWriteMTL: write a wavefront material library file
514 *
515 * model      - properly initialized GLMmodel structure
516 * modelpath  - pathname of the model being written
517 * mtllibname - name of the material library to be written
518 */
519static GLvoid
520_glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname)
521{
522  FILE* file;
523  char* dir;
524  char* filename;
525  GLMmaterial* material;
526  unsigned int i;
527
528  dir = _glmDirName(modelpath);
529  filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(mtllibname)));
530  strcpy(filename, dir);
531  strcat(filename, mtllibname);
532  free(dir);
533
534  /* open the file */
535  file = fopen(filename, "w");
536  if (!file) {
537    fprintf(stderr, "_glmWriteMTL() failed: can't open file \"%s\".\n",
538        filename);
539    return;
540  }
541  free(filename);
542
543  /* spit out a header */
544  fprintf(file, "#  \n");
545  fprintf(file, "#  Wavefront MTL generated by GLM library\n");
546  fprintf(file, "#  \n");
547  fprintf(file, "#  GLM library copyright (C) 1997 by Nate Robins\n");
548  fprintf(file, "#  email: ndr@pobox.com\n");
549  fprintf(file, "#  www:   http://www.pobox.com/~ndr\n");
550  fprintf(file, "#  \n\n");
551
552  for (i = 0; i < model->nummaterials; i++) {
553    material = &model->materials[i];
554    fprintf(file, "newmtl %s\n", material->name);
555    fprintf(file, "Ka %f %f %f\n",
556        material->ambient[0], material->ambient[1], material->ambient[2]);
557    fprintf(file, "Kd %f %f %f\n",
558        material->diffuse[0], material->diffuse[1], material->diffuse[2]);
559    fprintf(file, "Ks %f %f %f\n",
560        material->specular[0],material->specular[1],material->specular[2]);
561    fprintf(file, "Ns %f\n", material->shininess);
562    fprintf(file, "\n");
563  }
564}
565/* Create by RO to help handle g %s %s groups */
566static void createCompositeName(char* buf,char* compositeName)
567{
568    char *ptr_b = buf;
569    char *ptr_c = compositeName;
570
571    /* first skip over leading spaces */
572    while(*ptr_b!=0 && *ptr_b==' ') ++ptr_b;
573
574    /* copy over rest, changing spaces for underscores,
575     * to handle faces which are contained in several groups */
576    while(*ptr_b>=' ')
577    {
578      if (*ptr_b==' ') *ptr_c = '_';
579      else *ptr_c = *ptr_b;
580      ++ptr_c;
581      ++ptr_b;
582    }
583    *ptr_c = 0;
584}
585/* _glmFirstPass: first pass at a Wavefront OBJ file that gets all the
586 * statistics of the model (such as #vertices, #normals, etc)
587 *
588 * model - properly initialized GLMmodel structure
589 * file  - (fopen'd) file descriptor
590 */
591static GLvoid
592_glmFirstPass(GLMmodel* model, FILE* file)
593{
594  unsigned int    numvertices;        /* number of vertices in model */
595  unsigned int    numnormals;            /* number of normals in model */
596  unsigned int    numtexcoords;        /* number of texcoords in model */
597  unsigned int    numtriangles;        /* number of triangles in model */
598  GLMgroup* group;            /* current group */
599  unsigned  v, n, t;
600  char      buf[128];
601
602  /* make a default group */
603  group = _glmAddGroup(model, "default");
604
605  float x,y,z;
606  int r,g,b;
607
608  numvertices = numnormals = numtexcoords = numtriangles = 0;
609 
610  unsigned int numcolors = 0;
611 
612  while(fscanf(file, "%s", buf) != EOF) {
613 
614 
615    switch(buf[0]) {
616    case '#':                /* comment */
617      /* eat up rest of line */
618      fgets(buf, sizeof(buf), file);
619      break;
620    case 'v':                /* v, vn, vt */
621      switch(buf[1]) {
622      case '\0':            /* vertex */
623        {
624            /* eat up rest of line */
625            fgets(buf, sizeof(buf), file);
626
627            int noRead = sscanf(buf, "%f %f %f %d %d %d",
628                                &x, &y, &z, &r,&g,&b);
629
630            numvertices++;
631            if (noRead==6) numcolors++;
632
633
634            break;
635        }
636      case 'n':                /* normal */
637        /* eat up rest of line */
638        fgets(buf, sizeof(buf), file);
639        numnormals++;
640        break;
641      case 't':                /* texcoord */
642        /* eat up rest of line */
643        fgets(buf, sizeof(buf), file);
644        numtexcoords++;
645        break;
646      default:
647        printf("_glmFirstPass(): Unknown token \"%s\".\n", buf);
648        //exit(1);
649        return;
650      }
651      break;
652    case 'm':
653      fgets(buf, sizeof(buf), file);
654      sscanf(buf, "%s %s", buf, buf);
655      model->mtllibname = strdup(buf);
656      _glmReadMTL(model, buf);
657      break;
658    case 'u':
659      /* eat up rest of line */
660      fgets(buf, sizeof(buf), file);
661      break;
662    case 'o':                /* group */
663    case 's':                /* group */
664    case 'g':                /* group */
665      {
666        /* eat up rest of line */
667        fgets(buf, sizeof(buf), file);
668
669        char compositeName[128];
670        createCompositeName(buf,compositeName);
671
672        group = _glmAddGroup(model, compositeName);
673      }
674      break;
675    case 'f':                /* face */
676      v = n = t = 0;
677      fscanf(file, "%s", buf);
678      /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
679      if (strstr(buf, "//")) {
680    /* v//n */
681    sscanf(buf, "%d//%d", &v, &n);
682    fscanf(file, "%d//%d", &v, &n);
683    fscanf(file, "%d//%d", &v, &n);
684    numtriangles++;
685    group->numtriangles++;
686    while(fscanf(file, "%d//%d", &v, &n) > 0) {
687      numtriangles++;
688      group->numtriangles++;
689    }
690      } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
691    /* v/t/n */
692    fscanf(file, "%d/%d/%d", &v, &t, &n);
693    fscanf(file, "%d/%d/%d", &v, &t, &n);
694    numtriangles++;
695    group->numtriangles++;
696    while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
697      numtriangles++;
698      group->numtriangles++;
699    }
700      } else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
701    /* v/t */
702    fscanf(file, "%d/%d", &v, &t);
703    fscanf(file, "%d/%d", &v, &t);
704    numtriangles++;
705    group->numtriangles++;
706    while(fscanf(file, "%d/%d", &v, &t) > 0) {
707      numtriangles++;
708      group->numtriangles++;
709    }
710      } else {
711    /* v */
712    fscanf(file, "%d", &v);
713    fscanf(file, "%d", &v);
714    numtriangles++;
715    group->numtriangles++;
716    while(fscanf(file, "%d", &v) > 0) {
717      numtriangles++;
718      group->numtriangles++;
719    }
720      }
721      break;
722
723    default:
724      /* eat up rest of line */
725      fgets(buf, sizeof(buf), file);
726      break;
727    }
728
729    std::cout<<"line="<<buf<<std::endl;
730
731  }
732
733#if 0
734  /* announce the model statistics */
735  printf(" Vertices: %d\n", numvertices);
736  printf(" Normals: %d\n", numnormals);
737  printf(" Texcoords: %d\n", numtexcoords);
738  printf(" Triangles: %d\n", numtriangles);
739  printf(" Groups: %d\n", model->numgroups);
740#endif
741
742  /* set the stats in the model structure */
743  model->numvertices  = numvertices;
744  model->numnormals   = numnormals;
745  model->numtexcoords = numtexcoords;
746  model->numtriangles = numtriangles;
747
748  /* allocate memory for the triangles in each group */
749  group = model->groups;
750  while(group) {
751    group->triangles = (unsigned int*)malloc(sizeof(unsigned int) * group->numtriangles);
752    group->numtriangles = 0;
753    group = group->next;
754  }
755
756
757  // if all vertices have colours enables per vertex colors
758  if (numvertices==numcolors) model->useColors = true;
759
760}
761
762/* _glmSecondPass: second pass at a Wavefront OBJ file that gets all
763 * the data.
764 *
765 * model - properly initialized GLMmodel structure
766 * file  - (fopen'd) file descriptor
767 */
768static GLvoid
769_glmSecondPass(GLMmodel* model, FILE* file)
770{
771  unsigned int    numvertices;        /* number of vertices in model */
772  unsigned int    numnormals;            /* number of normals in model */
773  unsigned int    numtexcoords;        /* number of texcoords in model */
774  unsigned int    numtriangles;        /* number of triangles in model */
775  GLfloat*  vertices;            /* array of vertices  */
776  GLfloat*  normals;            /* array of normals */
777  GLfloat*  texcoords;            /* array of texture coordinates */
778  GLMgroup* group;            /* current group pointer */
779  unsigned int    material;            /* current material */
780  unsigned int    v, n, t;
781  char      buf[128];
782
783  /* set the pointer shortcuts */
784  vertices     = model->vertices;
785  normals      = model->normals;
786  texcoords    = model->texcoords;
787  group        = model->groups;
788
789  /* on the second pass through the file, read all the data into the
790     allocated arrays */
791  numvertices = numnormals = numtexcoords = 1;
792  numtriangles = 0;
793  material = 0;
794 
795  bool firstGroup = true;
796  bool previousLineWas_g = false;
797
798  int r,g,b;
799  while(fscanf(file, "%s", buf) != EOF) {
800    char c = buf[0];
801    switch(c) {
802    case '#':                /* comment */
803      /* eat up rest of line */
804      fgets(buf, sizeof(buf), file);
805      break;
806    case 'v':                /* v, vn, vt */
807      switch(buf[1]) {
808      case '\0':            /* vertex */
809        {
810            if (model->useColors)
811            {
812                fscanf(file, "%f %f %f %d %d %d",
813                             &vertices[3 * numvertices + X],
814                             &vertices[3 * numvertices + Y],
815                             &vertices[3 * numvertices + Z],
816                             &r,&g,&b);
817                model->colors[numvertices].set(r,g,b,255);
818
819                numvertices++;               
820            } else
821            {
822                fscanf(file, "%f %f %f",
823                             &vertices[3 * numvertices + X],
824                             &vertices[3 * numvertices + Y],
825                             &vertices[3 * numvertices + Z]);
826                numvertices++;               
827            }
828        }
829        break;
830      case 'n':                /* normal */
831        fscanf(file, "%f %f %f",
832               &normals[3 * numnormals + X],
833               &normals[3 * numnormals + Y],
834               &normals[3 * numnormals + Z]);
835        numnormals++;
836        break;
837      case 't':                /* texcoord */
838        fscanf(file, "%f %f",
839               &texcoords[2 * numtexcoords + X],
840               &texcoords[2 * numtexcoords + Y]);
841        numtexcoords++;
842        break;
843      }
844      break;
845    case 'u':
846      fgets(buf, sizeof(buf), file);
847      sscanf(buf, "%s %s", buf, buf);
848     
849      material = _glmFindMaterial(model, buf);
850     
851      group->material = material;
852
853      break;
854    case 'o':                /* group */
855    case 's':                /* group */
856    case 'g':                /* group */
857      /* eat up rest of line */
858      fgets(buf, sizeof(buf), file);
859      char compositeName[128];
860      createCompositeName(buf,compositeName);
861      group = _glmFindGroup(model, compositeName);
862      std::cout<<"compositeName="<<compositeName<<"  group="<<group<<std::endl;
863      group->material = material;
864      firstGroup = false;
865      break;
866    case 'f':                /* face */
867      v = n = t = 0;
868      fscanf(file, "%s", buf);
869      /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
870      if (strstr(buf, "//")) {
871        /* v//n */
872        sscanf(buf, "%d//%d", &v, &n);
873        T(numtriangles).vindices[0] = v;
874        T(numtriangles).nindices[0] = n;
875        fscanf(file, "%d//%d", &v, &n);
876        T(numtriangles).vindices[1] = v;
877        T(numtriangles).nindices[1] = n;
878        fscanf(file, "%d//%d", &v, &n);
879        T(numtriangles).vindices[2] = v;
880        T(numtriangles).nindices[2] = n;
881        group->triangles[group->numtriangles++] = numtriangles;
882        numtriangles++;
883        while(fscanf(file, "%d//%d", &v, &n) > 0) {
884          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
885          T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
886          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
887          T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
888          T(numtriangles).vindices[2] = v;
889          T(numtriangles).nindices[2] = n;
890          group->triangles[group->numtriangles++] = numtriangles;
891          numtriangles++;
892        }
893      } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) {
894        /* v/t/n */
895        T(numtriangles).vindices[0] = v;
896        T(numtriangles).tindices[0] = t;
897        T(numtriangles).nindices[0] = n;
898        fscanf(file, "%d/%d/%d", &v, &t, &n);
899        T(numtriangles).vindices[1] = v;
900        T(numtriangles).tindices[1] = t;
901        T(numtriangles).nindices[1] = n;
902        fscanf(file, "%d/%d/%d", &v, &t, &n);
903        T(numtriangles).vindices[2] = v;
904        T(numtriangles).tindices[2] = t;
905        T(numtriangles).nindices[2] = n;
906        group->triangles[group->numtriangles++] = numtriangles;
907        group->hastexcoords = true;
908        numtriangles++;
909        while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) {
910          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
911          T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
912          T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0];
913          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
914          T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
915          T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2];
916          T(numtriangles).vindices[2] = v;
917          T(numtriangles).tindices[2] = t;
918          T(numtriangles).nindices[2] = n;
919          group->triangles[group->numtriangles++] = numtriangles;
920          numtriangles++;
921        }
922      } else if (sscanf(buf, "%d/%d", &v, &t) == 2) {
923        /* v/t */
924        T(numtriangles).vindices[0] = v;
925        T(numtriangles).tindices[0] = t;
926        fscanf(file, "%d/%d", &v, &t);
927        T(numtriangles).vindices[1] = v;
928        T(numtriangles).tindices[1] = t;
929        fscanf(file, "%d/%d", &v, &t);
930        T(numtriangles).vindices[2] = v;
931        T(numtriangles).tindices[2] = t;
932        group->triangles[group->numtriangles++] = numtriangles;
933        group->hastexcoords = true;
934        numtriangles++;
935        while(fscanf(file, "%d/%d", &v, &t) > 0) {
936          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
937          T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0];
938          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
939          T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2];
940          T(numtriangles).vindices[2] = v;
941          T(numtriangles).tindices[2] = t;
942          group->triangles[group->numtriangles++] = numtriangles;
943          numtriangles++;
944        }
945      } else {
946        /* v */
947        sscanf(buf, "%d", &v);
948        T(numtriangles).vindices[0] = v;
949        fscanf(file, "%d", &v);
950        T(numtriangles).vindices[1] = v;
951        fscanf(file, "%d", &v);
952        T(numtriangles).vindices[2] = v;
953        group->triangles[group->numtriangles++] = numtriangles;
954        numtriangles++;
955        while(fscanf(file, "%d", &v) > 0) {
956          T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0];
957          T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2];
958          T(numtriangles).vindices[2] = v;
959          group->triangles[group->numtriangles++] = numtriangles;
960          numtriangles++;
961        }
962      }
963      break;
964
965    default:
966      /* eat up rest of line */
967      fgets(buf, sizeof(buf), file);
968      break;
969    }
970   
971    // a hack by Robert Osfield to account for usemtl being infront
972    // or the group, or after - but only one line after.
973    previousLineWas_g = (c=='g');
974  }
975
976#if 0
977  /* announce the memory requirements */
978  printf(" Memory: %d bytes\n",
979     numvertices  * 3*sizeof(GLfloat) +
980     numnormals   * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) +
981     numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) +
982     numtriangles * sizeof(GLMtriangle));
983#endif
984}
985
986
987
988
989/* public functions */
990
991/* glmUnitize: "unitize" a model by translating it to the origin and
992 * scaling it to fit in a unit cube around the origin.  Returns the
993 * scalefactor used.
994 *
995 * model - properly initialized GLMmodel structure
996 */
997GLfloat
998glmUnitize(GLMmodel* model)
999{
1000  unsigned int  i;
1001  GLfloat maxx, minx, maxy, miny, maxz, minz;
1002  GLfloat cx, cy, cz, w, h, d;
1003  GLfloat scale;
1004
1005  assert(model);
1006  assert(model->vertices);
1007
1008  /* get the max/mins */
1009  maxx = minx = model->vertices[3 + X];
1010  maxy = miny = model->vertices[3 + Y];
1011  maxz = minz = model->vertices[3 + Z];
1012  for (i = 1; i <= model->numvertices; i++) {
1013    if (maxx < model->vertices[3 * i + X])
1014      maxx = model->vertices[3 * i + X];
1015    if (minx > model->vertices[3 * i + X])
1016      minx = model->vertices[3 * i + X];
1017
1018    if (maxy < model->vertices[3 * i + Y])
1019      maxy = model->vertices[3 * i + Y];
1020    if (miny > model->vertices[3 * i + Y])
1021      miny = model->vertices[3 * i + Y];
1022
1023    if (maxz < model->vertices[3 * i + Z])
1024      maxz = model->vertices[3 * i + Z];
1025    if (minz > model->vertices[3 * i + Z])
1026      minz = model->vertices[3 * i + Z];
1027  }
1028
1029  /* calculate model width, height, and depth */
1030  w = _glmAbs(maxx) + _glmAbs(minx);
1031  h = _glmAbs(maxy) + _glmAbs(miny);
1032  d = _glmAbs(maxz) + _glmAbs(minz);
1033
1034  /* calculate center of the model */
1035  cx = (maxx + minx) / 2.0f;
1036  cy = (maxy + miny) / 2.0f;
1037  cz = (maxz + minz) / 2.0f;
1038
1039  /* calculate unitizing scale factor */
1040  scale = 2.0f / _glmMax(_glmMax(w, h), d);
1041
1042  /* translate around center then scale */
1043  for (i = 1; i <= model->numvertices; i++) {
1044    model->vertices[3 * i + X] -= cx;
1045    model->vertices[3 * i + Y] -= cy;
1046    model->vertices[3 * i + Z] -= cz;
1047    model->vertices[3 * i + X] *= scale;
1048    model->vertices[3 * i + Y] *= scale;
1049    model->vertices[3 * i + Z] *= scale;
1050  }
1051
1052  return scale;
1053}
1054
1055/* glmDimensions: Calculates the dimensions (width, height, depth) of
1056 * a model.
1057 *
1058 * model      - initialized GLMmodel structure
1059 * dimensions - array of 3 GLfloats (GLfloat dimensions[3])
1060 */
1061GLvoid
1062glmDimensions(GLMmodel* model, GLfloat* dimensions)
1063{
1064  unsigned int i;
1065  GLfloat maxx, minx, maxy, miny, maxz, minz;
1066
1067  assert(model);
1068  assert(model->vertices);
1069  assert(dimensions);
1070
1071  /* get the max/mins */
1072  maxx = minx = model->vertices[3 + X];
1073  maxy = miny = model->vertices[3 + Y];
1074  maxz = minz = model->vertices[3 + Z];
1075  for (i = 1; i <= model->numvertices; i++) {
1076    if (maxx < model->vertices[3 * i + X])
1077      maxx = model->vertices[3 * i + X];
1078    if (minx > model->vertices[3 * i + X])
1079      minx = model->vertices[3 * i + X];
1080
1081    if (maxy < model->vertices[3 * i + Y])
1082      maxy = model->vertices[3 * i + Y];
1083    if (miny > model->vertices[3 * i + Y])
1084      miny = model->vertices[3 * i + Y];
1085
1086    if (maxz < model->vertices[3 * i + Z])
1087      maxz = model->vertices[3 * i + Z];
1088    if (minz > model->vertices[3 * i + Z])
1089      minz = model->vertices[3 * i + Z];
1090  }
1091
1092  /* calculate model width, height, and depth */
1093  dimensions[X] = _glmAbs(maxx) + _glmAbs(minx);
1094  dimensions[Y] = _glmAbs(maxy) + _glmAbs(miny);
1095  dimensions[Z] = _glmAbs(maxz) + _glmAbs(minz);
1096}
1097
1098/* glmScale: Scales a model by a given amount.
1099 *
1100 * model - properly initialized GLMmodel structure
1101 * scale - scalefactor (0.5 = half as large, 2.0 = twice as large)
1102 */
1103GLvoid
1104glmScale(GLMmodel* model, GLfloat scale)
1105{
1106  unsigned int i;
1107
1108  for (i = 1; i <= model->numvertices; i++) {
1109    model->vertices[3 * i + X] *= scale;
1110    model->vertices[3 * i + Y] *= scale;
1111    model->vertices[3 * i + Z] *= scale;
1112  }
1113}
1114
1115/* glmReverseWinding: Reverse the polygon winding for all polygons in
1116 * this model.  Default winding is counter-clockwise.  Also changes
1117 * the direction of the normals.
1118 *
1119 * model - properly initialized GLMmodel structure
1120 */
1121GLvoid
1122glmReverseWinding(GLMmodel* model)
1123{
1124  unsigned int i, swap;
1125
1126  assert(model);
1127
1128  for (i = 0; i < model->numtriangles; i++) {
1129    swap = T(i).vindices[0];
1130    T(i).vindices[0] = T(i).vindices[2];
1131    T(i).vindices[2] = swap;
1132
1133    if (model->numnormals) {
1134      swap = T(i).nindices[0];
1135      T(i).nindices[0] = T(i).nindices[2];
1136      T(i).nindices[2] = swap;
1137    }
1138
1139    if (model->numtexcoords) {
1140      swap = T(i).tindices[0];
1141      T(i).tindices[0] = T(i).tindices[2];
1142      T(i).tindices[2] = swap;
1143    }
1144  }
1145
1146  /* reverse facet normals */
1147  for (i = 1; i <= model->numfacetnorms; i++) {
1148    model->facetnorms[3 * i + X] = -model->facetnorms[3 * i + X];
1149    model->facetnorms[3 * i + Y] = -model->facetnorms[3 * i + Y];
1150    model->facetnorms[3 * i + Z] = -model->facetnorms[3 * i + Z];
1151  }
1152
1153  /* reverse vertex normals */
1154  for (i = 1; i <= model->numnormals; i++) {
1155    model->normals[3 * i + X] = -model->normals[3 * i + X];
1156    model->normals[3 * i + Y] = -model->normals[3 * i + Y];
1157    model->normals[3 * i + Z] = -model->normals[3 * i + Z];
1158  }
1159}
1160
1161/* glmFacetNormals: Generates facet normals for a model (by taking the
1162 * cross product of the two vectors derived from the sides of each
1163 * triangle).  Assumes a counter-clockwise winding.
1164 *
1165 * model - initialized GLMmodel structure
1166 */
1167GLvoid
1168glmFacetNormals(GLMmodel* model)
1169{
1170  unsigned int  i;
1171  GLfloat u[3];
1172  GLfloat v[3];
1173 
1174  assert(model);
1175  assert(model->vertices);
1176
1177  /* clobber any old facetnormals */
1178  if (model->facetnorms)
1179    free(model->facetnorms);
1180
1181  /* allocate memory for the new facet normals */
1182  model->numfacetnorms = model->numtriangles;
1183  model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) *
1184                       3 * (model->numfacetnorms + 1));
1185
1186  for (i = 0; i < model->numtriangles; i++) {
1187    model->triangles[i].findex = i+1;
1188
1189    u[X] = model->vertices[3 * T(i).vindices[1] + X] -
1190           model->vertices[3 * T(i).vindices[0] + X];
1191    u[Y] = model->vertices[3 * T(i).vindices[1] + Y] -
1192           model->vertices[3 * T(i).vindices[0] + Y];
1193    u[Z] = model->vertices[3 * T(i).vindices[1] + Z] -
1194           model->vertices[3 * T(i).vindices[0] + Z];
1195
1196    v[X] = model->vertices[3 * T(i).vindices[2] + X] -
1197           model->vertices[3 * T(i).vindices[0] + X];
1198    v[Y] = model->vertices[3 * T(i).vindices[2] + Y] -
1199           model->vertices[3 * T(i).vindices[0] + Y];
1200    v[Z] = model->vertices[3 * T(i).vindices[2] + Z] -
1201           model->vertices[3 * T(i).vindices[0] + Z];
1202
1203    _glmCross(u, v, &model->facetnorms[3 * (i+1)]);
1204    _glmNormalize(&model->facetnorms[3 * (i+1)]);
1205  }
1206}
1207
1208/* glmVertexNormals: Generates smooth vertex normals for a model.
1209 * First builds a list of all the triangles each vertex is in.  Then
1210 * loops through each vertex in the the list averaging all the facet
1211 * normals of the triangles each vertex is in.  Finally, sets the
1212 * normal index in the triangle for the vertex to the generated smooth
1213 * normal.  If the dot product of a facet normal and the facet normal
1214 * associated with the first triangle in the list of triangles the
1215 * current vertex is in is greater than the cosine of the angle
1216 * parameter to the function, that facet normal is not added into the
1217 * average normal calculation and the corresponding vertex is given
1218 * the facet normal.  This tends to preserve hard edges.  The angle to
1219 * use depends on the model, but 90 degrees is usually a good start.
1220 *
1221 * model - initialized GLMmodel structure
1222 * angle - maximum angle (in degrees) to smooth across
1223 */
1224GLvoid
1225glmVertexNormals(GLMmodel* model, GLfloat angle)
1226{
1227  GLMnode*  node;
1228  GLMnode*  tail;
1229  GLMnode** members;
1230  GLfloat*  normals;
1231  unsigned int    numnormals;
1232  GLfloat   average[3];
1233  GLfloat   dot, cos_angle;
1234  unsigned int    i, avg;
1235
1236  assert(model);
1237  assert(model->facetnorms);
1238
1239  /* calculate the cosine of the angle (in degrees) */
1240  cos_angle = (float)cos(osg::DegreesToRadians(angle));
1241
1242  /* nuke any previous normals */
1243  if (model->normals)
1244    free(model->normals);
1245
1246  /* allocate space for new normals */
1247  model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */
1248  model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
1249
1250  /* allocate a structure that will hold a linked list of triangle
1251     indices for each vertex */
1252  members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1));
1253  for (i = 1; i <= model->numvertices; i++)
1254    members[i] = NULL;
1255 
1256  /* for every triangle, create a node for each vertex in it */
1257  for (i = 0; i < model->numtriangles; i++) {
1258    node = (GLMnode*)malloc(sizeof(GLMnode));
1259    node->index = i;
1260    node->next  = members[T(i).vindices[0]];
1261    members[T(i).vindices[0]] = node;
1262
1263    node = (GLMnode*)malloc(sizeof(GLMnode));
1264    node->index = i;
1265    node->next  = members[T(i).vindices[1]];
1266    members[T(i).vindices[1]] = node;
1267
1268    node = (GLMnode*)malloc(sizeof(GLMnode));
1269    node->index = i;
1270    node->next  = members[T(i).vindices[2]];
1271    members[T(i).vindices[2]] = node;
1272  }
1273
1274  /* calculate the average normal for each vertex */
1275  numnormals = 1;
1276  for (i = 1; i <= model->numvertices; i++) {
1277    /* calculate an average normal for this vertex by averaging the
1278       facet normal of every triangle this vertex is in */
1279    node = members[i];
1280    if (!node)
1281      fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n");
1282    average[0] = 0.0; average[1] = 0.0; average[2] = 0.0;
1283    avg = 0;
1284    while (node) {
1285      /* only average if the dot product of the angle between the two
1286         facet normals is greater than the cosine of the threshold
1287         angle -- or, said another way, the angle between the two
1288         facet normals is less than (or equal to) the threshold angle */
1289      dot = _glmDot(&model->facetnorms[3 * T(node->index).findex],
1290             &model->facetnorms[3 * T(members[i]->index).findex]);
1291      if (dot > cos_angle) {
1292    node->averaged = GL_TRUE;
1293    average[0] += model->facetnorms[3 * T(node->index).findex + 0];
1294    average[1] += model->facetnorms[3 * T(node->index).findex + 1];
1295    average[2] += model->facetnorms[3 * T(node->index).findex + 2];
1296    avg = 1;            /* we averaged at least one normal! */
1297      } else {
1298    node->averaged = GL_FALSE;
1299      }
1300      node = node->next;
1301    }
1302
1303    if (avg) {
1304      /* normalize the averaged normal */
1305      _glmNormalize(average);
1306
1307      /* add the normal to the vertex normals list */
1308      model->normals[3 * numnormals + 0] = average[0];
1309      model->normals[3 * numnormals + 1] = average[1];
1310      model->normals[3 * numnormals + 2] = average[2];
1311      avg = numnormals;
1312      numnormals++;
1313    }
1314
1315    /* set the normal of this vertex in each triangle it is in */
1316    node = members[i];
1317    while (node) {
1318      if (node->averaged) {
1319    /* if this node was averaged, use the average normal */
1320    if (T(node->index).vindices[0] == i)
1321      T(node->index).nindices[0] = avg;
1322    else if (T(node->index).vindices[1] == i)
1323      T(node->index).nindices[1] = avg;
1324    else if (T(node->index).vindices[2] == i)
1325      T(node->index).nindices[2] = avg;
1326      } else {
1327    /* if this node wasn't averaged, use the facet normal */
1328    model->normals[3 * numnormals + 0] =
1329      model->facetnorms[3 * T(node->index).findex + 0];
1330    model->normals[3 * numnormals + 1] =
1331      model->facetnorms[3 * T(node->index).findex + 1];
1332    model->normals[3 * numnormals + 2] =
1333      model->facetnorms[3 * T(node->index).findex + 2];
1334    if (T(node->index).vindices[0] == i)
1335      T(node->index).nindices[0] = numnormals;
1336    else if (T(node->index).vindices[1] == i)
1337      T(node->index).nindices[1] = numnormals;
1338    else if (T(node->index).vindices[2] == i)
1339      T(node->index).nindices[2] = numnormals;
1340    numnormals++;
1341      }
1342      node = node->next;
1343    }
1344  }
1345 
1346  model->numnormals = numnormals - 1;
1347
1348  /* free the member information */
1349  for (i = 1; i <= model->numvertices; i++) {
1350    node = members[i];
1351    while (node) {
1352      tail = node;
1353      node = node->next;
1354      free(tail);
1355    }
1356  }
1357  free(members);
1358
1359  /* pack the normals array (we previously allocated the maximum
1360     number of normals that could possibly be created (numtriangles *
1361     3), so get rid of some of them (usually alot unless none of the
1362     facet normals were averaged)) */
1363  normals = model->normals;
1364  model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1));
1365  for (i = 1; i <= model->numnormals; i++) {
1366    model->normals[3 * i + 0] = normals[3 * i + 0];
1367    model->normals[3 * i + 1] = normals[3 * i + 1];
1368    model->normals[3 * i + 2] = normals[3 * i + 2];
1369  }
1370  free(normals);
1371
1372  printf("glmVertexNormals(): %d normals generated\n", model->numnormals);
1373}
1374
1375
1376/* glmLinearTexture: Generates texture coordinates according to a
1377 * linear projection of the texture map.  It generates these by
1378 * linearly mapping the vertices onto a square.
1379 *
1380 * model - pointer to initialized GLMmodel structure
1381 */
1382GLvoid
1383glmLinearTexture(GLMmodel* model)
1384{
1385  GLMgroup *group;
1386  GLfloat dimensions[3];
1387  GLfloat x, y, scalefactor;
1388  unsigned int i;
1389 
1390  assert(model);
1391
1392  if (model->texcoords)
1393    free(model->texcoords);
1394  model->numtexcoords = model->numvertices;
1395  model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
1396 
1397  glmDimensions(model, dimensions);
1398  scalefactor = 2.0f /
1399    _glmAbs(_glmMax(_glmMax(dimensions[0], dimensions[1]), dimensions[2]));
1400
1401  /* do the calculations */
1402  for(i = 1; i <= model->numvertices; i++) {
1403    x = model->vertices[3 * i + 0] * scalefactor;
1404    y = model->vertices[3 * i + 2] * scalefactor;
1405    model->texcoords[2 * i + 0] = (x + 1.0f) / 2.0f;
1406    model->texcoords[2 * i + 1] = (y + 1.0f) / 2.0f;
1407  }
1408 
1409  /* go through and put texture coordinate indices in all the triangles */
1410  group = model->groups;
1411  while(group) {
1412    for(i = 0; i < group->numtriangles; i++) {
1413      T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0];
1414      T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1];
1415      T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2];
1416    }   
1417    group = group->next;
1418  }
1419
1420#if 0
1421  printf("glmLinearTexture(): generated %d linear texture coordinates\n",
1422      model->numtexcoords);
1423#endif
1424}
1425
1426/* glmSpheremapTexture: Generates texture coordinates according to a
1427 * spherical projection of the texture map.  Sometimes referred to as
1428 * spheremap, or reflection map texture coordinates.  It generates
1429 * these by using the normal to calculate where that vertex would map
1430 * onto a sphere.  Since it is impossible to map something flat
1431 * perfectly onto something spherical, there is distortion at the
1432 * poles.  This particular implementation causes the poles along the X
1433 * axis to be distorted.
1434 *
1435 * model - pointer to initialized GLMmodel structure
1436 */
1437GLvoid
1438glmSpheremapTexture(GLMmodel* model)
1439{
1440  GLMgroup* group;
1441  GLfloat theta, phi, rho, x, y, z, r;
1442  unsigned int i;
1443 
1444  assert(model);
1445  assert(model->normals);
1446
1447  if (model->texcoords)
1448    free(model->texcoords);
1449  model->numtexcoords = model->numnormals;
1450  model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1));
1451     
1452  /* do the calculations */
1453  for (i = 1; i <= model->numnormals; i++) {
1454    z = model->normals[3 * i + 0];    /* re-arrange for pole distortion */
1455    y = model->normals[3 * i + 1];
1456    x = model->normals[3 * i + 2];
1457    r = sqrtf((x * x) + (y * y));
1458    rho = sqrtf((r * r) + (z * z));
1459     
1460    if(r == 0.0f) {
1461    theta = 0.0f;
1462    phi = 0.0f;
1463    } else {
1464      if(z == 0.0)
1465    phi = 3.14159265f / 2.0f;
1466      else
1467    phi = acosf(z / rho);
1468     
1469#if WE_DONT_NEED_THIS_CODE
1470      if(x == 0.0)
1471    theta = 3.14159265f / 2.0f;    /* asin(y / r); */
1472      else
1473    theta = acos(x / r);
1474#endif
1475     
1476      if(y == 0.0)
1477    theta = 3.141592365f / 2.0f;    /* acos(x / r); */
1478      else
1479    theta = asinf(y / r) + 3.14159265f / 2.0f;
1480    }
1481   
1482    model->texcoords[2 * i + 0] = theta / 3.14159265f;
1483    model->texcoords[2 * i + 1] = phi / 3.14159265f;
1484  }
1485 
1486  /* go through and put texcoord indices in all the triangles */
1487  group = model->groups;
1488  while(group) {
1489    for (i = 0; i < group->numtriangles; i++) {
1490      T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0];
1491      T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1];
1492      T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2];
1493    }
1494    group = group->next;
1495  }
1496
1497#if 0 
1498  printf("glmSpheremapTexture(): generated %d spheremap texture coordinates\n",
1499     model->numtexcoords);
1500#endif
1501}
1502
1503/* glmDelete: Deletes a GLMmodel structure.
1504 *
1505 * model - initialized GLMmodel structure
1506 */
1507GLvoid
1508glmDelete(GLMmodel* model)
1509{
1510  GLMgroup* group;
1511  unsigned int i;
1512
1513  assert(model);
1514
1515  if (model->pathname)   free(model->pathname);
1516  if (model->mtllibname) free(model->mtllibname);
1517  if (model->vertices)   free(model->vertices);
1518  if (model->colors)     free(model->colors);
1519  if (model->normals)    free(model->normals);
1520  if (model->texcoords)  free(model->texcoords);
1521  if (model->facetnorms) free(model->facetnorms);
1522  if (model->triangles)  free(model->triangles);
1523  if (model->materials) {
1524    for (i = 0; i < model->nummaterials; i++)
1525    {
1526      free(model->materials[i].name);
1527      free(model->materials[i].textureName);
1528    }
1529  }
1530  free(model->materials);
1531  while(model->groups) {
1532    group = model->groups;
1533    model->groups = model->groups->next;
1534    free(group->name);
1535    free(group->triangles);
1536    free(group);
1537  }
1538
1539  free(model);
1540}
1541
1542/* glmReadOBJ: Reads a model description from a Wavefront .OBJ file.
1543 * Returns a pointer to the created object which should be free'd with
1544 * glmDelete().
1545 *
1546 * filename - name of the file containing the Wavefront .OBJ format data. 
1547 */
1548GLMmodel*
1549glmReadOBJ(char* filename)
1550{
1551  GLMmodel* model;
1552  FILE*     file;
1553
1554  /* open the file */
1555  file = fopen(filename, "r");
1556  if (!file) {
1557    fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n",
1558        filename);
1559    //exit(1);
1560    return NULL;
1561  }
1562
1563#if 0
1564  /* announce the model name */
1565  printf("Model: %s\n", filename);
1566#endif
1567
1568  /* allocate a new model */
1569  model = (GLMmodel*)malloc(sizeof(GLMmodel));
1570  model->pathname      = strdup(filename);
1571  model->mtllibname    = NULL;
1572  model->numvertices   = 0;
1573  model->vertices      = NULL;
1574  model->useColors     = false;
1575  model->colors        = NULL;
1576  model->numnormals    = 0;
1577  model->normals       = NULL;
1578  model->numtexcoords  = 0;
1579  model->texcoords     = NULL;
1580  model->numfacetnorms = 0;
1581  model->facetnorms    = NULL;
1582  model->numtriangles  = 0;
1583  model->triangles     = NULL;
1584  model->nummaterials  = 0;
1585  model->materials     = NULL;
1586  model->numgroups     = 0;
1587  model->groups        = NULL;
1588  model->position[0]   = 0.0;
1589  model->position[1]   = 0.0;
1590  model->position[2]   = 0.0;
1591
1592  /* make a first pass through the file to get a count of the number
1593     of vertices, normals, texcoords & triangles */
1594  _glmFirstPass(model, file);
1595
1596  /* allocate memory */
1597  model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
1598                     3 * (model->numvertices + 1));
1599
1600  if (model->useColors)                     
1601      model->colors = (osg::UByte4*)malloc(sizeof(osg::UByte4)*(model->numvertices + 1));
1602 
1603  model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) *
1604                      model->numtriangles);
1605  if (model->numnormals) {
1606    model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
1607                      3 * (model->numnormals + 1));
1608  }
1609  if (model->numtexcoords) {
1610    model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
1611                    2 * (model->numtexcoords + 1));
1612  }
1613
1614  /* rewind to beginning of file and read in the data this pass */
1615  rewind(file);
1616
1617  _glmSecondPass(model, file);
1618
1619  /* close the file */
1620  fclose(file);
1621
1622  return model;
1623}
1624
1625/* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to
1626 * a file.
1627 *
1628 * model    - initialized GLMmodel structure
1629 * filename - name of the file to write the Wavefront .OBJ format data to
1630 * mode     - a bitwise or of values describing what is written to the file
1631 *            GLM_NONE     -  render with only vertices
1632 *            GLM_FLAT     -  render with facet normals
1633 *            GLM_SMOOTH   -  render with vertex normals
1634 *            GLM_TEXTURE  -  render with texture coords
1635 *            GLM_COLOR    -  render with colors (color material)
1636 *            GLM_MATERIAL -  render with materials
1637 *            GLM_COLOR and GLM_MATERIAL should not both be specified. 
1638 *            GLM_FLAT and GLM_SMOOTH should not both be specified. 
1639 */
1640GLvoid
1641glmWriteOBJ(GLMmodel* model, char* filename, unsigned int mode)
1642{
1643  unsigned int    i;
1644  FILE*     file;
1645  GLMgroup* group;
1646
1647  assert(model);
1648
1649  /* do a bit of warning */
1650  if (mode & GLM_FLAT && !model->facetnorms) {
1651    printf("glmWriteOBJ() warning: flat normal output requested "
1652       "with no facet normals defined.\n");
1653    mode &= ~GLM_FLAT;
1654  }
1655  if (mode & GLM_SMOOTH && !model->normals) {
1656    printf("glmWriteOBJ() warning: smooth normal output requested "
1657       "with no normals defined.\n");
1658    mode &= ~GLM_SMOOTH;
1659  }
1660  if (mode & GLM_TEXTURE && !model->texcoords) {
1661    printf("glmWriteOBJ() warning: texture coordinate output requested "
1662       "with no texture coordinates defined.\n");
1663    mode &= ~GLM_TEXTURE;
1664  }
1665  if (mode & GLM_FLAT && mode & GLM_SMOOTH) {
1666    printf("glmWriteOBJ() warning: flat normal output requested "
1667       "and smooth normal output requested (using smooth).\n");
1668    mode &= ~GLM_FLAT;
1669  }
1670
1671  /* open the file */
1672  file = fopen(filename, "w");
1673  if (!file) {
1674    fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n",
1675        filename);
1676    //exit(1);
1677    return;
1678  }
1679
1680  /* spit out a header */
1681  fprintf(file, "#  \n");
1682  fprintf(file, "#  Wavefront OBJ generated by GLM library\n");
1683  fprintf(file, "#  \n");
1684  fprintf(file, "#  GLM library copyright (C) 1997 by Nate Robins\n");
1685  fprintf(file, "#  email: ndr@pobox.com\n");
1686  fprintf(file, "#  www:   http://www.pobox.com/~ndr\n");
1687  fprintf(file, "#  \n");
1688
1689  if (mode & GLM_MATERIAL && model->mtllibname) {
1690    fprintf(file, "\nmtllib %s\n\n", model->mtllibname);
1691    _glmWriteMTL(model, filename, model->mtllibname);
1692  }
1693
1694  /* spit out the vertices */
1695  fprintf(file, "\n");
1696  fprintf(file, "# %d vertices\n", model->numvertices);
1697  for (i = 1; i <= model->numvertices; i++) {
1698    fprintf(file, "v %f %f %f\n",
1699        model->vertices[3 * i + 0],
1700        model->vertices[3 * i + 1],
1701        model->vertices[3 * i + 2]);
1702  }
1703
1704  /* spit out the smooth/flat normals */
1705  if (mode & GLM_SMOOTH) {
1706    fprintf(file, "\n");
1707    fprintf(file, "# %d normals\n", model->numnormals);
1708    for (i = 1; i <= model->numnormals; i++) {
1709      fprintf(file, "vn %f %f %f\n",
1710          model->normals[3 * i + 0],
1711          model->normals[3 * i + 1],
1712          model->normals[3 * i + 2]);
1713    }
1714  } else if (mode & GLM_FLAT) {
1715    fprintf(file, "\n");
1716    fprintf(file, "# %d normals\n", model->numfacetnorms);
1717    for (i = 1; i <= model->numnormals; i++) {
1718      fprintf(file, "vn %f %f %f\n",
1719          model->facetnorms[3 * i + 0],
1720          model->facetnorms[3 * i + 1],
1721          model->facetnorms[3 * i + 2]);
1722    }
1723  }
1724
1725  /* spit out the texture coordinates */
1726  if (mode & GLM_TEXTURE) {
1727    fprintf(file, "\n");
1728    fprintf(file, "# %d texcoords\n", model->numtexcoords);
1729    for (i = 1; i <= model->numtexcoords; i++) {
1730      fprintf(file, "vt %f %f\n",
1731          model->texcoords[2 * i + 0],
1732          model->texcoords[2 * i + 1]);
1733    }
1734  }
1735
1736  fprintf(file, "\n");
1737  fprintf(file, "# %d groups\n", model->numgroups);
1738  fprintf(file, "# %d faces (triangles)\n", model->numtriangles);
1739  fprintf(file, "\n");
1740
1741  group = model->groups;
1742  while(group) {
1743    fprintf(file, "g %s\n", group->name);
1744    if (mode & GLM_MATERIAL)
1745      fprintf(file, "usemtl %s\n", model->materials[group->material].name);
1746    for (i = 0; i < group->numtriangles; i++) {
1747      if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) {
1748    fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n",
1749        T(group->triangles[i]).vindices[0],
1750        T(group->triangles[i]).nindices[0],
1751        T(group->triangles[i]).tindices[0],
1752        T(group->triangles[i]).vindices[1],
1753        T(group->triangles[i]).nindices[1],
1754        T(group->triangles[i]).tindices[1],
1755        T(group->triangles[i]).vindices[2],
1756        T(group->triangles[i]).nindices[2],
1757        T(group->triangles[i]).tindices[2]);
1758      } else if (mode & GLM_FLAT && mode & GLM_TEXTURE) {
1759    fprintf(file, "f %d/%d %d/%d %d/%d\n",
1760        T(group->triangles[i]).vindices[0],
1761        T(group->triangles[i]).findex,
1762        T(group->triangles[i]).vindices[1],
1763        T(group->triangles[i]).findex,
1764        T(group->triangles[i]).vindices[2],
1765        T(group->triangles[i]).findex);
1766      } else if (mode & GLM_TEXTURE) {
1767    fprintf(file, "f %d/%d %d/%d %d/%d\n",
1768        T(group->triangles[i]).vindices[0],
1769        T(group->triangles[i]).tindices[0],
1770        T(group->triangles[i]).vindices[1],
1771        T(group->triangles[i]).tindices[1],
1772        T(group->triangles[i]).vindices[2],
1773        T(group->triangles[i]).tindices[2]);
1774      } else if (mode & GLM_SMOOTH) {
1775    fprintf(file, "f %d//%d %d//%d %d//%d\n",
1776        T(group->triangles[i]).vindices[0],
1777        T(group->triangles[i]).nindices[0],
1778        T(group->triangles[i]).vindices[1],
1779        T(group->triangles[i]).nindices[1],
1780        T(group->triangles[i]).vindices[2],
1781        T(group->triangles[i]).nindices[2]);
1782      } else if (mode & GLM_FLAT) {
1783    fprintf(file, "f %d//%d %d//%d %d//%d\n",
1784        T(group->triangles[i]).vindices[0],
1785        T(group->triangles[i]).findex,
1786        T(group->triangles[i]).vindices[1],
1787        T(group->triangles[i]).findex,
1788        T(group->triangles[i]).vindices[2],
1789        T(group->triangles[i]).findex);
1790      } else {
1791    fprintf(file, "f %d %d %d\n",
1792        T(group->triangles[i]).vindices[0],
1793        T(group->triangles[i]).vindices[1],
1794        T(group->triangles[i]).vindices[2]);
1795      }
1796    }
1797    fprintf(file, "\n");
1798    group = group->next;
1799  }
1800
1801  fclose(file);
1802}
1803
1804/* glmWeld: eliminate (weld) vectors that are within an epsilon of
1805 * each other.
1806 *
1807 * model      - initialized GLMmodel structure
1808 * epsilon    - maximum difference between vertices
1809 *              ( 0.00001 is a good start for a unitized model)
1810 *
1811 */
1812GLvoid
1813glmWeld(GLMmodel* model, GLfloat epsilon)
1814{
1815  GLfloat* vectors;
1816  GLfloat* copies;
1817  unsigned int   numvectors;
1818  unsigned int   i;
1819
1820  /* vertices */
1821  numvectors = model->numvertices;
1822  vectors    = model->vertices;
1823  copies = _glmWeldVectors(vectors, &numvectors, epsilon);
1824
1825  printf("glmWeld(): %d redundant vertices.\n",
1826     model->numvertices - numvectors - 1);
1827
1828  for (i = 0; i < model->numtriangles; i++) {
1829    T(i).vindices[0] = (unsigned int)vectors[3 * T(i).vindices[0] + 0];
1830    T(i).vindices[1] = (unsigned int)vectors[3 * T(i).vindices[1] + 0];
1831    T(i).vindices[2] = (unsigned int)vectors[3 * T(i).vindices[2] + 0];
1832  }
1833
1834  /* free space for old vertices */
1835  free(vectors);
1836
1837  /* allocate space for the new vertices */
1838  model->numvertices = numvectors;
1839  model->vertices = (GLfloat*)malloc(sizeof(GLfloat) *
1840                     3 * (model->numvertices + 1));
1841
1842  /* copy the optimized vertices into the actual vertex list */
1843  for (i = 1; i <= model->numvertices; i++) {
1844    model->vertices[3 * i + 0] = copies[3 * i + 0];
1845    model->vertices[3 * i + 1] = copies[3 * i + 1];
1846    model->vertices[3 * i + 2] = copies[3 * i + 2];
1847  }
1848
1849  free(copies);
1850}
1851
1852
1853#if 0
1854  /* normals */
1855  if (model->numnormals) {
1856  numvectors = model->numnormals;
1857  vectors    = model->normals;
1858  copies = _glmOptimizeVectors(vectors, &numvectors);
1859
1860  printf("glmOptimize(): %d redundant normals.\n",
1861     model->numnormals - numvectors);
1862
1863  for (i = 0; i < model->numtriangles; i++) {
1864    T(i).nindices[0] = (unsigned int)vectors[3 * T(i).nindices[0] + 0];
1865    T(i).nindices[1] = (unsigned int)vectors[3 * T(i).nindices[1] + 0];
1866    T(i).nindices[2] = (unsigned int)vectors[3 * T(i).nindices[2] + 0];
1867  }
1868
1869  /* free space for old normals */
1870  free(vectors);
1871
1872  /* allocate space for the new normals */
1873  model->numnormals = numvectors;
1874  model->normals = (GLfloat*)malloc(sizeof(GLfloat) *
1875                    3 * (model->numnormals + 1));
1876
1877  /* copy the optimized vertices into the actual vertex list */
1878  for (i = 1; i <= model->numnormals; i++) {
1879    model->normals[3 * i + 0] = copies[3 * i + 0];
1880    model->normals[3 * i + 1] = copies[3 * i + 1];
1881    model->normals[3 * i + 2] = copies[3 * i + 2];
1882  }
1883
1884  free(copies);
1885  }
1886
1887  /* texcoords */
1888  if (model->numtexcoords) {
1889  numvectors = model->numtexcoords;
1890  vectors    = model->texcoords;
1891  copies = _glmOptimizeVectors(vectors, &numvectors);
1892
1893  printf("glmOptimize(): %d redundant texcoords.\n",
1894     model->numtexcoords - numvectors);
1895
1896  for (i = 0; i < model->numtriangles; i++) {
1897    for (j = 0; j < 3; j++) {
1898      T(i).tindices[j] = (unsigned int)vectors[3 * T(i).tindices[j] + 0];
1899    }
1900  }
1901
1902  /* free space for old texcoords */
1903  free(vectors);
1904
1905  /* allocate space for the new texcoords */
1906  model->numtexcoords = numvectors;
1907  model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) *
1908                      2 * (model->numtexcoords + 1));
1909
1910  /* copy the optimized vertices into the actual vertex list */
1911  for (i = 1; i <= model->numtexcoords; i++) {
1912    model->texcoords[2 * i + 0] = copies[2 * i + 0];
1913    model->texcoords[2 * i + 1] = copies[2 * i + 1];
1914  }
1915
1916  free(copies);
1917  }
1918#endif
1919
1920#if 0
1921  /* look for unused vertices */
1922  /* look for unused normals */
1923  /* look for unused texcoords */
1924  for (i = 1; i <= model->numvertices; i++) {
1925    for (j = 0; j < model->numtriangles; i++) {
1926      if (T(j).vindices[0] == i ||
1927      T(j).vindices[1] == i ||
1928      T(j).vindices[1] == i)
1929    break;
1930    }
1931  }
1932#endif
Note: See TracBrowser for help on using the browser.