]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Fix a small tile cache bug.
[flightgear.git] / src / 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
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #ifdef HAVE_WINDOWS_H
29 #  include <windows.h>
30 #endif
31
32 #include <GL/glut.h>
33 #include <XGL/xgl.h>
34
35 #include <Aircraft/aircraft.hxx>
36
37 #include <Debug/logstream.hxx>
38 // #include <Bucket/bucketutils.hxx>
39 #include <Include/fg_constants.h>
40 #include <Main/options.hxx>
41 #include <Main/views.hxx>
42 #include <Math/fg_geodesy.hxx>
43 #include <Math/mat3.h>
44 #include <Math/point3d.hxx>
45 #include <Math/polar3d.hxx>
46 #include <Math/vector.hxx>
47 #include <Objects/materialmgr.hxx>
48 #include <Objects/obj.hxx>
49 #include <Weather/weather.hxx>
50
51 #include "scenery.hxx"
52 #include "tilecache.hxx"
53 #include "tileentry.hxx"
54 #include "tilemgr.hxx"
55
56
57 // to test clipping speedup in fgTileMgrRender()
58 #if defined ( USE_FAST_FOV_CLIP )
59 // #define TEST_FOV_CLIP
60 // #define TEST_ELEV
61 #endif
62
63
64 extern ssgRoot *scene;
65
66
67 // the tile manager
68 FGTileMgr global_tile_mgr;
69
70
71 // Constructor
72 FGTileMgr::FGTileMgr ( void ):
73     state( Start )
74 {
75 }
76
77
78 // Destructor
79 FGTileMgr::~FGTileMgr ( void ) {
80 }
81
82
83 // Initialize the Tile Manager subsystem
84 int FGTileMgr::init( void ) {
85     FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
86
87     // load default material library
88     if ( ! material_mgr.loaded() ) {
89         material_mgr.load_lib();
90     }
91
92     state = Inited;
93
94     return 1;
95 }
96
97
98 // schedule a tile for loading
99 static void disable_tile( int cache_index ) {
100     // see if tile already exists in the cache
101     cout << "DISABLING CACHE ENTRY = " << cache_index << endl;
102     FGTileEntry *t = global_tile_cache.get_tile( cache_index );
103     t->ssg_disable();
104 }
105
106
107 // schedule a tile for loading
108 int FGTileMgr::sched_tile( const FGBucket& b ) {
109     // see if tile already exists in the cache
110     int cache_index = global_tile_cache.exists( b );
111
112     if ( cache_index >= 0 ) {
113         // tile exists in cache, reenable it.
114         cout << "REENABLING DISABLED TILE" << endl;
115         FGTileEntry *t = global_tile_cache.get_tile( cache_index );
116         t->select_ptr->select( 1 );
117         t->mark_loaded();
118     } else {
119         // find the next available cache entry and mark it as
120         // scheduled
121         cache_index = global_tile_cache.next_avail();
122         FGTileEntry *t = global_tile_cache.get_tile( cache_index );
123         t->mark_scheduled_for_use();
124
125         // register a load request
126         FGLoadRec request;
127         request.b = b;
128         request.cache_index = cache_index;
129         load_queue.push_back( request );
130     }
131
132     return cache_index;
133 }
134
135
136 // load a tile
137 void FGTileMgr::load_tile( const FGBucket& b, int cache_index) {
138
139     FG_LOG( FG_TERRAIN, FG_DEBUG, "Loading tile " << b );
140     
141     global_tile_cache.fill_in(cache_index, b);
142
143     FG_LOG( FG_TERRAIN, FG_DEBUG, "Loaded for cache index: " << cache_index );
144 }
145
146
147 // Calculate shortest distance from point to line
148 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp, 
149                                        MAT3vec d )
150 {
151     MAT3vec p, p0;
152
153     p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
154     p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
155
156     return fgPointLineSquared(p, p0, d);
157 }
158
159
160 // Determine scenery altitude.  Normally this just happens when we
161 // render the scene, but we'd also like to be able to do this
162 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
163 // Returns result in meters.
164 double
165 FGTileMgr::current_elev_new( const FGBucket& p ) {
166     FGTileEntry *t;
167     fgFRAGMENT *frag_ptr;
168     Point3D abs_view_pos = current_view.get_abs_view_pos();
169     Point3D earth_center(0.0);
170     Point3D result;
171     MAT3vec local_up;
172     double dist, lat_geod, alt, sea_level_r;
173     int index;
174
175     local_up[0] = abs_view_pos.x();
176     local_up[1] = abs_view_pos.y();
177     local_up[2] = abs_view_pos.z();
178
179     // Find current translation offset
180     // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
181     index = global_tile_cache.exists(p);
182     if ( index < 0 ) {
183         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
184         return 0.0;
185     }
186
187     t = global_tile_cache.get_tile(index);
188
189     scenery.next_center = t->center;
190     
191     FG_LOG( FG_TERRAIN, FG_DEBUG, 
192             "Current bucket = " << p << "  Index = " << p.gen_index_str() );
193     FG_LOG( FG_TERRAIN, FG_DEBUG,
194             "abs_view_pos = " << abs_view_pos );
195
196     // calculate tile offset
197     // x = (t->offset.x = t->center.x - scenery.center.x);
198     // y = (t->offset.y = t->center.y - scenery.center.y);
199     // z = (t->offset.z = t->center.z - scenery.center.z);
200     
201     // calc current terrain elevation calculate distance from
202     // vertical tangent line at current position to center of
203     // tile.
204         
205     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
206        point_line_dist_squared(&(t->offset), &(v->view_pos), 
207        v->local_up), t->bounding_radius); */
208
209     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
210     if ( dist < FG_SQUARE(t->bounding_radius) ) {
211
212         // traverse fragment list for tile
213         FGTileEntry::FragmentIterator current = t->begin();
214         FGTileEntry::FragmentIterator last = t->end();
215
216         for ( ; current != last; ++current ) {
217             frag_ptr = &(*current);
218             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
219                point_line_dist_squared( &(frag_ptr->center), 
220                &abs_view_pos), local_up),
221                frag_ptr->bounding_radius); */
222
223             dist = point_line_dist_squared( frag_ptr->center,
224                                             abs_view_pos,
225                                             local_up);
226             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
227                 if ( frag_ptr->intersect( abs_view_pos, 
228                                           earth_center, 0, result ) ) {
229                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
230                             result );
231                     // compute geocentric coordinates of tile center
232                     Point3D pp = fgCartToPolar3d(result);
233                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
234                     // convert to geodetic coordinates
235                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
236                                  &alt, &sea_level_r);
237
238                     // printf("alt = %.2f\n", alt);
239                     // exit since we found an intersection
240                     if ( alt > -9999.0 ) {
241                         // printf("returning alt\n");
242                         return alt;
243                     } else {
244                         // printf("returning 0\n");
245                         return 0.0;
246                     }
247                 }
248             }
249         }
250     }
251
252     FG_LOG( FG_TERRAIN, FG_INFO, "(new) no terrain intersection found" );
253
254     return 0.0;
255 }
256
257
258 // Determine scenery altitude.  Normally this just happens when we
259 // render the scene, but we'd also like to be able to do this
260 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
261 // Returns result in meters.
262 double
263 FGTileMgr::current_elev( double lon, double lat, const Point3D& abs_view_pos ) {
264     FGTileCache *c;
265     FGTileEntry *t;
266     fgFRAGMENT *frag_ptr;
267     Point3D earth_center(0.0);
268     Point3D result;
269     MAT3vec local_up;
270     double dist, lat_geod, alt, sea_level_r;
271     int index;
272
273     c = &global_tile_cache;
274
275     local_up[0] = abs_view_pos.x();
276     local_up[1] = abs_view_pos.y();
277     local_up[2] = abs_view_pos.z();
278
279     FG_LOG( FG_TERRAIN, FG_DEBUG, "Absolute view pos = " << abs_view_pos );
280
281     // Find current translation offset
282     FGBucket p( lon * RAD_TO_DEG, lat * RAD_TO_DEG );
283     index = c->exists(p);
284     if ( index < 0 ) {
285         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
286         return 0.0;
287     }
288
289     t = c->get_tile(index);
290
291     scenery.next_center = t->center;
292     
293     FG_LOG( FG_TERRAIN, FG_DEBUG, 
294             "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
295             << ")  Current bucket = " << p 
296             << "  Index = " << p.gen_index_str() );
297
298     FG_LOG( FG_TERRAIN, FG_DEBUG, "Tile center " << t->center 
299             << "  bounding radius = " << t->bounding_radius );
300
301     // calculate tile offset
302     // x = (t->offset.x = t->center.x - scenery.center.x);
303     // y = (t->offset.y = t->center.y - scenery.center.y);
304     // z = (t->offset.z = t->center.z - scenery.center.z);
305     
306     // calc current terrain elevation calculate distance from
307     // vertical tangent line at current position to center of
308     // tile.
309         
310     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
311        point_line_dist_squared(&(t->offset), &(v->view_pos), 
312        v->local_up), t->bounding_radius); */
313
314     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
315     FG_LOG( FG_TERRAIN, FG_DEBUG, "(gross check) dist squared = " << dist );
316
317     if ( dist < FG_SQUARE(t->bounding_radius) ) {
318
319         // traverse fragment list for tile
320         FGTileEntry::FragmentIterator current = t->begin();
321         FGTileEntry::FragmentIterator last = t->end();
322
323         for ( ; current != last; ++current ) {
324             frag_ptr = &(*current);
325             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
326                point_line_dist_squared( &(frag_ptr->center), 
327                &abs_view_pos), local_up),
328                frag_ptr->bounding_radius); */
329
330             dist = point_line_dist_squared( frag_ptr->center,
331                                             abs_view_pos,
332                                             local_up);
333             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
334                 if ( frag_ptr->intersect( abs_view_pos, 
335                                           earth_center, 0, result ) ) {
336                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
337                             result );
338                     // compute geocentric coordinates of tile center
339                     Point3D pp = fgCartToPolar3d(result);
340                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
341                     // convert to geodetic coordinates
342                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
343                                  &alt, &sea_level_r);
344
345                     // printf("alt = %.2f\n", alt);
346                     // exit since we found an intersection
347                     if ( alt > -9999.0 ) {
348                         // printf("returning alt\n");
349                         return alt;
350                     } else {
351                         // printf("returning 0\n");
352                         return 0.0;
353                     }
354                 }
355             }
356         }
357     }
358
359     FG_LOG( FG_TERRAIN, FG_INFO, "(old) no terrain intersection found" );
360
361     return 0.0;
362 }
363
364
365 // Determine scenery altitude via ssg.  Normally this just happens
366 // when we render the scene, but we'd also like to be able to do this
367 // explicitely.  lat & lon are in radians.  view_pos in current world
368 // coordinate translated near (0,0,0) (in meters.)  Returns result in
369 // meters.
370 double
371 FGTileMgr::current_elev_ssg( const Point3D& abs_view_pos, 
372                              const Point3D& view_pos )
373 {
374     ssgHit *results ;
375
376     // cout << "view pos = " << view_pos << endl;
377     // cout << "abs view pos = " << abs_view_pos << endl;
378
379     sgMat4 m;
380     sgMakeTransMat4( m, view_pos.x(), view_pos.y(), view_pos.z() );
381
382     sgVec3 s;
383     sgSetVec3(s, -abs_view_pos.x(), -abs_view_pos.y(), -abs_view_pos.z() );
384
385     int num_hits = ssgLOS ( scene, s, m, &results ) ;
386
387     for ( int i = 0 ; i < num_hits ; i++ ) {
388         ssgHit *h = &(results [ i ]) ;
389         cout << "got a hit!" << endl;
390         /* Do something with 'h' */
391     }
392
393     FG_LOG( FG_TERRAIN, FG_INFO, "(ssg) no terrain intersection found" );
394
395     return 0.0;
396 }
397
398
399 // given the current lon/lat, fill in the array of local chunks.  If
400 // the chunk isn't already in the cache, then read it from disk.
401 int FGTileMgr::update( void ) {
402     FGTileCache *c;
403     FGInterface *f;
404     FGBucket p2;
405     static FGBucket p_last(false);
406     static double last_lon = -1000.0;  // in degrees
407     static double last_lat = -1000.0;  // in degrees
408     int tile_diameter;
409     int i, j, dw, dh;
410
411     c = &global_tile_cache;
412     f = current_aircraft.fdm_state;
413
414     tile_diameter = current_options.get_tile_diameter();
415
416     FGBucket p1( f->get_Longitude() * RAD_TO_DEG,
417                  f->get_Latitude() * RAD_TO_DEG );
418     dw = tile_diameter / 2;
419     dh = tile_diameter / 2;
420
421     if ( (p1 == p_last) && (state == Running) ) {
422         // same bucket as last time
423         FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
424     } else if ( (state == Start) || (state == Inited) ) {
425         state = Running;
426
427         // First time through or we have teleported, initialize the
428         // system and load all relavant tiles
429
430         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
431         FG_LOG( FG_TERRAIN, FG_INFO, "  First time through ... " );
432         FG_LOG( FG_TERRAIN, FG_INFO, "  Updating Tile list for " << p1 );
433         FG_LOG( FG_TERRAIN, FG_INFO, "  Loading " 
434                 << tile_diameter * tile_diameter << " tiles" );
435
436         // wipe/initialize tile cache
437         c->init();
438         p_last.make_bad();
439
440         // build the local area list and schedule tiles for loading
441
442         // start with the center tile and work out in concentric
443         // "rings"
444
445         p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
446                              f->get_Latitude() * RAD_TO_DEG,
447                              0, 0 );
448         tiles[(dh*tile_diameter) + dw] = sched_tile( p2 );
449
450         for ( i = 3; i <= tile_diameter; i = i + 2 ) {
451             int span = i / 2;
452
453             // bottom row
454             for ( j = -span; j <= span; ++j ) {
455                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
456                                      f->get_Latitude() * RAD_TO_DEG,
457                                      j, -span );
458                 tiles[((dh-span)*tile_diameter) + dw+j] = sched_tile( p2 );
459             }
460
461             // top row
462             for ( j = -span; j <= span; ++j ) {
463                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
464                                      f->get_Latitude() * RAD_TO_DEG,
465                                      j, span );
466                 tiles[((dh+span)*tile_diameter) + dw+j] = sched_tile( p2 );
467             }
468
469             // middle rows
470             for ( j = -span + 1; j <= span - 1; ++j ) {
471                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
472                                      f->get_Latitude() * RAD_TO_DEG,
473                                      -span, j );
474                 tiles[((dh+j)*tile_diameter) + dw-span] = sched_tile( p2 );
475                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
476                                      f->get_Latitude() * RAD_TO_DEG,
477                                      span, j );
478                 tiles[((dh+j)*tile_diameter) + dw+span] = sched_tile( p2 );
479             }
480
481         }
482
483         /* for ( j = 0; j < tile_diameter; j++ ) {
484             for ( i = 0; i < tile_diameter; i++ ) {
485                 // fgBucketOffset(&p1, &p2, i - dw, j - dh);
486                 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
487                                      f->get_Latitude() * RAD_TO_DEG,
488                                      i - dw, j -dh );
489                 tiles[(j*tile_diameter) + i] = sched_tile( p2 );
490             }
491         } */
492
493         // Now force a load of the center tile and inner ring so we
494         // have something to see in our first frame.
495         for ( i = 0; i < 9; ++i ) {
496             if ( load_queue.size() ) {
497                 FG_LOG( FG_TERRAIN, FG_INFO, 
498                         "Load queue not empty, loading a tile" );
499             
500                 FGLoadRec pending = load_queue.front();
501                 load_queue.pop_front();
502                 load_tile( pending.b, pending.cache_index );
503             }
504         }
505
506     } else {
507         // We've moved to a new bucket, we need to scroll our
508         // structures, and load in the new tiles
509
510 #if 0 
511         // make sure load queue is flushed before doing shift
512         while ( load_queue.size() ) {
513             FG_LOG( FG_TERRAIN, FG_INFO, 
514                     "Load queue not empty, flushing queue before tile shift." );
515             
516             FGLoadRec pending = load_queue.front();
517             load_queue.pop_front();
518             load_tile( pending.b, pending.index );
519         }
520 #endif
521
522         // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
523         // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
524         // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
525
526         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
527
528         if ( (p1.get_lon() > p_last.get_lon()) ||
529              ( (p1.get_lon() == p_last.get_lon()) && (p1.get_x() > p_last.get_x()) ) ) {
530             FG_LOG( FG_TERRAIN, FG_INFO, 
531                     "  (East) Loading " << tile_diameter << " tiles" );
532             for ( j = 0; j < tile_diameter; j++ ) {
533                 // scrolling East
534                 disable_tile( tiles[(j*tile_diameter) + 0] );
535                 for ( i = 0; i < tile_diameter - 1; i++ ) {
536                     tiles[(j*tile_diameter) + i] = 
537                         tiles[(j*tile_diameter) + i + 1];
538                 }
539                 // load in new column
540                 p2 = fgBucketOffset( last_lon, last_lat, dw + 1, j - dh );
541                 tiles[(j*tile_diameter) + tile_diameter - 1] = sched_tile( p2 );
542             }
543         } else if ( (p1.get_lon() < p_last.get_lon()) ||
544                     ( (p1.get_lon() == p_last.get_lon()) && 
545                       (p1.get_x() < p_last.get_x()) ) ) {
546             FG_LOG( FG_TERRAIN, FG_INFO, 
547                     "  (West) Loading " << tile_diameter << " tiles" );
548             for ( j = 0; j < tile_diameter; j++ ) {
549                 // scrolling West
550                 disable_tile( tiles[(j*tile_diameter) + tile_diameter - 1] );
551                 for ( i = tile_diameter - 1; i > 0; i-- ) {
552                     tiles[(j*tile_diameter) + i] = 
553                         tiles[(j*tile_diameter) + i - 1];
554                 }
555                 // load in new column
556                 p2 = fgBucketOffset( last_lon, last_lat, -dw - 1, j - dh );
557                 tiles[(j*tile_diameter) + 0] = sched_tile( p2 );
558             }
559         }
560
561         if ( (p1.get_lat() > p_last.get_lat()) ||
562              ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() > p_last.get_y()) ) ) {
563             FG_LOG( FG_TERRAIN, FG_INFO, 
564                     "  (North) Loading " << tile_diameter << " tiles" );
565             for ( i = 0; i < tile_diameter; i++ ) {
566                 // scrolling North
567                 disable_tile( tiles[0 + i] );
568                 for ( j = 0; j < tile_diameter - 1; j++ ) {
569                     tiles[(j * tile_diameter) + i] =
570                         tiles[((j+1) * tile_diameter) + i];
571                 }
572                 // load in new column
573                 p2 = fgBucketOffset( last_lon, last_lat, i - dw, dh + 1);
574                 tiles[((tile_diameter-1) * tile_diameter) + i] = 
575                     sched_tile( p2 );
576             }
577         } else if ( (p1.get_lat() < p_last.get_lat()) ||
578                     ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() < p_last.get_y()) ) ) {
579             FG_LOG( FG_TERRAIN, FG_INFO, 
580                     "  (South) Loading " << tile_diameter << " tiles" );
581             for ( i = 0; i < tile_diameter; i++ ) {
582                 // scrolling South
583                 disable_tile( tiles[((tile_diameter-1) * tile_diameter) + i] );
584                 for ( j = tile_diameter - 1; j > 0; j-- ) {
585                     tiles[(j * tile_diameter) + i] = 
586                         tiles[((j-1) * tile_diameter) + i];
587                 }
588                 // load in new column
589                 p2 = fgBucketOffset( last_lon, last_lat, i - dw, -dh - 1);
590                 tiles[0 + i] = sched_tile( p2 );
591             }
592         }
593     }
594
595     if ( load_queue.size() ) {
596         FG_LOG( FG_TERRAIN, FG_INFO, "Load queue not empty, loading a tile" );
597
598         FGLoadRec pending = load_queue.front();
599         load_queue.pop_front();
600         load_tile( pending.b, pending.cache_index );
601     }
602
603     // find our current elevation (feed in the current bucket to save work)
604     Point3D geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
605     Point3D tmp_abs_view_pos = fgGeodToCart(geod_pos);
606
607     scenery.cur_elev = 
608         current_elev( f->get_Longitude(), f->get_Latitude(), tmp_abs_view_pos );
609     // cout << "current elevation == " << scenery.cur_elev << endl;
610     // double junk = current_elev_ssg( current_view.abs_view_pos,
611     //                                 current_view.view_pos );
612     // cout << "current elevation (ssg) == " << 
613         
614     p_last = p1;
615     last_lon = f->get_Longitude() * RAD_TO_DEG;
616     last_lat = f->get_Latitude() * RAD_TO_DEG;
617
618     return 1;
619 }
620
621
622 // Calculate if point/radius is inside view frustum
623 static int viewable( const Point3D& cp, double radius ) {
624     int viewable = 1; // start by assuming it's viewable
625     double x1, y1;
626
627     /********************************/
628 #if defined( USE_FAST_FOV_CLIP ) // views.hxx
629     /********************************/
630         
631     MAT3vec eye;        
632     double *mat;
633     double x, y, z;
634
635     x = cp.x();
636     y = cp.y();
637     z = cp.z();
638         
639     mat = (double *)(current_view.get_WORLD_TO_EYE());
640         
641     eye[2] =  x*mat[2] + y*mat[6] + z*mat[10] + mat[14];
642         
643     // Check near and far clip plane
644     if( ( eye[2] > radius ) ||
645         ( eye[2] + radius + current_weather.get_visibility() < 0) )
646         {
647             return(0);
648         }
649         
650     eye[0] = (x*mat[0] + y*mat[4] + z*mat[8] + mat[12])
651         * current_view.get_slope_x();
652
653     // check right and left clip plane (from eye perspective)
654     x1 = radius * current_view.get_fov_x_clip();
655     if( (eye[2] > -(eye[0]+x1)) || (eye[2] > (eye[0]-x1)) )
656         {
657             return(0);
658         }
659         
660     eye[1] = (x*mat[1] + y*mat[5] + z*mat[9] + mat[13]) 
661         * current_view.get_slope_y();
662
663     // check bottom and top clip plane (from eye perspective)
664     y1 = radius * current_view.get_fov_y_clip();
665     if( (eye[2] > -(eye[1]+y1)) || (eye[2] > (eye[1]-y1)) )
666         {
667             return(0);
668         }
669
670     /********************************/  
671 #else // DO NOT USE_FAST_FOV_CLIP
672     /********************************/  
673
674     fgVIEW *v;
675     MAT3hvec world, eye;
676     double x0, slope;
677
678     v = &current_view;
679
680     MAT3_SET_HVEC(world, cp->x, cp->y, cp->z, 1.0);
681     // MAT3mult_vec(eye, world, v->WORLD_TO_EYE);
682     // printf( "\nworld -> eye = %.2f %.2f %.2f  radius = %.2f\n", 
683     //         eye[0], eye[1], eye[2], radius);
684
685     // Use lazy evaluation for calculating eye hvec.
686 #define vec world
687 #define mat v->WORLD_TO_EYE
688     eye[2] = vec[0]*mat[0][2]+vec[1]*mat[1][2]+vec[2]*mat[2][2]+mat[3][2];
689
690     // Check near clip plane
691     if ( eye[2] > radius ) {
692         return(0);
693     }
694
695     // Check far clip plane
696     if ( eye[2] + radius < -current_weather.get_visibility() ) {
697         return(0);
698     }
699
700     // check right clip plane (from eye perspective)
701     // y = m * (x - x0) = equation of a line intercepting X axis at x0
702     x1 = v->cos_fov_x * radius;
703     y1 = v->sin_fov_x * radius;
704     slope = v->slope_x;
705     eye[0] = vec[0]*mat[0][0]+vec[1]*mat[1][0]+vec[2]*mat[2][0]+mat[3][0];
706
707     if ( eye[2] > ((slope * (eye[0] - x1)) + y1) ) {
708         return( false );
709     }
710
711     // check left clip plane (from eye perspective)
712     if ( eye[2] > -((slope * (eye[0] + x1)) - y1) ) {
713         return( false );
714     }
715
716     // check bottom clip plane (from eye perspective)
717     x1 = -(v->cos_fov_y) * radius;
718     y1 = v->sin_fov_y * radius;
719     slope = v->slope_y;
720     eye[1] = vec[0]*mat[0][1]+vec[1]*mat[1][1]+vec[2]*mat[2][1]+mat[3][1];
721 #undef vec
722 #undef mat
723
724     if ( eye[2] > ((slope * (eye[1] - x1)) + y1) ) {
725         return( false );
726     }
727
728     // check top clip plane (from eye perspective)
729     if ( eye[2] > -((slope * (eye[1] + x1)) - y1) ) {
730         return( false );
731     }
732
733 #endif // defined( USE_FAST_FOV_CLIP )
734         
735     return(viewable);
736 }
737
738
739 // NEW 
740
741 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
742 //      calculate distance from vertical tangent line at
743 //      current position to center of object.
744 //      this is equivalent to
745 //      dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos), 
746 //                                      v->local_up );
747 //      if ( dist < FG_SQUARE(t->bounding_radius) ) {
748 //
749 // the compiler should inline this for us
750
751 static int
752 inrange( const double radius, const Point3D& center, const Point3D& vp,
753          const MAT3vec up)
754 {
755     MAT3vec u, u1, v;
756     //  double tmp;
757         
758     // u = p - p0
759     u[0] = center.x() - vp.x();
760     u[1] = center.y() - vp.y();
761     u[2] = center.z() - vp.z();
762         
763     // calculate the projection, u1, of u along d.
764     // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
765         
766     MAT3_SCALE_VEC(u1, up,
767                    (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
768     
769     // v = u - u1 = vector from closest point on line, p1, to the
770     // original point, p.
771     MAT3_SUB_VEC(v, u, u1);
772         
773     return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
774 }
775
776
777 // NEW for legibility
778
779 // update this tile's geometry for current view
780 // The Compiler should inline this
781 static void
782 update_tile_geometry( FGTileEntry *t, GLdouble *MODEL_VIEW)
783 {
784     GLfloat *m;
785     double x, y, z;
786         
787     // calculate tile offset
788     t->offset = t->center - scenery.center;
789
790     x = t->offset.x();
791     y = t->offset.y();
792     z = t->offset.z();
793         
794     m = t->model_view;
795         
796     // Calculate the model_view transformation matrix for this tile
797     FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
798     
799     // This is equivalent to doing a glTranslatef(x, y, z);
800     m[12] += (m[0]*x + m[4]*y + m[8] *z);
801     m[13] += (m[1]*x + m[5]*y + m[9] *z);
802     m[14] += (m[2]*x + m[6]*y + m[10]*z);
803     // m[15] += (m[3]*x + m[7]*y + m[11]*z);
804     // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
805     // so m[15] is unchanged
806 }
807
808
809 // Prepare the ssg nodes ... for each tile, set it's proper
810 // transform and update it's range selector based on current
811 // visibilty
812 void FGTileMgr::prep_ssg_nodes( void ) {
813     FGTileEntry *t;
814
815     int tile_diameter = current_options.get_tile_diameter();
816
817     float ranges[2];
818     ranges[0] = 0.0f;
819
820     // traverse the potentially viewable tile list and update range
821     // selector and transform
822     for ( int i = 0; i < (tile_diameter * tile_diameter); i++ ) {
823         int index = tiles[i];
824         t = global_tile_cache.get_tile(index);
825
826         if ( t->is_loaded() ) {
827             // set range selector (LOD trick) to be distance to center
828             // of tile + bounding radius
829             ranges[1] = current_weather.get_visibility() + t->bounding_radius;
830             t->range_ptr->setRanges( ranges, 2 );
831
832             // calculate tile offset
833             t->SetOffset( scenery.center );
834
835             // calculate ssg transform
836             sgCoord sgcoord;
837             sgSetCoord( &sgcoord,
838                         t->offset.x(), t->offset.y(), t->offset.z(),
839                         0.0, 0.0, 0.0 );
840             t->transform_ptr->setTransform( &sgcoord );
841         }
842     }
843 }
844
845
846 // Render the local tiles
847 void FGTileMgr::render( void ) {
848     FGInterface *f;
849     FGTileCache *c;
850     FGTileEntry *t;
851     FGView *v;
852     Point3D frag_offset;
853     fgFRAGMENT *frag_ptr;
854     FGMaterialSlot *mtl_ptr;
855     int i;
856     int index;
857     int culled = 0;
858     int drawn = 0;
859
860     c = &global_tile_cache;
861     f = current_aircraft.fdm_state;
862     v = &current_view;
863
864     int tile_diameter = current_options.get_tile_diameter();
865
866     // moved to fgTileMgrUpdate, right after we check if we need to
867     // load additional tiles:
868     // scenery.cur_elev = fgTileMgrCurElev( FG_Longitude, FG_Latitude, 
869     //                                      v->abs_view_pos );
870  
871     // initialize the transient per-material fragment lists
872     material_mgr.init_transient_material_lists();
873    
874     // Pass 1
875     // traverse the potentially viewable tile list
876     for ( i = 0; i < (tile_diameter * tile_diameter); i++ ) {
877         index = tiles[i];
878         // fgPrintf( FG_TERRAIN, FG_DEBUG, "Index = %d\n", index);
879         t = c->get_tile(index);
880
881         if ( t->is_loaded() ) {
882
883             // calculate tile offset
884             t->SetOffset( scenery.center );
885
886             // Course (tile based) culling
887             if ( viewable(t->offset, t->bounding_radius) ) {
888                 // at least a portion of this tile could be viewable
889             
890                 // Calculate the model_view transformation matrix for this tile
891                 // This is equivalent to doing a glTranslatef(x, y, z);
892                 t->update_view_matrix( v->get_MODEL_VIEW() );
893
894                 // xglPushMatrix();
895                 // xglTranslatef(t->offset.x, t->offset.y, t->offset.z);
896
897                 // traverse fragment list for tile
898                 FGTileEntry::FragmentIterator current = t->begin();
899                 FGTileEntry::FragmentIterator last = t->end();
900
901                 for ( ; current != last; ++current ) {
902                     frag_ptr = &(*current);
903                 
904                     if ( frag_ptr->display_list >= 0 ) {
905                         // Fine (fragment based) culling
906                         frag_offset = frag_ptr->center - scenery.center;
907
908                         if ( viewable(frag_offset, 
909                                       frag_ptr->bounding_radius*2) )
910                         {
911                             // add to transient per-material property
912                             // fragment list
913
914                             // frag_ptr->tile_offset.x = t->offset.x;
915                             // frag_ptr->tile_offset.y = t->offset.y;
916                             // frag_ptr->tile_offset.z = t->offset.z;
917
918                             mtl_ptr = frag_ptr->material_ptr;
919                             // printf(" lookup = %s\n", mtl_ptr->texture_name);
920                             if ( ! mtl_ptr->append_sort_list( frag_ptr ) ) {
921                                 FG_LOG( FG_TERRAIN, FG_ALERT,
922                                         "Overran material sorting array" );
923                             }
924
925                             // xglCallList(frag_ptr->display_list);
926                             drawn++;
927                         } else {
928                             // printf("Culled a fragment %.2f %.2f %.2f %.2f\n",
929                             //        frag_ptr->center.x, frag_ptr->center.y,
930                             //        frag_ptr->center.z, 
931                             //        frag_ptr->bounding_radius);
932                             culled++;
933                         }
934                     }
935                 }
936
937                 // xglPopMatrix();
938             } else {
939                 culled += t->fragment_list.size();
940             }
941         } else {
942             FG_LOG( FG_TERRAIN, FG_DEBUG, "Skipping a not yet loaded tile" );
943         }
944     }
945
946     if ( (drawn + culled) > 0 ) {
947         v->set_vfc_ratio( (double)culled / (double)(drawn + culled) );
948     } else {
949         v->set_vfc_ratio( 0.0 );
950     }
951     // printf("drawn = %d  culled = %d  saved = %.2f\n", drawn, culled, 
952     //        v->vfc_ratio);
953
954     // Pass 2
955     // traverse the transient per-material fragment lists and render
956     // out all fragments for each material property.
957     xglPushMatrix();
958     material_mgr.render_fragments();
959     xglPopMatrix();
960 }