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