1 // Copyright (C) 2006 Mathias Froehlich - Mathias.Froehlich@web.de
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.
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.
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.
19 # include <simgear_config.h>
24 #include <simgear/structure/exception.hxx>
27 // These are hard numbers from the WGS84 standard. DON'T MODIFY
28 // unless you want to change the datum.
29 #define _EQURAD 6378137.0
30 #define _FLATTENING 298.257223563
32 // These are derived quantities more useful to the code:
34 #define _SQUASH (1 - 1/_FLATTENING)
35 #define _STRETCH (1/_SQUASH)
36 #define _POLRAD (EQURAD * _SQUASH)
38 // High-precision versions of the above produced with an arbitrary
39 // precision calculator (the compiler might lose a few bits in the FPU
40 // operations). These are specified to 81 bits of mantissa, which is
41 // higher than any FPU known to me:
42 #define _SQUASH 0.9966471893352525192801545
43 #define _STRETCH 1.0033640898209764189003079
44 #define _POLRAD 6356752.3142451794975639668
47 // The constants from the WGS84 standard
48 const double SGGeodesy::EQURAD = _EQURAD;
49 const double SGGeodesy::iFLATTENING = _FLATTENING;
50 const double SGGeodesy::SQUASH = _SQUASH;
51 const double SGGeodesy::STRETCH = _STRETCH;
52 const double SGGeodesy::POLRAD = _POLRAD;
54 // additional derived and precomputable ones
55 // for the geodetic conversion algorithm
57 #define E2 fabs(1 - _SQUASH*_SQUASH)
58 static double a = _EQURAD;
59 static double ra2 = 1/(_EQURAD*_EQURAD);
60 //static double e = sqrt(E2);
61 static double e2 = E2;
62 static double e4 = E2*E2;
72 SGGeodesy::SGCartToGeod(const SGVec3<double>& cart, SGGeod& geod)
76 // Direct transformation from geocentric to geodetic ccordinates,
77 // Journal of Geodesy (2002) 76:451-454
81 double XXpYY = X*X+Y*Y;
82 double sqrtXXpYY = sqrt(XXpYY);
84 double q = Z*Z*(1-e2)*ra2;
85 double r = 1/6.0*(p+q-e4);
86 double s = e4*p*q/(4*r*r*r);
87 double t = pow(1+s+sqrt(s*(2+s)), 1/3.0);
88 double u = r*(1+t+1/t);
89 double v = sqrt(u*u+e4*q);
90 double w = e2*(u+v-q)/(2*v);
91 double k = sqrt(u+v+w*w)-w;
92 double D = k*sqrtXXpYY/(k+e2);
93 geod.setLongitudeRad(2*atan2(Y, X+sqrtXXpYY));
94 double sqrtDDpZZ = sqrt(D*D+Z*Z);
95 geod.setLatitudeRad(2*atan2(Z, D+sqrtDDpZZ));
96 geod.setElevationM((k+e2-1)*sqrtDDpZZ/k);
100 SGGeodesy::SGGeodToCart(const SGGeod& geod, SGVec3<double>& cart)
104 // Direct transformation from geocentric to geodetic ccordinates,
105 // Journal of Geodesy (2002) 76:451-454
106 double lambda = geod.getLongitudeRad();
107 double phi = geod.getLatitudeRad();
108 double h = geod.getElevationM();
109 double sphi = sin(phi);
110 double n = a/sqrt(1-e2*sphi*sphi);
111 double cphi = cos(phi);
112 double slambda = sin(lambda);
113 double clambda = cos(lambda);
114 cart(0) = (h+n)*cphi*clambda;
115 cart(1) = (h+n)*cphi*slambda;
116 cart(2) = (h+n-e2*n)*sphi;
120 SGGeodesy::SGGeodToSeaLevelRadius(const SGGeod& geod)
122 // this is just a simplified version of the SGGeodToCart function above,
123 // substitute h = 0, take the 2-norm of the cartesian vector and simplify
124 double phi = geod.getLatitudeRad();
125 double sphi = sin(phi);
126 double sphi2 = sphi*sphi;
127 return a*sqrt((1 + (e4 - 2*e2)*sphi2)/(1 - e2*sphi2));
131 SGGeodesy::SGCartToGeoc(const SGVec3<double>& cart, SGGeoc& geoc)
133 double minVal = SGLimits<double>::min();
134 if (fabs(cart(0)) < minVal && fabs(cart(1)) < minVal)
135 geoc.setLongitudeRad(0);
137 geoc.setLongitudeRad(atan2(cart(1), cart(0)));
139 double nxy = sqrt(cart(0)*cart(0) + cart(1)*cart(1));
140 if (fabs(nxy) < minVal && fabs(cart(2)) < minVal)
141 geoc.setLatitudeRad(0);
143 geoc.setLatitudeRad(atan2(cart(2), nxy));
145 geoc.setRadiusM(norm(cart));
149 SGGeodesy::SGGeocToCart(const SGGeoc& geoc, SGVec3<double>& cart)
151 double lat = geoc.getLatitudeRad();
152 double lon = geoc.getLongitudeRad();
153 double slat = sin(lat);
154 double clat = cos(lat);
155 double slon = sin(lon);
156 double clon = cos(lon);
157 cart = geoc.getRadiusM()*SGVec3<double>(clat*clon, clat*slon, slat);
162 // The XYZ/cartesian coordinate system in use puts the X axis through
163 // zero lat/lon (off west Africa), the Z axis through the north pole,
164 // and the Y axis through 90 degrees longitude (in the Indian Ocean).
166 // All latitude and longitude values are in radians. Altitude is in
167 // meters, with zero on the WGS84 ellipsoid.
169 // The code below makes use of the notion of "squashed" space. This
170 // is a 2D cylindrical coordinate system where the radius from the Z
171 // axis is multiplied by SQUASH; the earth in this space is a perfect
172 // circle with a radius of POLRAD.
174 ////////////////////////////////////////////////////////////////////////
176 // Direct and inverse distance functions
178 // Proceedings of the 7th International Symposium on Geodetic
179 // Computations, 1985
181 // "The Nested Coefficient Method for Accurate Solutions of Direct and
182 // Inverse Geodetic Problems With Any Length"
187 // modified for FlightGear to use WGS84 only -- Norman Vine
189 static inline double M0( double e2 ) {
191 return SGMiscd::pi()*0.5*(1.0 - e2*( 1.0/4.0 + e2*( 3.0/64.0 +
196 // given, lat1, lon1, az1 and distance (s), calculate lat2, lon2
197 // and az2. Lat, lon, and azimuth are in degrees. distance in meters
198 static int _geo_direct_wgs_84 ( double lat1, double lon1, double az1,
199 double s, double *lat2, double *lon2,
202 double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
203 double testv = 1.0E-10;
204 double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
205 double b = a*(1.0-f);
206 double e2 = f*(2.0-f);
207 double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
208 double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
209 double azm1 = SGMiscd::deg2rad(az1);
210 double sinaz1 = sin(azm1), cosaz1 = cos(azm1);
213 if( fabs(s) < 0.01 ) { // distance < centimeter => congruency
217 if( *az2 > 360.0 ) *az2 -= 360.0;
219 } else if( SGLimitsd::min() < fabs(cosphi1) ) { // non-polar origin
220 // u1 is reduced latitude
221 double tanu1 = sqrt(1.0-e2)*sinphi1/cosphi1;
222 double sig1 = atan2(tanu1,cosaz1);
223 double cosu1 = 1.0/sqrt( 1.0 + tanu1*tanu1 ), sinu1 = tanu1*cosu1;
224 double sinaz = cosu1*sinaz1, cos2saz = 1.0-sinaz*sinaz;
225 double us = cos2saz*e2/(1.0-e2);
228 double ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/16384.0,
229 tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0,
232 // FIRST ESTIMATE OF SIGMA (SIG)
233 double first = s/(b*ta); // !!
235 double c2sigm, sinsig,cossig, temp,denom,rnumer, dlams, dlam;
237 c2sigm = cos(2.0*sig1+sig);
238 sinsig = sin(sig); cossig = cos(sig);
241 tb*sinsig*(c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm) -
242 tb*c2sigm*(-3.0+4.0*sinsig*sinsig)
243 *(-3.0+4.0*c2sigm*c2sigm)/6.0)
245 } while( fabs(sig-temp) > testv);
247 // LATITUDE OF POINT 2
248 // DENOMINATOR IN 2 PARTS (TEMP ALSO USED LATER)
249 temp = sinu1*sinsig-cosu1*cossig*cosaz1;
250 denom = (1.0-f)*sqrt(sinaz*sinaz+temp*temp);
253 rnumer = sinu1*cossig+cosu1*sinsig*cosaz1;
254 *lat2 = SGMiscd::rad2deg(atan2(rnumer,denom));
256 // DIFFERENCE IN LONGITUDE ON AUXILARY SPHERE (DLAMS )
257 rnumer = sinsig*sinaz1;
258 denom = cosu1*cossig-sinu1*sinsig*cosaz1;
259 dlams = atan2(rnumer,denom);
262 tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
264 // DIFFERENCE IN LONGITUDE
265 dlam = dlams-(1.0-tc)*f*sinaz*(sig+tc*sinsig*
269 *lon2 = SGMiscd::rad2deg(lam1+dlam);
270 if (*lon2 > 180.0 ) *lon2 -= 360.0;
271 if (*lon2 < -180.0 ) *lon2 += 360.0;
273 // AZIMUTH - FROM NORTH
274 *az2 = SGMiscd::rad2deg(atan2(-sinaz,temp));
275 if ( fabs(*az2) < testv ) *az2 = 0.0;
276 if( *az2 < 0.0) *az2 += 360.0;
278 } else { // phi1 == 90 degrees, polar origin
279 double dM = a*M0(e2) - s;
280 double paz = ( phi1 < 0.0 ? 180.0 : 0.0 );
282 return _geo_direct_wgs_84( zero, lon1, paz, dM, lat2, lon2, az2 );
287 SGGeodesy::direct(const SGGeod& p1, double course1,
288 double distance, SGGeod& p2, double& course2)
291 int ret = _geo_direct_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
292 course1, distance, &lat2, &lon2, &course2);
293 p2.setLatitudeDeg(lat2);
294 p2.setLongitudeDeg(lon2);
299 // given lat1, lon1, lat2, lon2, calculate starting and ending
300 // az1, az2 and distance (s). Lat, lon, and azimuth are in degrees.
301 // distance in meters
302 static int _geo_inverse_wgs_84( double lat1, double lon1, double lat2,
303 double lon2, double *az1, double *az2,
306 double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
308 double testv = 1.0E-10;
309 double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
310 double b = a*(1.0-f);
311 // double e2 = f*(2.0-f); // unused in this routine
312 double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
313 double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
314 double phi2 = SGMiscd::deg2rad(lat2), lam2 = SGMiscd::deg2rad(lon2);
315 double sinphi2 = sin(phi2), cosphi2 = cos(phi2);
317 if( (fabs(lat1-lat2) < testv &&
318 ( fabs(lon1-lon2) < testv)) || (fabs(lat1-90.0) < testv ) )
320 // TWO STATIONS ARE IDENTICAL : SET DISTANCE & AZIMUTHS TO ZERO */
321 *az1 = 0.0; *az2 = 0.0; *s = 0.0;
323 } else if( fabs(cosphi1) < testv ) {
324 // initial point is polar
325 int k = _geo_inverse_wgs_84( lat2,lon2,lat1,lon1, az1,az2,s );
326 k = k; // avoid compiler error since return result is unused
327 b = *az1; *az1 = *az2; *az2 = b;
329 } else if( fabs(cosphi2) < testv ) {
330 // terminal point is polar
331 double _lon1 = lon1 + 180.0f;
332 int k = _geo_inverse_wgs_84( lat1, lon1, lat1, _lon1,
334 k = k; // avoid compiler error since return result is unused
337 if( *az2 > 360.0 ) *az2 -= 360.0;
339 } else if( (fabs( fabs(lon1-lon2) - 180 ) < testv) &&
340 (fabs(lat1+lat2) < testv) )
342 // Geodesic passes through the pole (antipodal)
344 _geo_inverse_wgs_84( lat1,lon1, lat1,lon2, az1,az2, &s1 );
345 _geo_inverse_wgs_84( lat2,lon2, lat1,lon2, az1,az2, &s2 );
350 // antipodal and polar points don't get here
351 double dlam = lam2 - lam1, dlams = dlam;
352 double sdlams,cdlams, sig,sinsig,cossig, sinaz,
354 double tc,temp, us,rnumer,denom, ta,tb;
355 double cosu1,sinu1, sinu2,cosu2;
358 temp = (1.0-f)*sinphi1/cosphi1;
359 cosu1 = 1.0/sqrt(1.0+temp*temp);
361 temp = (1.0-f)*sinphi2/cosphi2;
362 cosu2 = 1.0/sqrt(1.0+temp*temp);
366 sdlams = sin(dlams), cdlams = cos(dlams);
367 sinsig = sqrt(cosu2*cosu2*sdlams*sdlams+
368 (cosu1*sinu2-sinu1*cosu2*cdlams)*
369 (cosu1*sinu2-sinu1*cosu2*cdlams));
370 cossig = sinu1*sinu2+cosu1*cosu2*cdlams;
372 sig = atan2(sinsig,cossig);
373 sinaz = cosu1*cosu2*sdlams/sinsig;
374 cos2saz = 1.0-sinaz*sinaz;
375 c2sigm = (sinu1 == 0.0 || sinu2 == 0.0 ? cossig :
376 cossig-2.0*sinu1*sinu2/cos2saz);
377 tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
379 dlams = dlam+(1.0-tc)*f*sinaz*
381 (c2sigm+tc*cossig*(-1.0+2.0*c2sigm*c2sigm)));
382 if (fabs(dlams) > SGMiscd::pi() && iter++ > 50) {
385 } while ( fabs(temp-dlams) > testv);
387 us = cos2saz*(a*a-b*b)/(b*b); // !!
388 // BACK AZIMUTH FROM NORTH
389 rnumer = -(cosu1*sdlams);
390 denom = sinu1*cosu2-cosu1*sinu2*cdlams;
391 *az2 = SGMiscd::rad2deg(atan2(rnumer,denom));
392 if( fabs(*az2) < testv ) *az2 = 0.0;
393 if(*az2 < 0.0) *az2 += 360.0;
395 // FORWARD AZIMUTH FROM NORTH
396 rnumer = cosu2*sdlams;
397 denom = cosu1*sinu2-sinu1*cosu2*cdlams;
398 *az1 = SGMiscd::rad2deg(atan2(rnumer,denom));
399 if( fabs(*az1) < testv ) *az1 = 0.0;
400 if(*az1 < 0.0) *az1 += 360.0;
403 ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/
405 tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0;
408 *s = b*ta*(sig-tb*sinsig*
409 (c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm)-tb*
410 c2sigm*(-3.0+4.0*sinsig*sinsig)*
411 (-3.0+4.0*c2sigm*c2sigm)/6.0)/
418 SGGeodesy::inverse(const SGGeod& p1, const SGGeod& p2, double& course1,
419 double& course2, double& distance)
421 int ret = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
422 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
423 &course1, &course2, &distance);
428 SGGeodesy::courseDeg(const SGGeod& p1, const SGGeod& p2)
430 double course1, course2, distance;
431 int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
432 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
433 &course1, &course2, &distance);
435 throw sg_exception("SGGeodesy::courseDeg, unable to compute course");
442 SGGeodesy::distanceM(const SGGeod& p1, const SGGeod& p2)
444 double course1, course2, distance;
445 int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
446 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
447 &course1, &course2, &distance);
449 throw sg_exception("SGGeodesy::distanceM, unable to compute distance");
456 SGGeodesy::distanceNm(const SGGeod& from, const SGGeod& to)
458 return distanceM(from, to) * SG_METER_TO_NM;
461 /// Geocentric routines
464 SGGeodesy::advanceRadM(const SGGeoc& geoc, double course, double distance,
467 result.setRadiusM(geoc.getRadiusM());
469 // lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
471 // lon=lon1 // endpoint a pole
473 // lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
476 distance *= SG_METER_TO_NM * SG_NM_TO_RAD;
478 double sinDistance = sin(distance);
479 double cosDistance = cos(distance);
481 double sinLat = sin(geoc.getLatitudeRad()) * cosDistance +
482 cos(geoc.getLatitudeRad()) * sinDistance * cos(course);
483 sinLat = SGMiscd::clip(sinLat, -1, 1);
484 result.setLatitudeRad(asin(sinLat));
485 double cosLat = cos(result.getLatitudeRad());
488 if (cosLat <= SGLimitsd::min()) {
490 result.setLongitudeRad(geoc.getLongitudeRad());
492 double tmp = SGMiscd::clip(sin(course) * sinDistance / cosLat, -1, 1);
493 double lon = SGMiscd::normalizeAngle(geoc.getLongitudeRad() - asin( tmp ));
494 result.setLongitudeRad(lon);
499 SGGeodesy::courseRad(const SGGeoc& from, const SGGeoc& to)
501 double diffLon = to.getLongitudeRad() - from.getLongitudeRad();
503 double sinLatFrom = sin(from.getLatitudeRad());
504 double cosLatFrom = cos(from.getLatitudeRad());
506 double sinLatTo = sin(to.getLatitudeRad());
507 double cosLatTo = cos(to.getLatitudeRad());
509 double x = cosLatTo*sin(diffLon);
510 double y = cosLatFrom*sinLatTo - sinLatFrom*cosLatTo*cos(diffLon);
512 // guard atan2 returning NaN's
513 if (fabs(x) <= SGLimitsd::min() && fabs(y) <= SGLimitsd::min())
516 double c = atan2(x, y);
518 return SGMiscd::twopi() - c;
524 SGGeodesy::distanceM(const SGGeoc& from, const SGGeoc& to)
526 // d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
527 // cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
528 double cosLatFrom = cos(from.getLatitudeRad());
529 double cosLatTo = cos(to.getLatitudeRad());
530 double tmp1 = sin(0.5*(from.getLatitudeRad() - to.getLatitudeRad()));
531 double tmp2 = sin(0.5*(from.getLongitudeRad() - to.getLongitudeRad()));
532 double square = tmp1*tmp1 + cosLatFrom*cosLatTo*tmp2*tmp2;
533 double s = SGMiscd::min(sqrt(SGMiscd::max(square, 0)), 1);
534 return 2 * asin(s) * SG_RAD_TO_NM * SG_NM_TO_METER;