]> git.mxchange.org Git - flightgear.git/blob - src/Time/light.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[flightgear.git] / src / Time / light.cxx
1 //
2 // light.cxx -- lighting routines
3 //
4 // Written by Curtis Olson, started April 1998.
5 //
6 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #include <cmath>
32
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/interpolater.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/scene/sky/sky.hxx>
38 #include <simgear/screen/colors.hxx>
39 #include <simgear/timing/sg_time.hxx>
40 #include <simgear/structure/event_mgr.hxx>
41
42 #include <Main/main.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Viewer/renderer.hxx>
46 #include <Viewer/view.hxx>
47
48 #include "light.hxx"
49 #include "sunsolver.hxx"
50
51 // Constructor
52 FGLight::FGLight ()
53     : _ambient_tbl( NULL ),
54       _diffuse_tbl( NULL ),
55       _specular_tbl( NULL ),
56       _sky_tbl( NULL ),
57       _sun_lon(0),
58       _sun_lat(0),
59       _moon_lon(0),
60       _moon_gc_lat(0),
61       _sun_vec(0, 0, 0, 0),
62       _moon_vec(0, 0, 0, 0),
63       _sun_vec_inv(0, 0, 0, 0),
64       _moon_vec_inv(0, 0, 0, 0),
65       _sun_angle(0),
66       _moon_angle(0),
67       _prev_sun_angle(0),
68       _sun_rotation(0),
69       _moon_rotation(0),
70       _scene_ambient(0, 0, 0, 0),
71       _scene_diffuse(0, 0, 0, 0),
72       _scene_specular(0, 0, 0, 0),
73       _scene_chrome(0, 0, 0, 0),
74       _sun_color(1, 1, 1, 0),
75       _sky_color(0, 0, 0, 0),
76       _fog_color(0, 0, 0, 0),
77       _cloud_color(0, 0, 0, 0),
78       _adj_fog_color(0, 0, 0, 0),
79       _adj_sky_color(0, 0, 0, 0),
80       _saturation(1.0),
81       _scattering(0.8),
82       _overcast(0.0),
83       _dt_total(0)
84 {
85 }
86
87 // Destructor
88 FGLight::~FGLight ()
89 {
90     delete _ambient_tbl;
91     delete _diffuse_tbl;
92     delete _specular_tbl;
93     delete _sky_tbl;
94 }
95
96
97 // initialize lighting tables
98 void FGLight::init () {
99     SG_LOG( SG_EVENT, SG_INFO, 
100             "Initializing Lighting interpolation tables." );
101
102     // build the path names of the lookup tables
103     SGPath path( globals->get_fg_root() );
104
105     // initialize ambient, diffuse and specular tables
106     SGPath ambient_path = path;
107     ambient_path.append( "Lighting/ambient" );
108     _ambient_tbl = new SGInterpTable( ambient_path.str() );
109
110     SGPath diffuse_path = path;
111     diffuse_path.append( "Lighting/diffuse" );
112     _diffuse_tbl = new SGInterpTable( diffuse_path.str() );
113
114     SGPath specular_path = path;
115     specular_path.append( "Lighting/specular" );
116     _specular_tbl = new SGInterpTable( specular_path.str() );
117     
118     // initialize sky table
119     SGPath sky_path = path;
120     sky_path.append( "Lighting/sky" );
121     _sky_tbl = new SGInterpTable( sky_path.str() );
122     
123     globals->get_event_mgr()->addTask("updateSunPos", this,
124                             &FGLight::updateSunPos, 0.5 );
125 }
126
127
128 void FGLight::reinit () {
129     _prev_sun_angle = -9999.0;
130     _dt_total = 0;
131
132     delete _ambient_tbl;
133     delete _diffuse_tbl;
134     delete _specular_tbl;
135     delete _sky_tbl;
136
137     init();
138
139     updateSunPos();
140     update_sky_color();
141     update_adj_fog_color();
142 }
143
144 void FGLight::bind () {
145     SGPropertyNode *prop = globals->get_props();
146
147     // Write Only
148     tie(prop,"/rendering/scene/saturation",     SGRawValuePointer<float>(&_saturation));
149     tie(prop,"/rendering/scene/scattering",     SGRawValuePointer<float>(&_scattering));
150     tie(prop,"/rendering/scene/overcast",       SGRawValuePointer<float>(&_overcast));
151
152     _sunAngleRad = prop->getNode("/sim/time/sun-angle-rad", true);
153     _sunAngleRad->setDoubleValue(_sun_angle);
154     _humidity = fgGetNode("/environment/relative-humidity", true);
155
156     // Read Only
157     tie(prop,"/rendering/scene/ambient/red",    SGRawValuePointer<float>(&_scene_ambient[0]));
158     tie(prop,"/rendering/scene/ambient/green",  SGRawValuePointer<float>(&_scene_ambient[1]));
159     tie(prop,"/rendering/scene/ambient/blue",   SGRawValuePointer<float>(&_scene_ambient[2]));
160     tie(prop,"/rendering/scene/diffuse/red",    SGRawValuePointer<float>(&_scene_diffuse[0]));
161     tie(prop,"/rendering/scene/diffuse/green",  SGRawValuePointer<float>(&_scene_diffuse[1]));
162     tie(prop,"/rendering/scene/diffuse/blue",   SGRawValuePointer<float>(&_scene_diffuse[2]));
163     tie(prop,"/rendering/scene/specular/red",   SGRawValuePointer<float>(&_scene_specular[0]));
164     tie(prop,"/rendering/scene/specular/green", SGRawValuePointer<float>(&_scene_specular[1]));
165     tie(prop,"/rendering/scene/specular/blue",  SGRawValuePointer<float>(&_scene_specular[2]));
166     tie(prop,"/rendering/dome/sun/red",         SGRawValuePointer<float>(&_sun_color[0]));
167     tie(prop,"/rendering/dome/sun/green",       SGRawValuePointer<float>(&_sun_color[1]));
168     tie(prop,"/rendering/dome/sun/blue",        SGRawValuePointer<float>(&_sun_color[2]));
169     tie(prop,"/rendering/dome/sky/red",         SGRawValuePointer<float>(&_sky_color[0]));
170     tie(prop,"/rendering/dome/sky/green",       SGRawValuePointer<float>(&_sky_color[1]));
171     tie(prop,"/rendering/dome/sky/blue",        SGRawValuePointer<float>(&_sky_color[2]));
172     tie(prop,"/rendering/dome/cloud/red",       SGRawValuePointer<float>(&_cloud_color[0]));
173     tie(prop,"/rendering/dome/cloud/green",     SGRawValuePointer<float>(&_cloud_color[1]));
174     tie(prop,"/rendering/dome/cloud/blue",      SGRawValuePointer<float>(&_cloud_color[2]));
175     tie(prop,"/rendering/dome/fog/red",         SGRawValuePointer<float>(&_fog_color[0]));
176     tie(prop,"/rendering/dome/fog/green",       SGRawValuePointer<float>(&_fog_color[1]));
177     tie(prop,"/rendering/dome/fog/blue",        SGRawValuePointer<float>(&_fog_color[2]));
178
179     // Sun vector
180     tie(prop,"/ephemeris/sun/local/x", SGRawValuePointer<float>(&_sun_vec[0]));
181     tie(prop,"/ephemeris/sun/local/y", SGRawValuePointer<float>(&_sun_vec[1]));
182     tie(prop,"/ephemeris/sun/local/z", SGRawValuePointer<float>(&_sun_vec[2]));
183
184     // Properties used directly by effects
185     _chromeProps[0] = prop->getNode("/rendering/scene/chrome-light/red", true);
186     _chromeProps[1] = prop->getNode("/rendering/scene/chrome-light/green",
187                                     true);
188     _chromeProps[2] = prop->getNode("/rendering/scene/chrome-light/blue", true);
189     _chromeProps[3] = prop->getNode("/rendering/scene/chrome-light/alpha",
190                                     true);
191     for (int i = 0; i < 4; ++i)
192         _chromeProps[i]->setValue(0.0);
193 }
194
195 void FGLight::unbind () {
196     _tiedProperties.Untie();
197     
198     for (int i = 0; i < 4; ++i)
199         _chromeProps[i] = SGPropertyNode_ptr();
200     _sunAngleRad = SGPropertyNode_ptr();
201     _humidity = SGPropertyNode_ptr();
202 }
203
204
205 // update lighting parameters based on current sun position
206 void FGLight::update( double dt )
207 {
208     update_adj_fog_color();
209
210     if (_prev_sun_angle != _sun_angle) {
211         _prev_sun_angle = _sun_angle;
212         update_sky_color();
213     }
214 }
215
216 void FGLight::update_sky_color () {
217     const SGVec4f base_sky_color( 0.31, 0.43, 0.69, 1.0 );
218     const SGVec4f base_fog_color( 0.63, 0.72, 0.88, 1.0 );
219
220     // calculate lighting parameters based on sun's relative angle to
221     // local up
222     float av = _humidity->getFloatValue() * 45;
223     float visibility_log = log(av)/11.0;
224     float visibility_inv = (45000.0 - av)/45000.0;
225
226     float deg = _sun_angle * SGD_RADIANS_TO_DEGREES;
227
228     if (_saturation < 0.0) _saturation = 0.0;
229     else if (_saturation > 1.0) _saturation = 1.0;
230     if (_scattering < 0.0) _scattering = 0.0;
231     else if (_scattering > 1.0) _scattering = 1.0;
232     if (_overcast < 0.0) _overcast = 0.0;
233     else if (_overcast > 1.0) _overcast = 1.0;
234
235     float ambient = _ambient_tbl->interpolate( deg ) + visibility_inv/10;
236     float diffuse = _diffuse_tbl->interpolate( deg );
237     float specular = _specular_tbl->interpolate( deg ) * visibility_log;
238     float sky_brightness = _sky_tbl->interpolate( deg );
239
240     ambient *= _saturation;
241     diffuse *= _saturation;
242     specular *= _saturation;
243     sky_brightness *= _saturation;
244
245     // sky_brightness = 0.15;  // used to force a dark sky (when testing)
246
247     /** fog color */
248     float sqr_sky_brightness = sky_brightness * sky_brightness * _scattering;
249     _fog_color = base_fog_color * sqr_sky_brightness;
250     _fog_color[3] = base_fog_color[3];
251     gamma_correct_rgb( _fog_color.data() );
252
253     /** sky color */
254     static const SGVec4f one_vec( 1.0f, 1.0f, 1.0f, 1.0f);
255     SGVec4f overcast_color = (one_vec - base_sky_color) * _overcast;
256     _sky_color = (base_sky_color + overcast_color) * sky_brightness;
257     _sky_color[3] = base_sky_color[3];
258     gamma_correct_rgb( _sky_color.data() );
259
260     /** cloud color */
261     _cloud_color = base_fog_color * sky_brightness;
262
263     /** adjust the cloud colors for sunrise/sunset effects (darken them) */
264     if (_sun_angle > 1.0) {
265        float sun2 = 1.0 / sqrt(_sun_angle);
266        _cloud_color *= sun2;
267     }
268     _cloud_color[3] = base_fog_color[3];
269     gamma_correct_rgb( _cloud_color.data() );
270
271     /** ambient light */
272     _scene_ambient = _fog_color  * ambient;
273     _scene_ambient[3] = _fog_color[3];
274     gamma_correct_rgb( _scene_ambient.data() );
275
276     /** diffuse light */
277     SGSky* thesky = globals->get_renderer()->getSky();
278     SGVec4f color = thesky->get_scene_color();
279     _scene_diffuse = color * diffuse;
280     _scene_diffuse[3] = color[3];
281     gamma_correct_rgb( _scene_diffuse.data() );
282
283     SGVec4f chrome = _scene_ambient * .4f + _scene_diffuse;
284     chrome[3] = 1.0f;
285     if (chrome != _scene_chrome) {
286         _scene_chrome = chrome;
287         for (int i = 0; i < 4; ++i)
288             _chromeProps[i]->setValue(static_cast<double>(_scene_chrome[i]));
289     }
290
291     /** specular light */
292     _sun_color = thesky->get_sun_color();
293     _scene_specular = _sun_color * specular;
294     _scene_specular[3] = _sun_color[3];
295     gamma_correct_rgb( _scene_specular.data() );
296 }
297
298
299 // calculate fog color adjusted for sunrise/sunset effects
300 void FGLight::update_adj_fog_color () {
301
302 //    double pitch = globals->get_current_view()->getPitch_deg()
303 //                     * SGD_DEGREES_TO_RADIANS;
304 //    double pitch_offset = globals->get_current_view()-> getPitchOffset_deg()
305 //                     * SGD_DEGREES_TO_RADIANS;
306     double heading = globals->get_current_view()->getHeading_deg()
307                      * SGD_DEGREES_TO_RADIANS;
308     double heading_offset = globals->get_current_view()->getHeadingOffset_deg()
309                             * SGD_DEGREES_TO_RADIANS;
310
311     // set fog color (we'll try to match the sunset color in the
312     // direction we are looking
313
314     // Do some sanity checking ...
315     if ( _sun_rotation < -2.0 * SGD_2PI || _sun_rotation > 2.0 * SGD_2PI ) {
316         SG_LOG( SG_EVENT, SG_ALERT, "Sun rotation bad = " << _sun_rotation );
317         return;
318     }
319
320     if ( heading < -2.0 * SGD_2PI || heading > 2.0 * SGD_2PI ) {
321         SG_LOG( SG_EVENT, SG_ALERT, "Heading rotation bad = " << heading );
322         return;
323     }
324
325     if ( heading_offset < -2.0 * SGD_2PI || heading_offset > 2.0 * SGD_2PI ) {
326         SG_LOG( SG_EVENT, SG_ALERT, "Heading offset bad = " << heading_offset );
327         return;
328     }
329
330     static float gamma = system_gamma;
331
332     // first determine the difference between our view angle and local
333     // direction to the sun
334     //double vert_rotation = pitch + pitch_offset;
335
336     // revert to unmodified values before using them.
337     //
338     SGSky* thesky = globals->get_renderer()->getSky();
339     SGVec4f color = thesky->get_scene_color();
340
341     gamma_restore_rgb( _fog_color.data(), gamma );
342     gamma_restore_rgb( _sky_color.data(), gamma );
343
344     // Calculate the fog color in the direction of the sun for
345     // sunrise/sunset effects.
346     //
347     _sun_color[0] = color[0]*color[0]*color[0];
348     _sun_color[1] = color[1]*color[1]*color[1];
349     _sun_color[2] = color[2]*color[2];
350
351     // interpolate between the sunrise/sunset color and the color
352     // at the opposite direction of this effect. Take in account
353     // the current visibility.
354     //
355     float av = thesky->get_visibility();
356     if (av > 45000) av = 45000;
357
358     float avf = 0.87 - (45000 - av) / 83333.33;
359     float sif = 0.5 - cos(_sun_angle*2)/2;
360
361     if (sif < 1e-4)
362        sif = 1e-4;
363
364     // determine horizontal angle between current view direction and sun
365     // since _sun_rotation is relative to South, and heading is in the local frame
366     // we need to account for the 180 degrees offset and differing signs 
367     // hence the negation and SGD_PI adjustment.
368     double hor_rotation = -_sun_rotation - SGD_PI - heading + heading_offset;
369     if (hor_rotation < 0 )
370         hor_rotation = fmod(hor_rotation, SGD_2PI) + SGD_2PI;
371     else
372         hor_rotation = fmod(hor_rotation, SGD_2PI);
373
374     float rf1 = fabs((hor_rotation - SGD_PI) / SGD_PI); // 0.0 .. 1.0
375     float rf2 = avf * pow(rf1*rf1, 1/sif) * 1.0639 * _saturation * _scattering;
376     float rf3 = 1.0 - rf2;
377
378     gamma = system_gamma * (0.9 - sif*avf);
379     _adj_fog_color = rf3 * _fog_color + rf2 * _sun_color;
380     _adj_fog_color[3] = 0;
381     gamma_correct_rgb( _adj_fog_color.data(), gamma);
382
383     // make sure the colors have their original value before they are being
384     // used by the rest of the program.
385     //
386     gamma_correct_rgb( _fog_color.data(), gamma );
387     gamma_correct_rgb( _sky_color.data(), gamma );
388 }
389
390 // update the cur_time_params structure with the current sun position
391 void FGLight::updateSunPos()
392 {
393     SGTime *t = globals->get_time_params();
394
395     fgSunPositionGST(t->getGst(), &_sun_lon, &_sun_lat);
396
397     // It might seem that sun_gc_lat needs to be converted to geodetic
398     // latitude here, but it doesn't. The sun latitude is the latitude
399     // of the point on the earth where the up vector has the same
400     // angle from geocentric Z as the sun direction. But geodetic
401     // latitude is defined as 90 - angle of up vector from Z!
402     SGVec3d sunpos = SGVec3d::fromGeoc(SGGeoc::fromRadM(_sun_lon, _sun_lat,
403                                                           SGGeodesy::EQURAD));
404
405     // update the sun light vector
406     _sun_vec = SGVec4f(toVec3f(normalize(sunpos)), 0);
407     _sun_vec_inv = - _sun_vec;
408
409     // calculate the sun's relative angle to local up
410     SGQuatd hlOr =  SGQuatd::fromLonLat( globals->get_view_position() );
411     SGVec3d world_up = hlOr.backTransform( -SGVec3d::e3() );
412     // cout << "nup = " << nup[0] << "," << nup[1] << ","
413     //      << nup[2] << endl;
414     // cout << "nsun = " << nsun[0] << "," << nsun[1] << ","
415     //      << nsun[2] << endl;
416
417     SGVec3d nsun = normalize(sunpos);
418     SGVec3d nup = normalize(world_up);
419     _sun_angle = acos( dot( nup, nsun ) );
420
421     double signedPI = (_sun_angle < 0.0) ? -SGD_PI : SGD_PI;
422     _sun_angle = fmod(_sun_angle+signedPI, SGD_2PI) - signedPI;
423
424     // Get direction to the sun in the local frame.
425     SGVec3d local_sun_vec = hlOr.transform(nsun);
426
427     // Angle from South. 
428     // atan2(y,x) returns the angle between the positive X-axis
429     // and the vector with the origin at 0, going through (x,y)
430     // Since the local frame coordinates have x-positive pointing Nord and 
431     // y-positive pointing East we need to negate local_sun_vec.x()
432     // _sun_rotation is positive counterclockwise from South (sun in the East)
433     // and negative clockwise from South (sun in the West)
434     _sun_rotation = atan2(local_sun_vec.y(), -local_sun_vec.x());
435
436     // cout << "  Sky needs to rotate = " << _sun_rotation << " rads = "
437     //      << _sun_rotation * SGD_RADIANS_TO_DEGREES << " degrees." << endl;
438   
439     _sunAngleRad->setDoubleValue(_sun_angle);
440 }