clientmap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "clientmap.h"
  17. #include "client.h"
  18. #include "mapblock_mesh.h"
  19. #include <IMaterialRenderer.h>
  20. #include <matrix4.h>
  21. #include "mapsector.h"
  22. #include "mapblock.h"
  23. #include "profiler.h"
  24. #include "settings.h"
  25. #include "camera.h" // CameraModes
  26. #include "util/basic_macros.h"
  27. #include <algorithm>
  28. #include "client/renderingengine.h"
  29. ClientMap::ClientMap(
  30. Client *client,
  31. MapDrawControl &control,
  32. s32 id
  33. ):
  34. Map(dout_client, client),
  35. scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(),
  36. RenderingEngine::get_scene_manager(), id),
  37. m_client(client),
  38. m_control(control)
  39. {
  40. m_box = aabb3f(-BS*1000000,-BS*1000000,-BS*1000000,
  41. BS*1000000,BS*1000000,BS*1000000);
  42. /* TODO: Add a callback function so these can be updated when a setting
  43. * changes. At this point in time it doesn't matter (e.g. /set
  44. * is documented to change server settings only)
  45. *
  46. * TODO: Local caching of settings is not optimal and should at some stage
  47. * be updated to use a global settings object for getting thse values
  48. * (as opposed to the this local caching). This can be addressed in
  49. * a later release.
  50. */
  51. m_cache_trilinear_filter = g_settings->getBool("trilinear_filter");
  52. m_cache_bilinear_filter = g_settings->getBool("bilinear_filter");
  53. m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter");
  54. }
  55. MapSector * ClientMap::emergeSector(v2s16 p2d)
  56. {
  57. // Check that it doesn't exist already
  58. MapSector *sector = getSectorNoGenerate(p2d);
  59. // Create it if it does not exist yet
  60. if (!sector) {
  61. sector = new MapSector(this, p2d, m_gamedef);
  62. m_sectors[p2d] = sector;
  63. }
  64. return sector;
  65. }
  66. void ClientMap::OnRegisterSceneNode()
  67. {
  68. if(IsVisible)
  69. {
  70. SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
  71. SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
  72. }
  73. ISceneNode::OnRegisterSceneNode();
  74. }
  75. void ClientMap::getBlocksInViewRange(v3s16 cam_pos_nodes,
  76. v3s16 *p_blocks_min, v3s16 *p_blocks_max)
  77. {
  78. v3s16 box_nodes_d = m_control.wanted_range * v3s16(1, 1, 1);
  79. // Define p_nodes_min/max as v3s32 because 'cam_pos_nodes -/+ box_nodes_d'
  80. // can exceed the range of v3s16 when a large view range is used near the
  81. // world edges.
  82. v3s32 p_nodes_min(
  83. cam_pos_nodes.X - box_nodes_d.X,
  84. cam_pos_nodes.Y - box_nodes_d.Y,
  85. cam_pos_nodes.Z - box_nodes_d.Z);
  86. v3s32 p_nodes_max(
  87. cam_pos_nodes.X + box_nodes_d.X,
  88. cam_pos_nodes.Y + box_nodes_d.Y,
  89. cam_pos_nodes.Z + box_nodes_d.Z);
  90. // Take a fair amount as we will be dropping more out later
  91. // Umm... these additions are a bit strange but they are needed.
  92. *p_blocks_min = v3s16(
  93. p_nodes_min.X / MAP_BLOCKSIZE - 3,
  94. p_nodes_min.Y / MAP_BLOCKSIZE - 3,
  95. p_nodes_min.Z / MAP_BLOCKSIZE - 3);
  96. *p_blocks_max = v3s16(
  97. p_nodes_max.X / MAP_BLOCKSIZE + 1,
  98. p_nodes_max.Y / MAP_BLOCKSIZE + 1,
  99. p_nodes_max.Z / MAP_BLOCKSIZE + 1);
  100. }
  101. void ClientMap::updateDrawList()
  102. {
  103. ScopeProfiler sp(g_profiler, "CM::updateDrawList()", SPT_AVG);
  104. for (auto &i : m_drawlist) {
  105. MapBlock *block = i.second;
  106. block->refDrop();
  107. }
  108. m_drawlist.clear();
  109. v3f camera_position = m_camera_position;
  110. v3f camera_direction = m_camera_direction;
  111. f32 camera_fov = m_camera_fov;
  112. // Use a higher fov to accomodate faster camera movements.
  113. // Blocks are cropped better when they are drawn.
  114. // Or maybe they aren't? Well whatever.
  115. camera_fov *= 1.2;
  116. v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
  117. v3s16 p_blocks_min;
  118. v3s16 p_blocks_max;
  119. getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max);
  120. // Number of blocks with mesh in rendering range
  121. u32 blocks_in_range_with_mesh = 0;
  122. // Number of blocks occlusion culled
  123. u32 blocks_occlusion_culled = 0;
  124. // No occlusion culling when free_move is on and camera is
  125. // inside ground
  126. bool occlusion_culling_enabled = true;
  127. if (g_settings->getBool("free_move") && g_settings->getBool("noclip")) {
  128. MapNode n = getNode(cam_pos_nodes);
  129. if (n.getContent() == CONTENT_IGNORE ||
  130. m_nodedef->get(n).solidness == 2)
  131. occlusion_culling_enabled = false;
  132. }
  133. // Uncomment to debug occluded blocks in the wireframe mode
  134. // TODO: Include this as a flag for an extended debugging setting
  135. //if (occlusion_culling_enabled && m_control.show_wireframe)
  136. // occlusion_culling_enabled = porting::getTimeS() & 1;
  137. for (const auto &sector_it : m_sectors) {
  138. MapSector *sector = sector_it.second;
  139. v2s16 sp = sector->getPos();
  140. if (!m_control.range_all) {
  141. if (sp.X < p_blocks_min.X || sp.X > p_blocks_max.X ||
  142. sp.Y < p_blocks_min.Z || sp.Y > p_blocks_max.Z)
  143. continue;
  144. }
  145. MapBlockVect sectorblocks;
  146. sector->getBlocks(sectorblocks);
  147. /*
  148. Loop through blocks in sector
  149. */
  150. u32 sector_blocks_drawn = 0;
  151. for (MapBlock *block : sectorblocks) {
  152. /*
  153. Compare block position to camera position, skip
  154. if not seen on display
  155. */
  156. if (block->mesh)
  157. block->mesh->updateCameraOffset(m_camera_offset);
  158. float range = 100000 * BS;
  159. if (!m_control.range_all)
  160. range = m_control.wanted_range * BS;
  161. float d = 0.0;
  162. if (!isBlockInSight(block->getPos(), camera_position,
  163. camera_direction, camera_fov, range, &d))
  164. continue;
  165. /*
  166. Ignore if mesh doesn't exist
  167. */
  168. if (!block->mesh)
  169. continue;
  170. blocks_in_range_with_mesh++;
  171. /*
  172. Occlusion culling
  173. */
  174. if ((!m_control.range_all && d > m_control.wanted_range * BS) ||
  175. (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) {
  176. blocks_occlusion_culled++;
  177. continue;
  178. }
  179. // This block is in range. Reset usage timer.
  180. block->resetUsageTimer();
  181. // Add to set
  182. block->refGrab();
  183. m_drawlist[block->getPos()] = block;
  184. sector_blocks_drawn++;
  185. } // foreach sectorblocks
  186. if (sector_blocks_drawn != 0)
  187. m_last_drawn_sectors.insert(sp);
  188. }
  189. g_profiler->avg("MapBlock meshes in range [#]", blocks_in_range_with_mesh);
  190. g_profiler->avg("MapBlocks occlusion culled [#]", blocks_occlusion_culled);
  191. g_profiler->avg("MapBlocks drawn [#]", m_drawlist.size());
  192. }
  193. struct MeshBufList
  194. {
  195. video::SMaterial m;
  196. std::vector<scene::IMeshBuffer*> bufs;
  197. };
  198. struct MeshBufListList
  199. {
  200. /*!
  201. * Stores the mesh buffers of the world.
  202. * The array index is the material's layer.
  203. * The vector part groups vertices by material.
  204. */
  205. std::vector<MeshBufList> lists[MAX_TILE_LAYERS];
  206. void clear()
  207. {
  208. for (auto &list : lists)
  209. list.clear();
  210. }
  211. void add(scene::IMeshBuffer *buf, u8 layer)
  212. {
  213. // Append to the correct layer
  214. std::vector<MeshBufList> &list = lists[layer];
  215. const video::SMaterial &m = buf->getMaterial();
  216. for (MeshBufList &l : list) {
  217. // comparing a full material is quite expensive so we don't do it if
  218. // not even first texture is equal
  219. if (l.m.TextureLayer[0].Texture != m.TextureLayer[0].Texture)
  220. continue;
  221. if (l.m == m) {
  222. l.bufs.push_back(buf);
  223. return;
  224. }
  225. }
  226. MeshBufList l;
  227. l.m = m;
  228. l.bufs.push_back(buf);
  229. list.push_back(l);
  230. }
  231. };
  232. void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
  233. {
  234. bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
  235. std::string prefix;
  236. if (pass == scene::ESNRP_SOLID)
  237. prefix = "renderMap(SOLID): ";
  238. else
  239. prefix = "renderMap(TRANSPARENT): ";
  240. /*
  241. This is called two times per frame, reset on the non-transparent one
  242. */
  243. if (pass == scene::ESNRP_SOLID)
  244. m_last_drawn_sectors.clear();
  245. /*
  246. Get animation parameters
  247. */
  248. float animation_time = m_client->getAnimationTime();
  249. int crack = m_client->getCrackLevel();
  250. u32 daynight_ratio = m_client->getEnv().getDayNightRatio();
  251. v3f camera_position = m_camera_position;
  252. v3f camera_direction = m_camera_direction;
  253. f32 camera_fov = m_camera_fov;
  254. /*
  255. Get all blocks and draw all visible ones
  256. */
  257. u32 vertex_count = 0;
  258. // For limiting number of mesh animations per frame
  259. u32 mesh_animate_count = 0;
  260. //u32 mesh_animate_count_far = 0;
  261. /*
  262. Draw the selected MapBlocks
  263. */
  264. MeshBufListList drawbufs;
  265. for (auto &i : m_drawlist) {
  266. MapBlock *block = i.second;
  267. // If the mesh of the block happened to get deleted, ignore it
  268. if (!block->mesh)
  269. continue;
  270. float d = 0.0;
  271. if (!isBlockInSight(block->getPos(), camera_position,
  272. camera_direction, camera_fov, 100000 * BS, &d))
  273. continue;
  274. // Mesh animation
  275. if (pass == scene::ESNRP_SOLID) {
  276. //MutexAutoLock lock(block->mesh_mutex);
  277. MapBlockMesh *mapBlockMesh = block->mesh;
  278. assert(mapBlockMesh);
  279. // Pretty random but this should work somewhat nicely
  280. bool faraway = d >= BS * 50;
  281. if (mapBlockMesh->isAnimationForced() || !faraway ||
  282. mesh_animate_count < (m_control.range_all ? 200 : 50)) {
  283. bool animated = mapBlockMesh->animate(faraway, animation_time,
  284. crack, daynight_ratio);
  285. if (animated)
  286. mesh_animate_count++;
  287. } else {
  288. mapBlockMesh->decreaseAnimationForceTimer();
  289. }
  290. }
  291. /*
  292. Get the meshbuffers of the block
  293. */
  294. {
  295. //MutexAutoLock lock(block->mesh_mutex);
  296. MapBlockMesh *mapBlockMesh = block->mesh;
  297. assert(mapBlockMesh);
  298. for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) {
  299. scene::IMesh *mesh = mapBlockMesh->getMesh(layer);
  300. assert(mesh);
  301. u32 c = mesh->getMeshBufferCount();
  302. for (u32 i = 0; i < c; i++) {
  303. scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
  304. video::SMaterial& material = buf->getMaterial();
  305. video::IMaterialRenderer* rnd =
  306. driver->getMaterialRenderer(material.MaterialType);
  307. bool transparent = (rnd && rnd->isTransparent());
  308. if (transparent == is_transparent_pass) {
  309. if (buf->getVertexCount() == 0)
  310. errorstream << "Block [" << analyze_block(block)
  311. << "] contains an empty meshbuf" << std::endl;
  312. material.setFlag(video::EMF_TRILINEAR_FILTER,
  313. m_cache_trilinear_filter);
  314. material.setFlag(video::EMF_BILINEAR_FILTER,
  315. m_cache_bilinear_filter);
  316. material.setFlag(video::EMF_ANISOTROPIC_FILTER,
  317. m_cache_anistropic_filter);
  318. material.setFlag(video::EMF_WIREFRAME,
  319. m_control.show_wireframe);
  320. drawbufs.add(buf, layer);
  321. }
  322. }
  323. }
  324. }
  325. }
  326. TimeTaker draw("Drawing mesh buffers");
  327. // Render all layers in order
  328. for (auto &lists : drawbufs.lists) {
  329. for (MeshBufList &list : lists) {
  330. // Check and abort if the machine is swapping a lot
  331. if (draw.getTimerTime() > 2000) {
  332. infostream << "ClientMap::renderMap(): Rendering took >2s, " <<
  333. "returning." << std::endl;
  334. return;
  335. }
  336. driver->setMaterial(list.m);
  337. for (scene::IMeshBuffer *buf : list.bufs) {
  338. driver->drawMeshBuffer(buf);
  339. vertex_count += buf->getVertexCount();
  340. }
  341. }
  342. }
  343. g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true));
  344. // Log only on solid pass because values are the same
  345. if (pass == scene::ESNRP_SOLID) {
  346. g_profiler->avg("renderMap(): animated meshes [#]", mesh_animate_count);
  347. }
  348. g_profiler->avg(prefix + "vertices drawn [#]", vertex_count);
  349. }
  350. static bool getVisibleBrightness(Map *map, const v3f &p0, v3f dir, float step,
  351. float step_multiplier, float start_distance, float end_distance,
  352. const NodeDefManager *ndef, u32 daylight_factor, float sunlight_min_d,
  353. int *result, bool *sunlight_seen)
  354. {
  355. int brightness_sum = 0;
  356. int brightness_count = 0;
  357. float distance = start_distance;
  358. dir.normalize();
  359. v3f pf = p0;
  360. pf += dir * distance;
  361. int noncount = 0;
  362. bool nonlight_seen = false;
  363. bool allow_allowing_non_sunlight_propagates = false;
  364. bool allow_non_sunlight_propagates = false;
  365. // Check content nearly at camera position
  366. {
  367. v3s16 p = floatToInt(p0 /*+ dir * 3*BS*/, BS);
  368. MapNode n = map->getNode(p);
  369. if(ndef->get(n).param_type == CPT_LIGHT &&
  370. !ndef->get(n).sunlight_propagates)
  371. allow_allowing_non_sunlight_propagates = true;
  372. }
  373. // If would start at CONTENT_IGNORE, start closer
  374. {
  375. v3s16 p = floatToInt(pf, BS);
  376. MapNode n = map->getNode(p);
  377. if(n.getContent() == CONTENT_IGNORE){
  378. float newd = 2*BS;
  379. pf = p0 + dir * 2*newd;
  380. distance = newd;
  381. sunlight_min_d = 0;
  382. }
  383. }
  384. for (int i=0; distance < end_distance; i++) {
  385. pf += dir * step;
  386. distance += step;
  387. step *= step_multiplier;
  388. v3s16 p = floatToInt(pf, BS);
  389. MapNode n = map->getNode(p);
  390. if (allow_allowing_non_sunlight_propagates && i == 0 &&
  391. ndef->get(n).param_type == CPT_LIGHT &&
  392. !ndef->get(n).sunlight_propagates) {
  393. allow_non_sunlight_propagates = true;
  394. }
  395. if (ndef->get(n).param_type != CPT_LIGHT ||
  396. (!ndef->get(n).sunlight_propagates &&
  397. !allow_non_sunlight_propagates)){
  398. nonlight_seen = true;
  399. noncount++;
  400. if(noncount >= 4)
  401. break;
  402. continue;
  403. }
  404. if (distance >= sunlight_min_d && !*sunlight_seen && !nonlight_seen)
  405. if (n.getLight(LIGHTBANK_DAY, ndef) == LIGHT_SUN)
  406. *sunlight_seen = true;
  407. noncount = 0;
  408. brightness_sum += decode_light(n.getLightBlend(daylight_factor, ndef));
  409. brightness_count++;
  410. }
  411. *result = 0;
  412. if(brightness_count == 0)
  413. return false;
  414. *result = brightness_sum / brightness_count;
  415. /*std::cerr<<"Sampled "<<brightness_count<<" points; result="
  416. <<(*result)<<std::endl;*/
  417. return true;
  418. }
  419. int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor,
  420. int oldvalue, bool *sunlight_seen_result)
  421. {
  422. ScopeProfiler sp(g_profiler, "CM::getBackgroundBrightness", SPT_AVG);
  423. static v3f z_directions[50] = {
  424. v3f(-100, 0, 0)
  425. };
  426. static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = {
  427. -1000,
  428. };
  429. if(z_directions[0].X < -99){
  430. for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
  431. // Assumes FOV of 72 and 16/9 aspect ratio
  432. z_directions[i] = v3f(
  433. 0.02 * myrand_range(-100, 100),
  434. 1.0,
  435. 0.01 * myrand_range(-100, 100)
  436. ).normalize();
  437. z_offsets[i] = 0.01 * myrand_range(0,100);
  438. }
  439. }
  440. int sunlight_seen_count = 0;
  441. float sunlight_min_d = max_d*0.8;
  442. if(sunlight_min_d > 35*BS)
  443. sunlight_min_d = 35*BS;
  444. std::vector<int> values;
  445. for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){
  446. v3f z_dir = z_directions[i];
  447. core::CMatrix4<f32> a;
  448. a.buildRotateFromTo(v3f(0,1,0), z_dir);
  449. v3f dir = m_camera_direction;
  450. a.rotateVect(dir);
  451. int br = 0;
  452. float step = BS*1.5;
  453. if(max_d > 35*BS)
  454. step = max_d / 35 * 1.5;
  455. float off = step * z_offsets[i];
  456. bool sunlight_seen_now = false;
  457. bool ok = getVisibleBrightness(this, m_camera_position, dir,
  458. step, 1.0, max_d*0.6+off, max_d, m_nodedef, daylight_factor,
  459. sunlight_min_d,
  460. &br, &sunlight_seen_now);
  461. if(sunlight_seen_now)
  462. sunlight_seen_count++;
  463. if(!ok)
  464. continue;
  465. values.push_back(br);
  466. // Don't try too much if being in the sun is clear
  467. if(sunlight_seen_count >= 20)
  468. break;
  469. }
  470. int brightness_sum = 0;
  471. int brightness_count = 0;
  472. std::sort(values.begin(), values.end());
  473. u32 num_values_to_use = values.size();
  474. if(num_values_to_use >= 10)
  475. num_values_to_use -= num_values_to_use/2;
  476. else if(num_values_to_use >= 7)
  477. num_values_to_use -= num_values_to_use/3;
  478. u32 first_value_i = (values.size() - num_values_to_use) / 2;
  479. for (u32 i=first_value_i; i < first_value_i + num_values_to_use; i++) {
  480. brightness_sum += values[i];
  481. brightness_count++;
  482. }
  483. int ret = 0;
  484. if(brightness_count == 0){
  485. MapNode n = getNode(floatToInt(m_camera_position, BS));
  486. if(m_nodedef->get(n).param_type == CPT_LIGHT){
  487. ret = decode_light(n.getLightBlend(daylight_factor, m_nodedef));
  488. } else {
  489. ret = oldvalue;
  490. }
  491. } else {
  492. ret = brightness_sum / brightness_count;
  493. }
  494. *sunlight_seen_result = (sunlight_seen_count > 0);
  495. return ret;
  496. }
  497. void ClientMap::renderPostFx(CameraMode cam_mode)
  498. {
  499. // Sadly ISceneManager has no "post effects" render pass, in that case we
  500. // could just register for that and handle it in renderMap().
  501. MapNode n = getNode(floatToInt(m_camera_position, BS));
  502. // - If the player is in a solid node, make everything black.
  503. // - If the player is in liquid, draw a semi-transparent overlay.
  504. // - Do not if player is in third person mode
  505. const ContentFeatures& features = m_nodedef->get(n);
  506. video::SColor post_effect_color = features.post_effect_color;
  507. if(features.solidness == 2 && !(g_settings->getBool("noclip") &&
  508. m_client->checkLocalPrivilege("noclip")) &&
  509. cam_mode == CAMERA_MODE_FIRST)
  510. {
  511. post_effect_color = video::SColor(255, 0, 0, 0);
  512. }
  513. if (post_effect_color.getAlpha() != 0)
  514. {
  515. // Draw a full-screen rectangle
  516. video::IVideoDriver* driver = SceneManager->getVideoDriver();
  517. v2u32 ss = driver->getScreenSize();
  518. core::rect<s32> rect(0,0, ss.X, ss.Y);
  519. driver->draw2DRectangle(post_effect_color, rect);
  520. }
  521. }
  522. void ClientMap::PrintInfo(std::ostream &out)
  523. {
  524. out<<"ClientMap: ";
  525. }