Remove superfluous pointer null checks
[oweals/minetest.git] / src / mesh_generator_thread.cpp
1 /*
2 Minetest
3 Copyright (C) 2013, 2017 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 "mesh_generator_thread.h"
21 #include "settings.h"
22 #include "profiler.h"
23 #include "client.h"
24 #include "mapblock.h"
25 #include "map.h"
26
27 /*
28         CachedMapBlockData
29 */
30
31 CachedMapBlockData::CachedMapBlockData():
32         p(-1337,-1337,-1337),
33         data(NULL),
34         refcount_from_queue(0),
35         last_used_timestamp(time(0))
36 {
37 }
38
39 CachedMapBlockData::~CachedMapBlockData()
40 {
41         assert(refcount_from_queue == 0);
42
43         delete[] data;
44 }
45
46 /*
47         QueuedMeshUpdate
48 */
49
50 QueuedMeshUpdate::QueuedMeshUpdate():
51         p(-1337,-1337,-1337),
52         ack_block_to_server(false),
53         urgent(false),
54         crack_level(-1),
55         crack_pos(0,0,0),
56         data(NULL)
57 {
58 }
59
60 QueuedMeshUpdate::~QueuedMeshUpdate()
61 {
62         delete data;
63 }
64
65 /*
66         MeshUpdateQueue
67 */
68
69 MeshUpdateQueue::MeshUpdateQueue(Client *client):
70         m_client(client)
71 {
72         m_cache_enable_shaders = g_settings->getBool("enable_shaders");
73         m_cache_use_tangent_vertices = m_cache_enable_shaders && (
74                 g_settings->getBool("enable_bumpmapping") ||
75                 g_settings->getBool("enable_parallax_occlusion"));
76         m_cache_smooth_lighting = g_settings->getBool("smooth_lighting");
77         m_meshgen_block_cache_size = g_settings->getS32("meshgen_block_cache_size");
78 }
79
80 MeshUpdateQueue::~MeshUpdateQueue()
81 {
82         MutexAutoLock lock(m_mutex);
83
84         for (std::map<v3s16, CachedMapBlockData *>::iterator i = m_cache.begin();
85                         i != m_cache.end(); ++i) {
86                 delete i->second;
87         }
88
89         for (std::vector<QueuedMeshUpdate*>::iterator i = m_queue.begin();
90                         i != m_queue.end(); ++i) {
91                 QueuedMeshUpdate *q = *i;
92                 delete q;
93         }
94 }
95
96 void MeshUpdateQueue::addBlock(Map *map, v3s16 p, bool ack_block_to_server, bool urgent)
97 {
98         DSTACK(FUNCTION_NAME);
99
100         MutexAutoLock lock(m_mutex);
101
102         cleanupCache();
103
104         /*
105                 Cache the block data (force-update the center block, don't update the
106                 neighbors but get them if they aren't already cached)
107         */
108         std::vector<CachedMapBlockData*> cached_blocks;
109         size_t cache_hit_counter = 0;
110         cached_blocks.reserve(3*3*3);
111         v3s16 dp;
112         for (dp.X = -1; dp.X <= 1; dp.X++)
113         for (dp.Y = -1; dp.Y <= 1; dp.Y++)
114         for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
115                 v3s16 p1 = p + dp;
116                 CachedMapBlockData *cached_block;
117                 if (dp == v3s16(0, 0, 0))
118                         cached_block = cacheBlock(map, p1, FORCE_UPDATE);
119                 else
120                         cached_block = cacheBlock(map, p1, SKIP_UPDATE_IF_ALREADY_CACHED,
121                                         &cache_hit_counter);
122                 cached_blocks.push_back(cached_block);
123         }
124         g_profiler->avg("MeshUpdateQueue MapBlock cache hit %",
125                         100.0f * cache_hit_counter / cached_blocks.size());
126
127         /*
128                 Mark the block as urgent if requested
129         */
130         if (urgent)
131                 m_urgents.insert(p);
132
133         /*
134                 Find if block is already in queue.
135                 If it is, update the data and quit.
136         */
137         for (std::vector<QueuedMeshUpdate*>::iterator i = m_queue.begin();
138                         i != m_queue.end(); ++i) {
139                 QueuedMeshUpdate *q = *i;
140                 if (q->p == p) {
141                         // NOTE: We are not adding a new position to the queue, thus
142                         //       refcount_from_queue stays the same.
143                         if(ack_block_to_server)
144                                 q->ack_block_to_server = true;
145                         q->crack_level = m_client->getCrackLevel();
146                         q->crack_pos = m_client->getCrackPos();
147                         return;
148                 }
149         }
150
151         /*
152                 Add the block
153         */
154         QueuedMeshUpdate *q = new QueuedMeshUpdate;
155         q->p = p;
156         q->ack_block_to_server = ack_block_to_server;
157         q->crack_level = m_client->getCrackLevel();
158         q->crack_pos = m_client->getCrackPos();
159         m_queue.push_back(q);
160
161         // This queue entry is a new reference to the cached blocks
162         for (size_t i=0; i<cached_blocks.size(); i++) {
163                 cached_blocks[i]->refcount_from_queue++;
164         }
165 }
166
167 // Returned pointer must be deleted
168 // Returns NULL if queue is empty
169 QueuedMeshUpdate *MeshUpdateQueue::pop()
170 {
171         MutexAutoLock lock(m_mutex);
172
173         bool must_be_urgent = !m_urgents.empty();
174         for (std::vector<QueuedMeshUpdate*>::iterator i = m_queue.begin();
175                         i != m_queue.end(); ++i) {
176                 QueuedMeshUpdate *q = *i;
177                 if(must_be_urgent && m_urgents.count(q->p) == 0)
178                         continue;
179                 m_queue.erase(i);
180                 m_urgents.erase(q->p);
181                 fillDataFromMapBlockCache(q);
182                 return q;
183         }
184         return NULL;
185 }
186
187 CachedMapBlockData* MeshUpdateQueue::cacheBlock(Map *map, v3s16 p, UpdateMode mode,
188                         size_t *cache_hit_counter)
189 {
190         std::map<v3s16, CachedMapBlockData*>::iterator it =
191                         m_cache.find(p);
192         if (it != m_cache.end()) {
193                 // Already in cache
194                 CachedMapBlockData *cached_block = it->second;
195                 if (mode == SKIP_UPDATE_IF_ALREADY_CACHED) {
196                         if (cache_hit_counter)
197                                 (*cache_hit_counter)++;
198                         return cached_block;
199                 }
200                 MapBlock *b = map->getBlockNoCreateNoEx(p);
201                 if (b) {
202                         if (cached_block->data == NULL)
203                                 cached_block->data =
204                                                 new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE];
205                         memcpy(cached_block->data, b->getData(),
206                                         MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * sizeof(MapNode));
207                 } else {
208                         delete[] cached_block->data;
209                         cached_block->data = NULL;
210                 }
211                 return cached_block;
212         } else {
213                 // Not yet in cache
214                 CachedMapBlockData *cached_block = new CachedMapBlockData();
215                 m_cache[p] = cached_block;
216                 MapBlock *b = map->getBlockNoCreateNoEx(p);
217                 if (b) {
218                         cached_block->data =
219                                         new MapNode[MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE];
220                         memcpy(cached_block->data, b->getData(),
221                                         MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE * sizeof(MapNode));
222                 }
223                 return cached_block;
224         }
225 }
226
227 CachedMapBlockData* MeshUpdateQueue::getCachedBlock(const v3s16 &p)
228 {
229         std::map<v3s16, CachedMapBlockData*>::iterator it = m_cache.find(p);
230         if (it != m_cache.end()) {
231                 return it->second;
232         }
233         return NULL;
234 }
235
236 void MeshUpdateQueue::fillDataFromMapBlockCache(QueuedMeshUpdate *q)
237 {
238         MeshMakeData *data = new MeshMakeData(m_client, m_cache_enable_shaders,
239                         m_cache_use_tangent_vertices);
240         q->data = data;
241
242         data->fillBlockDataBegin(q->p);
243
244         int t_now = time(0);
245
246         // Collect data for 3*3*3 blocks from cache
247         v3s16 dp;
248         for (dp.X = -1; dp.X <= 1; dp.X++)
249         for (dp.Y = -1; dp.Y <= 1; dp.Y++)
250         for (dp.Z = -1; dp.Z <= 1; dp.Z++) {
251                 v3s16 p = q->p + dp;
252                 CachedMapBlockData *cached_block = getCachedBlock(p);
253                 if (cached_block) {
254                         cached_block->refcount_from_queue--;
255                         cached_block->last_used_timestamp = t_now;
256                         if (cached_block->data)
257                                 data->fillBlockData(dp, cached_block->data);
258                 }
259         }
260
261         data->setCrack(q->crack_level, q->crack_pos);
262         data->setSmoothLighting(m_cache_smooth_lighting);
263 }
264
265 void MeshUpdateQueue::cleanupCache()
266 {
267         const int mapblock_kB = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE *
268                         sizeof(MapNode) / 1000;
269         g_profiler->avg("MeshUpdateQueue MapBlock cache size kB",
270                         mapblock_kB * m_cache.size());
271
272         // The cache size is kept roughly below cache_soft_max_size, not letting
273         // anything get older than cache_seconds_max or deleted before 2 seconds.
274         const int cache_seconds_max = 10;
275         const int cache_soft_max_size = m_meshgen_block_cache_size * 1000 / mapblock_kB;
276         int cache_seconds = MYMAX(2, cache_seconds_max -
277                         m_cache.size() / (cache_soft_max_size / cache_seconds_max));
278
279         int t_now = time(0);
280
281         for (std::map<v3s16, CachedMapBlockData*>::iterator it = m_cache.begin();
282                         it != m_cache.end(); ) {
283                 CachedMapBlockData *cached_block = it->second;
284                 if (cached_block->refcount_from_queue == 0 &&
285                                 cached_block->last_used_timestamp < t_now - cache_seconds) {
286                         m_cache.erase(it++);
287                         delete cached_block;
288                 } else {
289                         ++it;
290                 }
291         }
292 }
293
294 /*
295         MeshUpdateThread
296 */
297
298 MeshUpdateThread::MeshUpdateThread(Client *client):
299         UpdateThread("Mesh"),
300         m_queue_in(client)
301 {
302         m_generation_interval = g_settings->getU16("mesh_generation_interval");
303         m_generation_interval = rangelim(m_generation_interval, 0, 50);
304 }
305
306 void MeshUpdateThread::updateBlock(Map *map, v3s16 p, bool ack_block_to_server,
307                 bool urgent)
308 {
309         // Allow the MeshUpdateQueue to do whatever it wants
310         m_queue_in.addBlock(map, p, ack_block_to_server, urgent);
311         deferUpdate();
312 }
313
314 void MeshUpdateThread::doUpdate()
315 {
316         QueuedMeshUpdate *q;
317         while ((q = m_queue_in.pop())) {
318                 if (m_generation_interval)
319                         sleep_ms(m_generation_interval);
320                 ScopeProfiler sp(g_profiler, "Client: Mesh making");
321
322                 MapBlockMesh *mesh_new = new MapBlockMesh(q->data, m_camera_offset);
323
324                 MeshUpdateResult r;
325                 r.p = q->p;
326                 r.mesh = mesh_new;
327                 r.ack_block_to_server = q->ack_block_to_server;
328
329                 m_queue_out.push_back(r);
330
331                 delete q;
332         }
333 }