]> git.mxchange.org Git - flightgear.git/blob - src/Time/moonpos.cxx
Tidying up the SGEphemeris class.
[flightgear.git] / src / Time / moonpos.cxx
1 // moonpos.cxx (basically, this is a slightly modified version of the 'sunpos.cxx' file, adapted from XEarth)
2
3 // kirk johnson
4 // july 1993
5 //
6 // code for calculating the position on the earth's surface for which
7 // the moon is directly overhead (adapted from _practical astronomy
8 // with your calculator, third edition_, peter duffett-smith,
9 // cambridge university press, 1988.)
10 //
11 // Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
12 //
13 // Parts of the source code (as marked) are:
14 //   Copyright (C) 1989, 1990, 1991 by Jim Frost
15 //   Copyright (C) 1992 by Jamie Zawinski <jwz@lucid.com>
16 //
17 // Permission to use, copy, modify and freely distribute xearth for
18 // non-commercial and not-for-profit purposes is hereby granted
19 // without fee, provided that both the above copyright notice and this
20 // permission notice appear in all copies and in supporting
21 // documentation.
22 //
23 // The author makes no representations about the suitability of this
24 // software for any purpose. It is provided "as is" without express or
25 // implied warranty.
26 //
27 // THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
28 // INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
29 // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT
30 // OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
31 // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
32 // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
33 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34 //
35 // $Id$
36
37
38 #ifdef HAVE_CONFIG_H
39 #  include <config.h>
40 #endif
41
42 #include <simgear/compiler.h>
43
44 #ifdef FG_HAVE_STD_INCLUDES
45 #  include <cmath>
46 #  include <cstdio>
47 #  include <ctime>
48 #else
49 #  include <math.h>
50 #  include <stdio.h>
51 #  include <time.h>
52 #endif
53
54 #include <simgear/constants.h>
55 #include <simgear/debug/logstream.hxx>
56 #include <simgear/ephemeris/ephemeris.hxx>
57 #include <simgear/math/fg_geodesy.hxx>
58 #include <simgear/math/point3d.hxx>
59 #include <simgear/math/polar3d.hxx>
60 #include <simgear/math/vector.hxx>
61
62 #include <Main/globals.hxx>
63 #include <Main/views.hxx>
64 #include <Scenery/scenery.hxx>
65
66 #include "moonpos.hxx"
67
68 #undef E
69
70
71 /*
72  * the epoch upon which these astronomical calculations are based is
73  * 1990 january 0.0, 631065600 seconds since the beginning of the
74  * "unix epoch" (00:00:00 GMT, Jan. 1, 1970)
75  *
76  * given a number of seconds since the start of the unix epoch,
77  * DaysSinceEpoch() computes the number of days since the start of the
78  * astronomical epoch (1990 january 0.0)
79  */
80
81 #define EpochStart           (631065600)
82 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
83
84 /*
85  * assuming the apparent orbit of the moon about the earth is circular,
86  * the rate at which the orbit progresses is given by RadsPerDay --
87  * FG_2PI radians per orbit divided by 365.242191 days per year:
88  */
89
90 #define RadsPerDay (FG_2PI/365.242191)
91
92 /*
93  * details of moon's apparent orbit at epoch 1990.0 (after
94  * duffett-smith, table 6, section 46)
95  *
96  * Epsilon_g    (ecliptic longitude at epoch 1990.0) 279.403303 degrees
97  * OmegaBar_g   (ecliptic longitude of perigee)      282.768422 degrees
98  * Eccentricity (eccentricity of orbit)                0.016713
99  */
100
101 #define Epsilon_g    (279.403303*(FG_2PI/360))
102 #define OmegaBar_g   (282.768422*(FG_2PI/360))
103 #define Eccentricity (0.016713)
104
105 /*
106  * MeanObliquity gives the mean obliquity of the earth's axis at epoch
107  * 1990.0 (computed as 23.440592 degrees according to the method given
108  * in duffett-smith, section 27)
109  */
110 #define MeanObliquity (23.440592*(FG_2PI/360))
111
112 /* static double solve_keplers_equation(double); */
113 /* static double moon_ecliptic_longitude(time_t); */
114 static void   ecliptic_to_equatorial(double, double, double *, double *);
115 static double julian_date(int, int, int);
116 static double GST(time_t);
117
118 /*
119  * solve Kepler's equation via Newton's method
120  * (after duffett-smith, section 47)
121  */
122 /*
123 static double solve_keplers_equation(double M) {
124     double E;
125     double delta;
126
127     E = M;
128     while (1) {
129         delta = E - Eccentricity*sin(E) - M;
130         if (fabs(delta) <= 1e-10) break;
131         E -= delta / (1 - Eccentricity*cos(E));
132     }
133
134     return E;
135 }
136 */
137
138
139 /* compute ecliptic longitude of moon (in radians) (after
140  * duffett-smith, section 47) */
141 /*
142 static double moon_ecliptic_longitude(time_t ssue) {
143     // time_t ssue;              //  seconds since unix epoch
144     double D, N;
145     double M_moon, E;
146     double v;
147
148     D = DaysSinceEpoch(ssue);
149
150     N = RadsPerDay * D;
151     N = fmod(N, FG_2PI);
152     if (N < 0) N += FG_2PI;
153
154     M_moon = N + Epsilon_g - OmegaBar_g;
155     if (M_moon < 0) M_moon += FG_2PI;
156
157     E = solve_keplers_equation(M_moon);
158     v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
159
160     return (v + OmegaBar_g);
161 }
162 */
163
164
165 /* convert from ecliptic to equatorial coordinates (after
166  * duffett-smith, section 27) */
167
168 static void ecliptic_to_equatorial(double lambda, double beta, 
169                                    double *alpha, double *delta) {
170     /* double  lambda;            ecliptic longitude       */
171     /* double  beta;              ecliptic latitude        */
172     /* double *alpha;             (return) right ascension */
173     /* double *delta;             (return) declination     */
174
175     double sin_e, cos_e;
176     double sin_l, cos_l;
177
178     sin_e = sin(MeanObliquity);
179     cos_e = cos(MeanObliquity);
180     sin_l = sin(lambda);
181     cos_l = cos(lambda);
182
183     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
184     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
185 }
186
187
188 /* computing julian dates (assuming gregorian calendar, thus this is
189  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
190  * section 4) */
191
192 static double julian_date(int y, int m, int d) {
193     /* int y;                    year (e.g. 19xx)          */
194     /* int m;                    month (jan=1, feb=2, ...) */
195     /* int d;                    day of month              */
196
197     int    A, B, C, D;
198     double JD;
199
200     /* lazy test to ensure gregorian calendar */
201     if (y < 1583) {
202         FG_LOG( FG_EVENT, FG_ALERT, 
203                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
204     }
205
206     if ((m == 1) || (m == 2)) {
207         y -= 1;
208         m += 12;
209     }
210
211     A = y / 100;
212     B = 2 - A + (A / 4);
213     C = (int)(365.25 * y);
214     D = (int)(30.6001 * (m + 1));
215
216     JD = B + C + D + d + 1720994.5;
217
218     return JD;
219 }
220
221
222 /* compute greenwich mean sidereal time (GST) corresponding to a given
223  * number of seconds since the unix epoch (after duffett-smith,
224  * section 12) */
225 static double GST(time_t ssue) {
226     /* time_t ssue;           seconds since unix epoch */
227
228     double     JD;
229     double     T, T0;
230     double     UT;
231     struct tm *tm;
232
233     tm = gmtime(&ssue);
234
235     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
236     T  = (JD - 2451545) / 36525;
237
238     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
239
240     T0 = fmod(T0, 24.0);
241     if (T0 < 0) T0 += 24;
242
243     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
244
245     T0 += UT * 1.002737909;
246     T0 = fmod(T0, 24.0);
247     if (T0 < 0) T0 += 24;
248
249     return T0;
250 }
251
252
253 /* given a particular time (expressed in seconds since the unix
254  * epoch), compute position on the earth (lat, lon) such that moon is
255  * directly overhead.  (lat, lon are reported in radians */
256
257 void fgMoonPosition(time_t ssue, double *lon, double *lat) {
258     /* time_t  ssue;           seconds since unix epoch */
259     /* double *lat;            (return) latitude        */
260     /* double *lon;            (return) longitude       */
261
262     /* double lambda; */
263     double alpha, delta;
264     double tmp;
265
266     /* lambda = moon_ecliptic_longitude(ssue); */
267     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
268     //ecliptic_to_equatorial (solarPosition.lonMoon, 0.0, &alpha, &delta);
269     
270     /* ********************************************************************** 
271      * NOTE: in the next function, each time the moon's position is updated, the
272      * the moon's longitude is returned from solarSystem->moon. Note that the 
273      * moon's position is updated at a much higher frequency than the rate at 
274      * which the solar system's rebuilds occur. This is not a problem, however,
275      * because the fgMoonPosition we're talking about here concerns the changing
276      * position of the moon due to the daily rotation of the earth.
277      * The ecliptic longitude, however, represents the position of the moon with
278      * respect to the stars, and completes just one cycle over the course of a 
279      * year. Its therefore pretty safe to update the moon's longitude only once
280      * every ten minutes. (Comment added by Durk Talsma).
281      ************************************************************************/
282
283     ecliptic_to_equatorial( globals->get_ephem()->get_moon()->getLon(),
284                             0.0, &alpha, &delta );
285     tmp = alpha - (FG_2PI/24)*GST(ssue);
286     if (tmp < -FG_PI) {
287         do tmp += FG_2PI;
288         while (tmp < -FG_PI);
289     } else if (tmp > FG_PI) {
290         do tmp -= FG_2PI;
291         while (tmp < -FG_PI);
292     }
293
294     *lon = tmp;
295     *lat = delta;
296 }
297
298
299 /* given a particular time expressed in side real time at prime
300  * meridian (GST), compute position on the earth (lat, lon) such that
301  * moon is directly overhead.  (lat, lon are reported in radians */
302
303 static void fgMoonPositionGST(double gst, double *lon, double *lat) {
304     /* time_t  ssue;           seconds since unix epoch */
305     /* double *lat;            (return) latitude        */
306     /* double *lon;            (return) longitude       */
307
308     /* double lambda; */
309     double alpha, delta;
310     double tmp;
311
312     /* lambda = moon_ecliptic_longitude(ssue); */
313     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
314     //ecliptic_to_equatorial (solarPosition.lonMoon, 0.0, &alpha, &delta);
315     ecliptic_to_equatorial( globals->get_ephem()->get_moon()->getLon(),
316                             globals->get_ephem()->get_moon()->getLat(), 
317                             &alpha,  &delta );
318
319 //    tmp = alpha - (FG_2PI/24)*GST(ssue);
320     tmp = alpha - (FG_2PI/24)*gst;      
321     if (tmp < -FG_PI) {
322         do tmp += FG_2PI;
323         while (tmp < -FG_PI);
324     } else if (tmp > FG_PI) {
325         do tmp -= FG_2PI;
326         while (tmp < -FG_PI);
327     }
328
329     *lon = tmp;
330     *lat = delta;
331 }
332
333
334 // update the cur_time_params structure with the current moon position
335 void fgUpdateMoonPos( void ) {
336     fgLIGHT *l;
337     FGView *v;
338     sgVec3 nup, nmoon, v0, surface_to_moon;
339     Point3D p, rel_moonpos;
340     double dot, east_dot;
341     double moon_gd_lat, sl_radius;
342
343     l = &cur_light_params;
344     SGTime *t = globals->get_time_params();
345     v = &current_view;
346
347     FG_LOG( FG_EVENT, FG_INFO, "  Updating Moon position" );
348
349     // (not sure why there was two)
350     // fgMoonPosition(t->cur_time, &l->moon_lon, &moon_gd_lat);
351     fgMoonPositionGST(t->getGst(), &l->moon_lon, &moon_gd_lat);
352
353     fgGeodToGeoc(moon_gd_lat, 0.0, &sl_radius, &l->moon_gc_lat);
354
355     p = Point3D( l->moon_lon, l->moon_gc_lat, sl_radius );
356     l->fg_moonpos = fgPolarToCart3d(p);
357
358     FG_LOG( FG_EVENT, FG_INFO, "    t->cur_time = " << t->get_cur_time() );
359     FG_LOG( FG_EVENT, FG_INFO, 
360             "    Moon Geodetic lat = " << moon_gd_lat
361             << " Geocentric lat = " << l->moon_gc_lat );
362
363     // update the sun light vector
364     sgSetVec4( l->moon_vec,
365                l->fg_moonpos.x(), l->fg_moonpos.y(), l->fg_moonpos.z(), 0.0 );
366     sgNormalizeVec4( l->moon_vec );
367     sgCopyVec4( l->moon_vec_inv, l->moon_vec );
368     sgNegateVec4( l->moon_vec_inv );
369
370     // make sure these are directional light sources only
371     l->moon_vec[3] = l->moon_vec_inv[3] = 0.0;
372     // cout << "  l->moon_vec = " << l->moon_vec[0] << "," << l->moon_vec[1]
373     //      << ","<< l->moon_vec[2] << endl;
374
375     // calculate the moon's relative angle to local up
376     sgCopyVec3( nup, v->get_local_up() );
377     sgSetVec3( nmoon, l->fg_moonpos.x(), l->fg_moonpos.y(), l->fg_moonpos.z() );
378     sgNormalizeVec3(nup);
379     sgNormalizeVec3(nmoon);
380     // cout << "nup = " << nup[0] << "," << nup[1] << "," 
381     //      << nup[2] << endl;
382     // cout << "nmoon = " << nmoon[0] << "," << nmoon[1] << "," 
383     //      << nmoon[2] << endl;
384
385     l->moon_angle = acos( sgScalarProductVec3( nup, nmoon ) );
386     cout << "moon angle relative to current location = " 
387          << l->moon_angle << endl;
388     
389     // calculate vector to moon's position on the earth's surface
390     rel_moonpos = l->fg_moonpos - (v->get_view_pos() + scenery.center);
391     v->set_to_moon( rel_moonpos.x(), rel_moonpos.y(), rel_moonpos.z() );
392     // printf( "Vector to moon = %.2f %.2f %.2f\n",
393     //         v->to_moon[0], v->to_moon[1], v->to_moon[2]);
394
395     // make a vector to the current view position
396     Point3D view_pos = v->get_view_pos();
397     sgSetVec3( v0, view_pos.x(), view_pos.y(), view_pos.z() );
398
399     // Given a vector from the view position to the point on the
400     // earth's surface the moon is directly over, map into onto the
401     // local plane representing "horizontal".
402
403     sgmap_vec_onto_cur_surface_plane( v->get_local_up(), v0, 
404                                       v->get_to_moon(), surface_to_moon );
405     sgNormalizeVec3(surface_to_moon);
406     v->set_surface_to_moon( surface_to_moon[0], surface_to_moon[1], 
407                             surface_to_moon[2] );
408     // cout << "(sg) Surface direction to moon is "
409     //   << surface_to_moon[0] << "," 
410     //   << surface_to_moon[1] << ","
411     //   << surface_to_moon[2] << endl;
412     // cout << "Should be close to zero = " 
413     //   << sgScalarProductVec3(nup, surface_to_moon) << endl;
414
415     // calculate the angle between v->surface_to_moon and
416     // v->surface_east.  We do this so we can sort out the acos()
417     // ambiguity.  I wish I could think of a more efficient way ... :-(
418     east_dot = sgScalarProductVec3( surface_to_moon, v->get_surface_east() );
419    // cout << "  East dot product = " << east_dot << endl;
420
421     // calculate the angle between v->surface_to_moon and
422     // v->surface_south.  this is how much we have to rotate the sky
423     // for it to align with the moon
424     dot = sgScalarProductVec3( surface_to_moon, v->get_surface_south() );
425     // cout << "  Dot product = " << dot << endl;
426
427     if ( east_dot >= 0 ) {
428         l->moon_rotation = acos(dot);
429     } else {
430         l->moon_rotation = -acos(dot);
431     }
432     // cout << "  Sky needs to rotate = " << angle << " rads = "
433     //      << angle * RAD_TO_DEG << " degrees." << endl;
434 }
435
436