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