]> git.mxchange.org Git - flightgear.git/blob - src/FDM/groundcache.cxx
3ffc28331cf227b6654f35c68c4eaec1e999506b
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <float.h>
28
29 #include <plib/sg.h>
30 #include <osg/CullFace>
31 #include <osg/Drawable>
32 #include <osg/Geode>
33 #include <osg/Geometry>
34 #include <osg/TriangleFunctor>
35
36 #include <simgear/sg_inlines.h>
37 #include <simgear/constants.h>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/math/sg_geodesy.hxx>
40 #include <simgear/scene/material/mat.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42 #include <simgear/scene/util/SGNodeMasks.hxx>
43
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <Scenery/tilemgr.hxx>
47 #include <AIModel/AICarrier.hxx>
48
49 #include "flight.hxx"
50 #include "groundcache.hxx"
51
52 static inline bool
53 fgdRayTriangle(SGVec3d& x, const SGVec3d& point, const SGVec3d& dir,
54                const SGVec3d v[3])
55 {
56   double eps = 1e-4;
57   // Method based on the observation that we are looking for a
58   // point x that can be expressed in terms of the triangle points
59   //  x = p_0 + \mu_1*(p_1 - p_0) + \mu_2*(p_2 - p_0)
60   // with 0 <= \mu_1, \mu_2 and \mu_1 + \mu_2 <= 1.
61   // OTOH it could be expressed in terms of the ray
62   //  x = point + \lambda*dir
63   // Now we can compute \mu_i and \lambda.
64   // define
65   SGVec3d d1 = v[1] - v[0];
66   SGVec3d d2 = v[2] - v[0];
67   SGVec3d b = point - v[0];
68   
69   // the vector in normal direction, but not normalized
70   SGVec3d d1crossd2 = cross(d1, d2);
71   
72   double denom = -dot(dir, d1crossd2);
73   double signDenom = copysign(1, denom);
74   // return if paralell ??? FIXME what if paralell and in plane?
75   // may be we are ok below than anyway??
76   // if (SGMiscd::abs(denom) <= SGLimitsd::min())
77   //   return false;
78   
79   // Now \lambda would read
80   //   lambda = 1/denom*dot(b, d1crossd2);
81   // To avoid an expensive division we multiply by |denom|
82   double lambdaDenom = signDenom*dot(b, d1crossd2);
83   if (lambdaDenom < 0)
84     return false;
85   // For line segment we would test against
86   // if (1 < lambda)
87   //   return false;
88   // with the original lambda. The multiplied test would read
89   // if (absDenom < lambdaDenom)
90   //   return false;
91
92   double absDenom = fabs(denom);
93   double absDenomEps = absDenom*eps;
94   
95   SGVec3d bcrossr = cross(b, dir);
96   // double mu1 = 1/denom*dot(d2, bcrossr);
97   double mu1 = signDenom*dot(d2, bcrossr);
98   if (mu1 < -absDenomEps)
99     return false;
100   // double mu2 = -1/denom*dot(d1, bcrossr);
101   // if (mu2 < -eps)
102   //   return false;
103   double mmu2 = signDenom*dot(d1, bcrossr);
104   if (mmu2 > absDenomEps)
105     return false;
106   
107   if (mu1 - mmu2 > absDenom + absDenomEps)
108     return false;
109
110   x = point;
111   // if we have survived here it could only happen with denom == 0
112   // that the point is already in plane. Then return the origin ...
113   if (SGLimitsd::min() < absDenom)
114     x += (lambdaDenom/absDenom)*dir;
115
116   return true;
117 }
118
119 static inline bool
120 fgdPointInTriangle( const SGVec3d& point, const SGVec3d tri[3] )
121 {
122     SGVec3d dif;
123
124     // Some tolerance in meters we accept a point to be outside of the triangle
125     // and still return that it is inside.
126     SGDfloat min, max;
127     // punt if outside bouding cube
128     SG_MIN_MAX3 ( min, max, tri[0][0], tri[1][0], tri[2][0] );
129     if( (point[0] < min) || (point[0] > max) )
130         return false;
131     dif[0] = max - min;
132
133     SG_MIN_MAX3 ( min, max, tri[0][1], tri[1][1], tri[2][1] );
134     if( (point[1] < min) || (point[1] > max) )
135         return false;
136     dif[1] = max - min;
137
138     SG_MIN_MAX3 ( min, max, tri[0][2], tri[1][2], tri[2][2] );
139     if( (point[2] < min) || (point[2] > max) )
140         return false;
141     dif[2] = max - min;
142
143     // drop the smallest dimension so we only have to work in 2d.
144     SGDfloat min_dim = SG_MIN3 (dif[0], dif[1], dif[2]);
145     SGDfloat x1, y1, x2, y2, x3, y3, rx, ry;
146     if ( fabs(min_dim-dif[0]) <= DBL_EPSILON ) {
147         // x is the smallest dimension
148         x1 = point[1];
149         y1 = point[2];
150         x2 = tri[0][1];
151         y2 = tri[0][2];
152         x3 = tri[1][1];
153         y3 = tri[1][2];
154         rx = tri[2][1];
155         ry = tri[2][2];
156     } else if ( fabs(min_dim-dif[1]) <= DBL_EPSILON ) {
157         // y is the smallest dimension
158         x1 = point[0];
159         y1 = point[2];
160         x2 = tri[0][0];
161         y2 = tri[0][2];
162         x3 = tri[1][0];
163         y3 = tri[1][2];
164         rx = tri[2][0];
165         ry = tri[2][2];
166     } else if ( fabs(min_dim-dif[2]) <= DBL_EPSILON ) {
167         // z is the smallest dimension
168         x1 = point[0];
169         y1 = point[1];
170         x2 = tri[0][0];
171         y2 = tri[0][1];
172         x3 = tri[1][0];
173         y3 = tri[1][1];
174         rx = tri[2][0];
175         ry = tri[2][1];
176     } else {
177         // all dimensions are really small so lets call it close
178         // enough and return a successful match
179         return true;
180     }
181
182     // check if intersection point is on the same side of p1 <-> p2 as p3
183     SGDfloat tmp = (y2 - y3);
184     SGDfloat tmpn = (x2 - x3);
185     int side1 = SG_SIGN (tmp * (rx - x3) + (y3 - ry) * tmpn);
186     int side2 = SG_SIGN (tmp * (x1 - x3) + (y3 - y1) * tmpn);
187     if ( side1 != side2 ) {
188         // printf("failed side 1 check\n");
189         return false;
190     }
191
192     // check if intersection point is on correct side of p2 <-> p3 as p1
193     tmp = (y3 - ry);
194     tmpn = (x3 - rx);
195     side1 = SG_SIGN (tmp * (x2 - rx) + (ry - y2) * tmpn);
196     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn);
197     if ( side1 != side2 ) {
198         // printf("failed side 2 check\n");
199         return false;
200     }
201
202     // check if intersection point is on correct side of p1 <-> p3 as p2
203     tmp = (y2 - ry);
204     tmpn = (x2 - rx);
205     side1 = SG_SIGN (tmp * (x3 - rx) + (ry - y3) * tmpn);
206     side2 = SG_SIGN (tmp * (x1 - rx) + (ry - y1) * tmpn);
207     if ( side1 != side2 ) {
208         // printf("failed side 3  check\n");
209         return false;
210     }
211
212     return true;
213 }
214
215 // Test if the line given by the point on the line pt_on_line and the
216 // line direction dir intersects the sphere sp.
217 // Adapted from plib.
218 static inline bool
219 fgdIsectSphereInfLine(const SGVec3d& sphereCenter, double radius,
220                       const SGVec3d& pt_on_line, const SGVec3d& dir)
221 {
222   SGVec3d r = sphereCenter - pt_on_line;
223   double projectedDistance = dot(r, dir);
224   double dist = dot(r, r) - projectedDistance * projectedDistance;
225   return dist < radius*radius;
226 }
227
228 template<typename T>
229 class SGExtendedTriangleFunctor : public osg::TriangleFunctor<T> {
230 public:
231   // Ok, to be complete we should also implement the indexed variants
232   // For now this one appears to be enough ...
233   void drawArrays(GLenum mode, GLint first, GLsizei count)
234   {
235     if (_vertexArrayPtr==0 || count==0) return;
236
237     const osg::Vec3* vlast;
238     const osg::Vec3* vptr;
239     switch(mode) {
240     case(GL_LINES):
241       vlast = &_vertexArrayPtr[first+count];
242       for(vptr=&_vertexArrayPtr[first];vptr<vlast;vptr+=2)
243         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
244       break;
245     case(GL_LINE_STRIP):
246       vlast = &_vertexArrayPtr[first+count-1];
247       for(vptr=&_vertexArrayPtr[first];vptr<vlast;++vptr)
248         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
249       break;
250     case(GL_LINE_LOOP):
251       vlast = &_vertexArrayPtr[first+count-1];
252       for(vptr=&_vertexArrayPtr[first];vptr<vlast;++vptr)
253         this->operator()(*(vptr),*(vptr+1),_treatVertexDataAsTemporary);
254       this->operator()(_vertexArrayPtr[first+count-1],
255                        _vertexArrayPtr[first],_treatVertexDataAsTemporary);
256       break;
257     default:
258       osg::TriangleFunctor<T>::drawArrays(mode, first, count);
259       break;
260     }
261   }
262 protected:
263   using osg::TriangleFunctor<T>::_vertexArrayPtr;
264   using osg::TriangleFunctor<T>::_treatVertexDataAsTemporary;
265 };
266
267 class GroundCacheFillVisitor : public osg::NodeVisitor {
268 public:
269   
270   /// class to just redirect triangles to the GroundCacheFillVisitor
271   class GroundCacheFill {
272   public:
273     void setGroundCacheFillVisitor(GroundCacheFillVisitor* gcfv)
274     { mGroundCacheFillVisitor = gcfv; }
275     
276     void operator () (const osg::Vec3& v1, const osg::Vec3& v2,
277                       const osg::Vec3& v3, bool)
278     { mGroundCacheFillVisitor->addTriangle(v1, v2, v3); }
279
280     void operator () (const osg::Vec3& v1, const osg::Vec3& v2, bool)
281     { mGroundCacheFillVisitor->addLine(v1, v2); }
282     
283   private:
284     GroundCacheFillVisitor* mGroundCacheFillVisitor;
285   };
286
287
288   GroundCacheFillVisitor(FGGroundCache* groundCache,
289                          const SGVec3d& down, 
290                          const SGVec3d& cacheReference,
291                          double cacheRadius,
292                          double wireCacheRadius) :
293     osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
294     mGroundCache(groundCache)
295   {
296     setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
297     mDown = down;
298     mLocalDown = down;
299     sphIsec = true;
300     mBackfaceCulling = false;
301     mCacheReference = cacheReference;
302     mLocalCacheReference = cacheReference;
303     mCacheRadius = cacheRadius;
304     mWireCacheRadius = wireCacheRadius;
305
306     mTriangleFunctor.setGroundCacheFillVisitor(this);
307
308     mGroundProperty.wire_id = -1;
309     mGroundProperty.vel = SGVec3d(0, 0, 0);
310     mGroundProperty.rot = SGVec3d(0, 0, 0);
311     mGroundProperty.pivot = SGVec3d(0, 0, 0);
312   }
313
314   void updateCullMode(osg::StateSet* stateSet)
315   {
316     if (!stateSet)
317       return;
318
319     osg::StateAttribute* stateAttribute;
320     stateAttribute = stateSet->getAttribute(osg::StateAttribute::CULLFACE);
321     if (!stateAttribute)
322       return;
323     osg::CullFace* cullFace = static_cast<osg::CullFace*>(stateAttribute);
324     mBackfaceCulling = cullFace->getMode() == osg::CullFace::BACK;
325   }
326
327   bool enterBoundingSphere(const osg::BoundingSphere& bs)
328   {
329     if (!bs.valid())
330       return false;
331
332     SGVec3d cntr(osg::Vec3d(bs.center())*mLocalToGlobal);
333     double rc = bs.radius() + mCacheRadius;
334     // Ok, this node might intersect the cache. Visit it in depth.
335     double centerDist2 = distSqr(mCacheReference, cntr);
336     if (centerDist2 < rc*rc) {
337       sphIsec = true;
338     } else {
339       // Check if the down direction touches the bounding sphere of the node
340       // if so, do at least croase agl computations.
341       // Ther other thing is that we must check if we are in range of
342       // cats or wires
343       double rw = bs.radius() + mWireCacheRadius;
344       if (rw*rw < centerDist2 &&
345           !fgdIsectSphereInfLine(cntr, bs.radius(), mCacheReference, mDown))
346         return false;
347       sphIsec = false;
348     }
349
350     return true;
351   }
352
353   bool enterNode(osg::Node& node)
354   {
355     if (!enterBoundingSphere(node.getBound()))
356       return false;
357
358     updateCullMode(node.getStateSet());
359
360     FGGroundCache::GroundProperty& gp = mGroundProperty;
361     // get some material information for use in the gear model
362     gp.material = globals->get_matlib()->findMaterial(&node);
363     if (gp.material) {
364       gp.type = gp.material->get_solid() ? FGInterface::Solid : FGInterface::Water;
365       return true;
366     }
367     osg::Referenced* base = node.getUserData();
368     if (!base)
369       return true;
370     FGAICarrierHardware *ud =
371       dynamic_cast<FGAICarrierHardware*>(base);
372     if (!ud)
373       return true;
374
375     switch (ud->type) {
376     case FGAICarrierHardware::Wire:
377       gp.type = FGInterface::Wire;
378       gp.wire_id = ud->id;
379       break;
380     case FGAICarrierHardware::Catapult:
381       gp.type = FGInterface::Catapult;
382       break;
383     default:
384       gp.type = FGInterface::Solid;
385       break;
386     }
387     // Copy the velocity from the carrier class.
388     ud->carrier->getVelocityWrtEarth(gp.vel, gp.rot, gp.pivot);
389   
390     return true;
391   }
392
393   void fillWith(osg::Drawable* drawable)
394   {
395     bool oldSphIsec = sphIsec;
396     if (!enterBoundingSphere(drawable->getBound()))
397       return;
398
399     bool oldBackfaceCulling = mBackfaceCulling;
400     updateCullMode(drawable->getStateSet());
401
402     drawable->accept(mTriangleFunctor);
403
404     mBackfaceCulling = oldBackfaceCulling;
405     sphIsec = oldSphIsec;
406   }
407
408   virtual void apply(osg::Geode& geode)
409   {
410     bool oldBackfaceCulling = mBackfaceCulling;
411     bool oldSphIsec = sphIsec;
412     FGGroundCache::GroundProperty oldGp = mGroundProperty;
413     if (!enterNode(geode))
414       return;
415
416     for(unsigned i = 0; i < geode.getNumDrawables(); ++i)
417       fillWith(geode.getDrawable(i));
418     sphIsec = oldSphIsec;
419     mGroundProperty = oldGp;
420     mBackfaceCulling = oldBackfaceCulling;
421   }
422
423   virtual void apply(osg::Group& group)
424   {
425     bool oldBackfaceCulling = mBackfaceCulling;
426     bool oldSphIsec = sphIsec;
427     FGGroundCache::GroundProperty oldGp = mGroundProperty;
428     if (!enterNode(group))
429       return;
430     traverse(group);
431     sphIsec = oldSphIsec;
432     mBackfaceCulling = oldBackfaceCulling;
433     mGroundProperty = oldGp;
434   }
435
436   virtual void apply(osg::Transform& transform)
437   {
438     if (!enterNode(transform))
439       return;
440     bool oldBackfaceCulling = mBackfaceCulling;
441     bool oldSphIsec = sphIsec;
442     FGGroundCache::GroundProperty oldGp = mGroundProperty;
443     /// transform the caches center to local coords
444     osg::Matrix oldLocalToGlobal = mLocalToGlobal;
445     osg::Matrix oldGlobalToLocal = mGlobalToLocal;
446     transform.computeLocalToWorldMatrix(mLocalToGlobal, this);
447     transform.computeWorldToLocalMatrix(mGlobalToLocal, this);
448
449     SGVec3d oldLocalCacheReference = mLocalCacheReference;
450     mLocalCacheReference.osg() = mCacheReference.osg()*mGlobalToLocal;
451     SGVec3d oldLocalDown = mLocalDown;
452     mLocalDown.osg() = osg::Matrixd::transform3x3(mDown.osg(), mGlobalToLocal);
453
454     // walk the children
455     traverse(transform);
456
457     // Restore that one
458     mLocalDown = oldLocalDown;
459     mLocalCacheReference = oldLocalCacheReference;
460     mLocalToGlobal = oldLocalToGlobal;
461     mGlobalToLocal = oldGlobalToLocal;
462     sphIsec = oldSphIsec;
463     mBackfaceCulling = oldBackfaceCulling;
464     mGroundProperty = oldGp;
465   }
466   
467   void addTriangle(const osg::Vec3& v1, const osg::Vec3& v2,
468                    const osg::Vec3& v3)
469   {
470     SGVec3d v[3] = {
471       SGVec3d(v1),
472       SGVec3d(v2),
473       SGVec3d(v3)
474     };
475     
476     // a bounding sphere in the node local system
477     SGVec3d boundCenter = (1.0/3)*(v[0] + v[1] + v[2]);
478 #if 0
479     double boundRadius = std::max(norm1(v[0] - boundCenter),
480                                   norm1(v[1] - boundCenter));
481     boundRadius = std::max(boundRadius, norm1(v[2] - boundCenter));
482     // Ok, we take the 1-norm instead of the expensive 2 norm.
483     // Therefore we need that scaling factor - roughly sqrt(3)
484     boundRadius = 1.733*boundRadius;
485 #else
486     double boundRadius = std::max(distSqr(v[0], boundCenter),
487                                   distSqr(v[1], boundCenter));
488     boundRadius = std::max(boundRadius, distSqr(v[2], boundCenter));
489     boundRadius = sqrt(boundRadius);
490 #endif
491
492     // if we are not in the downward cylinder bail out
493     if (!fgdIsectSphereInfLine(boundCenter, boundRadius + mCacheRadius,
494                               mLocalCacheReference, mLocalDown))
495       return;
496
497     
498     // The normal and plane in the node local coordinate system
499     SGVec3d n = normalize(cross(v[1] - v[0], v[2] - v[0]));
500     if (0 < dot(mLocalDown, n)) {
501       if (mBackfaceCulling) {
502         // Surface points downwards, ignore for altitude computations.
503         return;
504       } else {
505         n = -n;
506         std::swap(v[1], v[2]);
507       }
508     }
509     
510     // Only check if the triangle is in the cache sphere if the plane
511     // containing the triangle is near enough
512     if (sphIsec && fabs(dot(n, v[0] - mLocalCacheReference)) < mCacheRadius) {
513       // Check if the sphere around the vehicle intersects the sphere
514       // around that triangle. If so, put that triangle into the cache.
515       double r2 = boundRadius + mCacheRadius;
516       if (distSqr(boundCenter, mLocalCacheReference) < r2*r2) {
517         FGGroundCache::Triangle t;
518         for (unsigned i = 0; i < 3; ++i)
519           t.vertices[i].osg() = v[i].osg()*mLocalToGlobal;
520         t.boundCenter.osg() = boundCenter.osg()*mLocalToGlobal;
521         t.boundRadius = boundRadius;
522         
523         SGVec3d tmp;
524         tmp.osg() = osg::Matrixd::transform3x3(n.osg(), mLocalToGlobal);
525         t.plane = SGVec4d(tmp[0], tmp[1], tmp[2], -dot(tmp, t.vertices[0]));
526         t.velocity = mGroundProperty.vel;
527         t.rotation = mGroundProperty.rot;
528         t.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
529         t.type = mGroundProperty.type;
530         t.material=mGroundProperty.material;
531         mGroundCache->triangles.push_back(t);
532       }
533     }
534     
535     // In case the cache is empty, we still provide agl computations.
536     // But then we use the old way of having a fixed elevation value for
537     // the whole lifetime of this cache.
538     SGVec4d plane = SGVec4d(n[0], n[1], n[2], -dot(n, v[0]));
539     SGVec3d isectpoint;
540
541     if (fgdRayTriangle(isectpoint, mLocalCacheReference, mLocalDown, v)) {
542       mGroundCache->found_ground = true;
543       isectpoint.osg() = isectpoint.osg()*mLocalToGlobal;
544       isectpoint += mGroundCache->cache_center;
545       double this_radius = length(isectpoint);
546       if (mGroundCache->ground_radius < this_radius)
547         mGroundCache->ground_radius = this_radius;
548     }
549   }
550   
551   void addLine(const osg::Vec3& v1, const osg::Vec3& v2)
552   {
553     SGVec3d gv1(osg::Vec3d(v1)*mLocalToGlobal);
554     SGVec3d gv2(osg::Vec3d(v2)*mLocalToGlobal);
555
556     SGVec3d boundCenter = 0.5*(gv1 + gv2);
557     double boundRadius = length(gv1 - boundCenter);
558
559     if (distSqr(boundCenter, mCacheReference)
560         < (boundRadius + mWireCacheRadius)*(boundRadius + mWireCacheRadius) ) {
561       if (mGroundProperty.type == FGInterface::Wire) {
562         FGGroundCache::Wire wire;
563         wire.ends[0] = gv1;
564         wire.ends[1] = gv2;
565         wire.velocity = mGroundProperty.vel;
566         wire.rotation = mGroundProperty.rot;
567         wire.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
568         wire.wire_id = mGroundProperty.wire_id;
569
570         mGroundCache->wires.push_back(wire);
571       }
572       if (mGroundProperty.type == FGInterface::Catapult) {
573         FGGroundCache::Catapult cat;
574         // Trick to get the ends in the right order.
575         // Use the x axis in the original coordinate system. Choose the
576         // most negative x-axis as the one pointing forward
577         if (v1[0] < v2[0]) {
578           cat.start = gv1;
579           cat.end = gv2;
580         } else {
581           cat.start = gv2;
582           cat.end = gv1;
583         }
584         cat.velocity = mGroundProperty.vel;
585         cat.rotation = mGroundProperty.rot;
586         cat.rotation_pivot = mGroundProperty.pivot - mGroundCache->cache_center;
587
588         mGroundCache->catapults.push_back(cat);
589       }
590     }
591   }
592
593   SGExtendedTriangleFunctor<GroundCacheFill> mTriangleFunctor;
594   FGGroundCache* mGroundCache;
595   SGVec3d mCacheReference;
596   double mCacheRadius;
597   double mWireCacheRadius;
598   osg::Matrix mLocalToGlobal;
599   osg::Matrix mGlobalToLocal;
600   SGVec3d mDown;
601   SGVec3d mLocalDown;
602   SGVec3d mLocalCacheReference;
603   bool sphIsec;
604   bool mBackfaceCulling;
605   FGGroundCache::GroundProperty mGroundProperty;
606 };
607
608 FGGroundCache::FGGroundCache()
609 {
610   cache_center = SGVec3d(0, 0, 0);
611   ground_radius = 0.0;
612   cache_ref_time = 0.0;
613   wire_id = 0;
614   reference_wgs84_point = SGVec3d(0, 0, 0);
615   reference_vehicle_radius = 0.0;
616   found_ground = false;
617 }
618
619 FGGroundCache::~FGGroundCache()
620 {
621 }
622
623 inline void
624 FGGroundCache::velocityTransformTriangle(double dt,
625                                          FGGroundCache::Triangle& dst,
626                                          const FGGroundCache::Triangle& src)
627 {
628   dst = src;
629
630   if (fabs(dt*dot(src.velocity, src.velocity)) < SGLimitsd::epsilon())
631     return;
632
633   for (int i = 0; i < 3; ++i) {
634     SGVec3d pivotoff = src.vertices[i] - src.rotation_pivot;
635     dst.vertices[i] += dt*(src.velocity + cross(src.rotation, pivotoff));
636   }
637   
638   // Transform the plane equation
639   SGVec3d pivotoff, vel;
640   sgdSubVec3(pivotoff.sg(), dst.plane.sg(), src.rotation_pivot.sg());
641   vel = src.velocity + cross(src.rotation, pivotoff);
642   dst.plane[3] += dt*sgdScalarProductVec3(dst.plane.sg(), vel.sg());
643   
644   dst.boundCenter += dt*src.velocity;
645 }
646
647 bool
648 FGGroundCache::prepare_ground_cache(double ref_time, const SGVec3d& pt,
649                                     double rad)
650 {
651   // Empty cache.
652   ground_radius = 0.0;
653   found_ground = false;
654   triangles.resize(0);
655   catapults.resize(0);
656   wires.resize(0);
657
658   // Store the parameters we used to build up that cache.
659   reference_wgs84_point = pt;
660   reference_vehicle_radius = rad;
661   // Store the time reference used to compute movements of moving triangles.
662   cache_ref_time = ref_time;
663
664   // Get a normalized down vector valid for the whole cache
665   SGQuatd hlToEc = SGQuatd::fromLonLat(SGGeod::fromCart(pt));
666   down = hlToEc.rotate(SGVec3d(0, 0, 1));
667
668   // Decide where we put the scenery center.
669   SGVec3d old_cntr = globals->get_scenery()->get_center();
670   SGVec3d cntr(pt);
671   // Only move the cache center if it is unacceptable far away.
672   if (40*40 < distSqr(old_cntr, cntr))
673     globals->get_scenery()->set_center(cntr);
674   else
675     cntr = old_cntr;
676
677   // The center of the cache.
678   cache_center = cntr;
679   
680   // Prepare sphere around the aircraft.
681   SGVec3d ptoff = pt - cache_center;
682   double cacheRadius = rad;
683
684   // Prepare bigger sphere around the aircraft.
685   // This one is required for reliably finding wires we have caught but
686   // have already left the hopefully smaller sphere for the ground reactions.
687   const double max_wire_dist = 300.0;
688   double wireCacheRadius = max_wire_dist < rad ? rad : max_wire_dist;
689
690   // Walk the scene graph and extract solid ground triangles and carrier data.
691   GroundCacheFillVisitor gcfv(this, down, ptoff, cacheRadius, wireCacheRadius);
692   globals->get_scenery()->get_scene_graph()->accept(gcfv);
693
694   // some stats
695   SG_LOG(SG_FLIGHT,SG_DEBUG, "prepare_ground_cache(): ac radius = " << rad
696          << ", # triangles = " << triangles.size()
697          << ", # wires = " << wires.size()
698          << ", # catapults = " << catapults.size()
699          << ", ground_radius = " << ground_radius );
700
701   // If the ground radius is still below 5e6 meters, then we do not yet have
702   // any scenery.
703   found_ground = found_ground && 5e6 < ground_radius;
704   if (!found_ground)
705     SG_LOG(SG_FLIGHT, SG_WARN, "prepare_ground_cache(): trying to build cache "
706            "without any scenery below the aircraft" );
707
708   if (cntr != old_cntr)
709     globals->get_scenery()->set_center(old_cntr);
710
711   return found_ground;
712 }
713
714 bool
715 FGGroundCache::is_valid(double& ref_time, SGVec3d& pt, double& rad)
716 {
717   pt = reference_wgs84_point;
718   rad = reference_vehicle_radius;
719   ref_time = cache_ref_time;
720   return found_ground;
721 }
722
723 double
724 FGGroundCache::get_cat(double t, const SGVec3d& dpt,
725                        SGVec3d end[2], SGVec3d vel[2])
726 {
727   // start with a distance of 1e10 meters...
728   double dist = 1e10;
729
730   // Time difference to the reference time.
731   t -= cache_ref_time;
732
733   size_t sz = catapults.size();
734   for (size_t i = 0; i < sz; ++i) {
735     SGVec3d pivotoff, rvel[2];
736     pivotoff = catapults[i].start - catapults[i].rotation_pivot;
737     rvel[0] = catapults[i].velocity + cross(catapults[i].rotation, pivotoff);
738     pivotoff = catapults[i].end - catapults[i].rotation_pivot;
739     rvel[1] = catapults[i].velocity + cross(catapults[i].rotation, pivotoff);
740
741     SGVec3d thisEnd[2];
742     thisEnd[0] = cache_center + catapults[i].start + t*rvel[0];
743     thisEnd[1] = cache_center + catapults[i].end + t*rvel[1];
744
745     sgdLineSegment3 ls;
746     sgdCopyVec3(ls.a, thisEnd[0].sg());
747     sgdCopyVec3(ls.b, thisEnd[1].sg());
748     double this_dist = sgdDistSquaredToLineSegmentVec3( ls, dpt.sg() );
749
750     if (this_dist < dist) {
751       SG_LOG(SG_FLIGHT,SG_INFO, "Found catapult "
752              << this_dist << " meters away");
753       dist = this_dist;
754         
755       end[0] = thisEnd[0];
756       end[1] = thisEnd[1];
757       vel[0] = rvel[0];
758       vel[1] = rvel[1];
759     }
760   }
761
762   // At the end take the root, we only computed squared distances ...
763   return sqrt(dist);
764 }
765
766 bool
767 FGGroundCache::get_agl(double t, const SGVec3d& dpt, double max_altoff,
768                        SGVec3d& contact, SGVec3d& normal, SGVec3d& vel,
769                        int *type, const SGMaterial** material, double *agl)
770 {
771   bool ret = false;
772
773   *type = FGInterface::Unknown;
774 //   *agl = 0.0;
775   if (material)
776     *material = 0;
777   vel = SGVec3d(0, 0, 0);
778   contact = SGVec3d(0, 0, 0);
779   normal = SGVec3d(0, 0, 0);
780
781   // Time difference to th reference time.
782   t -= cache_ref_time;
783
784   // The double valued point we start to search for intersection.
785   SGVec3d pt = dpt - cache_center;
786   // shift the start of our ray by maxaltoff upwards
787   SGVec3d raystart = pt - max_altoff*down;
788
789   // Initialize to something sensible
790   double current_radius = 0.0;
791
792   size_t sz = triangles.size();
793   for (size_t i = 0; i < sz; ++i) {
794     Triangle triangle;
795     velocityTransformTriangle(t, triangle, triangles[i]);
796     if (!fgdIsectSphereInfLine(triangle.boundCenter, triangle.boundRadius, pt, down))
797       continue;
798
799     // Check for intersection.
800     SGVec3d isecpoint;
801     if (fgdRayTriangle(isecpoint, raystart, down, triangle.vertices)) {
802       // Compute the vector from pt to the intersection point ...
803       SGVec3d off = isecpoint - pt;
804       // ... and check if it is too high or not
805       // Transform to the wgs system
806       isecpoint += cache_center;
807       // compute the radius, good enough approximation to take the geocentric radius
808       double radius = dot(isecpoint, isecpoint);
809       if (current_radius < radius) {
810         current_radius = radius;
811         ret = true;
812         // Save the new potential intersection point.
813         contact = isecpoint;
814         // The first three values in the vector are the plane normal.
815         sgdCopyVec3( normal.sg(), triangle.plane.sg() );
816         // The velocity wrt earth.
817         SGVec3d pivotoff = pt - triangle.rotation_pivot;
818         vel = triangle.velocity + cross(triangle.rotation, pivotoff);
819         // Save the ground type.
820         *type = triangle.type;
821         *agl = dot(down, contact - dpt);
822         if (material)
823           *material = triangle.material;
824       }
825     }
826   }
827
828   if (ret)
829     return true;
830
831   // Whenever we did not have a ground triangle for the requested point,
832   // take the ground level we found during the current cache build.
833   // This is as good as what we had before for agl.
834   double r = length(dpt);
835   contact = dpt;
836   contact *= ground_radius/r;
837   normal = -down;
838   vel = SGVec3d(0, 0, 0);
839   
840   // The altitude is the distance of the requested point from the
841   // contact point.
842   *agl = dot(down, contact - dpt);
843   *type = FGInterface::Unknown;
844
845   return ret;
846 }
847
848 bool FGGroundCache::caught_wire(double t, const SGVec3d pt[4])
849 {
850   size_t sz = wires.size();
851   if (sz == 0)
852     return false;
853
854   // Time difference to the reference time.
855   t -= cache_ref_time;
856
857   // Build the two triangles spanning the area where the hook has moved
858   // during the past step.
859   SGVec4d plane[2];
860   SGVec3d tri[2][3];
861   sgdMakePlane( plane[0].sg(), pt[0].sg(), pt[1].sg(), pt[2].sg() );
862   tri[0][0] = pt[0];
863   tri[0][1] = pt[1];
864   tri[0][2] = pt[2];
865   sgdMakePlane( plane[1].sg(), pt[0].sg(), pt[2].sg(), pt[3].sg() );
866   tri[1][0] = pt[0];
867   tri[1][1] = pt[2];
868   tri[1][2] = pt[3];
869
870   // Intersect the wire lines with each of these triangles.
871   // You have caught a wire if they intersect.
872   for (size_t i = 0; i < sz; ++i) {
873     SGVec3d le[2];
874     for (int k = 0; k < 2; ++k) {
875       le[k] = wires[i].ends[k];
876       SGVec3d pivotoff = le[k] - wires[i].rotation_pivot;
877       SGVec3d vel = wires[i].velocity + cross(wires[i].rotation, pivotoff);
878       le[k] += t*vel + cache_center;
879     }
880     
881     for (int k=0; k<2; ++k) {
882       SGVec3d isecpoint;
883       double isecval = sgdIsectLinesegPlane(isecpoint.sg(), le[0].sg(),
884                                             le[1].sg(), plane[k].sg());
885       if ( 0.0 <= isecval && isecval <= 1.0 &&
886            fgdPointInTriangle( isecpoint, tri[k] ) ) {
887         SG_LOG(SG_FLIGHT,SG_INFO, "Caught wire");
888         // Store the wire id.
889         wire_id = wires[i].wire_id;
890         return true;
891       }
892     }
893   }
894
895   return false;
896 }
897
898 bool FGGroundCache::get_wire_ends(double t, SGVec3d end[2], SGVec3d vel[2])
899 {
900   // Fast return if we do not have an active wire.
901   if (wire_id < 0)
902     return false;
903
904   // Time difference to the reference time.
905   t -= cache_ref_time;
906
907   // Search for the wire with the matching wire id.
908   size_t sz = wires.size();
909   for (size_t i = 0; i < sz; ++i) {
910     if (wires[i].wire_id == wire_id) {
911       for (size_t k = 0; k < 2; ++k) {
912         SGVec3d pivotoff = end[k] - wires[i].rotation_pivot;
913         vel[k] = wires[i].velocity + cross(wires[i].rotation, pivotoff);
914         end[k] = cache_center + wires[i].ends[k] + t*vel[k];
915       }
916       return true;
917     }
918   }
919
920   return false;
921 }
922
923 void FGGroundCache::release_wire(void)
924 {
925   wire_id = -1;
926 }