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