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,
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
66 MapSector *sector = getSectorNoGenerate(p2d);
68 // Create it if it does not exist yet
70 sector = new MapSector(this, p2d, m_gamedef);
71 m_sectors[p2d] = sector;
77 void ClientMap::OnRegisterSceneNode()
81 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
82 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
85 ISceneNode::OnRegisterSceneNode();
88 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
89 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
91 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
92 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
93 // can exceed the range of v3s16 when a large view range is used near the
96 cam_pos_nodes.X - box_nodes_d.X,
97 cam_pos_nodes.Y - box_nodes_d.Y,
98 cam_pos_nodes.Z - box_nodes_d.Z);
100 cam_pos_nodes.X + box_nodes_d.X,
101 cam_pos_nodes.Y + box_nodes_d.Y,
102 cam_pos_nodes.Z + box_nodes_d.Z);
103 // Take a fair amount as we will be dropping more out later
104 // Umm... these additions are a bit strange but they are needed.
105 *p_blocks_min = v3s16(
106 p_nodes_min.X / MAP_BLOCKSIZE - 3,
107 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
108 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
109 *p_blocks_max = v3s16(
110 p_nodes_max.X / MAP_BLOCKSIZE + 1,
111 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
112 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
115 void ClientMap::updateDrawList()
117 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
119 for (auto &i : m_drawlist) {
120 MapBlock *block = i.second;
125 const v3f camera_position = m_camera_position;
126 const v3f camera_direction = m_camera_direction;
127 const f32 camera_fov = m_camera_fov;
129 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
132 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
134 // Number of blocks currently loaded by the client
135 u32 blocks_loaded = 0;
136 // Number of blocks with mesh in rendering range
137 u32 blocks_in_range_with_mesh = 0;
138 // Number of blocks occlusion culled
139 u32 blocks_occlusion_culled = 0;
141 // No occlusion culling when free_move is on and camera is
143 bool occlusion_culling_enabled = true;
144 if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
145 MapNode n = getNode(cam_pos_nodes);
146 if (n.getContent() == CONTENT_IGNORE ||
147 m_nodedef->get(n).solidness == 2)
148 occlusion_culling_enabled = false;
151 // Uncomment to debug occluded blocks in the wireframe mode
152 // TODO: Include this as a flag for an extended debugging setting
153 //if (occlusion_culling_enabled && m_control.show_wireframe)
154 // occlusion_culling_enabled = porting::getTimeS() & 1;
156 for (const auto §or_it : m_sectors) {
157 MapSector *sector = sector_it.second;
158 v2s16 sp = sector->getPos();
160 blocks_loaded += sector->size();
161 if (!m_control.range_all) {
162 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
163 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
167 MapBlockVect sectorblocks;
168 sector->getBlocks(sectorblocks);
171 Loop through blocks in sector
174 u32 sector_blocks_drawn = 0;
176 for (MapBlock *block : sectorblocks) {
178 Compare block position to camera position, skip
179 if not seen on display
183 block->mesh->updateCameraOffset(m_camera_offset);
185 // Ignore if mesh doesn't exist
189 float range = 100000 * BS;
190 if (!m_control.range_all)
191 range = m_control.wanted_range * BS;
194 if (!isBlockInSight(block->getPos(), camera_position,
195 camera_direction, camera_fov, range, &d))
198 blocks_in_range_with_mesh++;
203 if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
204 (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
205 blocks_occlusion_culled++;
209 // This block is in range. Reset usage timer.
210 block->resetUsageTimer();
214 m_drawlist[block->getPos()] = block;
216 sector_blocks_drawn++;
217 } // foreach sectorblocks
219 if (sector_blocks_drawn != 0)
220 m_last_drawn_sectors.insert(sp);
223 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
224 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
225 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
226 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
232 std::vector<scene::IMeshBuffer*> bufs;
235 struct MeshBufListList
238 * Stores the mesh buffers of the world.
239 * The array index is the material's layer.
240 * The vector part groups vertices by material.
242 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
246 for (auto &list : lists)
250 void add(scene::IMeshBuffer *buf, u8 layer)
252 // Append to the correct layer
253 std::vector<MeshBufList> &list = lists[layer];
254 const video::SMaterial &m = buf->getMaterial();
255 for (MeshBufList &l : list) {
256 // comparing a full material is quite expensive so we don't do it if
257 // not even first texture is equal
258 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
262 l.bufs.push_back(buf);
268 l.bufs.push_back(buf);
273 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
275 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
278 if (pass == scene::ESNRP_SOLID)
279 prefix = "renderMap(SOLID): ";
281 prefix = "renderMap(TRANSPARENT): ";
284 This is called two times per frame, reset on the non-transparent one
286 if (pass == scene::ESNRP_SOLID)
287 m_last_drawn_sectors.clear();
290 Get animation parameters
292 const float animation_time = m_client->getAnimationTime();
293 const int crack = m_client->getCrackLevel();
294 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
296 const v3f camera_position = m_camera_position;
297 const v3f camera_direction = m_camera_direction;
298 const f32 camera_fov = m_camera_fov;
301 Get all blocks and draw all visible ones
304 u32 vertex_count = 0;
306 // For limiting number of mesh animations per frame
307 u32 mesh_animate_count = 0;
308 //u32 mesh_animate_count_far = 0;
311 Draw the selected MapBlocks
314 MeshBufListList drawbufs;
316 for (auto &i : m_drawlist) {
317 MapBlock *block = i.second;
319 // If the mesh of the block happened to get deleted, ignore it
324 if (!isBlockInSight(block->getPos(), camera_position,
325 camera_direction, camera_fov, 100000 * BS, &d))
329 if (pass == scene::ESNRP_SOLID) {
330 //MutexAutoLock lock(block->mesh_mutex);
331 MapBlockMesh *mapBlockMesh = block->mesh;
332 assert(mapBlockMesh);
333 // Pretty random but this should work somewhat nicely
334 bool faraway = d >= BS * 50;
335 if (mapBlockMesh->isAnimationForced() || !faraway ||
336 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
338 bool animated = mapBlockMesh->animate(faraway, animation_time,
339 crack, daynight_ratio);
341 mesh_animate_count++;
343 mapBlockMesh->decreaseAnimationForceTimer();
348 Get the meshbuffers of the block
351 //MutexAutoLock lock(block->mesh_mutex);
353 MapBlockMesh *mapBlockMesh = block->mesh;
354 assert(mapBlockMesh);
356 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
357 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
360 u32 c = mesh->getMeshBufferCount();
361 for (u32 i = 0; i < c; i++) {
362 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
364 video::SMaterial& material = buf->getMaterial();
365 video::IMaterialRenderer* rnd =
366 driver->getMaterialRenderer(material.MaterialType);
367 bool transparent = (rnd && rnd->isTransparent());
368 if (transparent == is_transparent_pass) {
369 if (buf->getVertexCount() == 0)
370 errorstream << "Block [" << analyze_block(block)
371 << "] contains an empty meshbuf" << std::endl;
373 material.setFlag(video::EMF_TRILINEAR_FILTER,
374 m_cache_trilinear_filter);
375 material.setFlag(video::EMF_BILINEAR_FILTER,
376 m_cache_bilinear_filter);
377 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
378 m_cache_anistropic_filter);
379 material.setFlag(video::EMF_WIREFRAME,
380 m_control.show_wireframe);
382 drawbufs.add(buf, layer);
389 TimeTaker draw("Drawing mesh buffers");
391 // Render all layers in order
392 for (auto &lists : drawbufs.lists) {
393 for (MeshBufList &list : lists) {
394 // Check and abort if the machine is swapping a lot
395 if (draw.getTimerTime() > 2000) {
396 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
397 "returning." << std::endl;
400 driver->setMaterial(list.m);
402 for (scene::IMeshBuffer *buf : list.bufs) {
403 driver->drawMeshBuffer(buf);
404 vertex_count += buf->getVertexCount();
408 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
410 // Log only on solid pass because values are the same
411 if (pass == scene::ESNRP_SOLID) {
412 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
415 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
418 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
419 float step_multiplier, float start_distance, float end_distance,
420 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
421 int *result, bool *sunlight_seen)
423 int brightness_sum = 0;
424 int brightness_count = 0;
425 float distance = start_distance;
428 pf += dir * distance;
430 bool nonlight_seen = false;
431 bool allow_allowing_non_sunlight_propagates = false;
432 bool allow_non_sunlight_propagates = false;
433 // Check content nearly at camera position
435 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
436 MapNode n = map->getNode(p);
437 if(ndef->get(n).param_type == CPT_LIGHT &&
438 !ndef->get(n).sunlight_propagates)
439 allow_allowing_non_sunlight_propagates = true;
441 // If would start at CONTENT_IGNORE, start closer
443 v3s16 p = floatToInt(pf, BS);
444 MapNode n = map->getNode(p);
445 if(n.getContent() == CONTENT_IGNORE){
447 pf = p0 + dir * 2*newd;
452 for (int i=0; distance < end_distance; i++) {
455 step *= step_multiplier;
457 v3s16 p = floatToInt(pf, BS);
458 MapNode n = map->getNode(p);
459 if (allow_allowing_non_sunlight_propagates && i == 0 &&
460 ndef->get(n).param_type == CPT_LIGHT &&
461 !ndef->get(n).sunlight_propagates) {
462 allow_non_sunlight_propagates = true;
465 if (ndef->get(n).param_type != CPT_LIGHT ||
466 (!ndef->get(n).sunlight_propagates &&
467 !allow_non_sunlight_propagates)){
468 nonlight_seen = true;
475 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
476 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
477 *sunlight_seen = true;
479 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
483 if(brightness_count == 0)
485 *result = brightness_sum / brightness_count;
486 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
487 <<(*result)<<std::endl;*/
491 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
492 int oldvalue, bool *sunlight_seen_result)
494 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
495 static v3f z_directions[50] = {
498 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
502 if(z_directions[0].X < -99){
503 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
504 // Assumes FOV of 72 and 16/9 aspect ratio
505 z_directions[i] = v3f(
506 0.02 * myrand_range(-100, 100),
508 0.01 * myrand_range(-100, 100)
510 z_offsets[i] = 0.01 * myrand_range(0,100);
514 int sunlight_seen_count = 0;
515 float sunlight_min_d = max_d*0.8;
516 if(sunlight_min_d > 35*BS)
517 sunlight_min_d = 35*BS;
518 std::vector<int> values;
519 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
520 v3f z_dir = z_directions[i];
521 core::CMatrix4<f32> a;
522 a.buildRotateFromTo(v3f(0,1,0), z_dir);
523 v3f dir = m_camera_direction;
528 step = max_d / 35 * 1.5;
529 float off = step * z_offsets[i];
530 bool sunlight_seen_now = false;
531 bool ok = getVisibleBrightness(this, m_camera_position, dir,
532 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
534 &br, &sunlight_seen_now);
535 if(sunlight_seen_now)
536 sunlight_seen_count++;
539 values.push_back(br);
540 // Don't try too much if being in the sun is clear
541 if(sunlight_seen_count >= 20)
544 int brightness_sum = 0;
545 int brightness_count = 0;
546 std::sort(values.begin(), values.end());
547 u32 num_values_to_use = values.size();
548 if(num_values_to_use >= 10)
549 num_values_to_use -= num_values_to_use/2;
550 else if(num_values_to_use >= 7)
551 num_values_to_use -= num_values_to_use/3;
552 u32 first_value_i = (values.size() - num_values_to_use) / 2;
554 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
555 brightness_sum += values[i];
560 if(brightness_count == 0){
561 MapNode n = getNode(floatToInt(m_camera_position, BS));
562 if(m_nodedef->get(n).param_type == CPT_LIGHT){
563 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
568 ret = brightness_sum / brightness_count;
571 *sunlight_seen_result = (sunlight_seen_count > 0);
575 void ClientMap::renderPostFx(CameraMode cam_mode)
577 // Sadly ISceneManager has no "post effects" render pass, in that case we
578 // could just register for that and handle it in renderMap().
580 MapNode n = getNode(floatToInt(m_camera_position, BS));
582 // - If the player is in a solid node, make everything black.
583 // - If the player is in liquid, draw a semi-transparent overlay.
584 // - Do not if player is in third person mode
585 const ContentFeatures& features = m_nodedef->get(n);
586 video::SColor post_effect_color = features.post_effect_color;
587 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
588 m_client->checkLocalPrivilege("noclip")) &&
589 cam_mode == CAMERA_MODE_FIRST)
591 post_effect_color = video::SColor(255, 0, 0, 0);
593 if (post_effect_color.getAlpha() != 0)
595 // Draw a full-screen rectangle
596 video::IVideoDriver* driver = SceneManager->getVideoDriver();
597 v2u32 ss = driver->getScreenSize();
598 core::rect<s32> rect(0,0, ss.X, ss.Y);
599 driver->draw2DRectangle(post_effect_color, rect);
603 void ClientMap::PrintInfo(std::ostream &out)