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