]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGGeodesy.cxx
cmake: add option to disable building tests
[simgear.git] / simgear / math / SGGeodesy.cxx
1 // Copyright (C) 2006  Mathias Froehlich - Mathias.Froehlich@web.de
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Library General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16 //
17
18 #ifdef HAVE_CONFIG_H
19 #  include <simgear_config.h>
20 #endif
21
22 #include <cmath>
23
24 #include <simgear/structure/exception.hxx>
25 #include <simgear/debug/logstream.hxx>
26
27 #include "SGMath.hxx"
28
29 // These are hard numbers from the WGS84 standard.  DON'T MODIFY
30 // unless you want to change the datum.
31 #define _EQURAD 6378137.0
32 #define _FLATTENING 298.257223563
33
34 // These are derived quantities more useful to the code:
35 #if 0
36 #define _SQUASH (1 - 1/_FLATTENING)
37 #define _STRETCH (1/_SQUASH)
38 #define _POLRAD (EQURAD * _SQUASH)
39 #else
40 // High-precision versions of the above produced with an arbitrary
41 // precision calculator (the compiler might lose a few bits in the FPU
42 // operations).  These are specified to 81 bits of mantissa, which is
43 // higher than any FPU known to me:
44 #define _SQUASH    0.9966471893352525192801545
45 #define _STRETCH   1.0033640898209764189003079
46 #define _POLRAD    6356752.3142451794975639668
47 #endif
48
49 // The constants from the WGS84 standard
50 const double SGGeodesy::EQURAD = _EQURAD;
51 const double SGGeodesy::iFLATTENING = _FLATTENING;
52 const double SGGeodesy::SQUASH = _SQUASH;
53 const double SGGeodesy::STRETCH = _STRETCH;
54 const double SGGeodesy::POLRAD = _POLRAD;
55
56 // additional derived and precomputable ones
57 // for the geodetic conversion algorithm
58
59 #define E2 fabs(1 - _SQUASH*_SQUASH)
60 static double a = _EQURAD;
61 static double ra2 = 1/(_EQURAD*_EQURAD);
62 //static double e = sqrt(E2);
63 static double e2 = E2;
64 static double e4 = E2*E2;
65
66 #undef _EQURAD
67 #undef _FLATTENING
68 #undef _SQUASH
69 #undef _STRETCH
70 #undef _POLRAD
71 #undef E2
72
73 void
74 SGGeodesy::SGCartToGeod(const SGVec3<double>& cart, SGGeod& geod)
75 {
76   // according to
77   // H. Vermeille,
78   // Direct transformation from geocentric to geodetic ccordinates,
79   // Journal of Geodesy (2002) 76:451-454
80   double X = cart(0);
81   double Y = cart(1);
82   double Z = cart(2);
83   double XXpYY = X*X+Y*Y;
84   if( XXpYY + Z*Z < 25 ) {
85     // This function fails near the geocenter region, so catch that special case here.
86     // Define the innermost sphere of small radius as earth center and return the 
87     // coordinates 0/0/-EQURAD. It may be any other place on geoide's surface,
88     // the Northpole, Hawaii or Wentorf. This one was easy to code ;-)
89     geod.setLongitudeRad( 0.0 );
90     geod.setLongitudeRad( 0.0 );
91     geod.setElevationM( -EQURAD );
92     return;
93   }
94     
95   double sqrtXXpYY = sqrt(XXpYY);
96   double p = XXpYY*ra2;
97   double q = Z*Z*(1-e2)*ra2;
98   double r = 1/6.0*(p+q-e4);
99   double s = e4*p*q/(4*r*r*r);
100 /* 
101   s*(2+s) is negative for s = [-2..0]
102   slightly negative values for s due to floating point rounding errors
103   cause nan for sqrt(s*(2+s))
104   We can probably clamp the resulting parable to positive numbers
105 */
106   if( s >= -2.0 && s <= 0.0 )
107     s = 0.0;
108   double t = pow(1+s+sqrt(s*(2+s)), 1/3.0);
109   double u = r*(1+t+1/t);
110   double v = sqrt(u*u+e4*q);
111   double w = e2*(u+v-q)/(2*v);
112   double k = sqrt(u+v+w*w)-w;
113   double D = k*sqrtXXpYY/(k+e2);
114   geod.setLongitudeRad(2*atan2(Y, X+sqrtXXpYY));
115   double sqrtDDpZZ = sqrt(D*D+Z*Z);
116   geod.setLatitudeRad(2*atan2(Z, D+sqrtDDpZZ));
117   geod.setElevationM((k+e2-1)*sqrtDDpZZ/k);
118 }
119
120 void
121 SGGeodesy::SGGeodToCart(const SGGeod& geod, SGVec3<double>& cart)
122 {
123   // according to
124   // H. Vermeille,
125   // Direct transformation from geocentric to geodetic ccordinates,
126   // Journal of Geodesy (2002) 76:451-454
127   double lambda = geod.getLongitudeRad();
128   double phi = geod.getLatitudeRad();
129   double h = geod.getElevationM();
130   double sphi = sin(phi);
131   double n = a/sqrt(1-e2*sphi*sphi);
132   double cphi = cos(phi);
133   double slambda = sin(lambda);
134   double clambda = cos(lambda);
135   cart(0) = (h+n)*cphi*clambda;
136   cart(1) = (h+n)*cphi*slambda;
137   cart(2) = (h+n-e2*n)*sphi;
138 }
139
140 double
141 SGGeodesy::SGGeodToSeaLevelRadius(const SGGeod& geod)
142 {
143   // this is just a simplified version of the SGGeodToCart function above,
144   // substitute h = 0, take the 2-norm of the cartesian vector and simplify
145   double phi = geod.getLatitudeRad();
146   double sphi = sin(phi);
147   double sphi2 = sphi*sphi;
148   return a*sqrt((1 + (e4 - 2*e2)*sphi2)/(1 - e2*sphi2));
149 }
150
151 void
152 SGGeodesy::SGCartToGeoc(const SGVec3<double>& cart, SGGeoc& geoc)
153 {
154   double minVal = SGLimits<double>::min();
155   if (fabs(cart(0)) < minVal && fabs(cart(1)) < minVal)
156     geoc.setLongitudeRad(0);
157   else
158     geoc.setLongitudeRad(atan2(cart(1), cart(0)));
159
160   double nxy = sqrt(cart(0)*cart(0) + cart(1)*cart(1));
161   if (fabs(nxy) < minVal && fabs(cart(2)) < minVal)
162     geoc.setLatitudeRad(0);
163   else
164     geoc.setLatitudeRad(atan2(cart(2), nxy));
165
166   geoc.setRadiusM(norm(cart));
167 }
168
169 void
170 SGGeodesy::SGGeocToCart(const SGGeoc& geoc, SGVec3<double>& cart)
171 {
172   double lat = geoc.getLatitudeRad();
173   double lon = geoc.getLongitudeRad();
174   double slat = sin(lat);
175   double clat = cos(lat);
176   double slon = sin(lon);
177   double clon = cos(lon);
178   cart = geoc.getRadiusM()*SGVec3<double>(clat*clon, clat*slon, slat);
179 }
180
181 // Notes:
182 //
183 // The XYZ/cartesian coordinate system in use puts the X axis through
184 // zero lat/lon (off west Africa), the Z axis through the north pole,
185 // and the Y axis through 90 degrees longitude (in the Indian Ocean).
186 //
187 // All latitude and longitude values are in radians.  Altitude is in
188 // meters, with zero on the WGS84 ellipsoid.
189 //
190 // The code below makes use of the notion of "squashed" space.  This
191 // is a 2D cylindrical coordinate system where the radius from the Z
192 // axis is multiplied by SQUASH; the earth in this space is a perfect
193 // circle with a radius of POLRAD.
194
195 ////////////////////////////////////////////////////////////////////////
196 //
197 // Direct and inverse distance functions 
198 //
199 // Proceedings of the 7th International Symposium on Geodetic
200 // Computations, 1985
201 //
202 // "The Nested Coefficient Method for Accurate Solutions of Direct and
203 // Inverse Geodetic Problems With Any Length"
204 //
205 // Zhang Xue-Lian
206 // pp 747-763
207 //
208 // modified for FlightGear to use WGS84 only -- Norman Vine
209
210 static inline double M0( double e2 ) {
211     //double e4 = e2*e2;
212   return SGMiscd::pi()*0.5*(1.0 - e2*( 1.0/4.0 + e2*( 3.0/64.0 + 
213                                                   e2*(5.0/256.0) )));
214 }
215
216
217 // given, lat1, lon1, az1 and distance (s), calculate lat2, lon2
218 // and az2.  Lat, lon, and azimuth are in degrees.  distance in meters
219 static int _geo_direct_wgs_84 ( double lat1, double lon1, double az1,
220                         double s, double *lat2, double *lon2,
221                         double *az2 )
222 {
223     double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
224     double testv = 1.0E-10;
225     double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
226     double b = a*(1.0-f);
227     double e2 = f*(2.0-f);
228     double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
229     double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
230     double azm1 = SGMiscd::deg2rad(az1);
231     double sinaz1 = sin(azm1), cosaz1 = cos(azm1);
232         
233         
234     if( fabs(s) < 0.01 ) {      // distance < centimeter => congruency
235         *lat2 = lat1;
236         *lon2 = lon1;
237         *az2 = 180.0 + az1;
238         if( *az2 > 360.0 ) *az2 -= 360.0;
239         return 0;
240     } else if( SGLimitsd::min() < fabs(cosphi1) ) {     // non-polar origin
241         // u1 is reduced latitude
242         double tanu1 = sqrt(1.0-e2)*sinphi1/cosphi1;
243         double sig1 = atan2(tanu1,cosaz1);
244         double cosu1 = 1.0/sqrt( 1.0 + tanu1*tanu1 ), sinu1 = tanu1*cosu1;
245         double sinaz =  cosu1*sinaz1, cos2saz = 1.0-sinaz*sinaz;
246         double us = cos2saz*e2/(1.0-e2);
247
248         // Terms
249         double  ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/16384.0,
250             tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0,
251             tc = 0;
252
253         // FIRST ESTIMATE OF SIGMA (SIG)
254         double first = s/(b*ta);  // !!
255         double sig = first;
256         double c2sigm, sinsig,cossig, temp,denom,rnumer, dlams, dlam;
257         do {
258             c2sigm = cos(2.0*sig1+sig);
259             sinsig = sin(sig); cossig = cos(sig);
260             temp = sig;
261             sig = first + 
262                 tb*sinsig*(c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm) - 
263                                       tb*c2sigm*(-3.0+4.0*sinsig*sinsig)
264                                       *(-3.0+4.0*c2sigm*c2sigm)/6.0)
265                            /4.0);
266         } while( fabs(sig-temp) > testv);
267
268         // LATITUDE OF POINT 2
269         // DENOMINATOR IN 2 PARTS (TEMP ALSO USED LATER)
270         temp = sinu1*sinsig-cosu1*cossig*cosaz1;
271         denom = (1.0-f)*sqrt(sinaz*sinaz+temp*temp);
272
273         // NUMERATOR
274         rnumer = sinu1*cossig+cosu1*sinsig*cosaz1;
275         *lat2 = SGMiscd::rad2deg(atan2(rnumer,denom));
276
277         // DIFFERENCE IN LONGITUDE ON AUXILARY SPHERE (DLAMS )
278         rnumer = sinsig*sinaz1;
279         denom = cosu1*cossig-sinu1*sinsig*cosaz1;
280         dlams = atan2(rnumer,denom);
281
282         // TERM C
283         tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
284
285         // DIFFERENCE IN LONGITUDE
286         dlam = dlams-(1.0-tc)*f*sinaz*(sig+tc*sinsig*
287                                        (c2sigm+
288                                         tc*cossig*(-1.0+2.0*
289                                                    c2sigm*c2sigm)));
290         *lon2 = SGMiscd::rad2deg(lam1+dlam);
291         if (*lon2 > 180.0  ) *lon2 -= 360.0;
292         if (*lon2 < -180.0 ) *lon2 += 360.0;
293
294         // AZIMUTH - FROM NORTH
295         *az2 = SGMiscd::rad2deg(atan2(-sinaz,temp));
296         if ( fabs(*az2) < testv ) *az2 = 0.0;
297         if( *az2 < 0.0) *az2 += 360.0;
298         return 0;
299     } else {                    // phi1 == 90 degrees, polar origin
300         double dM = a*M0(e2) - s;
301         double paz = ( phi1 < 0.0 ? 180.0 : 0.0 );
302         double zero = 0.0f;
303         return _geo_direct_wgs_84( zero, lon1, paz, dM, lat2, lon2, az2 );
304     } 
305 }
306
307 bool
308 SGGeodesy::direct(const SGGeod& p1, double course1,
309                   double distance, SGGeod& p2, double& course2)
310 {
311   double lat2, lon2;
312   int ret = _geo_direct_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
313                                course1, distance, &lat2, &lon2, &course2);
314   p2.setLatitudeDeg(lat2);
315   p2.setLongitudeDeg(lon2);
316   p2.setElevationM(0);
317   return ret == 0;
318 }
319
320 // given lat1, lon1, lat2, lon2, calculate starting and ending
321 // az1, az2 and distance (s).  Lat, lon, and azimuth are in degrees.
322 // distance in meters
323 static int _geo_inverse_wgs_84( double lat1, double lon1, double lat2,
324                         double lon2, double *az1, double *az2,
325                         double *s )
326 {
327     double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
328     int iter=0;
329     double testv = 1.0E-10;
330     double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
331     double b = a*(1.0-f);
332     // double e2 = f*(2.0-f); // unused in this routine
333     double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
334     double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
335     double phi2 = SGMiscd::deg2rad(lat2), lam2 = SGMiscd::deg2rad(lon2);
336     double sinphi2 = sin(phi2), cosphi2 = cos(phi2);
337         
338     if( (fabs(lat1-lat2) < testv && 
339          ( fabs(lon1-lon2) < testv)) || (fabs(lat1-90.0) < testv ) )
340     {   
341         // TWO STATIONS ARE IDENTICAL : SET DISTANCE & AZIMUTHS TO ZERO */
342         *az1 = 0.0; *az2 = 0.0; *s = 0.0;
343         return 0;
344     } else if(  fabs(cosphi1) < testv ) {
345         // initial point is polar
346         int k = _geo_inverse_wgs_84( lat2,lon2,lat1,lon1, az1,az2,s );
347         k = k; // avoid compiler error since return result is unused
348         b = *az1; *az1 = *az2; *az2 = b;
349         return 0;
350     } else if( fabs(cosphi2) < testv ) {
351         // terminal point is polar
352         double _lon1 = lon1 + 180.0f;
353         int k = _geo_inverse_wgs_84( lat1, lon1, lat1, _lon1, 
354                                     az1, az2, s );
355         k = k; // avoid compiler error since return result is unused
356         *s /= 2.0;
357         *az2 = *az1 + 180.0;
358         if( *az2 > 360.0 ) *az2 -= 360.0; 
359         return 0;
360     } else if( (fabs( fabs(lon1-lon2) - 180 ) < testv) && 
361                (fabs(lat1+lat2) < testv) ) 
362     {
363         // Geodesic passes through the pole (antipodal)
364         double s1,s2;
365         _geo_inverse_wgs_84( lat1,lon1, lat1,lon2, az1,az2, &s1 );
366         _geo_inverse_wgs_84( lat2,lon2, lat1,lon2, az1,az2, &s2 );
367         *az2 = *az1;
368         *s = s1 + s2;
369         return 0;
370     } else {
371         // antipodal and polar points don't get here
372         double dlam = lam2 - lam1, dlams = dlam;
373         double sdlams,cdlams, sig,sinsig,cossig, sinaz,
374             cos2saz, c2sigm;
375         double tc,temp, us,rnumer,denom, ta,tb;
376         double cosu1,sinu1, sinu2,cosu2;
377
378         // Reduced latitudes
379         temp = (1.0-f)*sinphi1/cosphi1;
380         cosu1 = 1.0/sqrt(1.0+temp*temp);
381         sinu1 = temp*cosu1;
382         temp = (1.0-f)*sinphi2/cosphi2;
383         cosu2 = 1.0/sqrt(1.0+temp*temp);
384         sinu2 = temp*cosu2;
385     
386         do {
387             sdlams = sin(dlams), cdlams = cos(dlams);
388             sinsig = sqrt(cosu2*cosu2*sdlams*sdlams+
389                           (cosu1*sinu2-sinu1*cosu2*cdlams)*
390                           (cosu1*sinu2-sinu1*cosu2*cdlams));
391             cossig = sinu1*sinu2+cosu1*cosu2*cdlams;
392             
393             sig = atan2(sinsig,cossig);
394             sinaz = cosu1*cosu2*sdlams/sinsig;
395             cos2saz = 1.0-sinaz*sinaz;
396             c2sigm = (sinu1 == 0.0 || sinu2 == 0.0 ? cossig : 
397                       cossig-2.0*sinu1*sinu2/cos2saz);
398             tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
399             temp = dlams;
400             dlams = dlam+(1.0-tc)*f*sinaz*
401                 (sig+tc*sinsig*
402                  (c2sigm+tc*cossig*(-1.0+2.0*c2sigm*c2sigm)));
403             if (fabs(dlams) > SGMiscd::pi() && iter++ > 50) {
404                 return iter;
405             }
406         } while ( fabs(temp-dlams) > testv);
407
408         us = cos2saz*(a*a-b*b)/(b*b); // !!
409         // BACK AZIMUTH FROM NORTH
410         rnumer = -(cosu1*sdlams);
411         denom = sinu1*cosu2-cosu1*sinu2*cdlams;
412         *az2 = SGMiscd::rad2deg(atan2(rnumer,denom));
413         if( fabs(*az2) < testv ) *az2 = 0.0;
414         if(*az2 < 0.0) *az2 += 360.0;
415
416         // FORWARD AZIMUTH FROM NORTH
417         rnumer = cosu2*sdlams;
418         denom = cosu1*sinu2-sinu1*cosu2*cdlams;
419         *az1 = SGMiscd::rad2deg(atan2(rnumer,denom));
420         if( fabs(*az1) < testv ) *az1 = 0.0;
421         if(*az1 < 0.0) *az1 += 360.0;
422
423         // Terms a & b
424         ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/
425             16384.0;
426         tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0;
427
428         // GEODETIC DISTANCE
429         *s = b*ta*(sig-tb*sinsig*
430                    (c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm)-tb*
431                                c2sigm*(-3.0+4.0*sinsig*sinsig)*
432                                (-3.0+4.0*c2sigm*c2sigm)/6.0)/
433                     4.0));
434         return 0;
435     }
436 }
437
438 bool
439 SGGeodesy::inverse(const SGGeod& p1, const SGGeod& p2, double& course1,
440                    double& course2, double& distance)
441 {
442   int ret = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
443                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
444                                 &course1, &course2, &distance);
445   return ret == 0;
446 }
447
448 double
449 SGGeodesy::courseDeg(const SGGeod& p1, const SGGeod& p2)
450 {
451   double course1, course2, distance;
452   int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
453                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
454                                 &course1, &course2, &distance);
455   if (r != 0) {
456     throw sg_exception("SGGeodesy::courseDeg, unable to compute course");
457   }
458   
459   return course1;
460 }
461
462 double
463 SGGeodesy::distanceM(const SGGeod& p1, const SGGeod& p2)
464 {
465   double course1, course2, distance;
466   int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
467                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
468                                 &course1, &course2, &distance);
469   if (r != 0) {
470     throw sg_exception("SGGeodesy::distanceM, unable to compute distance");
471   }
472   
473   return distance;
474 }
475
476 double
477 SGGeodesy::distanceNm(const SGGeod& from, const SGGeod& to)
478 {
479   return distanceM(from, to) * SG_METER_TO_NM;
480 }
481
482 /// Geocentric routines
483
484 void
485 SGGeodesy::advanceRadM(const SGGeoc& geoc, double course, double distance,
486                        SGGeoc& result)
487 {
488   result.setRadiusM(geoc.getRadiusM());
489
490   // lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
491   // IF (cos(lat)=0)
492   //   lon=lon1      // endpoint a pole
493   // ELSE
494   //   lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
495   // ENDIF
496   
497   distance *= SG_METER_TO_NM * SG_NM_TO_RAD;
498   
499   double sinDistance = sin(distance);
500   double cosDistance = cos(distance);
501
502   double sinLat = sin(geoc.getLatitudeRad()) * cosDistance +
503     cos(geoc.getLatitudeRad()) * sinDistance * cos(course);
504   sinLat = SGMiscd::clip(sinLat, -1, 1);
505   result.setLatitudeRad(asin(sinLat));
506   double cosLat = cos(result.getLatitudeRad());
507   
508   
509   if (cosLat <= SGLimitsd::min()) {
510     // endpoint a pole
511     result.setLongitudeRad(geoc.getLongitudeRad());
512   } else {
513     double tmp = SGMiscd::clip(sin(course) * sinDistance / cosLat, -1, 1);
514     double lon = SGMiscd::normalizeAngle(-geoc.getLongitudeRad() - asin( tmp ));
515     result.setLongitudeRad(-lon);
516   }
517 }
518
519 double
520 SGGeodesy::courseRad(const SGGeoc& from, const SGGeoc& to)
521 {
522   //double diffLon = to.getLongitudeRad() - from.getLongitudeRad();
523   double diffLon = from.getLongitudeRad() - to.getLongitudeRad();
524
525   double sinLatFrom = sin(from.getLatitudeRad());
526   double cosLatFrom = cos(from.getLatitudeRad());
527
528   double sinLatTo = sin(to.getLatitudeRad());
529   double cosLatTo = cos(to.getLatitudeRad());
530
531   double x = cosLatTo*sin(diffLon);
532   double y = cosLatFrom*sinLatTo - sinLatFrom*cosLatTo*cos(diffLon);
533
534   // guard atan2 returning NaN's
535   if (fabs(x) <= SGLimitsd::min() && fabs(y) <= SGLimitsd::min())
536     return 0;
537
538   double c = atan2(x, y);
539   if (c >= 0)
540     return SGMiscd::twopi() - c;
541   else
542     return -c;
543 }
544
545 double
546 SGGeodesy::distanceRad(const SGGeoc& from, const SGGeoc& to)
547 {
548   // d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
549   //            cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
550   double cosLatFrom = cos(from.getLatitudeRad());
551   double cosLatTo = cos(to.getLatitudeRad());
552   double tmp1 = sin(0.5*(from.getLatitudeRad() - to.getLatitudeRad()));
553   double tmp2 = sin(0.5*(from.getLongitudeRad() - to.getLongitudeRad()));
554   double square = tmp1*tmp1 + cosLatFrom*cosLatTo*tmp2*tmp2;
555   double s = SGMiscd::min(sqrt(SGMiscd::max(square, 0)), 1);
556   return 2 * asin(s);
557 }
558
559
560 double
561 SGGeodesy::distanceM(const SGGeoc& from, const SGGeoc& to)
562 {
563   return distanceRad(from, to) * SG_RAD_TO_NM * SG_NM_TO_METER;
564 }
565
566 bool 
567 SGGeodesy::radialIntersection(const SGGeoc& a, double r1, 
568     const SGGeoc& b, double r2, SGGeoc& result)
569 {
570   // implementation of
571   // http://williams.best.vwh.net/avform.htm#Intersection
572
573   double crs13 = r1 * SG_DEGREES_TO_RADIANS;
574   double crs23 = r2 * SG_DEGREES_TO_RADIANS;
575   double dst12 = SGGeodesy::distanceRad(a, b);
576
577   //IF sin(lon2-lon1)<0
578   // crs12=acos((sin(lat2)-sin(lat1)*cos(dst12))/(sin(dst12)*cos(lat1)))
579   // crs21=2.*pi-acos((sin(lat1)-sin(lat2)*cos(dst12))/(sin(dst12)*cos(lat2)))
580   // ELSE
581   // crs12=2.*pi-acos((sin(lat2)-sin(lat1)*cos(dst12))/(sin(dst12)*cos(lat1)))
582   // crs21=acos((sin(lat1)-sin(lat2)*cos(dst12))/(sin(dst12)*cos(lat2)))
583   // ENDIF
584   double crs12 = SGGeodesy::courseRad(a, b),
585          crs21 = SGGeodesy::courseRad(b, a);
586
587   double sinLat1 = sin(a.getLatitudeRad());
588   double cosLat1 = cos(a.getLatitudeRad());
589   double sinDst12 = sin(dst12);
590   double cosDst12 = cos(dst12);
591   
592   double ang1 = SGMiscd::normalizeAngle2(crs13-crs12);
593   double ang2 = SGMiscd::normalizeAngle2(crs21-crs23);
594    
595   if ((sin(ang1) == 0.0) && (sin(ang2) == 0.0)) {
596     SG_LOG(SG_GENERAL, SG_WARN, "SGGeodesy::radialIntersection: infinity of intersections");
597     return false;
598   }
599
600   if ((sin(ang1)*sin(ang2))<0.0) {
601     SG_LOG(SG_GENERAL, SG_WARN, "SGGeodesy::radialIntersection: intersection ambiguous");
602     return false;
603   }
604
605   ang1 = fabs(ang1);
606   ang2 = fabs(ang2);
607
608   //ang3=acos(-cos(ang1)*cos(ang2)+sin(ang1)*sin(ang2)*cos(dst12)) 
609   //dst13=atan2(sin(dst12)*sin(ang1)*sin(ang2),cos(ang2)+cos(ang1)*cos(ang3))
610   //lat3=asin(sin(lat1)*cos(dst13)+cos(lat1)*sin(dst13)*cos(crs13))
611   //lon3=mod(lon1-dlon+pi,2*pi)-pi
612
613   double ang3 = acos(-cos(ang1) * cos(ang2) + sin(ang1) * sin(ang2) * cosDst12);
614   double dst13 = atan2(sinDst12 * sin(ang1) * sin(ang2), cos(ang2) + cos(ang1)*cos(ang3));
615   double lat3 = asin(sinLat1 * cos(dst13) + cosLat1 * sin(dst13) * cos(crs13));
616   //dlon=atan2(sin(crs13)*sin(dst13)*cos(lat1),cos(dst13)-sin(lat1)*sin(lat3))
617   double dlon = atan2(sin(crs13)*sin(dst13)*cosLat1, cos(dst13)- (sinLat1 * sin(lat3)));
618   double lon3 = SGMiscd::normalizeAngle(-a.getLongitudeRad()-dlon);
619
620   result = SGGeoc::fromRadM(-lon3, lat3, a.getRadiusM());
621   return true;
622 }
623     
624 bool
625 SGGeodesy::radialIntersection(const SGGeod& a, double aRadial, 
626     const SGGeod& b, double bRadial, SGGeod& result)
627 {
628   SGGeoc r;
629   bool ok = radialIntersection(SGGeoc::fromGeod(a), aRadial, 
630     SGGeoc::fromGeod(b), bRadial, r);
631   if (!ok) {
632     return false;
633   }
634   
635   result = SGGeod::fromGeoc(r);
636   return true;
637 }