]> git.mxchange.org Git - flightgear.git/blob - Scenery/tilemgr.cxx
f956bf1f5f5ee16db5132ac88e334d0778047dba
[flightgear.git] / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
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 // (Log is kept at end of this file)
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #ifdef HAVE_WINDOWS_H
30 #  include <windows.h>
31 #endif
32
33 #include <GL/glut.h>
34 #include <XGL/xgl.h>
35
36 #include <Aircraft/aircraft.hxx>
37
38 #include <Bucket/bucketutils.hxx>
39 #include <Debug/logstream.hxx>
40 #include <Include/fg_constants.h>
41 #include <Main/options.hxx>
42 #include <Main/views.hxx>
43 #include <Math/fg_geodesy.hxx>
44 #include <Math/mat3.h>
45 #include <Math/point3d.hxx>
46 #include <Math/polar3d.hxx>
47 #include <Math/vector.hxx>
48 #include <Objects/material.hxx>
49 #include <Objects/obj.hxx>
50 #include <Weather/weather.hxx>
51
52 #include "scenery.hxx"
53 #include "tile.hxx"
54 #include "tilecache.hxx"
55 #include "tilemgr.hxx"
56
57
58 // to test clipping speedup in fgTileMgrRender()
59 #if defined ( USE_FAST_FOV_CLIP )
60   // #define TEST_FOV_CLIP
61   // #define TEST_ELEV
62 #endif
63
64
65 #define FG_LOCAL_X_Y         81  // max(o->tile_diameter) ** 2
66
67 #define FG_SQUARE( X ) ( (X) * (X) )
68
69 #if defined(USE_MEM) || defined(WIN32)
70 #  define FG_MEM_COPY(to,from,n)        memcpy(to, from, n)
71 #else
72 #  define FG_MEM_COPY(to,from,n)        bcopy(from, to, n)
73 #endif
74
75 // closest (potentially viewable) tiles, centered on current tile.
76 // This is an array of pointers to cache indexes.
77 int tiles[FG_LOCAL_X_Y];
78
79
80 // Initialize the Tile Manager subsystem
81 int fgTileMgrInit( void ) {
82     FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
83
84     // load default material library
85     material_mgr.load_lib();
86
87     return 1;
88 }
89
90
91 // load a tile
92 void fgTileMgrLoadTile( const fgBUCKET& p, int *index) {
93     fgTILECACHE *c;
94
95     c = &global_tile_cache;
96
97     FG_LOG( FG_TERRAIN, FG_DEBUG, "Updating for bucket " << p );
98     
99     // if not in cache, load tile into the next available slot
100     *index = c->exists(p);
101     if ( *index < 0 ) {
102         *index = c->next_avail();
103         c->fill_in(*index, p);
104     }
105
106     FG_LOG( FG_TERRAIN, FG_DEBUG, "Selected cache index: " << *index );
107 }
108
109
110 // Calculate shortest distance from point to line
111 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp, 
112                                        MAT3vec d )
113 {
114     MAT3vec p, p0;
115     double dist;
116
117     p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
118     p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
119
120     dist = fgPointLineSquared(p, p0, d);
121
122     // cout << "dist = " << dist << endl;
123
124     return(dist);
125 }
126
127
128 // Determine scenery altitude.  Normally this just happens when we
129 // render the scene, but we'd also like to be able to do this
130 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
131 // Returns result in meters.
132 double
133 fgTileMgrCurElevNEW( const fgBUCKET& p ) {
134     fgTILE *t;
135     fgFRAGMENT *frag_ptr;
136     Point3D abs_view_pos = current_view.get_abs_view_pos();
137     Point3D earth_center(0.0);
138     Point3D result;
139     MAT3vec local_up;
140     double dist, lat_geod, alt, sea_level_r;
141     int index;
142
143     local_up[0] = abs_view_pos.x();
144     local_up[1] = abs_view_pos.y();
145     local_up[2] = abs_view_pos.z();
146
147     // Find current translation offset
148     // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
149     index = global_tile_cache.exists(p);
150     if ( index < 0 ) {
151         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
152         return 0.0;
153     }
154
155     t = global_tile_cache.get_tile(index);
156
157     scenery.next_center = t->center;
158     
159     FG_LOG( FG_TERRAIN, FG_DEBUG, 
160             "Current bucket = " << p << "  Index = " << fgBucketGenIndex(&p) );
161     FG_LOG( FG_TERRAIN, FG_DEBUG,
162             "abs_view_pos = " << abs_view_pos );
163
164     // calculate tile offset
165     // x = (t->offset.x = t->center.x - scenery.center.x);
166     // y = (t->offset.y = t->center.y - scenery.center.y);
167     // z = (t->offset.z = t->center.z - scenery.center.z);
168     
169     // calc current terrain elevation calculate distance from
170     // vertical tangent line at current position to center of
171     // tile.
172         
173     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
174        point_line_dist_squared(&(t->offset), &(v->view_pos), 
175        v->local_up), t->bounding_radius); */
176
177     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
178     if ( dist < FG_SQUARE(t->bounding_radius) ) {
179
180         // traverse fragment list for tile
181         fgTILE::FragmentIterator current = t->begin();
182         fgTILE::FragmentIterator last = t->end();
183
184         for ( ; current != last; ++current ) {
185             frag_ptr = &(*current);
186             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
187                point_line_dist_squared( &(frag_ptr->center), 
188                &abs_view_pos), local_up),
189                frag_ptr->bounding_radius); */
190
191             dist = point_line_dist_squared( frag_ptr->center,
192                                             abs_view_pos,
193                                             local_up);
194             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
195                 if ( frag_ptr->intersect( abs_view_pos, 
196                                           earth_center, 0, result ) ) {
197                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
198                             result );
199                     // compute geocentric coordinates of tile center
200                     Point3D pp = fgCartToPolar3d(result);
201                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
202                     // convert to geodetic coordinates
203                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
204                                  &alt, &sea_level_r);
205
206                     // printf("alt = %.2f\n", alt);
207                     // exit since we found an intersection
208                     if ( alt > -9999.0 ) {
209                         // printf("returning alt\n");
210                         return alt;
211                     } else {
212                         // printf("returning 0\n");
213                         return 0.0;
214                     }
215                 }
216             }
217         }
218     }
219
220     FG_LOG( FG_TERRAIN, FG_INFO, "(new) no terrain intersection found" );
221
222     return 0.0;
223 }
224
225
226 // Determine scenery altitude.  Normally this just happens when we
227 // render the scene, but we'd also like to be able to do this
228 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
229 // Returns result in meters.
230 double
231 fgTileMgrCurElev( double lon, double lat, const Point3D& abs_view_pos ) {
232     fgTILECACHE *c;
233     fgTILE *t;
234     // fgVIEW *v;
235     fgFRAGMENT *frag_ptr;
236     fgBUCKET p;
237     Point3D earth_center(0.0);
238     Point3D result;
239     MAT3vec local_up;
240     double dist, lat_geod, alt, sea_level_r;
241     // double x, y, z;
242     int index;
243
244     c = &global_tile_cache;
245     // v = &current_view;
246
247     local_up[0] = abs_view_pos.x();
248     local_up[1] = abs_view_pos.y();
249     local_up[2] = abs_view_pos.z();
250
251     FG_LOG( FG_TERRAIN, FG_DEBUG, "Absolute view pos = " << abs_view_pos );
252
253     // Find current translation offset
254     fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
255     index = c->exists(p);
256     if ( index < 0 ) {
257         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
258         return 0.0;
259     }
260
261     t = c->get_tile(index);
262
263     scenery.next_center = t->center;
264     
265     FG_LOG( FG_TERRAIN, FG_DEBUG, 
266             "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
267             << ")  Current bucket = " << p 
268             << "  Index = " << fgBucketGenIndex(&p) );
269
270     // calculate tile offset
271     // x = (t->offset.x = t->center.x - scenery.center.x);
272     // y = (t->offset.y = t->center.y - scenery.center.y);
273     // z = (t->offset.z = t->center.z - scenery.center.z);
274     
275     // calc current terrain elevation calculate distance from
276     // vertical tangent line at current position to center of
277     // tile.
278         
279     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
280        point_line_dist_squared(&(t->offset), &(v->view_pos), 
281        v->local_up), t->bounding_radius); */
282
283     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
284     if ( dist < FG_SQUARE(t->bounding_radius) ) {
285
286         // traverse fragment list for tile
287         fgTILE::FragmentIterator current = t->begin();
288         fgTILE::FragmentIterator last = t->end();
289
290         for ( ; current != last; ++current ) {
291             frag_ptr = &(*current);
292             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
293                point_line_dist_squared( &(frag_ptr->center), 
294                &abs_view_pos), local_up),
295                frag_ptr->bounding_radius); */
296
297             dist = point_line_dist_squared( frag_ptr->center,
298                                             abs_view_pos,
299                                             local_up);
300             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
301                 if ( frag_ptr->intersect( abs_view_pos, 
302                                           earth_center, 0, result ) ) {
303                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
304                             result );
305                     // compute geocentric coordinates of tile center
306                     Point3D pp = fgCartToPolar3d(result);
307                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
308                     // convert to geodetic coordinates
309                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
310                                  &alt, &sea_level_r);
311
312                     // printf("alt = %.2f\n", alt);
313                     // exit since we found an intersection
314                     if ( alt > -9999.0 ) {
315                         // printf("returning alt\n");
316                         return alt;
317                     } else {
318                         // printf("returning 0\n");
319                         return 0.0;
320                     }
321                 }
322             }
323         }
324     }
325
326     FG_LOG( FG_TERRAIN, FG_INFO, "(old) no terrain intersection found" );
327
328     return 0.0;
329 }
330
331
332 // given the current lon/lat, fill in the array of local chunks.  If
333 // the chunk isn't already in the cache, then read it from disk.
334 int fgTileMgrUpdate( void ) {
335     fgTILECACHE *c;
336     FGState *f;
337     fgBUCKET p1, p2;
338     static fgBUCKET p_last = {-1000, 0, 0, 0};
339     int tile_diameter;
340     int i, j, dw, dh;
341
342     c = &global_tile_cache;
343     f = current_aircraft.fdm_state;
344
345     tile_diameter = current_options.get_tile_diameter();
346
347     fgBucketFind( f->get_Longitude() * RAD_TO_DEG,
348                   f->get_Latitude() * RAD_TO_DEG, &p1);
349     dw = tile_diameter / 2;
350     dh = tile_diameter / 2;
351
352     if ( p1 == p_last ) {
353         // same bucket as last time
354         FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
355     } else if ( p_last.lon == -1000 ) {
356         // First time through, initialize the system and load all
357         // relavant tiles
358
359         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
360         FG_LOG( FG_TERRAIN, FG_INFO, "  First time through ... " );
361         FG_LOG( FG_TERRAIN, FG_INFO, "  Updating Tile list for " << p1 );
362         FG_LOG( FG_TERRAIN, FG_INFO, "  Loading " 
363                 << tile_diameter * tile_diameter << " tiles" );
364
365         // wipe/initialize tile cache
366         c->init();
367
368         // build the local area list and update cache
369         for ( j = 0; j < tile_diameter; j++ ) {
370             for ( i = 0; i < tile_diameter; i++ ) {
371                 fgBucketOffset(&p1, &p2, i - dw, j - dh);
372                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + i]);
373             }
374         }
375     } else {
376         // We've moved to a new bucket, we need to scroll our
377         // structures, and load in the new tiles
378
379         // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
380         // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
381         // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
382
383         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
384
385         if ( (p1.lon > p_last.lon) ||
386              ( (p1.lon == p_last.lon) && (p1.x > p_last.x) ) ) {
387             FG_LOG( FG_TERRAIN, FG_INFO, 
388                     "  Loading " << tile_diameter << "tiles" );
389             for ( j = 0; j < tile_diameter; j++ ) {
390                 // scrolling East
391                 for ( i = 0; i < tile_diameter - 1; i++ ) {
392                     tiles[(j*tile_diameter) + i] = 
393                         tiles[(j*tile_diameter) + i + 1];
394                 }
395                 // load in new column
396                 fgBucketOffset(&p_last, &p2, dw + 1, j - dh);
397                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 
398                                              tile_diameter - 1]);
399             }
400         } else if ( (p1.lon < p_last.lon) ||
401                     ( (p1.lon == p_last.lon) && (p1.x < p_last.x) ) ) {
402             FG_LOG( FG_TERRAIN, FG_INFO, 
403                     "  Loading " << tile_diameter << "tiles" );
404             for ( j = 0; j < tile_diameter; j++ ) {
405                 // scrolling West
406                 for ( i = tile_diameter - 1; i > 0; i-- ) {
407                     tiles[(j*tile_diameter) + i] = 
408                         tiles[(j*tile_diameter) + i - 1];
409                 }
410                 // load in new column
411                 fgBucketOffset(&p_last, &p2, -dw - 1, j - dh);
412                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 0]);
413             }
414         }
415
416         if ( (p1.lat > p_last.lat) ||
417              ( (p1.lat == p_last.lat) && (p1.y > p_last.y) ) ) {
418             FG_LOG( FG_TERRAIN, FG_INFO, 
419                     "  Loading " << tile_diameter << "tiles" );
420             for ( i = 0; i < tile_diameter; i++ ) {
421                 // scrolling North
422                 for ( j = 0; j < tile_diameter - 1; j++ ) {
423                     tiles[(j * tile_diameter) + i] =
424                         tiles[((j+1) * tile_diameter) + i];
425                 }
426                 // load in new column
427                 fgBucketOffset(&p_last, &p2, i - dw, dh + 1);
428                 fgTileMgrLoadTile( p2, &tiles[((tile_diameter-1) * 
429                                                tile_diameter) + i]);
430             }
431         } else if ( (p1.lat < p_last.lat) ||
432                     ( (p1.lat == p_last.lat) && (p1.y < p_last.y) ) ) {
433             FG_LOG( FG_TERRAIN, FG_INFO, 
434                     "  Loading " << tile_diameter << "tiles" );
435             for ( i = 0; i < tile_diameter; i++ ) {
436                 // scrolling South
437                 for ( j = tile_diameter - 1; j > 0; j-- ) {
438                     tiles[(j * tile_diameter) + i] = 
439                         tiles[((j-1) * tile_diameter) + i];
440                 }
441                 // load in new column
442                 fgBucketOffset(&p_last, &p2, i - dw, -dh - 1);
443                 fgTileMgrLoadTile( p2, &tiles[0 + i]);
444             }
445         }
446     }
447
448     // find our current elevation (feed in the current bucket to save work)
449     Point3D geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
450     Point3D tmp_abs_view_pos = fgGeodToCart(geod_pos);
451
452     scenery.cur_elev = 
453         fgTileMgrCurElev( f->get_Longitude(), f->get_Latitude(), 
454                           tmp_abs_view_pos );
455
456     p_last.lon = p1.lon;
457     p_last.lat = p1.lat;
458     p_last.x = p1.x;
459     p_last.y = p1.y;
460
461     return 1;
462 }
463
464
465 // Calculate if point/radius is inside view frustum
466 static int viewable( const Point3D& cp, double radius ) {
467     int viewable = 1; // start by assuming it's viewable
468     double x1, y1;
469
470 /********************************/
471 #if defined( USE_FAST_FOV_CLIP ) // views.hxx
472 /********************************/
473         
474     MAT3vec eye;        
475     double *mat;
476     double x, y, z;
477
478     x = cp.x();
479     y = cp.y();
480     z = cp.z();
481         
482     mat = (double *)(current_view.get_WORLD_TO_EYE());
483         
484     eye[2] =  x*mat[2] + y*mat[6] + z*mat[10] + mat[14];
485         
486     // Check near and far clip plane
487     if( ( eye[2] > radius ) ||
488         ( eye[2] + radius + current_weather.get_visibility() < 0) )
489     {
490         return(0);
491     }
492         
493     eye[0] = (x*mat[0] + y*mat[4] + z*mat[8] + mat[12])
494         * current_view.get_slope_x();
495
496     // check right and left clip plane (from eye perspective)
497     x1 = radius * current_view.get_fov_x_clip();
498     if( (eye[2] > -(eye[0]+x1)) || (eye[2] > (eye[0]-x1)) )
499     {
500         return(0);
501     }
502         
503     eye[1] = (x*mat[1] + y*mat[5] + z*mat[9] + mat[13]) 
504         * current_view.get_slope_y();
505
506     // check bottom and top clip plane (from eye perspective)
507     y1 = radius * current_view.get_fov_y_clip();
508     if( (eye[2] > -(eye[1]+y1)) || (eye[2] > (eye[1]-y1)) )
509     {
510         return(0);
511     }
512
513 /********************************/      
514 #else // DO NOT USE_FAST_FOV_CLIP
515 /********************************/      
516
517     fgVIEW *v;
518     MAT3hvec world, eye;
519     double x0, slope;
520
521     v = &current_view;
522
523     MAT3_SET_HVEC(world, cp->x, cp->y, cp->z, 1.0);
524     // MAT3mult_vec(eye, world, v->WORLD_TO_EYE);
525     // printf( "\nworld -> eye = %.2f %.2f %.2f  radius = %.2f\n", 
526     //         eye[0], eye[1], eye[2], radius);
527
528     // Use lazy evaluation for calculating eye hvec.
529 #define vec world
530 #define mat v->WORLD_TO_EYE
531     eye[2] = vec[0]*mat[0][2]+vec[1]*mat[1][2]+vec[2]*mat[2][2]+mat[3][2];
532
533     // Check near clip plane
534     if ( eye[2] > radius ) {
535         return(0);
536     }
537
538     // Check far clip plane
539     if ( eye[2] + radius < -current_weather.get_visibility() ) {
540         return(0);
541     }
542
543     // check right clip plane (from eye perspective)
544     // y = m * (x - x0) = equation of a line intercepting X axis at x0
545     x1 = v->cos_fov_x * radius;
546     y1 = v->sin_fov_x * radius;
547     slope = v->slope_x;
548     eye[0] = vec[0]*mat[0][0]+vec[1]*mat[1][0]+vec[2]*mat[2][0]+mat[3][0];
549
550     if ( eye[2] > ((slope * (eye[0] - x1)) + y1) ) {
551         return( false );
552     }
553
554     // check left clip plane (from eye perspective)
555     if ( eye[2] > -((slope * (eye[0] + x1)) - y1) ) {
556         return( false );
557     }
558
559     // check bottom clip plane (from eye perspective)
560     x1 = -(v->cos_fov_y) * radius;
561     y1 = v->sin_fov_y * radius;
562     slope = v->slope_y;
563     eye[1] = vec[0]*mat[0][1]+vec[1]*mat[1][1]+vec[2]*mat[2][1]+mat[3][1];
564 #undef vec
565 #undef mat
566
567     if ( eye[2] > ((slope * (eye[1] - x1)) + y1) ) {
568         return( false );
569     }
570
571     // check top clip plane (from eye perspective)
572     if ( eye[2] > -((slope * (eye[1] + x1)) - y1) ) {
573         return( false );
574     }
575
576 #endif // defined( USE_FAST_FOV_CLIP )
577         
578     return(viewable);
579 }
580
581
582 // NEW 
583
584 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
585 //      calculate distance from vertical tangent line at
586 //      current position to center of object.
587 //      this is equivalent to
588 //      dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos), 
589 //                                      v->local_up );
590 //      if ( dist < FG_SQUARE(t->bounding_radius) ) {
591 //
592 // the compiler should inline this for us
593
594 static int
595 inrange( const double radius, const Point3D& center, const Point3D& vp,
596          const MAT3vec up)
597 {
598     MAT3vec u, u1, v;
599     //  double tmp;
600         
601     // u = p - p0
602     u[0] = center.x() - vp.x();
603     u[1] = center.y() - vp.y();
604     u[2] = center.z() - vp.z();
605         
606     // calculate the projection, u1, of u along d.
607     // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
608         
609     MAT3_SCALE_VEC(u1, up,
610                    (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
611     
612     // v = u - u1 = vector from closest point on line, p1, to the
613     // original point, p.
614     MAT3_SUB_VEC(v, u, u1);
615         
616     return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
617 }
618
619
620 // NEW for legibility
621
622 // update this tile's geometry for current view
623 // The Compiler should inline this
624 static void
625 update_tile_geometry( fgTILE *t, GLdouble *MODEL_VIEW)
626 {
627     GLdouble *m;
628     double x, y, z;
629         
630     // calculate tile offset
631     t->offset = t->center - scenery.center;
632
633     x = t->offset.x();
634     y = t->offset.y();
635     z = t->offset.z();
636         
637     m = t->model_view;
638         
639     // Calculate the model_view transformation matrix for this tile
640     FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
641     
642     // This is equivalent to doing a glTranslatef(x, y, z);
643     m[12] += (m[0]*x + m[4]*y + m[8] *z);
644     m[13] += (m[1]*x + m[5]*y + m[9] *z);
645     m[14] += (m[2]*x + m[6]*y + m[10]*z);
646     // m[15] += (m[3]*x + m[7]*y + m[11]*z);
647     // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
648     // so m[15] is unchanged
649 }
650
651
652 // Render the local tiles
653 void fgTileMgrRender( void ) {
654     FGState *f;
655     fgTILECACHE *c;
656     fgTILE *t;
657     FGView *v;
658     Point3D frag_offset;
659     fgFRAGMENT *frag_ptr;
660     fgMATERIAL *mtl_ptr;
661     int i;
662     int tile_diameter;
663     int index;
664     int culled = 0;
665     int drawn = 0;
666
667     c = &global_tile_cache;
668     f = current_aircraft.fdm_state;
669     v = &current_view;
670
671     tile_diameter = current_options.get_tile_diameter();
672
673     // moved to fgTileMgrUpdate, right after we check if we need to
674     // load additional tiles:
675     // scenery.cur_elev = fgTileMgrCurElev( FG_Longitude, FG_Latitude, 
676     //                                      v->abs_view_pos );
677  
678     // initialize the transient per-material fragment lists
679     material_mgr.init_transient_material_lists();
680    
681     // Pass 1
682     // traverse the potentially viewable tile list
683     for ( i = 0; i < (tile_diameter * tile_diameter); i++ ) {
684         index = tiles[i];
685         // fgPrintf( FG_TERRAIN, FG_DEBUG, "Index = %d\n", index);
686         t = c->get_tile(index);
687
688         // calculate tile offset
689         t->SetOffset( scenery.center );
690
691         // Course (tile based) culling
692         if ( viewable(t->offset, t->bounding_radius) ) {
693             // at least a portion of this tile could be viewable
694             
695             // Calculate the model_view transformation matrix for this tile
696             // This is equivalent to doing a glTranslatef(x, y, z);
697             t->UpdateViewMatrix( v->get_MODEL_VIEW() );
698
699             // xglPushMatrix();
700             // xglTranslatef(t->offset.x, t->offset.y, t->offset.z);
701
702             // traverse fragment list for tile
703             fgTILE::FragmentIterator current = t->begin();
704             fgTILE::FragmentIterator last = t->end();
705
706             for ( ; current != last; ++current ) {
707                 frag_ptr = &(*current);
708                 
709                 if ( frag_ptr->display_list >= 0 ) {
710                     // Fine (fragment based) culling
711                     frag_offset = frag_ptr->center - scenery.center;
712
713                     if ( viewable(frag_offset, frag_ptr->bounding_radius*2) ) {
714                         // add to transient per-material property fragment list
715                         // frag_ptr->tile_offset.x = t->offset.x;
716                         // frag_ptr->tile_offset.y = t->offset.y;
717                         // frag_ptr->tile_offset.z = t->offset.z;
718
719                         mtl_ptr = frag_ptr->material_ptr;
720                         // printf(" lookup = %s\n", mtl_ptr->texture_name);
721                         if ( ! mtl_ptr->append_sort_list( frag_ptr ) ) {
722                             FG_LOG( FG_TERRAIN, FG_ALERT,
723                                     "Overran material sorting array" );
724                         }
725
726                         // xglCallList(frag_ptr->display_list);
727                         drawn++;
728                     } else {
729                         // printf("Culled a fragment %.2f %.2f %.2f %.2f\n",
730                         //        frag_ptr->center.x, frag_ptr->center.y,
731                         //        frag_ptr->center.z, frag_ptr->bounding_radius);
732                         culled++;
733                     }
734                 }
735             }
736
737             // xglPopMatrix();
738         } else {
739             culled += t->fragment_list.size();
740         }
741     }
742
743     if ( (drawn + culled) > 0 ) {
744         v->set_vfc_ratio( (double)culled / (double)(drawn + culled) );
745     } else {
746         v->set_vfc_ratio( 0.0 );
747     }
748     // printf("drawn = %d  culled = %d  saved = %.2f\n", drawn, culled, 
749     //        v->vfc_ratio);
750
751     // Pass 2
752     // traverse the transient per-material fragment lists and render
753     // out all fragments for each material property.
754     xglPushMatrix();
755     material_mgr.render_fragments();
756     xglPopMatrix();
757 }
758
759
760 // $Log$
761 // Revision 1.52  1999/01/27 04:49:48  curt
762 // Fixes so that the sim can start out at an airport below sea level.
763 //
764 // Revision 1.51  1998/12/09 18:50:33  curt
765 // Converted "class fgVIEW" to "class FGView" and updated to make data
766 // members private and make required accessor functions.
767 //
768 // Revision 1.50  1998/12/06 13:51:25  curt
769 // Turned "struct fgWEATHER" into "class FGWeather".
770 //
771 // Revision 1.49  1998/12/05 15:54:26  curt
772 // Renamed class fgFLIGHT to class FGState as per request by JSB.
773 //
774 // Revision 1.48  1998/12/05 14:20:21  curt
775 // Looking into a terrain intersection problem.
776 //
777 // Revision 1.47  1998/12/05 14:11:19  curt
778 // Sun portability tweak.
779 //
780 // Revision 1.46  1998/12/03 14:15:24  curt
781 // Actually set the current scenery elevation based on scenery intersection point
782 // rather than calculating the intesection point and throwing it away.
783 //
784 // Revision 1.45  1998/12/03 01:18:18  curt
785 // Converted fgFLIGHT to a class.
786 // Tweaks for Sun Portability.
787 // Tweaked current terrain elevation code as per NHV.
788 //
789 // Revision 1.44  1998/11/23 21:49:48  curt
790 // minor tweaks.
791 //
792 // Revision 1.43  1998/11/09 23:40:52  curt
793 // Bernie Bright <bbright@c031.aone.net.au> writes:
794 // I've made some changes to the Scenery handling.  Basically just tidy ups.
795 // The main difference is in tile.[ch]xx where I've changed list<fgFRAGMENT> to
796 // vector<fgFRAGMENT>.  Studying our usage patterns this seems reasonable.
797 // Lists are good if you need to insert/delete elements randomly but we
798 // don't do that.  All access seems to be sequential.  Two additional
799 // benefits are smaller memory usage - each list element requires pointers
800 // to the next and previous elements, and faster access - vector iterators
801 // are smaller and faster than list iterators.  This should also help
802 // Charlie Hotchkiss' problem when compiling with Borland and STLport.
803 //
804 // ./Lib/Bucket/bucketutils.hxx
805 //   Convenience functions for fgBUCKET.
806 //
807 // ./Simulator/Scenery/tile.cxx
808 // ./Simulator/Scenery/tile.hxx
809 //   Changed fragment list to a vector.
810 //   Added some convenience member functions.
811 //
812 // ./Simulator/Scenery/tilecache.cxx
813 // ./Simulator/Scenery/tilecache.hxx
814 //   use const fgBUCKET& instead of fgBUCKET* where appropriate.
815 //
816 // ./Simulator/Scenery/tilemgr.cxx
817 // ./Simulator/Scenery/tilemgr.hxx
818 //   uses all the new convenience functions.
819 //
820 // Revision 1.42  1998/11/06 21:18:23  curt
821 // Converted to new logstream debugging facility.  This allows release
822 // builds with no messages at all (and no performance impact) by using
823 // the -DFG_NDEBUG flag.
824 //
825 // Revision 1.41  1998/10/18 01:17:23  curt
826 // Point3D tweaks.
827 //
828 // Revision 1.40  1998/10/17 01:34:28  curt
829 // C++ ifying ...
830 //
831 // Revision 1.39  1998/10/16 00:55:50  curt
832 // Converted to Point3D class.
833 //
834 // Revision 1.38  1998/09/17 18:36:18  curt
835 // Tweaks and optimizations by Norman Vine.
836 //
837 // Revision 1.37  1998/09/15 01:36:45  curt
838 // cleaned up my fragment.num_faces hack :-) to use the STL (no need in
839 // duplicating work.)
840 // Tweaked fgTileMgrRender() do not calc tile matrix unless necessary.
841 // removed some unneeded stuff from fgTileMgrCurElev()
842 //
843 // Revision 1.36  1998/09/14 12:45:26  curt
844 // minor tweaks.
845 //
846 // Revision 1.35  1998/09/10 19:07:16  curt
847 // /Simulator/Objects/fragment.hxx
848 //   Nested fgFACE inside fgFRAGMENT since its not used anywhere else.
849 //
850 // ./Simulator/Objects/material.cxx
851 // ./Simulator/Objects/material.hxx
852 //   Made fgMATERIAL and fgMATERIAL_MGR bona fide classes with private
853 //   data members - that should keep the rabble happy :)
854 //
855 // ./Simulator/Scenery/tilemgr.cxx
856 //   In viewable() delay evaluation of eye[0] and eye[1] in until they're
857 //   actually needed.
858 //   Change to fgTileMgrRender() to call fgMATERIAL_MGR::render_fragments()
859 //   method.
860 //
861 // ./Include/fg_stl_config.h
862 // ./Include/auto_ptr.hxx
863 //   Added support for g++ 2.7.
864 //   Further changes to other files are forthcoming.
865 //
866 // Brief summary of changes required for g++ 2.7.
867 //   operator->() not supported by iterators: use (*i).x instead of i->x
868 //   default template arguments not supported,
869 //   <functional> doesn't have mem_fun_ref() needed by callbacks.
870 //   some std include files have different names.
871 //   template member functions not supported.
872 //
873 // Revision 1.34  1998/09/09 20:58:09  curt
874 // Tweaks to loop constructs with STL usage.
875 //
876 // Revision 1.33  1998/09/08 15:05:10  curt
877 // Optimization by Norman Vine.
878 //
879 // Revision 1.32  1998/08/25 16:52:44  curt
880 // material.cxx material.hxx obj.cxx obj.hxx texload.c texload.h moved to
881 //   ../Objects
882 //
883 // Revision 1.31  1998/08/24 20:11:40  curt
884 // Tweaks ...
885 //
886 // Revision 1.30  1998/08/22  14:49:59  curt
887 // Attempting to iron out seg faults and crashes.
888 // Did some shuffling to fix a initialization order problem between view
889 // position, scenery elevation.
890 //
891 // Revision 1.29  1998/08/20 15:12:06  curt
892 // Used a forward declaration of classes fgTILE and fgMATERIAL to eliminate
893 // the need for "void" pointers and casts.
894 // Quick hack to count the number of scenery polygons that are being drawn.
895 //
896 // Revision 1.28  1998/08/12 21:13:06  curt
897 // material.cxx: don't load textures if they are disabled
898 // obj.cxx: optimizations from Norman Vine
899 // tile.cxx: minor tweaks
900 // tile.hxx: addition of num_faces
901 // tilemgr.cxx: minor tweaks
902 //
903 // Revision 1.27  1998/07/24 21:42:09  curt
904 // material.cxx: whups, double method declaration with no definition.
905 // obj.cxx: tweaks to avoid errors in SGI's CC.
906 // tile.cxx: optimizations by Norman Vine.
907 // tilemgr.cxx: optimizations by Norman Vine.
908 //
909 // Revision 1.26  1998/07/20 12:51:26  curt
910 // Added far clip plane to fragment clipping calculations and tie this to
911 // weather->visibility.  This way you can increase framerates by increasing
912 // for and lowering visibility.
913 //
914 // Revision 1.25  1998/07/13 21:02:01  curt
915 // Wrote access functions for current fgOPTIONS.
916 //
917 // Revision 1.24  1998/07/12 03:18:29  curt
918 // Added ground collision detection.  This involved:
919 // - saving the entire vertex list for each tile with the tile records.
920 // - saving the face list for each fragment with the fragment records.
921 // - code to intersect the current vertical line with the proper face in
922 //   an efficient manner as possible.
923 // Fixed a bug where the tiles weren't being shifted to "near" (0,0,0)
924 //
925 // Revision 1.23  1998/07/08 14:47:23  curt
926 // Fix GL_MODULATE vs. GL_DECAL problem introduced by splash screen.
927 // polare3d.h renamed to polar3d.hxx
928 // fg{Cartesian,Polar}Point3d consolodated.
929 // Added some initial support for calculating local current ground elevation.
930 //
931 // Revision 1.22  1998/07/04 00:54:31  curt
932 // Added automatic mipmap generation.
933 //
934 // When rendering fragments, use saved model view matrix from associated tile
935 // rather than recalculating it with push() translate() pop().
936 //
937 // Revision 1.21  1998/06/27 16:54:59  curt
938 // Check for GL_VERSION_1_1 or GL_EXT_texture_object to decide whether to use
939 //   "EXT" versions of texture management routines.
940 //
941 // Revision 1.20  1998/06/17 21:36:42  curt
942 // Load and manage multiple textures defined in the Materials library.
943 // Boost max material fagments for each material property to 800.
944 // Multiple texture support when rendering.
945 //
946 // Revision 1.19  1998/06/08 17:57:54  curt
947 // Working first pass at material proporty sorting.
948 //
949 // Revision 1.18  1998/06/06 01:09:32  curt
950 // I goofed on the log message in the last commit ... now fixed.
951 //
952 // Revision 1.17  1998/06/06 01:07:18  curt
953 // Increased per material fragment list size from 100 to 400.
954 // Now correctly draw viewable fragments in per material order.
955 //
956 // Revision 1.16  1998/06/05 22:39:55  curt
957 // Working on sorting by, and rendering by material properties.
958 //
959 // Revision 1.15  1998/06/03 00:47:51  curt
960 // No .h for STL includes.
961 // Minor view culling optimizations.
962 //
963 // Revision 1.14  1998/06/01 17:56:20  curt
964 // Incremental additions to material.cxx (not fully functional)
965 // Tweaked vfc_ratio math to avoid divide by zero.
966 //
967 // Revision 1.13  1998/05/24 02:49:10  curt
968 // Implimented fragment level view frustum culling.
969 //
970 // Revision 1.12  1998/05/23 14:09:23  curt
971 // Added tile.cxx and tile.hxx.
972 // Working on rewriting the tile management system so a tile is just a list
973 // fragments, and the fragment record contains the display list for that fragment.
974 //
975 // Revision 1.11  1998/05/20 20:53:55  curt
976 // Moved global ref point and radius (bounding sphere info, and offset) to
977 // data file rather than calculating it on the fly.
978 // Fixed polygon winding problem in scenery generation stage rather than
979 // compensating for it on the fly.
980 // Made a fgTILECACHE class.
981 //
982 // Revision 1.10  1998/05/17 16:59:34  curt
983 // Frist pass at view frustum culling now operational.
984 //
985 // Revision 1.9  1998/05/16 13:09:58  curt
986 // Beginning to add support for view frustum culling.
987 // Added some temporary code to calculate bouding radius, until the
988 //   scenery generation tools and scenery can be updated.
989 //
990 // Revision 1.8  1998/05/07 23:15:21  curt
991 // Fixed a glTexImage2D() usage bug where width and height were mis-swapped.
992 // Added support for --tile-radius=n option.
993 //
994 // Revision 1.7  1998/05/06 03:16:42  curt
995 // Added an option to control square tile radius.
996 //
997 // Revision 1.6  1998/05/02 01:52:18  curt
998 // Playing around with texture coordinates.
999 //
1000 // Revision 1.5  1998/04/30 12:35:32  curt
1001 // Added a command line rendering option specify smooth/flat shading.
1002 //
1003 // Revision 1.4  1998/04/27 03:30:14  curt
1004 // Minor transformation adjustments to try to keep scenery tiles closer to
1005 // (0, 0, 0)  GLfloats run out of precision at the distances we need to model
1006 // the earth, but we can do a bunch of pre-transformations using double math
1007 // and then cast to GLfloat once everything is close in where we have less
1008 // precision problems.
1009 //
1010 // Revision 1.3  1998/04/25 22:06:32  curt
1011 // Edited cvs log messages in source files ... bad bad bad!
1012 //
1013 // Revision 1.2  1998/04/24 00:51:09  curt
1014 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
1015 // Tweaked the scenery file extentions to be "file.obj" (uncompressed)
1016 // or "file.obz" (compressed.)
1017 //
1018 // Revision 1.1  1998/04/22 13:22:48  curt
1019 // C++ - ifing the code a bit.
1020 //
1021 // Revision 1.25  1998/04/18 04:14:07  curt
1022 // Moved fg_debug.c to it's own library.
1023 //
1024 // Revision 1.24  1998/04/14 02:23:18  curt
1025 // Code reorganizations.  Added a Lib/ directory for more general libraries.
1026 //
1027 // Revision 1.23  1998/04/08 23:30:08  curt
1028 // Adopted Gnu automake/autoconf system.
1029 //
1030 // Revision 1.22  1998/04/03 22:11:38  curt
1031 // Converting to Gnu autoconf system.
1032 //
1033 // Revision 1.21  1998/03/23 21:23:05  curt
1034 // Debugging output tweaks.
1035 //
1036 // Revision 1.20  1998/03/14 00:30:51  curt
1037 // Beginning initial terrain texturing experiments.
1038 //
1039 // Revision 1.19  1998/02/20 00:16:25  curt
1040 // Thursday's tweaks.
1041 //
1042 // Revision 1.18  1998/02/19 13:05:54  curt
1043 // Incorporated some HUD tweaks from Michelle America.
1044 // Tweaked the sky's sunset/rise colors.
1045 // Other misc. tweaks.
1046 //
1047 // Revision 1.17  1998/02/16 13:39:46  curt
1048 // Miscellaneous weekend tweaks.  Fixed? a cache problem that caused whole
1049 // tiles to occasionally be missing.
1050 //
1051 // Revision 1.16  1998/02/12 21:59:53  curt
1052 // Incorporated code changes contributed by Charlie Hotchkiss
1053 // <chotchkiss@namg.us.anritsu.com>
1054 //
1055 // Revision 1.14  1998/02/09 21:30:19  curt
1056 // Fixed a nagging problem with terrain tiles not "quite" matching up perfectly.
1057 //
1058 // Revision 1.13  1998/02/07 15:29:46  curt
1059 // Incorporated HUD changes and struct/typedef changes from Charlie Hotchkiss
1060 // <chotchkiss@namg.us.anritsu.com>
1061 //
1062 // Revision 1.12  1998/02/01 03:39:55  curt
1063 // Minor tweaks.
1064 //
1065 // Revision 1.11  1998/01/31 00:43:27  curt
1066 // Added MetroWorks patches from Carmen Volpe.
1067 //
1068 // Revision 1.10  1998/01/29 00:51:40  curt
1069 // First pass at tile cache, dynamic tile loading and tile unloading now works.
1070 //
1071 // Revision 1.9  1998/01/27 03:26:44  curt
1072 // Playing with new fgPrintf command.
1073 //
1074 // Revision 1.8  1998/01/27 00:48:04  curt
1075 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
1076 // system and commandline/config file processing code.
1077 //
1078 // Revision 1.7  1998/01/26 15:55:25  curt
1079 // Progressing on building dynamic scenery system.
1080 //
1081 // Revision 1.6  1998/01/24 00:03:30  curt
1082 // Initial revision.
1083 //
1084 // Revision 1.5  1998/01/19 19:27:18  curt
1085 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
1086 // This should simplify things tremendously.
1087 //
1088 // Revision 1.4  1998/01/19 18:40:38  curt
1089 // Tons of little changes to clean up the code and to remove fatal errors
1090 // when building with the c++ compiler.
1091 //
1092 // Revision 1.3  1998/01/13 00:23:11  curt
1093 // Initial changes to support loading and management of scenery tiles.  Note,
1094 // there's still a fair amount of work left to be done.
1095 //
1096 // Revision 1.2  1998/01/08 02:22:27  curt
1097 // Continue working on basic features.
1098 //
1099 // Revision 1.1  1998/01/07 23:50:51  curt
1100 // "area" renamed to "tile"
1101 //
1102 // Revision 1.2  1998/01/07 03:29:29  curt
1103 // Given an arbitrary lat/lon, we can now:
1104 //   generate a unique index for the chunk containing the lat/lon
1105 //   generate a path name to the chunk file
1106 //   build a list of the indexes of all the nearby areas.
1107 //
1108 // Revision 1.1  1998/01/07 02:05:48  curt
1109 // Initial revision.