15#include <QtCore/QVarLengthArray>
16#include <QtGui/QImage>
17#include <QtNetwork/QNetworkAccessManager>
18#include <QtNetwork/QNetworkReply>
36 "fetcher grid cap must match the patch mesh cap");
40QString terrariumProviderType()
46double heightAtPixel(
const QImage& image,
int px,
int py)
48 const QRgb rgb = image.pixel(px, py);
49 return (qRed(rgb) * 256.0) + qGreen(rgb) + (qBlue(rgb) / 256.0) - 32768.0;
54double heightAtUV(
const QImage& image,
double u,
double v)
56 const auto at = [&image](
int x,
int y) {
return heightAtPixel(image, x, y); };
57 return bilinearAtUV(image.width(), image.height(), u, v, at);
62QList<float> sampleGrid(
const QImage& image,
const QRectF& subWindow,
int gridSize)
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)));
78constexpr int kTileSizePixels = 256;
81QImage decodeTile(
const QByteArray& data)
84 if (!image.loadFromData(data) || image.width() != kTileSizePixels || image.height() != kTileSizePixels) {
87 return image.convertToFormat(QImage::Format_RGB32);
94 grid.
width = image.width();
95 grid.
height = image.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)));
119QVarLengthArray<TileMath::TileKey, 4> anchorKeysFor(
const TileMath::TileKey& fetchKey)
121 QVarLengthArray<TileMath::TileKey, 4> anchors;
127 for (
int dy = -1; dy <= 1; dy++) {
128 for (
int dx = -1; dx <= 1; dx++) {
134 if (!anchors.contains(anchor)) {
135 anchors.append(anchor);
146 _networkManager(networkManager ? networkManager : new QNetworkAccessManager(this)),
147 _mapId(
UrlFactory::getQtMapIdFromProviderType(terrariumProviderType()))
158 qCWarning(GeoMapTerrariumTileFetcherLog)
159 <<
"requestPatchHeights rejected: key" << key <<
"gridSize" << gridSize;
160 _pending.insert(requestId, PendingRequest{});
161 _failAsync(requestId);
165 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"requestPatchHeights: elevation provider not registered";
166 _pending.insert(requestId, PendingRequest{});
167 _failAsync(requestId);
173 PendingRequest pending;
174 pending.gridSize = gridSize;
175 pending.fetchKey = fetchKeyFor(key);
177 pending.subWindow = QRectF(0, 0, 1, 1);
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);
184 _pending.insert(requestId, pending);
185 _lastFetchKey = pending.fetchKey;
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)");
196 if (!_startFetch(pending.fetchKey)) {
197 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"requestPatchHeights: could not start fetch for" << pending.fetchKey;
198 _waiters.remove(pending.fetchKey);
199 _failAsync(requestId);
207 qCWarning(GeoMapTerrariumTileFetcherLog)
208 <<
"requestTile rejected: key" << key <<
"heightFieldSet" << (
_heightField !=
nullptr);
212 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"requestTile: elevation provider not registered";
217 if (
_heightField->hasTile(fetchKey) || _fieldRequests.contains(fetchKey) || _held.contains(fetchKey)) {
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)");
236 if (!_startFetch(fetchKey)) {
237 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"requestTile: could not start fetch for" << fetchKey;
238 _fieldRequests.remove(fetchKey);
244bool TerrariumTileFetcher::_fetchInFlight(
const TileMath::TileKey& fetchKey)
const
246 return _waiters.contains(fetchKey) || _fieldRequests.contains(fetchKey);
251 const QString providerType = terrariumProviderType();
252 QGCFetchTileTask*
const task =
255 const std::unique_ptr<QGCCacheTile> guard(tile);
256 if (!_fetchInFlight(fetchKey)) {
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);
269 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) <<
"tile" << fetchKey <<
"served from cache";
270 _deliverAll(fetchKey, image);
273 if (!_fetchInFlight(fetchKey)) {
276 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) <<
"tile" << fetchKey <<
"not cached, fetching from network";
277 _fetchFromNetwork(fetchKey);
281 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"could not queue cache lookup for" << fetchKey;
290 const auto pendingIt = _pending.constFind(requestId);
291 if (pendingIt == _pending.cend()) {
295 _pending.erase(pendingIt);
297 const auto waitersIt = _waiters.find(fetchKey);
298 if (waitersIt == _waiters.end()) {
301 waitersIt->removeOne(requestId);
302 if (!waitersIt->isEmpty()) {
305 _waiters.erase(waitersIt);
306 if (_fieldRequests.contains(fetchKey)) {
309 QNetworkReply*
const reply = _activeReplies.take(fetchKey);
311 qCDebug(GeoMapTerrariumTileFetcherVerboseLog) <<
"cancelRequest: aborting network fetch for" << fetchKey;
313 reply->deleteLater();
317void TerrariumTileFetcher::_failAsync(
int requestId)
320 QMetaObject::invokeMethod(
323 if (_pending.contains(requestId)) {
324 _finishFailed(requestId);
327 Qt::QueuedConnection);
332 if (_activeReplies.contains(fetchKey)) {
335 const QNetworkRequest request =
337 QNetworkReply*
const reply = _networkManager->get(request);
338 _activeReplies.insert(fetchKey, reply);
340 connect(reply, &QNetworkReply::finished,
this, [
this, fetchKey, reply] {
341 reply->deleteLater();
342 if (_activeReplies.value(fetchKey) != reply) {
345 _activeReplies.remove(fetchKey);
346 if (!_fetchInFlight(fetchKey)) {
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()));
355 const QByteArray data = reply->readAll();
356 if (data.isEmpty()) {
357 _failAll(fetchKey, QStringLiteral(
"network fetch returned empty body"));
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()));
367 qCDebug(GeoMapTerrariumTileFetcherVerboseLog)
368 <<
"tile" << fetchKey <<
"fetched from network," << data.size() <<
"bytes, caching";
370 const QString providerType = terrariumProviderType();
373 _deliverAll(fetchKey, image);
377void TerrariumTileFetcher::_deliverAll(
const TileMath::TileKey& fetchKey,
const QImage& image)
379 const bool forField = _fieldRequests.remove(fetchKey) &&
_heightField;
381 _insertIntoField(fetchKey, gridFromImage(image));
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);
394void TerrariumTileFetcher::_failAll(
const TileMath::TileKey& fetchKey,
const QString& reason)
398 _fieldRequests.remove(fetchKey);
400 const int released = _releaseHeld(fetchKey);
402 qCDebug(GeoMapTerrariumTileFetcherLog)
403 <<
"anchor" << fetchKey <<
"failed, released" << released <<
"held tiles";
406 const QList<int> requestIds = _waiters.take(fetchKey);
407 if (_shouldWarnFailure()) {
408 qCWarning(GeoMapTerrariumTileFetcherLog)
409 <<
"tile" << fetchKey <<
"failed:" << reason <<
"- failing" << requestIds.count() <<
"waiters";
411 qCDebug(GeoMapTerrariumTileFetcherLog) <<
"tile" << fetchKey <<
"failed:" << reason <<
"- failing"
412 << requestIds.count() <<
"waiters (warning suppressed)";
414 for (
int requestId : requestIds) {
415 if (_pending.contains(requestId)) {
416 _finishFailed(requestId);
421bool TerrariumTileFetcher::_shouldWarnFailure()
423 if (_failureWarnTimer.isValid() && (_failureWarnTimer.elapsed() < kFailureWarnIntervalMs)) {
426 _failureWarnTimer.restart();
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);
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)});
445 (void) _releaseHeld(fetchKey);
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);
460 for (
auto& [key, grid] : ready) {
463 return int(ready.count());
466void TerrariumTileFetcher::_deliver(
int requestId,
const QImage& image)
468 const PendingRequest pending = _pending.take(requestId);
469 emit
patchHeightsReady(requestId, sampleGrid(image, pending.subWindow, pending.gridSize));
472void TerrariumTileFetcher::_finishFailed(
int requestId)
474 _pending.remove(requestId);
double bilinearAtUV(int w, int h, double u, double v, SampleAt at)
#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)
void tileFetched(QGCCacheTile *tile)
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.
Decoded elevation samples for one tile, row-major from the NW corner.
QList< float > heights
meters