]> git.mxchange.org Git - flightgear.git/blob - src/FDM/groundcache.cxx
5c4be473ffe0e56cfb5bc2c1e396fb1d60de5a95
[flightgear.git] / src / FDM / groundcache.cxx
1 // groundcache.cxx -- carries a small subset of the scenegraph near the vehicle
2 //
3 // Written by Mathias Froehlich, started Nov 2004.
4 //
5 // Copyright (C) 2004  Mathias Froehlich - Mathias.Froehlich@web.de
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 #include <float.h>
25
26 #include <plib/sg.h>
27
28 #include <simgear/constants.h>
29 #include <simgear/debug/logstream.hxx>
30 #include <simgear/math/sg_geodesy.hxx>
31
32 #include <Main/globals.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scenery/tilemgr.hxx>
35 #include <AIModel/AICarrier.hxx>
36
37 #include "flight.hxx"
38 #include "groundcache.hxx"
39
40 FGGroundCache::FGGroundCache()
41 {
42   sgdSetVec3(cache_center, 0.0, 0.0, 0.0);
43   ground_radius = 0.0;
44   cache_ref_time = 0.0;
45   wire_id = 0;
46   sgdSetVec3(reference_wgs84_point, 0.0, 0.0, 0.0);
47   reference_vehicle_radius = 0.0;
48   found_ground = false;
49 }
50
51 FGGroundCache::~FGGroundCache()
52 {
53   cache_root.removeAllKids();
54 }
55
56 FGGroundCache::GroundProperty*
57 FGGroundCache::extractGroundProperty( ssgLeaf* l )
58 {
59   // FIXME: Do more ...
60   // Idea: have a get_globals() function which knows about that stuff.
61   // Or most propably read that from a configuration file,
62   // from property tree or whatever ...
63   
64   // Get ground dependent data.
65   GroundProperty *gp = new GroundProperty;
66   gp->wire_id = -1;
67   
68   FGAICarrierHardware *ud =
69     dynamic_cast<FGAICarrierHardware*>(l->getUserData());
70   if (ud) {
71     switch (ud->type) {
72     case FGAICarrierHardware::Wire:
73       gp->type = FGInterface::Wire;
74       gp->wire_id = ud->id;
75       break;
76     case FGAICarrierHardware::Catapult:
77       gp->type = FGInterface::Catapult;
78       break;
79     default:
80       gp->type = FGInterface::Solid;
81       break;
82     }
83
84     // Copy the velocity from the carrier class.
85     ud->carrier->getVelocityWrtEarth( gp->vel );
86   }
87
88   else {
89
90     // Initialize velocity field.
91     sgSetVec3( gp->vel, 0.0, 0.0, 0.0 );
92   }
93   
94   // Get the texture name and decide what ground type we have.
95   ssgState *st = l->getState();
96   if (st != NULL && st->isAKindOf(ssgTypeSimpleState())) {
97     ssgSimpleState *ss = (ssgSimpleState*)st;
98     SGPath fullPath( ss->getTextureFilename() ? ss->getTextureFilename(): "" );
99     string file = fullPath.file();
100     SGPath dirPath(fullPath.dir());
101     string category = dirPath.file();
102     
103     SG_LOG(SG_FLIGHT,SG_INFO,
104            "New triangle in cache: " << category << " " << file );
105     
106     if (category == "Runway")
107       gp->type = FGInterface::Solid;
108     else {
109       if (file == "asphault.rgb" || file == "airport.rgb")
110         gp->type = FGInterface::Solid;
111       else if (file == "water.rgb" || file == "water-lake.rgb")
112         gp->type = FGInterface::Water;
113       else if (file == "forest.rgb" || file == "cropwood.rgb")
114         gp->type = FGInterface::Forest;
115     }
116   }
117   
118   return gp;
119 }
120
121 // Test if the line given by the point on the line pt_on_line and the
122 // line direction dir intersects the sphere sp.
123 // Adapted from plib.
124 static bool
125 sgIsectSphereInfLine(const sgSphere *sp,
126                      const sgVec3 pt_on_line, const sgVec3 dir)
127 {
128   sgVec3 r ;
129   sgSubVec3 ( r, sp->getCenter(), pt_on_line ) ;
130
131   SGfloat projectedDistance = sgScalarProductVec3(r, dir);
132  
133   SGfloat dist = sgScalarProductVec3 ( r, r ) -
134     projectedDistance * projectedDistance; 
135
136   SGfloat radius = sp->getRadius();
137   return dist < radius*radius;
138 }
139
140 void
141 FGGroundCache::addAndFlattenLeaf(GLenum ty, ssgLeaf *l, ssgIndexArray *ia,
142                                  const sgMat4 xform)
143 {
144   // Extract data from the leaf which is just copied.
145   ssgVertexArray *va = ((ssgVtxTable *)l)->getVertices();
146   ssgNormalArray *na = ((ssgVtxTable *)l)->getNormals();
147   // Create a new leaf.
148   ssgVtxArray *vtxa = new ssgVtxArray( ty, va, na, 0, 0, ia );
149   // Clones data ...
150   vtxa->removeUnusedVertices();
151   // Apply transform. We won't store transforms in our cache.
152   vtxa->transform( xform );
153   // Check for magic texture names object names and such ...
154   GroundProperty *gp = extractGroundProperty( l );
155   // Assertation???
156   if ( !gp ) {
157     cerr << "Newly created cache leaf where userdata is not a Ground property!" << endl;
158   }
159   vtxa->setUserData( gp );
160   vtxa->setCullFace( l->getCullFace() );
161   
162   // Finally append to cache.
163   cache_root.addKid((ssgEntity*)vtxa);
164 }
165
166 void
167 FGGroundCache::putLineLeafIntoCache(const sgSphere *wsp, const sgMat4 xform,
168                                     ssgLeaf *l)
169 {
170   ssgIndexArray *ia = 0;
171   
172   // Lines must have special meanings.
173   // Wires and catapults are done with lines.
174   int nl = l->getNumLines();
175   for (int i = 0; i < nl; ++i) {
176     sgSphere tmp;
177     short v[2];
178     l->getLine(i, v, v+1 );
179     for (int k=0; k<2; ++k)
180       tmp.extend( l->getVertex( v[k] ) );
181     tmp.orthoXform(xform);
182     
183     if (wsp->intersects( &tmp )) {
184       if (ia == 0)
185         ia = new ssgIndexArray();
186         
187       ia->add( v[0] );
188       ia->add( v[1] );
189     }
190   }
191   if (!ia)
192     return;
193   
194   addAndFlattenLeaf(GL_LINES, l, ia, xform);
195 }
196
197 void
198 FGGroundCache::putSurfaceLeafIntoCache(const sgSphere *sp, const sgMat4 xform,
199                                        bool sphIsec, sgVec3 down, ssgLeaf *l)
200 {
201   ssgIndexArray *ia = 0;
202   
203   int nt = l->getNumTriangles();
204   for (int i = 0; i < nt; ++i) {
205     // Build up a sphere around that particular triangle-
206     sgSphere tmp;
207     short v[3];
208     l->getTriangle(i, v, v+1, v+2 );
209     for (int k=0; k<3; ++k)
210       tmp.extend( l->getVertex( v[k] ) );
211     tmp.orthoXform(xform);
212
213     // Check if the sphere around the vehicle intersects the sphere
214     // around that triangle. If so, put that triangle into the cache.
215     if (sphIsec && sp->intersects( &tmp )) {
216       if (ia == 0)
217         ia = new ssgIndexArray();
218       
219       ia->add( v[0] );
220       ia->add( v[1] );
221       ia->add( v[2] );
222     }
223     
224     // In case the cache is empty, we still provide agl computations.
225     // But then we use the old way of having a fixed elevation value for
226     // the whole lifetime of this cache.
227     if ( sgIsectSphereInfLine(&tmp, sp->getCenter(), down) ) {
228       sgVec3 tri[3];
229       for (int k=0; k<3; ++k) {
230         sgCopyVec3( tri[k], l->getVertex( v[k] ) );
231         sgXformPnt3( tri[k], xform );
232       }
233       
234       sgVec4 plane;
235       sgMakePlane( plane, tri[0], tri[1], tri[2]  );
236       sgVec3 ac_cent;
237       sgCopyVec3(ac_cent, sp->getCenter());
238       sgVec3 dst;
239       sgIsectInfLinePlane( dst, ac_cent, down, plane );
240       if ( sgPointInTriangle ( dst, tri ) ) {
241         found_ground = true;
242         sgdVec3 ddst;
243         sgdSetVec3(ddst, dst);
244         sgdAddVec3(ddst, cache_center);
245         double this_radius = sgdLengthVec3(ddst);
246         if (ground_radius < this_radius)
247           ground_radius = this_radius;
248       }
249     }
250   }
251   if (!ia)
252     return;
253   
254   addAndFlattenLeaf(GL_TRIANGLES, l, ia, xform);
255 }
256
257 // Here is the point where rotation should be handled
258 void
259 FGGroundCache::extractCacheRelativeVertex(double t, ssgVtxArray *va,
260                                           GroundProperty *gp,
261                                           short i, sgVec3 rel_pos,
262                                           sgdVec3 wgs84_vel)
263 {
264   sgCopyVec3( rel_pos, va->getVertex( i ) );
265   sgAddScaledVec3( rel_pos, gp->vel, t );
266
267   // Set velocity.
268   sgdSetVec3( wgs84_vel, gp->vel );
269 }
270
271 void
272 FGGroundCache::extractWgs84Vertex(double t, ssgVtxArray *va,
273                                   GroundProperty *gp, short i,
274                                   sgdVec3 wgs84_pos, sgdVec3 wgs84_vel)
275 {
276   sgVec3 rel_pos;
277   extractCacheRelativeVertex(t, va, gp, i, rel_pos, wgs84_vel);
278   sgdSetVec3( wgs84_pos, rel_pos );
279   sgdAddVec3( wgs84_pos, cache_center );
280 }
281
282
283 void
284 FGGroundCache::cache_fill(ssgBranch *branch, sgMat4 xform,
285                           sgSphere* sp, sgVec3 down, sgSphere* wsp)
286 {
287   // Travel through all kids.
288   ssgEntity *e;
289   for ( e = branch->getKid(0); e != NULL ; e = branch->getNextKid() ) {
290     if ( !( e->getTraversalMask() & SSGTRAV_HOT) )
291       continue;
292     if ( e->getBSphere()->isEmpty() )
293       continue;
294     
295     // Wee need to check further if either the sphere around the branch
296     // intersects the sphere around the aircraft or the line downwards from
297     // the aircraft intersects the branchs sphere.
298     sgSphere esphere = *(e->getBSphere());
299     esphere.orthoXform(xform);
300     bool wspIsec = wsp->intersects(&esphere);
301     bool downIsec = sgIsectSphereInfLine(&esphere, sp->getCenter(), down);
302     if (!wspIsec && !downIsec)
303       continue;
304       
305     // For branches collect up the transforms to reach that branch and
306     // call cache_fill recursively.
307     if ( e->isAKindOf( ssgTypeBranch() ) ) {
308       ssgBranch *b = (ssgBranch *)e;
309       if ( b->isAKindOf( ssgTypeTransform() ) ) {
310         // Collect up the transfors required to reach that part of
311         // the branch.
312         sgMat4 xform2;
313         sgMakeIdentMat4( xform2 );
314         ssgTransform *t = (ssgTransform*)b;
315         t->getTransform( xform2 );
316         sgPostMultMat4( xform2, xform );
317         cache_fill( b, xform2, sp, down, wsp );
318       } else
319         cache_fill( b, xform, sp, down, wsp );
320     }
321    
322     // For leafs, check each triangle for intersection.
323     // This will minimize the number of vertices/triangles in the cache.
324     else if (e->isAKindOf(ssgTypeLeaf())) {
325       // Since we reach that leaf if we have an intersection with the
326       // most propably bigger wire/catapult cache sphere, we need to check
327       // that here, if the smaller cache for the surface has a chance for hits.
328       // Also, if the spheres do not intersect compute a croase agl value
329       // by following the line downwards originating at the aircraft.
330       bool spIsec = sp->intersects(&esphere);
331       putSurfaceLeafIntoCache(sp, xform, spIsec, down, (ssgLeaf *)e);
332
333       // If we are here, we need to put all special hardware here into
334       // the cache.
335       if (wspIsec)
336         putLineLeafIntoCache(wsp, xform, (ssgLeaf *)e);
337     }
338   }
339 }
340
341 bool
342 FGGroundCache::prepare_ground_cache(double ref_time, const double pt[3],
343                                       double rad)
344 {
345   Point3D old_cntr = globals->get_scenery()->get_center();
346   Point3D cntr(pt[0], pt[1], pt[2]);
347   globals->get_scenery()->set_center( cntr );
348
349   // Empty cache.
350   cache_root.removeAllKids();
351   ground_radius = 0.0;
352   found_ground = false;
353
354   // Store the parameters we used to build up that cache.
355   sgdCopyVec3(reference_wgs84_point, pt);
356   reference_vehicle_radius = rad;
357   // Store the time reference used to compute movements of moving triangles.
358   cache_ref_time = ref_time;
359
360   // The center of the cache.
361   sgdCopyVec3(cache_center, pt);
362   
363   sgVec3 zero;
364   sgZeroVec3(zero);
365   // Prepare sphere around the aircraft.
366   sgSphere acSphere;
367   acSphere.setRadius(rad);
368   acSphere.setCenter(zero);
369
370   // Prepare bigger sphere around the aircraft.
371   // This one is required for reliably finding wires we have caught but
372   // have already left the hopefully smaller sphere for the ground reactions.
373   const double max_wire_dist = 300.0;
374   sgSphere wireSphere;
375   wireSphere.setRadius(max_wire_dist < rad ? rad : max_wire_dist);
376   wireSphere.setCenter(zero);
377
378   // Down vector. Is used for croase agl computations when we are far enough
379   // from ground that we have an empty cache.
380   sgVec3 down;
381   sgSetVec3(down, -pt[0], -pt[1], -pt[2]);
382   sgNormalizeVec3(down);
383
384   // We need the offset to the scenery scenery center.
385   sgdVec3 doffset;
386   Point3D psc = globals->get_scenery()->get_center();
387   sgdSetVec3(doffset, psc[0], psc[1], psc[2]);
388   sgdSubVec3(doffset, doffset, pt);
389
390   // We collaps all transforms we need to reach a particular leaf.
391   // The leafs itself will be then transformed later.
392   // So our cache is just flat.
393   // For leafs which are moving (carriers surface, etc ...)
394   // we will later store a speed in the GroundType class. We can then apply
395   // some translations to that nodes according to the time which has passed
396   // compared to that snapshot.
397   sgVec3 offset;
398   sgSetVec3(offset, doffset[0], doffset[1], doffset[2]);
399   sgMat4 xform;
400   sgMakeTransMat4(xform, offset);
401
402
403   // Walk the scene graph and extract solid ground triangles and carrier data.
404   ssgBranch *terrain = globals->get_scenery()->get_scene_graph();
405   cache_fill(terrain, xform, &acSphere, down, &wireSphere);
406
407   // some stats
408   SG_LOG(SG_FLIGHT,SG_INFO, "prepare_ground_cache(): ac radius = " << rad
409          << ", # leafs = " << cache_root.getNumKids()
410          << ", ground_radius = " << ground_radius );
411
412   // If the ground radius is still below 5e6 meters, then we do not yet have
413   // any scenery.
414   found_ground = found_ground && 5e6 < ground_radius;
415   if (!found_ground)
416     SG_LOG(SG_FLIGHT, SG_WARN, "prepare_ground_cache(): trying to build cache "
417            "without any scenery below the aircraft" );
418
419   globals->get_scenery()->set_center( old_cntr );
420
421   return found_ground;
422 }
423
424 bool
425 FGGroundCache::is_valid(double *ref_time, double pt[3], double *rad)
426 {
427   sgdCopyVec3(pt, reference_wgs84_point);
428   *rad = reference_vehicle_radius;
429   *ref_time = cache_ref_time;
430   return found_ground;
431 }
432
433 double
434 FGGroundCache::get_cat(double t, const double dpt[3],
435                          double end[2][3], double vel[2][3])
436 {
437   // start with a distance of 1e10 meters...
438   double dist = 1e10;
439
440   // Time difference to the reference time.
441   t -= cache_ref_time;
442
443   // We know that we have a flat cache ...
444   ssgEntity *e;
445   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
446     // We just know that, because we build that ourselfs ...
447     ssgVtxArray *va = (ssgVtxArray *)e;
448     // Only lines are interresting ...
449     if (va->getPrimitiveType() != GL_LINES)
450       continue;
451     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
452     // Check if we have a catapult ...
453     if ( gp->type != FGInterface::Catapult )
454       continue;
455
456     int nl = va->getNumLines();
457     for (int i=0; i < nl; ++i) {
458       sgdLineSegment3 ls;
459       sgdVec3 lsVel[2];
460       short vi[2];
461       va->getLine(i, vi, vi+1 );
462       extractWgs84Vertex(t, va, gp, vi[0], ls.a, lsVel[0]);
463       extractWgs84Vertex(t, va, gp, vi[1], ls.b, lsVel[1]);
464       
465       double this_dist = sgdDistSquaredToLineSegmentVec3( ls, dpt );
466       if (this_dist < dist) {
467         dist = this_dist;
468         
469         // end[0] is the end where the cat starts.
470         // end[1] is the end where the cat ends.
471         // The carrier code takes care of that ordering.
472         sgdCopyVec3( end[0], ls.a );
473         sgdCopyVec3( end[1], ls.b );
474         sgdCopyVec3( vel[0], lsVel[0] );
475         sgdCopyVec3( vel[1], lsVel[1] );
476       }
477     }
478   }
479
480   // At the end take the root, we only computed squared distances ...
481   return sqrt(dist);
482 }
483
484 bool
485 FGGroundCache::get_agl(double t, const double dpt[3],
486                          double contact[3], double normal[3], double vel[3],
487                          int *type, double *loadCapacity,
488                          double *frictionFactor, double *agl)
489 {
490   bool ret = false;
491
492   *type = FGInterface::Unknown;
493 //   *agl = 0.0;
494   *loadCapacity = DBL_MAX;
495   *frictionFactor = 1.0;
496   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
497   sgdSetVec3( contact, 0.0, 0.0, 0.0 );
498   sgdSetVec3( normal, 0.0, 0.0, 0.0 );
499
500   // Time difference to th reference time.
501   t -= cache_ref_time;
502
503   // The double valued point we start to search for intersection.
504   sgdVec3 tmp;
505   sgdSubVec3( tmp, dpt, cache_center );
506   sgVec3 pt;
507   sgSetVec3( pt, tmp );
508
509   // The search direction
510   sgVec3 dir;
511   sgSetVec3( dir, -dpt[0], -dpt[1], -dpt[2] );
512
513   // Initialize to something sensible
514   double sqdist = DBL_MAX;
515
516   // We know that we have a flat cache ...
517   // We just know that, because we build that ourselfs ...
518   ssgEntity *e;
519   for ( e = cache_root.getKid(0) ; e != NULL ; e = cache_root.getNextKid() ) {
520     // We just know that, because we build that ourselfs ...
521     ssgVtxArray *va = (ssgVtxArray *)e;
522     // AGL computations are done with triangle/surface leafs.
523     if (va->getPrimitiveType() != GL_TRIANGLES)
524       continue;
525     ssgBase *gpb = va->getUserData();
526     // Assertation???
527     if ( !gpb ) {
528       cerr << "Found cache leaf without userdata!" << endl;
529       continue;
530     }
531     GroundProperty *gp = static_cast<GroundProperty*>(gpb);
532
533     int nt = va->getNumTriangles();
534     for (int i=0; i < nt; ++i) {
535       short vi[3];
536       va->getTriangle( i, vi, vi+1, vi+2 );
537       
538       sgVec3 tri[3];
539       sgdVec3 dvel[3];
540       for (int k=0; k<3; ++k)
541         extractCacheRelativeVertex(t, va, gp, vi[k], tri[k], dvel[k]);
542       sgVec4 plane;
543       sgMakePlane( plane, tri[0], tri[1], tri[2] );
544       
545       // Check for intersection.
546       sgVec3 isecpoint;
547       if ( sgIsectInfLinePlane( isecpoint, pt, dir, plane ) &&
548            sgPointInTriangle3( isecpoint, tri ) ) {
549         // Only accept surfaces with the normal pointing upwards.
550         // For double sided surfaces flip the normal in this case.
551         float dirDot = sgScalarProductVec3(plane, dir);
552         if ( dirDot >= 0 && va->getCullFace() == 1 ) {
553           sgScaleVec4( plane, -1 );
554           dirDot = -dirDot;
555         }
556
557         // Check for the closest intersection point.
558         // FIXME: is this the right one?
559         double newSqdist = sgDistanceSquaredVec3( isecpoint, pt );
560         if ( newSqdist < sqdist && dirDot < 0 ) {
561           sqdist = newSqdist;
562           ret = true;
563           // Save the new potential intersection point.
564           sgdSetVec3( contact, isecpoint );
565           sgdAddVec3( contact, cache_center );
566           // The first three values in the vector are the plane normal.
567           sgdSetVec3( normal, plane );
568           // Remormalize that as double, else it *can* have surprising effects
569           // when used as plane normal together with a 6000000m offset in a
570           // plane equation.
571           sgdNormalizeVec3( normal );
572           // The velocity wrt earth.
573           /// FIXME: only true for non rotating objects!!!!
574           sgdCopyVec3( vel, dvel[0] );
575           // Save the ground type.
576           *type = gp->type;
577           // FIXME: figure out how to get that sign ...
578 //           *agl = sqrt(sqdist);
579           *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
580 //           *loadCapacity = DBL_MAX;
581 //           *frictionFactor = 1.0;
582         }
583       }
584     }
585   }
586
587   if (ret)
588     return true;
589
590   // Whenever we did not have a ground triangle for the requested point,
591   // take the ground level we found during the current cache build.
592   // This is as good as what we had before for agl.
593   double r = sgdLengthVec3( dpt );
594   sgdCopyVec3( contact, dpt );
595   sgdScaleVec3( contact, ground_radius/r );
596   sgdCopyVec3( normal, dpt );
597   sgdNormaliseVec3( normal );
598   sgdSetVec3( vel, 0.0, 0.0, 0.0 );
599   
600   // The altitude is the distance of the requested point from the
601   // contact point.
602   *agl = sgdLengthVec3( dpt ) - sgdLengthVec3( contact );
603   *type = FGInterface::Unknown;
604   *loadCapacity = DBL_MAX;
605   *frictionFactor = 1.0;
606
607   return ret;
608 }
609
610 bool FGGroundCache::caught_wire(double t, const double cpt[4][3])
611 {
612   bool ret = false;
613
614   // Time difference to the reference time.
615   t -= cache_ref_time;
616
617   bool firsttime = true;
618   sgVec4 plane[2];
619   sgVec3 tri[2][3];
620
621   // We know that we have a flat cache ...
622   ssgEntity *e;
623   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
624     // We just know that, because we build that ourselfs ...
625     ssgVtxArray *va = (ssgVtxArray *)e;
626     // Only lines are interresting ...
627     if (va->getPrimitiveType() != GL_LINES)
628       continue;
629     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
630     // Check if we have a catapult ...
631     if ( gp->type != FGInterface::Wire )
632       continue;
633
634     // Lazy compute the values required for intersectiion tests.
635     // Since we normally do not have wires in the cache this is a
636     // huge benefit.
637     if (firsttime) {
638       firsttime = false;
639       sgVec3 pt[4];
640       for (int k=0; k<4; ++k) {
641         sgdVec3 tmp;
642         sgdSubVec3( tmp, cpt[k], cache_center );
643         sgSetVec3( pt[k], tmp );
644       }
645       sgMakePlane( plane[0], pt[0], pt[1], pt[2] );
646       sgCopyVec3( tri[0][0], pt[0] );
647       sgCopyVec3( tri[0][1], pt[1] );
648       sgCopyVec3( tri[0][2], pt[2] );
649       sgMakePlane( plane[1], pt[0], pt[2], pt[3] );
650       sgCopyVec3( tri[1][0], pt[0] );
651       sgCopyVec3( tri[1][1], pt[2] );
652       sgCopyVec3( tri[1][2], pt[3] );
653     }
654     
655     int nl = va->getNumLines();
656     for (int i=0; i < nl; ++i) {
657       short vi[2];
658       va->getLine(i, vi, vi+1 );
659       sgVec3 le[2];
660       sgdVec3 dummy;
661       extractCacheRelativeVertex(t, va, gp, vi[0], le[0], dummy);
662       extractCacheRelativeVertex(t, va, gp, vi[1], le[1], dummy);
663       
664       for (int k=0; k<2; ++k) {
665         sgVec3 isecpoint;
666         float isecval = sgIsectLinesegPlane( isecpoint, le[0], le[1], plane[k] );
667         
668         if ( 0.0 <= isecval && isecval <= 1.0 &&
669              sgPointInTriangle( isecpoint, tri[k] ) ) {
670           // Store the wire id.
671           wire_id = gp->wire_id;
672           ret = true;
673         }
674       }
675     }
676   }
677
678   return ret;
679 }
680
681 bool FGGroundCache::get_wire_ends(double t, double end[2][3], double vel[2][3])
682 {
683   // Fast return if we do not have an active wire.
684   if (wire_id < 0)
685     return false;
686
687   bool ret = false;
688
689   // Time difference to th reference time.
690   t -= cache_ref_time;
691
692   // We know that we have a flat cache ...
693   ssgEntity *e;
694   for ( e = cache_root.getKid(0); e != NULL ; e = cache_root.getNextKid() ) {
695     // We just know that, because we build that ourselfs ...
696     ssgVtxArray *va = (ssgVtxArray *)e;
697     // Only lines are interresting ...
698     if (va->getPrimitiveType() != GL_LINES)
699       continue;
700     GroundProperty *gp = static_cast<GroundProperty*>(va->getUserData());
701     // Check if we have a catapult ...
702     if ( gp->type != FGInterface::Wire )
703       continue;
704     if ( gp->wire_id != wire_id )
705       continue;
706
707     // Get the line ends, that are the wire endpoints.
708     short vi[2];
709     va->getLine(0, vi, vi+1 );
710     extractWgs84Vertex(t, va, gp, vi[0], end[0], vel[0]);
711     extractWgs84Vertex(t, va, gp, vi[1], end[1], vel[1]);
712
713     ret = true;
714   }
715
716   return ret;
717 }
718
719 void FGGroundCache::release_wire(void)
720 {
721   wire_id = -1;
722 }