]> git.lizzy.rs Git - minetest.git/blob - src/client/clientmap.cpp
Occlusion culling algorithm based on recursive descend (#13104)
[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 "client/renderingengine.h"
32
33 #include <queue>
34
35 // struct MeshBufListList
36 void MeshBufListList::clear()
37 {
38         for (auto &list : lists)
39                 list.clear();
40 }
41
42 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
43 {
44         // Append to the correct layer
45         std::vector<MeshBufList> &list = lists[layer];
46         const video::SMaterial &m = buf->getMaterial();
47         for (MeshBufList &l : list) {
48                 // comparing a full material is quite expensive so we don't do it if
49                 // not even first texture is equal
50                 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
51                         continue;
52
53                 if (l.m == m) {
54                         l.bufs.emplace_back(position, buf);
55                         return;
56                 }
57         }
58         MeshBufList l;
59         l.m = m;
60         l.bufs.emplace_back(position, buf);
61         list.emplace_back(l);
62 }
63
64 static void on_settings_changed(const std::string &name, void *data)
65 {
66         static_cast<ClientMap*>(data)->onSettingChanged(name);
67 }
68 // ClientMap
69
70 ClientMap::ClientMap(
71                 Client *client,
72                 RenderingEngine *rendering_engine,
73                 MapDrawControl &control,
74                 s32 id
75 ):
76         Map(client),
77         scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
78                 rendering_engine->get_scene_manager(), id),
79         m_client(client),
80         m_rendering_engine(rendering_engine),
81         m_control(control),
82         m_drawlist(MapBlockComparer(v3s16(0,0,0)))
83 {
84
85         /*
86          * @Liso: Sadly C++ doesn't have introspection, so the only way we have to know
87          * the class is whith a name ;) Name property cames from ISceneNode base class.
88          */
89         Name = "ClientMap";
90         m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
91                         BS*1000000,BS*1000000,BS*1000000);
92
93         /* TODO: Add a callback function so these can be updated when a setting
94          *       changes.  At this point in time it doesn't matter (e.g. /set
95          *       is documented to change server settings only)
96          *
97          * TODO: Local caching of settings is not optimal and should at some stage
98          *       be updated to use a global settings object for getting thse values
99          *       (as opposed to the this local caching). This can be addressed in
100          *       a later release.
101          */
102         m_cache_trilinear_filter  = g_settings->getBool("trilinear_filter");
103         m_cache_bilinear_filter   = g_settings->getBool("bilinear_filter");
104         m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
105         m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance");
106         m_new_occlusion_culler = g_settings->get("occlusion_culler") == "bfs";
107         g_settings->registerChangedCallback("occlusion_culler", on_settings_changed, this);
108         m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
109         g_settings->registerChangedCallback("enable_raytraced_culling", on_settings_changed, this);
110 }
111
112 void ClientMap::onSettingChanged(const std::string &name)
113 {
114         if (name == "occlusion_culler")
115                 m_new_occlusion_culler = g_settings->get("occlusion_culler") == "bfs";
116         if (name == "enable_raytraced_culling")
117                 m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
118 }
119
120 ClientMap::~ClientMap()
121 {
122         g_settings->deregisterChangedCallback("occlusion_culler", on_settings_changed, this);
123         g_settings->deregisterChangedCallback("enable_raytraced_culling", on_settings_changed, this);
124 }
125
126 void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset)
127 {
128         v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset;
129         v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE);
130
131         m_camera_position = pos;
132         m_camera_direction = dir;
133         m_camera_fov = fov;
134         m_camera_offset = offset;
135
136         v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset;
137         v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE);
138
139         // reorder the blocks when camera crosses block boundary
140         if (previous_block != current_block)
141                 m_needs_update_drawlist = true;
142
143         // reorder transparent meshes when camera crosses node boundary
144         if (previous_node != current_node)
145                 m_needs_update_transparent_meshes = true;
146 }
147
148 MapSector * ClientMap::emergeSector(v2s16 p2d)
149 {
150         // Check that it doesn't exist already
151         MapSector *sector = getSectorNoGenerate(p2d);
152
153         // Create it if it does not exist yet
154         if (!sector) {
155                 sector = new MapSector(this, p2d, m_gamedef);
156                 m_sectors[p2d] = sector;
157         }
158
159         return sector;
160 }
161
162 void ClientMap::OnRegisterSceneNode()
163 {
164         if(IsVisible)
165         {
166                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
167                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
168         }
169
170         ISceneNode::OnRegisterSceneNode();
171         // It's not needed to register this node to the shadow renderer
172         // we have other way to find it
173 }
174
175 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
176                 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
177 {
178         if (range <= 0.0f)
179                 range = m_control.wanted_range;
180
181         v3s16 box_nodes_d = range * v3s16(1, 1, 1);
182         // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
183         // can exceed the range of v3s16 when a large view range is used near the
184         // world edges.
185         v3s32 p_nodes_min(
186                 cam_pos_nodes.X - box_nodes_d.X,
187                 cam_pos_nodes.Y - box_nodes_d.Y,
188                 cam_pos_nodes.Z - box_nodes_d.Z);
189         v3s32 p_nodes_max(
190                 cam_pos_nodes.X + box_nodes_d.X,
191                 cam_pos_nodes.Y + box_nodes_d.Y,
192                 cam_pos_nodes.Z + box_nodes_d.Z);
193         // Take a fair amount as we will be dropping more out later
194         // Umm... these additions are a bit strange but they are needed.
195         *p_blocks_min = v3s16(
196                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
197                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
198                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
199         *p_blocks_max = v3s16(
200                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
201                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
202                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
203 }
204
205 class MapBlockFlags
206 {
207 public:
208         static constexpr u16 CHUNK_EDGE = 8;
209         static constexpr u16 CHUNK_MASK = CHUNK_EDGE - 1;
210         static constexpr std::size_t CHUNK_VOLUME = CHUNK_EDGE * CHUNK_EDGE * CHUNK_EDGE; // volume of a chunk
211
212         MapBlockFlags(v3s16 min_pos, v3s16 max_pos)
213                         : min_pos(min_pos), volume((max_pos - min_pos) / CHUNK_EDGE + 1)
214         {
215                 chunks.resize(volume.X * volume.Y * volume.Z);
216         }
217
218         class Chunk
219         {
220         public:
221                 inline u8 &getBits(v3s16 pos)
222                 {
223                         std::size_t address = getAddress(pos);
224                         return bits[address];
225                 }
226
227         private:
228                 inline std::size_t getAddress(v3s16 pos) {
229                         std::size_t address = (pos.X & CHUNK_MASK) + (pos.Y & CHUNK_MASK) * CHUNK_EDGE + (pos.Z & CHUNK_MASK) * (CHUNK_EDGE * CHUNK_EDGE);
230                         return address;
231                 }
232
233                 std::array<u8, CHUNK_VOLUME> bits;
234         };
235
236         Chunk &getChunk(v3s16 pos)
237         {
238                 v3s16 delta = (pos - min_pos) / CHUNK_EDGE;
239                 std::size_t address = delta.X + delta.Y * volume.X + delta.Z * volume.X * volume.Y;
240                 Chunk *chunk = chunks[address].get();
241                 if (!chunk) {
242                         chunk = new Chunk();
243                         chunks[address].reset(chunk);
244                 }
245                 return *chunk;
246         }
247 private:
248         std::vector<std::unique_ptr<Chunk>> chunks;
249         v3s16 min_pos;
250         v3s16 volume;
251 };
252
253 void ClientMap::updateDrawList()
254 {
255         if (m_new_occlusion_culler) {
256                 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
257
258                 m_needs_update_drawlist = false;
259
260                 for (auto &i : m_drawlist) {
261                         MapBlock *block = i.second;
262                         block->refDrop();
263                 }
264                 m_drawlist.clear();
265
266                 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
267
268                 v3s16 p_blocks_min;
269                 v3s16 p_blocks_max;
270                 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
271
272                 // Number of blocks occlusion culled
273                 u32 blocks_occlusion_culled = 0;
274                 // Blocks visited by the algorithm
275                 u32 blocks_visited = 0;
276                 // Block sides that were not traversed
277                 u32 sides_skipped = 0;
278
279                 // No occlusion culling when free_move is on and camera is inside ground
280                 bool occlusion_culling_enabled = true;
281                 if (m_control.allow_noclip) {
282                         MapNode n = getNode(cam_pos_nodes);
283                         if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
284                                 occlusion_culling_enabled = false;
285                 }
286
287                 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
288                 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
289
290                 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
291
292                 // Uncomment to debug occluded blocks in the wireframe mode
293                 // TODO: Include this as a flag for an extended debugging setting
294                 // if (occlusion_culling_enabled && m_control.show_wireframe)
295                 //      occlusion_culling_enabled = porting::getTimeS() & 1;
296
297                 std::queue<v3s16> blocks_to_consider;
298
299                 // Bits per block:
300                 // [ visited | 0 | 0 | 0 | 0 | Z visible | Y visible | X visible ]
301                 MapBlockFlags blocks_seen(p_blocks_min, p_blocks_max);
302
303                 // Start breadth-first search with the block the camera is in
304                 blocks_to_consider.push(camera_block);
305                 blocks_seen.getChunk(camera_block).getBits(camera_block) = 0x07; // mark all sides as visible
306
307                 // Recursively walk the space and pick mapblocks for drawing
308                 while (blocks_to_consider.size() > 0) {
309
310                         v3s16 block_coord = blocks_to_consider.front();
311                         blocks_to_consider.pop();
312
313                         auto &flags = blocks_seen.getChunk(block_coord).getBits(block_coord);
314
315                         // Only visit each block once (it may have been queued up to three times)
316                         if ((flags & 0x80) == 0x80)
317                                 continue;
318                         flags |= 0x80;
319
320                         blocks_visited++;
321
322                         // Get the sector, block and mesh
323                         MapSector *sector = this->getSectorNoGenerate(v2s16(block_coord.X, block_coord.Z));
324
325                         if (!sector)
326                                 continue;
327
328                         MapBlock *block = sector->getBlockNoCreateNoEx(block_coord.Y);
329
330                         MapBlockMesh *mesh = block ? block->mesh : nullptr;
331
332
333                         // Calculate the coordinates for range and frutum culling
334                         v3f mesh_sphere_center;
335                         f32 mesh_sphere_radius;
336
337                         v3s16 block_pos_nodes = block_coord * MAP_BLOCKSIZE;
338
339                         if (mesh) {
340                                 mesh_sphere_center = intToFloat(block_pos_nodes, BS)
341                                                 + mesh->getBoundingSphereCenter();
342                                 mesh_sphere_radius = mesh->getBoundingRadius();
343                         }
344                         else {
345                                 mesh_sphere_center = intToFloat(block_pos_nodes, BS) + v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
346                                 mesh_sphere_radius = 0.0f;
347                         }
348
349                         // First, perform a simple distance check.
350                         if (!m_control.range_all &&
351                                 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
352                                         m_control.wanted_range * BS + mesh_sphere_radius)
353                                 continue; // Out of range, skip.
354
355                         // Frustum culling
356                         // Only do coarse culling here, to account for fast camera movement.
357                         // This is needed because this function is not called every frame.
358                         float frustum_cull_extra_radius = 300.0f;
359                         if (is_frustum_culled(mesh_sphere_center,
360                                         mesh_sphere_radius + frustum_cull_extra_radius))
361                                 continue;
362
363                         // Calculate the vector from the camera block to the current block
364                         // We use it to determine through which sides of the current block we can continue the search
365                         v3s16 look = block_coord - camera_block;
366
367                         // Occluded near sides will further occlude the far sides
368                         u8 visible_outer_sides = flags & 0x07;
369
370                         // Raytraced occlusion culling - send rays from the camera to the block's corners
371                         if (occlusion_culling_enabled && m_enable_raytraced_culling &&
372                                         block && mesh &&
373                                         visible_outer_sides != 0x07 && isBlockOccluded(block, cam_pos_nodes)) {
374                                 blocks_occlusion_culled++;
375                                 continue;
376                         }
377
378                         // The block is visible, add to the draw list
379                         if (mesh) {
380                                 // Add to set
381                                 block->refGrab();
382                                 m_drawlist[block_coord] = block;
383                         }
384
385                         // Decide which sides to traverse next or to block away
386
387                         // First, find the near sides that would occlude the far sides
388                         // * A near side can itself be occluded by a nearby block (the test above ^^)
389                         // * A near side can be visible but fully opaque by itself (e.g. ground at the 0 level)
390
391                         // mesh solid sides are +Z-Z+Y-Y+X-X
392                         // if we are inside the block's coordinates on an axis, 
393                         // treat these sides as opaque, as they should not allow to reach the far sides
394                         u8 block_inner_sides = (look.X == 0 ? 3 : 0) |
395                                 (look.Y == 0 ? 12 : 0) |
396                                 (look.Z == 0 ? 48 : 0);
397
398                         // get the mask for the sides that are relevant based on the direction
399                         u8 near_inner_sides = (look.X > 0 ? 1 : 2) |
400                                         (look.Y > 0 ? 4 : 8) |
401                                         (look.Z > 0 ? 16 : 32);
402                         
403                         // This bitset is +Z-Z+Y-Y+X-X (See MapBlockMesh), and axis is XYZ.
404                         // Get he block's transparent sides
405                         u8 transparent_sides = (occlusion_culling_enabled && block) ? ~block->solid_sides : 0x3F;
406
407                         // compress block transparent sides to ZYX mask of see-through axes
408                         u8 near_transparency =  (block_inner_sides == 0x3F) ? near_inner_sides : (transparent_sides & near_inner_sides);
409
410                         // when we are inside the camera block, do not block any sides
411                         if (block_inner_sides == 0x3F)
412                                 block_inner_sides = 0;
413
414                         near_transparency &= ~block_inner_sides & 0x3F;
415
416                         near_transparency |= (near_transparency >> 1);
417                         near_transparency = (near_transparency & 1) |
418                                         ((near_transparency >> 1) & 2) |
419                                         ((near_transparency >> 2) & 4);
420
421                         // combine with known visible sides that matter
422                         near_transparency &= visible_outer_sides;
423
424                         // The rule for any far side to be visible:
425                         // * Any of the adjacent near sides is transparent (different axes)
426                         // * The opposite near side (same axis) is transparent, if it is the dominant axis of the look vector
427
428                         // Calculate vector from camera to mapblock center. Because we only need relation between
429                         // coordinates we scale by 2 to avoid precision loss.
430                         v3s16 precise_look = 2 * (block_pos_nodes - cam_pos_nodes) + MAP_BLOCKSIZE - 1;
431
432                         // dominant axis flag
433                         u8 dominant_axis = (abs(precise_look.X) > abs(precise_look.Y) && abs(precise_look.X) > abs(precise_look.Z)) |
434                                                 ((abs(precise_look.Y) > abs(precise_look.Z) && abs(precise_look.Y) > abs(precise_look.X)) << 1) |
435                                                 ((abs(precise_look.Z) > abs(precise_look.X) && abs(precise_look.Z) > abs(precise_look.Y)) << 2);
436
437                         // Queue next blocks for processing:
438                         // - Examine "far" sides of the current blocks, i.e. never move towards the camera
439                         // - Only traverse the sides that are not occluded
440                         // - Only traverse the sides that are not opaque
441                         // When queueing, mark the relevant side on the next block as 'visible'
442                         for (s16 axis = 0; axis < 3; axis++) {
443
444                                 // Select a bit from transparent_sides for the side
445                                 u8 far_side_mask = 1 << (2 * axis);
446
447                                 // axis flag
448                                 u8 my_side = 1 << axis;
449                                 u8 adjacent_sides = my_side ^ 0x07;
450
451                                 auto traverse_far_side = [&](s8 next_pos_offset) {
452                                         // far side is visible if adjacent near sides are transparent, or if opposite side on dominant axis is transparent
453                                         bool side_visible = ((near_transparency & adjacent_sides) | (near_transparency & my_side & dominant_axis)) != 0;
454                                         side_visible = side_visible && ((far_side_mask & transparent_sides) != 0);
455
456                                         v3s16 next_pos = block_coord;
457                                         next_pos[axis] += next_pos_offset;
458
459                                         // If a side is a see-through, mark the next block's side as visible, and queue
460                                         if (side_visible) {
461                                                 auto &next_flags = blocks_seen.getChunk(next_pos).getBits(next_pos);
462                                                 next_flags |= my_side;
463                                                 blocks_to_consider.push(next_pos);
464                                         }
465                                         else {
466                                                 sides_skipped++;
467                                         }
468                                 };
469
470
471                                 // Test the '-' direction of the axis
472                                 if (look[axis] <= 0 && block_coord[axis] > p_blocks_min[axis])
473                                         traverse_far_side(-1);
474
475                                 // Test the '+' direction of the axis
476                                 far_side_mask <<= 1;
477
478                                 if (look[axis] >= 0 && block_coord[axis] < p_blocks_max[axis])
479                                         traverse_far_side(+1);
480                         }
481                 }
482
483                 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
484                 g_profiler->avg("MapBlocks sides skipped [#]", sides_skipped);
485                 g_profiler->avg("MapBlocks examined [#]", blocks_visited);
486                 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
487         }
488         else {
489                 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
490
491                 m_needs_update_drawlist = false;
492
493                 for (auto &i : m_drawlist) {
494                         MapBlock *block = i.second;
495                         block->refDrop();
496                 }
497                 m_drawlist.clear();
498
499                 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
500
501                 v3s16 p_blocks_min;
502                 v3s16 p_blocks_max;
503                 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
504
505                 // Number of blocks currently loaded by the client
506                 u32 blocks_loaded = 0;
507                 // Number of blocks with mesh in rendering range
508                 u32 blocks_in_range_with_mesh = 0;
509                 // Number of blocks occlusion culled
510                 u32 blocks_occlusion_culled = 0;
511
512                 // No occlusion culling when free_move is on and camera is inside ground
513                 bool occlusion_culling_enabled = true;
514                 if (m_control.allow_noclip) {
515                         MapNode n = getNode(cam_pos_nodes);
516                         if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
517                                 occlusion_culling_enabled = false;
518                 }
519
520                 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
521                 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
522
523                 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
524
525                 // Uncomment to debug occluded blocks in the wireframe mode
526                 // TODO: Include this as a flag for an extended debugging setting
527                 //if (occlusion_culling_enabled && m_control.show_wireframe)
528                 //    occlusion_culling_enabled = porting::getTimeS() & 1;
529
530                 for (const auto &sector_it : m_sectors) {
531                         MapSector *sector = sector_it.second;
532                         v2s16 sp = sector->getPos();
533
534                         blocks_loaded += sector->size();
535                         if (!m_control.range_all) {
536                                 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
537                                                 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
538                                         continue;
539                         }
540
541                         MapBlockVect sectorblocks;
542                         sector->getBlocks(sectorblocks);
543
544                         /*
545                                 Loop through blocks in sector
546                         */
547
548                         u32 sector_blocks_drawn = 0;
549
550                         for (MapBlock *block : sectorblocks) {
551                                 /*
552                                         Compare block position to camera position, skip
553                                         if not seen on display
554                                 */
555
556                                 if (!block->mesh) {
557                                         // Ignore if mesh doesn't exist
558                                         continue;
559                                 }
560
561                                 v3s16 block_coord = block->getPos();
562                                 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
563                                                 + block->mesh->getBoundingSphereCenter();
564                                 f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
565                                 // First, perform a simple distance check.
566                                 if (!m_control.range_all &&
567                                         mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
568                                                 m_control.wanted_range * BS + mesh_sphere_radius)
569                                         continue; // Out of range, skip.
570
571                                 // Keep the block alive as long as it is in range.
572                                 block->resetUsageTimer();
573                                 blocks_in_range_with_mesh++;
574
575                                 // Frustum culling
576                                 // Only do coarse culling here, to account for fast camera movement.
577                                 // This is needed because this function is not called every frame.
578                                 constexpr float frustum_cull_extra_radius = 300.0f;
579                                 if (is_frustum_culled(mesh_sphere_center,
580                                                 mesh_sphere_radius + frustum_cull_extra_radius))
581                                         continue;
582
583                                 // Occlusion culling
584                                 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
585                                         blocks_occlusion_culled++;
586                                         continue;
587                                 }
588
589                                 // Add to set
590                                 block->refGrab();
591                                 m_drawlist[block_coord] = block;
592
593                                 sector_blocks_drawn++;
594                         } // foreach sectorblocks
595
596                         if (sector_blocks_drawn != 0)
597                                 m_last_drawn_sectors.insert(sp);
598                 }
599
600                 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
601                 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
602                 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
603                 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
604         }
605 }
606
607 void ClientMap::touchMapBlocks()
608 {
609         if (!m_new_occlusion_culler)
610                 return;
611
612         v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
613
614         v3s16 p_blocks_min;
615         v3s16 p_blocks_max;
616         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
617
618         // Number of blocks currently loaded by the client
619         u32 blocks_loaded = 0;
620         // Number of blocks with mesh in rendering range
621         u32 blocks_in_range_with_mesh = 0;
622
623         for (const auto &sector_it : m_sectors) {
624                 MapSector *sector = sector_it.second;
625                 v2s16 sp = sector->getPos();
626
627                 blocks_loaded += sector->size();
628                 if (!m_control.range_all) {
629                         if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
630                                         sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
631                                 continue;
632                 }
633
634                 MapBlockVect sectorblocks;
635                 sector->getBlocks(sectorblocks);
636
637                 /*
638                         Loop through blocks in sector
639                 */
640
641                 for (MapBlock *block : sectorblocks) {
642                         /*
643                                 Compare block position to camera position, skip
644                                 if not seen on display
645                         */
646
647                         if (!block->mesh) {
648                                 // Ignore if mesh doesn't exist
649                                 continue;
650                         }
651
652                         v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
653                                         + block->mesh->getBoundingSphereCenter();
654                         f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
655                         // First, perform a simple distance check.
656                         if (!m_control.range_all &&
657                                 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
658                                         m_control.wanted_range * BS + mesh_sphere_radius)
659                                 continue; // Out of range, skip.
660
661                         // Keep the block alive as long as it is in range.
662                         block->resetUsageTimer();
663                         blocks_in_range_with_mesh++;
664                 }
665         }
666         g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
667         g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
668 }
669
670 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
671 {
672         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
673
674         std::string prefix;
675         if (pass == scene::ESNRP_SOLID)
676                 prefix = "renderMap(SOLID): ";
677         else
678                 prefix = "renderMap(TRANSPARENT): ";
679
680         /*
681                 This is called two times per frame, reset on the non-transparent one
682         */
683         if (pass == scene::ESNRP_SOLID)
684                 m_last_drawn_sectors.clear();
685
686         /*
687                 Get animation parameters
688         */
689         const float animation_time = m_client->getAnimationTime();
690         const int crack = m_client->getCrackLevel();
691         const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
692
693         const v3f camera_position = m_camera_position;
694
695         /*
696                 Get all blocks and draw all visible ones
697         */
698
699         u32 vertex_count = 0;
700         u32 drawcall_count = 0;
701
702         // For limiting number of mesh animations per frame
703         u32 mesh_animate_count = 0;
704         //u32 mesh_animate_count_far = 0;
705
706         /*
707                 Update transparent meshes
708         */
709         if (is_transparent_pass)
710                 updateTransparentMeshBuffers();
711
712         /*
713                 Draw the selected MapBlocks
714         */
715
716         MeshBufListList grouped_buffers;
717         std::vector<DrawDescriptor> draw_order;
718         video::SMaterial previous_material;
719
720         auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
721
722         for (auto &i : m_drawlist) {
723                 v3s16 block_pos = i.first;
724                 MapBlock *block = i.second;
725                 MapBlockMesh *block_mesh = block->mesh;
726
727                 // If the mesh of the block happened to get deleted, ignore it
728                 if (!block_mesh)
729                         continue;
730
731                 // Do exact frustum culling
732                 // (The one in updateDrawList is only coarse.)
733                 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
734                                 + block_mesh->getBoundingSphereCenter();
735                 f32 mesh_sphere_radius = block_mesh->getBoundingRadius();
736                 if (is_frustum_culled(mesh_sphere_center, mesh_sphere_radius))
737                         continue;
738
739                 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
740
741                 float d = camera_position.getDistanceFrom(block_pos_r);
742                 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
743
744                 // Mesh animation
745                 if (pass == scene::ESNRP_SOLID) {
746                         // Pretty random but this should work somewhat nicely
747                         bool faraway = d >= BS * 50;
748                         if (block_mesh->isAnimationForced() || !faraway ||
749                                         mesh_animate_count < (m_control.range_all ? 200 : 50)) {
750
751                                 bool animated = block_mesh->animate(faraway, animation_time,
752                                         crack, daynight_ratio);
753                                 if (animated)
754                                         mesh_animate_count++;
755                         } else {
756                                 block_mesh->decreaseAnimationForceTimer();
757                         }
758                 }
759
760                 /*
761                         Get the meshbuffers of the block
762                 */
763                 if (is_transparent_pass) {
764                         // In transparent pass, the mesh will give us
765                         // the partial buffers in the correct order
766                         for (auto &buffer : block_mesh->getTransparentBuffers())
767                                 draw_order.emplace_back(block_pos, &buffer);
768                 }
769                 else {
770                         // otherwise, group buffers across meshes
771                         // using MeshBufListList
772                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
773                                 scene::IMesh *mesh = block_mesh->getMesh(layer);
774                                 assert(mesh);
775
776                                 u32 c = mesh->getMeshBufferCount();
777                                 for (u32 i = 0; i < c; i++) {
778                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
779
780                                         video::SMaterial& material = buf->getMaterial();
781                                         video::IMaterialRenderer* rnd =
782                                                         driver->getMaterialRenderer(material.MaterialType);
783                                         bool transparent = (rnd && rnd->isTransparent());
784                                         if (!transparent) {
785                                                 if (buf->getVertexCount() == 0)
786                                                         errorstream << "Block [" << analyze_block(block)
787                                                                         << "] contains an empty meshbuf" << std::endl;
788
789                                                 grouped_buffers.add(buf, block_pos, layer);
790                                         }
791                                 }
792                         }
793                 }
794         }
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
806         TimeTaker draw("Drawing mesh buffers");
807
808         core::matrix4 m; // Model matrix
809         v3f offset = intToFloat(m_camera_offset, BS);
810         u32 material_swaps = 0;
811
812         // Render all mesh buffers in order
813         drawcall_count += draw_order.size();
814
815         for (auto &descriptor : draw_order) {
816                 scene::IMeshBuffer *buf = descriptor.getBuffer();
817
818                 if (!descriptor.m_reuse_material) {
819                         auto &material = buf->getMaterial();
820
821                         // Apply filter settings
822                         material.setFlag(video::EMF_TRILINEAR_FILTER,
823                                 m_cache_trilinear_filter);
824                         material.setFlag(video::EMF_BILINEAR_FILTER,
825                                 m_cache_bilinear_filter);
826                         material.setFlag(video::EMF_ANISOTROPIC_FILTER,
827                                 m_cache_anistropic_filter);
828                         material.setFlag(video::EMF_WIREFRAME,
829                                 m_control.show_wireframe);
830
831                         // pass the shadow map texture to the buffer texture
832                         ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
833                         if (shadow && shadow->is_active()) {
834                                 auto &layer = material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW];
835                                 layer.Texture = shadow->get_texture();
836                                 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
837                                 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
838                                 // Do not enable filter on shadow texture to avoid visual artifacts
839                                 // with colored shadows.
840                                 // Filtering is done in shader code anyway
841                                 layer.BilinearFilter = false;
842                                 layer.AnisotropicFilter = false;
843                                 layer.TrilinearFilter = false;
844                         }
845                         driver->setMaterial(material);
846                         ++material_swaps;
847                         material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW].Texture = nullptr;
848                 }
849
850                 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
851                 m.setTranslation(block_wpos - offset);
852
853                 driver->setTransform(video::ETS_WORLD, m);
854                 descriptor.draw(driver);
855                 vertex_count += buf->getIndexCount();
856         }
857
858         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
859
860         // Log only on solid pass because values are the same
861         if (pass == scene::ESNRP_SOLID) {
862                 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
863         }
864
865         if (pass == scene::ESNRP_TRANSPARENT) {
866                 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
867         }
868
869         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
870         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
871         g_profiler->avg(prefix + "material swaps [#]", material_swaps);
872 }
873
874 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
875         float step_multiplier, float start_distance, float end_distance,
876         const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
877         int *result, bool *sunlight_seen)
878 {
879         int brightness_sum = 0;
880         int brightness_count = 0;
881         float distance = start_distance;
882         dir.normalize();
883         v3f pf = p0;
884         pf += dir * distance;
885         int noncount = 0;
886         bool nonlight_seen = false;
887         bool allow_allowing_non_sunlight_propagates = false;
888         bool allow_non_sunlight_propagates = false;
889         // Check content nearly at camera position
890         {
891                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
892                 MapNode n = map->getNode(p);
893                 if(ndef->getLightingFlags(n).has_light &&
894                                 !ndef->getLightingFlags(n).sunlight_propagates)
895                         allow_allowing_non_sunlight_propagates = true;
896         }
897         // If would start at CONTENT_IGNORE, start closer
898         {
899                 v3s16 p = floatToInt(pf, BS);
900                 MapNode n = map->getNode(p);
901                 if(n.getContent() == CONTENT_IGNORE){
902                         float newd = 2*BS;
903                         pf = p0 + dir * 2*newd;
904                         distance = newd;
905                         sunlight_min_d = 0;
906                 }
907         }
908         for (int i=0; distance < end_distance; i++) {
909                 pf += dir * step;
910                 distance += step;
911                 step *= step_multiplier;
912
913                 v3s16 p = floatToInt(pf, BS);
914                 MapNode n = map->getNode(p);
915                 ContentLightingFlags f = ndef->getLightingFlags(n);
916                 if (allow_allowing_non_sunlight_propagates && i == 0 &&
917                                 f.has_light && !f.sunlight_propagates) {
918                         allow_non_sunlight_propagates = true;
919                 }
920
921                 if (!f.has_light || (!f.sunlight_propagates && !allow_non_sunlight_propagates)){
922                         nonlight_seen = true;
923                         noncount++;
924                         if(noncount >= 4)
925                                 break;
926                         continue;
927                 }
928
929                 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
930                         if (n.getLight(LIGHTBANK_DAY, f) == LIGHT_SUN)
931                                 *sunlight_seen = true;
932                 noncount = 0;
933                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, f));
934                 brightness_count++;
935         }
936         *result = 0;
937         if(brightness_count == 0)
938                 return false;
939         *result = brightness_sum / brightness_count;
940         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
941                         <<(*result)<<std::endl;*/
942         return true;
943 }
944
945 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
946                 int oldvalue, bool *sunlight_seen_result)
947 {
948         ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
949         static v3f z_directions[50] = {
950                 v3f(-100, 0, 0)
951         };
952         static f32 z_offsets[50] = {
953                 -1000,
954         };
955
956         if (z_directions[0].X < -99) {
957                 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
958                         // Assumes FOV of 72 and 16/9 aspect ratio
959                         z_directions[i] = v3f(
960                                 0.02 * myrand_range(-100, 100),
961                                 1.0,
962                                 0.01 * myrand_range(-100, 100)
963                         ).normalize();
964                         z_offsets[i] = 0.01 * myrand_range(0,100);
965                 }
966         }
967
968         int sunlight_seen_count = 0;
969         float sunlight_min_d = max_d*0.8;
970         if(sunlight_min_d > 35*BS)
971                 sunlight_min_d = 35*BS;
972         std::vector<int> values;
973         values.reserve(ARRLEN(z_directions));
974         for (u32 i = 0; i < ARRLEN(z_directions); i++) {
975                 v3f z_dir = z_directions[i];
976                 core::CMatrix4<f32> a;
977                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
978                 v3f dir = m_camera_direction;
979                 a.rotateVect(dir);
980                 int br = 0;
981                 float step = BS*1.5;
982                 if(max_d > 35*BS)
983                         step = max_d / 35 * 1.5;
984                 float off = step * z_offsets[i];
985                 bool sunlight_seen_now = false;
986                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
987                                 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
988                                 sunlight_min_d,
989                                 &br, &sunlight_seen_now);
990                 if(sunlight_seen_now)
991                         sunlight_seen_count++;
992                 if(!ok)
993                         continue;
994                 values.push_back(br);
995                 // Don't try too much if being in the sun is clear
996                 if(sunlight_seen_count >= 20)
997                         break;
998         }
999         int brightness_sum = 0;
1000         int brightness_count = 0;
1001         std::sort(values.begin(), values.end());
1002         u32 num_values_to_use = values.size();
1003         if(num_values_to_use >= 10)
1004                 num_values_to_use -= num_values_to_use/2;
1005         else if(num_values_to_use >= 7)
1006                 num_values_to_use -= num_values_to_use/3;
1007         u32 first_value_i = (values.size() - num_values_to_use) / 2;
1008
1009         for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
1010                 brightness_sum += values[i];
1011                 brightness_count++;
1012         }
1013
1014         int ret = 0;
1015         if(brightness_count == 0){
1016                 MapNode n = getNode(floatToInt(m_camera_position, BS));
1017                 ContentLightingFlags f = m_nodedef->getLightingFlags(n);
1018                 if(f.has_light){
1019                         ret = decode_light(n.getLightBlend(daylight_factor, f));
1020                 } else {
1021                         ret = oldvalue;
1022                 }
1023         } else {
1024                 ret = brightness_sum / brightness_count;
1025         }
1026
1027         *sunlight_seen_result = (sunlight_seen_count > 0);
1028         return ret;
1029 }
1030
1031 void ClientMap::renderPostFx(CameraMode cam_mode)
1032 {
1033         // Sadly ISceneManager has no "post effects" render pass, in that case we
1034         // could just register for that and handle it in renderMap().
1035
1036         MapNode n = getNode(floatToInt(m_camera_position, BS));
1037
1038         const ContentFeatures& features = m_nodedef->get(n);
1039         video::SColor post_effect_color = features.post_effect_color;
1040
1041         // If the camera is in a solid node, make everything black.
1042         // (first person mode only)
1043         if (features.solidness == 2 && cam_mode == CAMERA_MODE_FIRST &&
1044                 !m_control.allow_noclip) {
1045                 post_effect_color = video::SColor(255, 0, 0, 0);
1046         }
1047
1048         if (post_effect_color.getAlpha() != 0) {
1049                 // Draw a full-screen rectangle
1050                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
1051                 v2u32 ss = driver->getScreenSize();
1052                 core::rect<s32> rect(0,0, ss.X, ss.Y);
1053                 driver->draw2DRectangle(post_effect_color, rect);
1054         }
1055 }
1056
1057 void ClientMap::PrintInfo(std::ostream &out)
1058 {
1059         out<<"ClientMap: ";
1060 }
1061
1062 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
1063                 const video::SMaterial &material, s32 pass, int frame, int total_frames)
1064 {
1065         bool is_transparent_pass = pass != scene::ESNRP_SOLID;
1066         std::string prefix;
1067         if (is_transparent_pass)
1068                 prefix = "renderMap(SHADOW TRANS): ";
1069         else
1070                 prefix = "renderMap(SHADOW SOLID): ";
1071
1072         u32 drawcall_count = 0;
1073         u32 vertex_count = 0;
1074
1075         MeshBufListList grouped_buffers;
1076         std::vector<DrawDescriptor> draw_order;
1077
1078
1079         int count = 0;
1080         int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
1081         int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
1082
1083         // transparent pass should be rendered in one go
1084         if (is_transparent_pass && frame != total_frames - 1) {
1085                 return;
1086         }
1087
1088         for (const auto &i : m_drawlist_shadow) {
1089                 // only process specific part of the list & break early
1090                 ++count;
1091                 if (count <= low_bound)
1092                         continue;
1093                 if (count > high_bound)
1094                         break;
1095
1096                 v3s16 block_pos = i.first;
1097                 MapBlock *block = i.second;
1098
1099                 // If the mesh of the block happened to get deleted, ignore it
1100                 if (!block->mesh)
1101                         continue;
1102
1103                 /*
1104                         Get the meshbuffers of the block
1105                 */
1106                 if (is_transparent_pass) {
1107                         // In transparent pass, the mesh will give us
1108                         // the partial buffers in the correct order
1109                         for (auto &buffer : block->mesh->getTransparentBuffers())
1110                                 draw_order.emplace_back(block_pos, &buffer);
1111                 }
1112                 else {
1113                         // otherwise, group buffers across meshes
1114                         // using MeshBufListList
1115                         MapBlockMesh *mapBlockMesh = block->mesh;
1116                         assert(mapBlockMesh);
1117
1118                         for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
1119                                 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
1120                                 assert(mesh);
1121
1122                                 u32 c = mesh->getMeshBufferCount();
1123                                 for (u32 i = 0; i < c; i++) {
1124                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
1125
1126                                         video::SMaterial &mat = buf->getMaterial();
1127                                         auto rnd = driver->getMaterialRenderer(mat.MaterialType);
1128                                         bool transparent = rnd && rnd->isTransparent();
1129                                         if (!transparent)
1130                                                 grouped_buffers.add(buf, block_pos, layer);
1131                                 }
1132                         }
1133                 }
1134         }
1135
1136         u32 buffer_count = 0;
1137         for (auto &lists : grouped_buffers.lists)
1138                 for (MeshBufList &list : lists)
1139                         buffer_count += list.bufs.size();
1140
1141         draw_order.reserve(draw_order.size() + buffer_count);
1142
1143         // Capture draw order for all solid meshes
1144         for (auto &lists : grouped_buffers.lists) {
1145                 for (MeshBufList &list : lists) {
1146                         // iterate in reverse to draw closest blocks first
1147                         for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
1148                                 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
1149                 }
1150         }
1151
1152         TimeTaker draw("Drawing shadow mesh buffers");
1153
1154         core::matrix4 m; // Model matrix
1155         v3f offset = intToFloat(m_camera_offset, BS);
1156         u32 material_swaps = 0;
1157
1158         // Render all mesh buffers in order
1159         drawcall_count += draw_order.size();
1160
1161         for (auto &descriptor : draw_order) {
1162                 scene::IMeshBuffer *buf = descriptor.getBuffer();
1163
1164                 if (!descriptor.m_reuse_material) {
1165                         // override some material properties
1166                         video::SMaterial local_material = buf->getMaterial();
1167                         local_material.MaterialType = material.MaterialType;
1168                         local_material.BackfaceCulling = material.BackfaceCulling;
1169                         local_material.FrontfaceCulling = material.FrontfaceCulling;
1170                         local_material.BlendOperation = material.BlendOperation;
1171                         local_material.Lighting = false;
1172                         driver->setMaterial(local_material);
1173                         ++material_swaps;
1174                 }
1175
1176                 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
1177                 m.setTranslation(block_wpos - offset);
1178
1179                 driver->setTransform(video::ETS_WORLD, m);
1180                 descriptor.draw(driver);
1181                 vertex_count += buf->getIndexCount();
1182         }
1183
1184         // restore the driver material state
1185         video::SMaterial clean;
1186         clean.BlendOperation = video::EBO_ADD;
1187         driver->setMaterial(clean); // reset material to defaults
1188         driver->draw3DLine(v3f(), v3f(), video::SColor(0));
1189
1190         g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
1191         g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
1192         g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
1193         g_profiler->avg(prefix + "material swaps [#]", material_swaps);
1194 }
1195
1196 /*
1197         Custom update draw list for the pov of shadow light.
1198 */
1199 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
1200 {
1201         ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
1202
1203         v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
1204         v3s16 p_blocks_min;
1205         v3s16 p_blocks_max;
1206         getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
1207
1208         for (auto &i : m_drawlist_shadow) {
1209                 MapBlock *block = i.second;
1210                 block->refDrop();
1211         }
1212         m_drawlist_shadow.clear();
1213
1214         // Number of blocks currently loaded by the client
1215         u32 blocks_loaded = 0;
1216         // Number of blocks with mesh in rendering range
1217         u32 blocks_in_range_with_mesh = 0;
1218         // Number of blocks occlusion culled
1219         u32 blocks_occlusion_culled = 0;
1220
1221         for (auto &sector_it : m_sectors) {
1222                 MapSector *sector = sector_it.second;
1223                 if (!sector)
1224                         continue;
1225                 blocks_loaded += sector->size();
1226
1227                 MapBlockVect sectorblocks;
1228                 sector->getBlocks(sectorblocks);
1229
1230                 /*
1231                         Loop through blocks in sector
1232                 */
1233                 for (MapBlock *block : sectorblocks) {
1234                         if (!block->mesh) {
1235                                 // Ignore if mesh doesn't exist
1236                                 continue;
1237                         }
1238
1239                         v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
1240                         v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
1241                         if (projection.getDistanceFrom(block_pos) > radius)
1242                                 continue;
1243
1244                         blocks_in_range_with_mesh++;
1245
1246                         // This block is in range. Reset usage timer.
1247                         block->resetUsageTimer();
1248
1249                         // Add to set
1250                         if (m_drawlist_shadow.find(block->getPos()) == m_drawlist_shadow.end()) {
1251                                 block->refGrab();
1252                                 m_drawlist_shadow[block->getPos()] = block;
1253                         }
1254                 }
1255         }
1256
1257         g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
1258         g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
1259         g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
1260         g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
1261 }
1262
1263 void ClientMap::updateTransparentMeshBuffers()
1264 {
1265         ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
1266         u32 sorted_blocks = 0;
1267         u32 unsorted_blocks = 0;
1268         f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
1269
1270
1271         // Update the order of transparent mesh buffers in each mesh
1272         for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
1273                 MapBlock* block = it->second;
1274                 if (!block->mesh)
1275                         continue;
1276
1277                 if (m_needs_update_transparent_meshes ||
1278                                 block->mesh->getTransparentBuffers().size() == 0) {
1279
1280                         v3s16 block_pos = block->getPos();
1281                         v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
1282                         f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
1283                         if (distance <= sorting_distance_sq) {
1284                                 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
1285                                 ++sorted_blocks;
1286                         }
1287                         else {
1288                                 block->mesh->consolidateTransparentBuffers();
1289                                 ++unsorted_blocks;
1290                         }
1291                 }
1292         }
1293
1294         g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
1295         g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
1296         m_needs_update_transparent_meshes = false;
1297 }
1298
1299 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
1300 {
1301         return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
1302 }
1303
1304 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
1305 {
1306         if (m_use_partial_buffer) {
1307                 m_partial_buffer->beforeDraw();
1308                 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
1309                 m_partial_buffer->afterDraw();
1310         } else {
1311                 driver->drawMeshBuffer(m_buffer);
1312         }
1313 }