Light curve: Add and tune mid boost gaussian
[oweals/minetest.git] / src / light.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "light.h"
21 #include <cmath>
22 #include "util/numeric.h"
23 #include "settings.h"
24
25 #ifndef SERVER
26
27 // Length of LIGHT_MAX + 1 means LIGHT_MAX is the last value.
28 // LIGHT_SUN is read as LIGHT_MAX from here.
29 u8 light_LUT[LIGHT_MAX + 1];
30
31 // The const ref to light_LUT is what is actually used in the code
32 const u8 *light_decode_table = light_LUT;
33
34 // Initialize or update the light value tables using the specified gamma
35 void set_light_table(float gamma)
36 {
37 // Lighting curve derivatives
38         const float alpha = g_settings->getFloat("lighting_alpha");
39         const float beta  = g_settings->getFloat("lighting_beta");
40 // Lighting curve coefficients
41         const float a = alpha + beta - 2.0f;
42         const float b = 3.0f - 2.0f * alpha - beta;
43         const float c = alpha;
44 // Mid boost
45         const float d = g_settings->getFloat("lighting_boost");
46         const float e = g_settings->getFloat("lighting_boost_center");
47         const float f = g_settings->getFloat("lighting_boost_spread");
48 // Gamma correction
49         gamma = rangelim(gamma, 0.5f, 3.0f);
50
51         for (size_t i = 0; i < LIGHT_MAX; i++) {
52                 float x = i;
53                 x /= LIGHT_MAX;
54                 float brightness = a * x * x * x + b * x * x + c * x;
55                 float boost = d * std::exp(-((x - e) * (x - e)) / (2.0f * f * f));
56                 brightness = powf(brightness + boost, 1.0f / gamma);
57                 light_LUT[i] = rangelim((u32)(255.0f * brightness), 0, 255);
58                 if (i > 1 && light_LUT[i] <= light_LUT[i - 1])
59                         light_LUT[i] = light_LUT[i - 1] + 1;
60         }
61         light_LUT[LIGHT_MAX] = 255;
62 }
63 #endif