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