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