Move ClientMap to clientmap.{h,cpp}
[oweals/minetest.git] / src / clientmap.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2012 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "log.h"
25 #include "mapsector.h"
26 #include "main.h" // dout_client, g_settings
27 #include "nodedef.h"
28 #include "mapblock.h"
29 #include "profiler.h"
30 #include "settings.h"
31
32 ClientMap::ClientMap(
33                 Client *client,
34                 IGameDef *gamedef,
35                 MapDrawControl &control,
36                 scene::ISceneNode* parent,
37                 scene::ISceneManager* mgr,
38                 s32 id
39 ):
40         Map(dout_client, gamedef),
41         scene::ISceneNode(parent, mgr, id),
42         m_client(client),
43         m_control(control),
44         m_camera_position(0,0,0),
45         m_camera_direction(0,0,1),
46         m_camera_fov(PI)
47 {
48         m_camera_mutex.Init();
49         assert(m_camera_mutex.IsInitialized());
50         
51         m_box = core::aabbox3d<f32>(-BS*1000000,-BS*1000000,-BS*1000000,
52                         BS*1000000,BS*1000000,BS*1000000);
53 }
54
55 ClientMap::~ClientMap()
56 {
57         /*JMutexAutoLock lock(mesh_mutex);
58         
59         if(mesh != NULL)
60         {
61                 mesh->drop();
62                 mesh = NULL;
63         }*/
64 }
65
66 MapSector * ClientMap::emergeSector(v2s16 p2d)
67 {
68         DSTACK(__FUNCTION_NAME);
69         // Check that it doesn't exist already
70         try{
71                 return getSectorNoGenerate(p2d);
72         }
73         catch(InvalidPositionException &e)
74         {
75         }
76         
77         // Create a sector
78         ClientMapSector *sector = new ClientMapSector(this, p2d, m_gamedef);
79         
80         {
81                 //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
82                 m_sectors.insert(p2d, sector);
83         }
84         
85         return sector;
86 }
87
88 #if 0
89 void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
90 {
91         DSTACK(__FUNCTION_NAME);
92         ClientMapSector *sector = NULL;
93
94         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
95         
96         core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
97
98         if(n != NULL)
99         {
100                 sector = (ClientMapSector*)n->getValue();
101                 assert(sector->getId() == MAPSECTOR_CLIENT);
102         }
103         else
104         {
105                 sector = new ClientMapSector(this, p2d);
106                 {
107                         //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
108                         m_sectors.insert(p2d, sector);
109                 }
110         }
111
112         sector->deSerialize(is);
113 }
114 #endif
115
116 void ClientMap::OnRegisterSceneNode()
117 {
118         if(IsVisible)
119         {
120                 SceneManager->registerNodeForRendering(this, scene::ESNRP_SOLID);
121                 SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT);
122         }
123
124         ISceneNode::OnRegisterSceneNode();
125 }
126
127 static bool isOccluded(Map *map, v3s16 p0, v3s16 p1, float step, float stepfac,
128                 float start_off, float end_off, u32 needed_count, INodeDefManager *nodemgr)
129 {
130         float d0 = (float)BS * p0.getDistanceFrom(p1);
131         v3s16 u0 = p1 - p0;
132         v3f uf = v3f(u0.X, u0.Y, u0.Z) * BS;
133         uf.normalize();
134         v3f p0f = v3f(p0.X, p0.Y, p0.Z) * BS;
135         u32 count = 0;
136         for(float s=start_off; s<d0+end_off; s+=step){
137                 v3f pf = p0f + uf * s;
138                 v3s16 p = floatToInt(pf, BS);
139                 MapNode n = map->getNodeNoEx(p);
140                 bool is_transparent = false;
141                 const ContentFeatures &f = nodemgr->get(n);
142                 if(f.solidness == 0)
143                         is_transparent = (f.visual_solidness != 2);
144                 else
145                         is_transparent = (f.solidness != 2);
146                 if(!is_transparent){
147                         count++;
148                         if(count >= needed_count)
149                                 return true;
150                 }
151                 step *= stepfac;
152         }
153         return false;
154 }
155
156 void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass)
157 {
158         INodeDefManager *nodemgr = m_gamedef->ndef();
159
160         //m_dout<<DTIME<<"Rendering map..."<<std::endl;
161         DSTACK(__FUNCTION_NAME);
162
163         bool is_transparent_pass = pass == scene::ESNRP_TRANSPARENT;
164         
165         std::string prefix;
166         if(pass == scene::ESNRP_SOLID)
167                 prefix = "CM: solid: ";
168         else
169                 prefix = "CM: transparent: ";
170
171         /*
172                 This is called two times per frame, reset on the non-transparent one
173         */
174         if(pass == scene::ESNRP_SOLID)
175         {
176                 m_last_drawn_sectors.clear();
177         }
178
179         /*
180                 Get time for measuring timeout.
181                 
182                 Measuring time is very useful for long delays when the
183                 machine is swapping a lot.
184         */
185         int time1 = time(0);
186
187         /*
188                 Get animation parameters
189         */
190         float animation_time = m_client->getAnimationTime();
191         int crack = m_client->getCrackLevel();
192         u32 daynight_ratio = m_client->getDayNightRatio();
193
194         m_camera_mutex.Lock();
195         v3f camera_position = m_camera_position;
196         v3f camera_direction = m_camera_direction;
197         f32 camera_fov = m_camera_fov;
198         m_camera_mutex.Unlock();
199
200         /*
201                 Get all blocks and draw all visible ones
202         */
203
204         v3s16 cam_pos_nodes = floatToInt(camera_position, BS);
205         
206         v3s16 box_nodes_d = m_control.wanted_range * v3s16(1,1,1);
207
208         v3s16 p_nodes_min = cam_pos_nodes - box_nodes_d;
209         v3s16 p_nodes_max = cam_pos_nodes + box_nodes_d;
210
211         // Take a fair amount as we will be dropping more out later
212         // Umm... these additions are a bit strange but they are needed.
213         v3s16 p_blocks_min(
214                         p_nodes_min.X / MAP_BLOCKSIZE - 3,
215                         p_nodes_min.Y / MAP_BLOCKSIZE - 3,
216                         p_nodes_min.Z / MAP_BLOCKSIZE - 3);
217         v3s16 p_blocks_max(
218                         p_nodes_max.X / MAP_BLOCKSIZE + 1,
219                         p_nodes_max.Y / MAP_BLOCKSIZE + 1,
220                         p_nodes_max.Z / MAP_BLOCKSIZE + 1);
221         
222         u32 vertex_count = 0;
223         u32 meshbuffer_count = 0;
224         
225         // For limiting number of mesh animations per frame
226         u32 mesh_animate_count = 0;
227         u32 mesh_animate_count_far = 0;
228         
229         // Number of blocks in rendering range
230         u32 blocks_in_range = 0;
231         // Number of blocks occlusion culled
232         u32 blocks_occlusion_culled = 0;
233         // Number of blocks in rendering range but don't have a mesh
234         u32 blocks_in_range_without_mesh = 0;
235         // Blocks that had mesh that would have been drawn according to
236         // rendering range (if max blocks limit didn't kick in)
237         u32 blocks_would_have_drawn = 0;
238         // Blocks that were drawn and had a mesh
239         u32 blocks_drawn = 0;
240         // Blocks which had a corresponding meshbuffer for this pass
241         u32 blocks_had_pass_meshbuf = 0;
242         // Blocks from which stuff was actually drawn
243         u32 blocks_without_stuff = 0;
244
245         /*
246                 Collect a set of blocks for drawing
247         */
248         
249         core::map<v3s16, MapBlock*> drawset;
250
251         {
252         ScopeProfiler sp(g_profiler, prefix+"collecting blocks for drawing", SPT_AVG);
253
254         for(core::map<v2s16, MapSector*>::Iterator
255                         si = m_sectors.getIterator();
256                         si.atEnd() == false; si++)
257         {
258                 MapSector *sector = si.getNode()->getValue();
259                 v2s16 sp = sector->getPos();
260                 
261                 if(m_control.range_all == false)
262                 {
263                         if(sp.X < p_blocks_min.X
264                         || sp.X > p_blocks_max.X
265                         || sp.Y < p_blocks_min.Z
266                         || sp.Y > p_blocks_max.Z)
267                                 continue;
268                 }
269
270                 core::list< MapBlock * > sectorblocks;
271                 sector->getBlocks(sectorblocks);
272                 
273                 /*
274                         Loop through blocks in sector
275                 */
276
277                 u32 sector_blocks_drawn = 0;
278                 
279                 core::list< MapBlock * >::Iterator i;
280                 for(i=sectorblocks.begin(); i!=sectorblocks.end(); i++)
281                 {
282                         MapBlock *block = *i;
283
284                         /*
285                                 Compare block position to camera position, skip
286                                 if not seen on display
287                         */
288                         
289                         float range = 100000 * BS;
290                         if(m_control.range_all == false)
291                                 range = m_control.wanted_range * BS;
292
293                         float d = 0.0;
294                         if(isBlockInSight(block->getPos(), camera_position,
295                                         camera_direction, camera_fov,
296                                         range, &d) == false)
297                         {
298                                 continue;
299                         }
300
301                         // This is ugly (spherical distance limit?)
302                         /*if(m_control.range_all == false &&
303                                         d - 0.5*BS*MAP_BLOCKSIZE > range)
304                                 continue;*/
305
306                         blocks_in_range++;
307                         
308                         /*
309                                 Ignore if mesh doesn't exist
310                         */
311                         {
312                                 //JMutexAutoLock lock(block->mesh_mutex);
313
314                                 if(block->mesh == NULL){
315                                         blocks_in_range_without_mesh++;
316                                         continue;
317                                 }
318                         }
319
320                         /*
321                                 Occlusion culling
322                         */
323
324                         v3s16 cpn = block->getPos() * MAP_BLOCKSIZE;
325                         cpn += v3s16(MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2, MAP_BLOCKSIZE/2);
326                         float step = BS*1;
327                         float stepfac = 1.1;
328                         float startoff = BS*1;
329                         float endoff = -BS*MAP_BLOCKSIZE*1.42*1.42;
330                         v3s16 spn = cam_pos_nodes + v3s16(0,0,0);
331                         s16 bs2 = MAP_BLOCKSIZE/2 + 1;
332                         u32 needed_count = 1;
333                         if(
334                                 isOccluded(this, spn, cpn + v3s16(0,0,0),
335                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
336                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,bs2),
337                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
338                                 isOccluded(this, spn, cpn + v3s16(bs2,bs2,-bs2),
339                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
340                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,bs2),
341                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
342                                 isOccluded(this, spn, cpn + v3s16(bs2,-bs2,-bs2),
343                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
344                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,bs2),
345                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
346                                 isOccluded(this, spn, cpn + v3s16(-bs2,bs2,-bs2),
347                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
348                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,bs2),
349                                         step, stepfac, startoff, endoff, needed_count, nodemgr) &&
350                                 isOccluded(this, spn, cpn + v3s16(-bs2,-bs2,-bs2),
351                                         step, stepfac, startoff, endoff, needed_count, nodemgr)
352                         )
353                         {
354                                 blocks_occlusion_culled++;
355                                 continue;
356                         }
357                         
358                         // This block is in range. Reset usage timer.
359                         block->resetUsageTimer();
360
361                         // Limit block count in case of a sudden increase
362                         blocks_would_have_drawn++;
363                         if(blocks_drawn >= m_control.wanted_max_blocks
364                                         && m_control.range_all == false
365                                         && d > m_control.wanted_min_range * BS)
366                                 continue;
367
368                         // Mesh animation
369                         {
370                                 //JMutexAutoLock lock(block->mesh_mutex);
371                                 MapBlockMesh *mapBlockMesh = block->mesh;
372                                 // Pretty random but this should work somewhat nicely
373                                 bool faraway = d >= BS*50;
374                                 //bool faraway = d >= m_control.wanted_range * BS;
375                                 if(mapBlockMesh->isAnimationForced() ||
376                                                 !faraway ||
377                                                 mesh_animate_count_far < (m_control.range_all ? 200 : 50))
378                                 {
379                                         bool animated = mapBlockMesh->animate(
380                                                         faraway,
381                                                         animation_time,
382                                                         crack,
383                                                         daynight_ratio);
384                                         if(animated)
385                                                 mesh_animate_count++;
386                                         if(animated && faraway)
387                                                 mesh_animate_count_far++;
388                                 }
389                                 else
390                                 {
391                                         mapBlockMesh->decreaseAnimationForceTimer();
392                                 }
393                         }
394
395                         // Add to set
396                         drawset[block->getPos()] = block;
397                         
398                         sector_blocks_drawn++;
399                         blocks_drawn++;
400
401                 } // foreach sectorblocks
402
403                 if(sector_blocks_drawn != 0)
404                         m_last_drawn_sectors[sp] = true;
405         }
406         } // ScopeProfiler
407         
408         /*
409                 Draw the selected MapBlocks
410         */
411
412         {
413         ScopeProfiler sp(g_profiler, prefix+"drawing blocks", SPT_AVG);
414
415         int timecheck_counter = 0;
416         for(core::map<v3s16, MapBlock*>::Iterator
417                         i = drawset.getIterator();
418                         i.atEnd() == false; i++)
419         {
420                 {
421                         timecheck_counter++;
422                         if(timecheck_counter > 50)
423                         {
424                                 timecheck_counter = 0;
425                                 int time2 = time(0);
426                                 if(time2 > time1 + 4)
427                                 {
428                                         infostream<<"ClientMap::renderMap(): "
429                                                 "Rendering takes ages, returning."
430                                                 <<std::endl;
431                                         return;
432                                 }
433                         }
434                 }
435                 
436                 MapBlock *block = i.getNode()->getValue();
437
438                 /*
439                         Draw the faces of the block
440                 */
441                 {
442                         //JMutexAutoLock lock(block->mesh_mutex);
443
444                         MapBlockMesh *mapBlockMesh = block->mesh;
445                         assert(mapBlockMesh);
446
447                         scene::SMesh *mesh = mapBlockMesh->getMesh();
448                         assert(mesh);
449
450                         u32 c = mesh->getMeshBufferCount();
451                         bool stuff_actually_drawn = false;
452                         for(u32 i=0; i<c; i++)
453                         {
454                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
455                                 const video::SMaterial& material = buf->getMaterial();
456                                 video::IMaterialRenderer* rnd =
457                                                 driver->getMaterialRenderer(material.MaterialType);
458                                 bool transparent = (rnd && rnd->isTransparent());
459                                 // Render transparent on transparent pass and likewise.
460                                 if(transparent == is_transparent_pass)
461                                 {
462                                         if(buf->getVertexCount() == 0)
463                                                 errorstream<<"Block ["<<analyze_block(block)
464                                                                 <<"] contains an empty meshbuf"<<std::endl;
465                                         /*
466                                                 This *shouldn't* hurt too much because Irrlicht
467                                                 doesn't change opengl textures if the old
468                                                 material has the same texture.
469                                         */
470                                         driver->setMaterial(buf->getMaterial());
471                                         driver->drawMeshBuffer(buf);
472                                         vertex_count += buf->getVertexCount();
473                                         meshbuffer_count++;
474                                         stuff_actually_drawn = true;
475                                 }
476                         }
477                         if(stuff_actually_drawn)
478                                 blocks_had_pass_meshbuf++;
479                         else
480                                 blocks_without_stuff++;
481                 }
482         }
483         } // ScopeProfiler
484         
485         // Log only on solid pass because values are the same
486         if(pass == scene::ESNRP_SOLID){
487                 g_profiler->avg("CM: blocks in range", blocks_in_range);
488                 g_profiler->avg("CM: blocks occlusion culled", blocks_occlusion_culled);
489                 if(blocks_in_range != 0)
490                         g_profiler->avg("CM: blocks in range without mesh (frac)",
491                                         (float)blocks_in_range_without_mesh/blocks_in_range);
492                 g_profiler->avg("CM: blocks drawn", blocks_drawn);
493                 g_profiler->avg("CM: animated meshes", mesh_animate_count);
494                 g_profiler->avg("CM: animated meshes (far)", mesh_animate_count_far);
495         }
496         
497         g_profiler->avg(prefix+"vertices drawn", vertex_count);
498         if(blocks_had_pass_meshbuf != 0)
499                 g_profiler->avg(prefix+"meshbuffers per block",
500                                 (float)meshbuffer_count / (float)blocks_had_pass_meshbuf);
501         if(blocks_drawn != 0)
502                 g_profiler->avg(prefix+"empty blocks (frac)",
503                                 (float)blocks_without_stuff / blocks_drawn);
504
505         m_control.blocks_drawn = blocks_drawn;
506         m_control.blocks_would_have_drawn = blocks_would_have_drawn;
507
508         /*infostream<<"renderMap(): is_transparent_pass="<<is_transparent_pass
509                         <<", rendered "<<vertex_count<<" vertices."<<std::endl;*/
510 }
511
512 void ClientMap::renderPostFx()
513 {
514         INodeDefManager *nodemgr = m_gamedef->ndef();
515
516         // Sadly ISceneManager has no "post effects" render pass, in that case we
517         // could just register for that and handle it in renderMap().
518
519         m_camera_mutex.Lock();
520         v3f camera_position = m_camera_position;
521         m_camera_mutex.Unlock();
522
523         MapNode n = getNodeNoEx(floatToInt(camera_position, BS));
524
525         // - If the player is in a solid node, make everything black.
526         // - If the player is in liquid, draw a semi-transparent overlay.
527         const ContentFeatures& features = nodemgr->get(n);
528         video::SColor post_effect_color = features.post_effect_color;
529         if(features.solidness == 2 && g_settings->getBool("free_move") == false)
530         {
531                 post_effect_color = video::SColor(255, 0, 0, 0);
532         }
533         if (post_effect_color.getAlpha() != 0)
534         {
535                 // Draw a full-screen rectangle
536                 video::IVideoDriver* driver = SceneManager->getVideoDriver();
537                 v2u32 ss = driver->getScreenSize();
538                 core::rect<s32> rect(0,0, ss.X, ss.Y);
539                 driver->draw2DRectangle(post_effect_color, rect);
540         }
541 }
542
543 void ClientMap::PrintInfo(std::ostream &out)
544 {
545         out<<"ClientMap: ";
546 }
547
548