3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
23 #include "util/numeric.h"
28 static u8 light_LUT[LIGHT_SUN + 1];
30 // The const ref to light_LUT is what is actually used in the code
31 const u8 *light_decode_table = light_LUT;
34 struct LightingParams {
35 float a, b, c; // Lighting curve polynomial coefficients
36 float boost, center, sigma; // Lighting curve parametric boost
37 float gamma; // Lighting curve gamma correction
40 static LightingParams params;
43 float decode_light_f(float x)
45 if (x >= 1.0f) // x is often 1.0f
47 x = std::fmax(x, 0.0f);
48 float brightness = ((params.a * x + params.b) * x + params.c) * x;
49 brightness += params.boost *
50 std::exp(-0.5f * sqr((x - params.center) / params.sigma));
51 if (brightness <= 0.0f) // May happen if parameters are extreme
53 if (brightness >= 1.0f)
55 return powf(brightness, 1.0f / params.gamma);
59 // Initialize or update the light value tables using the specified gamma
60 void set_light_table(float gamma)
62 // Lighting curve bounding gradients
63 const float alpha = rangelim(g_settings->getFloat("lighting_alpha"), 0.0f, 3.0f);
64 const float beta = rangelim(g_settings->getFloat("lighting_beta"), 0.0f, 3.0f);
65 // Lighting curve polynomial coefficients
66 params.a = alpha + beta - 2.0f;
67 params.b = 3.0f - 2.0f * alpha - beta;
69 // Lighting curve parametric boost
70 params.boost = rangelim(g_settings->getFloat("lighting_boost"), 0.0f, 0.4f);
71 params.center = rangelim(g_settings->getFloat("lighting_boost_center"), 0.0f, 1.0f);
72 params.sigma = rangelim(g_settings->getFloat("lighting_boost_spread"), 0.0f, 0.4f);
73 // Lighting curve gamma correction
74 params.gamma = rangelim(gamma, 0.33f, 3.0f);
76 // Boundary values should be fixed
78 light_LUT[LIGHT_SUN] = 255;
80 for (size_t i = 1; i < LIGHT_SUN; i++) {
81 float brightness = decode_light_f((float)i / LIGHT_SUN);
82 // Strictly speaking, rangelim is not necessary here—if the implementation
83 // is conforming. But we don’t want problems in any case.
84 light_LUT[i] = rangelim((s32)(255.0f * brightness), 0, 255);
86 // Ensure light brightens with each level
87 if (i > 0 && light_LUT[i] <= light_LUT[i - 1]) {
88 light_LUT[i] = std::min((u8)254, light_LUT[i - 1]) + 1;