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"
34 // struct MeshBufListList
35 void MeshBufListList::clear()
37 for (auto &list : lists)
41 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
43 // Append to the correct layer
44 std::vector<MeshBufList> &list = lists[layer];
45 const video::SMaterial &m = buf->getMaterial();
46 for (MeshBufList &l : list) {
47 // comparing a full material is quite expensive so we don't do it if
48 // not even first texture is equal
49 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
53 l.bufs.emplace_back(position, buf);
59 l.bufs.emplace_back(position, buf);
67 MapDrawControl &control,
71 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
72 RenderingEngine::get_scene_manager(), id),
76 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
77 BS*1000000,BS*1000000,BS*1000000);
79 /* TODO: Add a callback function so these can be updated when a setting
80 * changes. At this point in time it doesn't matter (e.g. /set
81 * is documented to change server settings only)
83 * TODO: Local caching of settings is not optimal and should at some stage
84 * be updated to use a global settings object for getting thse values
85 * (as opposed to the this local caching). This can be addressed in
88 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
89 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
90 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
94 MapSector * ClientMap::emergeSector(v2s16 p2d)
96 // Check that it doesn't exist already
97 MapSector *sector = getSectorNoGenerate(p2d);
99 // Create it if it does not exist yet
101 sector = new MapSector(this, p2d, m_gamedef);
102 m_sectors[p2d] = sector;
108 void ClientMap::OnRegisterSceneNode()
112 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
113 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
116 ISceneNode::OnRegisterSceneNode();
119 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
120 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
122 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
123 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
124 // can exceed the range of v3s16 when a large view range is used near the
127 cam_pos_nodes.X - box_nodes_d.X,
128 cam_pos_nodes.Y - box_nodes_d.Y,
129 cam_pos_nodes.Z - box_nodes_d.Z);
131 cam_pos_nodes.X + box_nodes_d.X,
132 cam_pos_nodes.Y + box_nodes_d.Y,
133 cam_pos_nodes.Z + box_nodes_d.Z);
134 // Take a fair amount as we will be dropping more out later
135 // Umm... these additions are a bit strange but they are needed.
136 *p_blocks_min = v3s16(
137 p_nodes_min.X / MAP_BLOCKSIZE - 3,
138 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
139 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
140 *p_blocks_max = v3s16(
141 p_nodes_max.X / MAP_BLOCKSIZE + 1,
142 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
143 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
146 void ClientMap::updateDrawList()
148 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
150 for (auto &i : m_drawlist) {
151 MapBlock *block = i.second;
156 const v3f camera_position = m_camera_position;
157 const v3f camera_direction = m_camera_direction;
159 // Use a higher fov to accomodate faster camera movements.
160 // Blocks are cropped better when they are drawn.
161 const f32 camera_fov = m_camera_fov * 1.1f;
163 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
166 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
168 // Read the vision range, unless unlimited range is enabled.
169 float range = m_control.range_all ? 1e7 : m_control.wanted_range;
171 // Number of blocks currently loaded by the client
172 u32 blocks_loaded = 0;
173 // Number of blocks with mesh in rendering range
174 u32 blocks_in_range_with_mesh = 0;
175 // Number of blocks occlusion culled
176 u32 blocks_occlusion_culled = 0;
178 // No occlusion culling when free_move is on and camera is
180 bool occlusion_culling_enabled = true;
181 if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
182 MapNode n = getNode(cam_pos_nodes);
183 if (n.getContent() == CONTENT_IGNORE ||
184 m_nodedef->get(n).solidness == 2)
185 occlusion_culling_enabled = false;
189 // Uncomment to debug occluded blocks in the wireframe mode
190 // TODO: Include this as a flag for an extended debugging setting
191 //if (occlusion_culling_enabled && m_control.show_wireframe)
192 // occlusion_culling_enabled = porting::getTimeS() & 1;
194 for (const auto §or_it : m_sectors) {
195 MapSector *sector = sector_it.second;
196 v2s16 sp = sector->getPos();
198 blocks_loaded += sector->size();
199 if (!m_control.range_all) {
200 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
201 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
205 MapBlockVect sectorblocks;
206 sector->getBlocks(sectorblocks);
209 Loop through blocks in sector
212 u32 sector_blocks_drawn = 0;
214 for (MapBlock *block : sectorblocks) {
216 Compare block position to camera position, skip
217 if not seen on display
221 // Ignore if mesh doesn't exist
225 v3s16 block_coord = block->getPos();
226 v3s16 block_position = block->getPosRelative() + MAP_BLOCKSIZE / 2;
228 // First, perform a simple distance check, with a padding of one extra block.
229 if (!m_control.range_all &&
230 block_position.getDistanceFrom(cam_pos_nodes) > range + MAP_BLOCKSIZE)
231 continue; // Out of range, skip.
233 // Keep the block alive as long as it is in range.
234 block->resetUsageTimer();
235 blocks_in_range_with_mesh++;
239 if (!isBlockInSight(block_coord, camera_position,
240 camera_direction, camera_fov, range * BS, &d))
244 if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
245 (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
246 blocks_occlusion_culled++;
252 m_drawlist[block_coord] = block;
254 sector_blocks_drawn++;
255 } // foreach sectorblocks
257 if (sector_blocks_drawn != 0)
258 m_last_drawn_sectors.insert(sp);
261 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
262 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
263 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
264 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
267 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
269 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
272 if (pass == scene::ESNRP_SOLID)
273 prefix = "renderMap(SOLID): ";
275 prefix = "renderMap(TRANSPARENT): ";
278 This is called two times per frame, reset on the non-transparent one
280 if (pass == scene::ESNRP_SOLID)
281 m_last_drawn_sectors.clear();
284 Get animation parameters
286 const float animation_time = m_client->getAnimationTime();
287 const int crack = m_client->getCrackLevel();
288 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
290 const v3f camera_position = m_camera_position;
293 Get all blocks and draw all visible ones
296 u32 vertex_count = 0;
297 u32 drawcall_count = 0;
299 // For limiting number of mesh animations per frame
300 u32 mesh_animate_count = 0;
301 //u32 mesh_animate_count_far = 0;
304 Draw the selected MapBlocks
307 MeshBufListList drawbufs;
309 for (auto &i : m_drawlist) {
310 v3s16 block_pos = i.first;
311 MapBlock *block = i.second;
313 // If the mesh of the block happened to get deleted, ignore it
317 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
318 float d = camera_position.getDistanceFrom(block_pos_r);
319 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
322 if (pass == scene::ESNRP_SOLID) {
323 //MutexAutoLock lock(block->mesh_mutex);
324 MapBlockMesh *mapBlockMesh = block->mesh;
325 assert(mapBlockMesh);
326 // Pretty random but this should work somewhat nicely
327 bool faraway = d >= BS * 50;
328 if (mapBlockMesh->isAnimationForced() || !faraway ||
329 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
331 bool animated = mapBlockMesh->animate(faraway, animation_time,
332 crack, daynight_ratio);
334 mesh_animate_count++;
336 mapBlockMesh->decreaseAnimationForceTimer();
341 Get the meshbuffers of the block
344 //MutexAutoLock lock(block->mesh_mutex);
346 MapBlockMesh *mapBlockMesh = block->mesh;
347 assert(mapBlockMesh);
349 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
350 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
353 u32 c = mesh->getMeshBufferCount();
354 for (u32 i = 0; i < c; i++) {
355 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
357 video::SMaterial& material = buf->getMaterial();
358 video::IMaterialRenderer* rnd =
359 driver->getMaterialRenderer(material.MaterialType);
360 bool transparent = (rnd && rnd->isTransparent());
361 if (transparent == is_transparent_pass) {
362 if (buf->getVertexCount() == 0)
363 errorstream << "Block [" << analyze_block(block)
364 << "] contains an empty meshbuf" << std::endl;
366 material.setFlag(video::EMF_TRILINEAR_FILTER,
367 m_cache_trilinear_filter);
368 material.setFlag(video::EMF_BILINEAR_FILTER,
369 m_cache_bilinear_filter);
370 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
371 m_cache_anistropic_filter);
372 material.setFlag(video::EMF_WIREFRAME,
373 m_control.show_wireframe);
375 drawbufs.add(buf, block_pos, layer);
382 TimeTaker draw("Drawing mesh buffers");
384 core::matrix4 m; // Model matrix
385 v3f offset = intToFloat(m_camera_offset, BS);
387 // Render all layers in order
388 for (auto &lists : drawbufs.lists) {
389 for (MeshBufList &list : lists) {
390 // Check and abort if the machine is swapping a lot
391 if (draw.getTimerTime() > 2000) {
392 infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
393 "returning." << std::endl;
396 driver->setMaterial(list.m);
398 drawcall_count += list.bufs.size();
399 for (auto &pair : list.bufs) {
400 scene::IMeshBuffer *buf = pair.second;
402 v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS);
403 m.setTranslation(block_wpos - offset);
405 driver->setTransform(video::ETS_WORLD, m);
406 driver->drawMeshBuffer(buf);
407 vertex_count += buf->getVertexCount();
411 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
413 // Log only on solid pass because values are the same
414 if (pass == scene::ESNRP_SOLID) {
415 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
418 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
419 g_profiler->avg(prefix + "drawcalls [#]", drawcall_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)