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