3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "clientmap.h"
22 #include "mapblock_mesh.h"
23 #include <IMaterialRenderer.h>
26 #include "mapsector.h"
31 #include "camera.h" // CameraModes
32 #include "util/basic_macros.h"
37 MapDrawControl &control,
38 scene::ISceneNode* parent,
39 scene::ISceneManager* mgr,
42 Map(dout_client, client),
43 scene::ISceneNode(parent, mgr, id),
46 m_camera_position(0,0,0),
47 m_camera_direction(0,0,1),
50 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
51 BS*1000000,BS*1000000,BS*1000000);
53 /* TODO: Add a callback function so these can be updated when a setting
54 * changes. At this point in time it doesn't matter (e.g. /set
55 * is documented to change server settings only)
57 * TODO: Local caching of settings is not optimal and should at some stage
58 * be updated to use a global settings object for getting thse values
59 * (as opposed to the this local caching). This can be addressed in
62 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
63 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
64 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
68 ClientMap::~ClientMap()
70 /*MutexAutoLock lock(mesh_mutex);
79 MapSector * ClientMap::emergeSector(v2s16 p2d)
81 DSTACK(FUNCTION_NAME);
82 // Check that it doesn't exist already
84 return getSectorNoGenerate(p2d);
86 catch(InvalidPositionException &e)
91 ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
94 //MutexAutoLock lock(m_sector_mutex); // Bulk comment-out
95 m_sectors[p2d] = sector;
101 void ClientMap::OnRegisterSceneNode()
105 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
106 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
109 ISceneNode::OnRegisterSceneNode();
112 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
113 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
115 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
116 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
117 // can exceed the range of v3s16 when a large view range is used near the
120 cam_pos_nodes.X - box_nodes_d.X,
121 cam_pos_nodes.Y - box_nodes_d.Y,
122 cam_pos_nodes.Z - box_nodes_d.Z);
124 cam_pos_nodes.X + box_nodes_d.X,
125 cam_pos_nodes.Y + box_nodes_d.Y,
126 cam_pos_nodes.Z + box_nodes_d.Z);
127 // Take a fair amount as we will be dropping more out later
128 // Umm... these additions are a bit strange but they are needed.
129 *p_blocks_min = v3s16(
130 p_nodes_min.X / MAP_BLOCKSIZE - 3,
131 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
132 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
133 *p_blocks_max = v3s16(
134 p_nodes_max.X / MAP_BLOCKSIZE + 1,
135 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
136 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
139 void ClientMap::updateDrawList(video::IVideoDriver* driver)
141 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
142 g_profiler->add("CM::updateDrawList() count", 1);
144 for (std::map<v3s16, MapBlock*>::iterator i = m_drawlist.begin();
145 i != m_drawlist.end(); ++i) {
146 MapBlock *block = i->second;
151 v3f camera_position = m_camera_position;
152 v3f camera_direction = m_camera_direction;
153 f32 camera_fov = m_camera_fov;
155 // Use a higher fov to accomodate faster camera movements.
156 // Blocks are cropped better when they are drawn.
157 // Or maybe they aren't? Well whatever.
160 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
163 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
165 // Number of blocks in rendering range
166 u32 blocks_in_range = 0;
167 // Number of blocks occlusion culled
168 u32 blocks_occlusion_culled = 0;
169 // Number of blocks in rendering range but don't have a mesh
170 u32 blocks_in_range_without_mesh = 0;
171 // Blocks that had mesh that would have been drawn according to
172 // rendering range (if max blocks limit didn't kick in)
173 u32 blocks_would_have_drawn = 0;
174 // Blocks that were drawn and had a mesh
175 u32 blocks_drawn = 0;
176 // Blocks which had a corresponding meshbuffer for this pass
177 //u32 blocks_had_pass_meshbuf = 0;
178 // Blocks from which stuff was actually drawn
179 //u32 blocks_without_stuff = 0;
180 // Distance to farthest drawn block
181 float farthest_drawn = 0;
183 // No occlusion culling when free_move is on and camera is
185 bool occlusion_culling_enabled = true;
186 if (g_settings->getBool("free_move")) {
187 MapNode n = getNodeNoEx(cam_pos_nodes);
188 if (n.getContent() == CONTENT_IGNORE ||
189 m_nodedef->get(n).solidness == 2)
190 occlusion_culling_enabled = false;
193 for (std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
194 si != m_sectors.end(); ++si) {
195 MapSector *sector = si->second;
196 v2s16 sp = sector->getPos();
198 if (m_control.range_all == false) {
199 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
200 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
204 MapBlockVect sectorblocks;
205 sector->getBlocks(sectorblocks);
208 Loop through blocks in sector
211 u32 sector_blocks_drawn = 0;
213 for (MapBlockVect::iterator i = sectorblocks.begin();
214 i != sectorblocks.end(); ++i) {
215 MapBlock *block = *i;
218 Compare block position to camera position, skip
219 if not seen on display
222 if (block->mesh != NULL)
223 block->mesh->updateCameraOffset(m_camera_offset);
225 float range = 100000 * BS;
226 if (m_control.range_all == false)
227 range = m_control.wanted_range * BS;
230 if (!isBlockInSight(block->getPos(), camera_position,
231 camera_direction, camera_fov, range, &d))
237 Ignore if mesh doesn't exist
239 if (block->mesh == NULL) {
240 blocks_in_range_without_mesh++;
247 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
248 blocks_occlusion_culled++;
252 // This block is in range. Reset usage timer.
253 block->resetUsageTimer();
255 // Limit block count in case of a sudden increase
256 blocks_would_have_drawn++;
257 if (blocks_drawn >= m_control.wanted_max_blocks &&
258 !m_control.range_all &&
259 d > m_control.wanted_range * BS)
264 m_drawlist[block->getPos()] = block;
266 sector_blocks_drawn++;
268 if (d / BS > farthest_drawn)
269 farthest_drawn = d / BS;
271 } // foreach sectorblocks
273 if (sector_blocks_drawn != 0)
274 m_last_drawn_sectors.insert(sp);
277 m_control.blocks_would_have_drawn = blocks_would_have_drawn;
278 m_control.blocks_drawn = blocks_drawn;
279 m_control.farthest_drawn = farthest_drawn;
281 g_profiler->avg("CM: blocks in range", blocks_in_range);
282 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
283 if (blocks_in_range != 0)
284 g_profiler->avg("CM: blocks in range without mesh (frac)",
285 (float)blocks_in_range_without_mesh / blocks_in_range);
286 g_profiler->avg("CM: blocks drawn", blocks_drawn);
287 g_profiler->avg("CM: farthest drawn", farthest_drawn);
288 g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
294 * Specifies in which layer the list is.
295 * All lists which are in a lower layer are rendered before this list.
299 std::vector<scene::IMeshBuffer*> bufs;
302 struct MeshBufListList
304 std::vector<MeshBufList> lists;
311 void add(scene::IMeshBuffer *buf, u8 layer)
313 const video::SMaterial &m = buf->getMaterial();
314 for(std::vector<MeshBufList>::iterator i = lists.begin();
315 i != lists.end(); ++i){
318 // comparing a full material is quite expensive so we don't do it if
319 // not even first texture is equal
320 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
327 l.bufs.push_back(buf);
334 l.bufs.push_back(buf);
339 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
341 DSTACK(FUNCTION_NAME);
343 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
346 if (pass == scene::ESNRP_SOLID)
347 prefix = "CM: solid: ";
349 prefix = "CM: transparent: ";
352 This is called two times per frame, reset on the non-transparent one
354 if (pass == scene::ESNRP_SOLID)
355 m_last_drawn_sectors.clear();
358 Get time for measuring timeout.
360 Measuring time is very useful for long delays when the
361 machine is swapping a lot.
366 Get animation parameters
368 float animation_time = m_client->getAnimationTime();
369 int crack = m_client->getCrackLevel();
370 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
372 v3f camera_position = m_camera_position;
373 v3f camera_direction = m_camera_direction;
374 f32 camera_fov = m_camera_fov;
377 Get all blocks and draw all visible ones
380 u32 vertex_count = 0;
381 u32 meshbuffer_count = 0;
383 // For limiting number of mesh animations per frame
384 u32 mesh_animate_count = 0;
385 u32 mesh_animate_count_far = 0;
387 // Blocks that were drawn and had a mesh
388 u32 blocks_drawn = 0;
389 // Blocks which had a corresponding meshbuffer for this pass
390 u32 blocks_had_pass_meshbuf = 0;
391 // Blocks from which stuff was actually drawn
392 u32 blocks_without_stuff = 0;
395 Draw the selected MapBlocks
399 ScopeProfiler sp(g_profiler, prefix + "drawing blocks", SPT_AVG);
401 MeshBufListList drawbufs;
403 for (std::map<v3s16, MapBlock*>::iterator i = m_drawlist.begin();
404 i != m_drawlist.end(); ++i) {
405 MapBlock *block = i->second;
407 // If the mesh of the block happened to get deleted, ignore it
408 if (block->mesh == NULL)
412 if (!isBlockInSight(block->getPos(), camera_position,
413 camera_direction, camera_fov, 100000 * BS, &d))
417 if (pass == scene::ESNRP_SOLID) {
418 //MutexAutoLock lock(block->mesh_mutex);
419 MapBlockMesh *mapBlockMesh = block->mesh;
420 assert(mapBlockMesh);
421 // Pretty random but this should work somewhat nicely
422 bool faraway = d >= BS * 50;
423 //bool faraway = d >= m_control.wanted_range * BS;
424 if (mapBlockMesh->isAnimationForced() || !faraway ||
425 mesh_animate_count_far < (m_control.range_all ? 200 : 50)) {
426 bool animated = mapBlockMesh->animate(faraway, animation_time,
427 crack, daynight_ratio);
429 mesh_animate_count++;
430 if (animated && faraway)
431 mesh_animate_count_far++;
433 mapBlockMesh->decreaseAnimationForceTimer();
438 Get the meshbuffers of the block
441 //MutexAutoLock lock(block->mesh_mutex);
443 MapBlockMesh *mapBlockMesh = block->mesh;
444 assert(mapBlockMesh);
446 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
447 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
450 u32 c = mesh->getMeshBufferCount();
451 for (u32 i = 0; i < c; i++) {
452 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
454 video::SMaterial& material = buf->getMaterial();
455 video::IMaterialRenderer* rnd =
456 driver->getMaterialRenderer(material.MaterialType);
457 bool transparent = (rnd && rnd->isTransparent());
458 if (transparent == is_transparent_pass) {
459 if (buf->getVertexCount() == 0)
460 errorstream << "Block [" << analyze_block(block)
461 << "] contains an empty meshbuf" << std::endl;
463 material.setFlag(video::EMF_TRILINEAR_FILTER,
464 m_cache_trilinear_filter);
465 material.setFlag(video::EMF_BILINEAR_FILTER,
466 m_cache_bilinear_filter);
467 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
468 m_cache_anistropic_filter);
469 material.setFlag(video::EMF_WIREFRAME,
470 m_control.show_wireframe);
472 drawbufs.add(buf, layer);
479 std::vector<MeshBufList> &lists = drawbufs.lists;
481 int timecheck_counter = 0;
482 for (std::vector<MeshBufList>::iterator i = lists.begin();
483 i != lists.end(); ++i) {
485 if (timecheck_counter > 50) {
486 timecheck_counter = 0;
488 if (time2 > time1 + 4) {
489 infostream << "ClientMap::renderMap(): "
490 "Rendering takes ages, returning."
496 MeshBufList &list = *i;
498 driver->setMaterial(list.m);
500 for (std::vector<scene::IMeshBuffer*>::iterator j = list.bufs.begin();
501 j != list.bufs.end(); ++j) {
502 scene::IMeshBuffer *buf = *j;
503 driver->drawMeshBuffer(buf);
504 vertex_count += buf->getVertexCount();
511 // Log only on solid pass because values are the same
512 if (pass == scene::ESNRP_SOLID) {
513 g_profiler->avg("CM: animated meshes", mesh_animate_count);
514 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
517 g_profiler->avg(prefix + "vertices drawn", vertex_count);
518 if (blocks_had_pass_meshbuf != 0)
519 g_profiler->avg(prefix + "meshbuffers per block",
520 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
521 if (blocks_drawn != 0)
522 g_profiler->avg(prefix + "empty blocks (frac)",
523 (float)blocks_without_stuff / blocks_drawn);
525 /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
526 <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
529 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
530 float step_multiplier, float start_distance, float end_distance,
531 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
532 int *result, bool *sunlight_seen)
534 int brightness_sum = 0;
535 int brightness_count = 0;
536 float distance = start_distance;
539 pf += dir * distance;
541 bool nonlight_seen = false;
542 bool allow_allowing_non_sunlight_propagates = false;
543 bool allow_non_sunlight_propagates = false;
544 // Check content nearly at camera position
546 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
547 MapNode n = map->getNodeNoEx(p);
548 if(ndef->get(n).param_type == CPT_LIGHT &&
549 !ndef->get(n).sunlight_propagates)
550 allow_allowing_non_sunlight_propagates = true;
552 // If would start at CONTENT_IGNORE, start closer
554 v3s16 p = floatToInt(pf, BS);
555 MapNode n = map->getNodeNoEx(p);
556 if(n.getContent() == CONTENT_IGNORE){
558 pf = p0 + dir * 2*newd;
563 for(int i=0; distance < end_distance; i++){
566 step *= step_multiplier;
568 v3s16 p = floatToInt(pf, BS);
569 MapNode n = map->getNodeNoEx(p);
570 if(allow_allowing_non_sunlight_propagates && i == 0 &&
571 ndef->get(n).param_type == CPT_LIGHT &&
572 !ndef->get(n).sunlight_propagates){
573 allow_non_sunlight_propagates = true;
575 if(ndef->get(n).param_type != CPT_LIGHT ||
576 (!ndef->get(n).sunlight_propagates &&
577 !allow_non_sunlight_propagates)){
578 nonlight_seen = true;
584 if(distance >= sunlight_min_d && *sunlight_seen == false
585 && nonlight_seen == false)
586 if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
587 *sunlight_seen = true;
589 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
593 if(brightness_count == 0)
595 *result = brightness_sum / brightness_count;
596 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
597 <<(*result)<<std::endl;*/
601 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
602 int oldvalue, bool *sunlight_seen_result)
604 const bool debugprint = false;
605 static v3f z_directions[50] = {
608 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
611 if(z_directions[0].X < -99){
612 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
613 z_directions[i] = v3f(
614 0.01 * myrand_range(-100, 100),
616 0.01 * myrand_range(-100, 100)
618 z_offsets[i] = 0.01 * myrand_range(0,100);
622 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
623 int sunlight_seen_count = 0;
624 float sunlight_min_d = max_d*0.8;
625 if(sunlight_min_d > 35*BS)
626 sunlight_min_d = 35*BS;
627 std::vector<int> values;
628 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
629 v3f z_dir = z_directions[i];
631 core::CMatrix4<f32> a;
632 a.buildRotateFromTo(v3f(0,1,0), z_dir);
633 v3f dir = m_camera_direction;
638 step = max_d / 35 * 1.5;
639 float off = step * z_offsets[i];
640 bool sunlight_seen_now = false;
641 bool ok = getVisibleBrightness(this, m_camera_position, dir,
642 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
644 &br, &sunlight_seen_now);
645 if(sunlight_seen_now)
646 sunlight_seen_count++;
649 values.push_back(br);
650 // Don't try too much if being in the sun is clear
651 if(sunlight_seen_count >= 20)
654 int brightness_sum = 0;
655 int brightness_count = 0;
656 std::sort(values.begin(), values.end());
657 u32 num_values_to_use = values.size();
658 if(num_values_to_use >= 10)
659 num_values_to_use -= num_values_to_use/2;
660 else if(num_values_to_use >= 7)
661 num_values_to_use -= num_values_to_use/3;
662 u32 first_value_i = (values.size() - num_values_to_use) / 2;
664 for(u32 i=0; i < first_value_i; i++)
665 std::cerr<<values[i]<<" ";
668 for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
670 std::cerr<<values[i]<<" ";
671 brightness_sum += values[i];
676 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
677 std::cerr<<values[i]<<" ";
680 if(brightness_count == 0){
681 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
682 if(m_nodedef->get(n).param_type == CPT_LIGHT){
683 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
688 /*float pre = (float)brightness_sum / (float)brightness_count;
694 ret = MYMAX(0, MYMIN(255, preint));*/
695 ret = brightness_sum / brightness_count;
698 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
699 <<sunlight_seen_count<<std::endl;
700 *sunlight_seen_result = (sunlight_seen_count > 0);
704 void ClientMap::renderPostFx(CameraMode cam_mode)
706 // Sadly ISceneManager has no "post effects" render pass, in that case we
707 // could just register for that and handle it in renderMap().
709 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
711 // - If the player is in a solid node, make everything black.
712 // - If the player is in liquid, draw a semi-transparent overlay.
713 // - Do not if player is in third person mode
714 const ContentFeatures& features = m_nodedef->get(n);
715 video::SColor post_effect_color = features.post_effect_color;
716 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
717 m_client->checkLocalPrivilege("noclip")) &&
718 cam_mode == CAMERA_MODE_FIRST)
720 post_effect_color = video::SColor(255, 0, 0, 0);
722 if (post_effect_color.getAlpha() != 0)
724 // Draw a full-screen rectangle
725 video::IVideoDriver* driver = SceneManager->getVideoDriver();
726 v2u32 ss = driver->getScreenSize();
727 core::rect<s32> rect(0,0, ss.X, ss.Y);
728 driver->draw2DRectangle(post_effect_color, rect);
732 void ClientMap::PrintInfo(std::ostream &out)