Translated using Weblate (Chinese (Simplified))
[oweals/minetest.git] / src / client / minimap.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2015 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 "minimap.h"
21 #include <cmath>
22 #include "client.h"
23 #include "clientmap.h"
24 #include "settings.h"
25 #include "shader.h"
26 #include "mapblock.h"
27 #include "client/renderingengine.h"
28
29
30 ////
31 //// MinimapUpdateThread
32 ////
33
34 MinimapUpdateThread::~MinimapUpdateThread()
35 {
36         for (auto &it : m_blocks_cache) {
37                 delete it.second;
38         }
39
40         for (auto &q : m_update_queue) {
41                 delete q.data;
42         }
43 }
44
45 bool MinimapUpdateThread::pushBlockUpdate(v3s16 pos, MinimapMapblock *data)
46 {
47         MutexAutoLock lock(m_queue_mutex);
48
49         // Find if block is already in queue.
50         // If it is, update the data and quit.
51         for (QueuedMinimapUpdate &q : m_update_queue) {
52                 if (q.pos == pos) {
53                         delete q.data;
54                         q.data = data;
55                         return false;
56                 }
57         }
58
59         // Add the block
60         QueuedMinimapUpdate q;
61         q.pos  = pos;
62         q.data = data;
63         m_update_queue.push_back(q);
64
65         return true;
66 }
67
68 bool MinimapUpdateThread::popBlockUpdate(QueuedMinimapUpdate *update)
69 {
70         MutexAutoLock lock(m_queue_mutex);
71
72         if (m_update_queue.empty())
73                 return false;
74
75         *update = m_update_queue.front();
76         m_update_queue.pop_front();
77
78         return true;
79 }
80
81 void MinimapUpdateThread::enqueueBlock(v3s16 pos, MinimapMapblock *data)
82 {
83         pushBlockUpdate(pos, data);
84         deferUpdate();
85 }
86
87
88 void MinimapUpdateThread::doUpdate()
89 {
90         QueuedMinimapUpdate update;
91
92         while (popBlockUpdate(&update)) {
93                 if (update.data) {
94                         // Swap two values in the map using single lookup
95                         std::pair<std::map<v3s16, MinimapMapblock*>::iterator, bool>
96                             result = m_blocks_cache.insert(std::make_pair(update.pos, update.data));
97                         if (!result.second) {
98                                 delete result.first->second;
99                                 result.first->second = update.data;
100                         }
101                 } else {
102                         std::map<v3s16, MinimapMapblock *>::iterator it;
103                         it = m_blocks_cache.find(update.pos);
104                         if (it != m_blocks_cache.end()) {
105                                 delete it->second;
106                                 m_blocks_cache.erase(it);
107                         }
108                 }
109         }
110
111         if (data->map_invalidated && data->mode != MINIMAP_MODE_OFF) {
112                 getMap(data->pos, data->map_size, data->scan_height);
113                 data->map_invalidated = false;
114         }
115 }
116
117 void MinimapUpdateThread::getMap(v3s16 pos, s16 size, s16 height)
118 {
119         v3s16 pos_min(pos.X - size / 2, pos.Y - height / 2, pos.Z - size / 2);
120         v3s16 pos_max(pos_min.X + size - 1, pos.Y + height / 2, pos_min.Z + size - 1);
121         v3s16 blockpos_min = getNodeBlockPos(pos_min);
122         v3s16 blockpos_max = getNodeBlockPos(pos_max);
123
124 // clear the map
125         for (int z = 0; z < size; z++)
126         for (int x = 0; x < size; x++) {
127                 MinimapPixel &mmpixel = data->minimap_scan[x + z * size];
128                 mmpixel.air_count = 0;
129                 mmpixel.height = 0;
130                 mmpixel.n = MapNode(CONTENT_AIR);
131         }
132
133 // draw the map
134         v3s16 blockpos;
135         for (blockpos.Z = blockpos_min.Z; blockpos.Z <= blockpos_max.Z; ++blockpos.Z)
136         for (blockpos.Y = blockpos_min.Y; blockpos.Y <= blockpos_max.Y; ++blockpos.Y)
137         for (blockpos.X = blockpos_min.X; blockpos.X <= blockpos_max.X; ++blockpos.X) {
138                 std::map<v3s16, MinimapMapblock *>::const_iterator pblock =
139                         m_blocks_cache.find(blockpos);
140                 if (pblock == m_blocks_cache.end())
141                         continue;
142                 const MinimapMapblock &block = *pblock->second;
143
144                 v3s16 block_node_min(blockpos * MAP_BLOCKSIZE);
145                 v3s16 block_node_max(block_node_min + MAP_BLOCKSIZE - 1);
146                 // clip
147                 v3s16 range_min = componentwise_max(block_node_min, pos_min);
148                 v3s16 range_max = componentwise_min(block_node_max, pos_max);
149
150                 v3s16 pos;
151                 pos.Y = range_min.Y;
152                 for (pos.Z = range_min.Z; pos.Z <= range_max.Z; ++pos.Z)
153                 for (pos.X = range_min.X; pos.X <= range_max.X; ++pos.X) {
154                         v3s16 inblock_pos = pos - block_node_min;
155                         const MinimapPixel &in_pixel =
156                                 block.data[inblock_pos.Z * MAP_BLOCKSIZE + inblock_pos.X];
157
158                         v3s16 inmap_pos = pos - pos_min;
159                         MinimapPixel &out_pixel =
160                                 data->minimap_scan[inmap_pos.X + inmap_pos.Z * size];
161
162                         out_pixel.air_count += in_pixel.air_count;
163                         if (in_pixel.n.param0 != CONTENT_AIR) {
164                                 out_pixel.n = in_pixel.n;
165                                 out_pixel.height = inmap_pos.Y + in_pixel.height;
166                         }
167                 }
168         }
169 }
170
171 ////
172 //// Mapper
173 ////
174
175 Minimap::Minimap(Client *client)
176 {
177         this->client    = client;
178         this->driver    = RenderingEngine::get_video_driver();
179         this->m_tsrc    = client->getTextureSource();
180         this->m_shdrsrc = client->getShaderSource();
181         this->m_ndef    = client->getNodeDefManager();
182
183         m_angle = 0.f;
184
185         // Initialize static settings
186         m_enable_shaders = g_settings->getBool("enable_shaders");
187         m_surface_mode_scan_height =
188                 g_settings->getBool("minimap_double_scan_height") ? 256 : 128;
189
190         // Initialize minimap data
191         data = new MinimapData;
192         data->mode              = MINIMAP_MODE_OFF;
193         data->is_radar          = false;
194         data->map_invalidated   = true;
195         data->texture           = NULL;
196         data->heightmap_texture = NULL;
197         data->minimap_shape_round = g_settings->getBool("minimap_shape_round");
198
199         // Get round minimap textures
200         data->minimap_mask_round = driver->createImage(
201                 m_tsrc->getTexture("minimap_mask_round.png"),
202                 core::position2d<s32>(0, 0),
203                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
204         data->minimap_overlay_round = m_tsrc->getTexture("minimap_overlay_round.png");
205
206         // Get square minimap textures
207         data->minimap_mask_square = driver->createImage(
208                 m_tsrc->getTexture("minimap_mask_square.png"),
209                 core::position2d<s32>(0, 0),
210                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
211         data->minimap_overlay_square = m_tsrc->getTexture("minimap_overlay_square.png");
212
213         // Create player marker texture
214         data->player_marker = m_tsrc->getTexture("player_marker.png");
215         // Create object marker texture
216         data->object_marker_red = m_tsrc->getTexture("object_marker_red.png");
217
218         // Create mesh buffer for minimap
219         m_meshbuffer = getMinimapMeshBuffer();
220
221         // Initialize and start thread
222         m_minimap_update_thread = new MinimapUpdateThread();
223         m_minimap_update_thread->data = data;
224         m_minimap_update_thread->start();
225 }
226
227 Minimap::~Minimap()
228 {
229         m_minimap_update_thread->stop();
230         m_minimap_update_thread->wait();
231
232         m_meshbuffer->drop();
233
234         data->minimap_mask_round->drop();
235         data->minimap_mask_square->drop();
236
237         driver->removeTexture(data->texture);
238         driver->removeTexture(data->heightmap_texture);
239         driver->removeTexture(data->minimap_overlay_round);
240         driver->removeTexture(data->minimap_overlay_square);
241         driver->removeTexture(data->object_marker_red);
242
243         delete data;
244         delete m_minimap_update_thread;
245 }
246
247 void Minimap::addBlock(v3s16 pos, MinimapMapblock *data)
248 {
249         m_minimap_update_thread->enqueueBlock(pos, data);
250 }
251
252 void Minimap::toggleMinimapShape()
253 {
254         MutexAutoLock lock(m_mutex);
255
256         data->minimap_shape_round = !data->minimap_shape_round;
257         g_settings->setBool("minimap_shape_round", data->minimap_shape_round);
258         m_minimap_update_thread->deferUpdate();
259 }
260
261 void Minimap::setMinimapShape(MinimapShape shape)
262 {
263         MutexAutoLock lock(m_mutex);
264
265         if (shape == MINIMAP_SHAPE_SQUARE)
266                 data->minimap_shape_round = false;
267         else if (shape == MINIMAP_SHAPE_ROUND)
268                 data->minimap_shape_round = true;
269
270         g_settings->setBool("minimap_shape_round", data->minimap_shape_round);
271         m_minimap_update_thread->deferUpdate();
272 }
273
274 MinimapShape Minimap::getMinimapShape()
275 {
276         if (data->minimap_shape_round) {
277                 return MINIMAP_SHAPE_ROUND;
278         }
279
280         return MINIMAP_SHAPE_SQUARE;
281 }
282
283 void Minimap::setMinimapMode(MinimapMode mode)
284 {
285         static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = {
286                 {false, 0, 0},
287                 {false, m_surface_mode_scan_height, 256},
288                 {false, m_surface_mode_scan_height, 128},
289                 {false, m_surface_mode_scan_height, 64},
290                 {true, 32, 128},
291                 {true, 32, 64},
292                 {true, 32, 32}
293         };
294
295         if (mode >= MINIMAP_MODE_COUNT)
296                 return;
297
298         MutexAutoLock lock(m_mutex);
299
300         data->is_radar    = modedefs[mode].is_radar;
301         data->scan_height = modedefs[mode].scan_height;
302         data->map_size    = modedefs[mode].map_size;
303         data->mode        = mode;
304
305         m_minimap_update_thread->deferUpdate();
306 }
307
308 void Minimap::setPos(v3s16 pos)
309 {
310         bool do_update = false;
311
312         {
313                 MutexAutoLock lock(m_mutex);
314
315                 if (pos != data->old_pos) {
316                         data->old_pos = data->pos;
317                         data->pos = pos;
318                         do_update = true;
319                 }
320         }
321
322         if (do_update)
323                 m_minimap_update_thread->deferUpdate();
324 }
325
326 void Minimap::setAngle(f32 angle)
327 {
328         m_angle = angle;
329 }
330
331 void Minimap::blitMinimapPixelsToImageRadar(video::IImage *map_image)
332 {
333         video::SColor c(240, 0, 0, 0);
334         for (s16 x = 0; x < data->map_size; x++)
335         for (s16 z = 0; z < data->map_size; z++) {
336                 MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
337
338                 if (mmpixel->air_count > 0)
339                         c.setGreen(core::clamp(core::round32(32 + mmpixel->air_count * 8), 0, 255));
340                 else
341                         c.setGreen(0);
342
343                 map_image->setPixel(x, data->map_size - z - 1, c);
344         }
345 }
346
347 void Minimap::blitMinimapPixelsToImageSurface(
348         video::IImage *map_image, video::IImage *heightmap_image)
349 {
350         // This variable creation/destruction has a 1% cost on rendering minimap
351         video::SColor tilecolor;
352         for (s16 x = 0; x < data->map_size; x++)
353         for (s16 z = 0; z < data->map_size; z++) {
354                 MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size];
355
356                 const ContentFeatures &f = m_ndef->get(mmpixel->n);
357                 const TileDef *tile = &f.tiledef[0];
358
359                 // Color of the 0th tile (mostly this is the topmost)
360                 if(tile->has_color)
361                         tilecolor = tile->color;
362                 else
363                         mmpixel->n.getColor(f, &tilecolor);
364
365                 tilecolor.setRed(tilecolor.getRed() * f.minimap_color.getRed() / 255);
366                 tilecolor.setGreen(tilecolor.getGreen() * f.minimap_color.getGreen() / 255);
367                 tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255);
368                 tilecolor.setAlpha(240);
369
370                 map_image->setPixel(x, data->map_size - z - 1, tilecolor);
371
372                 u32 h = mmpixel->height;
373                 heightmap_image->setPixel(x,data->map_size - z - 1,
374                         video::SColor(255, h, h, h));
375         }
376 }
377
378 video::ITexture *Minimap::getMinimapTexture()
379 {
380         // update minimap textures when new scan is ready
381         if (data->map_invalidated)
382                 return data->texture;
383
384         // create minimap and heightmap images in memory
385         core::dimension2d<u32> dim(data->map_size, data->map_size);
386         video::IImage *map_image       = driver->createImage(video::ECF_A8R8G8B8, dim);
387         video::IImage *heightmap_image = driver->createImage(video::ECF_A8R8G8B8, dim);
388         video::IImage *minimap_image   = driver->createImage(video::ECF_A8R8G8B8,
389                 core::dimension2d<u32>(MINIMAP_MAX_SX, MINIMAP_MAX_SY));
390
391         // Blit MinimapPixels to images
392         if (data->is_radar)
393                 blitMinimapPixelsToImageRadar(map_image);
394         else
395                 blitMinimapPixelsToImageSurface(map_image, heightmap_image);
396
397         map_image->copyToScaling(minimap_image);
398         map_image->drop();
399
400         video::IImage *minimap_mask = data->minimap_shape_round ?
401                 data->minimap_mask_round : data->minimap_mask_square;
402
403         if (minimap_mask) {
404                 for (s16 y = 0; y < MINIMAP_MAX_SY; y++)
405                 for (s16 x = 0; x < MINIMAP_MAX_SX; x++) {
406                         const video::SColor &mask_col = minimap_mask->getPixel(x, y);
407                         if (!mask_col.getAlpha())
408                                 minimap_image->setPixel(x, y, video::SColor(0,0,0,0));
409                 }
410         }
411
412         if (data->texture)
413                 driver->removeTexture(data->texture);
414         if (data->heightmap_texture)
415                 driver->removeTexture(data->heightmap_texture);
416
417         data->texture = driver->addTexture("minimap__", minimap_image);
418         data->heightmap_texture =
419                 driver->addTexture("minimap_heightmap__", heightmap_image);
420         minimap_image->drop();
421         heightmap_image->drop();
422
423         data->map_invalidated = true;
424
425         return data->texture;
426 }
427
428 v3f Minimap::getYawVec()
429 {
430         if (data->minimap_shape_round) {
431                 return v3f(
432                         std::cos(m_angle * core::DEGTORAD),
433                         std::sin(m_angle * core::DEGTORAD),
434                         1.0);
435         }
436
437         return v3f(1.0, 0.0, 1.0);
438 }
439
440 scene::SMeshBuffer *Minimap::getMinimapMeshBuffer()
441 {
442         scene::SMeshBuffer *buf = new scene::SMeshBuffer();
443         buf->Vertices.set_used(4);
444         buf->Indices.set_used(6);
445         static const video::SColor c(255, 255, 255, 255);
446
447         buf->Vertices[0] = video::S3DVertex(-1, -1, 0, 0, 0, 1, c, 0, 1);
448         buf->Vertices[1] = video::S3DVertex(-1,  1, 0, 0, 0, 1, c, 0, 0);
449         buf->Vertices[2] = video::S3DVertex( 1,  1, 0, 0, 0, 1, c, 1, 0);
450         buf->Vertices[3] = video::S3DVertex( 1, -1, 0, 0, 0, 1, c, 1, 1);
451
452         buf->Indices[0] = 0;
453         buf->Indices[1] = 1;
454         buf->Indices[2] = 2;
455         buf->Indices[3] = 2;
456         buf->Indices[4] = 3;
457         buf->Indices[5] = 0;
458
459         return buf;
460 }
461
462 void Minimap::drawMinimap()
463 {
464         video::ITexture *minimap_texture = getMinimapTexture();
465         if (!minimap_texture)
466                 return;
467
468         updateActiveMarkers();
469         v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
470         const u32 size = 0.25 * screensize.Y;
471
472         core::rect<s32> oldViewPort = driver->getViewPort();
473         core::matrix4 oldProjMat = driver->getTransform(video::ETS_PROJECTION);
474         core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW);
475
476         driver->setViewPort(core::rect<s32>(
477                 screensize.X - size - 10, 10,
478                 screensize.X - 10, size + 10));
479         driver->setTransform(video::ETS_PROJECTION, core::matrix4());
480         driver->setTransform(video::ETS_VIEW, core::matrix4());
481
482         core::matrix4 matrix;
483         matrix.makeIdentity();
484
485         video::SMaterial &material = m_meshbuffer->getMaterial();
486         material.setFlag(video::EMF_TRILINEAR_FILTER, true);
487         material.Lighting = false;
488         material.TextureLayer[0].Texture = minimap_texture;
489         material.TextureLayer[1].Texture = data->heightmap_texture;
490
491         if (m_enable_shaders && !data->is_radar) {
492                 u16 sid = m_shdrsrc->getShader("minimap_shader", 1, 1);
493                 material.MaterialType = m_shdrsrc->getShaderInfo(sid).material;
494         } else {
495                 material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
496         }
497
498         if (data->minimap_shape_round)
499                 matrix.setRotationDegrees(core::vector3df(0, 0, 360 - m_angle));
500
501         // Draw minimap
502         driver->setTransform(video::ETS_WORLD, matrix);
503         driver->setMaterial(material);
504         driver->drawMeshBuffer(m_meshbuffer);
505
506         // Draw overlay
507         video::ITexture *minimap_overlay = data->minimap_shape_round ?
508                 data->minimap_overlay_round : data->minimap_overlay_square;
509         material.TextureLayer[0].Texture = minimap_overlay;
510         material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
511         driver->setMaterial(material);
512         driver->drawMeshBuffer(m_meshbuffer);
513
514         // Draw player marker on minimap
515         if (data->minimap_shape_round) {
516                 matrix.setRotationDegrees(core::vector3df(0, 0, 0));
517         } else {
518                 matrix.setRotationDegrees(core::vector3df(0, 0, m_angle));
519         }
520
521         material.TextureLayer[0].Texture = data->player_marker;
522         driver->setTransform(video::ETS_WORLD, matrix);
523         driver->setMaterial(material);
524         driver->drawMeshBuffer(m_meshbuffer);
525
526         // Reset transformations
527         driver->setTransform(video::ETS_VIEW, oldViewMat);
528         driver->setTransform(video::ETS_PROJECTION, oldProjMat);
529         driver->setViewPort(oldViewPort);
530
531         // Draw player markers
532         v2s32 s_pos(screensize.X - size - 10, 10);
533         core::dimension2di imgsize(data->object_marker_red->getOriginalSize());
534         core::rect<s32> img_rect(0, 0, imgsize.Width, imgsize.Height);
535         static const video::SColor col(255, 255, 255, 255);
536         static const video::SColor c[4] = {col, col, col, col};
537         f32 sin_angle = std::sin(m_angle * core::DEGTORAD);
538         f32 cos_angle = std::cos(m_angle * core::DEGTORAD);
539         s32 marker_size2 =  0.025 * (float)size;
540         for (std::list<v2f>::const_iterator
541                         i = m_active_markers.begin();
542                         i != m_active_markers.end(); ++i) {
543                 v2f posf = *i;
544                 if (data->minimap_shape_round) {
545                         f32 t1 = posf.X * cos_angle - posf.Y * sin_angle;
546                         f32 t2 = posf.X * sin_angle + posf.Y * cos_angle;
547                         posf.X = t1;
548                         posf.Y = t2;
549                 }
550                 posf.X = (posf.X + 0.5) * (float)size;
551                 posf.Y = (posf.Y + 0.5) * (float)size;
552                 core::rect<s32> dest_rect(
553                         s_pos.X + posf.X - marker_size2,
554                         s_pos.Y + posf.Y - marker_size2,
555                         s_pos.X + posf.X + marker_size2,
556                         s_pos.Y + posf.Y + marker_size2);
557                 driver->draw2DImage(data->object_marker_red, dest_rect,
558                         img_rect, &dest_rect, &c[0], true);
559         }
560 }
561
562 void Minimap::updateActiveMarkers()
563 {
564         video::IImage *minimap_mask = data->minimap_shape_round ?
565                 data->minimap_mask_round : data->minimap_mask_square;
566
567         const std::list<Nametag *> &nametags = client->getCamera()->getNametags();
568
569         m_active_markers.clear();
570
571         for (Nametag *nametag : nametags) {
572                 v3s16 pos = floatToInt(nametag->parent_node->getAbsolutePosition() +
573                         intToFloat(client->getCamera()->getOffset(), BS), BS);
574                 pos -= data->pos - v3s16(data->map_size / 2,
575                                 data->scan_height / 2,
576                                 data->map_size / 2);
577                 if (pos.X < 0 || pos.X > data->map_size ||
578                                 pos.Y < 0 || pos.Y > data->scan_height ||
579                                 pos.Z < 0 || pos.Z > data->map_size) {
580                         continue;
581                 }
582                 pos.X = ((float)pos.X / data->map_size) * MINIMAP_MAX_SX;
583                 pos.Z = ((float)pos.Z / data->map_size) * MINIMAP_MAX_SY;
584                 const video::SColor &mask_col = minimap_mask->getPixel(pos.X, pos.Z);
585                 if (!mask_col.getAlpha()) {
586                         continue;
587                 }
588
589                 m_active_markers.emplace_back(((float)pos.X / (float)MINIMAP_MAX_SX) - 0.5,
590                         (1.0 - (float)pos.Z / (float)MINIMAP_MAX_SY) - 0.5);
591         }
592 }
593
594 ////
595 //// MinimapMapblock
596 ////
597
598 void MinimapMapblock::getMinimapNodes(VoxelManipulator *vmanip, const v3s16 &pos)
599 {
600
601         for (s16 x = 0; x < MAP_BLOCKSIZE; x++)
602         for (s16 z = 0; z < MAP_BLOCKSIZE; z++) {
603                 s16 air_count = 0;
604                 bool surface_found = false;
605                 MinimapPixel *mmpixel = &data[z * MAP_BLOCKSIZE + x];
606
607                 for (s16 y = MAP_BLOCKSIZE -1; y >= 0; y--) {
608                         v3s16 p(x, y, z);
609                         MapNode n = vmanip->getNodeNoEx(pos + p);
610                         if (!surface_found && n.getContent() != CONTENT_AIR) {
611                                 mmpixel->height = y;
612                                 mmpixel->n = n;
613                                 surface_found = true;
614                         } else if (n.getContent() == CONTENT_AIR) {
615                                 air_count++;
616                         }
617                 }
618
619                 if (!surface_found)
620                         mmpixel->n = MapNode(CONTENT_AIR);
621
622                 mmpixel->air_count = air_count;
623         }
624 }