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