]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
This is step "1" of probably "many" in the process of separating out the
[flightgear.git] / src / Scenery / tileentry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <simgear/bucket/newbucket.hxx>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/math/sg_random.h>
34 #include <simgear/misc/sgstream.hxx>
35
36 #include <Aircraft/aircraft.hxx>
37 #include <Include/general.hxx>
38 #include <Main/globals.hxx>
39 #include <Main/viewer.hxx>
40 #include <Scenery/scenery.hxx>
41 #include <Time/light.hxx>
42 #include <Objects/apt_signs.hxx>
43 #include <Objects/matlib.hxx>
44 #include <Objects/newmat.hxx>
45 #include <Objects/obj.hxx>
46
47 #include "tileentry.hxx"
48 #include "tilemgr.hxx"
49
50
51 // Constructor
52 FGTileEntry::FGTileEntry ( const SGBucket& b )
53     : ncount( 0 ),
54       center( Point3D( 0.0 ) ),
55       tile_bucket( b ),
56       terra_transform( new ssgTransform ),
57       rwy_lights_transform( new ssgTransform ),
58       taxi_lights_transform( new ssgTransform ),
59       terra_range( new ssgRangeSelector ),
60       loaded(false),
61       pending_models(0),
62       free_tracker(0)
63 {
64     nodes.clear();
65
66     // update the contents
67     // if ( vec3_ptrs.size() || vec2_ptrs.size() || index_ptrs.size() ) {
68     //     SG_LOG( SG_TERRAIN, SG_ALERT, 
69     //             "Attempting to overwrite existing or"
70     //             << " not properly freed leaf data." );
71     //     exit(-1);
72     // }
73 }
74
75
76 // Destructor
77 FGTileEntry::~FGTileEntry () {
78     // cout << "nodes = " << nodes.size() << endl;;
79     // delete[] nodes;
80 }
81
82
83 #if 0
84 // Please keep this for reference.  We use Norman's optimized routine,
85 // but here is what the routine really is doing.
86 void
87 FGTileEntry::WorldCoordinate( sgCoord *obj_pos, Point3D center,
88                               double lat, double lon, double elev, double hdg)
89 {
90     // setup transforms
91     Point3D geod( lon * SGD_DEGREES_TO_RADIANS,
92                   lat * SGD_DEGREES_TO_RADIANS,
93                   elev );
94         
95     Point3D world_pos = sgGeodToCart( geod );
96     Point3D offset = world_pos - center;
97         
98     sgMat4 POS;
99     sgMakeTransMat4( POS, offset.x(), offset.y(), offset.z() );
100
101     sgVec3 obj_rt, obj_up;
102     sgSetVec3( obj_rt, 0.0, 1.0, 0.0); // Y axis
103     sgSetVec3( obj_up, 0.0, 0.0, 1.0); // Z axis
104
105     sgMat4 ROT_lon, ROT_lat, ROT_hdg;
106     sgMakeRotMat4( ROT_lon, lon, obj_up );
107     sgMakeRotMat4( ROT_lat, 90 - lat, obj_rt );
108     sgMakeRotMat4( ROT_hdg, hdg, obj_up );
109
110     sgMat4 TUX;
111     sgCopyMat4( TUX, ROT_hdg );
112     sgPostMultMat4( TUX, ROT_lat );
113     sgPostMultMat4( TUX, ROT_lon );
114     sgPostMultMat4( TUX, POS );
115
116     sgSetCoord( obj_pos, TUX );
117 }
118 #endif
119
120
121 // Norman's 'fast hack' for above
122 static void WorldCoordinate( sgCoord *obj_pos, Point3D center, double lat,
123                              double lon, double elev, double hdg )
124 {
125     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
126     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
127     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
128
129     // setup transforms
130     Point3D geod( lon_rad, lat_rad, elev );
131         
132     Point3D world_pos = sgGeodToCart( geod );
133     Point3D offset = world_pos - center;
134
135     sgMat4 mat;
136
137     SGfloat sin_lat = (SGfloat)sin( lat_rad );
138     SGfloat cos_lat = (SGfloat)cos( lat_rad );
139     SGfloat cos_lon = (SGfloat)cos( lon_rad );
140     SGfloat sin_lon = (SGfloat)sin( lon_rad );
141     SGfloat sin_hdg = (SGfloat)sin( hdg_rad ) ;
142     SGfloat cos_hdg = (SGfloat)cos( hdg_rad ) ;
143
144     mat[0][0] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - sin_hdg * (SGfloat)sin_lon;
145     mat[0][1] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + sin_hdg * (SGfloat)cos_lon;
146     mat[0][2] = -cos_hdg * (SGfloat)cos_lat;
147     mat[0][3] =  SG_ZERO;
148
149     mat[1][0] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - cos_hdg * (SGfloat)sin_lon;
150     mat[1][1] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + cos_hdg * (SGfloat)cos_lon;
151     mat[1][2] =  sin_hdg * (SGfloat)cos_lat;
152     mat[1][3] =  SG_ZERO;
153
154     mat[2][0] = (SGfloat)cos_lat * (SGfloat)cos_lon;
155     mat[2][1] = (SGfloat)cos_lat * (SGfloat)sin_lon;
156     mat[2][2] = (SGfloat)sin_lat;
157     mat[2][3] =  SG_ZERO;
158
159     mat[3][0] = offset.x();
160     mat[3][1] = offset.y();
161     mat[3][2] = offset.z();
162     mat[3][3] = SG_ONE ;
163
164     sgSetCoord( obj_pos, mat );
165 }
166
167
168 // recurse an ssg tree and call removeKid() on every node from the
169 // bottom up.  Leaves the original branch in existance, but empty so
170 // it can be removed by the calling routine.
171 static void my_remove_branch( ssgBranch * branch ) {
172     for ( ssgEntity *k = branch->getKid( 0 );
173           k != NULL; 
174           k = branch->getNextKid() )
175     {
176         if ( k -> isAKindOf ( ssgTypeBranch() ) ) {
177             my_remove_branch( (ssgBranch *)k );
178             branch -> removeKid ( k );
179         } else if ( k -> isAKindOf ( ssgTypeLeaf() ) ) {
180             branch -> removeKid ( k ) ;
181         }
182     }
183 }
184
185 // ADA
186 #define TEXRES_X 256
187 #define TEXRES_Y 256
188 unsigned char env_map[TEXRES_X][TEXRES_Y][4];
189 // SetColor & SetColor2 functions were provided by Christian Mayer (26 April 2001) - used without change
190 void setColor(float x, float y, float z, float angular_size, float r,
191 float g, float b, float a)
192 {
193     //normalize
194     float inv_length = 1.0 / sqrt(x*x + y*y + z*z);
195     x *= inv_length; y *= inv_length; z *= inv_length;
196   
197     float cos_angular_size = cos(angular_size*SG_DEGREES_TO_RADIANS);
198
199     for( int s = 0; s < TEXRES_X; s++) {
200         for( int t = 0; t < TEXRES_Y; t++) {
201
202             float s_2 = (float)s/TEXRES_X - 0.5; // centre of texture 0,0
203             float t_2 = (float)t/TEXRES_Y - 0.5; // elev
204
205             float rx, ry, rz;
206
207             if ((1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2) >= 0.0) {
208                 // sphere
209                 float m = 4.0 * sqrt(1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2);
210                 rx = m * s_2;
211                 ry = m * t_2;
212                 rz = m*m / 8.0 - 1.0;
213             } else {
214                 // singularity
215                 rx = 0.0;
216                 ry = 0.0;
217                 rz = -1.0;
218             }
219
220             float tx = rx;  //mirroring on the z=0 plane
221             float ty = ry;  //assumes that the normal is allways
222             float tz = -rz; //n(0.0, 0.0, 1.0)
223          
224             if ( cos_angular_size < (x*tx + y*ty + z*tz) ) {
225                 env_map[s][t][0] = (unsigned char) r * 255;  
226                 env_map[s][t][1] = (unsigned char) g * 255;
227                 env_map[s][t][2] = (unsigned char) b * 255;
228                 env_map[s][t][3] = (unsigned char) a * 255;
229             }
230         }
231     }
232 }
233
234 // elevation_size, float azimuth_size are the *total* angular size of the light
235 void setColor2(float elevation_size,float azimuth_size, float r, float g, float b, float a)
236 {
237     for( int s = 0; s < TEXRES_X; s++) {
238         for( int t = 0; t < TEXRES_Y; t++) {
239             float s_2 = (float)s/TEXRES_X - 0.5;
240             float t_2 = (float)t/TEXRES_Y - 0.5;
241
242             float rx, ry, rz;
243
244             if ((1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2) >= 0.0) {
245
246                 float m = 4.0 * sqrt(1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2);
247                 rx = m * s_2;
248                 ry = m * t_2;
249                 rz = m*m / 8.0 - 1.0;
250             } else {
251                 rx = 0.0;
252                 ry = 0.0;
253                 rz = -1.0;
254             }
255
256             float tx = rx;  //mirroring on the z=0 plane to reverse
257             float ty = ry;  //OpenGLs automatic mirroring
258             float tz = -rz; 
259
260             //get elevation => project t onto the x-z-plane
261             float tz_proj1 = tz / sqrt(tx*tx + tz*tz);
262             float televation = acos( -tz_proj1 ) * SG_RADIANS_TO_DEGREES;
263
264             //get azi => project t onto the y-z-plane
265             float tz_proj2 = tz / sqrt(ty*ty + tz*tz);
266             float tazimuth = acos( -tz_proj2 ) * SG_RADIANS_TO_DEGREES;
267
268             //note televation and tazimuth are the angles *between* the
269             //temporary vector and the normal (0,0,-1). They are *NOT*
270             //the elevation and azimuth angles
271
272             //square:
273             //if (((elevation_size > televation) || (elevation_size < -televation)) &&
274             //    ((azimuth_size   > tazimuth  ) || (azimuth_size   < -tazimuth  ))) 
275             //elliptical
276             if (((televation*televation) / (elevation_size*elevation_size / 4.0) +
277                  (tazimuth  *tazimuth  ) / (azimuth_size  *azimuth_size   / 4.0)) <= 1.0)
278             {
279                 env_map[s][t][0] = (unsigned char) r * 255;  
280                 env_map[s][t][1] = (unsigned char) g * 255;
281                 env_map[s][t][2] = (unsigned char) b * 255;
282                 env_map[s][t][3] = (unsigned char) a * 255;
283             }
284         }
285     }
286 }
287
288 // 23 March 2001
289 // This function performs billboarding of polygons drawn using the UP and RIGHT vectors obtained
290 // from the transpose of the MODEL_VIEW_MATRIX of the ssg_current_context. Each polygon is drawn
291 // at the coordinate array and material state as passed thro arguments.
292 void *fgBillboard( ssgBranch *lightmaps, ssgVertexArray *light_maps, ssgSimpleState *lightmap_state, float size) {
293     sgMat4 tmat;
294     sgVec3 rt, up, nrt, nup, pt, quads[4], lmaps[4];
295
296     ssgGetModelviewMatrix ( tmat );
297     sgSetVec3 (rt, tmat[0][0], tmat[1][0], tmat[2][0]);
298     sgSetVec3 (up, tmat[0][1], tmat[1][1], tmat[2][1]);
299     sgSetVec3 (nrt, tmat[0][0], tmat[1][0], tmat[2][0]);
300     sgSetVec3 (nup, tmat[0][1], tmat[1][1], tmat[2][1]);
301     sgNegateVec3 (nrt);
302     sgNegateVec3 (nup);
303
304     sgAddVec3 (quads[0], nrt, nup);
305     sgAddVec3 (quads[1],  rt, nup);
306     sgAddVec3 (quads[2],  rt,  up);
307     sgAddVec3 (quads[3], nrt,  up);
308
309     sgScaleVec3 (quads[0], size);
310     sgScaleVec3 (quads[1], size);
311     sgScaleVec3 (quads[2], size);
312     sgScaleVec3 (quads[3], size);
313
314     sgVec4 color;
315     sgSetVec4( color, 1.0, 1.0, 0.0, 1.0 );
316
317     sgVec2 texcoords[4];
318     sgSetVec2( texcoords[0], 1.0, 1.0 );
319     sgSetVec2( texcoords[1], 0.0, 1.0 );
320     sgSetVec2( texcoords[2], 0.0, 0.0 );
321     sgSetVec2( texcoords[3], 1.0, 0.0 );
322     
323     for (int j = 0; j < 4; j++ ) {
324         sgCopyVec3(lmaps[j]     ,quads[j]);
325     }
326
327     for ( int i = 0; i < light_maps->getNum(); ++i ) {
328         // Allocate ssg structure
329         ssgVertexArray   *vl = new ssgVertexArray( 1 );
330         ssgTexCoordArray *tl = new ssgTexCoordArray( 1 );
331         ssgColourArray   *cl = new ssgColourArray( 1 );
332
333         float *temp = light_maps->get(i);
334         sgSetVec3(pt,temp[0],temp[1],temp[2]);
335
336         for (int k=0; k<4; k++) {
337             sgAddVec3( quads[k],lmaps[k], pt );                 
338             vl->add(quads[k]);
339             tl->add(texcoords[k]);
340             cl->add(color);
341         }
342
343         ssgLeaf *leaf = NULL;
344         leaf = new ssgVtxTable ( GL_TRIANGLE_FAN, vl, NULL, tl, cl );
345         leaf->setState( lightmap_state );
346         lightmaps->addKid( leaf );
347     }
348
349     return NULL;
350 }
351
352 ssgBranch* FGTileEntry::gen_runway_lights( ssgVertexArray *points,ssgVertexArray *normal,
353                                            ssgVertexArray *dir, int type[]) 
354 {
355
356     //************** HARD CODED RUNWAY LIGHT TEXTURES BEGIN ************************    
357     GLuint texEdge, texTaxi, texTouchdown;
358     GLuint texThreshold;
359     GLuint texVasi, texWhite, texRed, texGreen, texYellow;
360
361     //VASI lights
362     setColor(0.0,0.0,1.0,360.0, 0, 0, 0, 0);
363     setColor2(10.0, 40.0, 1, 1, 1, 1);
364     setColor2(6.0, 40.0, 1, 0.5, 0.5, 1);
365     setColor2(5.0, 40.0, 1, 0, 0, 1);
366     glGenTextures(1, &texVasi);
367     glBindTexture(GL_TEXTURE_2D, texVasi);
368     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
369     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
370     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
371     ssgSimpleState *vasi_state;
372     vasi_state = new ssgSimpleState();
373     vasi_state->ref();
374     vasi_state->setTexture( texVasi );
375     vasi_state->disable( GL_LIGHTING );
376     vasi_state->enable( GL_TEXTURE_2D );
377     vasi_state->setShadeModel( GL_SMOOTH );
378
379     //EDGE
380     setColor(0.0,0.0,-1.0,180.0, 1, 1, 0.5, 1);
381     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
382     glGenTextures(1, &texEdge);
383     glBindTexture(GL_TEXTURE_2D, texEdge);
384     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
385     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
386     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
387     ssgSimpleState *edge_state;
388     edge_state = new ssgSimpleState();
389     edge_state->ref();
390     edge_state->setTexture( texEdge );
391     edge_state->disable( GL_LIGHTING );
392     edge_state->enable( GL_TEXTURE_2D );
393     edge_state->setShadeModel( GL_SMOOTH );
394
395     //TOUCHDOWN
396     setColor(0.0,0.0,-1.0,180.0, 0, 1, 0, 1);
397     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
398     glGenTextures(1, &texTouchdown);
399     glBindTexture(GL_TEXTURE_2D, texTouchdown);
400     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
401     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
402     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
403     ssgSimpleState *touchdown_state;
404     touchdown_state = new ssgSimpleState();
405     touchdown_state->ref();
406     touchdown_state->setTexture( texTouchdown );
407     touchdown_state->disable( GL_LIGHTING );
408     touchdown_state->enable( GL_TEXTURE_2D );
409     touchdown_state->setShadeModel( GL_SMOOTH );
410         
411     //THRESHOLD
412     setColor(0.0,0.0,-1.0,180.0, 1, 0, 0, 1);
413     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
414     glGenTextures(1, &texThreshold);
415     glBindTexture(GL_TEXTURE_2D, texThreshold);
416     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
417     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
418     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
419     ssgSimpleState *threshold_state;
420     threshold_state = new ssgSimpleState();
421     threshold_state->ref();
422     threshold_state->setTexture( texThreshold );
423     threshold_state->disable( GL_LIGHTING );
424     threshold_state->enable( GL_TEXTURE_2D );
425     threshold_state->setShadeModel( GL_SMOOTH );
426
427     //TAXI
428     setColor(0.0,0.0,-1.0,180.0, 0, 0, 1, 1);
429     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
430     glGenTextures(1, &texTaxi);
431     glBindTexture(GL_TEXTURE_2D, texTaxi);
432     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
433     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
434     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
435     ssgSimpleState *taxi_state;
436     taxi_state = new ssgSimpleState();
437     taxi_state->ref();
438     taxi_state->setTexture( texTaxi );
439     taxi_state->disable( GL_LIGHTING );
440     taxi_state->enable( GL_TEXTURE_2D );
441     taxi_state->setShadeModel( GL_SMOOTH );
442
443     //WHITE
444     setColor(0.0,0.0,-1.0,180.0, 1, 1, 1, 1);
445     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
446     glGenTextures(1, &texWhite);
447     glBindTexture(GL_TEXTURE_2D, texWhite);
448     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
449     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
450     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
451     ssgSimpleState *white_state;
452     white_state = new ssgSimpleState();
453     white_state->ref();
454     white_state->setTexture( texWhite );
455     white_state->disable( GL_LIGHTING );
456     white_state->enable( GL_TEXTURE_2D );
457     white_state->setShadeModel( GL_SMOOTH );
458
459     //RED
460     setColor(0.0,0.0,-1.0,180.0, 1, 0, 0, 1);
461     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
462     glGenTextures(1, &texRed);
463     glBindTexture(GL_TEXTURE_2D, texRed);
464     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
465     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
466     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
467     ssgSimpleState *red_state;
468     red_state = new ssgSimpleState();
469     red_state->ref();
470     red_state->setTexture( texRed );
471     red_state->disable( GL_LIGHTING );
472     red_state->enable( GL_TEXTURE_2D );
473     red_state->setShadeModel( GL_SMOOTH );
474
475     //GREEN
476     setColor(0.0,0.0,-1.0,180.0, 0, 1, 0, 1);
477     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
478     glGenTextures(1, &texGreen);
479     glBindTexture(GL_TEXTURE_2D, texGreen);
480     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
481     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
482     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
483     ssgSimpleState *green_state;
484     green_state = new ssgSimpleState();
485     green_state->ref();
486     green_state->setTexture( texGreen );
487     green_state->disable( GL_LIGHTING );
488     green_state->enable( GL_TEXTURE_2D );
489     green_state->setShadeModel( GL_SMOOTH );
490
491     //YELLOW
492     setColor(0.0,0.0,-1.0,180.0, 1, 1, 0, 1);
493     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
494     glGenTextures(1, &texYellow);
495     glBindTexture(GL_TEXTURE_2D, texYellow);
496     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
497     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
498     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
499     ssgSimpleState *yellow_state;
500     yellow_state = new ssgSimpleState();
501     yellow_state->ref();
502     yellow_state->setTexture( texYellow );
503     yellow_state->disable( GL_LIGHTING );
504     yellow_state->enable( GL_TEXTURE_2D );
505     yellow_state->setShadeModel( GL_SMOOTH );
506 //************** HARD CODED RUNWAY LIGHT TEXTURES END ************************    
507
508     ssgBranch *runway_lights = new ssgBranch;
509     sgVec3 v2,v3,inf,side;
510
511     ssgLeaf *leaf1 = NULL;
512     ssgLeaf *leaf2 = NULL;
513     ssgLeaf *leaf7 = NULL;
514     ssgLeaf *leaf8 = NULL;
515     ssgLeaf *leaf9 = NULL;
516
517     ssgVertexArray   *vlw = new ssgVertexArray( 1 );
518     ssgNormalArray   *nlw = new ssgNormalArray( 1 );
519     ssgVertexArray   *vlt = new ssgVertexArray( 1 );
520     ssgNormalArray   *nlt = new ssgNormalArray( 1 );
521     ssgVertexArray   *vlr = new ssgVertexArray( 1 );
522     ssgNormalArray   *nlr = new ssgNormalArray( 1 );
523     ssgVertexArray   *vlg = new ssgVertexArray( 1 );
524     ssgNormalArray   *nlg = new ssgNormalArray( 1 );
525     ssgVertexArray   *vly = new ssgVertexArray( 1 );
526     ssgNormalArray   *nly = new ssgNormalArray( 1 );
527
528     for ( int i = 0; i < points->getNum()-1; i=i++ ) {
529
530         // Allocate ssg structure
531         ssgVertexArray   *vl = new ssgVertexArray( 1 );
532         ssgNormalArray   *nl = new ssgNormalArray( 1 );
533         ssgVertexArray   *vl1 = new ssgVertexArray( 1 );
534         ssgNormalArray   *nl1 = new ssgNormalArray( 1 );
535
536         float *n1 = normal->get(i);
537         float *d1 = dir->get(i);
538
539         /* TEMPORARY CODE BEGIN 
540            // calculate normal using 1st, 2nd & last vertices of the group
541            sgVec3 n1;
542            sgMakeNormal (n1, points->get(0), points->get(1), points->get(points->getNum()-1) );
543            sgVec3 d1;
544            sgSubVec3(d1,points->get(1),points->get(0));
545            printf("%f %f %f\n",n1[0],n1[1],n1[2]);
546            printf("%f %f %f\n",d1[0],d1[1],d1[2]);
547            type[i] = 2;
548            ----TEMPORARY CODE END */
549
550
551         sgNormaliseVec3 ( n1 );
552         sgNormaliseVec3 ( d1 );
553         sgVec3 d2;
554         d2[0] = -d1[0];
555         d2[1] = -d1[1];
556         d2[2] = -d1[2];
557
558         sgVectorProductVec3(side,n1,d1);
559         sgScaleVec3 (inf,n1,-50);
560         sgScaleVec3 (side,5);
561
562         float *v1 = points->get(i);
563         sgAddVec3(v2,v1,inf);
564         sgAddVec3(v3,v2,side);
565
566         if ( type[i] == 1) {        //POINT,WHITE
567
568             vlw->add(v1);
569             nlw->add(d1);
570
571         } else if (type[i] == 2) {  //POINT,TAXI
572
573             vlt->add(v1);
574             nlt->add(d1);
575
576         } else if (type[i] == 3) {  //SINGLE POLYGON,VASI
577
578             vl->add(v1);
579             nl->add(d1);
580             vl->add(v3);
581             nl->add(d1);
582             vl->add(v2);
583             nl->add(d1);
584
585             ssgLeaf *leaf3 = NULL;
586             leaf3 = new ssgVtxTable ( GL_POLYGON, vl, nl, NULL, NULL );
587             leaf3->setState( vasi_state );
588             runway_lights->addKid( leaf3 );
589
590         } else if (type[i] == 4) {  //BACK-TO-BACK POLYGONS,TOUCHDOWN/THRESHOLD
591                 
592             vl->add(v1);
593             nl->add(d1);
594             vl->add(v3);
595             nl->add(d1);
596             vl->add(v2);
597             nl->add(d1);
598
599             vl1->add(v3);
600             nl1->add(d2);
601             vl1->add(v1);
602             nl1->add(d2);
603             vl1->add(v2);
604             nl1->add(d2);
605
606             ssgLeaf *leaf41 = NULL;
607             leaf41 = new ssgVtxTable ( GL_POLYGON, vl, nl, NULL, NULL );
608             leaf41->setState( touchdown_state );
609             runway_lights->addKid( leaf41 );
610
611             ssgLeaf *leaf42 = NULL;
612             leaf42 = new ssgVtxTable ( GL_POLYGON, vl1, nl1, NULL, NULL );
613             leaf42->setState( threshold_state );
614             runway_lights->addKid( leaf42 );
615
616         } else if ( type[i] == 5) {        //POINT,WHITE, SEQUENCE LIGHTS (RABBIT)
617
618             vl->add(v1);
619             nl->add(d1);
620             ssgLeaf *leaf5 = NULL;
621             leaf5 = new ssgVtxTable ( GL_POINTS, vl, nl, NULL, NULL );
622             leaf5->setState( white_state );
623             lightmaps_sequence->addKid (leaf5);
624
625         } else if ( type[i] == 6) {        //POINT,WHITE, SEQUENCE LIGHTS (RABBIT)
626
627             vl->add(v1);
628             nl->add(d1);
629             ssgLeaf *leaf6 = NULL;
630             leaf6 = new ssgVtxTable ( GL_POINTS, vl, nl, NULL, NULL );
631             leaf6->setState( yellow_state );
632             ols_transform->addKid (leaf6);
633             // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
634             //                  lightmaps_sequence->addKid (leaf6);
635             // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
636
637         } else if (type[i] == 7) {  //POINT,RED
638
639             vlr->add(v1);
640             nlr->add(d1);
641
642         } else if (type[i] == 8) {  //POINT,GREEN
643
644             vlg->add(v1);
645             nlg->add(d1);
646
647         } else if (type[i] == 9) {  //POINT,YELLOW
648
649             vly->add(v1);
650             nly->add(d1);
651
652         }
653
654     }
655
656     leaf1 = new ssgVtxTable ( GL_POINTS, vlw, nlw, NULL, NULL );
657     leaf1->setState( white_state );
658     runway_lights->addKid( leaf1 );
659
660     leaf2 = new ssgVtxTable ( GL_POINTS, vlt, nlt, NULL, NULL );
661     leaf2->setState( taxi_state );
662     runway_lights->addKid( leaf2 );
663         
664     leaf7 = new ssgVtxTable ( GL_POINTS, vlr, nlr, NULL, NULL );
665     leaf7->setState( red_state );
666     runway_lights->addKid( leaf7 );
667
668     leaf8 = new ssgVtxTable ( GL_POINTS, vlg, nlg, NULL, NULL );
669     leaf8->setState( green_state );
670     // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
671     ols_transform->ref();
672     lightmaps_sequence->addKid (ols_transform);
673     // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
674     lightmaps_sequence->addKid (leaf8);
675
676     leaf9 = new ssgVtxTable ( GL_POINTS, vly, nly, NULL, NULL );
677     leaf9->setState( yellow_state );
678     runway_lights->addKid( leaf9 );
679
680     lightmaps_sequence->select(0xFFFFFF);       
681     return runway_lights;
682 }
683 // ADA
684         
685
686 // Free "n" leaf elements of an ssg tree.  returns the number of
687 // elements freed.  An empty branch node is considered a leaf.  This
688 // is intended to spread the load of freeing a complex tile out over
689 // several frames.
690 static int fgPartialFreeSSGtree( ssgBranch *b, int n ) {
691 #if 0
692     // for testing: we could call the following two lines and replace
693     // the functionality of this entire function and everything will
694     // get properly freed, but it will happen all at once and could
695     // cause a huge frame rate hit.
696     ssgDeRefDelete( b );
697     return 0;
698 #endif
699
700     int num_deletes = 0;
701
702     if ( n > 0 ) {
703         // we still have some delete budget left
704         // if ( b->getNumKids() > 100 ) {
705         //     cout << "large family = " << b->getNumKids() << endl;
706         // }
707         // deleting in reverse would help if my plib patch get's
708         // applied, but for now it will make things slower.
709         // for ( int i = b->getNumKids() - 1; i >= 0 ; --i ) {
710         for ( int i = 0; i < b->getNumKids(); ++i ) {
711             ssgEntity *kid = b->getKid(i);
712             if ( kid->isAKindOf( ssgTypeBranch() ) && kid->getRef() <= 1 ) {
713                 int result = fgPartialFreeSSGtree( (ssgBranch *)kid, n );
714                 num_deletes += result;
715                 n -= result;
716                 if ( n < 0 ) {
717                     break;
718                 }
719             }
720             // remove the kid if (a) it is now empty -or- (b) it's ref
721             // count is > zero at which point we don't care if it's
722             // empty, we don't want to touch it's contents.
723             if ( kid->getNumKids() == 0 || kid->getRef() > 1 ) {
724                 b->removeKid( kid );
725                 num_deletes++;
726                 n--;
727             }
728         }
729     }
730
731     return num_deletes;
732 }
733
734
735 // Clean up the memory used by this tile and delete the arrays used by
736 // ssg as well as the whole ssg branch
737 bool FGTileEntry::free_tile() {
738     int i;
739     int delete_size = 100;
740     SG_LOG( SG_TERRAIN, SG_DEBUG,
741             "FREEING TILE = (" << tile_bucket << ")" );
742
743     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
744     
745     if ( !(free_tracker & NODES) ) {
746         SG_LOG( SG_TERRAIN, SG_DEBUG,
747                 "  deleting " << nodes.size() << " nodes" );
748         nodes.clear();
749
750         free_tracker |= NODES;
751     } else if ( !(free_tracker & VEC_PTRS) ) {
752         // delete the vector pointers
753         SG_LOG( SG_TERRAIN, SG_DEBUG,
754                 "  deleting (leaf data) vertex, normal, and "
755                 << " texture coordinate arrays" );
756
757         for ( i = 0; i < (int)vec3_ptrs.size(); ++i ) {
758             delete [] vec3_ptrs[i];
759         }
760         vec3_ptrs.clear();
761
762         for ( i = 0; i < (int)vec2_ptrs.size(); ++i ) {
763             delete [] vec2_ptrs[i];
764         }
765         vec2_ptrs.clear();
766
767         for ( i = 0; i < (int)index_ptrs.size(); ++i ) {
768             delete index_ptrs[i];
769         }
770         index_ptrs.clear();
771
772         free_tracker |= VEC_PTRS;
773     } else if ( !(free_tracker & TERRA_NODE) ) {
774         // delete the terrain branch (this should already have been
775         // disconnected from the scene graph)
776         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
777         if ( fgPartialFreeSSGtree( terra_transform, delete_size ) == 0 ) {
778             ssgDeRefDelete( terra_transform );
779             free_tracker |= TERRA_NODE;
780         }
781     } else if ( !(free_tracker & GROUND_LIGHTS) && gnd_lights_transform ) {
782         // delete the terrain lighting branch (this should already have been
783         // disconnected from the scene graph)
784         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING gnd_lights_transform" );
785         if ( fgPartialFreeSSGtree( gnd_lights_transform, delete_size ) == 0 ) {
786             ssgDeRefDelete( gnd_lights_transform );
787             free_tracker |= GROUND_LIGHTS;
788         }
789     } else if ( !(free_tracker & RWY_LIGHTS) && rwy_lights_transform ) {
790         // delete the runway lighting branch (this should already have
791         // been disconnected from the scene graph)
792         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING rwy_lights_transform" );
793         if ( fgPartialFreeSSGtree( rwy_lights_transform, delete_size ) == 0 ) {
794             ssgDeRefDelete( rwy_lights_transform );
795             free_tracker |= RWY_LIGHTS;
796         }
797     } else if ( !(free_tracker & TAXI_LIGHTS) && taxi_lights_transform ) {
798         // delete the taxi lighting branch (this should already have been
799         // disconnected from the scene graph)
800         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING taxi_lights_transform" );
801         if ( fgPartialFreeSSGtree( taxi_lights_transform, delete_size ) == 0 ) {
802             ssgDeRefDelete( taxi_lights_transform );
803             free_tracker |= TAXI_LIGHTS;
804         }
805     } else if ( !(free_tracker & LIGHTMAPS) && lightmaps_transform ) {
806         // ADA
807         // delete the terrain lighting branch (this should already have been
808         // disconnected from the scene graph)
809         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING lightmaps_transform" );
810         if ( fgPartialFreeSSGtree( lightmaps_transform, delete_size ) == 0 ) {
811             ssgDeRefDelete( lightmaps_transform );
812             free_tracker |= LIGHTMAPS;
813         }
814     } else {
815         return true;
816     }
817
818     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
819
820     // if we fall down to here, we still have work todo, return false
821     return false;
822 }
823
824
825 // Update the ssg transform node for this tile so it can be
826 // properly drawn relative to our (0,0,0) point
827 void FGTileEntry::prep_ssg_node( const Point3D& p, sgVec3 up, float vis) {
828     if ( !loaded ) return;
829
830     SetOffset( p );
831
832     // visibility can change from frame to frame so we update the
833     // range selector cutoff's each time.
834     terra_range->setRange( 0, SG_ZERO );
835     terra_range->setRange( 1, vis + bounding_radius );
836
837     if ( gnd_lights_range ) {
838         gnd_lights_range->setRange( 0, SG_ZERO );
839         gnd_lights_range->setRange( 1, vis * 1.5 + bounding_radius );
840     }
841
842     sgVec3 sgTrans;
843     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
844     terra_transform->setTransform( sgTrans );
845
846     if ( gnd_lights_transform ) {
847         // we need to lift the lights above the terrain to avoid
848         // z-buffer fighting.  We do this based on our altitude and
849         // the distance this tile is away from scenery center.
850
851         // we expect 'up' to be a unit vector coming in, but since we
852         // modify the value of lift_vec, we need to create a local
853         // copy.
854         sgVec3 lift_vec;
855         sgCopyVec3( lift_vec, up );
856
857         double agl;
858         agl = globals->get_current_view()->getAltitudeASL_ft()
859             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
860
861         // sgTrans just happens to be the
862         // vector from scenery center to the center of this tile which
863         // is what we want to calculate the distance of
864         sgVec3 to;
865         sgCopyVec3( to, sgTrans );
866         double dist = sgLengthVec3( to );
867
868         if ( general.get_glDepthBits() > 16 ) {
869             sgScaleVec3( lift_vec, 10.0 + agl / 100.0 + dist / 10000 );
870         } else {
871             sgScaleVec3( lift_vec, 10.0 + agl / 20.0 + dist / 5000 );
872         }
873
874         sgVec3 lt_trans;
875         sgCopyVec3( lt_trans, sgTrans );
876
877         sgAddVec3( lt_trans, lift_vec );
878         gnd_lights_transform->setTransform( lt_trans );
879
880         // select which set of lights based on sun angle
881         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
882         if ( sun_angle > 95 ) {
883             gnd_lights_brightness->select(0x04);
884         } else if ( sun_angle > 92 ) {
885             gnd_lights_brightness->select(0x02);
886         } else if ( sun_angle > 89 ) {
887             gnd_lights_brightness->select(0x01);
888         } else {
889             gnd_lights_brightness->select(0x00);
890         }
891     }
892
893     if ( rwy_lights_transform ) {
894         // we need to lift the lights above the terrain to avoid
895         // z-buffer fighting.  We do this based on our altitude and
896         // the distance this tile is away from scenery center.
897
898         sgVec3 lift_vec;
899         sgCopyVec3( lift_vec, up );
900
901         // we fudge agl by 30 meters so that the lifting function
902         // doesn't phase in until we are > 30m agl.
903         double agl;
904         agl = globals->get_current_view()->getAltitudeASL_ft()
905             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
906             - 30.0;
907         if ( agl < 0.0 ) {
908             agl = 0.0;
909         }
910         
911         if ( general.get_glDepthBits() > 16 ) {
912             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
913         } else {
914             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
915         }
916
917         sgVec3 lt_trans;
918         sgCopyVec3( lt_trans, sgTrans );
919
920         sgAddVec3( lt_trans, lift_vec );
921         rwy_lights_transform->setTransform( lt_trans );
922
923         // select which set of lights based on sun angle
924         // float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
925         // if ( sun_angle > 95 ) {
926         //     gnd_lights_brightness->select(0x04);
927         // } else if ( sun_angle > 92 ) {
928         //     gnd_lights_brightness->select(0x02);
929         // } else if ( sun_angle > 89 ) {
930         //     gnd_lights_brightness->select(0x01);
931         // } else {
932         //     gnd_lights_brightness->select(0x00);
933         // }
934     }
935
936     if ( taxi_lights_transform ) {
937         // we need to lift the lights above the terrain to avoid
938         // z-buffer fighting.  We do this based on our altitude and
939         // the distance this tile is away from scenery center.
940
941         sgVec3 lift_vec;
942         sgCopyVec3( lift_vec, up );
943
944         // we fudge agl by 30 meters so that the lifting function
945         // doesn't phase in until we are > 30m agl.
946         double agl;
947         agl = globals->get_current_view()->getAltitudeASL_ft()
948             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev()
949             - 30.0;
950         if ( agl < 0.0 ) {
951             agl = 0.0;
952         }
953         
954         if ( general.get_glDepthBits() > 16 ) {
955             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 );
956         } else {
957             sgScaleVec3( lift_vec, 0.0 + agl / 150.0 );
958         }
959
960         sgVec3 lt_trans;
961         sgCopyVec3( lt_trans, sgTrans );
962
963         sgAddVec3( lt_trans, lift_vec );
964         taxi_lights_transform->setTransform( lt_trans );
965
966         // select which set of lights based on sun angle
967         // float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
968         // if ( sun_angle > 95 ) {
969         //     gnd_lights_brightness->select(0x04);
970         // } else if ( sun_angle > 92 ) {
971         //     gnd_lights_brightness->select(0x02);
972         // } else if ( sun_angle > 89 ) {
973         //     gnd_lights_brightness->select(0x01);
974         // } else {
975         //     gnd_lights_brightness->select(0x00);
976         // }
977     }
978
979     // ADA
980     // Transform & Render runway lights - 23 Mar 2001
981     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
982     if ( lightmaps_transform ) {
983         static unsigned int selectnode = 0;
984         // Run-time extension check.
985         if (!glutExtensionSupported("GL_EXT_point_parameters")) {
986             //use lightmaps on billboarded polygons
987         } else {
988             // using GL_EXT_point_parameters
989                 
990             // This part is same as ground-lights code above by Curt
991             sgVec3 lift_vec;
992             sgCopyVec3( lift_vec, up );
993             
994             double agl1;
995             agl1 = globals->get_current_view()->getAltitudeASL_ft()
996                 * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
997
998             // sgTrans just happens to be the
999             // vector from scenery center to the center of this tile which
1000             // is what we want to calculate the distance of
1001             sgVec3 to1;
1002             sgCopyVec3( to1, sgTrans );
1003             double dist1 = sgLengthVec3( to1 );
1004
1005             if ( general.get_glDepthBits() > 16 ) {
1006                 sgScaleVec3( lift_vec, 0.0 + agl1 / 2000.0 + dist1 / 10000 );
1007             } else {
1008                 sgScaleVec3( lift_vec, 0.0 + agl1 / 20.0 + dist1 / 5000 );
1009             }
1010             sgAddVec3( sgTrans, lift_vec );
1011             lightmaps_transform->setTransform( sgTrans );
1012
1013             float sun_angle1 = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1014             if ( (sun_angle1 > 89) ) {
1015                 lightmaps_brightness->select(0x01);
1016                 selectnode *=2;
1017                 selectnode = selectnode | 0x000001;
1018                 if (selectnode > 0xFFFFFF) selectnode = 1;
1019                 lightmaps_sequence->select(selectnode);
1020             } else {
1021                 lightmaps_brightness->select(0x00);
1022                 lightmaps_sequence->select(0x000000);
1023             } 
1024         } // end of GL_EXT_point_parameters section
1025
1026     } // end of runway lights section
1027     // ADA
1028
1029 }
1030
1031
1032 // Set up lights rendering call backs
1033 static int fgLightsPredraw( ssgEntity *e ) {
1034 #if 0
1035 #ifdef GL_EXT_point_parameters
1036     if (glutExtensionSupported("GL_EXT_point_parameters")) {
1037         static float quadratic[3] = {1.0, 0.01, 0.0001};
1038         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
1039         glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
1040         glPointSize(4.0);
1041     }
1042 #endif
1043 #endif
1044     return true;
1045 }
1046
1047 static int fgLightsPostdraw( ssgEntity *e ) {
1048 #if 0
1049 #ifdef GL_EXT_point_parameters
1050     if (glutExtensionSupported("GL_EXT_point_parameters")) {
1051         static float default_attenuation[3] = {1.0, 0.0, 0.0};
1052         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
1053                               default_attenuation);
1054         glPointSize(1.0);
1055     }
1056 #endif
1057 #endif
1058     return true;
1059 }
1060
1061
1062 ssgLeaf* FGTileEntry::gen_lights( ssgVertexArray *lights, int inc, float bright ) {
1063     // generate a repeatable random seed
1064     float *p1 = lights->get( 0 );
1065     unsigned int *seed = (unsigned int *)p1;
1066     sg_srandom( *seed );
1067
1068     int size = lights->getNum() / inc;
1069
1070     // Allocate ssg structure
1071     ssgVertexArray   *vl = new ssgVertexArray( size + 1 );
1072     ssgNormalArray   *nl = NULL;
1073     ssgTexCoordArray *tl = NULL;
1074     ssgColourArray   *cl = new ssgColourArray( size + 1 );
1075
1076     sgVec4 color;
1077     for ( int i = 0; i < lights->getNum(); ++i ) {
1078         // this loop is slightly less efficient than it otherwise
1079         // could be, but we want a red light to always be red, and a
1080         // yellow light to always be yellow, etc. so we are trying to
1081         // preserve the random sequence.
1082         float zombie = sg_random();
1083         if ( i % inc == 0 ) {
1084             vl->add( lights->get(i) );
1085
1086             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
1087             float factor = sg_random();
1088             factor *= factor;
1089
1090             if ( zombie > 0.5 ) {
1091                 // 50% chance of yellowish
1092                 sgSetVec4( color, 0.9, 0.9, 0.3, bright - factor * 0.2 );
1093             } else if ( zombie > 0.15 ) {
1094                 // 35% chance of whitish
1095                 sgSetVec4( color, 0.9, 0.9, 0.8, bright - factor * 0.2 );
1096             } else if ( zombie > 0.05 ) {
1097                 // 10% chance of orangish
1098                 sgSetVec4( color, 0.9, 0.6, 0.2, bright - factor * 0.2 );
1099             } else {
1100                 // 5% chance of redish
1101                 sgSetVec4( color, 0.9, 0.2, 0.2, bright - factor * 0.2 );
1102             }
1103             cl->add( color );
1104         }
1105     }
1106
1107     // create ssg leaf
1108     ssgLeaf *leaf = 
1109         new ssgVtxTable ( GL_POINTS, vl, nl, tl, cl );
1110
1111     // assign state
1112     FGNewMat *newmat = material_lib.find( "GROUND_LIGHTS" );
1113     leaf->setState( newmat->get_state() );
1114     leaf->setCallback( SSG_CALLBACK_PREDRAW, fgLightsPredraw );
1115     leaf->setCallback( SSG_CALLBACK_POSTDRAW, fgLightsPostdraw );
1116
1117     return leaf;
1118 }
1119
1120
1121 bool FGTileEntry::obj_load( const std::string& path,
1122                             ssgBranch* geometry,
1123                             ssgBranch* rwy_lights,
1124                             ssgBranch* taxi_lights,
1125                             ssgVertexArray* ground_lights, bool is_base )
1126 {
1127     Point3D c;                  // returned center point
1128     double br;                  // returned bounding radius
1129
1130     // try loading binary format
1131     if ( fgBinObjLoad( path, is_base,
1132                        &c, &br, geometry,
1133                        rwy_lights, taxi_lights, ground_lights ) )
1134     {
1135         if ( is_base ) {
1136             center = c;
1137             bounding_radius = br;
1138         }
1139     } else {
1140         // default to an ocean tile
1141         if ( fgGenTile( path, tile_bucket, &c, &br, geometry ) ) {
1142             center = c;
1143             bounding_radius = br;
1144         } else {
1145             SG_LOG( SG_TERRAIN, SG_ALERT,
1146                     "Warning: failed to generate ocean tile!" );
1147         }
1148     }
1149
1150     return (geometry != NULL);
1151 }
1152
1153
1154 void
1155 FGTileEntry::load( const SGPath& base, bool is_base )
1156 {
1157     SG_LOG( SG_TERRAIN, SG_INFO, "load() base = " << base.str() );
1158
1159     // Generate names for later use
1160     string index_str = tile_bucket.gen_index_str();
1161
1162     SGPath tile_path = base;
1163     tile_path.append( tile_bucket.gen_base_path() );
1164
1165     SGPath basename = tile_path;
1166     basename.append( index_str );
1167     // string path = basename.str();
1168
1169     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << basename.str() );
1170
1171 #define FG_MAX_LIGHTS 1000
1172
1173     // obj_load() will generate ground lighting for us ...
1174     ssgVertexArray *light_pts = new ssgVertexArray( 100 );
1175
1176     // ADA
1177     ssgVertexArray *lights_rway = new ssgVertexArray( 100 );
1178     ssgVertexArray *lights_dir = new ssgVertexArray( 100 );
1179     ssgVertexArray *lights_normal = new ssgVertexArray( 100 );
1180     int lights_type[FG_MAX_LIGHTS];
1181     // ADA
1182
1183     ssgBranch* new_tile = new ssgBranch;
1184
1185     // Check for master .stg (scene terra gear) file
1186     SGPath stg_name = basename;
1187     stg_name.concat( ".stg" );
1188
1189     sg_gzifstream in( stg_name.str() );
1190
1191     if ( in.is_open() ) {
1192         string token, name;
1193
1194         while ( ! in.eof() ) {
1195             in >> token;
1196
1197             if ( token == "OBJECT_BASE" ) {
1198                 in >> name >> ::skipws;
1199                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1200                         << " name = " << name );
1201
1202                 SGPath custom_path = tile_path;
1203                 custom_path.append( name );
1204
1205                 ssgBranch *geometry = new ssgBranch;
1206                 if ( obj_load( custom_path.str(),
1207                                geometry, NULL, NULL, light_pts, true ) )
1208                 {
1209                     new_tile -> addKid( geometry );
1210                 } else {
1211                     delete geometry;
1212                 }
1213             } else if ( token == "OBJECT" ) {
1214                 in >> name >> ::skipws;
1215                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1216                         << " name = " << name );
1217
1218                 SGPath custom_path = tile_path;
1219                 custom_path.append( name );
1220
1221                 ssgBranch *geometry = new ssgBranch;
1222                 ssgBranch *rwy_lights = new ssgBranch;
1223                 ssgBranch *taxi_lights = new ssgBranch;
1224                 if ( obj_load( custom_path.str(),
1225                                geometry, rwy_lights, taxi_lights,
1226                                NULL, false ) )
1227                 {
1228                     if ( geometry -> getNumKids() > 0 ) {
1229                         new_tile -> addKid( geometry );
1230                     } else {
1231                         delete geometry;
1232                     }
1233                     if ( rwy_lights -> getNumKids() > 0 ) {
1234                         rwy_lights_transform -> addKid( rwy_lights );
1235                     } else {
1236                         delete rwy_lights;
1237                     }
1238                     if ( taxi_lights -> getNumKids() > 0 ) {
1239                         taxi_lights_transform -> addKid( taxi_lights );
1240                     } else {
1241                         delete taxi_lights;
1242                     }
1243                 } else {
1244                     delete geometry;
1245                     delete rwy_lights;
1246                     delete taxi_lights;
1247                 }
1248
1249             } else if ( token == "OBJECT_STATIC" ||
1250                         token == "OBJECT_SHARED" ) {
1251                 // load object info
1252                 double lon, lat, elev, hdg;
1253                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1254                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1255                         << " name = " << name 
1256                         << " pos = " << lon << ", " << lat
1257                         << " elevation = " << elev
1258                         << " heading = " << hdg );
1259
1260                 // object loading is deferred to main render thread,
1261                 // but lets figure out the paths right now.
1262                 SGPath custom_path;
1263                 if ( token == "OBJECT_STATIC" )
1264                     custom_path= tile_path;
1265                 custom_path.append( name );
1266
1267                 sgCoord obj_pos;
1268                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1269                 
1270                 ssgTransform *obj_trans = new ssgTransform;
1271                 obj_trans->setTransform( &obj_pos );
1272
1273                 // wire as much of the scene graph together as we can
1274                 new_tile->addKid( obj_trans );
1275
1276                 // bump up the pending models count
1277                 pending_models++;
1278
1279                 // push an entry onto the model load queue
1280                 FGDeferredModel *dm
1281                     = new FGDeferredModel( custom_path.str(), tile_path.str(),
1282                                            this, obj_trans );
1283                 FGTileMgr::model_ready( dm );
1284             } else if ( token == "OBJECT_TAXI_SIGN" ) {
1285                 // load object info
1286                 double lon, lat, elev, hdg;
1287                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1288                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1289                         << " name = " << name 
1290                         << " pos = " << lon << ", " << lat
1291                         << " elevation = " << elev
1292                         << " heading = " << hdg );
1293
1294                 // load the object itself
1295                 SGPath custom_path = tile_path;
1296                 custom_path.append( name );
1297
1298                 sgCoord obj_pos;
1299                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1300
1301                 ssgTransform *obj_trans = new ssgTransform;
1302                 obj_trans->setTransform( &obj_pos );
1303
1304                 ssgBranch *custom_obj
1305                     = gen_taxi_sign( custom_path.str(), name );
1306
1307                 // wire the pieces together
1308                 if ( custom_obj != NULL ) {
1309                     obj_trans -> addKid( custom_obj );
1310                 }
1311                 new_tile->addKid( obj_trans );
1312             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
1313                 // load object info
1314                 double lon, lat, elev, hdg;
1315                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1316                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1317                         << " name = " << name 
1318                         << " pos = " << lon << ", " << lat
1319                         << " elevation = " << elev
1320                         << " heading = " << hdg );
1321
1322                 // load the object itself
1323                 SGPath custom_path = tile_path;
1324                 custom_path.append( name );
1325
1326                 sgCoord obj_pos;
1327                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1328
1329                 ssgTransform *obj_trans = new ssgTransform;
1330                 obj_trans->setTransform( &obj_pos );
1331
1332                 ssgBranch *custom_obj
1333                     = gen_runway_sign( custom_path.str(), name );
1334
1335                 // wire the pieces together
1336                 if ( custom_obj != NULL ) {
1337                     obj_trans -> addKid( custom_obj );
1338                 }
1339                 new_tile->addKid( obj_trans );
1340             } else if ( token == "RWY_LIGHTS" ) {
1341                 double lon, lat, hdg, len, width;
1342                 string common, end1, end2;
1343                 in >> lon >> lat >> hdg >> len >> width
1344                    >> common >> end1 >> end2;
1345                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1346                         << " pos = " << lon << ", " << lat
1347                         << " hdg = " << hdg
1348                         << " size = " << len << ", " << width
1349                         << " codes = " << common << " "
1350                         << end1 << " " << end2 );
1351             } else {
1352                 SG_LOG( SG_TERRAIN, SG_ALERT,
1353                         "Unknown token " << token << " in "
1354                         << stg_name.str() );
1355                 in >> ::skipws;
1356             }
1357         }
1358     } else {
1359         // no .stg file, generate an ocean tile on the fly for this
1360         // area
1361         ssgBranch *geometry = new ssgBranch;
1362         Point3D c;
1363         double br;
1364         if ( fgGenTile( basename.str(), tile_bucket, &c, &br, geometry ) ) {
1365             center = c;
1366             bounding_radius = br;
1367             new_tile -> addKid( geometry );
1368         } else {
1369             delete geometry;
1370             SG_LOG( SG_TERRAIN, SG_ALERT,
1371                     "Warning: failed to generate ocean tile!" );
1372         }
1373     }
1374
1375     if ( new_tile != NULL ) {
1376         terra_range->addKid( new_tile );
1377     }
1378
1379     terra_transform->addKid( terra_range );
1380
1381     // calculate initial tile offset
1382     SetOffset( globals->get_scenery()->get_center() );
1383     sgCoord sgcoord;
1384     sgSetCoord( &sgcoord,
1385                 offset.x(), offset.y(), offset.z(),
1386                 0.0, 0.0, 0.0 );
1387     terra_transform->setTransform( &sgcoord );
1388     // terrain->addKid( terra_transform );
1389
1390     // Add ground lights to scene graph if any exist
1391     gnd_lights_transform = NULL;
1392     gnd_lights_range = NULL;
1393     if ( light_pts->getNum() ) {
1394         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
1395         gnd_lights_transform = new ssgTransform;
1396         gnd_lights_range = new ssgRangeSelector;
1397         gnd_lights_brightness = new ssgSelector;
1398         ssgLeaf *lights;
1399
1400         lights = gen_lights( light_pts, 4, 0.7 );
1401         gnd_lights_brightness->addKid( lights );
1402
1403         lights = gen_lights( light_pts, 2, 0.85 );
1404         gnd_lights_brightness->addKid( lights );
1405
1406         lights = gen_lights( light_pts, 1, 1.0 );
1407         gnd_lights_brightness->addKid( lights );
1408
1409         gnd_lights_range->addKid( gnd_lights_brightness );
1410         gnd_lights_transform->addKid( gnd_lights_range );
1411         gnd_lights_transform->setTransform( &sgcoord );
1412     }
1413
1414     // Add runway lights to scene graph if any exist
1415     if ( rwy_lights_transform->getNumKids() > 0 ) {
1416         SG_LOG( SG_TERRAIN, SG_DEBUG, "adding runway lights" );
1417         rwy_lights_transform->setTransform( &sgcoord );
1418     }
1419
1420      // Add taxi lights to scene graph if any exist
1421     if ( taxi_lights_transform->getNumKids() > 0 ) {
1422         SG_LOG( SG_TERRAIN, SG_DEBUG, "adding taxi lights" );
1423         taxi_lights_transform->setTransform( &sgcoord );
1424     }
1425
1426     // ADA
1427     // Create runway lights - 23 Mar 2001
1428     lightmaps_transform = NULL;
1429     lightmaps_sequence = NULL;
1430     ols_transform = NULL;
1431     //    lightmaps_range = NULL;
1432
1433     if ( lights_rway->getNum() ) {
1434         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating airport lights" );
1435         lightmaps_transform = new ssgTransform;
1436         //      lightmaps_range = new ssgRangeSelector;
1437         lightmaps_brightness = new ssgSelector;
1438         lightmaps_sequence = new ssgSelector;
1439         ols_transform = new ssgTransform;
1440         ssgBranch *lightmaps_branch;
1441
1442         // call function to generate the runway lights
1443         lightmaps_branch = gen_runway_lights( lights_rway, 
1444                                               lights_normal, lights_dir, lights_type);
1445         lightmaps_brightness->addKid( lightmaps_branch );
1446         
1447         // build the runway lights' scene
1448         //    lightmaps_range->addKid( lightmaps_brightness ); //dont know why this doesnt work !!
1449         //      lightmaps_transform->addKid( lightmaps_range );    //dont know why this doesnt work !!
1450         lightmaps_transform->addKid( lightmaps_brightness );
1451         lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1452         lightmaps_transform->addKid( lightmaps_sequence );
1453         lightmaps_transform->setTransform( &sgcoord );
1454     }
1455     // ADA
1456 }
1457
1458
1459 void
1460 FGTileEntry::add_ssg_nodes( ssgBranch* terrain_branch,
1461                             ssgBranch* gnd_lights_branch,
1462                             ssgBranch* rwy_lights_branch,
1463                             ssgBranch* taxi_lights_branch )
1464 {
1465     // bump up the ref count so we can remove this later without
1466     // having ssg try to free the memory.
1467     terra_transform->ref();
1468     terrain_branch->addKid( terra_transform );
1469
1470     SG_LOG( SG_TERRAIN, SG_DEBUG,
1471             "connected a tile into scene graph.  terra_transform = "
1472             << terra_transform );
1473     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
1474             << terra_transform->getNumParents() );
1475
1476     if ( gnd_lights_transform != NULL ) {
1477         // bump up the ref count so we can remove this later without
1478         // having ssg try to free the memory.
1479         gnd_lights_transform->ref();
1480         gnd_lights_branch->addKid( gnd_lights_transform );
1481     }
1482
1483     if ( rwy_lights_transform != NULL ) {
1484         // bump up the ref count so we can remove this later without
1485         // having ssg try to free the memory.
1486         rwy_lights_transform->ref();
1487         rwy_lights_branch->addKid( rwy_lights_transform );
1488     }
1489
1490     if ( taxi_lights_transform != NULL ) {
1491         // bump up the ref count so we can remove this later without
1492         // having ssg try to free the memory.
1493         taxi_lights_transform->ref();
1494         taxi_lights_branch->addKid( taxi_lights_transform );
1495     }
1496
1497     // ADA
1498     if ( lightmaps_transform != 0 ) {
1499         // bump up the ref count so we can remove this later without
1500         // having ssg try to free the memory.
1501         lightmaps_transform->ref();
1502         gnd_lights_branch->addKid( lightmaps_transform );
1503     }
1504     // ADA
1505
1506     loaded = true;
1507 }
1508
1509
1510 void
1511 FGTileEntry::disconnect_ssg_nodes()
1512 {
1513     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
1514
1515     if ( ! loaded ) {
1516         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
1517     } else {
1518         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform );
1519     }
1520         
1521     // find the terrain branch parent
1522     int pcount = terra_transform->getNumParents();
1523     if ( pcount > 0 ) {
1524         // find the first parent (should only be one)
1525         ssgBranch *parent = terra_transform->getParent( 0 ) ;
1526         if( parent ) {
1527             // disconnect the tile (we previously ref()'d it so it
1528             // won't get freed now)
1529             parent->removeKid( terra_transform );
1530         } else {
1531             SG_LOG( SG_TERRAIN, SG_ALERT,
1532                     "parent pointer is NULL!  Dying" );
1533             exit(-1);
1534         }
1535     } else {
1536         SG_LOG( SG_TERRAIN, SG_ALERT,
1537                 "Parent count is zero for an ssg tile!  Dying" );
1538         exit(-1);
1539     }
1540
1541     // find the ground lighting branch
1542     if ( gnd_lights_transform ) {
1543         pcount = gnd_lights_transform->getNumParents();
1544         if ( pcount > 0 ) {
1545             // find the first parent (should only be one)
1546             ssgBranch *parent = gnd_lights_transform->getParent( 0 ) ;
1547             if( parent ) {
1548                 // disconnect the light branch (we previously ref()'d
1549                 // it so it won't get freed now)
1550                 parent->removeKid( gnd_lights_transform );
1551             } else {
1552                 SG_LOG( SG_TERRAIN, SG_ALERT,
1553                         "parent pointer is NULL!  Dying" );
1554                 exit(-1);
1555             }
1556         } else {
1557             SG_LOG( SG_TERRAIN, SG_ALERT,
1558                     "Parent count is zero for an ssg light tile!  Dying" );
1559             exit(-1);
1560         }
1561     }
1562
1563     // find the runway lighting branch
1564     if ( rwy_lights_transform ) {
1565         pcount = rwy_lights_transform->getNumParents();
1566         if ( pcount > 0 ) {
1567             // find the first parent (should only be one)
1568             ssgBranch *parent = rwy_lights_transform->getParent( 0 ) ;
1569             if( parent ) {
1570                 // disconnect the light branch (we previously ref()'d
1571                 // it so it won't get freed now)
1572                 parent->removeKid( rwy_lights_transform );
1573             } else {
1574                 SG_LOG( SG_TERRAIN, SG_ALERT,
1575                         "parent pointer is NULL!  Dying" );
1576                 exit(-1);
1577             }
1578         } else {
1579             SG_LOG( SG_TERRAIN, SG_ALERT,
1580                     "Parent count is zero for an ssg light tile!  Dying" );
1581             exit(-1);
1582         }
1583     }
1584
1585     // find the taxi lighting branch
1586     if ( taxi_lights_transform ) {
1587         pcount = taxi_lights_transform->getNumParents();
1588         if ( pcount > 0 ) {
1589             // find the first parent (should only be one)
1590             ssgBranch *parent = taxi_lights_transform->getParent( 0 ) ;
1591             if( parent ) {
1592                 // disconnect the light branch (we previously ref()'d
1593                 // it so it won't get freed now)
1594                 parent->removeKid( taxi_lights_transform );
1595             } else {
1596                 SG_LOG( SG_TERRAIN, SG_ALERT,
1597                         "parent pointer is NULL!  Dying" );
1598                 exit(-1);
1599             }
1600         } else {
1601             SG_LOG( SG_TERRAIN, SG_ALERT,
1602                     "Parent count is zero for an ssg light tile!  Dying" );
1603             exit(-1);
1604         }
1605     }
1606
1607     // ADA
1608     //runway lights - 23 Mar 2001
1609     // Delete runway lights and free memory
1610     if ( lightmaps_transform ) {
1611         // delete the runway lighting branch
1612         pcount = lightmaps_transform->getNumParents();
1613         if ( pcount > 0 ) {
1614             // find the first parent (should only be one)
1615             ssgBranch *parent = lightmaps_transform->getParent( 0 ) ;
1616             if( parent ) {
1617                 parent->removeKid( lightmaps_transform );
1618                 lightmaps_transform = NULL;
1619             } else {
1620                 SG_LOG( SG_TERRAIN, SG_ALERT,
1621                         "lightmaps parent pointer is NULL!  Dying" );
1622                 exit(-1);
1623             }
1624         } else {
1625             SG_LOG( SG_TERRAIN, SG_ALERT,
1626                     "Parent count is zero for an ssg lightmap tile!  Dying" );
1627             exit(-1);
1628         }
1629     }
1630     // ADA
1631 }