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