QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
TerrariumTileFetcher.cc
Go to the documentation of this file.
1/****************************************************************************
2 *
3 * (c) 2009-2024 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 *
5 * QGroundControl is licensed according to the terms in the file
6 * COPYING.md in the root of the source code directory.
7 *
8 ****************************************************************************/
9
11
12#include <memory>
13#include <utility>
14
15#include <QtCore/QVarLengthArray>
16#include <QtGui/QImage>
17#include <QtNetwork/QNetworkAccessManager>
18#include <QtNetwork/QNetworkReply>
19
20#include "BilinearUV.h"
22#include "HeightField.h"
23#include "PatchGeometry.h"
24#include "QGCCacheTile.h"
25#include "QGCLoggingCategory.h"
26#include "QGCMapEngine.h"
27#include "QGCMapTasks.h"
28#include "QGCMapUrlEngine.h"
30#include "QGeoTileFetcherQGC.h"
31
32QGC_LOGGING_CATEGORY(GeoMapTerrariumTileFetcherLog, "GeoMap.TerrariumTileFetcher")
33QGC_LOGGING_CATEGORY(GeoMapTerrariumTileFetcherVerboseLog, "GeoMap.TerrariumTileFetcher.Verbose")
34
35static_assert(TerrariumTileFetcher::kMaxGridSize == PatchGeometry::kMaxGridSize,
36 "fetcher grid cap must match the patch mesh cap");
37
38namespace {
39
40QString terrariumProviderType()
41{
42 return QString::fromLatin1(TerrariumElevationProvider::kProviderKey);
43}
44
46double heightAtPixel(const QImage& image, int px, int py)
47{
48 const QRgb rgb = image.pixel(px, py);
49 return (qRed(rgb) * 256.0) + qGreen(rgb) + (qBlue(rgb) / 256.0) - 32768.0;
50}
51
54double heightAtUV(const QImage& image, double u, double v)
55{
56 const auto at = [&image](int x, int y) { return heightAtPixel(image, x, y); };
57 return bilinearAtUV(image.width(), image.height(), u, v, at);
58}
59
62QList<float> sampleGrid(const QImage& image, const QRectF& subWindow, int gridSize)
63{
64 QList<float> heights;
65 heights.reserve(qsizetype(gridSize + 1) * (gridSize + 1));
66 for (int row = 0; row <= gridSize; row++) {
67 const double v = subWindow.y() + (subWindow.height() * row / gridSize);
68 for (int col = 0; col <= gridSize; col++) {
69 const double u = subWindow.x() + (subWindow.width() * col / gridSize);
70 heights.append(static_cast<float>(heightAtUV(image, u, v)));
71 }
72 }
73 return heights;
74}
75
78constexpr int kTileSizePixels = 256;
79
81QImage decodeTile(const QByteArray& data)
82{
83 QImage image;
84 if (!image.loadFromData(data) || image.width() != kTileSizePixels || image.height() != kTileSizePixels) {
85 return QImage();
86 }
87 return image.convertToFormat(QImage::Format_RGB32);
88}
89
91ElevationTilePyramid::Grid gridFromImage(const QImage& image)
92{
94 grid.width = image.width();
95 grid.height = image.height();
96 grid.heights.reserve(qsizetype(grid.width) * grid.height);
97 for (int py = 0; py < grid.height; py++) {
98 for (int px = 0; px < grid.width; px++) {
99 grid.heights.append(static_cast<float>(heightAtPixel(image, px, py)));
100 }
101 }
102 return grid;
103}
104
107TileMath::TileKey fetchKeyFor(const TileMath::TileKey& key)
108{
110 return key;
111 }
112 const int shift = key.zoom - TerrariumTileFetcher::kMaxTileZoom;
113 return TileMath::TileKey{key.x >> shift, key.y >> shift, TerrariumTileFetcher::kMaxTileZoom};
114}
115
119QVarLengthArray<TileMath::TileKey, 4> anchorKeysFor(const TileMath::TileKey& fetchKey)
120{
121 QVarLengthArray<TileMath::TileKey, 4> anchors;
122 if (fetchKey.zoom <= TerrariumTileFetcher::kAnchorZoom) {
123 return anchors;
124 }
125 const int shift = fetchKey.zoom - TerrariumTileFetcher::kAnchorZoom;
126 anchors.append(TileMath::TileKey{fetchKey.x >> shift, fetchKey.y >> shift, TerrariumTileFetcher::kAnchorZoom});
127 for (int dy = -1; dy <= 1; dy++) {
128 for (int dx = -1; dx <= 1; dx++) {
129 const TileMath::TileKey neighbor{fetchKey.x + dx, fetchKey.y + dy, fetchKey.zoom};
130 if (!TileMath::isValidKey(neighbor)) {
131 continue;
132 }
133 const TileMath::TileKey anchor{neighbor.x >> shift, neighbor.y >> shift, TerrariumTileFetcher::kAnchorZoom};
134 if (!anchors.contains(anchor)) {
135 anchors.append(anchor);
136 }
137 }
138 }
139 return anchors;
140}
141
142} // namespace
143
144TerrariumTileFetcher::TerrariumTileFetcher(QObject* parent, QNetworkAccessManager* networkManager)
145 : HeightSource(parent),
146 _networkManager(networkManager ? networkManager : new QNetworkAccessManager(this)),
147 _mapId(UrlFactory::getQtMapIdFromProviderType(terrariumProviderType()))
148{
149 // Only a QtLocation map initializes the shared tile cache on its own
151}
152
154{
155 const int requestId = _nextRequestId();
156
157 if ((gridSize <= 0) || (gridSize > kMaxGridSize) || !TileMath::isValidKey(key)) {
158 qCWarning(GeoMapTerrariumTileFetcherLog)
159 << "requestPatchHeights rejected: key" << key << "gridSize" << gridSize;
160 _pending.insert(requestId, PendingRequest{});
161 _failAsync(requestId);
162 return requestId;
163 }
164 if (_mapId < 0) {
165 qCDebug(GeoMapTerrariumTileFetcherLog) << "requestPatchHeights: elevation provider not registered";
166 _pending.insert(requestId, PendingRequest{});
167 _failAsync(requestId);
168 return requestId;
169 }
170
171 // Deeper than the dataset: fetch the top-zoom ancestor and sample the
172 // patch's sub-window of it
173 PendingRequest pending;
174 pending.gridSize = gridSize;
175 pending.fetchKey = fetchKeyFor(key);
176 if (key.zoom <= kMaxTileZoom) {
177 pending.subWindow = QRectF(0, 0, 1, 1);
178 } else {
179 const int shift = key.zoom - kMaxTileZoom;
180 const double scale = 1.0 / (1LL << shift);
181 pending.subWindow = QRectF((key.x - (qint64(pending.fetchKey.x) << shift)) * scale,
182 (key.y - (qint64(pending.fetchKey.y) << shift)) * scale, scale, scale);
183 }
184 _pending.insert(requestId, pending);
185 _lastFetchKey = pending.fetchKey;
186
187 const bool inFlight = _fetchInFlight(pending.fetchKey);
188 _waiters[pending.fetchKey].append(requestId);
189 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
190 << "requestPatchHeights: key" << key << "requestId" << requestId << "fetchKey" << pending.fetchKey
191 << (inFlight ? "(joining in-flight fetch)" : "(starting fetch)");
192 if (inFlight) {
193 return requestId; // a fetch for this tile is already in flight; it serves all waiters
194 }
195
196 if (!_startFetch(pending.fetchKey)) {
197 qCDebug(GeoMapTerrariumTileFetcherLog) << "requestPatchHeights: could not start fetch for" << pending.fetchKey;
198 _waiters.remove(pending.fetchKey);
199 _failAsync(requestId);
200 }
201 return requestId;
202}
203
205{
206 if (!_heightField || !TileMath::isValidKey(key)) {
207 qCWarning(GeoMapTerrariumTileFetcherLog)
208 << "requestTile rejected: key" << key << "heightFieldSet" << (_heightField != nullptr);
209 return false;
210 }
211 if (_mapId < 0) {
212 qCDebug(GeoMapTerrariumTileFetcherLog) << "requestTile: elevation provider not registered";
213 return false;
214 }
215
216 const TileMath::TileKey fetchKey = fetchKeyFor(key);
217 if (_heightField->hasTile(fetchKey) || _fieldRequests.contains(fetchKey) || _held.contains(fetchKey)) {
218 return true;
219 }
220
221 // Anchors first: their fetches queue ahead, and _insertIntoField holds this tile until they land.
222 // An anchor that fails to start stops blocking, as a failed fetch does in _failAll.
223 for (const TileMath::TileKey& anchor : anchorKeysFor(fetchKey)) {
224 (void) requestTile(anchor);
225 }
226
227 const bool inFlight = _fetchInFlight(fetchKey);
228 _fieldRequests.insert(fetchKey);
229 _lastFetchKey = fetchKey;
230 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
231 << "requestTile: fetchKey" << fetchKey << (inFlight ? "(joining in-flight fetch)" : "(starting fetch)");
232 if (inFlight) {
233 return true; // piggyback on the fetch already serving patch waiters
234 }
235
236 if (!_startFetch(fetchKey)) {
237 qCDebug(GeoMapTerrariumTileFetcherLog) << "requestTile: could not start fetch for" << fetchKey;
238 _fieldRequests.remove(fetchKey);
239 return false;
240 }
241 return true;
242}
243
244bool TerrariumTileFetcher::_fetchInFlight(const TileMath::TileKey& fetchKey) const
245{
246 return _waiters.contains(fetchKey) || _fieldRequests.contains(fetchKey);
247}
248
249bool TerrariumTileFetcher::_startFetch(const TileMath::TileKey& fetchKey)
250{
251 const QString providerType = terrariumProviderType();
252 QGCFetchTileTask* const task =
253 QGeoFileTileCacheQGC::createFetchTileTask(providerType, fetchKey.x, fetchKey.y, fetchKey.zoom);
254 connect(task, &QGCFetchTileTask::tileFetched, this, [this, fetchKey](QGCCacheTile* tile) {
255 const std::unique_ptr<QGCCacheTile> guard(tile); // caller-owned per task contract
256 if (!_fetchInFlight(fetchKey)) {
257 return; // all interest cancelled while the lookup was in flight
258 }
259 // An unusable cached body (empty or corrupt) is a miss, not a
260 // failure: failing here would re-read the same bytes on every retry,
261 // blocking the network fallback until cache eviction
262 const QImage image = tile ? decodeTile(tile->img) : QImage();
263 if (image.isNull()) {
264 qCDebug(GeoMapTerrariumTileFetcherLog)
265 << "tile" << fetchKey << "cached entry unusable, fetching from network";
266 _fetchFromNetwork(fetchKey);
267 return;
268 }
269 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) << "tile" << fetchKey << "served from cache";
270 _deliverAll(fetchKey, image);
271 });
272 connect(task, &QGCMapTask::error, this, [this, fetchKey](QGCMapTask::TaskType, const QString&) {
273 if (!_fetchInFlight(fetchKey)) {
274 return;
275 }
276 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) << "tile" << fetchKey << "not cached, fetching from network";
277 _fetchFromNetwork(fetchKey);
278 });
279
280 if (!getQGCMapEngine()->addTask(task)) {
281 qCDebug(GeoMapTerrariumTileFetcherLog) << "could not queue cache lookup for" << fetchKey;
282 task->deleteLater(); // never enqueued: the worker will not clean it up
283 return false;
284 }
285 return true;
286}
287
289{
290 const auto pendingIt = _pending.constFind(requestId);
291 if (pendingIt == _pending.cend()) {
292 return;
293 }
294 const TileMath::TileKey fetchKey = pendingIt->fetchKey;
295 _pending.erase(pendingIt);
296
297 const auto waitersIt = _waiters.find(fetchKey);
298 if (waitersIt == _waiters.end()) {
299 return;
300 }
301 waitersIt->removeOne(requestId);
302 if (!waitersIt->isEmpty()) {
303 return; // other requests still wait on this tile's fetch
304 }
305 _waiters.erase(waitersIt);
306 if (_fieldRequests.contains(fetchKey)) {
307 return; // the field still wants this tile: keep the fetch alive
308 }
309 QNetworkReply* const reply = _activeReplies.take(fetchKey);
310 if (reply) {
311 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) << "cancelRequest: aborting network fetch for" << fetchKey;
312 reply->abort(); // finished handler is a no-op once no waiters remain
313 reply->deleteLater(); // don't rely on abort emitting finished for cleanup
314 }
315}
316
317void TerrariumTileFetcher::_failAsync(int requestId)
318{
319 // Deliver asynchronously so callers see one consistent flow
320 QMetaObject::invokeMethod(
321 this,
322 [this, requestId] {
323 if (_pending.contains(requestId)) {
324 _finishFailed(requestId);
325 }
326 },
327 Qt::QueuedConnection);
328}
329
330void TerrariumTileFetcher::_fetchFromNetwork(const TileMath::TileKey& fetchKey)
331{
332 if (_activeReplies.contains(fetchKey)) {
333 return; // a reply is already in flight for this tile
334 }
335 const QNetworkRequest request =
336 QGeoTileFetcherQGC::getNetworkRequest(_mapId, fetchKey.x, fetchKey.y, fetchKey.zoom);
337 QNetworkReply* const reply = _networkManager->get(request);
338 _activeReplies.insert(fetchKey, reply);
339
340 connect(reply, &QNetworkReply::finished, this, [this, fetchKey, reply] {
341 reply->deleteLater();
342 if (_activeReplies.value(fetchKey) != reply) {
343 return; // stale: cancelled (and possibly superseded by a newer fetch)
344 }
345 _activeReplies.remove(fetchKey);
346 if (!_fetchInFlight(fetchKey)) {
347 return; // all interest cancelled (abort also lands here)
348 }
349 if (reply->error() != QNetworkReply::NoError) {
350 _failAll(fetchKey, QStringLiteral("network error: %1 (http %2)")
351 .arg(reply->errorString())
352 .arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()));
353 return;
354 }
355 const QByteArray data = reply->readAll();
356 if (data.isEmpty()) {
357 _failAll(fetchKey, QStringLiteral("network fetch returned empty body"));
358 return;
359 }
360 // Never cache bodies that delivery would reject (e.g. HTTP-200 error
361 // pages): a cached invalid tile would fail every retry from then on
362 const QImage image = decodeTile(data);
363 if (image.isNull()) {
364 _failAll(fetchKey, QStringLiteral("network body is not a terrarium tile, %1 bytes").arg(data.size()));
365 return;
366 }
367 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
368 << "tile" << fetchKey << "fetched from network," << data.size() << "bytes, caching";
369 // Store back so the shared cache serves this tile from now on
370 const QString providerType = terrariumProviderType();
371 QGeoFileTileCacheQGC::cacheTile(providerType, fetchKey.x, fetchKey.y, fetchKey.zoom, data,
372 UrlFactory::getImageFormat(providerType, data));
373 _deliverAll(fetchKey, image);
374 });
375}
376
377void TerrariumTileFetcher::_deliverAll(const TileMath::TileKey& fetchKey, const QImage& image)
378{
379 const bool forField = _fieldRequests.remove(fetchKey) && _heightField;
380 if (forField) {
381 _insertIntoField(fetchKey, gridFromImage(image));
382 }
383
384 const QList<int> requestIds = _waiters.take(fetchKey);
385 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
386 << "delivering tile" << fetchKey << "to" << requestIds.count() << "waiters, field insert:" << forField;
387 for (int requestId : requestIds) {
388 if (_pending.contains(requestId)) {
389 _deliver(requestId, image);
390 }
391 }
392}
393
394void TerrariumTileFetcher::_failAll(const TileMath::TileKey& fetchKey, const QString& reason)
395{
396 // A failed tile inserts nothing: the field keeps its current estimate, and
397 // clearing the in-flight key lets a later request retry
398 _fieldRequests.remove(fetchKey);
399 // Better fine data with a cliff risk than none at all
400 const int released = _releaseHeld(fetchKey);
401 if (released > 0) {
402 qCDebug(GeoMapTerrariumTileFetcherLog)
403 << "anchor" << fetchKey << "failed, released" << released << "held tiles";
404 }
405
406 const QList<int> requestIds = _waiters.take(fetchKey);
407 if (_shouldWarnFailure()) {
408 qCWarning(GeoMapTerrariumTileFetcherLog)
409 << "tile" << fetchKey << "failed:" << reason << "- failing" << requestIds.count() << "waiters";
410 } else {
411 qCDebug(GeoMapTerrariumTileFetcherLog) << "tile" << fetchKey << "failed:" << reason << "- failing"
412 << requestIds.count() << "waiters (warning suppressed)";
413 }
414 for (int requestId : requestIds) {
415 if (_pending.contains(requestId)) {
416 _finishFailed(requestId);
417 }
418 }
419}
420
421bool TerrariumTileFetcher::_shouldWarnFailure()
422{
423 if (_failureWarnTimer.isValid() && (_failureWarnTimer.elapsed() < kFailureWarnIntervalMs)) {
424 return false;
425 }
426 _failureWarnTimer.restart();
427 return true;
428}
429
430void TerrariumTileFetcher::_insertIntoField(const TileMath::TileKey& fetchKey, ElevationTilePyramid::Grid grid)
431{
432 QSet<TileMath::TileKey> missingAnchors;
433 for (const TileMath::TileKey& anchor : anchorKeysFor(fetchKey)) {
434 if (!_heightField->hasTile(anchor) && _fieldRequests.contains(anchor)) {
435 missingAnchors.insert(anchor);
436 }
437 }
438 if (!missingAnchors.isEmpty()) {
439 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
440 << "holding tile" << fetchKey << "until anchors" << missingAnchors;
441 _held.insert(fetchKey, HeldTile{std::move(grid), std::move(missingAnchors)});
442 return;
443 }
444 _heightField->insertTile(fetchKey, std::move(grid));
445 (void) _releaseHeld(fetchKey);
446}
447
448int TerrariumTileFetcher::_releaseHeld(const TileMath::TileKey& anchor)
449{
450 QList<std::pair<TileMath::TileKey, ElevationTilePyramid::Grid>> ready;
451 for (auto it = _held.begin(); it != _held.end();) {
452 if (it->anchors.remove(anchor) && it->anchors.isEmpty()) {
453 ready.append({it.key(), std::move(it->grid)});
454 it = _held.erase(it);
455 } else {
456 ++it;
457 }
458 }
459 // Inserted after the walk: regionChanged handlers may re-enter requestTile
460 for (auto& [key, grid] : ready) {
461 _heightField->insertTile(key, std::move(grid));
462 }
463 return int(ready.count());
464}
465
466void TerrariumTileFetcher::_deliver(int requestId, const QImage& image)
467{
468 const PendingRequest pending = _pending.take(requestId);
469 emit patchHeightsReady(requestId, sampleGrid(image, pending.subWindow, pending.gridSize));
470}
471
472void TerrariumTileFetcher::_finishFailed(int requestId)
473{
474 _pending.remove(requestId);
475 emit patchHeightsFailed(requestId);
476}
double bilinearAtUV(int w, int h, double u, double v, SampleAt at)
Definition BilinearUV.h:24
#define QGC_LOGGING_CATEGORY(name, categoryStr)
QGCMapEngine * getQGCMapEngine()
void patchHeightsReady(int requestId, const QList< float > &heights)
heights has (gridSize+1)^2 entries, row-major from the north-west corner
void patchHeightsFailed(int requestId)
HeightField * _heightField
tile delivery target for requestTile (not owned)
HeightSource(QObject *parent=nullptr)
int _nextRequestId()
void tileFetched(QGCCacheTile *tile)
void ensureInitialized()
void error(QGCMapTask::TaskType type, const QString &errorString)
static QGCFetchTileTask * createFetchTileTask(const QString &type, int x, int y, int z)
static void cacheTile(const QString &type, int x, int y, int z, const QByteArray &image, const QString &format, qulonglong set=UINT64_MAX)
static QNetworkRequest getNetworkRequest(int mapId, int x, int y, int zoom)
static constexpr const char * kProviderKey
static constexpr int kAnchorZoom
static constexpr int kMaxGridSize
Largest supported patch grid (matches PatchGeometry::kMaxGridSize).
static constexpr int kMaxTileZoom
Highest zoom the terrarium dataset serves (deeper patches sample the ancestor).
bool requestTile(const TileMath::TileKey &key) override
TerrariumTileFetcher(QObject *parent=nullptr, QNetworkAccessManager *networkManager=nullptr)
networkManager overrides the internally created one (test injection seam)
void cancelRequest(int requestId) final
Cancel a pending request. No signal is emitted for a cancelled request.
int requestPatchHeights(const TileMath::TileKey &key, int gridSize) final
static QString getImageFormat(QStringView type, QByteArrayView image)
bool isValidKey(const TileKey &key)
True if zoom is within [kMinZoom, kMaxZoom] and x/y address a tile at that zoom.
Definition TileMath.cc:44
Decoded elevation samples for one tile, row-major from the NW corner.
QByteArray img