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
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 v3f camera_position = m_camera_position;
126 v3f camera_direction = m_camera_direction;
127 f32 camera_fov = m_camera_fov;
129 // Use a higher fov to accomodate faster camera movements.
130 // Blocks are cropped better when they are drawn.
131 // Or maybe they aren't? Well whatever.
134 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
137 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
139 // Number of blocks with mesh in rendering range
140 u32 blocks_in_range_with_mesh = 0;
141 // Number of blocks occlusion culled
142 u32 blocks_occlusion_culled = 0;
144 // No occlusion culling when free_move is on and camera is
146 bool occlusion_culling_enabled = true;
147 if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
148 MapNode n = getNode(cam_pos_nodes);
149 if (n.getContent() == CONTENT_IGNORE ||
150 m_nodedef->get(n).solidness == 2)
151 occlusion_culling_enabled = false;
154 // Uncomment to debug occluded blocks in the wireframe mode
155 // TODO: Include this as a flag for an extended debugging setting
156 //if (occlusion_culling_enabled && m_control.show_wireframe)
157 // occlusion_culling_enabled = porting::getTimeS() & 1;
159 for (const auto §or_it : m_sectors) {
160 MapSector *sector = sector_it.second;
161 v2s16 sp = sector->getPos();
163 if (!m_control.range_all) {
164 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
165 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
169 MapBlockVect sectorblocks;
170 sector->getBlocks(sectorblocks);
173 Loop through blocks in sector
176 u32 sector_blocks_drawn = 0;
178 for (MapBlock *block : sectorblocks) {
180 Compare block position to camera position, skip
181 if not seen on display
185 block->mesh->updateCameraOffset(m_camera_offset);
187 float range = 100000 * BS;
188 if (!m_control.range_all)
189 range = m_control.wanted_range * BS;
192 if (!isBlockInSight(block->getPos(), camera_position,
193 camera_direction, camera_fov, range, &d))
198 Ignore if mesh doesn't exist
203 blocks_in_range_with_mesh++;
208 if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
209 (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
210 blocks_occlusion_culled++;
214 // This block is in range. Reset usage timer.
215 block->resetUsageTimer();
219 m_drawlist[block->getPos()] = block;
221 sector_blocks_drawn++;
222 } // foreach sectorblocks
224 if (sector_blocks_drawn != 0)
225 m_last_drawn_sectors.insert(sp);
228 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
229 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
230 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
236 std::vector<scene::IMeshBuffer*> bufs;
239 struct MeshBufListList
242 * Stores the mesh buffers of the world.
243 * The array index is the material's layer.
244 * The vector part groups vertices by material.
246 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
250 for (auto &list : lists)
254 void add(scene::IMeshBuffer *buf, u8 layer)
256 // Append to the correct layer
257 std::vector<MeshBufList> &list = lists[layer];
258 const video::SMaterial &m = buf->getMaterial();
259 for (MeshBufList &l : list) {
260 // comparing a full material is quite expensive so we don't do it if
261 // not even first texture is equal
262 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
266 l.bufs.push_back(buf);
272 l.bufs.push_back(buf);
277 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
279 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
282 if (pass == scene::ESNRP_SOLID)
283 prefix = "renderMap(SOLID): ";
285 prefix = "renderMap(TRANSPARENT): ";
288 This is called two times per frame, reset on the non-transparent one
290 if (pass == scene::ESNRP_SOLID)
291 m_last_drawn_sectors.clear();
294 Get animation parameters
296 float animation_time = m_client->getAnimationTime();
297 int crack = m_client->getCrackLevel();
298 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
300 v3f camera_position = m_camera_position;
301 v3f camera_direction = m_camera_direction;
302 f32 camera_fov = m_camera_fov;
305 Get all blocks and draw all visible ones
308 u32 vertex_count = 0;
310 // For limiting number of mesh animations per frame
311 u32 mesh_animate_count = 0;
312 //u32 mesh_animate_count_far = 0;
315 Draw the selected MapBlocks
318 MeshBufListList drawbufs;
320 for (auto &i : m_drawlist) {
321 MapBlock *block = i.second;
323 // If the mesh of the block happened to get deleted, ignore it
328 if (!isBlockInSight(block->getPos(), camera_position,
329 camera_direction, camera_fov, 100000 * BS, &d))
333 if (pass == scene::ESNRP_SOLID) {
334 //MutexAutoLock lock(block->mesh_mutex);
335 MapBlockMesh *mapBlockMesh = block->mesh;
336 assert(mapBlockMesh);
337 // Pretty random but this should work somewhat nicely
338 bool faraway = d >= BS * 50;
339 if (mapBlockMesh->isAnimationForced() || !faraway ||
340 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
342 bool animated = mapBlockMesh->animate(faraway, animation_time,
343 crack, daynight_ratio);
345 mesh_animate_count++;
347 mapBlockMesh->decreaseAnimationForceTimer();
352 Get the meshbuffers of the block
355 //MutexAutoLock lock(block->mesh_mutex);
357 MapBlockMesh *mapBlockMesh = block->mesh;
358 assert(mapBlockMesh);
360 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
361 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
364 u32 c = mesh->getMeshBufferCount();
365 for (u32 i = 0; i < c; i++) {
366 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
368 video::SMaterial& material = buf->getMaterial();
369 video::IMaterialRenderer* rnd =
370 driver->getMaterialRenderer(material.MaterialType);
371 bool transparent = (rnd && rnd->isTransparent());
372 if (transparent == is_transparent_pass) {
373 if (buf->getVertexCount() == 0)
374 errorstream << "Block [" << analyze_block(block)
375 << "] contains an empty meshbuf" << std::endl;
377 material.setFlag(video::EMF_TRILINEAR_FILTER,
378 m_cache_trilinear_filter);
379 material.setFlag(video::EMF_BILINEAR_FILTER,
380 m_cache_bilinear_filter);
381 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
382 m_cache_anistropic_filter);
383 material.setFlag(video::EMF_WIREFRAME,
384 m_control.show_wireframe);
386 drawbufs.add(buf, layer);
393 TimeTaker draw("Drawing mesh buffers");
395 // Render all layers in order
396 for (auto &lists : drawbufs.lists) {
397 for (MeshBufList &list : lists) {
398 // Check and abort if the machine is swapping a lot
399 if (draw.getTimerTime() > 2000) {
400 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
401 "returning." << std::endl;
404 driver->setMaterial(list.m);
406 for (scene::IMeshBuffer *buf : list.bufs) {
407 driver->drawMeshBuffer(buf);
408 vertex_count += buf->getVertexCount();
412 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
414 // Log only on solid pass because values are the same
415 if (pass == scene::ESNRP_SOLID) {
416 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
419 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
422 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
423 float step_multiplier, float start_distance, float end_distance,
424 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
425 int *result, bool *sunlight_seen)
427 int brightness_sum = 0;
428 int brightness_count = 0;
429 float distance = start_distance;
432 pf += dir * distance;
434 bool nonlight_seen = false;
435 bool allow_allowing_non_sunlight_propagates = false;
436 bool allow_non_sunlight_propagates = false;
437 // Check content nearly at camera position
439 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
440 MapNode n = map->getNode(p);
441 if(ndef->get(n).param_type == CPT_LIGHT &&
442 !ndef->get(n).sunlight_propagates)
443 allow_allowing_non_sunlight_propagates = true;
445 // If would start at CONTENT_IGNORE, start closer
447 v3s16 p = floatToInt(pf, BS);
448 MapNode n = map->getNode(p);
449 if(n.getContent() == CONTENT_IGNORE){
451 pf = p0 + dir * 2*newd;
456 for (int i=0; distance < end_distance; i++) {
459 step *= step_multiplier;
461 v3s16 p = floatToInt(pf, BS);
462 MapNode n = map->getNode(p);
463 if (allow_allowing_non_sunlight_propagates && i == 0 &&
464 ndef->get(n).param_type == CPT_LIGHT &&
465 !ndef->get(n).sunlight_propagates) {
466 allow_non_sunlight_propagates = true;
469 if (ndef->get(n).param_type != CPT_LIGHT ||
470 (!ndef->get(n).sunlight_propagates &&
471 !allow_non_sunlight_propagates)){
472 nonlight_seen = true;
479 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
480 if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
481 *sunlight_seen = true;
483 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
487 if(brightness_count == 0)
489 *result = brightness_sum / brightness_count;
490 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
491 <<(*result)<<std::endl;*/
495 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
496 int oldvalue, bool *sunlight_seen_result)
498 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
499 static v3f z_directions[50] = {
502 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
506 if(z_directions[0].X < -99){
507 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
508 // Assumes FOV of 72 and 16/9 aspect ratio
509 z_directions[i] = v3f(
510 0.02 * myrand_range(-100, 100),
512 0.01 * myrand_range(-100, 100)
514 z_offsets[i] = 0.01 * myrand_range(0,100);
518 int sunlight_seen_count = 0;
519 float sunlight_min_d = max_d*0.8;
520 if(sunlight_min_d > 35*BS)
521 sunlight_min_d = 35*BS;
522 std::vector<int> values;
523 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
524 v3f z_dir = z_directions[i];
525 core::CMatrix4<f32> a;
526 a.buildRotateFromTo(v3f(0,1,0), z_dir);
527 v3f dir = m_camera_direction;
532 step = max_d / 35 * 1.5;
533 float off = step * z_offsets[i];
534 bool sunlight_seen_now = false;
535 bool ok = getVisibleBrightness(this, m_camera_position, dir,
536 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
538 &br, &sunlight_seen_now);
539 if(sunlight_seen_now)
540 sunlight_seen_count++;
543 values.push_back(br);
544 // Don't try too much if being in the sun is clear
545 if(sunlight_seen_count >= 20)
548 int brightness_sum = 0;
549 int brightness_count = 0;
550 std::sort(values.begin(), values.end());
551 u32 num_values_to_use = values.size();
552 if(num_values_to_use >= 10)
553 num_values_to_use -= num_values_to_use/2;
554 else if(num_values_to_use >= 7)
555 num_values_to_use -= num_values_to_use/3;
556 u32 first_value_i = (values.size() - num_values_to_use) / 2;
558 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
559 brightness_sum += values[i];
564 if(brightness_count == 0){
565 MapNode n = getNode(floatToInt(m_camera_position, BS));
566 if(m_nodedef->get(n).param_type == CPT_LIGHT){
567 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
572 ret = brightness_sum / brightness_count;
575 *sunlight_seen_result = (sunlight_seen_count > 0);
579 void ClientMap::renderPostFx(CameraMode cam_mode)
581 // Sadly ISceneManager has no "post effects" render pass, in that case we
582 // could just register for that and handle it in renderMap().
584 MapNode n = getNode(floatToInt(m_camera_position, BS));
586 // - If the player is in a solid node, make everything black.
587 // - If the player is in liquid, draw a semi-transparent overlay.
588 // - Do not if player is in third person mode
589 const ContentFeatures& features = m_nodedef->get(n);
590 video::SColor post_effect_color = features.post_effect_color;
591 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
592 m_client->checkLocalPrivilege("noclip")) &&
593 cam_mode == CAMERA_MODE_FIRST)
595 post_effect_color = video::SColor(255, 0, 0, 0);
597 if (post_effect_color.getAlpha() != 0)
599 // Draw a full-screen rectangle
600 video::IVideoDriver* driver = SceneManager->getVideoDriver();
601 v2u32 ss = driver->getScreenSize();
602 core::rect<s32> rect(0,0, ss.X, ss.Y);
603 driver->draw2DRectangle(post_effect_color, rect);
607 void ClientMap::PrintInfo(std::ostream &out)