]> git.mxchange.org Git - flightgear.git/blob - src/Objects/obj.cxx
Some various massaging and clean ups of initialization code.
[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 SG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #include <stdio.h>
33 #include <string.h>
34
35 #include <simgear/compiler.h>
36 #include <simgear/sg_inlines.h>
37 #include <simgear/io/sg_binobj.hxx>
38
39 #include STL_STRING
40 #include <map>                  // STL
41 #include <vector>               // STL
42 #include <ctype.h>              // isdigit()
43
44 #include <simgear/constants.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/math/point3d.hxx>
47 #include <simgear/math/polar3d.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/vector.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/misc/stopwatch.hxx>
53 #include <simgear/misc/texcoord.hxx>
54
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57 #include <Time/light.hxx>
58 #include <Scenery/tileentry.hxx>
59
60 #include "newmat.hxx"
61 #include "matlib.hxx"
62 #include "pt_lights.hxx"
63 #include "obj.hxx"
64
65 SG_USING_STD(string);
66 SG_USING_STD(vector);
67
68
69 typedef vector < int > int_list;
70 typedef int_list::iterator int_list_iterator;
71 typedef int_list::const_iterator int_point_list_iterator;
72
73
74 static double normals[FG_MAX_NODES][3];
75 static double tex_coords[FG_MAX_NODES*3][3];
76
77 // not used because plib branches don't honor call backs.
78 static int
79 runway_lights_pretrav (ssgEntity * e, int mask)
80 {
81                                 // Turn on lights only at night
82     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
83     return int((sun_angle > 90.0) ||
84                (fgGetDouble("/environment/visibility-m") < 5000.0));
85 }
86
87
88 #define FG_TEX_CONSTANT 69.0
89
90 // Calculate texture coordinates for a given point.
91 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
92     Point3D cp;
93     Point3D pp;
94     // double tmplon, tmplat;
95
96     // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
97     // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
98
99     cp = Point3D( node[0] + ref.x(),
100                   node[1] + ref.y(),
101                   node[2] + ref.z() );
102
103     pp = sgCartToPolar3d(cp);
104
105     // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
106     // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
107     // cout << tmplon << " " << tmplat << endl;
108
109     pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
110     pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
111
112     if ( pp.x() < 0.0 ) {
113         pp.setx( pp.x() + 11.0 );
114     }
115
116     if ( pp.y() < 0.0 ) {
117         pp.sety( pp.y() + 11.0 );
118     }
119
120     // cout << pp << endl;
121
122     return(pp);
123 }
124
125
126 // Generate an ocean tile
127 bool fgGenTile( const string& path, SGBucket b,
128                       Point3D *center,
129                       double *bounding_radius,
130                       ssgBranch* geometry )
131 {
132     FGNewMat *newmat;
133
134     ssgSimpleState *state = NULL;
135
136     geometry -> setName ( (char *)path.c_str() ) ;
137
138     double tex_width = 1000.0;
139     // double tex_height;
140
141     // find Ocean material in the properties list
142     newmat = material_lib.find( "Ocean" );
143     if ( newmat != NULL ) {
144         // set the texture width and height values for this
145         // material
146         tex_width = newmat->get_xsize();
147         // tex_height = newmat->get_ysize();
148         
149         // set ssgState
150         state = newmat->get_state();
151     } else {
152         SG_LOG( SG_TERRAIN, SG_ALERT, 
153                 "Ack! unknown usemtl name = " << "Ocean" 
154                 << " in " << path );
155     }
156
157     // Calculate center point
158     double clon = b.get_center_lon();
159     double clat = b.get_center_lat();
160     double height = b.get_height();
161     double width = b.get_width();
162
163     *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
164                                     clat*SGD_DEGREES_TO_RADIANS,
165                                     0.0) );
166     // cout << "center = " << center << endl;;
167     
168     // Caculate corner vertices
169     Point3D geod[4];
170     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
171     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
172     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
173     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
174
175     Point3D rad[4];
176     int i;
177     for ( i = 0; i < 4; ++i ) {
178         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
179                           geod[i].y() * SGD_DEGREES_TO_RADIANS,
180                           geod[i].z() );
181     }
182
183     Point3D cart[4], rel[4];
184     for ( i = 0; i < 4; ++i ) {
185         cart[i] = sgGeodToCart(rad[i]);
186         rel[i] = cart[i] - *center;
187         // cout << "corner " << i << " = " << cart[i] << endl;
188     }
189
190     // Calculate bounding radius
191     *bounding_radius = center->distance3D( cart[0] );
192     // cout << "bounding radius = " << t->bounding_radius << endl;
193
194     // Calculate normals
195     Point3D normals[4];
196     for ( i = 0; i < 4; ++i ) {
197         double length = cart[i].distance3D( Point3D(0.0) );
198         normals[i] = cart[i] / length;
199         // cout << "normal = " << normals[i] << endl;
200     }
201
202     // Calculate texture coordinates
203     point_list geod_nodes;
204     geod_nodes.clear();
205     geod_nodes.reserve(4);
206     int_list rectangle;
207     rectangle.clear();
208     rectangle.reserve(4);
209     for ( i = 0; i < 4; ++i ) {
210         geod_nodes.push_back( geod[i] );
211         rectangle.push_back( i );
212     }
213     point_list texs = calc_tex_coords( b, geod_nodes, rectangle, 
214                                        1000.0 / tex_width );
215
216     // Allocate ssg structure
217     ssgVertexArray   *vl = new ssgVertexArray( 4 );
218     ssgNormalArray   *nl = new ssgNormalArray( 4 );
219     ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
220     ssgColourArray   *cl = new ssgColourArray( 1 );
221
222     sgVec4 color;
223     sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
224     cl->add( color );
225
226     // sgVec3 *vtlist = new sgVec3 [ 4 ];
227     // t->vec3_ptrs.push_back( vtlist );
228     // sgVec3 *vnlist = new sgVec3 [ 4 ];
229     // t->vec3_ptrs.push_back( vnlist );
230     // sgVec2 *tclist = new sgVec2 [ 4 ];
231     // t->vec2_ptrs.push_back( tclist );
232
233     sgVec2 tmp2;
234     sgVec3 tmp3;
235     for ( i = 0; i < 4; ++i ) {
236         sgSetVec3( tmp3, 
237                    rel[i].x(), rel[i].y(), rel[i].z() );
238         vl->add( tmp3 );
239
240         sgSetVec3( tmp3, 
241                    normals[i].x(), normals[i].y(), normals[i].z() );
242         nl->add( tmp3 );
243
244         sgSetVec2( tmp2, texs[i].x(), texs[i].y());
245         tl->add( tmp2 );
246     }
247     
248     ssgLeaf *leaf = 
249         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
250
251     leaf->setState( state );
252
253     geometry->addKid( leaf );
254
255     return true;
256 }
257
258
259 static void random_pt_inside_tri( float *res,
260                                   float *n1, float *n2, float *n3 )
261 {
262     double a = sg_random();
263     double b = sg_random();
264     if ( a + b > 1.0 ) {
265         a = 1.0 - a;
266         b = 1.0 - b;
267     }
268     double c = 1 - a - b;
269
270     res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
271     res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
272     res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
273 }
274
275
276 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
277                                        double factor ) {
278     int num = leaf->getNumTriangles();
279     if ( num > 0 ) {
280         short int n1, n2, n3;
281         float *p1, *p2, *p3;
282         sgVec3 result;
283
284         // generate a repeatable random seed
285         p1 = leaf->getVertex( 0 );
286         unsigned int seed = (unsigned int)(fabs(p1[0]*100));
287         sg_srandom( seed );
288
289         for ( int i = 0; i < num; ++i ) {
290             leaf->getTriangle( i, &n1, &n2, &n3 );
291             p1 = leaf->getVertex(n1);
292             p2 = leaf->getVertex(n2);
293             p3 = leaf->getVertex(n3);
294             double area = sgTriArea( p1, p2, p3 );
295             double num = area / factor;
296
297             // generate a light point for each unit of area
298             while ( num > 1.0 ) {
299                 random_pt_inside_tri( result, p1, p2, p3 );
300                 lights->add( result );
301                 num -= 1.0;
302             }
303             // for partial units of area, use a zombie door method to
304             // create the proper random chance of a light being created
305             // for this triangle
306             if ( num > 0.0 ) {
307                 if ( sg_random() <= num ) {
308                     // a zombie made it through our door
309                     random_pt_inside_tri( result, p1, p2, p3 );
310                     lights->add( result );
311                 }
312             }
313         }
314     }
315 }
316
317
318 /**
319  * User data for populating leaves when they come in range.
320  */
321 class LeafUserData : public ssgBase
322 {
323 public:
324     bool is_filled_in;
325     ssgLeaf * leaf;
326     FGNewMat * mat;
327     ssgBranch * branch;
328     float sin_lat;
329     float cos_lat;
330     float sin_lon;
331     float cos_lon;
332
333     void setup_triangle( int i );
334 };
335
336
337 /**
338  * User data for populating triangles when they come in range.
339  */
340 class TriUserData : public ssgBase
341 {
342 public:
343   bool is_filled_in;
344   float * p1;
345   float * p2;
346   float * p3;
347     sgVec3 center;
348     double area;
349   FGNewMat::ObjectGroup * object_group;
350   ssgBranch * branch;
351     LeafUserData * leafData;
352   unsigned int seed;
353
354     void fill_in_triangle();
355     void add_object_to_triangle(FGNewMat::Object * object);
356     void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
357 };
358
359
360 /**
361  * Fill in a triangle with randomly-placed objects.
362  *
363  * This method is invoked by a callback when the triangle is in range
364  * but not yet populated.
365  *
366  */
367
368 void TriUserData::fill_in_triangle ()
369 {
370                                 // generate a repeatable random seed
371     sg_srandom(seed);
372
373     int nObjects = object_group->get_object_count();
374
375     for (int i = 0; i < nObjects; i++) {
376       FGNewMat::Object * object = object_group->get_object(i);
377       double num = area / object->get_coverage_m2();
378
379       // place an object each unit of area
380       while ( num > 1.0 ) {
381           add_object_to_triangle(object);
382           num -= 1.0;
383       }
384       // for partial units of area, use a zombie door method to
385       // create the proper random chance of an object being created
386       // for this triangle
387       if ( num > 0.0 ) {
388         if ( sg_random() <= num ) {
389           // a zombie made it through our door
390                 add_object_to_triangle(object);
391         }
392       }
393     }
394 }
395
396 void TriUserData::add_object_to_triangle (FGNewMat::Object * object)
397 {
398     // Set up the random heading if required.
399     double hdg_deg = 0;
400     if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
401         hdg_deg = sg_random() * 360;
402
403     sgMat4 mat;
404     makeWorldMatrix(mat, hdg_deg);
405
406     ssgTransform * pos = new ssgTransform;
407     pos->setTransform(mat);
408     pos->addKid(object->get_random_model());
409     branch->addKid(pos);
410 }
411
412 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
413 {
414     if (hdg_deg == 0) {
415         mat[0][0] =  leafData->sin_lat * leafData->cos_lon;
416         mat[0][1] =  leafData->sin_lat * leafData->sin_lon;
417         mat[0][2] = -leafData->cos_lat;
418         mat[0][3] =  SG_ZERO;
419
420         mat[1][0] =  -leafData->sin_lon;
421         mat[1][1] =  leafData->cos_lon;
422         mat[1][2] =  SG_ZERO;
423         mat[1][3] =  SG_ZERO;
424     } else {
425         float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
426         float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
427         mat[0][0] =  cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
428         mat[0][1] =  cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
429         mat[0][2] = -cos_hdg * leafData->cos_lat;
430         mat[0][3] =  SG_ZERO;
431
432         mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
433         mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
434         mat[1][2] =  sin_hdg * leafData->cos_lat;
435         mat[1][3] =  SG_ZERO;
436     }
437
438     mat[2][0] = leafData->cos_lat * leafData->cos_lon;
439     mat[2][1] = leafData->cos_lat * leafData->sin_lon;
440     mat[2][2] = leafData->sin_lat;
441     mat[2][3] = SG_ZERO;
442
443     // translate to random point in triangle
444     sgVec3 result;
445     random_pt_inside_tri(result, p1, p2, p3);
446     sgSubVec3(mat[3], result, center);
447
448     mat[3][3] = SG_ONE ;
449 }
450
451 /**
452  * SSG callback for an in-range triangle of randomly-placed objects.
453  *
454  * This pretraversal callback is attached to a branch that is traversed
455  * only when a triangle is in range.  If the triangle is not currently
456  * populated with randomly-placed objects, this callback will populate
457  * it.
458  *
459  * @param entity The entity to which the callback is attached (not used).
460  * @param mask The entity's traversal mask (not used).
461  * @return Always 1, to allow traversal and culling to continue.
462  */
463 static int
464 tri_in_range_callback (ssgEntity * entity, int mask)
465 {
466   TriUserData * data = (TriUserData *)entity->getUserData();
467   if (!data->is_filled_in) {
468         data->fill_in_triangle();
469     data->is_filled_in = true;
470   }
471   return 1;
472 }
473
474
475 /**
476  * SSG callback for an out-of-range triangle of randomly-placed objects.
477  *
478  * This pretraversal callback is attached to a branch that is traversed
479  * only when a triangle is out of range.  If the triangle is currently
480  * populated with randomly-placed objects, the objects will be removed.
481  *
482  *
483  * @param entity The entity to which the callback is attached (not used).
484  * @param mask The entity's traversal mask (not used).
485  * @return Always 0, to prevent any further traversal or culling.
486  */
487 static int
488 tri_out_of_range_callback (ssgEntity * entity, int mask)
489 {
490   TriUserData * data = (TriUserData *)entity->getUserData();
491   if (data->is_filled_in) {
492     data->branch->removeAllKids();
493     data->is_filled_in = false;
494   }
495   return 0;
496 }
497
498
499 /**
500  * ssgEntity with a dummy bounding sphere, to fool culling.
501  *
502  * This forces the in-range and out-of-range branches to be visited
503  * when appropriate, even if they have no children.  It's ugly, but
504  * it works and seems fairly efficient (since branches can still
505  * be culled when they're out of the view frustum).
506  */
507 class DummyBSphereEntity : public ssgEntity
508 {
509 public:
510   DummyBSphereEntity (float radius)
511   {
512     bsphere.setCenter(0, 0, 0);
513     bsphere.setRadius(radius);
514   }
515   virtual ~DummyBSphereEntity () {}
516   virtual void recalcBSphere () { bsphere_is_invalid = false; }
517   virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
518   virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
519   virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
520   virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
521 };
522
523
524 /**
525  * Calculate the bounding radius of a triangle from its center.
526  *
527  * @param center The triangle center.
528  * @param p1 The first point in the triangle.
529  * @param p2 The second point in the triangle.
530  * @param p3 The third point in the triangle.
531  * @return The greatest distance any point lies from the center.
532  */
533 static inline float
534 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
535 {
536    return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
537                          sgDistanceSquaredVec3(center, p2),
538                          sgDistanceSquaredVec3(center, p3) ) );
539 }
540
541
542 /**
543  * Set up a triangle for randomly-placed objects.
544  *
545  * No objects will be added unless the triangle comes into range.
546  *
547  */
548
549 void LeafUserData::setup_triangle (int i )
550 {
551     short n1, n2, n3;
552     leaf->getTriangle(i, &n1, &n2, &n3);
553
554     float * p1 = leaf->getVertex(n1);
555     float * p2 = leaf->getVertex(n2);
556     float * p3 = leaf->getVertex(n3);
557
558                                 // Set up a single center point for LOD
559     sgVec3 center;
560     sgSetVec3(center,
561               (p1[0] + p2[0] + p3[0]) / 3.0,
562               (p1[1] + p2[1] + p3[1]) / 3.0,
563               (p1[2] + p2[2] + p3[2]) / 3.0);
564     double area = sgTriArea(p1, p2, p3);
565       
566                                 // maximum radius of an object from center.
567     double bounding_radius = get_bounding_radius(center, p1, p2, p3);
568
569                                 // Set up a transformation to the center
570                                 // point, so that everything else can
571                                 // be specified relative to it.
572     ssgTransform * location = new ssgTransform;
573     sgMat4 TRANS;
574     sgMakeTransMat4(TRANS, center);
575     location->setTransform(TRANS);
576     branch->addKid(location);
577
578                                 // Iterate through all the object types.
579     int num_groups = mat->get_object_group_count();
580     for (int j = 0; j < num_groups; j++) {
581                                 // Look up the random object.
582         FGNewMat::ObjectGroup * group = mat->get_object_group(j);
583
584                                 // Set up the range selector for the entire
585                                 // triangle; note that we use the object
586                                 // range plus the bounding radius here, to
587                                 // allow for objects far from the center.
588         float ranges[] = { 0,
589                           group->get_range_m() + bounding_radius,
590                 SG_MAX };
591         ssgRangeSelector * lod = new ssgRangeSelector;
592         lod->setRanges(ranges, 3);
593         location->addKid(lod);
594
595                                 // Create the in-range and out-of-range
596                                 // branches.
597         ssgBranch * in_range = new ssgBranch;
598         ssgBranch * out_of_range = new ssgBranch;
599
600                                 // Set up the user data for if/when
601                                 // the random objects in this triangle
602                                 // are filled in.
603         TriUserData * data = new TriUserData;
604         data->is_filled_in = false;
605         data->p1 = p1;
606         data->p2 = p2;
607         data->p3 = p3;
608         sgCopyVec3 (data->center, center);
609         data->area = area;
610         data->object_group = group;
611         data->branch = in_range;
612         data->leafData = this;
613         data->seed = (unsigned int)(p1[0] * j);
614
615                                 // Set up the in-range node.
616         in_range->setUserData(data);
617         in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
618                                  tri_in_range_callback);
619         lod->addKid(in_range);
620
621                                 // Set up the out-of-range node.
622         out_of_range->setUserData(data);
623         out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
624                                       tri_out_of_range_callback);
625         out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
626         lod->addKid(out_of_range);
627     }
628 }
629
630 /**
631  * SSG callback for an in-range leaf of randomly-placed objects.
632  *
633  * This pretraversal callback is attached to a branch that is
634  * traversed only when a leaf is in range.  If the leaf is not
635  * currently prepared to be populated with randomly-placed objects,
636  * this callback will prepare it (actual population is handled by
637  * the tri_in_range_callback for individual triangles).
638  *
639  * @param entity The entity to which the callback is attached (not used).
640  * @param mask The entity's traversal mask (not used).
641  * @return Always 1, to allow traversal and culling to continue.
642  */
643 static int
644 leaf_in_range_callback (ssgEntity * entity, int mask)
645 {
646   LeafUserData * data = (LeafUserData *)entity->getUserData();
647
648   if (!data->is_filled_in) {
649                                 // Iterate through all the triangles
650                                 // and populate them.
651     int num_tris = data->leaf->getNumTriangles();
652     for ( int i = 0; i < num_tris; ++i ) {
653             data->setup_triangle(i);
654     }
655     data->is_filled_in = true;
656   }
657   return 1;
658 }
659
660
661 /**
662  * SSG callback for an out-of-range leaf of randomly-placed objects.
663  *
664  * This pretraversal callback is attached to a branch that is
665  * traversed only when a leaf is out of range.  If the leaf is
666  * currently prepared to be populated with randomly-placed objects (or
667  * is actually populated), the objects will be removed.
668  *
669  * @param entity The entity to which the callback is attached (not used).
670  * @param mask The entity's traversal mask (not used).
671  * @return Always 0, to prevent any further traversal or culling.
672  */
673 static int
674 leaf_out_of_range_callback (ssgEntity * entity, int mask)
675 {
676   LeafUserData * data = (LeafUserData *)entity->getUserData();
677   if (data->is_filled_in) {
678     data->branch->removeAllKids();
679     data->is_filled_in = false;
680   }
681   return 0;
682 }
683
684
685 /**
686  * Randomly place objects on a surface.
687  *
688  * The leaf node provides the geometry of the surface, while the
689  * material provides the objects and placement density.  Latitude
690  * and longitude are required so that the objects can be rotated
691  * to the world-up vector.  This function does not actually add
692  * any objects; instead, it attaches an ssgRangeSelector to the
693  * branch with callbacks to generate the objects when needed.
694  *
695  * @param leaf The surface where the objects should be placed.
696  * @param branch The branch that will hold the randomly-placed objects.
697  * @param center The center of the leaf in FlightGear coordinates.
698  * @param material_name The name of the surface's material.
699  */
700 static void
701 gen_random_surface_objects (ssgLeaf *leaf,
702                             ssgBranch *branch,
703                             Point3D * center,
704                             const string &material_name)
705 {
706                                 // If the surface has no triangles, return
707                                 // now.
708     int num_tris = leaf->getNumTriangles();
709     if (num_tris < 1)
710       return;
711
712                                 // Get the material for this surface.
713     FGNewMat * mat = material_lib.find(material_name);
714     if (mat == 0) {
715       SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
716       return;
717     }
718
719                                 // If the material has no randomly-placed
720                                 // objects, return now.
721     if (mat->get_object_group_count() < 1)
722       return;
723
724                                 // Calculate the geodetic centre of
725                                 // the tile, for aligning automatic
726                                 // objects.
727     double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
728     Point3D geoc = sgCartToPolar3d(*center);
729     lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
730     sgGeocToGeod(geoc.lat(), geoc.radius(),
731                  &lat_rad, &alt_m, &sl_radius_m);
732     lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
733
734                                 // LOD for the leaf
735                                 // max random object range: 20000m
736     float ranges[] = { 0, 20000, 1000000 };
737     ssgRangeSelector * lod = new ssgRangeSelector;
738     lod->setRanges(ranges, 3);
739     branch->addKid(lod);
740
741                                 // Create the in-range and out-of-range
742                                 // branches.
743     ssgBranch * in_range = new ssgBranch;
744     ssgBranch * out_of_range = new ssgBranch;
745     lod->addKid(in_range);
746     lod->addKid(out_of_range);
747
748     LeafUserData * data = new LeafUserData;
749     data->is_filled_in = false;
750     data->leaf = leaf;
751     data->mat = mat;
752     data->branch = in_range;
753     data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
754     data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
755     data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
756     data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
757
758     in_range->setUserData(data);
759     in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
760     out_of_range->setUserData(data);
761     out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
762                                    leaf_out_of_range_callback);
763     out_of_range
764       ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
765 }
766
767
768 \f
769 ////////////////////////////////////////////////////////////////////////
770 // Scenery loaders.
771 ////////////////////////////////////////////////////////////////////////
772
773
774 // Load an Ascii obj file
775 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
776                            ssgVertexArray *lights, const bool is_base)
777 {
778     FGNewMat *newmat = NULL;
779     string material;
780     float coverage = -1;
781     Point3D pp;
782     // sgVec3 approx_normal;
783     // double normal[3], scale = 0.0;
784     // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
785     // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
786     // GLint display_list = 0;
787     int shading;
788     bool in_faces = false;
789     int vncount, vtcount;
790     int n1 = 0, n2 = 0, n3 = 0;
791     int tex;
792     // int last1 = 0, last2 = 0;
793     bool odd = false;
794     point_list nodes;
795     Point3D node;
796     Point3D center;
797     double scenery_version = 0.0;
798     double tex_width = 1000.0, tex_height = 1000.0;
799     bool shared_done = false;
800     int_list fan_vertices;
801     int_list fan_tex_coords;
802     int i;
803     ssgSimpleState *state = NULL;
804     sgVec3 *vtlist, *vnlist;
805     sgVec2 *tclist;
806
807     ssgBranch *tile = new ssgBranch () ;
808
809     tile -> setName ( (char *)path.c_str() ) ;
810
811     // Attempt to open "path.gz" or "path"
812     sg_gzifstream in( path );
813     if ( ! in.is_open() ) {
814         SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
815         SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
816
817         delete tile;
818
819         return NULL;
820     }
821
822     shading = fgGetBool("/sim/rendering/shading");
823
824     if ( is_base ) {
825         t->ncount = 0;
826     }
827     vncount = 0;
828     vtcount = 0;
829     if ( is_base ) {
830         t->bounding_radius = 0.0;
831     }
832     center = t->center;
833
834     // StopWatch stopwatch;
835     // stopwatch.start();
836
837     // ignore initial comments and blank lines. (priming the pump)
838     // in >> skipcomment;
839     // string line;
840
841     string token;
842     char c;
843
844 #ifdef __MWERKS__
845     while ( in.get(c) && c  != '\0' ) {
846         in.putback(c);
847 #else
848     while ( ! in.eof() ) {
849 #endif
850         in >> ::skipws;
851
852         if ( in.get( c ) && c == '#' ) {
853             // process a comment line
854
855             // getline( in, line );
856             // cout << "comment = " << line << endl;
857
858             in >> token;
859
860             if ( token == "Version" ) {
861                 // read scenery versions number
862                 in >> scenery_version;
863                 // cout << "scenery_version = " << scenery_version << endl;
864                 if ( scenery_version > 0.4 ) {
865                     SG_LOG( SG_TERRAIN, SG_ALERT, 
866                             "\nYou are attempting to load a tile format that\n"
867                             << "is newer than this version of flightgear can\n"
868                             << "handle.  You should upgrade your copy of\n"
869                             << "FlightGear to the newest version.  For\n"
870                             << "details, please see:\n"
871                             << "\n    http://www.flightgear.org\n" );
872                     exit(-1);
873                 }
874             } else if ( token == "gbs" ) {
875                 // reference point (center offset)
876                 if ( is_base ) {
877                     in >> t->center >> t->bounding_radius;
878                 } else {
879                     Point3D junk1;
880                     double junk2;
881                     in >> junk1 >> junk2;
882                 }
883                 center = t->center;
884                 // cout << "center = " << center 
885                 //      << " radius = " << t->bounding_radius << endl;
886             } else if ( token == "bs" ) {
887                 // reference point (center offset)
888                 // (skip past this)
889                 Point3D junk1;
890                 double junk2;
891                 in >> junk1 >> junk2;
892             } else if ( token == "usemtl" ) {
893                 // material property specification
894
895                 // if first usemtl with shared_done = false, then set
896                 // shared_done true and build the ssg shared lists
897                 if ( ! shared_done ) {
898                     // sanity check
899                     if ( (int)nodes.size() != vncount ) {
900                         SG_LOG( SG_TERRAIN, SG_ALERT, 
901                                 "Tile has mismatched nodes = " << nodes.size()
902                                 << " and normals = " << vncount << " : " 
903                                 << path );
904                         // exit(-1);
905                     }
906                     shared_done = true;
907
908                     vtlist = new sgVec3 [ nodes.size() ];
909                     t->vec3_ptrs.push_back( vtlist );
910                     vnlist = new sgVec3 [ vncount ];
911                     t->vec3_ptrs.push_back( vnlist );
912                     tclist = new sgVec2 [ vtcount ];
913                     t->vec2_ptrs.push_back( tclist );
914
915                     for ( i = 0; i < (int)nodes.size(); ++i ) {
916                         sgSetVec3( vtlist[i], 
917                                    nodes[i][0], nodes[i][1], nodes[i][2] );
918                     }
919                     for ( i = 0; i < vncount; ++i ) {
920                         sgSetVec3( vnlist[i], 
921                                    normals[i][0], 
922                                    normals[i][1],
923                                    normals[i][2] );
924                     }
925                     for ( i = 0; i < vtcount; ++i ) {
926                         sgSetVec2( tclist[i],
927                                    tex_coords[i][0],
928                                    tex_coords[i][1] );
929                     }
930                 }
931
932                 // display_list = xglGenLists(1);
933                 // xglNewList(display_list, GL_COMPILE);
934                 // printf("xglGenLists(); xglNewList();\n");
935                 in_faces = false;
936
937                 // scan the material line
938                 in >> material;
939                 
940                 // find this material in the properties list
941
942                 newmat = material_lib.find( material );
943                 if ( newmat == NULL ) {
944                     // see if this is an on the fly texture
945                     string file = path;
946                     int pos = file.rfind( "/" );
947                     file = file.substr( 0, pos );
948                     // cout << "current file = " << file << endl;
949                     file += "/";
950                     file += material;
951                     // cout << "current file = " << file << endl;
952                     if ( ! material_lib.add_item( file ) ) {
953                         SG_LOG( SG_TERRAIN, SG_ALERT, 
954                                 "Ack! unknown usemtl name = " << material 
955                                 << " in " << path );
956                     } else {
957                         // locate our newly created material
958                         newmat = material_lib.find( material );
959                         if ( newmat == NULL ) {
960                             SG_LOG( SG_TERRAIN, SG_ALERT, 
961                                     "Ack! bad on the fly materia create = "
962                                     << material << " in " << path );
963                         }
964                     }
965                 }
966
967                 if ( newmat != NULL ) {
968                     // set the texture width and height values for this
969                     // material
970                     tex_width = newmat->get_xsize();
971                     tex_height = newmat->get_ysize();
972                     state = newmat->get_state();
973                     coverage = newmat->get_light_coverage();
974                     // cout << "(w) = " << tex_width << " (h) = "
975                     //      << tex_width << endl;
976                 } else {
977                     coverage = -1;
978                 }
979             } else {
980                 // unknown comment, just gobble the input until the
981                 // end of line
982
983                 in >> skipeol;
984             }
985         } else {
986             in.putback( c );
987         
988             in >> token;
989
990             // cout << "token = " << token << endl;
991
992             if ( token == "vn" ) {
993                 // vertex normal
994                 if ( vncount < FG_MAX_NODES ) {
995                     in >> normals[vncount][0]
996                        >> normals[vncount][1]
997                        >> normals[vncount][2];
998                     vncount++;
999                 } else {
1000                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1001                             "Read too many vertex normals in " << path 
1002                             << " ... dying :-(" );
1003                     exit(-1);
1004                 }
1005             } else if ( token == "vt" ) {
1006                 // vertex texture coordinate
1007                 if ( vtcount < FG_MAX_NODES*3 ) {
1008                     in >> tex_coords[vtcount][0]
1009                        >> tex_coords[vtcount][1];
1010                     vtcount++;
1011                 } else {
1012                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1013                             "Read too many vertex texture coords in " << path
1014                             << " ... dying :-("
1015                             );
1016                     exit(-1);
1017                 }
1018             } else if ( token == "v" ) {
1019                 // node (vertex)
1020                 if ( t->ncount < FG_MAX_NODES ) {
1021                     /* in >> nodes[t->ncount][0]
1022                        >> nodes[t->ncount][1]
1023                        >> nodes[t->ncount][2]; */
1024                     in >> node;
1025                     nodes.push_back(node);
1026                     if ( is_base ) {
1027                         t->ncount++;
1028                     }
1029                 } else {
1030                     SG_LOG( SG_TERRAIN, SG_ALERT, 
1031                             "Read too many nodes in " << path 
1032                             << " ... dying :-(");
1033                     exit(-1);
1034                 }
1035             } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1036                 // triangle fan, strip, or individual face
1037                 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1038
1039                 fan_vertices.clear();
1040                 fan_tex_coords.clear();
1041                 odd = true;
1042
1043                 // xglBegin(GL_TRIANGLE_FAN);
1044
1045                 in >> n1;
1046                 fan_vertices.push_back( n1 );
1047                 // xglNormal3dv(normals[n1]);
1048                 if ( in.get( c ) && c == '/' ) {
1049                     in >> tex;
1050                     fan_tex_coords.push_back( tex );
1051                     if ( scenery_version >= 0.4 ) {
1052                         if ( tex_width > 0 ) {
1053                             tclist[tex][0] *= (1000.0 / tex_width);
1054                         }
1055                         if ( tex_height > 0 ) {
1056                             tclist[tex][1] *= (1000.0 / tex_height);
1057                         }
1058                     }
1059                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1060                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1061                 } else {
1062                     in.putback( c );
1063                     pp = local_calc_tex_coords(nodes[n1], center);
1064                 }
1065                 // xglTexCoord2f(pp.x(), pp.y());
1066                 // xglVertex3dv(nodes[n1].get_n());
1067
1068                 in >> n2;
1069                 fan_vertices.push_back( n2 );
1070                 // xglNormal3dv(normals[n2]);
1071                 if ( in.get( c ) && c == '/' ) {
1072                     in >> tex;
1073                     fan_tex_coords.push_back( tex );
1074                     if ( scenery_version >= 0.4 ) {
1075                         if ( tex_width > 0 ) {
1076                             tclist[tex][0] *= (1000.0 / tex_width);
1077                         }
1078                         if ( tex_height > 0 ) {
1079                             tclist[tex][1] *= (1000.0 / tex_height);
1080                         }
1081                     }
1082                     pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1083                     pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1084                 } else {
1085                     in.putback( c );
1086                     pp = local_calc_tex_coords(nodes[n2], center);
1087                 }
1088                 // xglTexCoord2f(pp.x(), pp.y());
1089                 // xglVertex3dv(nodes[n2].get_n());
1090                 
1091                 // read all subsequent numbers until next thing isn't a number
1092                 while ( true ) {
1093                     in >> ::skipws;
1094
1095                     char c;
1096                     in.get(c);
1097                     in.putback(c);
1098                     if ( ! isdigit(c) || in.eof() ) {
1099                         break;
1100                     }
1101
1102                     in >> n3;
1103                     fan_vertices.push_back( n3 );
1104                     // cout << "  triangle = "
1105                     //      << n1 << "," << n2 << "," << n3
1106                     //      << endl;
1107                     // xglNormal3dv(normals[n3]);
1108                     if ( in.get( c ) && c == '/' ) {
1109                         in >> tex;
1110                         fan_tex_coords.push_back( tex );
1111                         if ( scenery_version >= 0.4 ) {
1112                             if ( tex_width > 0 ) {
1113                                 tclist[tex][0] *= (1000.0 / tex_width);
1114                             }
1115                             if ( tex_height > 0 ) {
1116                                 tclist[tex][1] *= (1000.0 / tex_height);
1117                             }
1118                         }
1119                         pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1120                         pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1121                     } else {
1122                         in.putback( c );
1123                         pp = local_calc_tex_coords(nodes[n3], center);
1124                     }
1125                     // xglTexCoord2f(pp.x(), pp.y());
1126                     // xglVertex3dv(nodes[n3].get_n());
1127
1128                     if ( (token == "tf") || (token == "f") ) {
1129                         // triangle fan
1130                         n2 = n3;
1131                     } else {
1132                         // triangle strip
1133                         odd = !odd;
1134                         n1 = n2;
1135                         n2 = n3;
1136                     }
1137                 }
1138
1139                 // xglEnd();
1140
1141                 // build the ssg entity
1142                 int size = (int)fan_vertices.size();
1143                 ssgVertexArray   *vl = new ssgVertexArray( size );
1144                 ssgNormalArray   *nl = new ssgNormalArray( size );
1145                 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1146                 ssgColourArray   *cl = new ssgColourArray( 1 );
1147
1148                 sgVec4 color;
1149                 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1150                 cl->add( color );
1151
1152                 sgVec2 tmp2;
1153                 sgVec3 tmp3;
1154                 for ( i = 0; i < size; ++i ) {
1155                     sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1156                     vl -> add( tmp3 );
1157
1158                     sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1159                     nl -> add( tmp3 );
1160
1161                     sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1162                     tl -> add( tmp2 );
1163                 }
1164
1165                 ssgLeaf *leaf = NULL;
1166                 if ( token == "tf" ) {
1167                     // triangle fan
1168                     leaf = 
1169                         new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1170                 } else if ( token == "ts" ) {
1171                     // triangle strip
1172                     leaf = 
1173                         new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1174                 } else if ( token == "f" ) {
1175                     // triangle
1176                     leaf = 
1177                         new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1178                 }
1179                 // leaf->makeDList();
1180                 leaf->setState( state );
1181
1182                 tile->addKid( leaf );
1183
1184                 if ( is_base ) {
1185                     if ( coverage > 0.0 ) {
1186                         if ( coverage < 10000.0 ) {
1187                             SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1188                                    << coverage << ", pushing up to 10000");
1189                             coverage = 10000;
1190                         }
1191                         gen_random_surface_points(leaf, lights, coverage);
1192                     }
1193                 }
1194             } else {
1195                 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in " 
1196                         << path << " = " << token );
1197             }
1198
1199             // eat white space before start of while loop so if we are
1200             // done with useful input it is noticed before hand.
1201             in >> ::skipws;
1202         }
1203     }
1204
1205     if ( is_base ) {
1206         t->nodes = nodes;
1207     }
1208
1209     // stopwatch.stop();
1210     // SG_LOG( SG_TERRAIN, SG_DEBUG, 
1211     //     "Loaded " << path << " in " 
1212     //     << stopwatch.elapsedSeconds() << " seconds" );
1213
1214     return tile;
1215 }
1216
1217
1218 ssgLeaf *gen_leaf( const string& path,
1219                    const GLenum ty, const string& material,
1220                    const point_list& nodes, const point_list& normals,
1221                    const point_list& texcoords,
1222                    const int_list& node_index,
1223                    const int_list& normal_index,
1224                    const int_list& tex_index,
1225                    const bool calc_lights, ssgVertexArray *lights )
1226 {
1227     double tex_width = 1000.0, tex_height = 1000.0;
1228     ssgSimpleState *state = NULL;
1229     float coverage = -1;
1230
1231     FGNewMat *newmat = material_lib.find( material );
1232     if ( newmat == NULL ) {
1233         // see if this is an on the fly texture
1234         string file = path;
1235         string::size_type pos = file.rfind( "/" );
1236         file = file.substr( 0, pos );
1237         // cout << "current file = " << file << endl;
1238         file += "/";
1239         file += material;
1240         // cout << "current file = " << file << endl;
1241         if ( ! material_lib.add_item( file ) ) {
1242             SG_LOG( SG_TERRAIN, SG_ALERT, 
1243                     "Ack! unknown usemtl name = " << material 
1244                     << " in " << path );
1245         } else {
1246             // locate our newly created material
1247             newmat = material_lib.find( material );
1248             if ( newmat == NULL ) {
1249                 SG_LOG( SG_TERRAIN, SG_ALERT, 
1250                         "Ack! bad on the fly material create = "
1251                         << material << " in " << path );
1252             }
1253         }
1254     }
1255
1256     if ( newmat != NULL ) {
1257         // set the texture width and height values for this
1258         // material
1259         tex_width = newmat->get_xsize();
1260         tex_height = newmat->get_ysize();
1261         state = newmat->get_state();
1262         coverage = newmat->get_light_coverage();
1263         // cout << "(w) = " << tex_width << " (h) = "
1264         //      << tex_width << endl;
1265     } else {
1266         coverage = -1;
1267     }
1268
1269     sgVec2 tmp2;
1270     sgVec3 tmp3;
1271     sgVec4 tmp4;
1272     int i;
1273
1274     // vertices
1275     int size = node_index.size();
1276     if ( size < 1 ) {
1277         SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1278         exit(-1);
1279     }
1280     ssgVertexArray *vl = new ssgVertexArray( size );
1281     Point3D node;
1282     for ( i = 0; i < size; ++i ) {
1283         node = nodes[ node_index[i] ];
1284         sgSetVec3( tmp3, node[0], node[1], node[2] );
1285         vl -> add( tmp3 );
1286     }
1287
1288     // normals
1289     Point3D normal;
1290     ssgNormalArray *nl = new ssgNormalArray( size );
1291     if ( normal_index.size() ) {
1292         // object file specifies normal indices (i.e. normal indices
1293         // aren't 'implied'
1294         for ( i = 0; i < size; ++i ) {
1295             normal = normals[ normal_index[i] ];
1296             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1297             nl -> add( tmp3 );
1298         }
1299     } else {
1300         // use implied normal indices.  normal index = vertex index.
1301         for ( i = 0; i < size; ++i ) {
1302             normal = normals[ node_index[i] ];
1303             sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1304             nl -> add( tmp3 );
1305         }
1306     }
1307
1308     // colors
1309     ssgColourArray *cl = new ssgColourArray( 1 );
1310     sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1311     cl->add( tmp4 );
1312
1313     // texture coordinates
1314     size = tex_index.size();
1315     Point3D texcoord;
1316     ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1317     if ( size == 1 ) {
1318         texcoord = texcoords[ tex_index[0] ];
1319         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1320         sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1321         if ( tex_width > 0 ) {
1322             tmp2[0] *= (1000.0 / tex_width);
1323         }
1324         if ( tex_height > 0 ) {
1325             tmp2[1] *= (1000.0 / tex_height);
1326         }
1327         tl -> add( tmp2 );
1328     } else if ( size > 1 ) {
1329         for ( i = 0; i < size; ++i ) {
1330             texcoord = texcoords[ tex_index[i] ];
1331             sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1332             if ( tex_width > 0 ) {
1333                 tmp2[0] *= (1000.0 / tex_width);
1334             }
1335             if ( tex_height > 0 ) {
1336                 tmp2[1] *= (1000.0 / tex_height);
1337             }
1338             tl -> add( tmp2 );
1339         }
1340     }
1341
1342     ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1343
1344     // lookup the state record
1345
1346     leaf->setState( state );
1347
1348     if ( calc_lights ) {
1349         if ( coverage > 0.0 ) {
1350             if ( coverage < 10000.0 ) {
1351                 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1352                        << coverage << ", pushing up to 10000");
1353                 coverage = 10000;
1354             }
1355             gen_random_surface_points(leaf, lights, coverage);
1356         }
1357     }
1358
1359     return leaf;
1360 }
1361
1362
1363 // Load an Binary obj file
1364 bool fgBinObjLoad( const string& path, const bool is_base,
1365                    Point3D *center,
1366                    double *bounding_radius,
1367                    ssgBranch* geometry,
1368                    ssgBranch* rwy_lights,
1369                    ssgBranch* taxi_lights,
1370                    ssgVertexArray *ground_lights )
1371 {
1372     SGBinObject obj;
1373     bool use_random_objects =
1374       fgGetBool("/sim/rendering/random-objects", true);
1375
1376     if ( ! obj.read_bin( path ) ) {
1377         return false;
1378     }
1379
1380     geometry->setName( (char *)path.c_str() );
1381
1382     // reference point (center offset/bounding sphere)
1383     *center = obj.get_gbs_center();
1384     *bounding_radius = obj.get_gbs_radius();
1385
1386     point_list const& nodes = obj.get_wgs84_nodes();
1387     // point_list const& colors = obj.get_colors();
1388     point_list const& normals = obj.get_normals();
1389     point_list const& texcoords = obj.get_texcoords();
1390
1391     string material;
1392     int_list tex_index;
1393
1394     group_list::size_type i;
1395
1396     // generate points
1397     string_list const& pt_materials = obj.get_pt_materials();
1398     group_list const& pts_v = obj.get_pts_v();
1399     group_list const& pts_n = obj.get_pts_n();
1400     for ( i = 0; i < pts_v.size(); ++i ) {
1401         // cout << "pts_v.size() = " << pts_v.size() << endl;
1402         if ( pt_materials[i].substr(0, 3) == "RWY" ) {
1403             sgVec3 up;
1404             sgSetVec3( up, center->x(), center->y(), center->z() );
1405             // returns a transform -> lod -> leaf structure
1406             ssgBranch *branch = gen_directional_lights( nodes, normals,
1407                                                         pts_v[i], pts_n[i],
1408                                                         pt_materials[i],
1409                                                         up );
1410             // branches don't honor callbacks as far as I know so I'm
1411             // commenting this out to avoid a plib runtime warning.
1412             branch->setTravCallback( SSG_CALLBACK_PRETRAV,
1413                                      runway_lights_pretrav );
1414             if ( pt_materials[i].substr(0, 16) == "RWY_BLUE_TAXIWAY" ) {
1415                 taxi_lights->addKid( branch );
1416             } else {
1417                 rwy_lights->addKid( branch );
1418             }
1419         } else {
1420             material = pt_materials[i];
1421             tex_index.clear();
1422             ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1423                                       nodes, normals, texcoords,
1424                                       pts_v[i], pts_n[i], tex_index,
1425                                       false, ground_lights );
1426             geometry->addKid( leaf );
1427         }
1428     }
1429
1430     // Put all randomly-placed objects under a separate branch
1431     // (actually an ssgRangeSelector) named "random-models".
1432     ssgBranch * random_object_branch = 0;
1433     if (use_random_objects) {
1434         float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
1435         ssgRangeSelector * object_lod = new ssgRangeSelector;
1436         object_lod->setRanges(ranges, 2);
1437         object_lod->setName("random-models");
1438         geometry->addKid(object_lod);
1439         random_object_branch = new ssgBranch;
1440         object_lod->addKid(random_object_branch);
1441     }
1442
1443     // generate triangles
1444     string_list const& tri_materials = obj.get_tri_materials();
1445     group_list const& tris_v = obj.get_tris_v();
1446     group_list const& tris_n = obj.get_tris_n();
1447     group_list const& tris_tc = obj.get_tris_tc();
1448     for ( i = 0; i < tris_v.size(); ++i ) {
1449         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
1450                                   nodes, normals, texcoords,
1451                                   tris_v[i], tris_n[i], tris_tc[i],
1452                                   is_base, ground_lights );
1453
1454         if (use_random_objects)
1455           gen_random_surface_objects(leaf, random_object_branch,
1456                                      center, tri_materials[i]);
1457         geometry->addKid( leaf );
1458     }
1459
1460     // generate strips
1461     string_list const& strip_materials = obj.get_strip_materials();
1462     group_list const& strips_v = obj.get_strips_v();
1463     group_list const& strips_n = obj.get_strips_n();
1464     group_list const& strips_tc = obj.get_strips_tc();
1465     for ( i = 0; i < strips_v.size(); ++i ) {
1466         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
1467                                   nodes, normals, texcoords,
1468                                   strips_v[i], strips_n[i], strips_tc[i],
1469                                   is_base, ground_lights );
1470
1471         if (use_random_objects)
1472           gen_random_surface_objects(leaf, random_object_branch,
1473                                      center,strip_materials[i]);
1474         geometry->addKid( leaf );
1475     }
1476
1477     // generate fans
1478     string_list const& fan_materials = obj.get_fan_materials();
1479     group_list const& fans_v = obj.get_fans_v();
1480     group_list const& fans_n = obj.get_fans_n();
1481     group_list const& fans_tc = obj.get_fans_tc();
1482     for ( i = 0; i < fans_v.size(); ++i ) {
1483         ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
1484                                   nodes, normals, texcoords,
1485                                   fans_v[i], fans_n[i], fans_tc[i],
1486                                   is_base, ground_lights );
1487         if (use_random_objects)
1488           gen_random_surface_objects(leaf, random_object_branch,
1489                                      center, fan_materials[i]);
1490         geometry->addKid( leaf );
1491     }
1492
1493     return true;
1494 }