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 DSTACK(FUNCTION_NAME);
66 // Check that it doesn't exist already
68 return getSectorNoGenerate(p2d);
70 catch(InvalidPositionException &e)
75 ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
78 //MutexAutoLock lock(m_sector_mutex); // Bulk comment-out
79 m_sectors[p2d] = sector;
85 void ClientMap::OnRegisterSceneNode()
89 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
90 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
93 ISceneNode::OnRegisterSceneNode();
96 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
97 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
99 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
100 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
101 // can exceed the range of v3s16 when a large view range is used near the
104 cam_pos_nodes.X - box_nodes_d.X,
105 cam_pos_nodes.Y - box_nodes_d.Y,
106 cam_pos_nodes.Z - box_nodes_d.Z);
108 cam_pos_nodes.X + box_nodes_d.X,
109 cam_pos_nodes.Y + box_nodes_d.Y,
110 cam_pos_nodes.Z + box_nodes_d.Z);
111 // Take a fair amount as we will be dropping more out later
112 // Umm... these additions are a bit strange but they are needed.
113 *p_blocks_min = v3s16(
114 p_nodes_min.X / MAP_BLOCKSIZE - 3,
115 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
116 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
117 *p_blocks_max = v3s16(
118 p_nodes_max.X / MAP_BLOCKSIZE + 1,
119 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
120 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
123 void ClientMap::updateDrawList()
125 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
126 g_profiler->add("CM::updateDrawList() count", 1);
128 for (auto &i : m_drawlist) {
129 MapBlock *block = i.second;
134 v3f camera_position = m_camera_position;
135 v3f camera_direction = m_camera_direction;
136 f32 camera_fov = m_camera_fov;
138 // Use a higher fov to accomodate faster camera movements.
139 // Blocks are cropped better when they are drawn.
140 // Or maybe they aren't? Well whatever.
143 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
146 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
148 // Number of blocks in rendering range
149 u32 blocks_in_range = 0;
150 // Number of blocks occlusion culled
151 u32 blocks_occlusion_culled = 0;
152 // Number of blocks in rendering range but don't have a mesh
153 u32 blocks_in_range_without_mesh = 0;
154 // Blocks that had mesh that would have been drawn according to
155 // rendering range (if max blocks limit didn't kick in)
156 u32 blocks_would_have_drawn = 0;
157 // Blocks that were drawn and had a mesh
158 u32 blocks_drawn = 0;
159 // Blocks which had a corresponding meshbuffer for this pass
160 //u32 blocks_had_pass_meshbuf = 0;
161 // Blocks from which stuff was actually drawn
162 //u32 blocks_without_stuff = 0;
163 // Distance to farthest drawn block
164 float farthest_drawn = 0;
166 // No occlusion culling when free_move is on and camera is
168 bool occlusion_culling_enabled = true;
169 if (g_settings->getBool("free_move")) {
170 MapNode n = getNodeNoEx(cam_pos_nodes);
171 if (n.getContent() == CONTENT_IGNORE ||
172 m_nodedef->get(n).solidness == 2)
173 occlusion_culling_enabled = false;
176 for (const auto §or_it : m_sectors) {
177 MapSector *sector = sector_it.second;
178 v2s16 sp = sector->getPos();
180 if (!m_control.range_all) {
181 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
182 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
186 MapBlockVect sectorblocks;
187 sector->getBlocks(sectorblocks);
190 Loop through blocks in sector
193 u32 sector_blocks_drawn = 0;
195 for (auto block : sectorblocks) {
197 Compare block position to camera position, skip
198 if not seen on display
202 block->mesh->updateCameraOffset(m_camera_offset);
204 float range = 100000 * BS;
205 if (!m_control.range_all)
206 range = m_control.wanted_range * BS;
209 if (!isBlockInSight(block->getPos(), camera_position,
210 camera_direction, camera_fov, range, &d))
216 Ignore if mesh doesn't exist
219 blocks_in_range_without_mesh++;
226 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
227 blocks_occlusion_culled++;
231 // This block is in range. Reset usage timer.
232 block->resetUsageTimer();
234 // Limit block count in case of a sudden increase
235 blocks_would_have_drawn++;
236 if (blocks_drawn >= m_control.wanted_max_blocks &&
237 !m_control.range_all &&
238 d > m_control.wanted_range * BS)
243 m_drawlist[block->getPos()] = block;
245 sector_blocks_drawn++;
247 if (d / BS > farthest_drawn)
248 farthest_drawn = d / BS;
250 } // foreach sectorblocks
252 if (sector_blocks_drawn != 0)
253 m_last_drawn_sectors.insert(sp);
256 g_profiler->avg("CM: blocks in range", blocks_in_range);
257 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
258 if (blocks_in_range != 0)
259 g_profiler->avg("CM: blocks in range without mesh (frac)",
260 (float)blocks_in_range_without_mesh / blocks_in_range);
261 g_profiler->avg("CM: blocks drawn", blocks_drawn);
262 g_profiler->avg("CM: farthest drawn", farthest_drawn);
263 g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
269 std::vector<scene::IMeshBuffer*> bufs;
272 struct MeshBufListList
275 * Stores the mesh buffers of the world.
276 * The array index is the material's layer.
277 * The vector part groups vertices by material.
279 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
283 for (int l = 0; l < MAX_TILE_LAYERS; l++)
287 void add(scene::IMeshBuffer *buf, u8 layer)
289 // Append to the correct layer
290 std::vector<MeshBufList> &list = lists[layer];
291 const video::SMaterial &m = buf->getMaterial();
292 for (MeshBufList &l : list) {
293 // comparing a full material is quite expensive so we don't do it if
294 // not even first texture is equal
295 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
299 l.bufs.push_back(buf);
305 l.bufs.push_back(buf);
310 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
312 DSTACK(FUNCTION_NAME);
314 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
317 if (pass == scene::ESNRP_SOLID)
318 prefix = "CM: solid: ";
320 prefix = "CM: transparent: ";
323 This is called two times per frame, reset on the non-transparent one
325 if (pass == scene::ESNRP_SOLID)
326 m_last_drawn_sectors.clear();
329 Get time for measuring timeout.
331 Measuring time is very useful for long delays when the
332 machine is swapping a lot.
334 std::time_t time1 = time(0);
337 Get animation parameters
339 float animation_time = m_client->getAnimationTime();
340 int crack = m_client->getCrackLevel();
341 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
343 v3f camera_position = m_camera_position;
344 v3f camera_direction = m_camera_direction;
345 f32 camera_fov = m_camera_fov;
348 Get all blocks and draw all visible ones
351 u32 vertex_count = 0;
352 u32 meshbuffer_count = 0;
354 // For limiting number of mesh animations per frame
355 u32 mesh_animate_count = 0;
356 u32 mesh_animate_count_far = 0;
358 // Blocks that were drawn and had a mesh
359 u32 blocks_drawn = 0;
360 // Blocks which had a corresponding meshbuffer for this pass
361 u32 blocks_had_pass_meshbuf = 0;
362 // Blocks from which stuff was actually drawn
363 u32 blocks_without_stuff = 0;
366 Draw the selected MapBlocks
370 ScopeProfiler sp(g_profiler, prefix + "drawing blocks", SPT_AVG);
372 MeshBufListList drawbufs;
374 for (auto &i : m_drawlist) {
375 MapBlock *block = i.second;
377 // If the mesh of the block happened to get deleted, ignore it
382 if (!isBlockInSight(block->getPos(), camera_position,
383 camera_direction, camera_fov, 100000 * BS, &d))
387 if (pass == scene::ESNRP_SOLID) {
388 //MutexAutoLock lock(block->mesh_mutex);
389 MapBlockMesh *mapBlockMesh = block->mesh;
390 assert(mapBlockMesh);
391 // Pretty random but this should work somewhat nicely
392 bool faraway = d >= BS * 50;
393 //bool faraway = d >= m_control.wanted_range * BS;
394 if (mapBlockMesh->isAnimationForced() || !faraway ||
395 mesh_animate_count_far < (m_control.range_all ? 200 : 50)) {
396 bool animated = mapBlockMesh->animate(faraway, animation_time,
397 crack, daynight_ratio);
399 mesh_animate_count++;
400 if (animated && faraway)
401 mesh_animate_count_far++;
403 mapBlockMesh->decreaseAnimationForceTimer();
408 Get the meshbuffers of the block
411 //MutexAutoLock lock(block->mesh_mutex);
413 MapBlockMesh *mapBlockMesh = block->mesh;
414 assert(mapBlockMesh);
416 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
417 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
420 u32 c = mesh->getMeshBufferCount();
421 for (u32 i = 0; i < c; i++) {
422 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
424 video::SMaterial& material = buf->getMaterial();
425 video::IMaterialRenderer* rnd =
426 driver->getMaterialRenderer(material.MaterialType);
427 bool transparent = (rnd && rnd->isTransparent());
428 if (transparent == is_transparent_pass) {
429 if (buf->getVertexCount() == 0)
430 errorstream << "Block [" << analyze_block(block)
431 << "] contains an empty meshbuf" << std::endl;
433 material.setFlag(video::EMF_TRILINEAR_FILTER,
434 m_cache_trilinear_filter);
435 material.setFlag(video::EMF_BILINEAR_FILTER,
436 m_cache_bilinear_filter);
437 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
438 m_cache_anistropic_filter);
439 material.setFlag(video::EMF_WIREFRAME,
440 m_control.show_wireframe);
442 drawbufs.add(buf, layer);
449 // Render all layers in order
450 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
451 std::vector<MeshBufList> &lists = drawbufs.lists[layer];
453 int timecheck_counter = 0;
454 for (MeshBufList &list : lists) {
456 if (timecheck_counter > 50) {
457 timecheck_counter = 0;
458 std::time_t time2 = time(0);
459 if (time2 > time1 + 4) {
460 infostream << "ClientMap::renderMap(): "
461 "Rendering takes ages, returning."
467 driver->setMaterial(list.m);
469 for (scene::IMeshBuffer *buf : list.bufs) {
470 driver->drawMeshBuffer(buf);
471 vertex_count += buf->getVertexCount();
478 // Log only on solid pass because values are the same
479 if (pass == scene::ESNRP_SOLID) {
480 g_profiler->avg("CM: animated meshes", mesh_animate_count);
481 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
484 g_profiler->avg(prefix + "vertices drawn", vertex_count);
485 if (blocks_had_pass_meshbuf != 0)
486 g_profiler->avg(prefix + "meshbuffers per block",
487 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
488 if (blocks_drawn != 0)
489 g_profiler->avg(prefix + "empty blocks (frac)",
490 (float)blocks_without_stuff / blocks_drawn);
493 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
494 float step_multiplier, float start_distance, float end_distance,
495 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
496 int *result, bool *sunlight_seen)
498 int brightness_sum = 0;
499 int brightness_count = 0;
500 float distance = start_distance;
503 pf += dir * distance;
505 bool nonlight_seen = false;
506 bool allow_allowing_non_sunlight_propagates = false;
507 bool allow_non_sunlight_propagates = false;
508 // Check content nearly at camera position
510 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
511 MapNode n = map->getNodeNoEx(p);
512 if(ndef->get(n).param_type == CPT_LIGHT &&
513 !ndef->get(n).sunlight_propagates)
514 allow_allowing_non_sunlight_propagates = true;
516 // If would start at CONTENT_IGNORE, start closer
518 v3s16 p = floatToInt(pf, BS);
519 MapNode n = map->getNodeNoEx(p);
520 if(n.getContent() == CONTENT_IGNORE){
522 pf = p0 + dir * 2*newd;
527 for (int i=0; distance < end_distance; i++) {
530 step *= step_multiplier;
532 v3s16 p = floatToInt(pf, BS);
533 MapNode n = map->getNodeNoEx(p);
534 if (allow_allowing_non_sunlight_propagates && i == 0 &&
535 ndef->get(n).param_type == CPT_LIGHT &&
536 !ndef->get(n).sunlight_propagates) {
537 allow_non_sunlight_propagates = true;
540 if (ndef->get(n).param_type != CPT_LIGHT ||
541 (!ndef->get(n).sunlight_propagates &&
542 !allow_non_sunlight_propagates)){
543 nonlight_seen = true;
550 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
551 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
552 *sunlight_seen = true;
554 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
558 if(brightness_count == 0)
560 *result = brightness_sum / brightness_count;
561 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
562 <<(*result)<<std::endl;*/
566 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
567 int oldvalue, bool *sunlight_seen_result)
569 static v3f z_directions[50] = {
572 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
576 if(z_directions[0].X < -99){
577 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
578 // Assumes FOV of 72 and 16/9 aspect ratio
579 z_directions[i] = v3f(
580 0.02 * myrand_range(-100, 100),
582 0.01 * myrand_range(-100, 100)
584 z_offsets[i] = 0.01 * myrand_range(0,100);
588 int sunlight_seen_count = 0;
589 float sunlight_min_d = max_d*0.8;
590 if(sunlight_min_d > 35*BS)
591 sunlight_min_d = 35*BS;
592 std::vector<int> values;
593 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
594 v3f z_dir = z_directions[i];
595 core::CMatrix4<f32> a;
596 a.buildRotateFromTo(v3f(0,1,0), z_dir);
597 v3f dir = m_camera_direction;
602 step = max_d / 35 * 1.5;
603 float off = step * z_offsets[i];
604 bool sunlight_seen_now = false;
605 bool ok = getVisibleBrightness(this, m_camera_position, dir,
606 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
608 &br, &sunlight_seen_now);
609 if(sunlight_seen_now)
610 sunlight_seen_count++;
613 values.push_back(br);
614 // Don't try too much if being in the sun is clear
615 if(sunlight_seen_count >= 20)
618 int brightness_sum = 0;
619 int brightness_count = 0;
620 std::sort(values.begin(), values.end());
621 u32 num_values_to_use = values.size();
622 if(num_values_to_use >= 10)
623 num_values_to_use -= num_values_to_use/2;
624 else if(num_values_to_use >= 7)
625 num_values_to_use -= num_values_to_use/3;
626 u32 first_value_i = (values.size() - num_values_to_use) / 2;
628 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
629 brightness_sum += values[i];
634 if(brightness_count == 0){
635 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
636 if(m_nodedef->get(n).param_type == CPT_LIGHT){
637 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
642 ret = brightness_sum / brightness_count;
645 *sunlight_seen_result = (sunlight_seen_count > 0);
649 void ClientMap::renderPostFx(CameraMode cam_mode)
651 // Sadly ISceneManager has no "post effects" render pass, in that case we
652 // could just register for that and handle it in renderMap().
654 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
656 // - If the player is in a solid node, make everything black.
657 // - If the player is in liquid, draw a semi-transparent overlay.
658 // - Do not if player is in third person mode
659 const ContentFeatures& features = m_nodedef->get(n);
660 video::SColor post_effect_color = features.post_effect_color;
661 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
662 m_client->checkLocalPrivilege("noclip")) &&
663 cam_mode == CAMERA_MODE_FIRST)
665 post_effect_color = video::SColor(255, 0, 0, 0);
667 if (post_effect_color.getAlpha() != 0)
669 // Draw a full-screen rectangle
670 video::IVideoDriver* driver = SceneManager->getVideoDriver();
671 v2u32 ss = driver->getScreenSize();
672 core::rect<s32> rect(0,0, ss.X, ss.Y);
673 driver->draw2DRectangle(post_effect_color, rect);
677 void ClientMap::PrintInfo(std::ostream &out)