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>
26 #include "mapsector.h"
31 #include "camera.h" // CameraModes
32 #include "util/basic_macros.h"
34 #include "client/renderingengine.h"
38 MapDrawControl &control,
41 Map(dout_client, client),
42 scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
43 RenderingEngine::get_scene_manager(), id),
46 m_camera_position(0,0,0),
47 m_camera_direction(0,0,1),
50 m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
51 BS*1000000,BS*1000000,BS*1000000);
53 /* TODO: Add a callback function so these can be updated when a setting
54 * changes. At this point in time it doesn't matter (e.g. /set
55 * is documented to change server settings only)
57 * TODO: Local caching of settings is not optimal and should at some stage
58 * be updated to use a global settings object for getting thse values
59 * (as opposed to the this local caching). This can be addressed in
62 m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
63 m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
64 m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
68 ClientMap::~ClientMap()
72 MapSector * ClientMap::emergeSector(v2s16 p2d)
74 DSTACK(FUNCTION_NAME);
75 // Check that it doesn't exist already
77 return getSectorNoGenerate(p2d);
79 catch(InvalidPositionException &e)
84 ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
87 //MutexAutoLock lock(m_sector_mutex); // Bulk comment-out
88 m_sectors[p2d] = sector;
94 void ClientMap::OnRegisterSceneNode()
98 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
99 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
102 ISceneNode::OnRegisterSceneNode();
105 void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
106 v3s16 *p_blocks_min, v3s16 *p_blocks_max)
108 v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
109 // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
110 // can exceed the range of v3s16 when a large view range is used near the
113 cam_pos_nodes.X - box_nodes_d.X,
114 cam_pos_nodes.Y - box_nodes_d.Y,
115 cam_pos_nodes.Z - box_nodes_d.Z);
117 cam_pos_nodes.X + box_nodes_d.X,
118 cam_pos_nodes.Y + box_nodes_d.Y,
119 cam_pos_nodes.Z + box_nodes_d.Z);
120 // Take a fair amount as we will be dropping more out later
121 // Umm... these additions are a bit strange but they are needed.
122 *p_blocks_min = v3s16(
123 p_nodes_min.X / MAP_BLOCKSIZE - 3,
124 p_nodes_min.Y / MAP_BLOCKSIZE - 3,
125 p_nodes_min.Z / MAP_BLOCKSIZE - 3);
126 *p_blocks_max = v3s16(
127 p_nodes_max.X / MAP_BLOCKSIZE + 1,
128 p_nodes_max.Y / MAP_BLOCKSIZE + 1,
129 p_nodes_max.Z / MAP_BLOCKSIZE + 1);
132 void ClientMap::updateDrawList(video::IVideoDriver* driver)
134 ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
135 g_profiler->add("CM::updateDrawList() count", 1);
137 for (std::map<v3s16, MapBlock*>::iterator i = m_drawlist.begin();
138 i != m_drawlist.end(); ++i) {
139 MapBlock *block = i->second;
144 v3f camera_position = m_camera_position;
145 v3f camera_direction = m_camera_direction;
146 f32 camera_fov = m_camera_fov;
148 // Use a higher fov to accomodate faster camera movements.
149 // Blocks are cropped better when they are drawn.
150 // Or maybe they aren't? Well whatever.
153 v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
156 getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
158 // Number of blocks in rendering range
159 u32 blocks_in_range = 0;
160 // Number of blocks occlusion culled
161 u32 blocks_occlusion_culled = 0;
162 // Number of blocks in rendering range but don't have a mesh
163 u32 blocks_in_range_without_mesh = 0;
164 // Blocks that had mesh that would have been drawn according to
165 // rendering range (if max blocks limit didn't kick in)
166 u32 blocks_would_have_drawn = 0;
167 // Blocks that were drawn and had a mesh
168 u32 blocks_drawn = 0;
169 // Blocks which had a corresponding meshbuffer for this pass
170 //u32 blocks_had_pass_meshbuf = 0;
171 // Blocks from which stuff was actually drawn
172 //u32 blocks_without_stuff = 0;
173 // Distance to farthest drawn block
174 float farthest_drawn = 0;
176 // No occlusion culling when free_move is on and camera is
178 bool occlusion_culling_enabled = true;
179 if (g_settings->getBool("free_move")) {
180 MapNode n = getNodeNoEx(cam_pos_nodes);
181 if (n.getContent() == CONTENT_IGNORE ||
182 m_nodedef->get(n).solidness == 2)
183 occlusion_culling_enabled = false;
186 for (std::map<v2s16, MapSector*>::iterator si = m_sectors.begin();
187 si != m_sectors.end(); ++si) {
188 MapSector *sector = si->second;
189 v2s16 sp = sector->getPos();
191 if (m_control.range_all == false) {
192 if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
193 sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
197 MapBlockVect sectorblocks;
198 sector->getBlocks(sectorblocks);
201 Loop through blocks in sector
204 u32 sector_blocks_drawn = 0;
206 for (MapBlockVect::iterator i = sectorblocks.begin();
207 i != sectorblocks.end(); ++i) {
208 MapBlock *block = *i;
211 Compare block position to camera position, skip
212 if not seen on display
216 block->mesh->updateCameraOffset(m_camera_offset);
218 float range = 100000 * BS;
219 if (!m_control.range_all)
220 range = m_control.wanted_range * BS;
223 if (!isBlockInSight(block->getPos(), camera_position,
224 camera_direction, camera_fov, range, &d))
230 Ignore if mesh doesn't exist
233 blocks_in_range_without_mesh++;
240 if (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes)) {
241 blocks_occlusion_culled++;
245 // This block is in range. Reset usage timer.
246 block->resetUsageTimer();
248 // Limit block count in case of a sudden increase
249 blocks_would_have_drawn++;
250 if (blocks_drawn >= m_control.wanted_max_blocks &&
251 !m_control.range_all &&
252 d > m_control.wanted_range * BS)
257 m_drawlist[block->getPos()] = block;
259 sector_blocks_drawn++;
261 if (d / BS > farthest_drawn)
262 farthest_drawn = d / BS;
264 } // foreach sectorblocks
266 if (sector_blocks_drawn != 0)
267 m_last_drawn_sectors.insert(sp);
270 m_control.blocks_would_have_drawn = blocks_would_have_drawn;
271 m_control.blocks_drawn = blocks_drawn;
272 m_control.farthest_drawn = farthest_drawn;
274 g_profiler->avg("CM: blocks in range", blocks_in_range);
275 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
276 if (blocks_in_range != 0)
277 g_profiler->avg("CM: blocks in range without mesh (frac)",
278 (float)blocks_in_range_without_mesh / blocks_in_range);
279 g_profiler->avg("CM: blocks drawn", blocks_drawn);
280 g_profiler->avg("CM: farthest drawn", farthest_drawn);
281 g_profiler->avg("CM: wanted max blocks", m_control.wanted_max_blocks);
287 std::vector<scene::IMeshBuffer*> bufs;
290 struct MeshBufListList
293 * Stores the mesh buffers of the world.
294 * The array index is the material's layer.
295 * The vector part groups vertices by material.
297 std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
301 for (int l = 0; l < MAX_TILE_LAYERS; l++)
305 void add(scene::IMeshBuffer *buf, u8 layer)
307 // Append to the correct layer
308 std::vector<MeshBufList> &list = lists[layer];
309 const video::SMaterial &m = buf->getMaterial();
310 for (MeshBufList &l : list) {
311 // comparing a full material is quite expensive so we don't do it if
312 // not even first texture is equal
313 if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
317 l.bufs.push_back(buf);
323 l.bufs.push_back(buf);
328 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
330 DSTACK(FUNCTION_NAME);
332 bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
335 if (pass == scene::ESNRP_SOLID)
336 prefix = "CM: solid: ";
338 prefix = "CM: transparent: ";
341 This is called two times per frame, reset on the non-transparent one
343 if (pass == scene::ESNRP_SOLID)
344 m_last_drawn_sectors.clear();
347 Get time for measuring timeout.
349 Measuring time is very useful for long delays when the
350 machine is swapping a lot.
352 std::time_t time1 = time(0);
355 Get animation parameters
357 float animation_time = m_client->getAnimationTime();
358 int crack = m_client->getCrackLevel();
359 u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
361 v3f camera_position = m_camera_position;
362 v3f camera_direction = m_camera_direction;
363 f32 camera_fov = m_camera_fov;
366 Get all blocks and draw all visible ones
369 u32 vertex_count = 0;
370 u32 meshbuffer_count = 0;
372 // For limiting number of mesh animations per frame
373 u32 mesh_animate_count = 0;
374 u32 mesh_animate_count_far = 0;
376 // Blocks that were drawn and had a mesh
377 u32 blocks_drawn = 0;
378 // Blocks which had a corresponding meshbuffer for this pass
379 u32 blocks_had_pass_meshbuf = 0;
380 // Blocks from which stuff was actually drawn
381 u32 blocks_without_stuff = 0;
384 Draw the selected MapBlocks
388 ScopeProfiler sp(g_profiler, prefix + "drawing blocks", SPT_AVG);
390 MeshBufListList drawbufs;
392 for (std::map<v3s16, MapBlock*>::iterator i = m_drawlist.begin();
393 i != m_drawlist.end(); ++i) {
394 MapBlock *block = i->second;
396 // If the mesh of the block happened to get deleted, ignore it
401 if (!isBlockInSight(block->getPos(), camera_position,
402 camera_direction, camera_fov, 100000 * BS, &d))
406 if (pass == scene::ESNRP_SOLID) {
407 //MutexAutoLock lock(block->mesh_mutex);
408 MapBlockMesh *mapBlockMesh = block->mesh;
409 assert(mapBlockMesh);
410 // Pretty random but this should work somewhat nicely
411 bool faraway = d >= BS * 50;
412 //bool faraway = d >= m_control.wanted_range * BS;
413 if (mapBlockMesh->isAnimationForced() || !faraway ||
414 mesh_animate_count_far < (m_control.range_all ? 200 : 50)) {
415 bool animated = mapBlockMesh->animate(faraway, animation_time,
416 crack, daynight_ratio);
418 mesh_animate_count++;
419 if (animated && faraway)
420 mesh_animate_count_far++;
422 mapBlockMesh->decreaseAnimationForceTimer();
427 Get the meshbuffers of the block
430 //MutexAutoLock lock(block->mesh_mutex);
432 MapBlockMesh *mapBlockMesh = block->mesh;
433 assert(mapBlockMesh);
435 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
436 scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
439 u32 c = mesh->getMeshBufferCount();
440 for (u32 i = 0; i < c; i++) {
441 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
443 video::SMaterial& material = buf->getMaterial();
444 video::IMaterialRenderer* rnd =
445 driver->getMaterialRenderer(material.MaterialType);
446 bool transparent = (rnd && rnd->isTransparent());
447 if (transparent == is_transparent_pass) {
448 if (buf->getVertexCount() == 0)
449 errorstream << "Block [" << analyze_block(block)
450 << "] contains an empty meshbuf" << std::endl;
452 material.setFlag(video::EMF_TRILINEAR_FILTER,
453 m_cache_trilinear_filter);
454 material.setFlag(video::EMF_BILINEAR_FILTER,
455 m_cache_bilinear_filter);
456 material.setFlag(video::EMF_ANISOTROPIC_FILTER,
457 m_cache_anistropic_filter);
458 material.setFlag(video::EMF_WIREFRAME,
459 m_control.show_wireframe);
461 drawbufs.add(buf, layer);
468 // Render all layers in order
469 for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
470 std::vector<MeshBufList> &lists = drawbufs.lists[layer];
472 int timecheck_counter = 0;
473 for (MeshBufList &list : lists) {
475 if (timecheck_counter > 50) {
476 timecheck_counter = 0;
477 std::time_t time2 = time(0);
478 if (time2 > time1 + 4) {
479 infostream << "ClientMap::renderMap(): "
480 "Rendering takes ages, returning."
486 driver->setMaterial(list.m);
488 for (scene::IMeshBuffer *buf : list.bufs) {
489 driver->drawMeshBuffer(buf);
490 vertex_count += buf->getVertexCount();
497 // Log only on solid pass because values are the same
498 if (pass == scene::ESNRP_SOLID) {
499 g_profiler->avg("CM: animated meshes", mesh_animate_count);
500 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
503 g_profiler->avg(prefix + "vertices drawn", vertex_count);
504 if (blocks_had_pass_meshbuf != 0)
505 g_profiler->avg(prefix + "meshbuffers per block",
506 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
507 if (blocks_drawn != 0)
508 g_profiler->avg(prefix + "empty blocks (frac)",
509 (float)blocks_without_stuff / blocks_drawn);
511 /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
512 <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
515 static bool getVisibleBrightness(Map *map, v3f p0, v3f dir, float step,
516 float step_multiplier, float start_distance, float end_distance,
517 INodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
518 int *result, bool *sunlight_seen)
520 int brightness_sum = 0;
521 int brightness_count = 0;
522 float distance = start_distance;
525 pf += dir * distance;
527 bool nonlight_seen = false;
528 bool allow_allowing_non_sunlight_propagates = false;
529 bool allow_non_sunlight_propagates = false;
530 // Check content nearly at camera position
532 v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
533 MapNode n = map->getNodeNoEx(p);
534 if(ndef->get(n).param_type == CPT_LIGHT &&
535 !ndef->get(n).sunlight_propagates)
536 allow_allowing_non_sunlight_propagates = true;
538 // If would start at CONTENT_IGNORE, start closer
540 v3s16 p = floatToInt(pf, BS);
541 MapNode n = map->getNodeNoEx(p);
542 if(n.getContent() == CONTENT_IGNORE){
544 pf = p0 + dir * 2*newd;
549 for(int i=0; distance < end_distance; i++){
552 step *= step_multiplier;
554 v3s16 p = floatToInt(pf, BS);
555 MapNode n = map->getNodeNoEx(p);
556 if(allow_allowing_non_sunlight_propagates && i == 0 &&
557 ndef->get(n).param_type == CPT_LIGHT &&
558 !ndef->get(n).sunlight_propagates){
559 allow_non_sunlight_propagates = true;
561 if(ndef->get(n).param_type != CPT_LIGHT ||
562 (!ndef->get(n).sunlight_propagates &&
563 !allow_non_sunlight_propagates)){
564 nonlight_seen = true;
570 if(distance >= sunlight_min_d && *sunlight_seen == false
571 && nonlight_seen == false)
572 if(n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
573 *sunlight_seen = true;
575 brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
579 if(brightness_count == 0)
581 *result = brightness_sum / brightness_count;
582 /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
583 <<(*result)<<std::endl;*/
587 int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
588 int oldvalue, bool *sunlight_seen_result)
590 const bool debugprint = false;
591 static v3f z_directions[50] = {
594 static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
597 if(z_directions[0].X < -99){
598 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
599 z_directions[i] = v3f(
600 0.01 * myrand_range(-100, 100),
602 0.01 * myrand_range(-100, 100)
604 z_offsets[i] = 0.01 * myrand_range(0,100);
608 std::cerr<<"In goes "<<PP(m_camera_direction)<<", out comes ";
609 int sunlight_seen_count = 0;
610 float sunlight_min_d = max_d*0.8;
611 if(sunlight_min_d > 35*BS)
612 sunlight_min_d = 35*BS;
613 std::vector<int> values;
614 for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
615 v3f z_dir = z_directions[i];
617 core::CMatrix4<f32> a;
618 a.buildRotateFromTo(v3f(0,1,0), z_dir);
619 v3f dir = m_camera_direction;
624 step = max_d / 35 * 1.5;
625 float off = step * z_offsets[i];
626 bool sunlight_seen_now = false;
627 bool ok = getVisibleBrightness(this, m_camera_position, dir,
628 step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
630 &br, &sunlight_seen_now);
631 if(sunlight_seen_now)
632 sunlight_seen_count++;
635 values.push_back(br);
636 // Don't try too much if being in the sun is clear
637 if(sunlight_seen_count >= 20)
640 int brightness_sum = 0;
641 int brightness_count = 0;
642 std::sort(values.begin(), values.end());
643 u32 num_values_to_use = values.size();
644 if(num_values_to_use >= 10)
645 num_values_to_use -= num_values_to_use/2;
646 else if(num_values_to_use >= 7)
647 num_values_to_use -= num_values_to_use/3;
648 u32 first_value_i = (values.size() - num_values_to_use) / 2;
650 for(u32 i=0; i < first_value_i; i++)
651 std::cerr<<values[i]<<" ";
654 for(u32 i=first_value_i; i < first_value_i+num_values_to_use; i++){
656 std::cerr<<values[i]<<" ";
657 brightness_sum += values[i];
662 for(u32 i=first_value_i+num_values_to_use; i < values.size(); i++)
663 std::cerr<<values[i]<<" ";
666 if(brightness_count == 0){
667 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
668 if(m_nodedef->get(n).param_type == CPT_LIGHT){
669 ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
674 /*float pre = (float)brightness_sum / (float)brightness_count;
680 ret = MYMAX(0, MYMIN(255, preint));*/
681 ret = brightness_sum / brightness_count;
684 std::cerr<<"Result: "<<ret<<" sunlight_seen_count="
685 <<sunlight_seen_count<<std::endl;
686 *sunlight_seen_result = (sunlight_seen_count > 0);
690 void ClientMap::renderPostFx(CameraMode cam_mode)
692 // Sadly ISceneManager has no "post effects" render pass, in that case we
693 // could just register for that and handle it in renderMap().
695 MapNode n = getNodeNoEx(floatToInt(m_camera_position, BS));
697 // - If the player is in a solid node, make everything black.
698 // - If the player is in liquid, draw a semi-transparent overlay.
699 // - Do not if player is in third person mode
700 const ContentFeatures& features = m_nodedef->get(n);
701 video::SColor post_effect_color = features.post_effect_color;
702 if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
703 m_client->checkLocalPrivilege("noclip")) &&
704 cam_mode == CAMERA_MODE_FIRST)
706 post_effect_color = video::SColor(255, 0, 0, 0);
708 if (post_effect_color.getAlpha() != 0)
710 // Draw a full-screen rectangle
711 video::IVideoDriver* driver = SceneManager->getVideoDriver();
712 v2u32 ss = driver->getScreenSize();
713 core::rect<s32> rect(0,0, ss.X, ss.Y);
714 driver->draw2DRectangle(post_effect_color, rect);
718 void ClientMap::PrintInfo(std::ostream &out)