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