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