]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/sky.cpp
Merge branch 'master' of https://github.com/minetest/minetest
[dragonfireclient.git] / src / client / sky.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2020 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "sky.h"
22 #include "ITexture.h"
23 #include "IVideoDriver.h"
24 #include "ISceneManager.h"
25 #include "ICameraSceneNode.h"
26 #include "S3DVertex.h"
27 #include "client/tile.h"
28 #include "noise.h" // easeCurve
29 #include "profiler.h"
30 #include "util/numeric.h"
31 #include <cmath>
32 #include "client/renderingengine.h"
33 #include "settings.h"
34 #include "camera.h" // CameraModes
35 #include "config.h"
36 using namespace irr::core;
37
38 static video::SMaterial baseMaterial()
39 {
40         video::SMaterial mat;
41         mat.Lighting = false;
42 #if ENABLE_GLES
43         mat.ZBuffer = video::ECFN_DISABLED;
44 #else
45         mat.ZBuffer = video::ECFN_NEVER;
46 #endif
47         mat.ZWriteEnable = false;
48         mat.AntiAliasing = 0;
49         mat.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE;
50         mat.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE;
51         mat.BackfaceCulling = false;
52         return mat;
53 };
54
55 Sky::Sky(s32 id, ITextureSource *tsrc, IShaderSource *ssrc) :
56                 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
57                         RenderingEngine::get_scene_manager(), id)
58 {
59         setAutomaticCulling(scene::EAC_OFF);
60         m_box.MaxEdge.set(0, 0, 0);
61         m_box.MinEdge.set(0, 0, 0);
62
63         m_enable_shaders = g_settings->getBool("enable_shaders");
64
65         // Create materials
66
67         m_materials[0] = baseMaterial();
68         m_materials[0].MaterialType = ssrc->getShaderInfo(ssrc->getShader("stars_shader", TILE_MATERIAL_ALPHA)).material;
69         m_materials[0].Lighting = true;
70         m_materials[0].ColorMaterial = video::ECM_NONE;
71
72         m_materials[1] = baseMaterial();
73         //m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA;
74         m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
75
76         m_materials[2] = baseMaterial();
77         m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png"));
78         m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
79         //m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR;
80
81         // Ensures that sun and moon textures and tonemaps are correct.
82         setSkyDefaults();
83         m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) ?
84                 tsrc->getTextureForMesh(m_sun_params.texture) : NULL;
85         m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) ?
86                 tsrc->getTextureForMesh(m_moon_params.texture) : NULL;
87         m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
88                 tsrc->getTexture(m_sun_params.tonemap) : NULL;
89         m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
90                 tsrc->getTexture(m_moon_params.tonemap) : NULL;
91
92         if (m_sun_texture) {
93                 m_materials[3] = baseMaterial();
94                 m_materials[3].setTexture(0, m_sun_texture);
95                 m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
96                 // Disables texture filtering
97                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
98                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
99                 m_materials[3].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
100                 // Use tonemaps if available
101                 if (m_sun_tonemap)
102                         m_materials[3].Lighting = true;
103         }
104         if (m_moon_texture) {
105                 m_materials[4] = baseMaterial();
106                 m_materials[4].setTexture(0, m_moon_texture);
107                 m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
108                 // Disables texture filtering
109                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
110                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
111                 m_materials[4].setFlag(video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
112                 // Use tonemaps if available
113                 if (m_moon_tonemap)
114                         m_materials[4].Lighting = true;
115         }
116
117         for (int i = 5; i < 11; i++) {
118                 m_materials[i] = baseMaterial();
119                 m_materials[i].Lighting = true;
120                 m_materials[i].MaterialType = video::EMT_SOLID;
121         }
122         m_directional_colored_fog = g_settings->getBool("directional_colored_fog");
123         setStarCount(1000, true);
124 }
125
126 void Sky::OnRegisterSceneNode()
127 {
128         if (IsVisible)
129                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SKY_BOX);
130
131         scene::ISceneNode::OnRegisterSceneNode();
132 }
133
134 void Sky::render()
135 {
136         video::IVideoDriver *driver = SceneManager->getVideoDriver();
137         scene::ICameraSceneNode *camera = SceneManager->getActiveCamera();
138
139         if (!camera || !driver)
140                 return;
141
142         ScopeProfiler sp(g_profiler, "Sky::render()", SPT_AVG);
143
144         // Draw perspective skybox
145
146         core::matrix4 translate(AbsoluteTransformation);
147         translate.setTranslation(camera->getAbsolutePosition());
148
149         // Draw the sky box between the near and far clip plane
150         const f32 viewDistance = (camera->getNearValue() + camera->getFarValue()) * 0.5f;
151         core::matrix4 scale;
152         scale.setScale(core::vector3df(viewDistance, viewDistance, viewDistance));
153
154         driver->setTransform(video::ETS_WORLD, translate * scale);
155
156         if (m_sunlight_seen) {
157                 float sunsize = 0.07;
158                 video::SColorf suncolor_f(1, 1, 0, 1);
159                 //suncolor_f.r = 1;
160                 //suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5));
161                 //suncolor_f.b = MYMAX(0.0, m_brightness * 0.95);
162                 video::SColorf suncolor2_f(1, 1, 1, 1);
163                 // The values below were probably meant to be suncolor2_f instead of a
164                 // reassignment of suncolor_f. However, the resulting colour was chosen
165                 // and is our long-running classic colour. So preserve, but comment-out
166                 // the unnecessary first assignments above.
167                 suncolor_f.r = 1;
168                 suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.85 + m_time_brightness * 0.5));
169                 suncolor_f.b = MYMAX(0.0, m_brightness);
170
171                 float moonsize = 0.04;
172                 video::SColorf mooncolor_f(0.50, 0.57, 0.65, 1);
173                 video::SColorf mooncolor2_f(0.85, 0.875, 0.9, 1);
174
175                 float nightlength = 0.415;
176                 float wn = nightlength / 2;
177                 float wicked_time_of_day = 0;
178                 if (m_time_of_day > wn && m_time_of_day < 1.0 - wn)
179                         wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25;
180                 else if (m_time_of_day < 0.5)
181                         wicked_time_of_day = m_time_of_day / wn * 0.25;
182                 else
183                         wicked_time_of_day = 1.0 - ((1.0 - m_time_of_day) / wn * 0.25);
184                 /*std::cerr<<"time_of_day="<<m_time_of_day<<" -> "
185                                 <<"wicked_time_of_day="<<wicked_time_of_day<<std::endl;*/
186
187                 video::SColor suncolor = suncolor_f.toSColor();
188                 video::SColor suncolor2 = suncolor2_f.toSColor();
189                 video::SColor mooncolor = mooncolor_f.toSColor();
190                 video::SColor mooncolor2 = mooncolor2_f.toSColor();
191
192                 // Calculate offset normalized to the X dimension of a 512x1 px tonemap
193                 float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511;
194
195                 if (m_sun_tonemap) {
196                         u8 * texels = (u8 *)m_sun_tonemap->lock();
197                         video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
198                         video::SColor texel_color (255, texel->getRed(),
199                                 texel->getGreen(), texel->getBlue());
200                         m_sun_tonemap->unlock();
201                         m_materials[3].EmissiveColor = texel_color;
202                 }
203
204                 if (m_moon_tonemap) {
205                         u8 * texels = (u8 *)m_moon_tonemap->lock();
206                         video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4);
207                         video::SColor texel_color (255, texel->getRed(),
208                                 texel->getGreen(), texel->getBlue());
209                         m_moon_tonemap->unlock();
210                         m_materials[4].EmissiveColor = texel_color;
211                 }
212
213                 const f32 t = 1.0f;
214                 const f32 o = 0.0f;
215                 static const u16 indices[6] = {0, 1, 2, 0, 2, 3};
216                 video::S3DVertex vertices[4];
217
218                 driver->setMaterial(m_materials[1]);
219
220                 video::SColor cloudyfogcolor = m_bgcolor;
221
222                 // Abort rendering if we're in the clouds.
223                 // Stops rendering a pure white hole in the bottom of the skybox.
224                 if (m_in_clouds)
225                         return;
226
227                 // Draw the six sided skybox,
228                 if (m_sky_params.textures.size() == 6) {
229                         for (u32 j = 5; j < 11; j++) {
230                                 video::SColor c(255, 255, 255, 255);
231                                 driver->setMaterial(m_materials[j]);
232                                 // Use 1.05 rather than 1.0 to avoid colliding with the
233                                 // sun, moon and stars, as this is a background skybox.
234                                 vertices[0] = video::S3DVertex(-1.05, -1.05, -1.05, 0, 0, 1, c, t, t);
235                                 vertices[1] = video::S3DVertex( 1.05, -1.05, -1.05, 0, 0, 1, c, o, t);
236                                 vertices[2] = video::S3DVertex( 1.05,  1.05, -1.05, 0, 0, 1, c, o, o);
237                                 vertices[3] = video::S3DVertex(-1.05,  1.05, -1.05, 0, 0, 1, c, t, o);
238                                 for (video::S3DVertex &vertex : vertices) {
239                                         if (j == 5) { // Top texture
240                                                 vertex.Pos.rotateYZBy(90);
241                                                 vertex.Pos.rotateXZBy(90);
242                                         } else if (j == 6) { // Bottom texture
243                                                 vertex.Pos.rotateYZBy(-90);
244                                                 vertex.Pos.rotateXZBy(90);
245                                         } else if (j == 7) { // Left texture
246                                                 vertex.Pos.rotateXZBy(90);
247                                         } else if (j == 8) { // Right texture
248                                                 vertex.Pos.rotateXZBy(-90);
249                                         } else if (j == 9) { // Front texture, do nothing
250                                                 // Irrlicht doesn't like it when vertexes are left
251                                                 // alone and not rotated for some reason.
252                                                 vertex.Pos.rotateXZBy(0);
253                                         } else {// Back texture
254                                                 vertex.Pos.rotateXZBy(180);
255                                         }
256                                 }
257                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
258                         }
259                 }
260
261                 // Draw far cloudy fog thing blended with skycolor
262                 if (m_visible) {
263                         driver->setMaterial(m_materials[1]);
264                         for (u32 j = 0; j < 4; j++) {
265                                 vertices[0] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, m_bgcolor, t, t);
266                                 vertices[1] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, m_bgcolor, o, t);
267                                 vertices[2] = video::S3DVertex( 1, 0.45, -1, 0, 0, 1, m_skycolor, o, o);
268                                 vertices[3] = video::S3DVertex(-1, 0.45, -1, 0, 0, 1, m_skycolor, t, o);
269                                 for (video::S3DVertex &vertex : vertices) {
270                                         if (j == 0)
271                                                 // Don't switch
272                                                 {}
273                                         else if (j == 1)
274                                                 // Switch from -Z (south) to +X (east)
275                                                 vertex.Pos.rotateXZBy(90);
276                                         else if (j == 2)
277                                                 // Switch from -Z (south) to -X (west)
278                                                 vertex.Pos.rotateXZBy(-90);
279                                         else
280                                                 // Switch from -Z (south) to +Z (north)
281                                                 vertex.Pos.rotateXZBy(-180);
282                                 }
283                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
284                         }
285                 }
286
287                 // Draw stars before sun and moon to be behind them
288                 if (m_star_params.visible)
289                         draw_stars(driver, wicked_time_of_day);
290
291                 // Draw sunrise/sunset horizon glow texture
292                 // (textures/base/pack/sunrisebg.png)
293                 if (m_sun_params.sunrise_visible) {
294                         driver->setMaterial(m_materials[2]);
295                         float mid1 = 0.25;
296                         float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1);
297                         float a_ = 1.0f - std::fabs(wicked_time_of_day - mid) * 35.0f;
298                         float a = easeCurve(MYMAX(0, MYMIN(1, a_)));
299                         //std::cerr<<"a_="<<a_<<" a="<<a<<std::endl;
300                         video::SColor c(255, 255, 255, 255);
301                         float y = -(1.0 - a) * 0.22;
302                         vertices[0] = video::S3DVertex(-1, -0.05 + y, -1, 0, 0, 1, c, t, t);
303                         vertices[1] = video::S3DVertex( 1, -0.05 + y, -1, 0, 0, 1, c, o, t);
304                         vertices[2] = video::S3DVertex( 1,   0.2 + y, -1, 0, 0, 1, c, o, o);
305                         vertices[3] = video::S3DVertex(-1,   0.2 + y, -1, 0, 0, 1, c, t, o);
306                         for (video::S3DVertex &vertex : vertices) {
307                                 if (wicked_time_of_day < 0.5)
308                                         // Switch from -Z (south) to +X (east)
309                                         vertex.Pos.rotateXZBy(90);
310                                 else
311                                         // Switch from -Z (south) to -X (west)
312                                         vertex.Pos.rotateXZBy(-90);
313                         }
314                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
315                 }
316
317                 // Draw sun
318                 if (m_sun_params.visible)
319                         draw_sun(driver, sunsize, suncolor, suncolor2, wicked_time_of_day);
320
321                 // Draw moon
322                 if (m_moon_params.visible)
323                         draw_moon(driver, moonsize, mooncolor, mooncolor2, wicked_time_of_day);
324
325                 // Draw far cloudy fog thing below all horizons in front of sun, moon
326                 // and stars.
327                 if (m_visible) {
328                         driver->setMaterial(m_materials[1]);
329
330                         for (u32 j = 0; j < 4; j++) {
331                                 video::SColor c = cloudyfogcolor;
332                                 vertices[0] = video::S3DVertex(-1, -1.0,  -1, 0, 0, 1, c, t, t);
333                                 vertices[1] = video::S3DVertex( 1, -1.0,  -1, 0, 0, 1, c, o, t);
334                                 vertices[2] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, c, o, o);
335                                 vertices[3] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, c, t, o);
336                                 for (video::S3DVertex &vertex : vertices) {
337                                         if (j == 0)
338                                                 // Don't switch
339                                                 {}
340                                         else if (j == 1)
341                                                 // Switch from -Z (south) to +X (east)
342                                                 vertex.Pos.rotateXZBy(90);
343                                         else if (j == 2)
344                                                 // Switch from -Z (south) to -X (west)
345                                                 vertex.Pos.rotateXZBy(-90);
346                                         else
347                                                 // Switch from -Z (south) to +Z (north)
348                                                 vertex.Pos.rotateXZBy(-180);
349                                 }
350                                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
351                         }
352
353                         // Draw bottom far cloudy fog thing in front of sun, moon and stars
354                         video::SColor c = cloudyfogcolor;
355                         vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 1, 0, c, t, t);
356                         vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 1, 0, c, o, t);
357                         vertices[2] = video::S3DVertex( 1, -1.0, 1, 0, 1, 0, c, o, o);
358                         vertices[3] = video::S3DVertex(-1, -1.0, 1, 0, 1, 0, c, t, o);
359                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
360                 }
361         }
362 }
363
364 void Sky::update(float time_of_day, float time_brightness,
365         float direct_brightness, bool sunlight_seen,
366         CameraMode cam_mode, float yaw, float pitch)
367 {
368         // Stabilize initial brightness and color values by flooding updates
369         if (m_first_update) {
370                 /*dstream<<"First update with time_of_day="<<time_of_day
371                                 <<" time_brightness="<<time_brightness
372                                 <<" direct_brightness="<<direct_brightness
373                                 <<" sunlight_seen="<<sunlight_seen<<std::endl;*/
374                 m_first_update = false;
375                 for (u32 i = 0; i < 100; i++) {
376                         update(time_of_day, time_brightness, direct_brightness,
377                                         sunlight_seen, cam_mode, yaw, pitch);
378                 }
379                 return;
380         }
381
382         m_time_of_day = time_of_day;
383         m_time_brightness = time_brightness;
384         m_sunlight_seen = sunlight_seen;
385         m_in_clouds = false;
386
387         bool is_dawn = (time_brightness >= 0.20 && time_brightness < 0.35);
388
389         /*
390         Development colours
391
392         video::SColorf bgcolor_bright_normal_f(170. / 255, 200. / 255, 230. / 255, 1.0);
393         video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 * 0.5, 1.0);
394         video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0);
395         video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.0, 1.0);
396         video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.2, 1.0);
397
398         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.591, 0.4);
399         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.65, 0.44);
400         video::SColorf cloudcolor_bright_dawn_f(1.0, 0.7, 0.5);
401         */
402
403         video::SColorf bgcolor_bright_normal_f = m_sky_params.sky_color.day_horizon;
404         video::SColorf bgcolor_bright_indoor_f = m_sky_params.sky_color.indoors;
405         video::SColorf bgcolor_bright_dawn_f = m_sky_params.sky_color.dawn_horizon;
406         video::SColorf bgcolor_bright_night_f = m_sky_params.sky_color.night_horizon;
407
408         video::SColorf skycolor_bright_normal_f = m_sky_params.sky_color.day_sky;
409         video::SColorf skycolor_bright_dawn_f = m_sky_params.sky_color.dawn_sky;
410         video::SColorf skycolor_bright_night_f = m_sky_params.sky_color.night_sky;
411
412         video::SColorf cloudcolor_bright_normal_f = m_cloudcolor_day_f;
413         video::SColorf cloudcolor_bright_dawn_f = m_cloudcolor_dawn_f;
414
415         float cloud_color_change_fraction = 0.95;
416         if (sunlight_seen) {
417                 if (std::fabs(time_brightness - m_brightness) < 0.2f) {
418                         m_brightness = m_brightness * 0.95 + time_brightness * 0.05;
419                 } else {
420                         m_brightness = m_brightness * 0.80 + time_brightness * 0.20;
421                         cloud_color_change_fraction = 0.0;
422                 }
423         } else {
424                 if (direct_brightness < m_brightness)
425                         m_brightness = m_brightness * 0.95 + direct_brightness * 0.05;
426                 else
427                         m_brightness = m_brightness * 0.98 + direct_brightness * 0.02;
428         }
429
430         m_clouds_visible = true;
431         float color_change_fraction = 0.98f;
432         if (sunlight_seen) {
433                 if (is_dawn) { // Dawn
434                         m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
435                                 bgcolor_bright_dawn_f, color_change_fraction);
436                         m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
437                                 skycolor_bright_dawn_f, color_change_fraction);
438                         m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
439                                 cloudcolor_bright_dawn_f, color_change_fraction);
440                 } else {
441                         if (time_brightness < 0.13f) { // Night
442                                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
443                                         bgcolor_bright_night_f, color_change_fraction);
444                                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
445                                         skycolor_bright_night_f, color_change_fraction);
446                         } else { // Day
447                                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
448                                         bgcolor_bright_normal_f, color_change_fraction);
449                                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
450                                         skycolor_bright_normal_f, color_change_fraction);
451                         }
452
453                         m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
454                                 cloudcolor_bright_normal_f, color_change_fraction);
455                 }
456         } else {
457                 m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated(
458                         bgcolor_bright_indoor_f, color_change_fraction);
459                 m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated(
460                         bgcolor_bright_indoor_f, color_change_fraction);
461                 m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated(
462                         cloudcolor_bright_normal_f, color_change_fraction);
463                 m_clouds_visible = false;
464         }
465
466         video::SColor bgcolor_bright = m_bgcolor_bright_f.toSColor();
467         m_bgcolor = video::SColor(
468                 255,
469                 bgcolor_bright.getRed() * m_brightness,
470                 bgcolor_bright.getGreen() * m_brightness,
471                 bgcolor_bright.getBlue() * m_brightness
472         );
473
474         video::SColor skycolor_bright = m_skycolor_bright_f.toSColor();
475         m_skycolor = video::SColor(
476                 255,
477                 skycolor_bright.getRed() * m_brightness,
478                 skycolor_bright.getGreen() * m_brightness,
479                 skycolor_bright.getBlue() * m_brightness
480         );
481
482         // Horizon coloring based on sun and moon direction during sunset and sunrise
483         video::SColor pointcolor = video::SColor(m_bgcolor.getAlpha(), 255, 255, 255);
484         if (m_directional_colored_fog) {
485                 if (m_horizon_blend() != 0) {
486                         // Calculate hemisphere value from yaw, (inverted in third person front view)
487                         s8 dir_factor = 1;
488                         if (cam_mode > CAMERA_MODE_THIRD)
489                                 dir_factor = -1;
490                         f32 pointcolor_blend = wrapDegrees_0_360(yaw * dir_factor + 90);
491                         if (pointcolor_blend > 180)
492                                 pointcolor_blend = 360 - pointcolor_blend;
493                         pointcolor_blend /= 180;
494                         // Bound view angle to determine where transition starts and ends
495                         pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0, 1 / 1.375) *
496                                 1.375;
497                         // Combine the colors when looking up or down, otherwise turning looks weird
498                         pointcolor_blend += (0.5 - pointcolor_blend) *
499                                 (1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5, 1));
500                         // Invert direction to match where the sun and moon are rising
501                         if (m_time_of_day > 0.5)
502                                 pointcolor_blend = 1 - pointcolor_blend;
503                         // Horizon colors of sun and moon
504                         f32 pointcolor_light = rangelim(m_time_brightness * 3, 0.2, 1);
505
506                         video::SColorf pointcolor_sun_f(1, 1, 1, 1);
507                         // Use tonemap only if default sun/moon tinting is used
508                         // which keeps previous behaviour.
509                         if (m_sun_tonemap && m_default_tint) {
510                                 pointcolor_sun_f.r = pointcolor_light *
511                                         (float)m_materials[3].EmissiveColor.getRed() / 255;
512                                 pointcolor_sun_f.b = pointcolor_light *
513                                         (float)m_materials[3].EmissiveColor.getBlue() / 255;
514                                 pointcolor_sun_f.g = pointcolor_light *
515                                         (float)m_materials[3].EmissiveColor.getGreen() / 255;
516                         } else if (!m_default_tint) {
517                                 pointcolor_sun_f = m_sky_params.fog_sun_tint;
518                         } else {
519                                 pointcolor_sun_f.r = pointcolor_light * 1;
520                                 pointcolor_sun_f.b = pointcolor_light *
521                                         (0.25 + (rangelim(m_time_brightness, 0.25, 0.75) - 0.25) * 2 * 0.75);
522                                 pointcolor_sun_f.g = pointcolor_light * (pointcolor_sun_f.b * 0.375 +
523                                         (rangelim(m_time_brightness, 0.05, 0.15) - 0.05) * 10 * 0.625);
524                         }
525
526                         video::SColorf pointcolor_moon_f;
527                         if (m_default_tint) {
528                                 pointcolor_moon_f = video::SColorf(
529                                         0.5 * pointcolor_light,
530                                         0.6 * pointcolor_light,
531                                         0.8 * pointcolor_light,
532                                         1
533                                 );
534                         } else {
535                                 pointcolor_moon_f = video::SColorf(
536                                         (m_sky_params.fog_moon_tint.getRed() / 255) * pointcolor_light,
537                                         (m_sky_params.fog_moon_tint.getGreen() / 255) * pointcolor_light,
538                                         (m_sky_params.fog_moon_tint.getBlue() / 255) * pointcolor_light,
539                                         1
540                                 );
541                         }
542                         if (m_moon_tonemap && m_default_tint) {
543                                 pointcolor_moon_f.r = pointcolor_light *
544                                         (float)m_materials[4].EmissiveColor.getRed() / 255;
545                                 pointcolor_moon_f.b = pointcolor_light *
546                                         (float)m_materials[4].EmissiveColor.getBlue() / 255;
547                                 pointcolor_moon_f.g = pointcolor_light *
548                                         (float)m_materials[4].EmissiveColor.getGreen() / 255;
549                         }
550
551                         video::SColor pointcolor_sun = pointcolor_sun_f.toSColor();
552                         video::SColor pointcolor_moon = pointcolor_moon_f.toSColor();
553                         // Calculate the blend color
554                         pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun, pointcolor_blend);
555                 }
556                 m_bgcolor = m_mix_scolor(m_bgcolor, pointcolor, m_horizon_blend() * 0.5);
557                 m_skycolor = m_mix_scolor(m_skycolor, pointcolor, m_horizon_blend() * 0.25);
558         }
559
560         float cloud_direct_brightness = 0.0f;
561         if (sunlight_seen) {
562                 if (!m_directional_colored_fog) {
563                         cloud_direct_brightness = time_brightness;
564                         // Boost cloud brightness relative to sky, at dawn, dusk and at night
565                         if (time_brightness < 0.7f)
566                                 cloud_direct_brightness *= 1.3f;
567                 } else {
568                         cloud_direct_brightness = std::fmin(m_horizon_blend() * 0.15f +
569                                 m_time_brightness, 1.0f);
570                         // Set the same minimum cloud brightness at night
571                         if (time_brightness < 0.5f)
572                                 cloud_direct_brightness = std::fmax(cloud_direct_brightness,
573                                         time_brightness * 1.3f);
574                 }
575         } else {
576                 cloud_direct_brightness = direct_brightness;
577         }
578
579         m_cloud_brightness = m_cloud_brightness * cloud_color_change_fraction +
580                 cloud_direct_brightness * (1.0 - cloud_color_change_fraction);
581         m_cloudcolor_f = video::SColorf(
582                 m_cloudcolor_bright_f.r * m_cloud_brightness,
583                 m_cloudcolor_bright_f.g * m_cloud_brightness,
584                 m_cloudcolor_bright_f.b * m_cloud_brightness,
585                 1.0
586         );
587         if (m_directional_colored_fog) {
588                 m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f,
589                         video::SColorf(pointcolor), m_horizon_blend() * 0.25);
590         }
591 }
592
593 void Sky::draw_sun(video::IVideoDriver *driver, float sunsize, const video::SColor &suncolor,
594         const video::SColor &suncolor2, float wicked_time_of_day)
595         /* Draw sun in the sky.
596          * driver: Video driver object used to draw
597          * sunsize: the default size of the sun
598          * suncolor: main sun color
599          * suncolor2: second sun color
600          * wicked_time_of_day: current time of day, to know where should be the sun in the sky
601          */
602 {
603         static const u16 indices[] = {0, 1, 2, 0, 2, 3};
604         std::array<video::S3DVertex, 4> vertices;
605         if (!m_sun_texture) {
606                 driver->setMaterial(m_materials[1]);
607                 const float sunsizes[4] = {
608                         (sunsize * 1.7f) * m_sun_params.scale,
609                         (sunsize * 1.2f) * m_sun_params.scale,
610                         (sunsize) * m_sun_params.scale,
611                         (sunsize * 0.7f) * m_sun_params.scale
612                 };
613                 video::SColor c1 = suncolor;
614                 video::SColor c2 = suncolor;
615                 c1.setAlpha(0.05 * 255);
616                 c2.setAlpha(0.15 * 255);
617                 const video::SColor colors[4] = {c1, c2, suncolor, suncolor2};
618                 for (int i = 0; i < 4; i++) {
619                         draw_sky_body(vertices, -sunsizes[i], sunsizes[i], colors[i]);
620                         place_sky_body(vertices, 90, wicked_time_of_day * 360 - 90);
621                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
622                 }
623         } else {
624                 driver->setMaterial(m_materials[3]);
625                 float d = (sunsize * 1.7) * m_sun_params.scale;
626                 video::SColor c;
627                 if (m_sun_tonemap)
628                         c = video::SColor(0, 0, 0, 0);
629                 else
630                         c = video::SColor(255, 255, 255, 255);
631                 draw_sky_body(vertices, -d, d, c);
632                 place_sky_body(vertices, 90, wicked_time_of_day * 360 - 90);
633                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
634         }
635 }
636
637
638 void Sky::draw_moon(video::IVideoDriver *driver, float moonsize, const video::SColor &mooncolor,
639         const video::SColor &mooncolor2, float wicked_time_of_day)
640 /*
641         * Draw moon in the sky.
642         * driver: Video driver object used to draw
643         * moonsize: the default size of the moon
644         * mooncolor: main moon color
645         * mooncolor2: second moon color
646         * wicked_time_of_day: current time of day, to know where should be the moon in
647         * the sky
648         */
649 {
650         static const u16 indices[] = {0, 1, 2, 0, 2, 3};
651         std::array<video::S3DVertex, 4> vertices;
652         if (!m_moon_texture) {
653                 driver->setMaterial(m_materials[1]);
654                 const float moonsizes_1[4] = {
655                         (-moonsize * 1.9f) * m_moon_params.scale,
656                         (-moonsize * 1.3f) * m_moon_params.scale,
657                         (-moonsize) * m_moon_params.scale,
658                         (-moonsize) * m_moon_params.scale
659                 };
660                 const float moonsizes_2[4] = {
661                         (moonsize * 1.9f) * m_moon_params.scale,
662                         (moonsize * 1.3f) * m_moon_params.scale,
663                         (moonsize) *m_moon_params.scale,
664                         (moonsize * 0.6f) * m_moon_params.scale
665                 };
666                 video::SColor c1 = mooncolor;
667                 video::SColor c2 = mooncolor;
668                 c1.setAlpha(0.05 * 255);
669                 c2.setAlpha(0.15 * 255);
670                 const video::SColor colors[4] = {c1, c2, mooncolor, mooncolor2};
671                 for (int i = 0; i < 4; i++) {
672                         draw_sky_body(vertices, moonsizes_1[i], moonsizes_2[i], colors[i]);
673                         place_sky_body(vertices, -90, wicked_time_of_day * 360 - 90);
674                         driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
675                 }
676         } else {
677                 driver->setMaterial(m_materials[4]);
678                 float d = (moonsize * 1.9) * m_moon_params.scale;
679                 video::SColor c;
680                 if (m_moon_tonemap)
681                         c = video::SColor(0, 0, 0, 0);
682                 else
683                         c = video::SColor(255, 255, 255, 255);
684                 draw_sky_body(vertices, -d, d, c);
685                 place_sky_body(vertices, -90, wicked_time_of_day * 360 - 90);
686                 driver->drawIndexedTriangleList(&vertices[0], 4, indices, 2);
687         }
688 }
689
690 void Sky::draw_stars(video::IVideoDriver * driver, float wicked_time_of_day)
691 {
692         // Tune values so that stars first appear just after the sun
693         // disappears over the horizon, and disappear just before the sun
694         // appears over the horizon.
695         // Also tune so that stars are at full brightness from time 20000
696         // to time 4000.
697
698         float tod = wicked_time_of_day < 0.5f ? wicked_time_of_day : (1.0f - wicked_time_of_day);
699         float starbrightness = (0.25f - fabsf(tod)) * 20.0f;
700         m_star_color = m_star_params.starcolor;
701         m_star_color.a *= clamp(starbrightness, 0.0f, 1.0f);
702         if (m_star_color.a <= 0.0f) // Stars are only drawn when not fully transparent
703                 return;
704         m_materials[0].DiffuseColor = m_materials[0].EmissiveColor = m_star_color.toSColor();
705         auto sky_rotation = core::matrix4().setRotationAxisRadians(2.0f * M_PI * (wicked_time_of_day - 0.25f), v3f(0.0f, 0.0f, 1.0f));
706         auto world_matrix = driver->getTransform(video::ETS_WORLD);
707         driver->setTransform(video::ETS_WORLD, world_matrix * sky_rotation);
708         driver->setMaterial(m_materials[0]);
709         driver->drawMeshBuffer(m_stars.get());
710         driver->setTransform(video::ETS_WORLD, world_matrix);
711 }
712
713 void Sky::draw_sky_body(std::array<video::S3DVertex, 4> &vertices, float pos_1, float pos_2, const video::SColor &c)
714 {
715         /*
716         * Create an array of vertices with the dimensions specified.
717         * pos_1, pos_2: position of the body's vertices
718         * c: color of the body
719         */
720
721         const f32 t = 1.0f;
722         const f32 o = 0.0f;
723         vertices[0] = video::S3DVertex(pos_1, pos_1, -1, 0, 0, 1, c, t, t);
724         vertices[1] = video::S3DVertex(pos_2, pos_1, -1, 0, 0, 1, c, o, t);
725         vertices[2] = video::S3DVertex(pos_2, pos_2, -1, 0, 0, 1, c, o, o);
726         vertices[3] = video::S3DVertex(pos_1, pos_2, -1, 0, 0, 1, c, t, o);
727 }
728
729
730 void Sky::place_sky_body(
731         std::array<video::S3DVertex, 4> &vertices, float horizon_position, float day_position)
732         /*
733         * Place body in the sky.
734         * vertices: The body as a rectangle of 4 vertices
735         * horizon_position: turn the body around the Y axis
736         * day_position: turn the body around the Z axis, to place it depending of the time of the day
737         */
738 {
739         for (video::S3DVertex &vertex : vertices) {
740                 // Body is directed to -Z (south) by default
741                 vertex.Pos.rotateXZBy(horizon_position);
742                 vertex.Pos.rotateXYBy(day_position);
743         }
744 }
745
746 void Sky::setSunTexture(std::string sun_texture,
747                 std::string sun_tonemap, ITextureSource *tsrc)
748 {
749         // Ignore matching textures (with modifiers) entirely,
750         // but lets at least update the tonemap before hand.
751         m_sun_params.tonemap = sun_tonemap;
752         m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ?
753                 tsrc->getTexture(m_sun_params.tonemap) : NULL;
754         m_materials[3].Lighting = !!m_sun_tonemap;
755
756         if (m_sun_params.texture == sun_texture)
757                 return;
758         m_sun_params.texture = sun_texture;
759
760         if (sun_texture != "") {
761                 // We want to ensure the texture exists first.
762                 m_sun_texture = tsrc->getTextureForMesh(m_sun_params.texture);
763
764                 if (m_sun_texture) {
765                         m_materials[3] = baseMaterial();
766                         m_materials[3].setTexture(0, m_sun_texture);
767                         m_materials[3].MaterialType = video::
768                                 EMT_TRANSPARENT_ALPHA_CHANNEL;
769                         // Disables texture filtering
770                         m_materials[3].setFlag(
771                                 video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
772                         m_materials[3].setFlag(
773                                 video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
774                         m_materials[3].setFlag(
775                                 video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
776                 }
777         } else {
778                 m_sun_texture = nullptr;
779         }
780 }
781
782 void Sky::setSunriseTexture(std::string sunglow_texture,
783                 ITextureSource* tsrc)
784 {
785         // Ignore matching textures (with modifiers) entirely.
786         if (m_sun_params.sunrise == sunglow_texture)
787                 return;
788         m_sun_params.sunrise = sunglow_texture;
789         m_materials[2].setTexture(0, tsrc->getTextureForMesh(
790                 sunglow_texture.empty() ? "sunrisebg.png" : sunglow_texture)
791         );
792 }
793
794 void Sky::setMoonTexture(std::string moon_texture,
795                 std::string moon_tonemap, ITextureSource *tsrc)
796 {
797         // Ignore matching textures (with modifiers) entirely,
798         // but lets at least update the tonemap before hand.
799         m_moon_params.tonemap = moon_tonemap;
800         m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ?
801                 tsrc->getTexture(m_moon_params.tonemap) : NULL;
802         m_materials[4].Lighting = !!m_moon_tonemap;
803
804         if (m_moon_params.texture == moon_texture)
805                 return;
806         m_moon_params.texture = moon_texture;
807
808         if (moon_texture != "") {
809                 // We want to ensure the texture exists first.
810                 m_moon_texture = tsrc->getTextureForMesh(m_moon_params.texture);
811
812                 if (m_moon_texture) {
813                         m_materials[4] = baseMaterial();
814                         m_materials[4].setTexture(0, m_moon_texture);
815                         m_materials[4].MaterialType = video::
816                                 EMT_TRANSPARENT_ALPHA_CHANNEL;
817                         // Disables texture filtering
818                         m_materials[4].setFlag(
819                                 video::E_MATERIAL_FLAG::EMF_BILINEAR_FILTER, false);
820                         m_materials[4].setFlag(
821                                 video::E_MATERIAL_FLAG::EMF_TRILINEAR_FILTER, false);
822                         m_materials[4].setFlag(
823                                 video::E_MATERIAL_FLAG::EMF_ANISOTROPIC_FILTER, false);
824                 }
825         } else {
826                 m_moon_texture = nullptr;
827         }
828 }
829
830 void Sky::setStarCount(u16 star_count, bool force_update)
831 {
832         // Allow force updating star count at game init.
833         if (m_star_params.count != star_count || force_update) {
834                 m_star_params.count = star_count;
835                 m_seed = (u64)myrand() << 32 | myrand();
836                 updateStars();
837         }
838 }
839
840 void Sky::updateStars()
841 {
842         m_stars.reset(new scene::SMeshBuffer());
843         // Stupid IrrLicht doesn’t allow non-indexed rendering, and indexed quad
844         // rendering is slow due to lack of hardware support. So as indices are
845         // 16-bit and there are 4 vertices per star... the limit is 2^16/4 = 0x4000.
846         // That should be well enough actually.
847         if (m_star_params.count > 0x4000) {
848                 warningstream << "Requested " << m_star_params.count << " stars but " << 0x4000 << " is the max\n";
849                 m_star_params.count = 0x4000;
850         }
851         m_stars->Vertices.reallocate(4 * m_star_params.count);
852         m_stars->Indices.reallocate(6 * m_star_params.count);
853
854         video::SColor fallback_color = m_star_params.starcolor; // used on GLES 2 “without shaders”
855         PcgRandom rgen(m_seed);
856         float d = (0.006 / 2) * m_star_params.scale;
857         for (u16 i = 0; i < m_star_params.count; i++) {
858                 v3f r = v3f(
859                         rgen.range(-10000, 10000),
860                         rgen.range(-10000, 10000),
861                         rgen.range(-10000, 10000)
862                 );
863                 core::CMatrix4<f32> a;
864                 a.buildRotateFromTo(v3f(0, 1, 0), r);
865                 v3f p = v3f(-d, 1, -d);
866                 v3f p1 = v3f(d, 1, -d);
867                 v3f p2 = v3f(d, 1, d);
868                 v3f p3 = v3f(-d, 1, d);
869                 a.rotateVect(p);
870                 a.rotateVect(p1);
871                 a.rotateVect(p2);
872                 a.rotateVect(p3);
873                 m_stars->Vertices.push_back(video::S3DVertex(p, {}, fallback_color, {}));
874                 m_stars->Vertices.push_back(video::S3DVertex(p1, {}, fallback_color, {}));
875                 m_stars->Vertices.push_back(video::S3DVertex(p2, {}, fallback_color, {}));
876                 m_stars->Vertices.push_back(video::S3DVertex(p3, {}, fallback_color, {}));
877         }
878         for (u16 i = 0; i < m_star_params.count; i++) {
879                 m_stars->Indices.push_back(i * 4 + 0);
880                 m_stars->Indices.push_back(i * 4 + 1);
881                 m_stars->Indices.push_back(i * 4 + 2);
882                 m_stars->Indices.push_back(i * 4 + 2);
883                 m_stars->Indices.push_back(i * 4 + 3);
884                 m_stars->Indices.push_back(i * 4 + 0);
885         }
886         m_stars->setHardwareMappingHint(scene::EHM_STATIC);
887 }
888
889 void Sky::setSkyColors(const SkyColor &sky_color)
890 {
891         m_sky_params.sky_color = sky_color;
892 }
893
894 void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint,
895                 std::string use_sun_tint)
896 {
897         // Change sun and moon tinting:
898         m_sky_params.fog_sun_tint = sun_tint;
899         m_sky_params.fog_moon_tint = moon_tint;
900         // Faster than comparing strings every rendering frame
901         if (use_sun_tint == "default")
902                 m_default_tint = true;
903         else if (use_sun_tint == "custom")
904                 m_default_tint = false;
905         else
906                 m_default_tint = true;
907 }
908
909 void Sky::addTextureToSkybox(std::string texture, int material_id,
910                 ITextureSource *tsrc)
911 {
912         // Sanity check for more than six textures.
913         if (material_id + 5 >= SKY_MATERIAL_COUNT)
914                 return;
915         // Keep a list of texture names handy.
916         m_sky_params.textures.emplace_back(texture);
917         video::ITexture *result = tsrc->getTextureForMesh(texture);
918         m_materials[material_id+5] = baseMaterial();
919         m_materials[material_id+5].setTexture(0, result);
920         m_materials[material_id+5].MaterialType = video::EMT_SOLID;
921 }
922
923 // To be called once at game init to setup default values.
924 void Sky::setSkyDefaults()
925 {
926         SkyboxDefaults sky_defaults;
927         m_sky_params.sky_color = sky_defaults.getSkyColorDefaults();
928         m_sun_params = sky_defaults.getSunDefaults();
929         m_moon_params = sky_defaults.getMoonDefaults();
930         m_star_params = sky_defaults.getStarDefaults();
931 }