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