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