]> git.mxchange.org Git - flightgear.git/blob - Time/sunpos.cxx
polar3d.h renamed to polar3d.hxx
[flightgear.git] / Time / sunpos.cxx
1 // sunpos.c (taken 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 // RCS $Id$
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 // (Log is kept at end of this file)
38
39
40 #ifdef HAVE_CONFIG_H
41 #  include <config.h>
42 #endif
43
44 #include <math.h>
45 #include <stdio.h>
46 #include <time.h>
47
48 #include <Astro/orbits.hxx>
49 #include <Include/fg_constants.h>
50 #include <Main/views.hxx>
51 #include <Math/fg_geodesy.h>
52 #include <Math/mat3.h>
53 #include <Math/polar3d.hxx>
54 #include <Math/vector.hxx>
55 #include <Scenery/scenery.hxx>
56
57 #include "fg_time.hxx"
58 #include "sunpos.hxx"
59
60
61 #undef E
62
63
64 /*
65  * the epoch upon which these astronomical calculations are based is
66  * 1990 january 0.0, 631065600 seconds since the beginning of the
67  * "unix epoch" (00:00:00 GMT, Jan. 1, 1970)
68  *
69  * given a number of seconds since the start of the unix epoch,
70  * DaysSinceEpoch() computes the number of days since the start of the
71  * astronomical epoch (1990 january 0.0)
72  */
73
74 #define EpochStart           (631065600)
75 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
76
77 /*
78  * assuming the apparent orbit of the sun about the earth is circular,
79  * the rate at which the orbit progresses is given by RadsPerDay --
80  * FG_2PI radians per orbit divided by 365.242191 days per year:
81  */
82
83 #define RadsPerDay (FG_2PI/365.242191)
84
85 /*
86  * details of sun's apparent orbit at epoch 1990.0 (after
87  * duffett-smith, table 6, section 46)
88  *
89  * Epsilon_g    (ecliptic longitude at epoch 1990.0) 279.403303 degrees
90  * OmegaBar_g   (ecliptic longitude of perigee)      282.768422 degrees
91  * Eccentricity (eccentricity of orbit)                0.016713
92  */
93
94 #define Epsilon_g    (279.403303*(FG_2PI/360))
95 #define OmegaBar_g   (282.768422*(FG_2PI/360))
96 #define Eccentricity (0.016713)
97
98 /*
99  * MeanObliquity gives the mean obliquity of the earth's axis at epoch
100  * 1990.0 (computed as 23.440592 degrees according to the method given
101  * in duffett-smith, section 27)
102  */
103 #define MeanObliquity (23.440592*(FG_2PI/360))
104
105 /* static double solve_keplers_equation(double); */
106 /* static double sun_ecliptic_longitude(time_t); */
107 static void   ecliptic_to_equatorial(double, double, double *, double *);
108 static double julian_date(int, int, int);
109 static double GST(time_t);
110
111 /*
112  * solve Kepler's equation via Newton's method
113  * (after duffett-smith, section 47)
114  */
115 /*
116 static double solve_keplers_equation(double M) {
117     double E;
118     double delta;
119
120     E = M;
121     while (1) {
122         delta = E - Eccentricity*sin(E) - M;
123         if (fabs(delta) <= 1e-10) break;
124         E -= delta / (1 - Eccentricity*cos(E));
125     }
126
127     return E;
128 }
129 */
130
131
132 /* compute ecliptic longitude of sun (in radians) (after
133  * duffett-smith, section 47) */
134 /*
135 static double sun_ecliptic_longitude(time_t ssue) {
136     // time_t ssue;              //  seconds since unix epoch
137     double D, N;
138     double M_sun, E;
139     double v;
140
141     D = DaysSinceEpoch(ssue);
142
143     N = RadsPerDay * D;
144     N = fmod(N, FG_2PI);
145     if (N < 0) N += FG_2PI;
146
147     M_sun = N + Epsilon_g - OmegaBar_g;
148     if (M_sun < 0) M_sun += FG_2PI;
149
150     E = solve_keplers_equation(M_sun);
151     v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
152
153     return (v + OmegaBar_g);
154 }
155 */
156
157
158 /* convert from ecliptic to equatorial coordinates (after
159  * duffett-smith, section 27) */
160
161 static void ecliptic_to_equatorial(double lambda, double beta, 
162                                    double *alpha, double *delta) {
163     /* double  lambda;            ecliptic longitude       */
164     /* double  beta;              ecliptic latitude        */
165     /* double *alpha;             (return) right ascension */
166     /* double *delta;             (return) declination     */
167
168     double sin_e, cos_e;
169
170     sin_e = sin(MeanObliquity);
171     cos_e = cos(MeanObliquity);
172
173     *alpha = atan2(sin(lambda)*cos_e - tan(beta)*sin_e, cos(lambda));
174     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin(lambda));
175 }
176
177
178 /* computing julian dates (assuming gregorian calendar, thus this is
179  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
180  * section 4) */
181
182 static double julian_date(int y, int m, int d) {
183     /* int y;                    year (e.g. 19xx)          */
184     /* int m;                    month (jan=1, feb=2, ...) */
185     /* int d;                    day of month              */
186
187     int    A, B, C, D;
188     double JD;
189
190     /* lazy test to ensure gregorian calendar */
191     if (y < 1583) {
192         printf("WHOOPS! Julian dates only valid for 1582 oct 15 or later\n");
193     }
194
195     if ((m == 1) || (m == 2)) {
196         y -= 1;
197         m += 12;
198     }
199
200     A = y / 100;
201     B = 2 - A + (A / 4);
202     C = (int)(365.25 * y);
203     D = (int)(30.6001 * (m + 1));
204
205     JD = B + C + D + d + 1720994.5;
206
207     return JD;
208 }
209
210
211 /* compute greenwich mean sidereal time (GST) corresponding to a given
212  * number of seconds since the unix epoch (after duffett-smith,
213  * section 12) */
214 static double GST(time_t ssue) {
215     /* time_t ssue;           seconds since unix epoch */
216
217     double     JD;
218     double     T, T0;
219     double     UT;
220     struct tm *tm;
221
222     tm = gmtime(&ssue);
223
224     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
225     T  = (JD - 2451545) / 36525;
226
227     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
228
229     T0 = fmod(T0, 24.0);
230     if (T0 < 0) T0 += 24;
231
232     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
233
234     T0 += UT * 1.002737909;
235     T0 = fmod(T0, 24.0);
236     if (T0 < 0) T0 += 24;
237
238     return T0;
239 }
240
241
242 /* given a particular time (expressed in seconds since the unix
243  * epoch), compute position on the earth (lat, lon) such that sun is
244  * directly overhead.  (lat, lon are reported in radians */
245
246 void fgSunPosition(time_t ssue, double *lon, double *lat) {
247     /* time_t  ssue;           seconds since unix epoch */
248     /* double *lat;            (return) latitude        */
249     /* double *lon;            (return) longitude       */
250
251     /* double lambda; */
252     double alpha, delta;
253     double tmp;
254
255     /* lambda = sun_ecliptic_longitude(ssue); */
256     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
257     ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
258
259     tmp = alpha - (FG_2PI/24)*GST(ssue);
260     if (tmp < -FG_PI) {
261         do tmp += FG_2PI;
262         while (tmp < -FG_PI);
263     } else if (tmp > FG_PI) {
264         do tmp -= FG_2PI;
265         while (tmp < -FG_PI);
266     }
267
268     *lon = tmp;
269     *lat = delta;
270 }
271
272
273 // update the cur_time_params structure with the current sun position
274 void fgUpdateSunPos( void ) {
275     fgLIGHT *l;
276     fgTIME *t;
277     fgVIEW *v;
278     MAT3vec nup, nsun, v0;
279     fgPoint3d p;
280     double sun_gd_lat, sl_radius;
281     double ntmp;
282
283     l = &cur_light_params;
284     t = &cur_time_params;
285     v = &current_view;
286
287     printf("  Updating Sun position\n");
288
289     fgSunPosition(t->cur_time, &l->sun_lon, &sun_gd_lat);
290     fgSunPosition(t->cur_time, &l->sun_lon, &sun_gd_lat);
291
292     fgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
293
294     p.lon = l->sun_lon;
295     p.lat = l->sun_gc_lat;
296     p.radius = sl_radius;
297     l->fg_sunpos = fgPolarToCart3d(p);
298
299     printf( "    t->cur_time = %ld\n", t->cur_time);
300     printf( "    Sun Geodetic lat = %.5f Geocentric lat = %.5f\n",
301             sun_gd_lat, l->sun_gc_lat);
302
303     // I think this will work better for generating the sun light vector
304     l->sun_vec[0] = l->fg_sunpos.x;
305     l->sun_vec[1] = l->fg_sunpos.y;
306     l->sun_vec[2] = l->fg_sunpos.z;
307     MAT3_NORMALIZE_VEC(l->sun_vec, ntmp);
308     MAT3_SCALE_VEC(l->sun_vec_inv, l->sun_vec, -1.0);
309
310     // make sure these are directional light sources only
311     l->sun_vec[3] = 0.0;
312     l->sun_vec_inv[3] = 0.0;
313
314     printf("  l->sun_vec = %.2f %.2f %.2f\n", l->sun_vec[0], l->sun_vec[1],
315            l->sun_vec[2]);
316
317     // calculate the sun's relative angle to local up
318     MAT3_COPY_VEC(nup, v->local_up);
319     nsun[0] = l->fg_sunpos.x; 
320     nsun[1] = l->fg_sunpos.y;
321     nsun[2] = l->fg_sunpos.z;
322     MAT3_NORMALIZE_VEC(nup, ntmp);
323     MAT3_NORMALIZE_VEC(nsun, ntmp);
324
325     l->sun_angle = acos(MAT3_DOT_PRODUCT(nup, nsun));
326     printf("  SUN ANGLE relative to current location = %.3f rads.\n", 
327            l->sun_angle);
328     
329     // calculate vector to sun's position on the earth's surface
330     v->to_sun[0] = l->fg_sunpos.x - (v->view_pos.x + scenery.center.x);
331     v->to_sun[1] = l->fg_sunpos.y - (v->view_pos.y + scenery.center.y);
332     v->to_sun[2] = l->fg_sunpos.z - (v->view_pos.z + scenery.center.z);
333     // printf( "Vector to sun = %.2f %.2f %.2f\n",
334     //         v->to_sun[0], v->to_sun[1], v->to_sun[2]);
335
336     // make a vector to the current view position
337     MAT3_SET_VEC(v0, v->view_pos.x, v->view_pos.y, v->view_pos.z);
338
339     // Given a vector from the view position to the point on the
340     // earth's surface the sun is directly over, map into onto the
341     // local plane representing "horizontal".
342     map_vec_onto_cur_surface_plane(v->local_up, v0, v->to_sun, 
343                                    v->surface_to_sun);
344     MAT3_NORMALIZE_VEC(v->surface_to_sun, ntmp);
345     // printf("Surface direction to sun is %.2f %.2f %.2f\n",
346     //        v->surface_to_sun[0], v->surface_to_sun[1], v->surface_to_sun[2]);
347     // printf("Should be close to zero = %.2f\n", 
348     //        MAT3_DOT_PRODUCT(v->local_up, v->surface_to_sun));
349 }
350
351
352 // $Log$
353 // Revision 1.9  1998/07/08 14:48:39  curt
354 // polar3d.h renamed to polar3d.hxx
355 //
356 // Revision 1.8  1998/05/02 01:53:18  curt
357 // Fine tuning mktime() support because of varying behavior on different
358 // platforms.
359 //
360 // Revision 1.7  1998/04/30 12:36:05  curt
361 // C++-ifying a couple source files.
362 //
363 // Revision 1.6  1998/04/28 01:22:18  curt
364 // Type-ified fgTIME and fgVIEW.
365 //
366 // Revision 1.5  1998/04/26 05:10:05  curt
367 // "struct fgLIGHT" -> "fgLIGHT" because fgLIGHT is typedef'd.
368 //
369 // Revision 1.4  1998/04/25 22:06:34  curt
370 // Edited cvs log messages in source files ... bad bad bad!
371 //
372 // Revision 1.3  1998/04/25 20:24:03  curt
373 // Cleaned up initialization sequence to eliminate interdependencies
374 // between sun position, lighting, and view position.  This creates a
375 // valid single pass initialization path.
376 //
377 // Revision 1.2  1998/04/24 00:52:31  curt
378 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
379 // Fog color fixes.
380 // Separated out lighting calcs into their own file.
381 //
382 // Revision 1.1  1998/04/22 13:24:07  curt
383 // C++ - ifiing the code a bit.
384 // Starting to reorginize some of the lighting calcs to use a table lookup.
385 //
386 // Revision 1.27  1998/04/03 22:12:57  curt
387 // Converting to Gnu autoconf system.
388 // Centralized time handling differences.
389 //
390 // Revision 1.26  1998/02/23 19:08:00  curt
391 // Incorporated Durk's Astro/ tweaks.  Includes unifying the sun position
392 // calculation code between sun display, and other FG sections that use this
393 // for things like lighting.
394 //
395 // Revision 1.25  1998/02/09 15:07:53  curt
396 // Minor tweaks.
397 //
398 // Revision 1.24  1998/01/27 00:48:07  curt
399 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
400 // system and commandline/config file processing code.
401 //
402 // Revision 1.23  1998/01/19 19:27:21  curt
403 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
404 // This should simplify things tremendously.
405 //
406 // Revision 1.22  1998/01/19 18:40:40  curt
407 // Tons of little changes to clean up the code and to remove fatal errors
408 // when building with the c++ compiler.
409 //
410 // Revision 1.21  1997/12/30 23:10:19  curt
411 // Calculate lighting parameters here.
412 //
413 // Revision 1.20  1997/12/30 22:22:43  curt
414 // Further integration of event manager.
415 //
416 // Revision 1.19  1997/12/30 20:47:59  curt
417 // Integrated new event manager with subsystem initializations.
418 //
419 // Revision 1.18  1997/12/23 04:58:40  curt
420 // Tweaked the sky coloring a bit to build in structures to allow finer rgb
421 // control.
422 //
423 // Revision 1.17  1997/12/15 23:55:08  curt
424 // Add xgl wrappers for debugging.
425 // Generate terrain normals on the fly.
426 //
427 // Revision 1.16  1997/12/11 04:43:57  curt
428 // Fixed sun vector and lighting problems.  I thing the moon is now lit
429 // correctly.
430 //
431 // Revision 1.15  1997/12/10 22:37:55  curt
432 // Prepended "fg" on the name of all global structures that didn't have it yet.
433 // i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
434 //
435 // Revision 1.14  1997/12/09 04:25:39  curt
436 // Working on adding a global lighting params structure.
437 //
438 // Revision 1.13  1997/11/25 19:25:42  curt
439 // Changes to integrate Durk's moon/sun code updates + clean up.
440 //
441 // Revision 1.12  1997/11/15 18:15:39  curt
442 // Reverse direction of sun vector, so object normals can be more normal.
443 //
444 // Revision 1.11  1997/10/28 21:07:21  curt
445 // Changed GLUT/ -> Main/
446 //
447 // Revision 1.10  1997/09/13 02:00:09  curt
448 // Mostly working on stars and generating sidereal time for accurate star
449 // placement.
450 //
451 // Revision 1.9  1997/09/05 14:17:31  curt
452 // More tweaking with stars.
453 //
454 // Revision 1.8  1997/09/05 01:36:04  curt
455 // Working on getting stars right.
456 //
457 // Revision 1.7  1997/09/04 02:17:40  curt
458 // Shufflin' stuff.
459 //
460 // Revision 1.6  1997/08/27 03:30:37  curt
461 // Changed naming scheme of basic shared structures.
462 //
463 // Revision 1.5  1997/08/22 21:34:41  curt
464 // Doing a bit of reorganizing and house cleaning.
465 //
466 // Revision 1.4  1997/08/19 23:55:09  curt
467 // Worked on better simulating real lighting.
468 //
469 // Revision 1.3  1997/08/13 20:23:49  curt
470 // The interface to sunpos now updates a global structure rather than returning
471 // current sun position.
472 //
473 // Revision 1.2  1997/08/06 00:24:32  curt
474 // Working on correct real time sun lighting.
475 //
476 // Revision 1.1  1997/08/01 15:27:56  curt
477 // Initial revision.
478 //