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