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