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>
25 #include "mapsector.h"
29 #include "camera.h" // CameraModes
30 #include "util/basic_macros.h"
32 #include "client/renderingengine.h"
36 MapDrawControl &control,
39 Map(dout_client, client),
40 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
41 RenderingEngine::get_scene_manager(), id),
45 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
46 BS*1000000,BS*1000000,BS*1000000);
48 /* TODO: Add a callback function so these can be updated when a setting
49 * changes. At this point in time it doesn't matter (e.g. /set
50 * is documented to change server settings only)
52 * TODO: Local caching of settings is not optimal and should at some stage
53 * be updated to use a global settings object for getting thse values
54 * (as opposed to the this local caching). This can be addressed in
57 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
58 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
59 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
63 MapSector * ClientMap::emergeSector(v2s16 p2d)
65 // Check that it doesn't exist already
67 return getSectorNoGenerate(p2d);
68 } catch(InvalidPositionException &e) {
72 MapSector *sector = new MapSector(this, p2d, m_gamedef);
73 m_sectors[p2d] = sector;
78 void ClientMap::OnRegisterSceneNode()
82 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
83 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
86 ISceneNode::OnRegisterSceneNode();
89 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
90 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
92 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
93 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
94 // can exceed the range of v3s16 when a large view range is used near the
97 cam_pos_nodes.X - box_nodes_d.X,
98 cam_pos_nodes.Y - box_nodes_d.Y,
99 cam_pos_nodes.Z - box_nodes_d.Z);
101 cam_pos_nodes.X + box_nodes_d.X,
102 cam_pos_nodes.Y + box_nodes_d.Y,
103 cam_pos_nodes.Z + box_nodes_d.Z);
104 // Take a fair amount as we will be dropping more out later
105 // Umm... these additions are a bit strange but they are needed.
106 *p_blocks_min = v3s16(
107 p_nodes_min.X / MAP_BLOCKSIZE - 3,
108 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
109 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
110 *p_blocks_max = v3s16(
111 p_nodes_max.X / MAP_BLOCKSIZE + 1,
112 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
113 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
116 void ClientMap::updateDrawList()
118 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
119 g_profiler->add("CM::updateDrawList() count", 1);
121 for (auto &i : m_drawlist) {
122 MapBlock *block = i.second;
127 v3f camera_position = m_camera_position;
128 v3f camera_direction = m_camera_direction;
129 f32 camera_fov = m_camera_fov;
131 // Use a higher fov to accomodate faster camera movements.
132 // Blocks are cropped better when they are drawn.
133 // Or maybe they aren't? Well whatever.
136 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
139 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
141 // Number of blocks in rendering range
142 u32 blocks_in_range = 0;
143 // Number of blocks occlusion culled
144 u32 blocks_occlusion_culled = 0;
145 // Number of blocks in rendering range but don't have a mesh
146 u32 blocks_in_range_without_mesh = 0;
147 // Blocks that had mesh that would have been drawn according to
148 // rendering range (if max blocks limit didn't kick in)
149 u32 blocks_would_have_drawn = 0;
150 // Blocks that were drawn and had a mesh
151 u32 blocks_drawn = 0;
152 // Blocks which had a corresponding meshbuffer for this pass
153 //u32 blocks_had_pass_meshbuf = 0;
154 // Blocks from which stuff was actually drawn
155 //u32 blocks_without_stuff = 0;
156 // Distance to farthest drawn block
157 float farthest_drawn = 0;
159 // No occlusion culling when free_move is on and camera is
161 bool occlusion_culling_enabled = true;
162 if (g_settings->getBool("free_move")) {
163 MapNode n = getNodeNoEx(cam_pos_nodes);
164 if (n.getContent() == CONTENT_IGNORE ||
165 m_nodedef->get(n).solidness == 2)
166 occlusion_culling_enabled = false;
169 for (const auto §or_it : m_sectors) {
170 MapSector *sector = sector_it.second;
171 v2s16 sp = sector->getPos();
173 if (!m_control.range_all) {
174 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
175 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
179 MapBlockVect sectorblocks;
180 sector->getBlocks(sectorblocks);
183 Loop through blocks in sector
186 u32 sector_blocks_drawn = 0;
188 for (auto block : sectorblocks) {
190 Compare block position to camera position, skip
191 if not seen on display
195 block->mesh->updateCameraOffset(m_camera_offset);
197 float range = 100000 * BS;
198 if (!m_control.range_all)
199 range = m_control.wanted_range * BS;
202 if (!isBlockInSight(block->getPos(), camera_position,
203 camera_direction, camera_fov, range, &d))
209 Ignore if mesh doesn't exist
212 blocks_in_range_without_mesh++;
219 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
220 blocks_occlusion_culled++;
224 // This block is in range. Reset usage timer.
225 block->resetUsageTimer();
227 // Limit block count in case of a sudden increase
228 blocks_would_have_drawn++;
229 if (blocks_drawn >= m_control.wanted_max_blocks &&
230 !m_control.range_all &&
231 d > m_control.wanted_range * BS)
236 m_drawlist[block->getPos()] = block;
238 sector_blocks_drawn++;
240 if (d / BS > farthest_drawn)
241 farthest_drawn = d / BS;
243 } // foreach sectorblocks
245 if (sector_blocks_drawn != 0)
246 m_last_drawn_sectors.insert(sp);
249 g_profiler->avg("CM: blocks in range", blocks_in_range);
250 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
251 if (blocks_in_range != 0)
252 g_profiler->avg("CM: blocks in range without mesh (frac)",
253 (float)blocks_in_range_without_mesh / blocks_in_range);
254 g_profiler->avg("CM: blocks drawn", blocks_drawn);
255 g_profiler->avg("CM: farthest drawn", farthest_drawn);
256 g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
262 std::vector<scene::IMeshBuffer*> bufs;
265 struct MeshBufListList
268 * Stores the mesh buffers of the world.
269 * The array index is the material's layer.
270 * The vector part groups vertices by material.
272 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
276 for (auto &list : lists)
280 void add(scene::IMeshBuffer *buf, u8 layer)
282 // Append to the correct layer
283 std::vector<MeshBufList> &list = lists[layer];
284 const video::SMaterial &m = buf->getMaterial();
285 for (MeshBufList &l : list) {
286 // comparing a full material is quite expensive so we don't do it if
287 // not even first texture is equal
288 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
292 l.bufs.push_back(buf);
298 l.bufs.push_back(buf);
303 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
305 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
308 if (pass == scene::ESNRP_SOLID)
309 prefix = "CM: solid: ";
311 prefix = "CM: transparent: ";
314 This is called two times per frame, reset on the non-transparent one
316 if (pass == scene::ESNRP_SOLID)
317 m_last_drawn_sectors.clear();
320 Get time for measuring timeout.
322 Measuring time is very useful for long delays when the
323 machine is swapping a lot.
325 std::time_t time1 = time(0);
328 Get animation parameters
330 float animation_time = m_client->getAnimationTime();
331 int crack = m_client->getCrackLevel();
332 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
334 v3f camera_position = m_camera_position;
335 v3f camera_direction = m_camera_direction;
336 f32 camera_fov = m_camera_fov;
339 Get all blocks and draw all visible ones
342 u32 vertex_count = 0;
343 u32 meshbuffer_count = 0;
345 // For limiting number of mesh animations per frame
346 u32 mesh_animate_count = 0;
347 u32 mesh_animate_count_far = 0;
349 // Blocks that were drawn and had a mesh
350 u32 blocks_drawn = 0;
351 // Blocks which had a corresponding meshbuffer for this pass
352 u32 blocks_had_pass_meshbuf = 0;
353 // Blocks from which stuff was actually drawn
354 u32 blocks_without_stuff = 0;
357 Draw the selected MapBlocks
361 ScopeProfiler sp(g_profiler, prefix + "drawing blocks", SPT_AVG);
363 MeshBufListList drawbufs;
365 for (auto &i : m_drawlist) {
366 MapBlock *block = i.second;
368 // If the mesh of the block happened to get deleted, ignore it
373 if (!isBlockInSight(block->getPos(), camera_position,
374 camera_direction, camera_fov, 100000 * BS, &d))
378 if (pass == scene::ESNRP_SOLID) {
379 //MutexAutoLock lock(block->mesh_mutex);
380 MapBlockMesh *mapBlockMesh = block->mesh;
381 assert(mapBlockMesh);
382 // Pretty random but this should work somewhat nicely
383 bool faraway = d >= BS * 50;
384 //bool faraway = d >= m_control.wanted_range * BS;
385 if (mapBlockMesh->isAnimationForced() || !faraway ||
386 mesh_animate_count_far < (m_control.range_all ? 200 : 50)) {
387 bool animated = mapBlockMesh->animate(faraway, animation_time,
388 crack, daynight_ratio);
390 mesh_animate_count++;
391 if (animated && faraway)
392 mesh_animate_count_far++;
394 mapBlockMesh->decreaseAnimationForceTimer();
399 Get the meshbuffers of the block
402 //MutexAutoLock lock(block->mesh_mutex);
404 MapBlockMesh *mapBlockMesh = block->mesh;
405 assert(mapBlockMesh);
407 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
408 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
411 u32 c = mesh->getMeshBufferCount();
412 for (u32 i = 0; i < c; i++) {
413 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
415 video::SMaterial& material = buf->getMaterial();
416 video::IMaterialRenderer* rnd =
417 driver->getMaterialRenderer(material.MaterialType);
418 bool transparent = (rnd && rnd->isTransparent());
419 if (transparent == is_transparent_pass) {
420 if (buf->getVertexCount() == 0)
421 errorstream << "Block [" << analyze_block(block)
422 << "] contains an empty meshbuf" << std::endl;
424 material.setFlag(video::EMF_TRILINEAR_FILTER,
425 m_cache_trilinear_filter);
426 material.setFlag(video::EMF_BILINEAR_FILTER,
427 m_cache_bilinear_filter);
428 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
429 m_cache_anistropic_filter);
430 material.setFlag(video::EMF_WIREFRAME,
431 m_control.show_wireframe);
433 drawbufs.add(buf, layer);
440 // Render all layers in order
441 for (auto &lists : drawbufs.lists) {
442 int timecheck_counter = 0;
443 for (MeshBufList &list : lists) {
445 if (timecheck_counter > 50) {
446 timecheck_counter = 0;
447 std::time_t time2 = time(0);
448 if (time2 > time1 + 4) {
449 infostream << "ClientMap::renderMap(): "
450 "Rendering takes ages, returning."
456 driver->setMaterial(list.m);
458 for (scene::IMeshBuffer *buf : list.bufs) {
459 driver->drawMeshBuffer(buf);
460 vertex_count += buf->getVertexCount();
467 // Log only on solid pass because values are the same
468 if (pass == scene::ESNRP_SOLID) {
469 g_profiler->avg("CM: animated meshes", mesh_animate_count);
470 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
473 g_profiler->avg(prefix + "vertices drawn", vertex_count);
474 if (blocks_had_pass_meshbuf != 0)
475 g_profiler->avg(prefix + "meshbuffers per block",
476 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
477 if (blocks_drawn != 0)
478 g_profiler->avg(prefix + "empty blocks (frac)",
479 (float)blocks_without_stuff / blocks_drawn);
482 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
483 float step_multiplier, float start_distance, float end_distance,
484 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
485 int *result, bool *sunlight_seen)
487 int brightness_sum = 0;
488 int brightness_count = 0;
489 float distance = start_distance;
492 pf += dir * distance;
494 bool nonlight_seen = false;
495 bool allow_allowing_non_sunlight_propagates = false;
496 bool allow_non_sunlight_propagates = false;
497 // Check content nearly at camera position
499 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
500 MapNode n = map->getNodeNoEx(p);
501 if(ndef->get(n).param_type == CPT_LIGHT &&
502 !ndef->get(n).sunlight_propagates)
503 allow_allowing_non_sunlight_propagates = true;
505 // If would start at CONTENT_IGNORE, start closer
507 v3s16 p = floatToInt(pf, BS);
508 MapNode n = map->getNodeNoEx(p);
509 if(n.getContent() == CONTENT_IGNORE){
511 pf = p0 + dir * 2*newd;
516 for (int i=0; distance < end_distance; i++) {
519 step *= step_multiplier;
521 v3s16 p = floatToInt(pf, BS);
522 MapNode n = map->getNodeNoEx(p);
523 if (allow_allowing_non_sunlight_propagates && i == 0 &&
524 ndef->get(n).param_type == CPT_LIGHT &&
525 !ndef->get(n).sunlight_propagates) {
526 allow_non_sunlight_propagates = true;
529 if (ndef->get(n).param_type != CPT_LIGHT ||
530 (!ndef->get(n).sunlight_propagates &&
531 !allow_non_sunlight_propagates)){
532 nonlight_seen = true;
539 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
540 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
541 *sunlight_seen = true;
543 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
547 if(brightness_count == 0)
549 *result = brightness_sum / brightness_count;
550 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
551 <<(*result)<<std::endl;*/
555 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
556 int oldvalue, bool *sunlight_seen_result)
558 static v3f z_directions[50] = {
561 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
565 if(z_directions[0].X < -99){
566 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
567 // Assumes FOV of 72 and 16/9 aspect ratio
568 z_directions[i] = v3f(
569 0.02 * myrand_range(-100, 100),
571 0.01 * myrand_range(-100, 100)
573 z_offsets[i] = 0.01 * myrand_range(0,100);
577 int sunlight_seen_count = 0;
578 float sunlight_min_d = max_d*0.8;
579 if(sunlight_min_d > 35*BS)
580 sunlight_min_d = 35*BS;
581 std::vector<int> values;
582 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
583 v3f z_dir = z_directions[i];
584 core::CMatrix4<f32> a;
585 a.buildRotateFromTo(v3f(0,1,0), z_dir);
586 v3f dir = m_camera_direction;
591 step = max_d / 35 * 1.5;
592 float off = step * z_offsets[i];
593 bool sunlight_seen_now = false;
594 bool ok = getVisibleBrightness(this, m_camera_position, dir,
595 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
597 &br, &sunlight_seen_now);
598 if(sunlight_seen_now)
599 sunlight_seen_count++;
602 values.push_back(br);
603 // Don't try too much if being in the sun is clear
604 if(sunlight_seen_count >= 20)
607 int brightness_sum = 0;
608 int brightness_count = 0;
609 std::sort(values.begin(), values.end());
610 u32 num_values_to_use = values.size();
611 if(num_values_to_use >= 10)
612 num_values_to_use -= num_values_to_use/2;
613 else if(num_values_to_use >= 7)
614 num_values_to_use -= num_values_to_use/3;
615 u32 first_value_i = (values.size() - num_values_to_use) / 2;
617 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
618 brightness_sum += values[i];
623 if(brightness_count == 0){
624 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
625 if(m_nodedef->get(n).param_type == CPT_LIGHT){
626 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
631 ret = brightness_sum / brightness_count;
634 *sunlight_seen_result = (sunlight_seen_count > 0);
638 void ClientMap::renderPostFx(CameraMode cam_mode)
640 // Sadly ISceneManager has no "post effects" render pass, in that case we
641 // could just register for that and handle it in renderMap().
643 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
645 // - If the player is in a solid node, make everything black.
646 // - If the player is in liquid, draw a semi-transparent overlay.
647 // - Do not if player is in third person mode
648 const ContentFeatures& features = m_nodedef->get(n);
649 video::SColor post_effect_color = features.post_effect_color;
650 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
651 m_client->checkLocalPrivilege("noclip")) &&
652 cam_mode == CAMERA_MODE_FIRST)
654 post_effect_color = video::SColor(255, 0, 0, 0);
656 if (post_effect_color.getAlpha() != 0)
658 // Draw a full-screen rectangle
659 video::IVideoDriver* driver = SceneManager->getVideoDriver();
660 v2u32 ss = driver->getScreenSize();
661 core::rect<s32> rect(0,0, ss.X, ss.Y);
662 driver->draw2DRectangle(post_effect_color, rect);
666 void ClientMap::PrintInfo(std::ostream &out)