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"
31 #include "client/renderingengine.h"
35 // struct MeshBufListList
36 void MeshBufListList::clear()
38 for (auto &list : lists)
42 void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer)
44 // Append to the correct layer
45 std::vector<MeshBufList> &list = lists[layer];
46 const video::SMaterial &m = buf->getMaterial();
47 for (MeshBufList &l : list) {
48 // comparing a full material is quite expensive so we don't do it if
49 // not even first texture is equal
50 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
54 l.bufs.emplace_back(position, buf);
60 l.bufs.emplace_back(position, buf);
64 static void on_settings_changed(const std::string &name, void *data)
66 static_cast<ClientMap*>(data)->onSettingChanged(name);
72 RenderingEngine *rendering_engine,
73 MapDrawControl &control,
77 scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(),
78 rendering_engine->get_scene_manager(), id),
80 m_rendering_engine(rendering_engine),
82 m_drawlist(MapBlockComparer(v3s16(0,0,0)))
86 * @Liso: Sadly C++ doesn't have introspection, so the only way we have to know
87 * the class is whith a name ;) Name property cames from ISceneNode base class.
90 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
91 BS*1000000,BS*1000000,BS*1000000);
93 /* TODO: Add a callback function so these can be updated when a setting
94 * changes. At this point in time it doesn't matter (e.g. /set
95 * is documented to change server settings only)
97 * TODO: Local caching of settings is not optimal and should at some stage
98 * be updated to use a global settings object for getting thse values
99 * (as opposed to the this local caching). This can be addressed in
102 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
103 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
104 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
105 m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance");
106 m_new_occlusion_culler = g_settings->get("occlusion_culler") == "bfs";
107 g_settings->registerChangedCallback("occlusion_culler", on_settings_changed, this);
108 m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
109 g_settings->registerChangedCallback("enable_raytraced_culling", on_settings_changed, this);
112 void ClientMap::onSettingChanged(const std::string &name)
114 if (name == "occlusion_culler")
115 m_new_occlusion_culler = g_settings->get("occlusion_culler") == "bfs";
116 if (name == "enable_raytraced_culling")
117 m_enable_raytraced_culling = g_settings->getBool("enable_raytraced_culling");
120 ClientMap::~ClientMap()
122 g_settings->deregisterChangedCallback("occlusion_culler", on_settings_changed, this);
123 g_settings->deregisterChangedCallback("enable_raytraced_culling", on_settings_changed, this);
126 void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset)
128 v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset;
129 v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE);
131 m_camera_position = pos;
132 m_camera_direction = dir;
134 m_camera_offset = offset;
136 v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset;
137 v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE);
139 // reorder the blocks when camera crosses block boundary
140 if (previous_block != current_block)
141 m_needs_update_drawlist = true;
143 // reorder transparent meshes when camera crosses node boundary
144 if (previous_node != current_node)
145 m_needs_update_transparent_meshes = true;
148 MapSector * ClientMap::emergeSector(v2s16 p2d)
150 // Check that it doesn't exist already
151 MapSector *sector = getSectorNoGenerate(p2d);
153 // Create it if it does not exist yet
155 sector = new MapSector(this, p2d, m_gamedef);
156 m_sectors[p2d] = sector;
162 void ClientMap::OnRegisterSceneNode()
166 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
167 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
170 ISceneNode::OnRegisterSceneNode();
171 // It's not needed to register this node to the shadow renderer
172 // we have other way to find it
175 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
176 v3s16 *p_blocks_min, v3s16 *p_blocks_max, float range)
179 range = m_control.wanted_range;
181 v3s16 box_nodes_d = range * v3s16(1, 1, 1);
182 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
183 // can exceed the range of v3s16 when a large view range is used near the
186 cam_pos_nodes.X - box_nodes_d.X,
187 cam_pos_nodes.Y - box_nodes_d.Y,
188 cam_pos_nodes.Z - box_nodes_d.Z);
190 cam_pos_nodes.X + box_nodes_d.X,
191 cam_pos_nodes.Y + box_nodes_d.Y,
192 cam_pos_nodes.Z + box_nodes_d.Z);
193 // Take a fair amount as we will be dropping more out later
194 // Umm... these additions are a bit strange but they are needed.
195 *p_blocks_min = v3s16(
196 p_nodes_min.X / MAP_BLOCKSIZE - 3,
197 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
198 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
199 *p_blocks_max = v3s16(
200 p_nodes_max.X / MAP_BLOCKSIZE + 1,
201 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
202 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
208 static constexpr u16 CHUNK_EDGE = 8;
209 static constexpr u16 CHUNK_MASK = CHUNK_EDGE - 1;
210 static constexpr std::size_t CHUNK_VOLUME = CHUNK_EDGE * CHUNK_EDGE * CHUNK_EDGE; // volume of a chunk
212 MapBlockFlags(v3s16 min_pos, v3s16 max_pos)
213 : min_pos(min_pos), volume((max_pos - min_pos) / CHUNK_EDGE + 1)
215 chunks.resize(volume.X * volume.Y * volume.Z);
221 inline u8 &getBits(v3s16 pos)
223 std::size_t address = getAddress(pos);
224 return bits[address];
228 inline std::size_t getAddress(v3s16 pos) {
229 std::size_t address = (pos.X & CHUNK_MASK) + (pos.Y & CHUNK_MASK) * CHUNK_EDGE + (pos.Z & CHUNK_MASK) * (CHUNK_EDGE * CHUNK_EDGE);
233 std::array<u8, CHUNK_VOLUME> bits;
236 Chunk &getChunk(v3s16 pos)
238 v3s16 delta = (pos - min_pos) / CHUNK_EDGE;
239 std::size_t address = delta.X + delta.Y * volume.X + delta.Z * volume.X * volume.Y;
240 Chunk *chunk = chunks[address].get();
243 chunks[address].reset(chunk);
248 std::vector<std::unique_ptr<Chunk>> chunks;
253 void ClientMap::updateDrawList()
255 if (m_new_occlusion_culler) {
256 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
258 m_needs_update_drawlist = false;
260 for (auto &i : m_drawlist) {
261 MapBlock *block = i.second;
266 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
270 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
272 // Number of blocks occlusion culled
273 u32 blocks_occlusion_culled = 0;
274 // Blocks visited by the algorithm
275 u32 blocks_visited = 0;
276 // Block sides that were not traversed
277 u32 sides_skipped = 0;
279 // No occlusion culling when free_move is on and camera is inside ground
280 bool occlusion_culling_enabled = true;
281 if (m_control.allow_noclip) {
282 MapNode n = getNode(cam_pos_nodes);
283 if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
284 occlusion_culling_enabled = false;
287 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
288 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
290 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
292 // Uncomment to debug occluded blocks in the wireframe mode
293 // TODO: Include this as a flag for an extended debugging setting
294 // if (occlusion_culling_enabled && m_control.show_wireframe)
295 // occlusion_culling_enabled = porting::getTimeS() & 1;
297 std::queue<v3s16> blocks_to_consider;
300 // [ visited | 0 | 0 | 0 | 0 | Z visible | Y visible | X visible ]
301 MapBlockFlags blocks_seen(p_blocks_min, p_blocks_max);
303 // Start breadth-first search with the block the camera is in
304 blocks_to_consider.push(camera_block);
305 blocks_seen.getChunk(camera_block).getBits(camera_block) = 0x07; // mark all sides as visible
307 // Recursively walk the space and pick mapblocks for drawing
308 while (blocks_to_consider.size() > 0) {
310 v3s16 block_coord = blocks_to_consider.front();
311 blocks_to_consider.pop();
313 auto &flags = blocks_seen.getChunk(block_coord).getBits(block_coord);
315 // Only visit each block once (it may have been queued up to three times)
316 if ((flags & 0x80) == 0x80)
322 // Get the sector, block and mesh
323 MapSector *sector = this->getSectorNoGenerate(v2s16(block_coord.X, block_coord.Z));
328 MapBlock *block = sector->getBlockNoCreateNoEx(block_coord.Y);
330 MapBlockMesh *mesh = block ? block->mesh : nullptr;
333 // Calculate the coordinates for range and frutum culling
334 v3f mesh_sphere_center;
335 f32 mesh_sphere_radius;
337 v3s16 block_pos_nodes = block_coord * MAP_BLOCKSIZE;
340 mesh_sphere_center = intToFloat(block_pos_nodes, BS)
341 + mesh->getBoundingSphereCenter();
342 mesh_sphere_radius = mesh->getBoundingRadius();
345 mesh_sphere_center = intToFloat(block_pos_nodes, BS) + v3f((MAP_BLOCKSIZE * 0.5f - 0.5f) * BS);
346 mesh_sphere_radius = 0.0f;
349 // First, perform a simple distance check.
350 if (!m_control.range_all &&
351 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
352 m_control.wanted_range * BS + mesh_sphere_radius)
353 continue; // Out of range, skip.
356 // Only do coarse culling here, to account for fast camera movement.
357 // This is needed because this function is not called every frame.
358 float frustum_cull_extra_radius = 300.0f;
359 if (is_frustum_culled(mesh_sphere_center,
360 mesh_sphere_radius + frustum_cull_extra_radius))
363 // Calculate the vector from the camera block to the current block
364 // We use it to determine through which sides of the current block we can continue the search
365 v3s16 look = block_coord - camera_block;
367 // Occluded near sides will further occlude the far sides
368 u8 visible_outer_sides = flags & 0x07;
370 // Raytraced occlusion culling - send rays from the camera to the block's corners
371 if (occlusion_culling_enabled && m_enable_raytraced_culling &&
373 visible_outer_sides != 0x07 && isBlockOccluded(block, cam_pos_nodes)) {
374 blocks_occlusion_culled++;
378 // The block is visible, add to the draw list
382 m_drawlist[block_coord] = block;
385 // Decide which sides to traverse next or to block away
387 // First, find the near sides that would occlude the far sides
388 // * A near side can itself be occluded by a nearby block (the test above ^^)
389 // * A near side can be visible but fully opaque by itself (e.g. ground at the 0 level)
391 // mesh solid sides are +Z-Z+Y-Y+X-X
392 // if we are inside the block's coordinates on an axis,
393 // treat these sides as opaque, as they should not allow to reach the far sides
394 u8 block_inner_sides = (look.X == 0 ? 3 : 0) |
395 (look.Y == 0 ? 12 : 0) |
396 (look.Z == 0 ? 48 : 0);
398 // get the mask for the sides that are relevant based on the direction
399 u8 near_inner_sides = (look.X > 0 ? 1 : 2) |
400 (look.Y > 0 ? 4 : 8) |
401 (look.Z > 0 ? 16 : 32);
403 // This bitset is +Z-Z+Y-Y+X-X (See MapBlockMesh), and axis is XYZ.
404 // Get he block's transparent sides
405 u8 transparent_sides = (occlusion_culling_enabled && block) ? ~block->solid_sides : 0x3F;
407 // compress block transparent sides to ZYX mask of see-through axes
408 u8 near_transparency = (block_inner_sides == 0x3F) ? near_inner_sides : (transparent_sides & near_inner_sides);
410 // when we are inside the camera block, do not block any sides
411 if (block_inner_sides == 0x3F)
412 block_inner_sides = 0;
414 near_transparency &= ~block_inner_sides & 0x3F;
416 near_transparency |= (near_transparency >> 1);
417 near_transparency = (near_transparency & 1) |
418 ((near_transparency >> 1) & 2) |
419 ((near_transparency >> 2) & 4);
421 // combine with known visible sides that matter
422 near_transparency &= visible_outer_sides;
424 // The rule for any far side to be visible:
425 // * Any of the adjacent near sides is transparent (different axes)
426 // * The opposite near side (same axis) is transparent, if it is the dominant axis of the look vector
428 // Calculate vector from camera to mapblock center. Because we only need relation between
429 // coordinates we scale by 2 to avoid precision loss.
430 v3s16 precise_look = 2 * (block_pos_nodes - cam_pos_nodes) + MAP_BLOCKSIZE - 1;
432 // dominant axis flag
433 u8 dominant_axis = (abs(precise_look.X) > abs(precise_look.Y) && abs(precise_look.X) > abs(precise_look.Z)) |
434 ((abs(precise_look.Y) > abs(precise_look.Z) && abs(precise_look.Y) > abs(precise_look.X)) << 1) |
435 ((abs(precise_look.Z) > abs(precise_look.X) && abs(precise_look.Z) > abs(precise_look.Y)) << 2);
437 // Queue next blocks for processing:
438 // - Examine "far" sides of the current blocks, i.e. never move towards the camera
439 // - Only traverse the sides that are not occluded
440 // - Only traverse the sides that are not opaque
441 // When queueing, mark the relevant side on the next block as 'visible'
442 for (s16 axis = 0; axis < 3; axis++) {
444 // Select a bit from transparent_sides for the side
445 u8 far_side_mask = 1 << (2 * axis);
448 u8 my_side = 1 << axis;
449 u8 adjacent_sides = my_side ^ 0x07;
451 auto traverse_far_side = [&](s8 next_pos_offset) {
452 // far side is visible if adjacent near sides are transparent, or if opposite side on dominant axis is transparent
453 bool side_visible = ((near_transparency & adjacent_sides) | (near_transparency & my_side & dominant_axis)) != 0;
454 side_visible = side_visible && ((far_side_mask & transparent_sides) != 0);
456 v3s16 next_pos = block_coord;
457 next_pos[axis] += next_pos_offset;
459 // If a side is a see-through, mark the next block's side as visible, and queue
461 auto &next_flags = blocks_seen.getChunk(next_pos).getBits(next_pos);
462 next_flags |= my_side;
463 blocks_to_consider.push(next_pos);
471 // Test the '-' direction of the axis
472 if (look[axis] <= 0 && block_coord[axis] > p_blocks_min[axis])
473 traverse_far_side(-1);
475 // Test the '+' direction of the axis
478 if (look[axis] >= 0 && block_coord[axis] < p_blocks_max[axis])
479 traverse_far_side(+1);
483 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
484 g_profiler->avg("MapBlocks sides skipped [#]", sides_skipped);
485 g_profiler->avg("MapBlocks examined [#]", blocks_visited);
486 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
489 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
491 m_needs_update_drawlist = false;
493 for (auto &i : m_drawlist) {
494 MapBlock *block = i.second;
499 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
503 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
505 // Number of blocks currently loaded by the client
506 u32 blocks_loaded = 0;
507 // Number of blocks with mesh in rendering range
508 u32 blocks_in_range_with_mesh = 0;
509 // Number of blocks occlusion culled
510 u32 blocks_occlusion_culled = 0;
512 // No occlusion culling when free_move is on and camera is inside ground
513 bool occlusion_culling_enabled = true;
514 if (m_control.allow_noclip) {
515 MapNode n = getNode(cam_pos_nodes);
516 if (n.getContent() == CONTENT_IGNORE || m_nodedef->get(n).solidness == 2)
517 occlusion_culling_enabled = false;
520 v3s16 camera_block = getContainerPos(cam_pos_nodes, MAP_BLOCKSIZE);
521 m_drawlist = std::map<v3s16, MapBlock*, MapBlockComparer>(MapBlockComparer(camera_block));
523 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
525 // Uncomment to debug occluded blocks in the wireframe mode
526 // TODO: Include this as a flag for an extended debugging setting
527 //if (occlusion_culling_enabled && m_control.show_wireframe)
528 // occlusion_culling_enabled = porting::getTimeS() & 1;
530 for (const auto §or_it : m_sectors) {
531 MapSector *sector = sector_it.second;
532 v2s16 sp = sector->getPos();
534 blocks_loaded += sector->size();
535 if (!m_control.range_all) {
536 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
537 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
541 MapBlockVect sectorblocks;
542 sector->getBlocks(sectorblocks);
545 Loop through blocks in sector
548 u32 sector_blocks_drawn = 0;
550 for (MapBlock *block : sectorblocks) {
552 Compare block position to camera position, skip
553 if not seen on display
557 // Ignore if mesh doesn't exist
561 v3s16 block_coord = block->getPos();
562 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
563 + block->mesh->getBoundingSphereCenter();
564 f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
565 // First, perform a simple distance check.
566 if (!m_control.range_all &&
567 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
568 m_control.wanted_range * BS + mesh_sphere_radius)
569 continue; // Out of range, skip.
571 // Keep the block alive as long as it is in range.
572 block->resetUsageTimer();
573 blocks_in_range_with_mesh++;
576 // Only do coarse culling here, to account for fast camera movement.
577 // This is needed because this function is not called every frame.
578 constexpr float frustum_cull_extra_radius = 300.0f;
579 if (is_frustum_culled(mesh_sphere_center,
580 mesh_sphere_radius + frustum_cull_extra_radius))
584 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
585 blocks_occlusion_culled++;
591 m_drawlist[block_coord] = block;
593 sector_blocks_drawn++;
594 } // foreach sectorblocks
596 if (sector_blocks_drawn != 0)
597 m_last_drawn_sectors.insert(sp);
600 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
601 g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
602 g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
603 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
607 void ClientMap::touchMapBlocks()
609 if (!m_new_occlusion_culler)
612 v3s16 cam_pos_nodes = floatToInt(m_camera_position, BS);
616 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
618 // Number of blocks currently loaded by the client
619 u32 blocks_loaded = 0;
620 // Number of blocks with mesh in rendering range
621 u32 blocks_in_range_with_mesh = 0;
623 for (const auto §or_it : m_sectors) {
624 MapSector *sector = sector_it.second;
625 v2s16 sp = sector->getPos();
627 blocks_loaded += sector->size();
628 if (!m_control.range_all) {
629 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
630 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
634 MapBlockVect sectorblocks;
635 sector->getBlocks(sectorblocks);
638 Loop through blocks in sector
641 for (MapBlock *block : sectorblocks) {
643 Compare block position to camera position, skip
644 if not seen on display
648 // Ignore if mesh doesn't exist
652 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
653 + block->mesh->getBoundingSphereCenter();
654 f32 mesh_sphere_radius = block->mesh->getBoundingRadius();
655 // First, perform a simple distance check.
656 if (!m_control.range_all &&
657 mesh_sphere_center.getDistanceFrom(intToFloat(cam_pos_nodes, BS)) >
658 m_control.wanted_range * BS + mesh_sphere_radius)
659 continue; // Out of range, skip.
661 // Keep the block alive as long as it is in range.
662 block->resetUsageTimer();
663 blocks_in_range_with_mesh++;
666 g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
667 g_profiler->avg("MapBlocks loaded [#]", blocks_loaded);
670 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
672 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
675 if (pass == scene::ESNRP_SOLID)
676 prefix = "renderMap(SOLID): ";
678 prefix = "renderMap(TRANSPARENT): ";
681 This is called two times per frame, reset on the non-transparent one
683 if (pass == scene::ESNRP_SOLID)
684 m_last_drawn_sectors.clear();
687 Get animation parameters
689 const float animation_time = m_client->getAnimationTime();
690 const int crack = m_client->getCrackLevel();
691 const u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
693 const v3f camera_position = m_camera_position;
696 Get all blocks and draw all visible ones
699 u32 vertex_count = 0;
700 u32 drawcall_count = 0;
702 // For limiting number of mesh animations per frame
703 u32 mesh_animate_count = 0;
704 //u32 mesh_animate_count_far = 0;
707 Update transparent meshes
709 if (is_transparent_pass)
710 updateTransparentMeshBuffers();
713 Draw the selected MapBlocks
716 MeshBufListList grouped_buffers;
717 std::vector<DrawDescriptor> draw_order;
718 video::SMaterial previous_material;
720 auto is_frustum_culled = m_client->getCamera()->getFrustumCuller();
722 for (auto &i : m_drawlist) {
723 v3s16 block_pos = i.first;
724 MapBlock *block = i.second;
725 MapBlockMesh *block_mesh = block->mesh;
727 // If the mesh of the block happened to get deleted, ignore it
731 // Do exact frustum culling
732 // (The one in updateDrawList is only coarse.)
733 v3f mesh_sphere_center = intToFloat(block->getPosRelative(), BS)
734 + block_mesh->getBoundingSphereCenter();
735 f32 mesh_sphere_radius = block_mesh->getBoundingRadius();
736 if (is_frustum_culled(mesh_sphere_center, mesh_sphere_radius))
739 v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS);
741 float d = camera_position.getDistanceFrom(block_pos_r);
742 d = MYMAX(0,d - BLOCK_MAX_RADIUS);
745 if (pass == scene::ESNRP_SOLID) {
746 // Pretty random but this should work somewhat nicely
747 bool faraway = d >= BS * 50;
748 if (block_mesh->isAnimationForced() || !faraway ||
749 mesh_animate_count < (m_control.range_all ? 200 : 50)) {
751 bool animated = block_mesh->animate(faraway, animation_time,
752 crack, daynight_ratio);
754 mesh_animate_count++;
756 block_mesh->decreaseAnimationForceTimer();
761 Get the meshbuffers of the block
763 if (is_transparent_pass) {
764 // In transparent pass, the mesh will give us
765 // the partial buffers in the correct order
766 for (auto &buffer : block_mesh->getTransparentBuffers())
767 draw_order.emplace_back(block_pos, &buffer);
770 // otherwise, group buffers across meshes
771 // using MeshBufListList
772 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
773 scene::IMesh *mesh = block_mesh->getMesh(layer);
776 u32 c = mesh->getMeshBufferCount();
777 for (u32 i = 0; i < c; i++) {
778 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
780 video::SMaterial& material = buf->getMaterial();
781 video::IMaterialRenderer* rnd =
782 driver->getMaterialRenderer(material.MaterialType);
783 bool transparent = (rnd && rnd->isTransparent());
785 if (buf->getVertexCount() == 0)
786 errorstream << "Block [" << analyze_block(block)
787 << "] contains an empty meshbuf" << std::endl;
789 grouped_buffers.add(buf, block_pos, layer);
796 // Capture draw order for all solid meshes
797 for (auto &lists : grouped_buffers.lists) {
798 for (MeshBufList &list : lists) {
799 // iterate in reverse to draw closest blocks first
800 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) {
801 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
806 TimeTaker draw("Drawing mesh buffers");
808 core::matrix4 m; // Model matrix
809 v3f offset = intToFloat(m_camera_offset, BS);
810 u32 material_swaps = 0;
812 // Render all mesh buffers in order
813 drawcall_count += draw_order.size();
815 for (auto &descriptor : draw_order) {
816 scene::IMeshBuffer *buf = descriptor.getBuffer();
818 if (!descriptor.m_reuse_material) {
819 auto &material = buf->getMaterial();
821 // Apply filter settings
822 material.setFlag(video::EMF_TRILINEAR_FILTER,
823 m_cache_trilinear_filter);
824 material.setFlag(video::EMF_BILINEAR_FILTER,
825 m_cache_bilinear_filter);
826 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
827 m_cache_anistropic_filter);
828 material.setFlag(video::EMF_WIREFRAME,
829 m_control.show_wireframe);
831 // pass the shadow map texture to the buffer texture
832 ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer();
833 if (shadow && shadow->is_active()) {
834 auto &layer = material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW];
835 layer.Texture = shadow->get_texture();
836 layer.TextureWrapU = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
837 layer.TextureWrapV = video::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
838 // Do not enable filter on shadow texture to avoid visual artifacts
839 // with colored shadows.
840 // Filtering is done in shader code anyway
841 layer.BilinearFilter = false;
842 layer.AnisotropicFilter = false;
843 layer.TrilinearFilter = false;
845 driver->setMaterial(material);
847 material.TextureLayer[ShadowRenderer::TEXTURE_LAYER_SHADOW].Texture = nullptr;
850 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
851 m.setTranslation(block_wpos - offset);
853 driver->setTransform(video::ETS_WORLD, m);
854 descriptor.draw(driver);
855 vertex_count += buf->getIndexCount();
858 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
860 // Log only on solid pass because values are the same
861 if (pass == scene::ESNRP_SOLID) {
862 g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
865 if (pass == scene::ESNRP_TRANSPARENT) {
866 g_profiler->avg("renderMap(): transparent buffers [#]", draw_order.size());
869 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
870 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
871 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
874 static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
875 float step_multiplier, float start_distance, float end_distance,
876 const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
877 int *result, bool *sunlight_seen)
879 int brightness_sum = 0;
880 int brightness_count = 0;
881 float distance = start_distance;
884 pf += dir * distance;
886 bool nonlight_seen = false;
887 bool allow_allowing_non_sunlight_propagates = false;
888 bool allow_non_sunlight_propagates = false;
889 // Check content nearly at camera position
891 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
892 MapNode n = map->getNode(p);
893 if(ndef->getLightingFlags(n).has_light &&
894 !ndef->getLightingFlags(n).sunlight_propagates)
895 allow_allowing_non_sunlight_propagates = true;
897 // If would start at CONTENT_IGNORE, start closer
899 v3s16 p = floatToInt(pf, BS);
900 MapNode n = map->getNode(p);
901 if(n.getContent() == CONTENT_IGNORE){
903 pf = p0 + dir * 2*newd;
908 for (int i=0; distance < end_distance; i++) {
911 step *= step_multiplier;
913 v3s16 p = floatToInt(pf, BS);
914 MapNode n = map->getNode(p);
915 ContentLightingFlags f = ndef->getLightingFlags(n);
916 if (allow_allowing_non_sunlight_propagates && i == 0 &&
917 f.has_light && !f.sunlight_propagates) {
918 allow_non_sunlight_propagates = true;
921 if (!f.has_light || (!f.sunlight_propagates && !allow_non_sunlight_propagates)){
922 nonlight_seen = true;
929 if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
930 if (n.getLight(LIGHTBANK_DAY, f) == LIGHT_SUN)
931 *sunlight_seen = true;
933 brightness_sum += decode_light(n.getLightBlend(daylight_factor, f));
937 if(brightness_count == 0)
939 *result = brightness_sum / brightness_count;
940 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
941 <<(*result)<<std::endl;*/
945 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
946 int oldvalue, bool *sunlight_seen_result)
948 ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
949 static v3f z_directions[50] = {
952 static f32 z_offsets[50] = {
956 if (z_directions[0].X < -99) {
957 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
958 // Assumes FOV of 72 and 16/9 aspect ratio
959 z_directions[i] = v3f(
960 0.02 * myrand_range(-100, 100),
962 0.01 * myrand_range(-100, 100)
964 z_offsets[i] = 0.01 * myrand_range(0,100);
968 int sunlight_seen_count = 0;
969 float sunlight_min_d = max_d*0.8;
970 if(sunlight_min_d > 35*BS)
971 sunlight_min_d = 35*BS;
972 std::vector<int> values;
973 values.reserve(ARRLEN(z_directions));
974 for (u32 i = 0; i < ARRLEN(z_directions); i++) {
975 v3f z_dir = z_directions[i];
976 core::CMatrix4<f32> a;
977 a.buildRotateFromTo(v3f(0,1,0), z_dir);
978 v3f dir = m_camera_direction;
983 step = max_d / 35 * 1.5;
984 float off = step * z_offsets[i];
985 bool sunlight_seen_now = false;
986 bool ok = getVisibleBrightness(this, m_camera_position, dir,
987 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
989 &br, &sunlight_seen_now);
990 if(sunlight_seen_now)
991 sunlight_seen_count++;
994 values.push_back(br);
995 // Don't try too much if being in the sun is clear
996 if(sunlight_seen_count >= 20)
999 int brightness_sum = 0;
1000 int brightness_count = 0;
1001 std::sort(values.begin(), values.end());
1002 u32 num_values_to_use = values.size();
1003 if(num_values_to_use >= 10)
1004 num_values_to_use -= num_values_to_use/2;
1005 else if(num_values_to_use >= 7)
1006 num_values_to_use -= num_values_to_use/3;
1007 u32 first_value_i = (values.size() - num_values_to_use) / 2;
1009 for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
1010 brightness_sum += values[i];
1015 if(brightness_count == 0){
1016 MapNode n = getNode(floatToInt(m_camera_position, BS));
1017 ContentLightingFlags f = m_nodedef->getLightingFlags(n);
1019 ret = decode_light(n.getLightBlend(daylight_factor, f));
1024 ret = brightness_sum / brightness_count;
1027 *sunlight_seen_result = (sunlight_seen_count > 0);
1031 void ClientMap::renderPostFx(CameraMode cam_mode)
1033 // Sadly ISceneManager has no "post effects" render pass, in that case we
1034 // could just register for that and handle it in renderMap().
1036 MapNode n = getNode(floatToInt(m_camera_position, BS));
1038 const ContentFeatures& features = m_nodedef->get(n);
1039 video::SColor post_effect_color = features.post_effect_color;
1041 // If the camera is in a solid node, make everything black.
1042 // (first person mode only)
1043 if (features.solidness == 2 && cam_mode == CAMERA_MODE_FIRST &&
1044 !m_control.allow_noclip) {
1045 post_effect_color = video::SColor(255, 0, 0, 0);
1048 if (post_effect_color.getAlpha() != 0) {
1049 // Draw a full-screen rectangle
1050 video::IVideoDriver* driver = SceneManager->getVideoDriver();
1051 v2u32 ss = driver->getScreenSize();
1052 core::rect<s32> rect(0,0, ss.X, ss.Y);
1053 driver->draw2DRectangle(post_effect_color, rect);
1057 void ClientMap::PrintInfo(std::ostream &out)
1062 void ClientMap::renderMapShadows(video::IVideoDriver *driver,
1063 const video::SMaterial &material, s32 pass, int frame, int total_frames)
1065 bool is_transparent_pass = pass != scene::ESNRP_SOLID;
1067 if (is_transparent_pass)
1068 prefix = "renderMap(SHADOW TRANS): ";
1070 prefix = "renderMap(SHADOW SOLID): ";
1072 u32 drawcall_count = 0;
1073 u32 vertex_count = 0;
1075 MeshBufListList grouped_buffers;
1076 std::vector<DrawDescriptor> draw_order;
1080 int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame;
1081 int high_bound = is_transparent_pass ? m_drawlist_shadow.size() : m_drawlist_shadow.size() / total_frames * (frame + 1);
1083 // transparent pass should be rendered in one go
1084 if (is_transparent_pass && frame != total_frames - 1) {
1088 for (const auto &i : m_drawlist_shadow) {
1089 // only process specific part of the list & break early
1091 if (count <= low_bound)
1093 if (count > high_bound)
1096 v3s16 block_pos = i.first;
1097 MapBlock *block = i.second;
1099 // If the mesh of the block happened to get deleted, ignore it
1104 Get the meshbuffers of the block
1106 if (is_transparent_pass) {
1107 // In transparent pass, the mesh will give us
1108 // the partial buffers in the correct order
1109 for (auto &buffer : block->mesh->getTransparentBuffers())
1110 draw_order.emplace_back(block_pos, &buffer);
1113 // otherwise, group buffers across meshes
1114 // using MeshBufListList
1115 MapBlockMesh *mapBlockMesh = block->mesh;
1116 assert(mapBlockMesh);
1118 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
1119 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
1122 u32 c = mesh->getMeshBufferCount();
1123 for (u32 i = 0; i < c; i++) {
1124 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
1126 video::SMaterial &mat = buf->getMaterial();
1127 auto rnd = driver->getMaterialRenderer(mat.MaterialType);
1128 bool transparent = rnd && rnd->isTransparent();
1130 grouped_buffers.add(buf, block_pos, layer);
1136 u32 buffer_count = 0;
1137 for (auto &lists : grouped_buffers.lists)
1138 for (MeshBufList &list : lists)
1139 buffer_count += list.bufs.size();
1141 draw_order.reserve(draw_order.size() + buffer_count);
1143 // Capture draw order for all solid meshes
1144 for (auto &lists : grouped_buffers.lists) {
1145 for (MeshBufList &list : lists) {
1146 // iterate in reverse to draw closest blocks first
1147 for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it)
1148 draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin());
1152 TimeTaker draw("Drawing shadow mesh buffers");
1154 core::matrix4 m; // Model matrix
1155 v3f offset = intToFloat(m_camera_offset, BS);
1156 u32 material_swaps = 0;
1158 // Render all mesh buffers in order
1159 drawcall_count += draw_order.size();
1161 for (auto &descriptor : draw_order) {
1162 scene::IMeshBuffer *buf = descriptor.getBuffer();
1164 if (!descriptor.m_reuse_material) {
1165 // override some material properties
1166 video::SMaterial local_material = buf->getMaterial();
1167 local_material.MaterialType = material.MaterialType;
1168 local_material.BackfaceCulling = material.BackfaceCulling;
1169 local_material.FrontfaceCulling = material.FrontfaceCulling;
1170 local_material.BlendOperation = material.BlendOperation;
1171 local_material.Lighting = false;
1172 driver->setMaterial(local_material);
1176 v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS);
1177 m.setTranslation(block_wpos - offset);
1179 driver->setTransform(video::ETS_WORLD, m);
1180 descriptor.draw(driver);
1181 vertex_count += buf->getIndexCount();
1184 // restore the driver material state
1185 video::SMaterial clean;
1186 clean.BlendOperation = video::EBO_ADD;
1187 driver->setMaterial(clean); // reset material to defaults
1188 driver->draw3DLine(v3f(), v3f(), video::SColor(0));
1190 g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
1191 g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
1192 g_profiler->avg(prefix + "drawcalls [#]", drawcall_count);
1193 g_profiler->avg(prefix + "material swaps [#]", material_swaps);
1197 Custom update draw list for the pov of shadow light.
1199 void ClientMap::updateDrawListShadow(v3f shadow_light_pos, v3f shadow_light_dir, float radius, float length)
1201 ScopeProfiler sp(g_profiler, "CM::updateDrawListShadow()", SPT_AVG);
1203 v3s16 cam_pos_nodes = floatToInt(shadow_light_pos, BS);
1206 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max, radius + length);
1208 for (auto &i : m_drawlist_shadow) {
1209 MapBlock *block = i.second;
1212 m_drawlist_shadow.clear();
1214 // Number of blocks currently loaded by the client
1215 u32 blocks_loaded = 0;
1216 // Number of blocks with mesh in rendering range
1217 u32 blocks_in_range_with_mesh = 0;
1218 // Number of blocks occlusion culled
1219 u32 blocks_occlusion_culled = 0;
1221 for (auto §or_it : m_sectors) {
1222 MapSector *sector = sector_it.second;
1225 blocks_loaded += sector->size();
1227 MapBlockVect sectorblocks;
1228 sector->getBlocks(sectorblocks);
1231 Loop through blocks in sector
1233 for (MapBlock *block : sectorblocks) {
1235 // Ignore if mesh doesn't exist
1239 v3f block_pos = intToFloat(block->getPos() * MAP_BLOCKSIZE, BS);
1240 v3f projection = shadow_light_pos + shadow_light_dir * shadow_light_dir.dotProduct(block_pos - shadow_light_pos);
1241 if (projection.getDistanceFrom(block_pos) > radius)
1244 blocks_in_range_with_mesh++;
1246 // This block is in range. Reset usage timer.
1247 block->resetUsageTimer();
1250 if (m_drawlist_shadow.find(block->getPos()) == m_drawlist_shadow.end()) {
1252 m_drawlist_shadow[block->getPos()] = block;
1257 g_profiler->avg("SHADOW MapBlock meshes in range [#]", blocks_in_range_with_mesh);
1258 g_profiler->avg("SHADOW MapBlocks occlusion culled [#]", blocks_occlusion_culled);
1259 g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size());
1260 g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded);
1263 void ClientMap::updateTransparentMeshBuffers()
1265 ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG);
1266 u32 sorted_blocks = 0;
1267 u32 unsorted_blocks = 0;
1268 f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f);
1271 // Update the order of transparent mesh buffers in each mesh
1272 for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) {
1273 MapBlock* block = it->second;
1277 if (m_needs_update_transparent_meshes ||
1278 block->mesh->getTransparentBuffers().size() == 0) {
1280 v3s16 block_pos = block->getPos();
1281 v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS);
1282 f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f);
1283 if (distance <= sorting_distance_sq) {
1284 block->mesh->updateTransparentBuffers(m_camera_position, block_pos);
1288 block->mesh->consolidateTransparentBuffers();
1294 g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks);
1295 g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks);
1296 m_needs_update_transparent_meshes = false;
1299 scene::IMeshBuffer* ClientMap::DrawDescriptor::getBuffer()
1301 return m_use_partial_buffer ? m_partial_buffer->getBuffer() : m_buffer;
1304 void ClientMap::DrawDescriptor::draw(video::IVideoDriver* driver)
1306 if (m_use_partial_buffer) {
1307 m_partial_buffer->beforeDraw();
1308 driver->drawMeshBuffer(m_partial_buffer->getBuffer());
1309 m_partial_buffer->afterDraw();
1311 driver->drawMeshBuffer(m_buffer);