]> git.lizzy.rs Git - minetest.git/blob - src/client/clientmap.cpp
Improvements to colored shadows (#11516)
[minetest.git] / src / client / clientmap.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-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 "clientmap.h"
21 #include "client.h"
22 #include "mapblock_mesh.h"
23 #include <IMaterialRenderer.h>
24 #include <matrix4.h>
25 #include "mapsector.h"
26 #include "mapblock.h"
27 #include "profiler.h"
28 #include "settings.h"
29 #include "camera.h"               // CameraModes
30 #include "util/basic_macros.h"
31 #include <algorithm>
32 #include "client/renderingengine.h"
33
34 // struct MeshBufListList
35 void MeshBufListList::clear()
36 {
37         for (auto &list : lists)
38                 list.clear();
39 }
40
41 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
42 {
43         // Append to the correct layer
44         std::vector<MeshBufList> &list = lists[layer];
45         const video::SMaterial &m = buf->getMaterial();
46         for (MeshBufList &l : list) {
47                 // comparing a full material is quite expensive so we don't do it if
48                 // not even first texture is equal
49                 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
50                         continue;
51
52                 if (l.m == m) {
53                         l.bufs.emplace_back(position, buf);
54                         return;
55                 }
56         }
57         MeshBufList l;
58         l.m = m;
59         l.bufs.emplace_back(position, buf);
60         list.emplace_back(l);
61 }
62
63 // ClientMap
64
65 ClientMap::ClientMap(
66                 Client *client,
67                 RenderingEngine *rendering_engine,
68                 MapDrawControl &control,
69                 s32 id
70 ):
71         Map(client),
72         scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
73                 rendering_engine->get_scene_manager(), id),
74         m_client(client),
75         m_rendering_engine(rendering_engine),
76         m_control(control),
77         m_drawlist(MapBlockComparer(v3s16(0,0,0)))
78 {
79
80         /*
81          * @Liso: Sadly C++ doesn't have introspection, so the only way we have to know
82          * the class is whith a name ;) Name property cames from ISceneNode base class.
83          */
84         Name = "ClientMap";
85         m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
86                         BS*1000000,BS*1000000,BS*1000000);
87
88         /* TODO: Add a callback function so these can be updated when a setting
89          *       changes.  At this point in time it doesn't matter (e.g. /set
90          *       is documented to change server settings only)
91          *
92          * TODO: Local caching of settings is not optimal and should at some stage
93          *       be updated to use a global settings object for getting thse values
94          *       (as opposed to the this local caching). This can be addressed in
95          *       a later release.
96          */
97         m_cache_trilinear_filter  = g_settings->getBool("trilinear_filter");
98         m_cache_bilinear_filter   = g_settings->getBool("bilinear_filter");
99         m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
100
101 }
102
103 MapSector * ClientMap::emergeSector(v2s16 p2d)
104 {
105         // Check that it doesn't exist already
106         MapSector *sector = getSectorNoGenerate(p2d);
107
108         // Create it if it does not exist yet
109         if (!sector) {
110                 sector = new MapSector(this, p2d, m_gamedef);
111                 m_sectors[p2d] = sector;
112         }
113
114         return sector;
115 }
116
117 void ClientMap::OnRegisterSceneNode()
118 {
119         if(IsVisible)
120         {
121                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
122                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
123         }
124
125         ISceneNode::OnRegisterSceneNode();
126
127         if (!m_added_to_shadow_renderer) {
128                 m_added_to_shadow_renderer = true;
129                 if (auto shadows = m_rendering_engine->get_shadow_renderer())
130                         shadows->addNodeToShadowList(this);
131         }
132 }
133
134 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
135                 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
136 {
137         if (range <= 0.0f)
138                 range = m_control.wanted_range;
139
140         v3s16 box_nodes_d = range * v3s16(1, 1, 1);
141         // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
142         // can exceed the range of v3s16 when a large view range is used near the
143         // world edges.
144         v3s32 p_nodes_min(
145                 cam_pos_nodes.X - box_nodes_d.X,
146                 cam_pos_nodes.Y - box_nodes_d.Y,
147                 cam_pos_nodes.Z - box_nodes_d.Z);
148         v3s32 p_nodes_max(
149                 cam_pos_nodes.X + box_nodes_d.X,
150                 cam_pos_nodes.Y + box_nodes_d.Y,
151                 cam_pos_nodes.Z + box_nodes_d.Z);
152         // Take a fair amount as we will be dropping more out later
153         // Umm... these additions are a bit strange but they are needed.
154         *p_blocks_min = v3s16(
155                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
156                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
157                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
158         *p_blocks_max = v3s16(
159                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
160                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
161                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
162 }
163
164 void ClientMap::updateDrawList()
165 {
166         ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
167
168         m_needs_update_drawlist = false;
169
170         for (auto &i : m_drawlist) {
171                 MapBlock *block = i.second;
172                 block->refDrop();
173         }
174         m_drawlist.clear();
175
176         const v3f camera_position = m_camera_position;
177         const v3f camera_direction = m_camera_direction;
178
179         // Use a higher fov to accomodate faster camera movements.
180         // Blocks are cropped better when they are drawn.
181         const f32 camera_fov = m_camera_fov * 1.1f;
182
183         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
184
185         v3s16 p_blocks_min;
186         v3s16 p_blocks_max;
187         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
188
189         // Read the vision range, unless unlimited range is enabled.
190         float range = m_control.range_all ? 1e7 : m_control.wanted_range;
191
192         // Number of blocks currently loaded by the client
193         u32 blocks_loaded = 0;
194         // Number of blocks with mesh in rendering range
195         u32 blocks_in_range_with_mesh = 0;
196         // Number of blocks occlusion culled
197         u32 blocks_occlusion_culled = 0;
198
199         // No occlusion culling when free_move is on and camera is
200         // inside ground
201         bool occlusion_culling_enabled = true;
202         if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
203                 MapNode n = getNode(cam_pos_nodes);
204                 if (n.getContent() == CONTENT_IGNORE ||
205                                 m_nodedef->get(n).solidness == 2)
206                         occlusion_culling_enabled = false;
207         }
208
209         v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
210         m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
211
212         // Uncomment to debug occluded blocks in the wireframe mode
213         // TODO: Include this as a flag for an extended debugging setting
214         //if (occlusion_culling_enabled && m_control.show_wireframe)
215         //    occlusion_culling_enabled = porting::getTimeS() & 1;
216
217         for (const auto &sector_it : m_sectors) {
218                 MapSector *sector = sector_it.second;
219                 v2s16 sp = sector->getPos();
220
221                 blocks_loaded += sector->size();
222                 if (!m_control.range_all) {
223                         if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
224                                         sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
225                                 continue;
226                 }
227
228                 MapBlockVect sectorblocks;
229                 sector->getBlocks(sectorblocks);
230
231                 /*
232                         Loop through blocks in sector
233                 */
234
235                 u32 sector_blocks_drawn = 0;
236
237                 for (MapBlock *block : sectorblocks) {
238                         /*
239                                 Compare block position to camera position, skip
240                                 if not seen on display
241                         */
242
243                         if (!block->mesh) {
244                                 // Ignore if mesh doesn't exist
245                                 continue;
246                         }
247
248                         v3s16 block_coord = block->getPos();
249                         v3s16 block_position = block->getPosRelative() + MAP_BLOCKSIZE / 2;
250
251                         // First, perform a simple distance check, with a padding of one extra block.
252                         if (!m_control.range_all &&
253                                         block_position.getDistanceFrom(cam_pos_nodes) > range + MAP_BLOCKSIZE)
254                                 continue; // Out of range, skip.
255
256                         // Keep the block alive as long as it is in range.
257                         block->resetUsageTimer();
258                         blocks_in_range_with_mesh++;
259
260                         // Frustum culling
261                         float d = 0.0;
262                         if (!isBlockInSight(block_coord, camera_position,
263                                         camera_direction, camera_fov, range * BS, &d))
264                                 continue;
265
266                         // Occlusion culling
267                         if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
268                                         (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
269                                 blocks_occlusion_culled++;
270                                 continue;
271                         }
272
273                         // Add to set
274                         block->refGrab();
275                         m_drawlist[block_coord] = block;
276
277                         sector_blocks_drawn++;
278                 } // foreach sectorblocks
279
280                 if (sector_blocks_drawn != 0)
281                         m_last_drawn_sectors.insert(sp);
282         }
283
284         g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
285         g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
286         g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
287         g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
288 }
289
290 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
291 {
292         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
293
294         std::string prefix;
295         if (pass == scene::ESNRP_SOLID)
296                 prefix = "renderMap(SOLID): ";
297         else
298                 prefix = "renderMap(TRANSPARENT): ";
299
300         /*
301                 This is called two times per frame, reset on the non-transparent one
302         */
303         if (pass == scene::ESNRP_SOLID)
304                 m_last_drawn_sectors.clear();
305
306         /*
307                 Get animation parameters
308         */
309         const float animation_time = m_client->getAnimationTime();
310         const int crack = m_client->getCrackLevel();
311         const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
312
313         const v3f camera_position = m_camera_position;
314
315         /*
316                 Get all blocks and draw all visible ones
317         */
318
319         u32 vertex_count = 0;
320         u32 drawcall_count = 0;
321
322         // For limiting number of mesh animations per frame
323         u32 mesh_animate_count = 0;
324         //u32 mesh_animate_count_far = 0;
325
326         /*
327                 Draw the selected MapBlocks
328         */
329
330         MeshBufListList grouped_buffers;
331
332         struct DrawDescriptor {
333                 v3s16 m_pos;
334                 scene::IMeshBuffer *m_buffer;
335                 bool m_reuse_material;
336
337                 DrawDescriptor(const v3s16 &pos, scene::IMeshBuffer *buffer, bool reuse_material) :
338                         m_pos(pos), m_buffer(buffer), m_reuse_material(reuse_material)
339                 {}
340         };
341
342         std::vector<DrawDescriptor> draw_order;
343         video::SMaterial previous_material;
344
345         for (auto &i : m_drawlist) {
346                 v3s16 block_pos = i.first;
347                 MapBlock *block = i.second;
348
349                 // If the mesh of the block happened to get deleted, ignore it
350                 if (!block->mesh)
351                         continue;
352
353                 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
354                 float d = camera_position.getDistanceFrom(block_pos_r);
355                 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
356
357                 // Mesh animation
358                 if (pass == scene::ESNRP_SOLID) {
359                         MapBlockMesh *mapBlockMesh = block->mesh;
360                         assert(mapBlockMesh);
361                         // Pretty random but this should work somewhat nicely
362                         bool faraway = d >= BS * 50;
363                         if (mapBlockMesh->isAnimationForced() || !faraway ||
364                                         mesh_animate_count < (m_control.range_all ? 200 : 50)) {
365
366                                 bool animated = mapBlockMesh->animate(faraway, animation_time,
367                                         crack, daynight_ratio);
368                                 if (animated)
369                                         mesh_animate_count++;
370                         } else {
371                                 mapBlockMesh->decreaseAnimationForceTimer();
372                         }
373                 }
374
375                 /*
376                         Get the meshbuffers of the block
377                 */
378                 {
379                         MapBlockMesh *mapBlockMesh = block->mesh;
380                         assert(mapBlockMesh);
381
382                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
383                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
384                                 assert(mesh);
385
386                                 u32 c = mesh->getMeshBufferCount();
387                                 for (u32 i = 0; i < c; i++) {
388                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
389
390                                         video::SMaterial& material = buf->getMaterial();
391                                         video::IMaterialRenderer* rnd =
392                                                 driver->getMaterialRenderer(material.MaterialType);
393                                         bool transparent = (rnd && rnd->isTransparent());
394                                         if (transparent == is_transparent_pass) {
395                                                 if (buf->getVertexCount() == 0)
396                                                         errorstream << "Block [" << analyze_block(block)
397                                                                 << "] contains an empty meshbuf" << std::endl;
398
399                                                 material.setFlag(video::EMF_TRILINEAR_FILTER,
400                                                         m_cache_trilinear_filter);
401                                                 material.setFlag(video::EMF_BILINEAR_FILTER,
402                                                         m_cache_bilinear_filter);
403                                                 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
404                                                         m_cache_anistropic_filter);
405                                                 material.setFlag(video::EMF_WIREFRAME,
406                                                         m_control.show_wireframe);
407
408                                                 if (is_transparent_pass) {
409                                                         // Same comparison as in MeshBufListList
410                                                         bool new_material = material.getTexture(0) != previous_material.getTexture(0) ||
411                                                                         material != previous_material;
412
413                                                         draw_order.emplace_back(block_pos, buf, !new_material);
414
415                                                         if (new_material)
416                                                                 previous_material = material;
417                                                 }
418                                                 else {
419                                                         grouped_buffers.add(buf, block_pos, layer);
420                                                 }
421                                         }
422                                 }
423                         }
424                 }
425         }
426
427         // Capture draw order for all solid meshes
428         for (auto &lists : grouped_buffers.lists) {
429                 for (MeshBufList &list : lists) {
430                         // iterate in reverse to draw closest blocks first
431                         for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
432                                 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
433                         }
434                 }
435         }
436
437         TimeTaker draw("Drawing mesh buffers");
438
439         core::matrix4 m; // Model matrix
440         v3f offset = intToFloat(m_camera_offset, BS);
441         u32 material_swaps = 0;
442
443         // Render all mesh buffers in order
444         drawcall_count += draw_order.size();
445         for (auto &descriptor : draw_order) {
446                 scene::IMeshBuffer *buf = descriptor.m_buffer;
447
448                 // Check and abort if the machine is swapping a lot
449                 if (draw.getTimerTime() > 2000) {
450                         infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
451                                         "returning." << std::endl;
452                         return;
453                 }
454
455                 if (!descriptor.m_reuse_material) {
456                         auto &material = buf->getMaterial();
457                         // pass the shadow map texture to the buffer texture
458                         ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
459                         if (shadow && shadow->is_active()) {
460                                 auto &layer = material.TextureLayer[3];
461                                 layer.Texture = shadow->get_texture();
462                                 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
463                                 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
464                                 // Do not enable filter on shadow texture to avoid visual artifacts
465                                 // with colored shadows.
466                                 // Filtering is done in shader code anyway
467                                 layer.TrilinearFilter = false;
468                         }
469                         driver->setMaterial(material);
470                         ++material_swaps;
471                 }
472
473                 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
474                 m.setTranslation(block_wpos - offset);
475
476                 driver->setTransform(video::ETS_WORLD, m);
477                 driver->drawMeshBuffer(buf);
478                 vertex_count += buf->getVertexCount();
479         }
480
481         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
482
483         // Log only on solid pass because values are the same
484         if (pass == scene::ESNRP_SOLID) {
485                 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
486         }
487
488         if (pass == scene::ESNRP_TRANSPARENT) {
489                 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
490         }
491
492         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
493         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
494         g_profiler->avg(prefix + "material swaps [#]", material_swaps);
495 }
496
497 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
498         float step_multiplier, float start_distance, float end_distance,
499         const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
500         int *result, bool *sunlight_seen)
501 {
502         int brightness_sum = 0;
503         int brightness_count = 0;
504         float distance = start_distance;
505         dir.normalize();
506         v3f pf = p0;
507         pf += dir * distance;
508         int noncount = 0;
509         bool nonlight_seen = false;
510         bool allow_allowing_non_sunlight_propagates = false;
511         bool allow_non_sunlight_propagates = false;
512         // Check content nearly at camera position
513         {
514                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
515                 MapNode n = map->getNode(p);
516                 if(ndef->get(n).param_type == CPT_LIGHT &&
517                                 !ndef->get(n).sunlight_propagates)
518                         allow_allowing_non_sunlight_propagates = true;
519         }
520         // If would start at CONTENT_IGNORE, start closer
521         {
522                 v3s16 p = floatToInt(pf, BS);
523                 MapNode n = map->getNode(p);
524                 if(n.getContent() == CONTENT_IGNORE){
525                         float newd = 2*BS;
526                         pf = p0 + dir * 2*newd;
527                         distance = newd;
528                         sunlight_min_d = 0;
529                 }
530         }
531         for (int i=0; distance < end_distance; i++) {
532                 pf += dir * step;
533                 distance += step;
534                 step *= step_multiplier;
535
536                 v3s16 p = floatToInt(pf, BS);
537                 MapNode n = map->getNode(p);
538                 if (allow_allowing_non_sunlight_propagates && i == 0 &&
539                                 ndef->get(n).param_type == CPT_LIGHT &&
540                                 !ndef->get(n).sunlight_propagates) {
541                         allow_non_sunlight_propagates = true;
542                 }
543
544                 if (ndef->get(n).param_type != CPT_LIGHT ||
545                                 (!ndef->get(n).sunlight_propagates &&
546                                         !allow_non_sunlight_propagates)){
547                         nonlight_seen = true;
548                         noncount++;
549                         if(noncount >= 4)
550                                 break;
551                         continue;
552                 }
553
554                 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
555                         if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
556                                 *sunlight_seen = true;
557                 noncount = 0;
558                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
559                 brightness_count++;
560         }
561         *result = 0;
562         if(brightness_count == 0)
563                 return false;
564         *result = brightness_sum / brightness_count;
565         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
566                         <<(*result)<<std::endl;*/
567         return true;
568 }
569
570 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
571                 int oldvalue, bool *sunlight_seen_result)
572 {
573         ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
574         static v3f z_directions[50] = {
575                 v3f(-100, 0, 0)
576         };
577         static f32 z_offsets[50] = {
578                 -1000,
579         };
580
581         if (z_directions[0].X < -99) {
582                 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
583                         // Assumes FOV of 72 and 16/9 aspect ratio
584                         z_directions[i] = v3f(
585                                 0.02 * myrand_range(-100, 100),
586                                 1.0,
587                                 0.01 * myrand_range(-100, 100)
588                         ).normalize();
589                         z_offsets[i] = 0.01 * myrand_range(0,100);
590                 }
591         }
592
593         int sunlight_seen_count = 0;
594         float sunlight_min_d = max_d*0.8;
595         if(sunlight_min_d > 35*BS)
596                 sunlight_min_d = 35*BS;
597         std::vector<int> values;
598         values.reserve(ARRLEN(z_directions));
599         for (u32 i = 0; i < ARRLEN(z_directions); i++) {
600                 v3f z_dir = z_directions[i];
601                 core::CMatrix4<f32> a;
602                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
603                 v3f dir = m_camera_direction;
604                 a.rotateVect(dir);
605                 int br = 0;
606                 float step = BS*1.5;
607                 if(max_d > 35*BS)
608                         step = max_d / 35 * 1.5;
609                 float off = step * z_offsets[i];
610                 bool sunlight_seen_now = false;
611                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
612                                 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
613                                 sunlight_min_d,
614                                 &br, &sunlight_seen_now);
615                 if(sunlight_seen_now)
616                         sunlight_seen_count++;
617                 if(!ok)
618                         continue;
619                 values.push_back(br);
620                 // Don't try too much if being in the sun is clear
621                 if(sunlight_seen_count >= 20)
622                         break;
623         }
624         int brightness_sum = 0;
625         int brightness_count = 0;
626         std::sort(values.begin(), values.end());
627         u32 num_values_to_use = values.size();
628         if(num_values_to_use >= 10)
629                 num_values_to_use -= num_values_to_use/2;
630         else if(num_values_to_use >= 7)
631                 num_values_to_use -= num_values_to_use/3;
632         u32 first_value_i = (values.size() - num_values_to_use) / 2;
633
634         for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
635                 brightness_sum += values[i];
636                 brightness_count++;
637         }
638
639         int ret = 0;
640         if(brightness_count == 0){
641                 MapNode n = getNode(floatToInt(m_camera_position, BS));
642                 if(m_nodedef->get(n).param_type == CPT_LIGHT){
643                         ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
644                 } else {
645                         ret = oldvalue;
646                 }
647         } else {
648                 ret = brightness_sum / brightness_count;
649         }
650
651         *sunlight_seen_result = (sunlight_seen_count > 0);
652         return ret;
653 }
654
655 void ClientMap::renderPostFx(CameraMode cam_mode)
656 {
657         // Sadly ISceneManager has no "post effects" render pass, in that case we
658         // could just register for that and handle it in renderMap().
659
660         MapNode n = getNode(floatToInt(m_camera_position, BS));
661
662         // - If the player is in a solid node, make everything black.
663         // - If the player is in liquid, draw a semi-transparent overlay.
664         // - Do not if player is in third person mode
665         const ContentFeatures& features = m_nodedef->get(n);
666         video::SColor post_effect_color = features.post_effect_color;
667         if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
668                         m_client->checkLocalPrivilege("noclip")) &&
669                         cam_mode == CAMERA_MODE_FIRST)
670         {
671                 post_effect_color = video::SColor(255, 0, 0, 0);
672         }
673         if (post_effect_color.getAlpha() != 0)
674         {
675                 // Draw a full-screen rectangle
676                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
677                 v2u32 ss = driver->getScreenSize();
678                 core::rect<s32> rect(0,0, ss.X, ss.Y);
679                 driver->draw2DRectangle(post_effect_color, rect);
680         }
681 }
682
683 void ClientMap::PrintInfo(std::ostream &out)
684 {
685         out<<"ClientMap: ";
686 }
687
688 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
689                 const video::SMaterial &material, s32 pass, int frame, int total_frames)
690 {
691         bool is_transparent_pass = pass != scene::ESNRP_SOLID;
692         std::string prefix;
693         if (is_transparent_pass)
694                 prefix = "renderMap(SHADOW TRANS): ";
695         else
696                 prefix = "renderMap(SHADOW SOLID): ";
697
698         u32 drawcall_count = 0;
699         u32 vertex_count = 0;
700
701         MeshBufListList drawbufs;
702
703         int count = 0;
704         int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
705         int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
706
707         // transparent pass should be rendered in one go
708         if (is_transparent_pass && frame != total_frames - 1) {
709                 return;
710         }
711
712         for (auto &i : m_drawlist_shadow) {
713                 // only process specific part of the list & break early
714                 ++count;
715                 if (count <= low_bound)
716                         continue;
717                 if (count > high_bound)
718                         break;
719
720                 v3s16 block_pos = i.first;
721                 MapBlock *block = i.second;
722
723                 // If the mesh of the block happened to get deleted, ignore it
724                 if (!block->mesh)
725                         continue;
726
727                 /*
728                         Get the meshbuffers of the block
729                 */
730                 {
731                         MapBlockMesh *mapBlockMesh = block->mesh;
732                         assert(mapBlockMesh);
733
734                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
735                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
736                                 assert(mesh);
737
738                                 u32 c = mesh->getMeshBufferCount();
739                                 for (u32 i = 0; i < c; i++) {
740                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
741
742                                         video::SMaterial &mat = buf->getMaterial();
743                                         auto rnd = driver->getMaterialRenderer(mat.MaterialType);
744                                         bool transparent = rnd && rnd->isTransparent();
745                                         if (transparent == is_transparent_pass)
746                                                 drawbufs.add(buf, block_pos, layer);
747                                 }
748                         }
749                 }
750         }
751
752         TimeTaker draw("Drawing shadow mesh buffers");
753
754         core::matrix4 m; // Model matrix
755         v3f offset = intToFloat(m_camera_offset, BS);
756
757         // Render all layers in order
758         for (auto &lists : drawbufs.lists) {
759                 for (MeshBufList &list : lists) {
760                         // Check and abort if the machine is swapping a lot
761                         if (draw.getTimerTime() > 1000) {
762                                 infostream << "ClientMap::renderMapShadows(): Rendering "
763                                                 "took >1s, returning." << std::endl;
764                                 break;
765                         }
766                         for (auto &pair : list.bufs) {
767                                 scene::IMeshBuffer *buf = pair.second;
768
769                                 // override some material properties
770                                 video::SMaterial local_material = buf->getMaterial();
771                                 local_material.MaterialType = material.MaterialType;
772                                 local_material.BackfaceCulling = material.BackfaceCulling;
773                                 local_material.FrontfaceCulling = material.FrontfaceCulling;
774                                 local_material.BlendOperation = material.BlendOperation;
775                                 local_material.Lighting = false;
776                                 driver->setMaterial(local_material);
777
778                                 v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS);
779                                 m.setTranslation(block_wpos - offset);
780
781                                 driver->setTransform(video::ETS_WORLD, m);
782                                 driver->drawMeshBuffer(buf);
783                                 vertex_count += buf->getVertexCount();
784                         }
785
786                         drawcall_count += list.bufs.size();
787                 }
788         }
789
790         // restore the driver material state 
791         video::SMaterial clean;
792         clean.BlendOperation = video::EBO_ADD;
793         driver->setMaterial(clean); // reset material to defaults
794         driver->draw3DLine(v3f(), v3f(), video::SColor(0));
795         
796         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
797         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
798         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
799 }
800
801 /*
802         Custom update draw list for the pov of shadow light.
803 */
804 void ClientMap::updateDrawListShadow(const v3f &shadow_light_pos, const v3f &shadow_light_dir, float shadow_range)
805 {
806         ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
807
808         const v3f camera_position = shadow_light_pos;
809         const v3f camera_direction = shadow_light_dir;
810         // I "fake" fov just to avoid creating a new function to handle orthographic
811         // projection.
812         const f32 camera_fov = m_camera_fov * 1.9f;
813
814         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
815         v3s16 p_blocks_min;
816         v3s16 p_blocks_max;
817         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, shadow_range);
818
819         std::vector<v2s16> blocks_in_range;
820
821         for (auto &i : m_drawlist_shadow) {
822                 MapBlock *block = i.second;
823                 block->refDrop();
824         }
825         m_drawlist_shadow.clear();
826
827         // We need to append the blocks from the camera POV because sometimes
828         // they are not inside the light frustum and it creates glitches.
829         // FIXME: This could be removed if we figure out why they are missing
830         // from the light frustum.
831         for (auto &i : m_drawlist) {
832                 i.second->refGrab();
833                 m_drawlist_shadow[i.first] = i.second;
834         }
835
836         // Number of blocks currently loaded by the client
837         u32 blocks_loaded = 0;
838         // Number of blocks with mesh in rendering range
839         u32 blocks_in_range_with_mesh = 0;
840         // Number of blocks occlusion culled
841         u32 blocks_occlusion_culled = 0;
842
843         for (auto &sector_it : m_sectors) {
844                 MapSector *sector = sector_it.second;
845                 if (!sector)
846                         continue;
847                 blocks_loaded += sector->size();
848
849                 MapBlockVect sectorblocks;
850                 sector->getBlocks(sectorblocks);
851
852                 /*
853                         Loop through blocks in sector
854                 */
855                 for (MapBlock *block : sectorblocks) {
856                         if (!block->mesh) {
857                                 // Ignore if mesh doesn't exist
858                                 continue;
859                         }
860
861                         float range = shadow_range;
862
863                         float d = 0.0;
864                         if (!isBlockInSight(block->getPos(), camera_position,
865                                             camera_direction, camera_fov, range, &d))
866                                 continue;
867
868                         blocks_in_range_with_mesh++;
869
870                         /*
871                                 Occlusion culling
872                         */
873                         if (isBlockOccluded(block, cam_pos_nodes)) {
874                                 blocks_occlusion_culled++;
875                                 continue;
876                         }
877
878                         // This block is in range. Reset usage timer.
879                         block->resetUsageTimer();
880
881                         // Add to set
882                         if (m_drawlist_shadow.find(block->getPos()) == m_drawlist_shadow.end()) {
883                                 block->refGrab();
884                                 m_drawlist_shadow[block->getPos()] = block;
885                         }
886                 }
887         }
888
889         g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
890         g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
891         g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
892         g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
893 }