]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
8be1c426a6abff83d0425f47d555bf5250127426
[flightgear.git] / src / Objects / obj.cxx
1 // obj.cxx -- routines to handle "sorta" WaveFront .obj format files.
2 //
3 // Written by Curtis Olson, started October 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #ifdef FG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34
35 // #if defined ( __sun__ )
36 // extern "C" void *memmove(void *, const void *, size_t);
37 // extern "C" void *memset(void *, int, size_t);
38 // #endif
39
40 #include <simgear/compiler.h>
41 #include <simgear/io/sg_binobj.hxx>
42
43 #include STL_STRING
44 #include <map>                  // STL
45 #include <vector>               // STL
46 #include <ctype.h>              // isdigit()
47
48 #include <simgear/constants.h>
49 #include <simgear/debug/logstream.hxx>
50 #include <simgear/math/point3d.hxx>
51 #include <simgear/math/polar3d.hxx>
52 #include <simgear/math/sg_geodesy.hxx>
53 #include <simgear/math/sg_random.h>
54 #include <simgear/misc/fgstream.hxx>
55 #include <simgear/misc/stopwatch.hxx>
56 #include <simgear/misc/texcoord.hxx>
57
58 #include <Main/globals.hxx>
59 #include <Scenery/tileentry.hxx>
60
61 #include "matlib.hxx"
62 #include "obj.hxx"
63
64 FG_USING_STD(string);
65 FG_USING_STD(vector);
66
67
68 typedef vector < int > int_list;
69 typedef int_list::iterator int_list_iterator;
70 typedef int_list::const_iterator int_point_list_iterator;
71
72
73 static double normals[FG_MAX_NODES][3];
74 static double tex_coords[FG_MAX_NODES*3][3];
75
76
77 #define FG_TEX_CONSTANT 69.0
78
79 // Calculate texture coordinates for a given point.
80 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
81     Point3D cp;
82     Point3D pp;
83     // double tmplon, tmplat;
84
85     // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
86     // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
87
88     cp = Point3D( node[0] + ref.x(),
89                   node[1] + ref.y(),
90                   node[2] + ref.z() );
91
92     pp = sgCartToPolar3d(cp);
93
94     // tmplon = pp.lon() * RAD_TO_DEG;
95     // tmplat = pp.lat() * RAD_TO_DEG;
96     // cout << tmplon << " " << tmplat << endl;
97
98     pp.setx( fmod(RAD_TO_DEG * FG_TEX_CONSTANT * pp.x(), 11.0) );
99     pp.sety( fmod(RAD_TO_DEG * FG_TEX_CONSTANT * pp.y(), 11.0) );
100
101     if ( pp.x() < 0.0 ) {
102         pp.setx( pp.x() + 11.0 );
103     }
104
105     if ( pp.y() < 0.0 ) {
106         pp.sety( pp.y() + 11.0 );
107     }
108
109     // cout << pp << endl;
110
111     return(pp);
112 }
113
114
115 // Generate a generic ocean tile on the fly
116 ssgBranch *fgGenTile( const string& path, FGTileEntry *t) {
117     FGNewMat *newmat;
118
119     ssgSimpleState *state = NULL;
120
121     ssgBranch *tile = new ssgBranch () ;
122     tile -> setName ( (char *)path.c_str() ) ;
123
124     double tex_width = 1000.0;
125     // double tex_height;
126
127     // find Ocean material in the properties list
128     newmat = material_lib.find( "Ocean" );
129     if ( newmat != NULL ) {
130         // set the texture width and height values for this
131         // material
132         tex_width = newmat->get_xsize();
133         // tex_height = newmat->get_ysize();
134         
135         // set ssgState
136         state = newmat->get_state();
137     } else {
138         FG_LOG( FG_TERRAIN, FG_ALERT, 
139                 "Ack! unknown usemtl name = " << "Ocean" 
140                 << " in " << path );
141     }
142
143     // Calculate center point
144     SGBucket b = t->tile_bucket;
145     double clon = b.get_center_lon();
146     double clat = b.get_center_lat();
147     double height = b.get_height();
148     double width = b.get_width();
149
150     Point3D center = sgGeodToCart(Point3D(clon*DEG_TO_RAD,clat*DEG_TO_RAD,0.0));
151     t->center = center;
152     // cout << "center = " << center << endl;;
153     
154     // Caculate corner vertices
155     Point3D geod[4];
156     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
157     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
158     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
159     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
160
161     Point3D rad[4];
162     int i;
163     for ( i = 0; i < 4; ++i ) {
164         rad[i] = Point3D( geod[i].x() * DEG_TO_RAD, geod[i].y() * DEG_TO_RAD,
165                           geod[i].z() );
166     }
167
168     Point3D cart[4], rel[4];
169     t->nodes.clear();
170     for ( i = 0; i < 4; ++i ) {
171         cart[i] = sgGeodToCart(rad[i]);
172         rel[i] = cart[i] - center;
173         t->nodes.push_back( rel[i] );
174         // cout << "corner " << i << " = " << cart[i] << endl;
175     }
176
177     t->ncount = 4;
178
179     // Calculate bounding radius
180     t->bounding_radius = center.distance3D( cart[0] );
181     // cout << "bounding radius = " << t->bounding_radius << endl;
182
183     // Calculate normals
184     Point3D normals[4];
185     for ( i = 0; i < 4; ++i ) {
186         normals[i] = cart[i];
187         double length = normals[i].distance3D( Point3D(0.0) );
188         normals[i] /= length;
189         // cout << "normal = " << normals[i] << endl;
190     }
191
192     // Calculate texture coordinates
193     point_list geod_nodes;
194     geod_nodes.clear();
195     for ( i = 0; i < 4; ++i ) {
196         geod_nodes.push_back( geod[i] );
197     }
198     int_list rectangle;
199     rectangle.clear();
200     for ( i = 0; i < 4; ++i ) {
201         rectangle.push_back( i );
202     }
203     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
204                                        1000.0 / tex_width );
205
206     // Allocate ssg structure
207     ssgVertexArray   *vl = new ssgVertexArray( 4 );
208     ssgNormalArray   *nl = new ssgNormalArray( 4 );
209     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
210     ssgColourArray   *cl = new ssgColourArray( 1 );
211
212     sgVec4 color;
213     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
214     cl->add( color );
215
216     // sgVec3 *vtlist = new sgVec3 [ 4 ];
217     // t->vec3_ptrs.push_back( vtlist );
218     // sgVec3 *vnlist = new sgVec3 [ 4 ];
219     // t->vec3_ptrs.push_back( vnlist );
220     // sgVec2 *tclist = new sgVec2 [ 4 ];
221     // t->vec2_ptrs.push_back( tclist );
222
223     sgVec2 tmp2;
224     sgVec3 tmp3;
225     for ( i = 0; i < 4; ++i ) {
226         sgSetVec3( tmp3, 
227                    rel[i].x(), rel[i].y(), rel[i].z() );
228         vl->add( tmp3 );
229
230         sgSetVec3( tmp3, 
231                    normals[i].x(), normals[i].y(), normals[i].z() );
232         nl->add( tmp3 );
233
234         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
235         tl->add( tmp2 );
236     }
237     
238     ssgLeaf *leaf = 
239         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
240
241     leaf->setState( state );
242
243     tile->addKid( leaf );
244     // if ( globals->get_options()->get_clouds() ) {
245     //    fgGenCloudTile(path, t, tile);
246     // }
247
248     return tile;
249 }
250
251
252 static float fgTriArea( sgVec3 p0, sgVec3 p1, sgVec3 p2 ) {
253     /* 
254        From comp.graph.algorithms FAQ
255        2A(P) = abs(N.(sum_{i=0}^{n-1}(v_i x v_{i+1})))
256      */
257     sgVec3 sum;
258     sgZeroVec3( sum );
259         
260     sgVec3 norm;
261     sgMakeNormal( norm, p0, p1, p2 );
262         
263     float *vv[3];
264     vv[0] = p0;
265     vv[1] = p1;
266     vv[2] = p2;
267         
268     for( int i=0; i<3; i++ ) {
269         int ii = (i+1) % 3;
270         sum[0] += (vv[i][1] * vv[ii][2] - vv[i][2] * vv[ii][1]) ;
271         sum[1] += (vv[i][2] * vv[ii][0] - vv[i][0] * vv[ii][2]) ;
272         sum[2] += (vv[i][0] * vv[ii][1] - vv[i][1] * vv[ii][0]) ;
273     }
274
275     return( sgAbs(sgScalarProductVec3( norm, sum )) * SG_HALF );
276 }
277
278
279 static void random_pt_inside_tri( float *res,
280                                   float *n1, float *n2, float *n3 )
281 {
282     sgVec3 p1, p2, p3;
283
284     double a = sg_random();
285     double b = sg_random();
286     if ( a + b > 1.0 ) {
287         a = 1.0 - a;
288         b = 1.0 - b;
289     }
290     double c = 1 - a - b;
291
292     sgScaleVec3( p1, n1, a );
293     sgScaleVec3( p2, n2, b );
294     sgScaleVec3( p3, n3, c );
295
296     sgAddVec3( res, p1, p2 );
297     sgAddVec3( res, p3 );
298 }
299
300
301 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
302                                        double factor ) {
303     int num = leaf->getNumTriangles();
304     if ( num > 0 ) {
305         short int n1, n2, n3;
306         float *p1, *p2, *p3;
307         sgVec3 result;
308
309         // generate a repeatable random seed
310         p1 = leaf->getVertex( 0 );
311         unsigned int *seed = (unsigned int *)p1;
312         sg_srandom( *seed );
313
314         for ( int i = 0; i < num; ++i ) {
315             leaf->getTriangle( i, &n1, &n2, &n3 );
316             p1 = leaf->getVertex(n1);
317             p2 = leaf->getVertex(n2);
318             p3 = leaf->getVertex(n3);
319             double area = fgTriArea( p1, p2, p3 );
320             double num = area / factor;
321
322             // generate a light point for each unit of area
323             while ( num > 1.0 ) {
324                 random_pt_inside_tri( result, p1, p2, p3 );
325                 lights->add( result );
326                 num -= 1.0;
327             }
328             // for partial units of area, use a zombie door method to
329             // create the proper random chance of a light being created
330             // for this triangle
331             if ( num > 0.0 ) {
332                 if ( sg_random() <= num ) {
333                     // a zombie made it through our door
334                     random_pt_inside_tri( result, p1, p2, p3 );
335                     lights->add( result );
336                 }
337             }
338         }
339     }
340 }
341
342
343 // Load an Ascii obj file
344 static ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
345                                   ssgVertexArray *lights, const bool is_base)
346 {
347     FGNewMat *newmat = NULL;
348     string material;
349     float coverage = -1;
350     Point3D pp;
351     // sgVec3 approx_normal;
352     // double normal[3], scale = 0.0;
353     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
354     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
355     // GLint display_list = 0;
356     int shading;
357     bool in_faces = false;
358     int vncount, vtcount;
359     int n1 = 0, n2 = 0, n3 = 0;
360     int tex;
361     // int last1 = 0, last2 = 0;
362     bool odd = false;
363     point_list nodes;
364     Point3D node;
365     Point3D center;
366     double scenery_version = 0.0;
367     double tex_width = 1000.0, tex_height = 1000.0;
368     bool shared_done = false;
369     int_list fan_vertices;
370     int_list fan_tex_coords;
371     int i;
372     ssgSimpleState *state = NULL;
373     sgVec3 *vtlist, *vnlist;
374     sgVec2 *tclist;
375
376     ssgBranch *tile = new ssgBranch () ;
377
378     tile -> setName ( (char *)path.c_str() ) ;
379
380     // Attempt to open "path.gz" or "path"
381     fg_gzifstream in( path );
382     if ( ! in.is_open() ) {
383         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << path );
384         FG_LOG( FG_TERRAIN, FG_ALERT, "default to ocean tile: " << path );
385
386         return NULL;
387     }
388
389     shading = globals->get_options()->get_shading();
390
391     if ( is_base ) {
392         t->ncount = 0;
393     }
394     vncount = 0;
395     vtcount = 0;
396     if ( is_base ) {
397         t->bounding_radius = 0.0;
398     }
399     center = t->center;
400
401     StopWatch stopwatch;
402     stopwatch.start();
403
404     // ignore initial comments and blank lines. (priming the pump)
405     // in >> skipcomment;
406     // string line;
407
408     string token;
409     char c;
410
411 #ifdef __MWERKS__
412     while ( in.get(c) && c  != '\0' ) {
413         in.putback(c);
414 #else
415     while ( ! in.eof() ) {
416 #endif
417
418 #if defined( macintosh ) || defined( _MSC_VER )
419         in >> ::skipws;
420 #else
421         in >> skipws;
422 #endif
423
424         if ( in.get( c ) && c == '#' ) {
425             // process a comment line
426
427             // getline( in, line );
428             // cout << "comment = " << line << endl;
429
430             in >> token;
431
432             if ( token == "Version" ) {
433                 // read scenery versions number
434                 in >> scenery_version;
435                 // cout << "scenery_version = " << scenery_version << endl;
436                 if ( scenery_version > 0.4 ) {
437                     FG_LOG( FG_TERRAIN, FG_ALERT, 
438                             "\nYou are attempting to load a tile format that\n"
439                             << "is newer than this version of flightgear can\n"
440                             << "handle.  You should upgrade your copy of\n"
441                             << "FlightGear to the newest version.  For\n"
442                             << "details, please see:\n"
443                             << "\n    http://www.flightgear.org\n" );
444                     exit(-1);
445                 }
446             } else if ( token == "gbs" ) {
447                 // reference point (center offset)
448                 if ( is_base ) {
449                     in >> t->center >> t->bounding_radius;
450                 } else {
451                     Point3D junk1;
452                     double junk2;
453                     in >> junk1 >> junk2;
454                 }
455                 center = t->center;
456                 // cout << "center = " << center 
457                 //      << " radius = " << t->bounding_radius << endl;
458             } else if ( token == "bs" ) {
459                 // reference point (center offset)
460                 // (skip past this)
461                 Point3D junk1;
462                 double junk2;
463                 in >> junk1 >> junk2;
464             } else if ( token == "usemtl" ) {
465                 // material property specification
466
467                 // if first usemtl with shared_done = false, then set
468                 // shared_done true and build the ssg shared lists
469                 if ( ! shared_done ) {
470                     // sanity check
471                     if ( (int)nodes.size() != vncount ) {
472                         FG_LOG( FG_TERRAIN, FG_ALERT, 
473                                 "Tile has mismatched nodes = " << nodes.size()
474                                 << " and normals = " << vncount << " : " 
475                                 << path );
476                         // exit(-1);
477                     }
478                     shared_done = true;
479
480                     vtlist = new sgVec3 [ nodes.size() ];
481                     t->vec3_ptrs.push_back( vtlist );
482                     vnlist = new sgVec3 [ vncount ];
483                     t->vec3_ptrs.push_back( vnlist );
484                     tclist = new sgVec2 [ vtcount ];
485                     t->vec2_ptrs.push_back( tclist );
486
487                     for ( i = 0; i < (int)nodes.size(); ++i ) {
488                         sgSetVec3( vtlist[i], 
489                                    nodes[i][0], nodes[i][1], nodes[i][2] );
490                     }
491                     for ( i = 0; i < vncount; ++i ) {
492                         sgSetVec3( vnlist[i], 
493                                    normals[i][0], 
494                                    normals[i][1],
495                                    normals[i][2] );
496                     }
497                     for ( i = 0; i < vtcount; ++i ) {
498                         sgSetVec2( tclist[i],
499                                    tex_coords[i][0],
500                                    tex_coords[i][1] );
501                     }
502                 }
503
504                 // display_list = xglGenLists(1);
505                 // xglNewList(display_list, GL_COMPILE);
506                 // printf("xglGenLists(); xglNewList();\n");
507                 in_faces = false;
508
509                 // scan the material line
510                 in >> material;
511                 
512                 // find this material in the properties list
513
514                 newmat = material_lib.find( material );
515                 if ( newmat == NULL ) {
516                     // see if this is an on the fly texture
517                     string file = path;
518                     int pos = file.rfind( "/" );
519                     file = file.substr( 0, pos );
520                     cout << "current file = " << file << endl;
521                     file += "/";
522                     file += material;
523                     cout << "current file = " << file << endl;
524                     if ( ! material_lib.add_item( file ) ) {
525                         FG_LOG( FG_TERRAIN, FG_ALERT, 
526                                 "Ack! unknown usemtl name = " << material 
527                                 << " in " << path );
528                     } else {
529                         // locate our newly created material
530                         newmat = material_lib.find( material );
531                         if ( newmat == NULL ) {
532                             FG_LOG( FG_TERRAIN, FG_ALERT, 
533                                     "Ack! bad on the fly materia create = "
534                                     << material << " in " << path );
535                         }
536                     }
537                 }
538
539                 if ( newmat != NULL ) {
540                     // set the texture width and height values for this
541                     // material
542                     tex_width = newmat->get_xsize();
543                     tex_height = newmat->get_ysize();
544                     state = newmat->get_state();
545                     coverage = newmat->get_light_coverage();
546                     // cout << "(w) = " << tex_width << " (h) = " 
547                     //      << tex_width << endl;
548                 } else {
549                     coverage = -1;
550                 }
551             } else {
552                 // unknown comment, just gobble the input until the
553                 // end of line
554
555                 in >> skipeol;
556             }
557         } else {
558             in.putback( c );
559         
560             in >> token;
561
562             // cout << "token = " << token << endl;
563
564             if ( token == "vn" ) {
565                 // vertex normal
566                 if ( vncount < FG_MAX_NODES ) {
567                     in >> normals[vncount][0]
568                        >> normals[vncount][1]
569                        >> normals[vncount][2];
570                     vncount++;
571                 } else {
572                     FG_LOG( FG_TERRAIN, FG_ALERT, 
573                             "Read too many vertex normals in " << path 
574                             << " ... dying :-(" );
575                     exit(-1);
576                 }
577             } else if ( token == "vt" ) {
578                 // vertex texture coordinate
579                 if ( vtcount < FG_MAX_NODES*3 ) {
580                     in >> tex_coords[vtcount][0]
581                        >> tex_coords[vtcount][1];
582                     vtcount++;
583                 } else {
584                     FG_LOG( FG_TERRAIN, FG_ALERT, 
585                             "Read too many vertex texture coords in " << path
586                             << " ... dying :-("
587                             );
588                     exit(-1);
589                 }
590             } else if ( token == "v" ) {
591                 // node (vertex)
592                 if ( t->ncount < FG_MAX_NODES ) {
593                     /* in >> nodes[t->ncount][0]
594                        >> nodes[t->ncount][1]
595                        >> nodes[t->ncount][2]; */
596                     in >> node;
597                     nodes.push_back(node);
598                     if ( is_base ) {
599                         t->ncount++;
600                     }
601                 } else {
602                     FG_LOG( FG_TERRAIN, FG_ALERT, 
603                             "Read too many nodes in " << path 
604                             << " ... dying :-(");
605                     exit(-1);
606                 }
607             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
608                 // triangle fan, strip, or individual face
609                 // FG_LOG( FG_TERRAIN, FG_INFO, "new fan or strip");
610
611                 fan_vertices.clear();
612                 fan_tex_coords.clear();
613                 odd = true;
614
615                 // xglBegin(GL_TRIANGLE_FAN);
616
617                 in >> n1;
618                 fan_vertices.push_back( n1 );
619                 // xglNormal3dv(normals[n1]);
620                 if ( in.get( c ) && c == '/' ) {
621                     in >> tex;
622                     fan_tex_coords.push_back( tex );
623                     if ( scenery_version >= 0.4 ) {
624                         if ( tex_width > 0 ) {
625                             tclist[tex][0] *= (1000.0 / tex_width);
626                         }
627                         if ( tex_height > 0 ) {
628                             tclist[tex][1] *= (1000.0 / tex_height);
629                         }
630                     }
631                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
632                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
633                 } else {
634                     in.putback( c );
635                     pp = local_calc_tex_coords(nodes[n1], center);
636                 }
637                 // xglTexCoord2f(pp.x(), pp.y());
638                 // xglVertex3dv(nodes[n1].get_n());
639
640                 in >> n2;
641                 fan_vertices.push_back( n2 );
642                 // xglNormal3dv(normals[n2]);
643                 if ( in.get( c ) && c == '/' ) {
644                     in >> tex;
645                     fan_tex_coords.push_back( tex );
646                     if ( scenery_version >= 0.4 ) {
647                         if ( tex_width > 0 ) {
648                             tclist[tex][0] *= (1000.0 / tex_width);
649                         }
650                         if ( tex_height > 0 ) {
651                             tclist[tex][1] *= (1000.0 / tex_height);
652                         }
653                     }
654                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
655                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
656                 } else {
657                     in.putback( c );
658                     pp = local_calc_tex_coords(nodes[n2], center);
659                 }
660                 // xglTexCoord2f(pp.x(), pp.y());
661                 // xglVertex3dv(nodes[n2].get_n());
662                 
663                 // read all subsequent numbers until next thing isn't a number
664                 while ( true ) {
665 #if defined( macintosh ) || defined( _MSC_VER )
666                     in >> ::skipws;
667 #else
668                     in >> skipws;
669 #endif
670
671                     char c;
672                     in.get(c);
673                     in.putback(c);
674                     if ( ! isdigit(c) || in.eof() ) {
675                         break;
676                     }
677
678                     in >> n3;
679                     fan_vertices.push_back( n3 );
680                     // cout << "  triangle = " 
681                     //      << n1 << "," << n2 << "," << n3 
682                     //      << endl;
683                     // xglNormal3dv(normals[n3]);
684                     if ( in.get( c ) && c == '/' ) {
685                         in >> tex;
686                         fan_tex_coords.push_back( tex );
687                         if ( scenery_version >= 0.4 ) {
688                             if ( tex_width > 0 ) {
689                                 tclist[tex][0] *= (1000.0 / tex_width);
690                             }
691                             if ( tex_height > 0 ) {
692                                 tclist[tex][1] *= (1000.0 / tex_height);
693                             }
694                         }
695                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
696                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
697                     } else {
698                         in.putback( c );
699                         pp = local_calc_tex_coords(nodes[n3], center);
700                     }
701                     // xglTexCoord2f(pp.x(), pp.y());
702                     // xglVertex3dv(nodes[n3].get_n());
703
704                     if ( (token == "tf") || (token == "f") ) {
705                         // triangle fan
706                         n2 = n3;
707                     } else {
708                         // triangle strip
709                         odd = !odd;
710                         n1 = n2;
711                         n2 = n3;
712                     }
713                 }
714
715                 // xglEnd();
716
717                 // build the ssg entity
718                 int size = (int)fan_vertices.size();
719                 ssgVertexArray   *vl = new ssgVertexArray( size );
720                 ssgNormalArray   *nl = new ssgNormalArray( size );
721                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
722                 ssgColourArray   *cl = new ssgColourArray( 1 );
723
724                 sgVec4 color;
725                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
726                 cl->add( color );
727
728                 sgVec2 tmp2;
729                 sgVec3 tmp3;
730                 for ( i = 0; i < size; ++i ) {
731                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
732                     vl -> add( tmp3 );
733
734                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
735                     nl -> add( tmp3 );
736
737                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
738                     tl -> add( tmp2 );
739                 }
740
741                 ssgLeaf *leaf = NULL;
742                 if ( token == "tf" ) {
743                     // triangle fan
744                     leaf = 
745                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
746                 } else if ( token == "ts" ) {
747                     // triangle strip
748                     leaf = 
749                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
750                 } else if ( token == "f" ) {
751                     // triangle
752                     leaf = 
753                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
754                 }
755                 // leaf->makeDList();
756                 leaf->setState( state );
757
758                 tile->addKid( leaf );
759
760                 if ( is_base ) {
761                     if ( coverage > 0.0 ) {
762                         if ( coverage < 10000.0 ) {
763                             FG_LOG(FG_INPUT, FG_ALERT, "Light coverage is "
764                                    << coverage << ", pushing up to 10000");
765                             coverage = 10000;
766                         }
767                         gen_random_surface_points(leaf, lights, coverage);
768                     }
769                 }
770             } else {
771                 FG_LOG( FG_TERRAIN, FG_WARN, "Unknown token in " 
772                         << path << " = " << token );
773             }
774
775             // eat white space before start of while loop so if we are
776             // done with useful input it is noticed before hand.
777 #if defined( macintosh ) || defined( _MSC_VER )
778             in >> ::skipws;
779 #else
780             in >> skipws;
781 #endif
782         }
783     }
784
785     if ( is_base ) {
786         t->nodes = nodes;
787     }
788
789     stopwatch.stop();
790     FG_LOG( FG_TERRAIN, FG_DEBUG, 
791             "Loaded " << path << " in " 
792             << stopwatch.elapsedSeconds() << " seconds" );
793
794     // Generate a cloud layer above the tiles
795     // if ( globals->get_options()->get_clouds() ) {
796     //          fgGenCloudTile(path, t, tile);
797     // }
798
799     return tile;
800 }
801
802
803 static ssgLeaf *gen_leaf( const string& path,
804                           const GLenum ty, const string& material,
805                           const point_list& nodes, const point_list& normals,
806                           const point_list& texcoords,
807                           const int_list& node_index,
808                           const int_list& tex_index,
809                           const bool calc_lights, ssgVertexArray *lights )
810 {
811     double tex_width = 1000.0, tex_height = 1000.0;
812     ssgSimpleState *state = NULL;
813     float coverage = -1;
814
815     int size = node_index.size();
816     ssgVertexArray   *vl = new ssgVertexArray( size );
817     ssgNormalArray   *nl = new ssgNormalArray( size );
818     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
819     ssgColourArray   *cl = new ssgColourArray( 1 );
820
821     sgVec4 color;
822     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
823     cl->add( color );
824
825     sgVec2 tmp2;
826     sgVec3 tmp3;
827     int i;
828     for ( i = 0; i < size; ++i ) {
829         Point3D node = nodes[ node_index[i] ];
830         sgSetVec3( tmp3, node[0], node[1], node[2] );
831         vl -> add( tmp3 );
832
833         Point3D normal = normals[ node_index[i] ];
834         sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
835         nl -> add( tmp3 );
836
837         Point3D texcoord = texcoords[ tex_index[i] ];
838         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
839         tl -> add( tmp2 );
840     }
841
842     cout << "before leaf create" << endl;
843     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
844     cout << "after leaf create" << endl;
845
846     // lookup the state record
847     cout << "looking up material = " << endl;
848     cout << material << endl;
849     cout << "'" << endl;
850
851     FGNewMat *newmat = material_lib.find( material );
852     if ( newmat == NULL ) {
853         // see if this is an on the fly texture
854         string file = path;
855         int pos = file.rfind( "/" );
856         file = file.substr( 0, pos );
857         cout << "current file = " << file << endl;
858         file += "/";
859         file += material;
860         cout << "current file = " << file << endl;
861         if ( ! material_lib.add_item( file ) ) {
862             FG_LOG( FG_TERRAIN, FG_ALERT, 
863                     "Ack! unknown usemtl name = " << material 
864                     << " in " << path );
865         } else {
866             // locate our newly created material
867             newmat = material_lib.find( material );
868             if ( newmat == NULL ) {
869                 FG_LOG( FG_TERRAIN, FG_ALERT, 
870                         "Ack! bad on the fly materia create = "
871                         << material << " in " << path );
872             }
873         }
874     }
875
876     if ( newmat != NULL ) {
877         // set the texture width and height values for this
878         // material
879         tex_width = newmat->get_xsize();
880         tex_height = newmat->get_ysize();
881         state = newmat->get_state();
882         coverage = newmat->get_light_coverage();
883         // cout << "(w) = " << tex_width << " (h) = " 
884         //      << tex_width << endl;
885     } else {
886         coverage = -1;
887     }
888
889     leaf->setState( state );
890
891     if ( calc_lights ) {
892         if ( coverage > 0.0 ) {
893             if ( coverage < 10000.0 ) {
894                 FG_LOG(FG_INPUT, FG_ALERT, "Light coverage is "
895                        << coverage << ", pushing up to 10000");
896                 coverage = 10000;
897             }
898             gen_random_surface_points(leaf, lights, coverage);
899         }
900     }
901
902     return leaf;
903 }
904
905
906 // Load an Binary obj file
907 static ssgBranch *fgBinObjLoad( const string& path, FGTileEntry *t,
908                                 ssgVertexArray *lights, const bool is_base)
909 {
910     int i;
911
912     Point3D gbs_center;
913     float gbs_radius;
914     
915     point_list offset_nodes; offset_nodes.clear();
916     point_list normals;      normals.clear();
917     point_list texcoords;    texcoords.clear();
918
919     // allocate and initialize triangle group structures
920     group_list tris_v;   group_list tris_tc;   string_list tri_materials;
921     tris_v.clear();      tris_tc.clear();      tri_materials.clear();
922
923     group_list strips_v; group_list strips_tc; string_list strip_materials;
924     strips_v.clear();    strips_tc.clear();    strip_materials.clear();
925
926     group_list fans_v;   group_list fans_tc;   string_list fan_materials;
927     fans_v.clear();      fans_tc.clear();      fan_materials.clear();
928
929     bool result = sgReadBinObj( path, gbs_center, &gbs_radius, 
930                                 offset_nodes, normals, texcoords, 
931                                 tris_v, tris_tc, tri_materials,
932                                 strips_v, strips_tc, strip_materials, 
933                                 fans_v, fans_tc, fan_materials );
934
935     if ( !result ) {
936         return NULL;
937     }
938
939     cout << "fans size = " << fans_v.size() << " fan_mats size = " <<
940         fan_materials.size() << endl;
941
942     ssgBranch *object = new ssgBranch();
943     object->setName( (char *)path.c_str() );
944    
945     if ( is_base && t != NULL ) {
946         // reference point (center offset/bounding sphere)
947         t->center = gbs_center;
948         t->bounding_radius = gbs_radius;
949     }
950
951     // generate triangles
952     for ( i = 0; i < (int)tris_v.size(); ++i ) {
953         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
954                                   offset_nodes, normals, texcoords,
955                                   tris_v[i], tris_tc[i],
956                                   is_base, lights );
957
958         object->addKid( leaf );
959     }
960
961     // generate strips
962     for ( i = 0; i < (int)strips_v.size(); ++i ) {
963         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
964                                   offset_nodes, normals, texcoords,
965                                   strips_v[i], strips_tc[i],
966                                   is_base, lights );
967
968         object->addKid( leaf );
969     }
970
971     // generate fans
972     for ( i = 0; i < (int)fans_v.size(); ++i ) {
973         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
974                                   offset_nodes, normals, texcoords,
975                                   fans_v[i], fans_tc[i],
976                                   is_base, lights );
977
978         object->addKid( leaf );
979     }
980
981     return object;
982 }
983
984
985 // Load an obj file
986 ssgBranch *fgObjLoad( const string& path, FGTileEntry *t,
987                       ssgVertexArray *lights, const bool is_base)
988 {
989     ssgBranch *result;
990
991     // try loading binary format
992     result = fgBinObjLoad( path, t, lights, is_base );
993     if ( result == NULL ) {
994         // next try the older ascii format
995         result = fgAsciiObjLoad( path, t, lights, is_base );
996         if ( result == NULL ) {
997             // default to an ocean tile
998             result = fgGenTile( path, t );
999         }
1000     }
1001
1002     return result;
1003 }