]> git.mxchange.org Git - flightgear.git/blob - Simulator/Time/sunpos.cxx
Merge Include as subdirectory
[flightgear.git] / Simulator / Time / sunpos.cxx
1 // sunpos.cxx (adapted from XEarth)
2 // kirk johnson
3 // july 1993
4 //
5 // code for calculating the position on the earth's surface for which
6 // the sun is directly overhead (adapted from _practical astronomy
7 // with your calculator, third edition_, peter duffett-smith,
8 // cambridge university press, 1988.)
9 //
10 // Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
11 //
12 // Parts of the source code (as marked) are:
13 //   Copyright (C) 1989, 1990, 1991 by Jim Frost
14 //   Copyright (C) 1992 by Jamie Zawinski <jwz@lucid.com>
15 //
16 // Permission to use, copy, modify and freely distribute xearth for
17 // non-commercial and not-for-profit purposes is hereby granted
18 // without fee, provided that both the above copyright notice and this
19 // permission notice appear in all copies and in supporting
20 // documentation.
21 //
22 // The author makes no representations about the suitability of this
23 // software for any purpose. It is provided "as is" without express or
24 // implied warranty.
25 //
26 // THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
27 // INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
28 // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT
29 // OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
30 // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
31 // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
32 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
33 //
34 // $Id$
35 // (Log is kept at end of this file)
36
37
38 #ifdef HAVE_CONFIG_H
39 #  include <config.h>
40 #endif
41
42 #include <Include/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 <Debug/logstream.hxx>
55 #include <Astro/solarsystem.hxx>
56 #include <Include/fg_constants.h>
57 #include <Main/views.hxx>
58 #include <Math/fg_geodesy.hxx>
59 #include <Math/mat3.h>
60 #include <Math/point3d.hxx>
61 #include <Math/polar3d.hxx>
62 #include <Math/vector.hxx>
63 #include <Scenery/scenery.hxx>
64
65 #include "fg_time.hxx"
66 #include "sunpos.hxx"
67
68 extern SolarSystem *solarSystem;
69
70 #undef E
71 #define MeanObliquity (23.440592*(FG_2PI/360))
72
73 static void   ecliptic_to_equatorial(double, double, double *, double *);
74 static double julian_date(int, int, int);
75 static double GST(time_t);
76
77 static void ecliptic_to_equatorial(double lambda, double beta, 
78                                    double *alpha, double *delta) {
79     /* double  lambda;            ecliptic longitude       */
80     /* double  beta;              ecliptic latitude        */
81     /* double *alpha;             (return) right ascension */
82     /* double *delta;             (return) declination     */
83
84     double sin_e, cos_e;
85     double sin_l, cos_l;
86
87     sin_e = sin(MeanObliquity);
88     cos_e = cos(MeanObliquity);
89     sin_l = sin(lambda);
90     cos_l = cos(lambda);
91
92     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
93     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
94 }
95
96
97 /* computing julian dates (assuming gregorian calendar, thus this is
98  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
99  * section 4) */
100
101 static double julian_date(int y, int m, int d) {
102     /* int y;                    year (e.g. 19xx)          */
103     /* int m;                    month (jan=1, feb=2, ...) */
104     /* int d;                    day of month              */
105
106     int    A, B, C, D;
107     double JD;
108
109     /* lazy test to ensure gregorian calendar */
110     if (y < 1583) {
111         FG_LOG( FG_EVENT, FG_ALERT, 
112                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
113     }
114
115     if ((m == 1) || (m == 2)) {
116         y -= 1;
117         m += 12;
118     }
119
120     A = y / 100;
121     B = 2 - A + (A / 4);
122     C = (int)(365.25 * y);
123     D = (int)(30.6001 * (m + 1));
124
125     JD = B + C + D + d + 1720994.5;
126
127     return JD;
128 }
129
130
131 /* compute greenwich mean sidereal time (GST) corresponding to a given
132  * number of seconds since the unix epoch (after duffett-smith,
133  * section 12) */
134 static double GST(time_t ssue) {
135     /* time_t ssue;           seconds since unix epoch */
136
137     double     JD;
138     double     T, T0;
139     double     UT;
140     struct tm *tm;
141
142     tm = gmtime(&ssue);
143
144     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
145     T  = (JD - 2451545) / 36525;
146
147     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
148
149     T0 = fmod(T0, 24.0);
150     if (T0 < 0) T0 += 24;
151
152     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
153
154     T0 += UT * 1.002737909;
155     T0 = fmod(T0, 24.0);
156     if (T0 < 0) T0 += 24;
157
158     return T0;
159 }
160
161
162 /* given a particular time (expressed in seconds since the unix
163  * epoch), compute position on the earth (lat, lon) such that sun is
164  * directly overhead.  (lat, lon are reported in radians */
165
166 void fgSunPosition(time_t ssue, double *lon, double *lat) {
167     /* time_t  ssue;           seconds since unix epoch */
168     /* double *lat;            (return) latitude        */
169     /* double *lon;            (return) longitude       */
170
171     /* double lambda; */
172     double alpha, delta;
173     double tmp;
174
175     /* lambda = sun_ecliptic_longitude(ssue); */
176     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
177     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
178     
179     /* ********************************************************************** 
180      * NOTE: in the next function, each time the sun's position is updated, the
181      * the sun's longitude is returned from solarSystem->sun. Note that the 
182      * sun's position is updated at a much higher frequency than the rate at 
183      * which the solar system's rebuilds occur. This is not a problem, however,
184      * because the fgSunPosition we're talking about here concerns the changing
185      * position of the sun due to the daily rotation of the earth.
186      * The ecliptic longitude, however, represents the position of the sun with
187      * respect to the stars, and completes just one cycle over the course of a 
188      * year. Its therefore pretty safe to update the sun's longitude only once
189      * every ten minutes. (Comment added by Durk Talsma).
190      ************************************************************************/
191
192     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getSun()->getLon(),
193                             0.0, &alpha, &delta );
194     tmp = alpha - (FG_2PI/24)*GST(ssue);
195     if (tmp < -FG_PI) {
196         do tmp += FG_2PI;
197         while (tmp < -FG_PI);
198     } else if (tmp > FG_PI) {
199         do tmp -= FG_2PI;
200         while (tmp < -FG_PI);
201     }
202
203     *lon = tmp;
204     *lat = delta;
205 }
206
207
208 /* given a particular time expressed in side real time at prime
209  * meridian (GST), compute position on the earth (lat, lon) such that
210  * sun is directly overhead.  (lat, lon are reported in radians */
211
212 static void fgSunPositionGST(double gst, double *lon, double *lat) {
213     /* time_t  ssue;           seconds since unix epoch */
214     /* double *lat;            (return) latitude        */
215     /* double *lon;            (return) longitude       */
216
217     /* double lambda; */
218     double alpha, delta;
219     double tmp;
220
221     /* lambda = sun_ecliptic_longitude(ssue); */
222     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
223     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
224     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getSun()->getLon(),
225                             SolarSystem::theSolarSystem->getSun()->getLat(),
226                             &alpha,  &delta );
227
228 //    tmp = alpha - (FG_2PI/24)*GST(ssue);
229     tmp = alpha - (FG_2PI/24)*gst;      
230     if (tmp < -FG_PI) {
231         do tmp += FG_2PI;
232         while (tmp < -FG_PI);
233     } else if (tmp > FG_PI) {
234         do tmp -= FG_2PI;
235         while (tmp < -FG_PI);
236     }
237
238     *lon = tmp;
239     *lat = delta;
240 }
241
242
243 // update the cur_time_params structure with the current sun position
244 void fgUpdateSunPos( void ) {
245     fgLIGHT *l;
246     fgTIME *t;
247     FGView *v;
248     MAT3vec nup, nsun, v0, surface_to_sun;
249     Point3D p, rel_sunpos;
250     double dot, east_dot;
251     double sun_gd_lat, sl_radius;
252     double ntmp;
253
254     l = &cur_light_params;
255     t = &cur_time_params;
256     v = &current_view;
257
258     FG_LOG( FG_EVENT, FG_INFO, "  Updating Sun position" );
259
260     // (not sure why there was two)
261     // fgSunPosition(t->cur_time, &l->sun_lon, &sun_gd_lat);
262     fgSunPositionGST(t->gst, &l->sun_lon, &sun_gd_lat);
263
264     fgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
265
266     p = Point3D( l->sun_lon, l->sun_gc_lat, sl_radius );
267     l->fg_sunpos = fgPolarToCart3d(p);
268
269     FG_LOG( FG_EVENT, FG_INFO, "    t->cur_time = " << t->cur_time );
270     FG_LOG( FG_EVENT, FG_INFO, 
271             "    Sun Geodetic lat = " << sun_gd_lat
272             << " Geocentric lat = " << l->sun_gc_lat );
273
274     // I think this will work better for generating the sun light vector
275     l->sun_vec[0] = l->fg_sunpos.x();
276     l->sun_vec[1] = l->fg_sunpos.y();
277     l->sun_vec[2] = l->fg_sunpos.z();
278     MAT3_NORMALIZE_VEC(l->sun_vec, ntmp);
279     MAT3_SCALE_VEC(l->sun_vec_inv, l->sun_vec, -1.0);
280
281     // make sure these are directional light sources only
282     l->sun_vec[3] = 0.0;
283     l->sun_vec_inv[3] = 0.0;
284
285     // printf("  l->sun_vec = %.2f %.2f %.2f\n", l->sun_vec[0], l->sun_vec[1],
286     //        l->sun_vec[2]);
287
288     // calculate the sun's relative angle to local up
289     MAT3_COPY_VEC(nup, v->get_local_up());
290     nsun[0] = l->fg_sunpos.x(); 
291     nsun[1] = l->fg_sunpos.y();
292     nsun[2] = l->fg_sunpos.z();
293     MAT3_NORMALIZE_VEC(nup, ntmp);
294     MAT3_NORMALIZE_VEC(nsun, ntmp);
295
296     l->sun_angle = acos(MAT3_DOT_PRODUCT(nup, nsun));
297     // printf("  SUN ANGLE relative to current location = %.3f rads.\n", 
298     //        l->sun_angle);
299     
300     // calculate vector to sun's position on the earth's surface
301     rel_sunpos = l->fg_sunpos - (v->get_view_pos() + scenery.center);
302     v->set_to_sun( rel_sunpos.x(), rel_sunpos.y(), rel_sunpos.z() );
303     // printf( "Vector to sun = %.2f %.2f %.2f\n",
304     //         v->to_sun[0], v->to_sun[1], v->to_sun[2]);
305
306     // make a vector to the current view position
307     Point3D view_pos = v->get_view_pos();
308     MAT3_SET_VEC(v0, view_pos.x(), view_pos.y(), view_pos.z());
309
310     // Given a vector from the view position to the point on the
311     // earth's surface the sun is directly over, map into onto the
312     // local plane representing "horizontal".
313     map_vec_onto_cur_surface_plane( v->get_local_up(), v0, v->get_to_sun(), 
314                                     surface_to_sun );
315     MAT3_NORMALIZE_VEC(surface_to_sun, ntmp);
316     v->set_surface_to_sun( surface_to_sun[0], surface_to_sun[1], 
317                            surface_to_sun[2] );
318     // printf("Surface direction to sun is %.2f %.2f %.2f\n",
319     //        v->surface_to_sun[0], v->surface_to_sun[1], v->surface_to_sun[2]);
320     // printf("Should be close to zero = %.2f\n", 
321     //        MAT3_DOT_PRODUCT(v->local_up, v->surface_to_sun));
322
323     // calculate the angle between v->surface_to_sun and
324     // v->surface_east.  We do this so we can sort out the acos()
325     // ambiguity.  I wish I could think of a more efficient way ... :-(
326     east_dot = MAT3_DOT_PRODUCT( surface_to_sun, v->get_surface_east() );
327     // printf("  East dot product = %.2f\n", east_dot);
328
329     // calculate the angle between v->surface_to_sun and
330     // v->surface_south.  this is how much we have to rotate the sky
331     // for it to align with the sun
332     dot = MAT3_DOT_PRODUCT( surface_to_sun, v->get_surface_south() );
333     // printf("  Dot product = %.2f\n", dot);
334     if ( east_dot >= 0 ) {
335         l->sun_rotation = acos(dot);
336     } else {
337         l->sun_rotation = -acos(dot);
338     }
339     // printf("  Sky needs to rotate = %.3f rads = %.1f degrees.\n", 
340     //        angle, angle * RAD_TO_DEG); */
341 }
342
343
344 // $Log$
345 // Revision 1.21  1999/03/22 02:08:18  curt
346 // Changes contributed by Durk Talsma:
347 //
348 // Here's a few changes I made to fg-0.58 this weekend. Included are the
349 // following features:
350 // - Sun and moon have a halo
351 // - The moon has a light vector, moon_angle, etc. etc. so that we can have
352 //   some moonlight during the night.
353 // - Lot's of small changes tweakes, including some stuff Norman Vine sent
354 //   me earlier.
355 //
356 // Revision 1.20  1999/02/26 22:10:11  curt
357 // Added initial support for native SGI compilers.
358 //
359 // Revision 1.19  1999/01/07 20:25:37  curt
360 // Portability changes and updates from Bernie Bright.
361 //
362 // Revision 1.18  1998/12/09 18:50:36  curt
363 // Converted "class fgVIEW" to "class FGView" and updated to make data
364 // members private and make required accessor functions.
365 //
366 // Revision 1.17  1998/11/09 23:41:53  curt
367 // Log message clean ups.
368 //
369 // Revision 1.16  1998/11/07 19:07:14  curt
370 // Enable release builds using the --without-logging option to the configure
371 // script.  Also a couple log message cleanups, plus some C to C++ comment
372 // conversion.
373 //
374 // Revision 1.15  1998/10/18 01:17:24  curt
375 // Point3D tweaks.
376 //
377 // Revision 1.14  1998/10/17 01:34:32  curt
378 // C++ ifying ...
379 //
380 // Revision 1.13  1998/10/16 00:56:12  curt
381 // Converted to Point3D class.
382 //
383 // Revision 1.12  1998/09/15 04:27:50  curt
384 // Changes for new astro code.
385 //
386 // Revision 1.11  1998/08/12 21:13:22  curt
387 // Optimizations by Norman Vine.
388 //
389 // Revision 1.10  1998/07/22 21:45:39  curt
390 // fg_time.cxx: Removed call to ctime() in a printf() which should be harmless
391 //   but seems to be triggering a bug.
392 // light.cxx: Added code to adjust fog color based on sunrise/sunset effects
393 //   and view orientation.  This is an attempt to match the fog color to the
394 //   sky color in the center of the screen.  You see discrepancies at the
395 //   edges, but what else can be done?
396 // sunpos.cxx: Caculate local direction to sun here.  (what compass direction
397 //   do we need to face to point directly at sun)
398 //
399 // Revision 1.9  1998/07/08 14:48:39  curt
400 // polar3d.h renamed to polar3d.hxx
401 //
402 // Revision 1.8  1998/05/02 01:53:18  curt
403 // Fine tuning mktime() support because of varying behavior on different
404 // platforms.
405 //
406 // Revision 1.7  1998/04/30 12:36:05  curt
407 // C++-ifying a couple source files.
408 //
409 // Revision 1.6  1998/04/28 01:22:18  curt
410 // Type-ified fgTIME and fgVIEW.
411 //
412 // Revision 1.5  1998/04/26 05:10:05  curt
413 // "struct fgLIGHT" -> "fgLIGHT" because fgLIGHT is typedef'd.
414 //
415 // Revision 1.4  1998/04/25 22:06:34  curt
416 // Edited cvs log messages in source files ... bad bad bad!
417 //
418 // Revision 1.3  1998/04/25 20:24:03  curt
419 // Cleaned up initialization sequence to eliminate interdependencies
420 // between sun position, lighting, and view position.  This creates a
421 // valid single pass initialization path.
422 //
423 // Revision 1.2  1998/04/24 00:52:31  curt
424 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
425 // Fog color fixes.
426 // Separated out lighting calcs into their own file.
427 //
428 // Revision 1.1  1998/04/22 13:24:07  curt
429 // C++ - ifiing the code a bit.
430 // Starting to reorginize some of the lighting calcs to use a table lookup.
431 //
432 // Revision 1.27  1998/04/03 22:12:57  curt
433 // Converting to Gnu autoconf system.
434 // Centralized time handling differences.
435 //
436 // Revision 1.26  1998/02/23 19:08:00  curt
437 // Incorporated Durk's Astro/ tweaks.  Includes unifying the sun position
438 // calculation code between sun display, and other FG sections that use this
439 // for things like lighting.
440 //
441 // Revision 1.25  1998/02/09 15:07:53  curt
442 // Minor tweaks.
443 //
444 // Revision 1.24  1998/01/27 00:48:07  curt
445 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
446 // system and commandline/config file processing code.
447 //
448 // Revision 1.23  1998/01/19 19:27:21  curt
449 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
450 // This should simplify things tremendously.
451 //
452 // Revision 1.22  1998/01/19 18:40:40  curt
453 // Tons of little changes to clean up the code and to remove fatal errors
454 // when building with the c++ compiler.
455 //
456 // Revision 1.21  1997/12/30 23:10:19  curt
457 // Calculate lighting parameters here.
458 //
459 // Revision 1.20  1997/12/30 22:22:43  curt
460 // Further integration of event manager.
461 //
462 // Revision 1.19  1997/12/30 20:47:59  curt
463 // Integrated new event manager with subsystem initializations.
464 //
465 // Revision 1.18  1997/12/23 04:58:40  curt
466 // Tweaked the sky coloring a bit to build in structures to allow finer rgb
467 // control.
468 //
469 // Revision 1.17  1997/12/15 23:55:08  curt
470 // Add xgl wrappers for debugging.
471 // Generate terrain normals on the fly.
472 //
473 // Revision 1.16  1997/12/11 04:43:57  curt
474 // Fixed sun vector and lighting problems.  I thing the moon is now lit
475 // correctly.
476 //
477 // Revision 1.15  1997/12/10 22:37:55  curt
478 // Prepended "fg" on the name of all global structures that didn't have it yet.
479 // i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
480 //
481 // Revision 1.14  1997/12/09 04:25:39  curt
482 // Working on adding a global lighting params structure.
483 //
484 // Revision 1.13  1997/11/25 19:25:42  curt
485 // Changes to integrate Durk's moon/sun code updates + clean up.
486 //
487 // Revision 1.12  1997/11/15 18:15:39  curt
488 // Reverse direction of sun vector, so object normals can be more normal.
489 //
490 // Revision 1.11  1997/10/28 21:07:21  curt
491 // Changed GLUT/ -> Main/
492 //
493 // Revision 1.10  1997/09/13 02:00:09  curt
494 // Mostly working on stars and generating sidereal time for accurate star
495 // placement.
496 //
497 // Revision 1.9  1997/09/05 14:17:31  curt
498 // More tweaking with stars.
499 //
500 // Revision 1.8  1997/09/05 01:36:04  curt
501 // Working on getting stars right.
502 //
503 // Revision 1.7  1997/09/04 02:17:40  curt
504 // Shufflin' stuff.
505 //
506 // Revision 1.6  1997/08/27 03:30:37  curt
507 // Changed naming scheme of basic shared structures.
508 //
509 // Revision 1.5  1997/08/22 21:34:41  curt
510 // Doing a bit of reorganizing and house cleaning.
511 //
512 // Revision 1.4  1997/08/19 23:55:09  curt
513 // Worked on better simulating real lighting.
514 //
515 // Revision 1.3  1997/08/13 20:23:49  curt
516 // The interface to sunpos now updates a global structure rather than returning
517 // current sun position.
518 //
519 // Revision 1.2  1997/08/06 00:24:32  curt
520 // Working on correct real time sun lighting.
521 //
522 // Revision 1.1  1997/08/01 15:27:56  curt
523 // Initial revision.
524 //