]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
Moved random ground cover object management code (userdata.[ch]xx) over
[flightgear.git] / src / Scenery / tileentry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  Curtis L. Olson  - curt@flightgear.org
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 #include <simgear/compiler.h>
29
30 #include STL_STRING
31
32 #include <simgear/bucket/newbucket.hxx>
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/misc/sgstream.hxx>
37 #include <simgear/scene/material/mat.hxx>
38 #include <simgear/scene/material/matlib.hxx>
39 #include <simgear/scene/tgdb/apt_signs.hxx>
40
41 #include <Aircraft/aircraft.hxx>
42 #include <Include/general.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Main/globals.hxx>
45 #include <Main/viewer.hxx>
46 #include <Scenery/scenery.hxx>
47 #include <Time/light.hxx>
48 #include <Objects/obj.hxx>
49
50 #include "tileentry.hxx"
51 #include "tilemgr.hxx"
52
53 SG_USING_STD(string);
54
55
56 // Constructor
57 FGTileEntry::FGTileEntry ( const SGBucket& b )
58     : center( Point3D( 0.0 ) ),
59       tile_bucket( b ),
60       terra_transform( new ssgTransform ),
61       rwy_lights_transform( new ssgTransform ),
62       taxi_lights_transform( new ssgTransform ),
63       terra_range( new ssgRangeSelector ),
64       rwy_lights_selector( new ssgSelector ),
65       taxi_lights_selector( new ssgSelector ),
66       loaded(false),
67       pending_models(0),
68       free_tracker(0)
69 {
70     // update the contents
71     // if ( vec3_ptrs.size() || vec2_ptrs.size() || index_ptrs.size() ) {
72     //     SG_LOG( SG_TERRAIN, SG_ALERT, 
73     //             "Attempting to overwrite existing or"
74     //             << " not properly freed leaf data." );
75     //     exit(-1);
76     // }
77 }
78
79
80 // Destructor
81 FGTileEntry::~FGTileEntry () {
82     // cout << "nodes = " << nodes.size() << endl;;
83     // delete[] nodes;
84 }
85
86
87 #if 0
88 // Please keep this for reference.  We use Norman's optimized routine,
89 // but here is what the routine really is doing.
90 void
91 FGTileEntry::WorldCoordinate( sgCoord *obj_pos, Point3D center,
92                               double lat, double lon, double elev, double hdg)
93 {
94     // setup transforms
95     Point3D geod( lon * SGD_DEGREES_TO_RADIANS,
96                   lat * SGD_DEGREES_TO_RADIANS,
97                   elev );
98         
99     Point3D world_pos = sgGeodToCart( geod );
100     Point3D offset = world_pos - center;
101         
102     sgMat4 POS;
103     sgMakeTransMat4( POS, offset.x(), offset.y(), offset.z() );
104
105     sgVec3 obj_rt, obj_up;
106     sgSetVec3( obj_rt, 0.0, 1.0, 0.0); // Y axis
107     sgSetVec3( obj_up, 0.0, 0.0, 1.0); // Z axis
108
109     sgMat4 ROT_lon, ROT_lat, ROT_hdg;
110     sgMakeRotMat4( ROT_lon, lon, obj_up );
111     sgMakeRotMat4( ROT_lat, 90 - lat, obj_rt );
112     sgMakeRotMat4( ROT_hdg, hdg, obj_up );
113
114     sgMat4 TUX;
115     sgCopyMat4( TUX, ROT_hdg );
116     sgPostMultMat4( TUX, ROT_lat );
117     sgPostMultMat4( TUX, ROT_lon );
118     sgPostMultMat4( TUX, POS );
119
120     sgSetCoord( obj_pos, TUX );
121 }
122 #endif
123
124
125 // Norman's 'fast hack' for above
126 static void WorldCoordinate( sgCoord *obj_pos, Point3D center, double lat,
127                              double lon, double elev, double hdg )
128 {
129     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
130     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
131     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
132
133     // setup transforms
134     Point3D geod( lon_rad, lat_rad, elev );
135         
136     Point3D world_pos = sgGeodToCart( geod );
137     Point3D offset = world_pos - center;
138
139     sgMat4 mat;
140
141     SGfloat sin_lat = (SGfloat)sin( lat_rad );
142     SGfloat cos_lat = (SGfloat)cos( lat_rad );
143     SGfloat cos_lon = (SGfloat)cos( lon_rad );
144     SGfloat sin_lon = (SGfloat)sin( lon_rad );
145     SGfloat sin_hdg = (SGfloat)sin( hdg_rad ) ;
146     SGfloat cos_hdg = (SGfloat)cos( hdg_rad ) ;
147
148     mat[0][0] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - sin_hdg * (SGfloat)sin_lon;
149     mat[0][1] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + sin_hdg * (SGfloat)cos_lon;
150     mat[0][2] = -cos_hdg * (SGfloat)cos_lat;
151     mat[0][3] =  SG_ZERO;
152
153     mat[1][0] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - cos_hdg * (SGfloat)sin_lon;
154     mat[1][1] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + cos_hdg * (SGfloat)cos_lon;
155     mat[1][2] =  sin_hdg * (SGfloat)cos_lat;
156     mat[1][3] =  SG_ZERO;
157
158     mat[2][0] = (SGfloat)cos_lat * (SGfloat)cos_lon;
159     mat[2][1] = (SGfloat)cos_lat * (SGfloat)sin_lon;
160     mat[2][2] = (SGfloat)sin_lat;
161     mat[2][3] =  SG_ZERO;
162
163     mat[3][0] = offset.x();
164     mat[3][1] = offset.y();
165     mat[3][2] = offset.z();
166     mat[3][3] = SG_ONE ;
167
168     sgSetCoord( obj_pos, mat );
169 }
170
171
172 // recurse an ssg tree and call removeKid() on every node from the
173 // bottom up.  Leaves the original branch in existance, but empty so
174 // it can be removed by the calling routine.
175 static void my_remove_branch( ssgBranch * branch ) {
176     for ( ssgEntity *k = branch->getKid( 0 );
177           k != NULL; 
178           k = branch->getNextKid() )
179     {
180         if ( k -> isAKindOf ( ssgTypeBranch() ) ) {
181             my_remove_branch( (ssgBranch *)k );
182             branch -> removeKid ( k );
183         } else if ( k -> isAKindOf ( ssgTypeLeaf() ) ) {
184             branch -> removeKid ( k ) ;
185         }
186     }
187 }
188
189
190 // Free "n" leaf elements of an ssg tree.  returns the number of
191 // elements freed.  An empty branch node is considered a leaf.  This
192 // is intended to spread the load of freeing a complex tile out over
193 // several frames.
194 static int fgPartialFreeSSGtree( ssgBranch *b, int n ) {
195
196 #if 0
197     // for testing: we could call the following two lines and replace
198     // the functionality of this entire function and everything will
199     // get properly freed, but it will happen all at once and could
200     // cause a huge frame rate hit.
201     ssgDeRefDelete( b );
202     return 0;
203 #endif
204
205     int num_deletes = 0;
206
207     if ( n > 0 ) {
208         // we still have some delete budget left
209         // if ( b->getNumKids() > 100 ) {
210         //     cout << "large family = " << b->getNumKids() << endl;
211         // }
212         // deleting in reverse would help if my plib patch get's
213         // applied, but for now it will make things slower.
214         // for ( int i = b->getNumKids() - 1; i >= 0 ; --i ) {
215         for ( int i = 0; i < b->getNumKids(); ++i ) {
216             ssgEntity *kid = b->getKid(i);
217             if ( kid->isAKindOf( ssgTypeBranch() ) && kid->getRef() <= 1 ) {
218                 int result = fgPartialFreeSSGtree( (ssgBranch *)kid, n );
219                 num_deletes += result;
220                 n -= result;
221                 if ( n < 0 ) {
222                     break;
223                 }
224             }
225             // remove the kid if (a) it is now empty -or- (b) it's ref
226             // count is > zero at which point we don't care if it's
227             // empty, we don't want to touch it's contents.
228             if ( kid->getNumKids() == 0 || kid->getRef() > 1 ) {
229                 b->removeKid( kid );
230                 num_deletes++;
231                 n--;
232             }
233         }
234     }
235
236     return num_deletes;
237 }
238
239
240 // Clean up the memory used by this tile and delete the arrays used by
241 // ssg as well as the whole ssg branch
242 bool FGTileEntry::free_tile() {
243     int delete_size = 100;
244     SG_LOG( SG_TERRAIN, SG_DEBUG,
245             "FREEING TILE = (" << tile_bucket << ")" );
246
247     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
248     
249     if ( !(free_tracker & NODES) ) {
250         free_tracker |= NODES;
251     } else if ( !(free_tracker & VEC_PTRS) ) {
252         free_tracker |= VEC_PTRS;
253     } else if ( !(free_tracker & TERRA_NODE) ) {
254         // delete the terrain branch (this should already have been
255         // disconnected from the scene graph)
256         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
257         if ( fgPartialFreeSSGtree( terra_transform, delete_size ) == 0 ) {
258             ssgDeRefDelete( terra_transform );
259             free_tracker |= TERRA_NODE;
260         }
261     } else if ( !(free_tracker & GROUND_LIGHTS) && gnd_lights_transform ) {
262         // delete the terrain lighting branch (this should already have been
263         // disconnected from the scene graph)
264         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING gnd_lights_transform" );
265         if ( fgPartialFreeSSGtree( gnd_lights_transform, delete_size ) == 0 ) {
266             ssgDeRefDelete( gnd_lights_transform );
267             free_tracker |= GROUND_LIGHTS;
268         }
269     } else if ( !(free_tracker & RWY_LIGHTS) && rwy_lights_selector ) {
270         // delete the runway lighting branch (this should already have
271         // been disconnected from the scene graph)
272         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING rwy_lights_selector" );
273         if ( fgPartialFreeSSGtree( rwy_lights_selector, delete_size ) == 0 ) {
274             ssgDeRefDelete( rwy_lights_selector );
275             free_tracker |= RWY_LIGHTS;
276         }
277     } else if ( !(free_tracker & TAXI_LIGHTS) && taxi_lights_selector ) {
278         // delete the taxi lighting branch (this should already have been
279         // disconnected from the scene graph)
280         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING taxi_lights_selector" );
281         if ( fgPartialFreeSSGtree( taxi_lights_selector, delete_size ) == 0 ) {
282             ssgDeRefDelete( taxi_lights_selector );
283             free_tracker |= TAXI_LIGHTS;
284         }
285     } else if ( !(free_tracker & LIGHTMAPS) ) {
286         free_tracker |= LIGHTMAPS;
287     } else {
288         return true;
289     }
290
291     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
292
293     // if we fall down to here, we still have work todo, return false
294     return false;
295 }
296
297
298 // Update the ssg transform node for this tile so it can be
299 // properly drawn relative to our (0,0,0) point
300 void FGTileEntry::prep_ssg_node( const Point3D& p, sgVec3 up, float vis) {
301     if ( !loaded ) return;
302
303     SetOffset( p );
304
305     // visibility can change from frame to frame so we update the
306     // range selector cutoff's each time.
307     terra_range->setRange( 0, SG_ZERO );
308     terra_range->setRange( 1, vis + bounding_radius );
309
310     if ( gnd_lights_range ) {
311         gnd_lights_range->setRange( 0, SG_ZERO );
312         gnd_lights_range->setRange( 1, vis * 1.5 + bounding_radius );
313     }
314
315     sgVec3 sgTrans;
316     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
317     terra_transform->setTransform( sgTrans );
318
319     if ( gnd_lights_transform ) {
320         // we need to lift the lights above the terrain to avoid
321         // z-buffer fighting.  We do this based on our altitude and
322         // the distance this tile is away from scenery center.
323
324         // we expect 'up' to be a unit vector coming in, but since we
325         // modify the value of lift_vec, we need to create a local
326         // copy.
327         sgVec3 lift_vec;
328         sgCopyVec3( lift_vec, up );
329
330         double agl;
331         agl = globals->get_current_view()->getAltitudeASL_ft()
332             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
333
334         // sgTrans just happens to be the
335         // vector from scenery center to the center of this tile which
336         // is what we want to calculate the distance of
337         sgVec3 to;
338         sgCopyVec3( to, sgTrans );
339         double dist = sgLengthVec3( to );
340
341         if ( general.get_glDepthBits() > 16 ) {
342             sgScaleVec3( lift_vec, 10.0 + agl / 100.0 + dist / 10000 );
343         } else {
344             sgScaleVec3( lift_vec, 10.0 + agl / 20.0 + dist / 5000 );
345         }
346
347         sgVec3 lt_trans;
348         sgCopyVec3( lt_trans, sgTrans );
349
350         sgAddVec3( lt_trans, lift_vec );
351         gnd_lights_transform->setTransform( lt_trans );
352
353         // select which set of lights based on sun angle
354         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
355         if ( sun_angle > 95 ) {
356             gnd_lights_brightness->select(0x04);
357         } else if ( sun_angle > 92 ) {
358             gnd_lights_brightness->select(0x02);
359         } else if ( sun_angle > 89 ) {
360             gnd_lights_brightness->select(0x01);
361         } else {
362             gnd_lights_brightness->select(0x00);
363         }
364     }
365
366     if ( rwy_lights_transform ) {
367         // we need to lift the lights above the terrain to avoid
368         // z-buffer fighting.  We do this based on our altitude and
369         // the distance this tile is away from scenery center.
370
371         sgVec3 lift_vec;
372         sgCopyVec3( lift_vec, up );
373
374         // we fudge agl by 30 meters so that the lifting function
375         // doesn't phase in until we are > 30m agl.
376         double agl;
377         agl = globals->get_current_view()->getAltitudeASL_ft()
378             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
379             - 30.0;
380         if ( agl < 0.0 ) {
381             agl = 0.0;
382         }
383         
384         if ( general.get_glDepthBits() > 16 ) {
385             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
386         } else {
387             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
388         }
389
390         sgVec3 lt_trans;
391         sgCopyVec3( lt_trans, sgTrans );
392
393         sgAddVec3( lt_trans, lift_vec );
394         rwy_lights_transform->setTransform( lt_trans );
395
396         // turn runway lights on/off based on sun angle and visibility
397         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
398         if ( sun_angle > 85 ||
399              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
400             rwy_lights_selector->select(0x01);
401         } else {
402             rwy_lights_selector->select(0x00);
403         }
404     }
405
406     if ( taxi_lights_transform ) {
407         // we need to lift the lights above the terrain to avoid
408         // z-buffer fighting.  We do this based on our altitude and
409         // the distance this tile is away from scenery center.
410
411         sgVec3 lift_vec;
412         sgCopyVec3( lift_vec, up );
413
414         // we fudge agl by 30 meters so that the lifting function
415         // doesn't phase in until we are > 30m agl.
416         double agl;
417         agl = globals->get_current_view()->getAltitudeASL_ft()
418             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
419             - 30.0;
420         if ( agl < 0.0 ) {
421             agl = 0.0;
422         }
423         
424         if ( general.get_glDepthBits() > 16 ) {
425             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
426         } else {
427             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
428         }
429
430         sgVec3 lt_trans;
431         sgCopyVec3( lt_trans, sgTrans );
432
433         sgAddVec3( lt_trans, lift_vec );
434         taxi_lights_transform->setTransform( lt_trans );
435
436         // turn taxi lights on/off based on sun angle and visibility
437         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
438         if ( sun_angle > 85 ||
439              (fgGetDouble("/environment/visibility-m") < 5000.0) ) {
440             taxi_lights_selector->select(0x01);
441         } else {
442             taxi_lights_selector->select(0x00);
443         }
444     }
445 }
446
447
448 // Set up lights rendering call backs
449 static int fgLightsPredraw( ssgEntity *e ) {
450 #if 0
451 #ifdef GL_EXT_point_parameters
452     if (glutExtensionSupported("GL_EXT_point_parameters")) {
453         static float quadratic[3] = {1.0, 0.01, 0.0001};
454         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
455         glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
456         glPointSize(4.0);
457     }
458 #endif
459 #endif
460     return true;
461 }
462
463 static int fgLightsPostdraw( ssgEntity *e ) {
464 #if 0
465 #ifdef GL_EXT_point_parameters
466     if (glutExtensionSupported("GL_EXT_point_parameters")) {
467         static float default_attenuation[3] = {1.0, 0.0, 0.0};
468         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
469                               default_attenuation);
470         glPointSize(1.0);
471     }
472 #endif
473 #endif
474     return true;
475 }
476
477
478 ssgLeaf* FGTileEntry::gen_lights( SGMaterialLib *matlib, ssgVertexArray *lights,
479                                   int inc, float bright )
480 {
481     // generate a repeatable random seed
482     float *p1 = lights->get( 0 );
483     unsigned int *seed = (unsigned int *)p1;
484     sg_srandom( *seed );
485
486     int size = lights->getNum() / inc;
487
488     // Allocate ssg structure
489     ssgVertexArray   *vl = new ssgVertexArray( size + 1 );
490     ssgNormalArray   *nl = NULL;
491     ssgTexCoordArray *tl = NULL;
492     ssgColourArray   *cl = new ssgColourArray( size + 1 );
493
494     sgVec4 color;
495     for ( int i = 0; i < lights->getNum(); ++i ) {
496         // this loop is slightly less efficient than it otherwise
497         // could be, but we want a red light to always be red, and a
498         // yellow light to always be yellow, etc. so we are trying to
499         // preserve the random sequence.
500         float zombie = sg_random();
501         if ( i % inc == 0 ) {
502             vl->add( lights->get(i) );
503
504             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
505             float factor = sg_random();
506             factor *= factor;
507
508             if ( zombie > 0.5 ) {
509                 // 50% chance of yellowish
510                 sgSetVec4( color, 0.9, 0.9, 0.3, bright - factor * 0.2 );
511             } else if ( zombie > 0.15 ) {
512                 // 35% chance of whitish
513                 sgSetVec4( color, 0.9, 0.9, 0.8, bright - factor * 0.2 );
514             } else if ( zombie > 0.05 ) {
515                 // 10% chance of orangish
516                 sgSetVec4( color, 0.9, 0.6, 0.2, bright - factor * 0.2 );
517             } else {
518                 // 5% chance of redish
519                 sgSetVec4( color, 0.9, 0.2, 0.2, bright - factor * 0.2 );
520             }
521             cl->add( color );
522         }
523     }
524
525     // create ssg leaf
526     ssgLeaf *leaf = 
527         new ssgVtxTable ( GL_POINTS, vl, nl, tl, cl );
528
529     // assign state
530     SGMaterial *mat = matlib->find( "GROUND_LIGHTS" );
531     leaf->setState( mat->get_state() );
532     leaf->setCallback( SSG_CALLBACK_PREDRAW, fgLightsPredraw );
533     leaf->setCallback( SSG_CALLBACK_POSTDRAW, fgLightsPostdraw );
534
535     return leaf;
536 }
537
538
539 bool FGTileEntry::obj_load( const string& path,
540                             ssgBranch* geometry,
541                             ssgBranch* rwy_lights,
542                             ssgBranch* taxi_lights,
543                             ssgVertexArray* ground_lights, bool is_base )
544 {
545     Point3D c;                  // returned center point
546     double br;                  // returned bounding radius
547
548     bool use_random_objects =
549         fgGetBool("/sim/rendering/random-objects", true);
550
551     // try loading binary format
552     if ( fgBinObjLoad( path, is_base,
553                        &c, &br, globals->get_matlib(), use_random_objects,
554                        geometry, rwy_lights, taxi_lights, ground_lights ) )
555     {
556         if ( is_base ) {
557             center = c;
558             bounding_radius = br;
559         }
560     } else {
561         // default to an ocean tile
562         if ( fgGenTile( path, tile_bucket, &c, &br,
563                         globals->get_matlib(), geometry ) )
564         {
565             center = c;
566             bounding_radius = br;
567         } else {
568             SG_LOG( SG_TERRAIN, SG_ALERT,
569                     "Warning: failed to generate ocean tile!" );
570         }
571     }
572
573     return (geometry != NULL);
574 }
575
576
577 void
578 FGTileEntry::load( const SGPath& base, bool is_base )
579 {
580     SG_LOG( SG_TERRAIN, SG_INFO, "load() base = " << base.str() );
581
582     // Generate names for later use
583     string index_str = tile_bucket.gen_index_str();
584
585     SGPath tile_path = base;
586     tile_path.append( tile_bucket.gen_base_path() );
587
588     SGPath basename = tile_path;
589     basename.append( index_str );
590     // string path = basename.str();
591
592     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << basename.str() );
593
594 #define FG_MAX_LIGHTS 1000
595
596     // obj_load() will generate ground lighting for us ...
597     ssgVertexArray *light_pts = new ssgVertexArray( 100 );
598
599     ssgBranch* new_tile = new ssgBranch;
600
601     // Check for master .stg (scene terra gear) file
602     SGPath stg_name = basename;
603     stg_name.concat( ".stg" );
604
605     sg_gzifstream in( stg_name.str() );
606
607     if ( in.is_open() ) {
608         string token, name;
609
610         while ( ! in.eof() ) {
611             in >> token;
612
613             if ( token == "OBJECT_BASE" ) {
614                 in >> name >> ::skipws;
615                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
616                         << " name = " << name );
617
618                 SGPath custom_path = tile_path;
619                 custom_path.append( name );
620
621                 ssgBranch *geometry = new ssgBranch;
622                 if ( obj_load( custom_path.str(),
623                                geometry, NULL, NULL, light_pts, true ) )
624                 {
625                     new_tile -> addKid( geometry );
626                 } else {
627                     delete geometry;
628                 }
629             } else if ( token == "OBJECT" ) {
630                 in >> name >> ::skipws;
631                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
632                         << " name = " << name );
633
634                 SGPath custom_path = tile_path;
635                 custom_path.append( name );
636
637                 ssgBranch *geometry = new ssgBranch;
638                 ssgBranch *rwy_lights = new ssgBranch;
639                 ssgBranch *taxi_lights = new ssgBranch;
640                 if ( obj_load( custom_path.str(),
641                                geometry, rwy_lights, taxi_lights,
642                                NULL, false ) )
643                 {
644                     if ( geometry -> getNumKids() > 0 ) {
645                         new_tile -> addKid( geometry );
646                     } else {
647                         delete geometry;
648                     }
649                     if ( rwy_lights -> getNumKids() > 0 ) {
650                         rwy_lights_transform -> addKid( rwy_lights );
651                     } else {
652                         delete rwy_lights;
653                     }
654                     if ( taxi_lights -> getNumKids() > 0 ) {
655                         taxi_lights_transform -> addKid( taxi_lights );
656                     } else {
657                         delete taxi_lights;
658                     }
659                 } else {
660                     delete geometry;
661                     delete rwy_lights;
662                     delete taxi_lights;
663                 }
664
665             } else if ( token == "OBJECT_STATIC" ||
666                         token == "OBJECT_SHARED" ) {
667                 // load object info
668                 double lon, lat, elev, hdg;
669                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
670                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
671                         << " name = " << name 
672                         << " pos = " << lon << ", " << lat
673                         << " elevation = " << elev
674                         << " heading = " << hdg );
675
676                 // object loading is deferred to main render thread,
677                 // but lets figure out the paths right now.
678                 SGPath custom_path;
679                 if ( token == "OBJECT_STATIC" )
680                     custom_path= tile_path;
681                 custom_path.append( name );
682
683                 sgCoord obj_pos;
684                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
685                 
686                 ssgTransform *obj_trans = new ssgTransform;
687                 obj_trans->setTransform( &obj_pos );
688
689                 // wire as much of the scene graph together as we can
690                 new_tile->addKid( obj_trans );
691
692                 // bump up the pending models count
693                 pending_models++;
694
695                 // push an entry onto the model load queue
696                 FGDeferredModel *dm
697                     = new FGDeferredModel( custom_path.str(), tile_path.str(),
698                                            this, obj_trans );
699                 FGTileMgr::model_ready( dm );
700             } else if ( token == "OBJECT_TAXI_SIGN" ) {
701                 // load object info
702                 double lon, lat, elev, hdg;
703                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
704                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
705                         << " name = " << name 
706                         << " pos = " << lon << ", " << lat
707                         << " elevation = " << elev
708                         << " heading = " << hdg );
709
710                 // load the object itself
711                 SGPath custom_path = tile_path;
712                 custom_path.append( name );
713
714                 sgCoord obj_pos;
715                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
716
717                 ssgTransform *obj_trans = new ssgTransform;
718                 obj_trans->setTransform( &obj_pos );
719
720                 ssgBranch *custom_obj
721                     = sgMakeTaxiSign( globals->get_matlib(),
722                                       custom_path.str(), name );
723
724                 // wire the pieces together
725                 if ( custom_obj != NULL ) {
726                     obj_trans -> addKid( custom_obj );
727                 }
728                 new_tile->addKid( obj_trans );
729             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
730                 // load object info
731                 double lon, lat, elev, hdg;
732                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
733                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
734                         << " name = " << name 
735                         << " pos = " << lon << ", " << lat
736                         << " elevation = " << elev
737                         << " heading = " << hdg );
738
739                 // load the object itself
740                 SGPath custom_path = tile_path;
741                 custom_path.append( name );
742
743                 sgCoord obj_pos;
744                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
745
746                 ssgTransform *obj_trans = new ssgTransform;
747                 obj_trans->setTransform( &obj_pos );
748
749                 ssgBranch *custom_obj
750                     = sgMakeRunwaySign( globals->get_matlib(),
751                                         custom_path.str(), name );
752
753                 // wire the pieces together
754                 if ( custom_obj != NULL ) {
755                     obj_trans -> addKid( custom_obj );
756                 }
757                 new_tile->addKid( obj_trans );
758             } else if ( token == "RWY_LIGHTS" ) {
759                 double lon, lat, hdg, len, width;
760                 string common, end1, end2;
761                 in >> lon >> lat >> hdg >> len >> width
762                    >> common >> end1 >> end2;
763                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
764                         << " pos = " << lon << ", " << lat
765                         << " hdg = " << hdg
766                         << " size = " << len << ", " << width
767                         << " codes = " << common << " "
768                         << end1 << " " << end2 );
769             } else {
770                 SG_LOG( SG_TERRAIN, SG_ALERT,
771                         "Unknown token " << token << " in "
772                         << stg_name.str() );
773                 in >> ::skipws;
774             }
775         }
776     } else {
777         // no .stg file, generate an ocean tile on the fly for this
778         // area
779         ssgBranch *geometry = new ssgBranch;
780         Point3D c;
781         double br;
782         if ( fgGenTile( basename.str(), tile_bucket, &c, &br,
783                         globals->get_matlib(), geometry ) ) {
784             center = c;
785             bounding_radius = br;
786             new_tile -> addKid( geometry );
787         } else {
788             delete geometry;
789             SG_LOG( SG_TERRAIN, SG_ALERT,
790                     "Warning: failed to generate ocean tile!" );
791         }
792     }
793
794     if ( new_tile != NULL ) {
795         terra_range->addKid( new_tile );
796     }
797
798     terra_transform->addKid( terra_range );
799
800     // calculate initial tile offset
801     SetOffset( globals->get_scenery()->get_center() );
802     sgCoord sgcoord;
803     sgSetCoord( &sgcoord,
804                 offset.x(), offset.y(), offset.z(),
805                 0.0, 0.0, 0.0 );
806     terra_transform->setTransform( &sgcoord );
807     // terrain->addKid( terra_transform );
808
809     // Add ground lights to scene graph if any exist
810     gnd_lights_transform = NULL;
811     gnd_lights_range = NULL;
812     if ( light_pts->getNum() ) {
813         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
814         gnd_lights_transform = new ssgTransform;
815         gnd_lights_range = new ssgRangeSelector;
816         gnd_lights_brightness = new ssgSelector;
817         ssgLeaf *lights;
818
819         lights = gen_lights( globals->get_matlib(), light_pts, 4, 0.7 );
820         gnd_lights_brightness->addKid( lights );
821
822         lights = gen_lights( globals->get_matlib(), light_pts, 2, 0.85 );
823         gnd_lights_brightness->addKid( lights );
824
825         lights = gen_lights( globals->get_matlib(), light_pts, 1, 1.0 );
826         gnd_lights_brightness->addKid( lights );
827
828         gnd_lights_range->addKid( gnd_lights_brightness );
829         gnd_lights_transform->addKid( gnd_lights_range );
830         gnd_lights_transform->setTransform( &sgcoord );
831     }
832
833     // Update runway lights transform
834     if ( rwy_lights_transform->getNumKids() > 0 ) {
835         rwy_lights_transform->setTransform( &sgcoord );
836     }
837
838      // Update taxi lights transform
839     if ( taxi_lights_transform->getNumKids() > 0 ) {
840         taxi_lights_transform->setTransform( &sgcoord );
841     }
842 }
843
844
845 void
846 FGTileEntry::add_ssg_nodes( ssgBranch* terrain_branch,
847                             ssgBranch* gnd_lights_branch,
848                             ssgBranch* rwy_lights_branch,
849                             ssgBranch* taxi_lights_branch )
850 {
851     // bump up the ref count so we can remove this later without
852     // having ssg try to free the memory.
853     terra_transform->ref();
854     terrain_branch->addKid( terra_transform );
855
856     SG_LOG( SG_TERRAIN, SG_DEBUG,
857             "connected a tile into scene graph.  terra_transform = "
858             << terra_transform );
859     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
860             << terra_transform->getNumParents() );
861
862     if ( gnd_lights_transform != NULL ) {
863         // bump up the ref count so we can remove this later without
864         // having ssg try to free the memory.
865         gnd_lights_transform->ref();
866         gnd_lights_branch->addKid( gnd_lights_transform );
867     }
868
869     if ( rwy_lights_transform != NULL ) {
870         // bump up the ref count so we can remove this later without
871         // having ssg try to free the memory.
872         rwy_lights_selector->ref();
873         rwy_lights_selector->addKid( rwy_lights_transform );
874         rwy_lights_branch->addKid( rwy_lights_selector );
875     }
876
877     if ( taxi_lights_transform != NULL ) {
878         // bump up the ref count so we can remove this later without
879         // having ssg try to free the memory.
880         taxi_lights_selector->ref();
881         taxi_lights_selector->addKid( taxi_lights_transform );
882         taxi_lights_branch->addKid( taxi_lights_selector );
883     }
884
885     loaded = true;
886 }
887
888
889 void
890 FGTileEntry::disconnect_ssg_nodes()
891 {
892     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
893
894     if ( ! loaded ) {
895         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
896     } else {
897         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform );
898     }
899         
900     // find the terrain branch parent
901     int pcount = terra_transform->getNumParents();
902     if ( pcount > 0 ) {
903         // find the first parent (should only be one)
904         ssgBranch *parent = terra_transform->getParent( 0 ) ;
905         if( parent ) {
906             // disconnect the tile (we previously ref()'d it so it
907             // won't get freed now)
908             parent->removeKid( terra_transform );
909         } else {
910             SG_LOG( SG_TERRAIN, SG_ALERT,
911                     "parent pointer is NULL!  Dying" );
912             exit(-1);
913         }
914     } else {
915         SG_LOG( SG_TERRAIN, SG_ALERT,
916                 "Parent count is zero for an ssg tile!  Dying" );
917         exit(-1);
918     }
919
920     // find the ground lighting branch
921     if ( gnd_lights_transform ) {
922         pcount = gnd_lights_transform->getNumParents();
923         if ( pcount > 0 ) {
924             // find the first parent (should only be one)
925             ssgBranch *parent = gnd_lights_transform->getParent( 0 ) ;
926             if( parent ) {
927                 // disconnect the light branch (we previously ref()'d
928                 // it so it won't get freed now)
929                 parent->removeKid( gnd_lights_transform );
930             } else {
931                 SG_LOG( SG_TERRAIN, SG_ALERT,
932                         "parent pointer is NULL!  Dying" );
933                 exit(-1);
934             }
935         } else {
936             SG_LOG( SG_TERRAIN, SG_ALERT,
937                     "Parent count is zero for an ssg light tile!  Dying" );
938             exit(-1);
939         }
940     }
941
942     // find the runway lighting branch
943     if ( rwy_lights_transform ) {
944         pcount = rwy_lights_transform->getNumParents();
945         if ( pcount > 0 ) {
946             // find the first parent (should only be one)
947             ssgBranch *parent = rwy_lights_transform->getParent( 0 ) ;
948             if( parent ) {
949                 // disconnect the light branch (we previously ref()'d
950                 // it so it won't get freed now)
951                 parent->removeKid( rwy_lights_transform );
952             } else {
953                 SG_LOG( SG_TERRAIN, SG_ALERT,
954                         "parent pointer is NULL!  Dying" );
955                 exit(-1);
956             }
957         } else {
958             SG_LOG( SG_TERRAIN, SG_ALERT,
959                     "Parent count is zero for an ssg light tile!  Dying" );
960             exit(-1);
961         }
962     }
963
964     // find the taxi lighting branch
965     if ( taxi_lights_transform ) {
966         pcount = taxi_lights_transform->getNumParents();
967         if ( pcount > 0 ) {
968             // find the first parent (should only be one)
969             ssgBranch *parent = taxi_lights_transform->getParent( 0 ) ;
970             if( parent ) {
971                 // disconnect the light branch (we previously ref()'d
972                 // it so it won't get freed now)
973                 parent->removeKid( taxi_lights_transform );
974             } else {
975                 SG_LOG( SG_TERRAIN, SG_ALERT,
976                         "parent pointer is NULL!  Dying" );
977                 exit(-1);
978             }
979         } else {
980             SG_LOG( SG_TERRAIN, SG_ALERT,
981                     "Parent count is zero for an ssg light tile!  Dying" );
982             exit(-1);
983         }
984     }
985 }