Performance of main client loop up to 2x faster In places, up to 3 times faster
[oweals/minetest.git] / src / 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 "log.h"
26 #include "mapsector.h"
27 #include "main.h" // dout_client, g_settings
28 #include "nodedef.h"
29 #include "mapblock.h"
30 #include "profiler.h"
31 #include "settings.h"
32 #include "camera.h" // CameraModes
33 #include "util/mathconstants.h"
34 #include <algorithm>
35
36 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
37
38 ClientMap::ClientMap(
39                 Client *client,
40                 IGameDef *gamedef,
41                 MapDrawControl &control,
42                 scene::ISceneNode* parent,
43                 scene::ISceneManager* mgr,
44                 s32 id
45 ):
46         Map(dout_client, gamedef),
47         scene::ISceneNode(parent, mgr, id),
48         m_client(client),
49         m_control(control),
50         m_camera_position(0,0,0),
51         m_camera_direction(0,0,1),
52         m_camera_fov(M_PI)
53 {
54         m_box = core::aabbox3d<f32>(-BS*1000000,-BS*1000000,-BS*1000000,
55                         BS*1000000,BS*1000000,BS*1000000);
56
57         /* TODO: Add a callback function so these can be updated when a setting
58          *       changes.  At this point in time it doesn't matter (e.g. /set
59          *       is documented to change server settings only)
60          *
61          * TODO: Local caching of settings is not optimal and should at some stage
62          *       be updated to use a global settings object for getting thse values
63          *       (as opposed to the this local caching). This can be addressed in
64          *       a later release.
65          */
66         m_cache_trilinear_filter  = g_settings->getBool("trilinear_filter");
67         m_cache_bilinear_filter   = g_settings->getBool("bilinear_filter");
68         m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
69
70 }
71
72 ClientMap::~ClientMap()
73 {
74         /*JMutexAutoLock lock(mesh_mutex);
75
76         if(mesh != NULL)
77         {
78                 mesh->drop();
79                 mesh = NULL;
80         }*/
81 }
82
83 MapSector * ClientMap::emergeSector(v2s16 p2d)
84 {
85         DSTACK(__FUNCTION_NAME);
86         // Check that it doesn't exist already
87         try{
88                 return getSectorNoGenerate(p2d);
89         }
90         catch(InvalidPositionException &e)
91         {
92         }
93
94         // Create a sector
95         ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
96
97         {
98                 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
99                 m_sectors[p2d] = sector;
100         }
101
102         return sector;
103 }
104
105 #if 0
106 void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
107 {
108         DSTACK(__FUNCTION_NAME);
109         ClientMapSector *sector = NULL;
110
111         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
112
113         core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
114
115         if(n != NULL)
116         {
117                 sector = (ClientMapSector*)n->getValue();
118                 assert(sector->getId() == MAPSECTOR_CLIENT);
119         }
120         else
121         {
122                 sector = new ClientMapSector(this, p2d);
123                 {
124                         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
125                         m_sectors.insert(p2d, sector);
126                 }
127         }
128
129         sector->deSerialize(is);
130 }
131 #endif
132
133 void ClientMap::OnRegisterSceneNode()
134 {
135         if(IsVisible)
136         {
137                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
138                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
139         }
140
141         ISceneNode::OnRegisterSceneNode();
142 }
143
144 static bool isOccluded(Map *map, v3s16 p0, v3s16 p1, float step, float stepfac,
145                 float start_off, float end_off, u32 needed_count, INodeDefManager *nodemgr)
146 {
147         float d0 = (float)BS * p0.getDistanceFrom(p1);
148         v3s16 u0 = p1 - p0;
149         v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
150         uf.normalize();
151         v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
152         u32 count = 0;
153         for(float s=start_off; s<d0+end_off; s+=step){
154                 v3f pf = p0f + uf * s;
155                 v3s16 p = floatToInt(pf, BS);
156                 MapNode n = map->getNodeNoEx(p);
157                 bool is_transparent = false;
158                 const ContentFeatures &f = nodemgr->get(n);
159                 if(f.solidness == 0)
160                         is_transparent = (f.visual_solidness != 2);
161                 else
162                         is_transparent = (f.solidness != 2);
163                 if(!is_transparent){
164                         count++;
165                         if(count >= needed_count)
166                                 return true;
167                 }
168                 step *= stepfac;
169         }
170         return false;
171 }
172
173 void ClientMap::updateDrawList(video::IVideoDriver* driver)
174 {
175         ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
176         g_profiler->add("CM::updateDrawList() count", 1);
177
178         INodeDefManager *nodemgr = m_gamedef->ndef();
179
180         for(std::map<v3s16, MapBlock*>::iterator
181                         i = m_drawlist.begin();
182                         i != m_drawlist.end(); ++i)
183         {
184                 MapBlock *block = i->second;
185                 block->refDrop();
186         }
187         m_drawlist.clear();
188
189         m_camera_mutex.Lock();
190         v3f camera_position = m_camera_position;
191         v3f camera_direction = m_camera_direction;
192         f32 camera_fov = m_camera_fov;
193         v3s16 camera_offset = m_camera_offset;
194         m_camera_mutex.Unlock();
195
196         // Use a higher fov to accomodate faster camera movements.
197         // Blocks are cropped better when they are drawn.
198         // Or maybe they aren't? Well whatever.
199         camera_fov *= 1.2;
200
201         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
202         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
203         v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
204         v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
205         // Take a fair amount as we will be dropping more out later
206         // Umm... these additions are a bit strange but they are needed.
207         v3s16 p_blocks_min(
208                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
209                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
210                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
211         v3s16 p_blocks_max(
212                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
213                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
214                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
215
216         // Number of blocks in rendering range
217         u32 blocks_in_range = 0;
218         // Number of blocks occlusion culled
219         u32 blocks_occlusion_culled = 0;
220         // Number of blocks in rendering range but don't have a mesh
221         u32 blocks_in_range_without_mesh = 0;
222         // Blocks that had mesh that would have been drawn according to
223         // rendering range (if max blocks limit didn't kick in)
224         u32 blocks_would_have_drawn = 0;
225         // Blocks that were drawn and had a mesh
226         u32 blocks_drawn = 0;
227         // Blocks which had a corresponding meshbuffer for this pass
228         //u32 blocks_had_pass_meshbuf = 0;
229         // Blocks from which stuff was actually drawn
230         //u32 blocks_without_stuff = 0;
231         // Distance to farthest drawn block
232         float farthest_drawn = 0;
233
234         for(std::map<v2s16, MapSector*>::iterator
235                         si = m_sectors.begin();
236                         si != m_sectors.end(); ++si)
237         {
238                 MapSector *sector = si->second;
239                 v2s16 sp = sector->getPos();
240
241                 if(m_control.range_all == false)
242                 {
243                         if(sp.X < p_blocks_min.X
244                         || sp.X > p_blocks_max.X
245                         || sp.Y < p_blocks_min.Z
246                         || sp.Y > p_blocks_max.Z)
247                                 continue;
248                 }
249
250                 std::list< MapBlock * > sectorblocks;
251                 sector->getBlocks(sectorblocks);
252
253                 /*
254                         Loop through blocks in sector
255                 */
256
257                 u32 sector_blocks_drawn = 0;
258
259                 std::list< MapBlock * >::iterator i;
260                 for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++)
261                 {
262                         MapBlock *block = *i;
263
264                         /*
265                                 Compare block position to camera position, skip
266                                 if not seen on display
267                         */
268
269                         if (block->mesh != NULL)
270                                 block->mesh->updateCameraOffset(m_camera_offset);
271
272                         float range = 100000 * BS;
273                         if(m_control.range_all == false)
274                                 range = m_control.wanted_range * BS;
275
276                         float d = 0.0;
277                         if(isBlockInSight(block->getPos(), camera_position,
278                                         camera_direction, camera_fov,
279                                         range, &d) == false)
280                         {
281                                 continue;
282                         }
283
284                         // This is ugly (spherical distance limit?)
285                         /*if(m_control.range_all == false &&
286                                         d - 0.5*BS*MAP_BLOCKSIZE > range)
287                                 continue;*/
288
289                         blocks_in_range++;
290
291                         /*
292                                 Ignore if mesh doesn't exist
293                         */
294                         {
295                                 //JMutexAutoLock lock(block->mesh_mutex);
296
297                                 if(block->mesh == NULL){
298                                         blocks_in_range_without_mesh++;
299                                         continue;
300                                 }
301                         }
302
303                         /*
304                                 Occlusion culling
305                         */
306
307                         // No occlusion culling when free_move is on and camera is
308                         // inside ground
309                         bool occlusion_culling_enabled = true;
310                         if(g_settings->getBool("free_move")){
311                                 MapNode n = getNodeNoEx(cam_pos_nodes);
312                                 if(n.getContent() == CONTENT_IGNORE ||
313                                                 nodemgr->get(n).solidness == 2)
314                                         occlusion_culling_enabled = false;
315                         }
316
317                         v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
318                         cpn += v3s16(MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2);
319                         float step = BS*1;
320                         float stepfac = 1.1;
321                         float startoff = BS*1;
322                         float endoff = -BS*MAP_BLOCKSIZE*1.42*1.42;
323                         v3s16 spn = cam_pos_nodes + v3s16(0,0,0);
324                         s16 bs2 = MAP_BLOCKSIZE/2 + 1;
325                         u32 needed_count = 1;
326                         if(
327                                 occlusion_culling_enabled &&
328                                 isOccluded(this, spn, cpn + v3s16(0,0,0),
329                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
330                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2),
331                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
332                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2),
333                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
334                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2),
335                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
336                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2),
337                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
338                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2),
339                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
340                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2),
341                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
342                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2),
343                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
344                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2),
345                                         step, stepfac, startoff, endoff, needed_count, nodemgr)
346                         )
347                         {
348                                 blocks_occlusion_culled++;
349                                 continue;
350                         }
351
352                         // This block is in range. Reset usage timer.
353                         block->resetUsageTimer();
354
355                         // Limit block count in case of a sudden increase
356                         blocks_would_have_drawn++;
357                         if(blocks_drawn >= m_control.wanted_max_blocks
358                                         && m_control.range_all == false
359                                         && d > m_control.wanted_min_range * BS)
360                                 continue;
361
362                         // Add to set
363                         block->refGrab();
364                         m_drawlist[block->getPos()] = block;
365
366                         sector_blocks_drawn++;
367                         blocks_drawn++;
368                         if(d/BS > farthest_drawn)
369                                 farthest_drawn = d/BS;
370
371                 } // foreach sectorblocks
372
373                 if(sector_blocks_drawn != 0)
374                         m_last_drawn_sectors.insert(sp);
375         }
376
377         m_control.blocks_would_have_drawn = blocks_would_have_drawn;
378         m_control.blocks_drawn = blocks_drawn;
379         m_control.farthest_drawn = farthest_drawn;
380
381         g_profiler->avg("CM: blocks in range", blocks_in_range);
382         g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
383         if(blocks_in_range != 0)
384                 g_profiler->avg("CM: blocks in range without mesh (frac)",
385                                 (float)blocks_in_range_without_mesh/blocks_in_range);
386         g_profiler->avg("CM: blocks drawn", blocks_drawn);
387         g_profiler->avg("CM: farthest drawn", farthest_drawn);
388         g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
389 }
390
391 struct MeshBufList
392 {
393         video::SMaterial m;
394         std::list<scene::IMeshBuffer*> bufs;
395 };
396
397 struct MeshBufListList
398 {
399         std::list<MeshBufList> lists;
400
401         void clear()
402         {
403                 lists.clear();
404         }
405
406         void add(scene::IMeshBuffer *buf)
407         {
408                 for(std::list<MeshBufList>::iterator i = lists.begin();
409                                 i != lists.end(); ++i){
410                         MeshBufList &l = *i;
411                         video::SMaterial &m = buf->getMaterial();
412
413                         // comparing a full material is quite expensive so we don't do it if
414                         // not even first texture is equal
415                         if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
416                                 continue;
417
418                         if (l.m == m) {
419                                 l.bufs.push_back(buf);
420                                 return;
421                         }
422                 }
423                 MeshBufList l;
424                 l.m = buf->getMaterial();
425                 l.bufs.push_back(buf);
426                 lists.push_back(l);
427         }
428 };
429
430 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
431 {
432         DSTACK(__FUNCTION_NAME);
433
434         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
435
436         std::string prefix;
437         if(pass == scene::ESNRP_SOLID)
438                 prefix = "CM: solid: ";
439         else
440                 prefix = "CM: transparent: ";
441
442         /*
443                 This is called two times per frame, reset on the non-transparent one
444         */
445         if(pass == scene::ESNRP_SOLID)
446         {
447                 m_last_drawn_sectors.clear();
448         }
449
450         /*
451                 Get time for measuring timeout.
452
453                 Measuring time is very useful for long delays when the
454                 machine is swapping a lot.
455         */
456         int time1 = time(0);
457
458         /*
459                 Get animation parameters
460         */
461         float animation_time = m_client->getAnimationTime();
462         int crack = m_client->getCrackLevel();
463         u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
464
465         m_camera_mutex.Lock();
466         v3f camera_position = m_camera_position;
467         v3f camera_direction = m_camera_direction;
468         f32 camera_fov = m_camera_fov;
469         m_camera_mutex.Unlock();
470
471         /*
472                 Get all blocks and draw all visible ones
473         */
474
475         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
476
477         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
478
479         v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
480         v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
481
482         // Take a fair amount as we will be dropping more out later
483         // Umm... these additions are a bit strange but they are needed.
484         v3s16 p_blocks_min(
485                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
486                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
487                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
488         v3s16 p_blocks_max(
489                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
490                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
491                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
492
493         u32 vertex_count = 0;
494         u32 meshbuffer_count = 0;
495
496         // For limiting number of mesh animations per frame
497         u32 mesh_animate_count = 0;
498         u32 mesh_animate_count_far = 0;
499
500         // Blocks that were drawn and had a mesh
501         u32 blocks_drawn = 0;
502         // Blocks which had a corresponding meshbuffer for this pass
503         u32 blocks_had_pass_meshbuf = 0;
504         // Blocks from which stuff was actually drawn
505         u32 blocks_without_stuff = 0;
506
507         /*
508                 Draw the selected MapBlocks
509         */
510
511         {
512         ScopeProfiler sp(g_profiler, prefix+"drawing blocks", SPT_AVG);
513
514         MeshBufListList drawbufs;
515
516         for(std::map<v3s16, MapBlock*>::iterator
517                         i = m_drawlist.begin();
518                         i != m_drawlist.end(); ++i)
519         {
520                 MapBlock *block = i->second;
521
522                 // If the mesh of the block happened to get deleted, ignore it
523                 if(block->mesh == NULL)
524                         continue;
525
526                 float d = 0.0;
527                 if(isBlockInSight(block->getPos(), camera_position,
528                                 camera_direction, camera_fov,
529                                 100000*BS, &d) == false)
530                 {
531                         continue;
532                 }
533
534                 // Mesh animation
535                 {
536                         //JMutexAutoLock lock(block->mesh_mutex);
537                         MapBlockMesh *mapBlockMesh = block->mesh;
538                         assert(mapBlockMesh);
539                         // Pretty random but this should work somewhat nicely
540                         bool faraway = d >= BS*50;
541                         //bool faraway = d >= m_control.wanted_range * BS;
542                         if(mapBlockMesh->isAnimationForced() ||
543                                         !faraway ||
544                                         mesh_animate_count_far < (m_control.range_all ? 200 : 50))
545                         {
546                                 bool animated = mapBlockMesh->animate(
547                                                 faraway,
548                                                 animation_time,
549                                                 crack,
550                                                 daynight_ratio);
551                                 if(animated)
552                                         mesh_animate_count++;
553                                 if(animated && faraway)
554                                         mesh_animate_count_far++;
555                         }
556                         else
557                         {
558                                 mapBlockMesh->decreaseAnimationForceTimer();
559                         }
560                 }
561
562                 /*
563                         Get the meshbuffers of the block
564                 */
565                 {
566                         //JMutexAutoLock lock(block->mesh_mutex);
567
568                         MapBlockMesh *mapBlockMesh = block->mesh;
569                         assert(mapBlockMesh);
570
571                         scene::SMesh *mesh = mapBlockMesh->getMesh();
572                         assert(mesh);
573
574                         u32 c = mesh->getMeshBufferCount();
575                         for(u32 i=0; i<c; i++)
576                         {
577                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
578
579                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, m_cache_trilinear_filter);
580                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, m_cache_bilinear_filter);
581                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, m_cache_anistropic_filter);
582
583                                 const video::SMaterial& material = buf->getMaterial();
584                                 video::IMaterialRenderer* rnd =
585                                                 driver->getMaterialRenderer(material.MaterialType);
586                                 bool transparent = (rnd && rnd->isTransparent());
587                                 if(transparent == is_transparent_pass)
588                                 {
589                                         if(buf->getVertexCount() == 0)
590                                                 errorstream<<"Block ["<<analyze_block(block)
591                                                                 <<"] contains an empty meshbuf"<<std::endl;
592                                         drawbufs.add(buf);
593                                 }
594                         }
595                 }
596         }
597
598         std::list<MeshBufList> &lists = drawbufs.lists;
599
600         int timecheck_counter = 0;
601         for(std::list<MeshBufList>::iterator i = lists.begin();
602                         i != lists.end(); ++i)
603         {
604                 {
605                         timecheck_counter++;
606                         if(timecheck_counter > 50)
607                         {
608                                 timecheck_counter = 0;
609                                 int time2 = time(0);
610                                 if(time2 > time1 + 4)
611                                 {
612                                         infostream<<"ClientMap::renderMap(): "
613                                                 "Rendering takes ages, returning."
614                                                 <<std::endl;
615                                         return;
616                                 }
617                         }
618                 }
619
620                 MeshBufList &list = *i;
621
622                 driver->setMaterial(list.m);
623
624                 for(std::list<scene::IMeshBuffer*>::iterator j = list.bufs.begin();
625                                 j != list.bufs.end(); ++j)
626                 {
627                         scene::IMeshBuffer *buf = *j;
628                         driver->drawMeshBuffer(buf);
629                         vertex_count += buf->getVertexCount();
630                         meshbuffer_count++;
631                 }
632 #if 0
633                 /*
634                         Draw the faces of the block
635                 */
636                 {
637                         //JMutexAutoLock lock(block->mesh_mutex);
638
639                         MapBlockMesh *mapBlockMesh = block->mesh;
640                         assert(mapBlockMesh);
641
642                         scene::SMesh *mesh = mapBlockMesh->getMesh();
643                         assert(mesh);
644
645                         u32 c = mesh->getMeshBufferCount();
646                         bool stuff_actually_drawn = false;
647                         for(u32 i=0; i<c; i++)
648                         {
649                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
650                                 const video::SMaterial& material = buf->getMaterial();
651                                 video::IMaterialRenderer* rnd =
652                                                 driver->getMaterialRenderer(material.MaterialType);
653                                 bool transparent = (rnd && rnd->isTransparent());
654                                 // Render transparent on transparent pass and likewise.
655                                 if(transparent == is_transparent_pass)
656                                 {
657                                         if(buf->getVertexCount() == 0)
658                                                 errorstream<<"Block ["<<analyze_block(block)
659                                                                 <<"] contains an empty meshbuf"<<std::endl;
660                                         /*
661                                                 This *shouldn't* hurt too much because Irrlicht
662                                                 doesn't change opengl textures if the old
663                                                 material has the same texture.
664                                         */
665                                         driver->setMaterial(buf->getMaterial());
666                                         driver->drawMeshBuffer(buf);
667                                         vertex_count += buf->getVertexCount();
668                                         meshbuffer_count++;
669                                         stuff_actually_drawn = true;
670                                 }
671                         }
672                         if(stuff_actually_drawn)
673                                 blocks_had_pass_meshbuf++;
674                         else
675                                 blocks_without_stuff++;
676                 }
677 #endif
678         }
679         } // ScopeProfiler
680
681         // Log only on solid pass because values are the same
682         if(pass == scene::ESNRP_SOLID){
683                 g_profiler->avg("CM: animated meshes", mesh_animate_count);
684                 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
685         }
686
687         g_profiler->avg(prefix+"vertices drawn", vertex_count);
688         if(blocks_had_pass_meshbuf != 0)
689                 g_profiler->avg(prefix+"meshbuffers per block",
690                                 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
691         if(blocks_drawn != 0)
692                 g_profiler->avg(prefix+"empty blocks (frac)",
693                                 (float)blocks_without_stuff / blocks_drawn);
694
695         /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
696                         <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
697 }
698
699 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
700                 float step_multiplier, float start_distance, float end_distance,
701                 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
702                 int *result, bool *sunlight_seen)
703 {
704         int brightness_sum = 0;
705         int brightness_count = 0;
706         float distance = start_distance;
707         dir.normalize();
708         v3f pf = p0;
709         pf += dir * distance;
710         int noncount = 0;
711         bool nonlight_seen = false;
712         bool allow_allowing_non_sunlight_propagates = false;
713         bool allow_non_sunlight_propagates = false;
714         // Check content nearly at camera position
715         {
716                 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
717                 MapNode n = map->getNodeNoEx(p);
718                 if(ndef->get(n).param_type == CPT_LIGHT &&
719                                 !ndef->get(n).sunlight_propagates)
720                         allow_allowing_non_sunlight_propagates = true;
721         }
722         // If would start at CONTENT_IGNORE, start closer
723         {
724                 v3s16 p = floatToInt(pf, BS);
725                 MapNode n = map->getNodeNoEx(p);
726                 if(n.getContent() == CONTENT_IGNORE){
727                         float newd = 2*BS;
728                         pf = p0 + dir * 2*newd;
729                         distance = newd;
730                         sunlight_min_d = 0;
731                 }
732         }
733         for(int i=0; distance < end_distance; i++){
734                 pf += dir * step;
735                 distance += step;
736                 step *= step_multiplier;
737
738                 v3s16 p = floatToInt(pf, BS);
739                 MapNode n = map->getNodeNoEx(p);
740                 if(allow_allowing_non_sunlight_propagates && i == 0 &&
741                                 ndef->get(n).param_type == CPT_LIGHT &&
742                                 !ndef->get(n).sunlight_propagates){
743                         allow_non_sunlight_propagates = true;
744                 }
745                 if(ndef->get(n).param_type != CPT_LIGHT ||
746                                 (!ndef->get(n).sunlight_propagates &&
747                                         !allow_non_sunlight_propagates)){
748                         nonlight_seen = true;
749                         noncount++;
750                         if(noncount >= 4)
751                                 break;
752                         continue;
753                 }
754                 if(distance >= sunlight_min_d && *sunlight_seen == false
755                                 && nonlight_seen == false)
756                         if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
757                                 *sunlight_seen = true;
758                 noncount = 0;
759                 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
760                 brightness_count++;
761         }
762         *result = 0;
763         if(brightness_count == 0)
764                 return false;
765         *result = brightness_sum / brightness_count;
766         /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
767                         <<(*result)<<std::endl;*/
768         return true;
769 }
770
771 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
772                 int oldvalue, bool *sunlight_seen_result)
773 {
774         const bool debugprint = false;
775         INodeDefManager *ndef = m_gamedef->ndef();
776         static v3f z_directions[50] = {
777                 v3f(-100, 0, 0)
778         };
779         static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
780                 -1000,
781         };
782         if(z_directions[0].X < -99){
783                 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
784                         z_directions[i] = v3f(
785                                 0.01 * myrand_range(-100, 100),
786                                 1.0,
787                                 0.01 * myrand_range(-100, 100)
788                         );
789                         z_offsets[i] = 0.01 * myrand_range(0,100);
790                 }
791         }
792         if(debugprint)
793                 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
794         int sunlight_seen_count = 0;
795         float sunlight_min_d = max_d*0.8;
796         if(sunlight_min_d > 35*BS)
797                 sunlight_min_d = 35*BS;
798         std::vector<int> values;
799         for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
800                 v3f z_dir = z_directions[i];
801                 z_dir.normalize();
802                 core::CMatrix4<f32> a;
803                 a.buildRotateFromTo(v3f(0,1,0), z_dir);
804                 v3f dir = m_camera_direction;
805                 a.rotateVect(dir);
806                 int br = 0;
807                 float step = BS*1.5;
808                 if(max_d > 35*BS)
809                         step = max_d / 35 * 1.5;
810                 float off = step * z_offsets[i];
811                 bool sunlight_seen_now = false;
812                 bool ok = getVisibleBrightness(this, m_camera_position, dir,
813                                 step, 1.0, max_d*0.6+off, max_d, ndef, daylight_factor,
814                                 sunlight_min_d,
815                                 &br, &sunlight_seen_now);
816                 if(sunlight_seen_now)
817                         sunlight_seen_count++;
818                 if(!ok)
819                         continue;
820                 values.push_back(br);
821                 // Don't try too much if being in the sun is clear
822                 if(sunlight_seen_count >= 20)
823                         break;
824         }
825         int brightness_sum = 0;
826         int brightness_count = 0;
827         std::sort(values.begin(), values.end());
828         u32 num_values_to_use = values.size();
829         if(num_values_to_use >= 10)
830                 num_values_to_use -= num_values_to_use/2;
831         else if(num_values_to_use >= 7)
832                 num_values_to_use -= num_values_to_use/3;
833         u32 first_value_i = (values.size() - num_values_to_use) / 2;
834         if(debugprint){
835                 for(u32 i=0; i < first_value_i; i++)
836                         std::cerr<<values[i]<<" ";
837                 std::cerr<<"[";
838         }
839         for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
840                 if(debugprint)
841                         std::cerr<<values[i]<<" ";
842                 brightness_sum += values[i];
843                 brightness_count++;
844         }
845         if(debugprint){
846                 std::cerr<<"]";
847                 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
848                         std::cerr<<values[i]<<" ";
849         }
850         int ret = 0;
851         if(brightness_count == 0){
852                 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
853                 if(ndef->get(n).param_type == CPT_LIGHT){
854                         ret = decode_light(n.getLightBlend(daylight_factor, ndef));
855                 } else {
856                         ret = oldvalue;
857                         //ret = blend_light(255, 0, daylight_factor);
858                 }
859         } else {
860                 /*float pre = (float)brightness_sum / (float)brightness_count;
861                 float tmp = pre;
862                 const float d = 0.2;
863                 pre *= 1.0 + d*2;
864                 pre -= tmp * d;
865                 int preint = pre;
866                 ret = MYMAX(0, MYMIN(255, preint));*/
867                 ret = brightness_sum / brightness_count;
868         }
869         if(debugprint)
870                 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
871                                 <<sunlight_seen_count<<std::endl;
872         *sunlight_seen_result = (sunlight_seen_count > 0);
873         return ret;
874 }
875
876 void ClientMap::renderPostFx(CameraMode cam_mode)
877 {
878         INodeDefManager *nodemgr = m_gamedef->ndef();
879
880         // Sadly ISceneManager has no "post effects" render pass, in that case we
881         // could just register for that and handle it in renderMap().
882
883         m_camera_mutex.Lock();
884         v3f camera_position = m_camera_position;
885         m_camera_mutex.Unlock();
886
887         MapNode n = getNodeNoEx(floatToInt(camera_position, BS));
888
889         // - If the player is in a solid node, make everything black.
890         // - If the player is in liquid, draw a semi-transparent overlay.
891         // - Do not if player is in third person mode
892         const ContentFeatures& features = nodemgr->get(n);
893         video::SColor post_effect_color = features.post_effect_color;
894         if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
895                         m_gamedef->checkLocalPrivilege("noclip")) &&
896                         cam_mode == CAMERA_MODE_FIRST)
897         {
898                 post_effect_color = video::SColor(255, 0, 0, 0);
899         }
900         if (post_effect_color.getAlpha() != 0)
901         {
902                 // Draw a full-screen rectangle
903                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
904                 v2u32 ss = driver->getScreenSize();
905                 core::rect<s32> rect(0,0, ss.X, ss.Y);
906                 driver->draw2DRectangle(post_effect_color, rect);
907         }
908 }
909
910 void ClientMap::PrintInfo(std::ostream &out)
911 {
912         out<<"ClientMap: ";
913 }
914
915