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