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