Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL MBTiles driver
4 : * Purpose: Implement GDAL MBTiles support using OGR SQLite driver
5 : * Author: Even Rouault, Even Rouault <even.rouault at spatialys.com>
6 : *
7 : **********************************************************************
8 : * Copyright (c) 2012-2016, Even Rouault <even.rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #if defined(HAVE_SQLITE) && defined(HAVE_GEOS)
14 : // Needed by mvtutils.h
15 : #define HAVE_MVT_WRITE_SUPPORT
16 : #endif
17 :
18 : #include "gdal_frmts.h"
19 : #include "gdal_pam.h"
20 : #include "ogr_api.h"
21 : #include "cpl_json.h"
22 : #include "cpl_vsil_curl_priv.h"
23 : #include "gpkgmbtilescommon.h"
24 : #include "gdal_utils.h"
25 : #include "gdalwarper.h"
26 : #include "mvtutils.h"
27 : #include "ogrsqlitevfs.h"
28 : #include "ogrsqlitebase.h"
29 :
30 : #include "zlib.h"
31 : #include "ogrlibjsonutils.h"
32 :
33 : #include <math.h>
34 : #include <algorithm>
35 : #include <memory>
36 : #include <vector>
37 :
38 : static const char *const apszAllowedDrivers[] = {"JPEG", "PNG", "WEBP",
39 : nullptr};
40 :
41 : #define SRS_EPSG_3857 \
42 : "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS " \
43 : "84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS " \
44 : "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[" \
45 : "\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]" \
46 : ",UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]]," \
47 : "AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[" \
48 : "\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_" \
49 : "easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[" \
50 : "\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION[" \
51 : "\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 " \
52 : "+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext " \
53 : "+no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]"
54 :
55 : #define SPHERICAL_RADIUS 6378137.0
56 : #define MAX_GM (SPHERICAL_RADIUS * M_PI) // 20037508.342789244
57 :
58 : // TileMatrixSet origin : caution this is in GeoPackage / WMTS convention ! That
59 : // is upper-left corner
60 : #define TMS_ORIGIN_X -MAX_GM
61 : #define TMS_ORIGIN_Y MAX_GM
62 :
63 : #if defined(DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) || \
64 : defined(ALLOW_FORMAT_DUMPS)
65 : // Enable accepting a SQL dump (starting with a "-- SQL MBTILES" line) as a
66 : // valid file. This makes fuzzer life easier
67 : #define ENABLE_SQL_SQLITE_FORMAT
68 : #endif
69 :
70 : constexpr int knDEFAULT_BLOCK_SIZE = 256;
71 :
72 : class MBTilesBand;
73 :
74 : /************************************************************************/
75 : /* MBTILESOpenSQLiteDB() */
76 : /************************************************************************/
77 :
78 77 : static GDALDatasetH MBTILESOpenSQLiteDB(const char *pszFilename,
79 : GDALAccess eAccess)
80 : {
81 77 : const char *l_apszAllowedDrivers[] = {"SQLITE", nullptr};
82 154 : return GDALOpenEx((CPLString("SQLITE:") + pszFilename).c_str(),
83 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL |
84 : ((eAccess == GA_Update) ? GDAL_OF_UPDATE : 0),
85 154 : l_apszAllowedDrivers, nullptr, nullptr);
86 : }
87 :
88 : /************************************************************************/
89 : /* ==================================================================== */
90 : /* MBTilesDataset */
91 : /* ==================================================================== */
92 : /************************************************************************/
93 :
94 : class MBTilesDataset final : public GDALPamDataset,
95 : public GDALGPKGMBTilesLikePseudoDataset
96 : {
97 : friend class MBTilesBand;
98 : friend class MBTilesVectorLayer;
99 :
100 : public:
101 : MBTilesDataset();
102 :
103 : ~MBTilesDataset() override;
104 :
105 : CPLErr GetGeoTransform(GDALGeoTransform >) const override;
106 : CPLErr SetGeoTransform(const GDALGeoTransform >) override;
107 : const OGRSpatialReference *GetSpatialRef() const override;
108 : CPLErr SetSpatialRef(const OGRSpatialReference *poSRS) override;
109 :
110 : char **GetMetadataDomainList() override;
111 : char **GetMetadata(const char *pszDomain = "") override;
112 : virtual const char *GetMetadataItem(const char *pszName,
113 : const char *pszDomain = "") override;
114 :
115 : CPLErr IBuildOverviews(const char *pszResampling, int nOverviews,
116 : const int *panOverviewList, int nBandsIn,
117 : const int * /* panBandList */,
118 : GDALProgressFunc pfnProgress, void *pProgressData,
119 : CSLConstList papszOptions) override;
120 :
121 1166 : int GetLayerCount() const override
122 : {
123 1166 : return static_cast<int>(m_apoLayers.size());
124 : }
125 :
126 : const OGRLayer *GetLayer(int) const override;
127 :
128 : static GDALDataset *Open(GDALOpenInfo *);
129 : static int Identify(GDALOpenInfo *);
130 : static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
131 : int nBandsIn, GDALDataType eDT,
132 : char **papszOptions);
133 : static GDALDataset *CreateCopy(const char *pszFilename,
134 : GDALDataset *poSrcDS, int bStrict,
135 : char **papszOptions,
136 : GDALProgressFunc pfnProgress,
137 : void *pProgressData);
138 :
139 : char *FindKey(int iPixel, int iLine);
140 :
141 : bool HasNonEmptyGrids();
142 :
143 : private:
144 : bool m_bWriteBounds;
145 : CPLString m_osBounds;
146 : CPLString m_osCenter;
147 : bool m_bWriteMinMaxZoom;
148 : MBTilesDataset *poMainDS;
149 : bool m_bGeoTransformValid;
150 : GDALGeoTransform m_gt{};
151 : int m_nMinZoomLevel = 0;
152 : OGRSpatialReference m_oSRS{};
153 :
154 : int m_nOverviewCount;
155 : MBTilesDataset **m_papoOverviewDS;
156 :
157 : GDALDatasetH hDS;
158 : sqlite3 *hDB;
159 :
160 : sqlite3_vfs *pMyVFS;
161 :
162 : bool bFetchedMetadata;
163 : CPLStringList aosList;
164 :
165 : int nHasNonEmptyGrids;
166 :
167 : bool m_bInFlushCache;
168 :
169 : CPLString m_osMetadataMemFilename;
170 : CPLString m_osClip;
171 : std::vector<std::unique_ptr<OGRLayer>> m_apoLayers;
172 :
173 : void ParseCompressionOptions(char **papszOptions);
174 : CPLErr FinalizeRasterRegistration();
175 : void ComputeTileAndPixelShifts();
176 : bool InitRaster(MBTilesDataset *poParentDS, int nZoomLevel, int nBandCount,
177 : int nTileSize, double dfGDALMinX, double dfGDALMinY,
178 : double dfGDALMaxX, double dfGDALMaxY);
179 :
180 : bool CreateInternal(const char *pszFilename, int nXSize, int nYSize,
181 : int nBandsIn, GDALDataType eDT, char **papszOptions);
182 : void InitVector(double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
183 : bool bZoomLevelFromSpatialFilter, bool bJsonField);
184 :
185 : protected:
186 : // Coming from GDALGPKGMBTilesLikePseudoDataset
187 :
188 : CPLErr IFlushCacheWithErrCode(bool bAtClosing) override;
189 :
190 1963 : int IGetRasterCount() override
191 : {
192 1963 : return nBands;
193 : }
194 :
195 3310 : GDALRasterBand *IGetRasterBand(int nBand) override
196 : {
197 3310 : return GetRasterBand(nBand);
198 : }
199 :
200 546 : sqlite3 *IGetDB() override
201 : {
202 546 : return hDB;
203 : }
204 :
205 943 : bool IGetUpdate() override
206 : {
207 943 : return eAccess == GA_Update;
208 : }
209 :
210 : bool ICanIWriteBlock() override;
211 : OGRErr IStartTransaction() override;
212 : OGRErr ICommitTransaction() override;
213 :
214 22 : const char *IGetFilename() override
215 : {
216 22 : return GetDescription();
217 : }
218 :
219 : int GetRowFromIntoTopConvention(int nRow) override;
220 : };
221 :
222 : /************************************************************************/
223 : /* ==================================================================== */
224 : /* MBTilesVectorLayer */
225 : /* ==================================================================== */
226 : /************************************************************************/
227 :
228 : class MBTilesVectorLayer final : public OGRLayer
229 : {
230 : MBTilesDataset *m_poDS = nullptr;
231 : OGRFeatureDefn *m_poFeatureDefn = nullptr;
232 : OGRLayerH m_hTileIteratorLyr = nullptr;
233 : bool m_bEOF = false;
234 : CPLString m_osTmpFilename;
235 : GDALDatasetH m_hTileDS = nullptr;
236 : GIntBig m_nFeatureCount = -1;
237 : int m_nX = 0;
238 : int m_nY = 0;
239 : OGREnvelope m_sExtent;
240 : int m_nFilterMinX = 0;
241 : int m_nFilterMinY = 0;
242 : int m_nFilterMaxX = 0;
243 : int m_nFilterMaxY = 0;
244 : int m_nZoomLevel = 0;
245 : bool m_bZoomLevelAuto = false;
246 : bool m_bJsonField = false;
247 :
248 : OGRFeature *GetNextRawFeature();
249 : OGRFeature *GetNextSrcFeature();
250 : OGRFeature *CreateFeatureFrom(OGRFeature *poSrcFeature) const;
251 :
252 : public:
253 : MBTilesVectorLayer(MBTilesDataset *poDS, const char *pszLayerName,
254 : const CPLJSONObject &oFields,
255 : const CPLJSONArray &oAttributesFromTileStats,
256 : bool bJsonField, double dfMinX, double dfMinY,
257 : double dfMaxX, double dfMaxY,
258 : OGRwkbGeometryType eGeomType,
259 : bool bZoomLevelFromSpatialFilter);
260 : ~MBTilesVectorLayer() override;
261 :
262 : void ResetReading() override;
263 : OGRFeature *GetNextFeature() override;
264 :
265 750 : const OGRFeatureDefn *GetLayerDefn() const override
266 : {
267 750 : return m_poFeatureDefn;
268 : }
269 :
270 : GIntBig GetFeatureCount(int bForce) override;
271 : int TestCapability(const char *) const override;
272 :
273 : OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
274 : bool bForce) override;
275 :
276 : virtual OGRErr ISetSpatialFilter(int iGeomField,
277 : const OGRGeometry *poGeom) override;
278 :
279 : OGRFeature *GetFeature(GIntBig nFID) override;
280 : };
281 :
282 : /************************************************************************/
283 : /* ==================================================================== */
284 : /* MBTilesBand */
285 : /* ==================================================================== */
286 : /************************************************************************/
287 :
288 : class MBTilesBand final : public GDALGPKGMBTilesLikeRasterBand
289 : {
290 : friend class MBTilesDataset;
291 :
292 : CPLString osLocationInfo;
293 :
294 : public:
295 : explicit MBTilesBand(MBTilesDataset *poDS, int nTileSize);
296 :
297 : int GetOverviewCount() override;
298 : GDALRasterBand *GetOverview(int nLevel) override;
299 :
300 : char **GetMetadataDomainList() override;
301 : virtual const char *GetMetadataItem(const char *pszName,
302 : const char *pszDomain = "") override;
303 : };
304 :
305 : /************************************************************************/
306 : /* MBTilesBand() */
307 : /************************************************************************/
308 :
309 734 : MBTilesBand::MBTilesBand(MBTilesDataset *poDSIn, int nTileSize)
310 734 : : GDALGPKGMBTilesLikeRasterBand(poDSIn, nTileSize, nTileSize)
311 : {
312 734 : }
313 :
314 : /************************************************************************/
315 : /* utf8decode() */
316 : /************************************************************************/
317 :
318 0 : static unsigned utf8decode(const char *p, const char *end, int *len)
319 : {
320 0 : unsigned char c = *(unsigned char *)p;
321 0 : if (c < 0x80)
322 : {
323 0 : *len = 1;
324 0 : return c;
325 : }
326 0 : else if (c < 0xc2)
327 : {
328 0 : goto FAIL;
329 : }
330 0 : if (p + 1 >= end || (p[1] & 0xc0) != 0x80)
331 0 : goto FAIL;
332 0 : if (c < 0xe0)
333 : {
334 0 : *len = 2;
335 0 : return ((p[0] & 0x1f) << 6) + ((p[1] & 0x3f));
336 : }
337 0 : else if (c == 0xe0)
338 : {
339 0 : if (((unsigned char *)p)[1] < 0xa0)
340 0 : goto FAIL;
341 0 : goto UTF8_3;
342 : }
343 : #if STRICT_RFC3629
344 : else if (c == 0xed)
345 : {
346 : // RFC 3629 says surrogate chars are illegal.
347 : if (((unsigned char *)p)[1] >= 0xa0)
348 : goto FAIL;
349 : goto UTF8_3;
350 : }
351 : else if (c == 0xef)
352 : {
353 : // 0xfffe and 0xffff are also illegal characters
354 : if (((unsigned char *)p)[1] == 0xbf && ((unsigned char *)p)[2] >= 0xbe)
355 : goto FAIL;
356 : goto UTF8_3;
357 : }
358 : #endif
359 0 : else if (c < 0xf0)
360 : {
361 0 : UTF8_3:
362 0 : if (p + 2 >= end || (p[2] & 0xc0) != 0x80)
363 0 : goto FAIL;
364 0 : *len = 3;
365 0 : return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + ((p[2] & 0x3f));
366 : }
367 0 : else if (c == 0xf0)
368 : {
369 0 : if (((unsigned char *)p)[1] < 0x90)
370 0 : goto FAIL;
371 0 : goto UTF8_4;
372 : }
373 0 : else if (c < 0xf4)
374 : {
375 0 : UTF8_4:
376 0 : if (p + 3 >= end || (p[2] & 0xc0) != 0x80 || (p[3] & 0xc0) != 0x80)
377 0 : goto FAIL;
378 0 : *len = 4;
379 : #if STRICT_RFC3629
380 : // RFC 3629 says all codes ending in fffe or ffff are illegal:
381 : if ((p[1] & 0xf) == 0xf && ((unsigned char *)p)[2] == 0xbf &&
382 : ((unsigned char *)p)[3] >= 0xbe)
383 : goto FAIL;
384 : #endif
385 0 : return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) +
386 0 : ((p[2] & 0x3f) << 6) + ((p[3] & 0x3f));
387 : }
388 0 : else if (c == 0xf4)
389 : {
390 0 : if (((unsigned char *)p)[1] > 0x8f)
391 0 : goto FAIL; // after 0x10ffff
392 0 : goto UTF8_4;
393 : }
394 : else
395 : {
396 0 : FAIL:
397 0 : *len = 1;
398 0 : return 0xfffd; // Unicode REPLACEMENT CHARACTER
399 : }
400 : }
401 :
402 : /************************************************************************/
403 : /* HasNonEmptyGrids() */
404 : /************************************************************************/
405 :
406 0 : bool MBTilesDataset::HasNonEmptyGrids()
407 : {
408 : OGRLayerH hSQLLyr;
409 : OGRFeatureH hFeat;
410 :
411 0 : if (poMainDS)
412 0 : return poMainDS->HasNonEmptyGrids();
413 :
414 0 : if (nHasNonEmptyGrids >= 0)
415 0 : return nHasNonEmptyGrids != FALSE;
416 :
417 0 : nHasNonEmptyGrids = false;
418 :
419 0 : if (GDALDatasetGetLayerByName(hDS, "grids") == nullptr)
420 0 : return false;
421 :
422 0 : const char *pszSQL = "SELECT type FROM sqlite_master WHERE name = 'grids'";
423 0 : CPLDebug("MBTILES", "%s", pszSQL);
424 0 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
425 0 : if (hSQLLyr == nullptr)
426 0 : return false;
427 :
428 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
429 0 : if (hFeat == nullptr || !OGR_F_IsFieldSetAndNotNull(hFeat, 0))
430 : {
431 0 : OGR_F_Destroy(hFeat);
432 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
433 0 : return false;
434 : }
435 :
436 0 : bool bGridsIsView = strcmp(OGR_F_GetFieldAsString(hFeat, 0), "view") == 0;
437 :
438 0 : OGR_F_Destroy(hFeat);
439 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
440 :
441 0 : nHasNonEmptyGrids = TRUE;
442 :
443 : /* In the case 'grids' is a view (and a join between the 'map' and
444 : * 'grid_utfgrid' layers */
445 : /* the cost of evaluating a join is very long, even if grid_utfgrid is empty
446 : */
447 : /* so check it is not empty */
448 0 : if (bGridsIsView)
449 : {
450 : OGRLayerH hGridUTFGridLyr;
451 0 : hGridUTFGridLyr = GDALDatasetGetLayerByName(hDS, "grid_utfgrid");
452 0 : if (hGridUTFGridLyr != nullptr)
453 : {
454 0 : OGR_L_ResetReading(hGridUTFGridLyr);
455 0 : hFeat = OGR_L_GetNextFeature(hGridUTFGridLyr);
456 0 : OGR_F_Destroy(hFeat);
457 :
458 0 : nHasNonEmptyGrids = hFeat != nullptr;
459 : }
460 : }
461 :
462 0 : return nHasNonEmptyGrids != FALSE;
463 : }
464 :
465 : /************************************************************************/
466 : /* FindKey() */
467 : /************************************************************************/
468 :
469 0 : char *MBTilesDataset::FindKey(int iPixel, int iLine)
470 : {
471 : int nBlockXSize;
472 : int nBlockYSize;
473 0 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
474 :
475 : // Compute shift between GDAL origin and TileMatrixSet origin
476 : // Caution this is in GeoPackage / WMTS convention ! That is upper-left
477 : // corner
478 : const int nShiftXPixels =
479 0 : (int)floor(0.5 + (m_gt[0] - TMS_ORIGIN_X) / m_gt[1]);
480 : const int nShiftYPixelsFromGPKGOrigin =
481 0 : (int)floor(0.5 + (m_gt[3] - TMS_ORIGIN_Y) / m_gt[5]);
482 :
483 0 : const int iLineFromGPKGOrigin = iLine + nShiftYPixelsFromGPKGOrigin;
484 0 : const int iLineFromMBTilesOrigin =
485 0 : m_nTileMatrixHeight * nBlockYSize - 1 - iLineFromGPKGOrigin;
486 0 : const int iPixelFromMBTilesOrigin = iPixel + nShiftXPixels;
487 :
488 0 : const int nTileColumn = iPixelFromMBTilesOrigin / nBlockXSize;
489 0 : const int nTileRow = iLineFromMBTilesOrigin / nBlockYSize;
490 0 : int nColInTile = iPixelFromMBTilesOrigin % nBlockXSize;
491 0 : int nRowInTile = nBlockYSize - 1 - (iLineFromMBTilesOrigin % nBlockYSize);
492 :
493 0 : char *pszKey = nullptr;
494 :
495 : OGRLayerH hSQLLyr;
496 : OGRFeatureH hFeat;
497 0 : json_object *poGrid = nullptr;
498 : int i;
499 :
500 : /* See https://github.com/mapbox/utfgrid-spec/blob/master/1.0/utfgrid.md */
501 : /* for the explanation of the following process */
502 : const char *pszSQL =
503 0 : CPLSPrintf("SELECT grid FROM grids WHERE "
504 : "zoom_level = %d AND tile_column = %d AND tile_row = %d",
505 : m_nZoomLevel, nTileColumn, nTileRow);
506 0 : CPLDebug("MBTILES", "%s", pszSQL);
507 0 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
508 0 : if (hSQLLyr == nullptr)
509 0 : return nullptr;
510 :
511 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
512 0 : if (hFeat == nullptr || !OGR_F_IsFieldSetAndNotNull(hFeat, 0))
513 : {
514 0 : OGR_F_Destroy(hFeat);
515 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
516 0 : return nullptr;
517 : }
518 :
519 0 : int nDataSize = 0;
520 0 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
521 :
522 0 : int nUncompressedSize = nBlockXSize * nBlockYSize;
523 0 : GByte *pabyUncompressed = (GByte *)VSIMalloc(nUncompressedSize + 1);
524 0 : if (pabyUncompressed == nullptr)
525 : {
526 0 : OGR_F_Destroy(hFeat);
527 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
528 0 : return nullptr;
529 : }
530 :
531 : z_stream sStream;
532 0 : memset(&sStream, 0, sizeof(sStream));
533 0 : if (inflateInit(&sStream) != Z_OK)
534 : {
535 0 : OGR_F_Destroy(hFeat);
536 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
537 0 : CPLFree(pabyUncompressed);
538 0 : return nullptr;
539 : }
540 0 : sStream.next_in = pabyData;
541 0 : sStream.avail_in = nDataSize;
542 0 : sStream.next_out = pabyUncompressed;
543 0 : sStream.avail_out = nUncompressedSize;
544 0 : int nStatus = inflate(&sStream, Z_FINISH);
545 0 : inflateEnd(&sStream);
546 0 : if (nStatus != Z_OK && nStatus != Z_STREAM_END)
547 : {
548 0 : CPLDebug("MBTILES", "Error unzipping grid");
549 0 : nUncompressedSize = 0;
550 0 : pabyUncompressed[nUncompressedSize] = 0;
551 : }
552 : else
553 : {
554 0 : nUncompressedSize -= sStream.avail_out;
555 0 : pabyUncompressed[nUncompressedSize] = 0;
556 : // CPLDebug("MBTILES", "Grid size = %d", nUncompressedSize);
557 : // CPLDebug("MBTILES", "Grid value = %s", (const
558 : // char*)pabyUncompressed);
559 : }
560 :
561 0 : json_object *jsobj = nullptr;
562 :
563 0 : if (nUncompressedSize == 0)
564 : {
565 0 : goto end;
566 : }
567 :
568 0 : if (!OGRJSonParse((const char *)pabyUncompressed, &jsobj, true))
569 : {
570 0 : goto end;
571 : }
572 :
573 0 : if (json_object_is_type(jsobj, json_type_object))
574 : {
575 0 : poGrid = CPL_json_object_object_get(jsobj, "grid");
576 : }
577 0 : if (poGrid != nullptr && json_object_is_type(poGrid, json_type_array))
578 : {
579 : int nFactor;
580 : json_object *poRow;
581 0 : char *pszRow = nullptr;
582 :
583 0 : const int nLines = static_cast<int>(json_object_array_length(poGrid));
584 0 : if (nLines == 0)
585 0 : goto end;
586 :
587 0 : nFactor = nBlockXSize / nLines;
588 0 : nRowInTile /= nFactor;
589 0 : nColInTile /= nFactor;
590 :
591 0 : poRow = json_object_array_get_idx(poGrid, nRowInTile);
592 :
593 : /* Extract line of interest in grid */
594 0 : if (poRow != nullptr && json_object_is_type(poRow, json_type_string))
595 : {
596 0 : pszRow = CPLStrdup(json_object_get_string(poRow));
597 : }
598 :
599 0 : if (pszRow == nullptr)
600 0 : goto end;
601 :
602 : /* Unapply JSON encoding */
603 0 : for (i = 0; pszRow[i] != '\0'; i++)
604 : {
605 0 : unsigned char c = ((GByte *)pszRow)[i];
606 0 : if (c >= 93)
607 0 : c--;
608 0 : if (c >= 35)
609 0 : c--;
610 0 : if (c < 32)
611 : {
612 0 : CPLDebug("MBTILES", "Invalid character at byte %d", i);
613 0 : break;
614 : }
615 0 : c -= 32;
616 0 : ((GByte *)pszRow)[i] = c;
617 : }
618 :
619 0 : if (pszRow[i] == '\0')
620 : {
621 0 : char *pszEnd = pszRow + i;
622 :
623 0 : int iCol = 0;
624 0 : i = 0;
625 0 : int nKey = -1;
626 0 : while (pszRow + i < pszEnd)
627 : {
628 0 : int len = 0;
629 0 : unsigned int res = utf8decode(pszRow + i, pszEnd, &len);
630 :
631 : /* Invalid UTF8 ? */
632 0 : if (res > 127 && len == 1)
633 0 : break;
634 :
635 0 : if (iCol == nColInTile)
636 : {
637 0 : nKey = (int)res;
638 : // CPLDebug("MBTILES", "Key index = %d", nKey);
639 0 : break;
640 : }
641 0 : i += len;
642 0 : iCol++;
643 : }
644 :
645 : /* Find key */
646 0 : json_object *poKeys = CPL_json_object_object_get(jsobj, "keys");
647 0 : if (nKey >= 0 && poKeys != nullptr &&
648 0 : json_object_is_type(poKeys, json_type_array) &&
649 0 : nKey < static_cast<int>(json_object_array_length(poKeys)))
650 : {
651 0 : json_object *poKey = json_object_array_get_idx(poKeys, nKey);
652 0 : if (poKey != nullptr &&
653 0 : json_object_is_type(poKey, json_type_string))
654 : {
655 0 : pszKey = CPLStrdup(json_object_get_string(poKey));
656 : }
657 : }
658 : }
659 :
660 0 : CPLFree(pszRow);
661 : }
662 :
663 0 : end:
664 0 : if (jsobj)
665 0 : json_object_put(jsobj);
666 0 : VSIFree(pabyUncompressed);
667 0 : if (hFeat)
668 0 : OGR_F_Destroy(hFeat);
669 0 : if (hSQLLyr)
670 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
671 :
672 0 : return pszKey;
673 : }
674 :
675 : /************************************************************************/
676 : /* GetMetadataDomainList() */
677 : /************************************************************************/
678 :
679 0 : char **MBTilesBand::GetMetadataDomainList()
680 : {
681 0 : return CSLAddString(GDALPamRasterBand::GetMetadataDomainList(),
682 0 : "LocationInfo");
683 : }
684 :
685 : /************************************************************************/
686 : /* GetMetadataItem() */
687 : /************************************************************************/
688 :
689 42 : const char *MBTilesBand::GetMetadataItem(const char *pszName,
690 : const char *pszDomain)
691 : {
692 42 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
693 :
694 : /* ==================================================================== */
695 : /* LocationInfo handling. */
696 : /* ==================================================================== */
697 42 : if (poGDS->hDS != nullptr && pszDomain != nullptr &&
698 20 : EQUAL(pszDomain, "LocationInfo") &&
699 0 : (STARTS_WITH_CI(pszName, "Pixel_") ||
700 0 : STARTS_WITH_CI(pszName, "GeoPixel_")))
701 : {
702 : int iPixel, iLine;
703 :
704 0 : if (!poGDS->HasNonEmptyGrids())
705 0 : return nullptr;
706 :
707 : /* --------------------------------------------------------------------
708 : */
709 : /* What pixel are we aiming at? */
710 : /* --------------------------------------------------------------------
711 : */
712 0 : if (STARTS_WITH_CI(pszName, "Pixel_"))
713 : {
714 0 : if (sscanf(pszName + 6, "%d_%d", &iPixel, &iLine) != 2)
715 0 : return nullptr;
716 : }
717 0 : else if (STARTS_WITH_CI(pszName, "GeoPixel_"))
718 : {
719 0 : GDALGeoTransform gt;
720 0 : GDALGeoTransform invGT;
721 : double dfGeoX, dfGeoY;
722 :
723 0 : dfGeoX = CPLAtof(pszName + 9);
724 0 : const char *pszUnderscore = strchr(pszName + 9, '_');
725 0 : if (!pszUnderscore)
726 0 : return nullptr;
727 0 : dfGeoY = CPLAtof(pszUnderscore + 1);
728 :
729 0 : if (GetDataset() == nullptr)
730 0 : return nullptr;
731 :
732 0 : if (GetDataset()->GetGeoTransform(gt) != CE_None)
733 0 : return nullptr;
734 :
735 0 : if (!GDALInvGeoTransform(gt.data(), invGT.data()))
736 0 : return nullptr;
737 :
738 0 : iPixel =
739 0 : (int)floor(invGT[0] + invGT[1] * dfGeoX + invGT[2] * dfGeoY);
740 0 : iLine =
741 0 : (int)floor(invGT[3] + invGT[4] * dfGeoX + invGT[5] * dfGeoY);
742 : }
743 : else
744 0 : return nullptr;
745 :
746 0 : if (iPixel < 0 || iLine < 0 || iPixel >= GetXSize() ||
747 0 : iLine >= GetYSize())
748 0 : return nullptr;
749 :
750 0 : char *pszKey = poGDS->FindKey(iPixel, iLine);
751 :
752 0 : if (pszKey != nullptr)
753 : {
754 : // CPLDebug("MBTILES", "Key = %s", pszKey);
755 :
756 0 : osLocationInfo = "<LocationInfo>";
757 0 : osLocationInfo += "<Key>";
758 : char *pszXMLEscaped =
759 0 : CPLEscapeString(pszKey, -1, CPLES_XML_BUT_QUOTES);
760 0 : osLocationInfo += pszXMLEscaped;
761 0 : CPLFree(pszXMLEscaped);
762 0 : osLocationInfo += "</Key>";
763 :
764 0 : if (GDALDatasetGetLayerByName(poGDS->hDS, "grid_data") != nullptr &&
765 0 : strchr(pszKey, '\'') == nullptr)
766 : {
767 : OGRLayerH hSQLLyr;
768 : OGRFeatureH hFeat;
769 :
770 : const char *pszSQL =
771 0 : CPLSPrintf("SELECT key_json FROM keymap WHERE "
772 : "key_name = '%s'",
773 : pszKey);
774 0 : CPLDebug("MBTILES", "%s", pszSQL);
775 : hSQLLyr =
776 0 : GDALDatasetExecuteSQL(poGDS->hDS, pszSQL, nullptr, nullptr);
777 0 : if (hSQLLyr)
778 : {
779 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
780 0 : if (hFeat != nullptr &&
781 0 : OGR_F_IsFieldSetAndNotNull(hFeat, 0))
782 : {
783 0 : const char *pszJSon = OGR_F_GetFieldAsString(hFeat, 0);
784 : // CPLDebug("MBTILES", "JSon = %s", pszJSon);
785 :
786 0 : osLocationInfo += "<JSon>";
787 : #ifdef CPLES_XML_BUT_QUOTES
788 : pszXMLEscaped =
789 0 : CPLEscapeString(pszJSon, -1, CPLES_XML_BUT_QUOTES);
790 : #else
791 : pszXMLEscaped = CPLEscapeString(pszJSon, -1, CPLES_XML);
792 : #endif
793 0 : osLocationInfo += pszXMLEscaped;
794 0 : CPLFree(pszXMLEscaped);
795 0 : osLocationInfo += "</JSon>";
796 : }
797 0 : OGR_F_Destroy(hFeat);
798 : }
799 0 : GDALDatasetReleaseResultSet(poGDS->hDS, hSQLLyr);
800 : }
801 :
802 0 : osLocationInfo += "</LocationInfo>";
803 :
804 0 : CPLFree(pszKey);
805 :
806 0 : return osLocationInfo.c_str();
807 : }
808 :
809 0 : return nullptr;
810 : }
811 : else
812 42 : return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
813 : }
814 :
815 : /************************************************************************/
816 : /* GetOverviewCount() */
817 : /************************************************************************/
818 :
819 6 : int MBTilesBand::GetOverviewCount()
820 : {
821 6 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
822 :
823 6 : if (poGDS->m_nOverviewCount >= 1)
824 5 : return poGDS->m_nOverviewCount;
825 : else
826 1 : return GDALPamRasterBand::GetOverviewCount();
827 : }
828 :
829 : /************************************************************************/
830 : /* GetOverview() */
831 : /************************************************************************/
832 :
833 7 : GDALRasterBand *MBTilesBand::GetOverview(int nLevel)
834 : {
835 7 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
836 :
837 7 : if (poGDS->m_nOverviewCount == 0)
838 0 : return GDALPamRasterBand::GetOverview(nLevel);
839 :
840 7 : if (nLevel < 0 || nLevel >= poGDS->m_nOverviewCount)
841 0 : return nullptr;
842 :
843 7 : GDALDataset *poOvrDS = poGDS->m_papoOverviewDS[nLevel];
844 7 : if (poOvrDS)
845 7 : return poOvrDS->GetRasterBand(nBand);
846 : else
847 0 : return nullptr;
848 : }
849 :
850 : /************************************************************************/
851 : /* MBTilesDataset() */
852 : /************************************************************************/
853 :
854 276 : MBTilesDataset::MBTilesDataset()
855 : {
856 276 : m_bWriteBounds = true;
857 276 : m_bWriteMinMaxZoom = true;
858 276 : poMainDS = nullptr;
859 276 : m_nOverviewCount = 0;
860 276 : hDS = nullptr;
861 276 : m_papoOverviewDS = nullptr;
862 276 : bFetchedMetadata = false;
863 276 : nHasNonEmptyGrids = -1;
864 276 : hDB = nullptr;
865 276 : pMyVFS = nullptr;
866 :
867 276 : m_bGeoTransformValid = false;
868 276 : m_bInFlushCache = false;
869 :
870 276 : m_osRasterTable = "tiles";
871 276 : m_eTF = GPKG_TF_PNG;
872 :
873 276 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
874 276 : m_oSRS.importFromEPSG(3857);
875 276 : }
876 :
877 : /************************************************************************/
878 : /* ~MBTilesDataset() */
879 : /************************************************************************/
880 :
881 552 : MBTilesDataset::~MBTilesDataset()
882 : {
883 : // Need to explicitly clear it before close hDS
884 276 : m_apoLayers.clear();
885 :
886 276 : FlushCache(true);
887 :
888 276 : if (poMainDS == nullptr)
889 : {
890 101 : if (m_papoOverviewDS)
891 : {
892 235 : for (int i = 0; i < m_nOverviewCount; i++)
893 175 : delete m_papoOverviewDS[i];
894 60 : CPLFree(m_papoOverviewDS);
895 : }
896 :
897 101 : if (hDS != nullptr)
898 : {
899 60 : GDALClose(hDS);
900 60 : hDB = nullptr;
901 : }
902 101 : if (hDB != nullptr)
903 : {
904 41 : sqlite3_close(hDB);
905 :
906 41 : if (pMyVFS)
907 : {
908 23 : sqlite3_vfs_unregister(pMyVFS);
909 23 : CPLFree(pMyVFS->pAppData);
910 23 : CPLFree(pMyVFS);
911 : }
912 : }
913 : }
914 :
915 276 : if (!m_osMetadataMemFilename.empty())
916 : {
917 32 : VSIUnlink(m_osMetadataMemFilename);
918 : }
919 552 : }
920 :
921 : /************************************************************************/
922 : /* IStartTransaction() */
923 : /************************************************************************/
924 :
925 24 : OGRErr MBTilesDataset::IStartTransaction()
926 : {
927 24 : char *pszErrMsg = nullptr;
928 24 : const int rc = sqlite3_exec(hDB, "BEGIN", nullptr, nullptr, &pszErrMsg);
929 24 : if (rc != SQLITE_OK)
930 : {
931 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
932 : "BEGIN", pszErrMsg);
933 0 : sqlite3_free(pszErrMsg);
934 0 : return OGRERR_FAILURE;
935 : }
936 :
937 24 : return OGRERR_NONE;
938 : }
939 :
940 : /************************************************************************/
941 : /* ICommitTransaction() */
942 : /************************************************************************/
943 :
944 24 : OGRErr MBTilesDataset::ICommitTransaction()
945 : {
946 24 : char *pszErrMsg = nullptr;
947 24 : const int rc = sqlite3_exec(hDB, "COMMIT", nullptr, nullptr, &pszErrMsg);
948 24 : if (rc != SQLITE_OK)
949 : {
950 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
951 : "COMMIT", pszErrMsg);
952 0 : sqlite3_free(pszErrMsg);
953 0 : return OGRERR_FAILURE;
954 : }
955 :
956 24 : return OGRERR_NONE;
957 : }
958 :
959 : /************************************************************************/
960 : /* ICanIWriteBlock() */
961 : /************************************************************************/
962 :
963 155 : bool MBTilesDataset::ICanIWriteBlock()
964 : {
965 155 : if (eAccess != GA_Update)
966 : {
967 0 : CPLError(
968 : CE_Failure, CPLE_NotSupported,
969 : "IWriteBlock() not supported on dataset opened in read-only mode");
970 0 : return false;
971 : }
972 :
973 155 : if (!m_bGeoTransformValid)
974 : {
975 0 : CPLError(CE_Failure, CPLE_NotSupported,
976 : "IWriteBlock() not supported if georeferencing not set");
977 0 : return false;
978 : }
979 155 : return true;
980 : }
981 :
982 : /************************************************************************/
983 : /* IFlushCacheWithErrCode() */
984 : /************************************************************************/
985 :
986 3240 : CPLErr MBTilesDataset::IFlushCacheWithErrCode(bool bAtClosing)
987 :
988 : {
989 3240 : if (m_bInFlushCache)
990 2474 : return CE_None;
991 766 : m_bInFlushCache = true;
992 : // Short circuit GDALPamDataset to avoid serialization to .aux.xml
993 766 : GDALDataset::FlushCache(bAtClosing);
994 :
995 766 : CPLErr eErr = FlushTiles();
996 :
997 766 : m_bInFlushCache = false;
998 766 : return eErr;
999 : }
1000 :
1001 : /************************************************************************/
1002 : /* ICanIWriteBlock() */
1003 : /************************************************************************/
1004 :
1005 546 : int MBTilesDataset::GetRowFromIntoTopConvention(int nRow)
1006 : {
1007 546 : return m_nTileMatrixHeight - 1 - nRow;
1008 : }
1009 :
1010 : /************************************************************************/
1011 : /* GetGeoTransform() */
1012 : /************************************************************************/
1013 :
1014 31 : CPLErr MBTilesDataset::GetGeoTransform(GDALGeoTransform >) const
1015 : {
1016 31 : gt = m_gt;
1017 31 : return (m_bGeoTransformValid) ? CE_None : CE_Failure;
1018 : }
1019 :
1020 : /************************************************************************/
1021 : /* SphericalMercatorToLongLat() */
1022 : /************************************************************************/
1023 :
1024 69 : static void SphericalMercatorToLongLat(double *x, double *y)
1025 : {
1026 69 : double lng = *x / SPHERICAL_RADIUS / M_PI * 180;
1027 69 : double lat = 2 * (atan(exp(*y / SPHERICAL_RADIUS)) - M_PI / 4) / M_PI * 180;
1028 69 : *x = lng;
1029 69 : *y = lat;
1030 69 : }
1031 :
1032 : /************************************************************************/
1033 : /* LongLatToSphericalMercator() */
1034 : /************************************************************************/
1035 :
1036 112 : static void LongLatToSphericalMercator(double *x, double *y)
1037 : {
1038 112 : double X = SPHERICAL_RADIUS * (*x) / 180 * M_PI;
1039 112 : double Y = SPHERICAL_RADIUS * log(tan(M_PI / 4 + 0.5 * (*y) / 180 * M_PI));
1040 112 : *x = X;
1041 112 : *y = Y;
1042 112 : }
1043 :
1044 : /************************************************************************/
1045 : /* SetGeoTransform() */
1046 : /************************************************************************/
1047 :
1048 28 : CPLErr MBTilesDataset::SetGeoTransform(const GDALGeoTransform >)
1049 : {
1050 28 : if (eAccess != GA_Update)
1051 : {
1052 1 : CPLError(CE_Failure, CPLE_NotSupported,
1053 : "SetGeoTransform() not supported on read-only dataset");
1054 1 : return CE_Failure;
1055 : }
1056 27 : if (m_bGeoTransformValid)
1057 : {
1058 1 : CPLError(CE_Failure, CPLE_NotSupported,
1059 : "Cannot modify geotransform once set");
1060 1 : return CE_Failure;
1061 : }
1062 26 : if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
1063 : {
1064 1 : CPLError(CE_Failure, CPLE_NotSupported,
1065 : "Only north-up non rotated geotransform supported");
1066 1 : return CE_Failure;
1067 : }
1068 :
1069 25 : if (m_bWriteBounds)
1070 : {
1071 46 : CPLString osBounds(m_osBounds);
1072 23 : if (osBounds.empty())
1073 : {
1074 23 : double minx = gt[0];
1075 23 : double miny = gt[3] + nRasterYSize * gt[5];
1076 23 : double maxx = gt[0] + nRasterXSize * gt[1];
1077 23 : double maxy = gt[3];
1078 :
1079 23 : SphericalMercatorToLongLat(&minx, &miny);
1080 23 : SphericalMercatorToLongLat(&maxx, &maxy);
1081 23 : if (fabs(minx + 180) < 1e-7)
1082 : {
1083 3 : minx = -180.0;
1084 : }
1085 23 : if (fabs(maxx - 180) < 1e-7)
1086 : {
1087 3 : maxx = 180.0;
1088 : }
1089 :
1090 : // Clamp latitude so that when transformed back to EPSG:3857, we
1091 : // don't have too big northings
1092 23 : double tmpx = 0.0;
1093 23 : double ok_maxy = MAX_GM;
1094 23 : SphericalMercatorToLongLat(&tmpx, &ok_maxy);
1095 23 : if (maxy > ok_maxy)
1096 0 : maxy = ok_maxy;
1097 23 : if (miny < -ok_maxy)
1098 0 : miny = -ok_maxy;
1099 :
1100 23 : osBounds.Printf("%.17g,%.17g,%.17g,%.17g", minx, miny, maxx, maxy);
1101 : }
1102 :
1103 23 : char *pszSQL = sqlite3_mprintf(
1104 : "INSERT INTO metadata (name, value) VALUES ('bounds', '%q')",
1105 : osBounds.c_str());
1106 23 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1107 23 : sqlite3_free(pszSQL);
1108 :
1109 23 : if (!m_osCenter.empty())
1110 : {
1111 0 : pszSQL = sqlite3_mprintf(
1112 : "INSERT INTO metadata (name, value) VALUES ('center', '%q')",
1113 : m_osCenter.c_str());
1114 0 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1115 0 : sqlite3_free(pszSQL);
1116 : }
1117 : }
1118 :
1119 : int nBlockXSize;
1120 : int nBlockYSize;
1121 25 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
1122 25 : const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockXSize;
1123 25 : const double dfPixelYSizeZoomLevel0 = 2 * MAX_GM / nBlockYSize;
1124 181 : for (m_nZoomLevel = 0; m_nZoomLevel < 25; m_nZoomLevel++)
1125 : {
1126 180 : double dfExpectedPixelXSize =
1127 180 : dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
1128 180 : double dfExpectedPixelYSize =
1129 180 : dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
1130 204 : if (fabs(gt[1] - dfExpectedPixelXSize) < 1e-8 * dfExpectedPixelXSize &&
1131 24 : fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
1132 24 : 1e-8 * dfExpectedPixelYSize)
1133 : {
1134 24 : break;
1135 : }
1136 : }
1137 25 : if (m_nZoomLevel == 25)
1138 : {
1139 1 : m_nZoomLevel = -1;
1140 1 : CPLError(CE_Failure, CPLE_NotSupported,
1141 : "Could not find an appropriate zoom level that matches raster "
1142 : "pixel size");
1143 1 : return CE_Failure;
1144 : }
1145 :
1146 24 : m_gt = gt;
1147 24 : m_bGeoTransformValid = true;
1148 :
1149 24 : return FinalizeRasterRegistration();
1150 : }
1151 :
1152 : /************************************************************************/
1153 : /* ComputeTileAndPixelShifts() */
1154 : /************************************************************************/
1155 :
1156 259 : void MBTilesDataset::ComputeTileAndPixelShifts()
1157 : {
1158 : int nTileWidth, nTileHeight;
1159 259 : GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
1160 :
1161 : // Compute shift between GDAL origin and TileMatrixSet origin
1162 : // Caution this is in GeoPackage / WMTS convention ! That is upper-left
1163 : // corner
1164 259 : int nShiftXPixels = (int)floor(0.5 + (m_gt[0] - TMS_ORIGIN_X) / m_gt[1]);
1165 259 : m_nShiftXTiles = (int)floor(1.0 * nShiftXPixels / nTileWidth);
1166 259 : m_nShiftXPixelsMod =
1167 259 : ((nShiftXPixels % nTileWidth) + nTileWidth) % nTileWidth;
1168 259 : int nShiftYPixels = (int)floor(0.5 + (m_gt[3] - TMS_ORIGIN_Y) / m_gt[5]);
1169 259 : m_nShiftYTiles = (int)floor(1.0 * nShiftYPixels / nTileHeight);
1170 259 : m_nShiftYPixelsMod =
1171 259 : ((nShiftYPixels % nTileHeight) + nTileHeight) % nTileHeight;
1172 259 : }
1173 :
1174 : /************************************************************************/
1175 : /* FinalizeRasterRegistration() */
1176 : /************************************************************************/
1177 :
1178 24 : CPLErr MBTilesDataset::FinalizeRasterRegistration()
1179 : {
1180 24 : m_nTileMatrixWidth = (1 << m_nZoomLevel);
1181 24 : m_nTileMatrixHeight = (1 << m_nZoomLevel);
1182 :
1183 24 : ComputeTileAndPixelShifts();
1184 :
1185 24 : double dfGDALMinX = m_gt[0];
1186 24 : double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
1187 24 : double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
1188 24 : double dfGDALMaxY = m_gt[3];
1189 :
1190 24 : m_nOverviewCount = m_nZoomLevel;
1191 48 : m_papoOverviewDS = (MBTilesDataset **)CPLCalloc(sizeof(MBTilesDataset *),
1192 24 : m_nOverviewCount);
1193 :
1194 24 : if (m_bWriteMinMaxZoom)
1195 : {
1196 24 : char *pszSQL = sqlite3_mprintf(
1197 : "INSERT INTO metadata (name, value) VALUES ('minzoom', '%d')",
1198 : m_nZoomLevel);
1199 24 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1200 24 : sqlite3_free(pszSQL);
1201 24 : pszSQL = sqlite3_mprintf(
1202 : "INSERT INTO metadata (name, value) VALUES ('maxzoom', '%d')",
1203 : m_nZoomLevel);
1204 24 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1205 24 : sqlite3_free(pszSQL);
1206 : }
1207 :
1208 155 : for (int i = 0; i < m_nOverviewCount; i++)
1209 : {
1210 131 : MBTilesDataset *poOvrDS = new MBTilesDataset();
1211 131 : poOvrDS->ShareLockWithParentDataset(this);
1212 : int nBlockSize;
1213 131 : GetRasterBand(1)->GetBlockSize(&nBlockSize, &nBlockSize);
1214 131 : poOvrDS->InitRaster(this, i, nBands, nBlockSize, dfGDALMinX, dfGDALMinY,
1215 : dfGDALMaxX, dfGDALMaxY);
1216 :
1217 131 : m_papoOverviewDS[m_nZoomLevel - 1 - i] = poOvrDS;
1218 : }
1219 :
1220 24 : return CE_None;
1221 : }
1222 :
1223 : /************************************************************************/
1224 : /* InitRaster() */
1225 : /************************************************************************/
1226 :
1227 235 : bool MBTilesDataset::InitRaster(MBTilesDataset *poParentDS, int nZoomLevel,
1228 : int nBandCount, int nTileSize,
1229 : double dfGDALMinX, double dfGDALMinY,
1230 : double dfGDALMaxX, double dfGDALMaxY)
1231 : {
1232 235 : m_nZoomLevel = nZoomLevel;
1233 235 : m_nTileMatrixWidth = 1 << nZoomLevel;
1234 235 : m_nTileMatrixHeight = 1 << nZoomLevel;
1235 :
1236 235 : const int nTileWidth = nTileSize;
1237 235 : const int nTileHeight = nTileSize;
1238 235 : const double dfPixelXSize = 2 * MAX_GM / nTileWidth / (1 << nZoomLevel);
1239 235 : const double dfPixelYSize = 2 * MAX_GM / nTileHeight / (1 << nZoomLevel);
1240 :
1241 235 : m_bGeoTransformValid = true;
1242 235 : m_gt[0] = dfGDALMinX;
1243 235 : m_gt[1] = dfPixelXSize;
1244 235 : m_gt[3] = dfGDALMaxY;
1245 235 : m_gt[5] = -dfPixelYSize;
1246 235 : double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
1247 235 : double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
1248 235 : if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
1249 0 : return false;
1250 235 : nRasterXSize = (int)dfRasterXSize;
1251 235 : nRasterYSize = (int)dfRasterYSize;
1252 :
1253 235 : m_pabyCachedTiles =
1254 235 : (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nTileWidth, nTileHeight);
1255 235 : if (m_pabyCachedTiles == nullptr)
1256 : {
1257 0 : return false;
1258 : }
1259 :
1260 235 : if (poParentDS)
1261 : {
1262 175 : eAccess = poParentDS->eAccess;
1263 : }
1264 :
1265 914 : for (int i = 1; i <= nBandCount; i++)
1266 679 : SetBand(i, new MBTilesBand(this, nTileSize));
1267 :
1268 235 : ComputeTileAndPixelShifts();
1269 :
1270 235 : GDALDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
1271 235 : GDALDataset::SetMetadataItem("ZOOM_LEVEL", CPLSPrintf("%d", m_nZoomLevel));
1272 :
1273 235 : if (poParentDS)
1274 : {
1275 175 : m_poParentDS = poParentDS;
1276 175 : poMainDS = poParentDS;
1277 175 : hDS = poParentDS->hDS;
1278 175 : hDB = poParentDS->hDB;
1279 175 : m_eTF = poParentDS->m_eTF;
1280 175 : m_nQuality = poParentDS->m_nQuality;
1281 175 : m_nZLevel = poParentDS->m_nZLevel;
1282 175 : m_bDither = poParentDS->m_bDither;
1283 175 : m_osWHERE = poParentDS->m_osWHERE;
1284 175 : SetDescription(CPLSPrintf("%s - zoom_level=%d",
1285 175 : poParentDS->GetDescription(), m_nZoomLevel));
1286 : }
1287 :
1288 235 : return true;
1289 : }
1290 :
1291 : /************************************************************************/
1292 : /* GetSpatialRef() */
1293 : /************************************************************************/
1294 :
1295 3 : const OGRSpatialReference *MBTilesDataset::GetSpatialRef() const
1296 : {
1297 3 : return &m_oSRS;
1298 : }
1299 :
1300 : /************************************************************************/
1301 : /* SetSpatialRef() */
1302 : /************************************************************************/
1303 :
1304 3 : CPLErr MBTilesDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
1305 : {
1306 3 : if (eAccess != GA_Update)
1307 : {
1308 1 : CPLError(CE_Failure, CPLE_NotSupported,
1309 : "SetSpatialRef() not supported on read-only dataset");
1310 1 : return CE_Failure;
1311 : }
1312 :
1313 2 : if (poSRS == nullptr || poSRS->GetAuthorityName(nullptr) == nullptr ||
1314 1 : !EQUAL(poSRS->GetAuthorityName(nullptr), "EPSG") ||
1315 5 : poSRS->GetAuthorityCode(nullptr) == nullptr ||
1316 1 : !EQUAL(poSRS->GetAuthorityCode(nullptr), "3857"))
1317 : {
1318 1 : CPLError(CE_Failure, CPLE_NotSupported,
1319 : "Only EPSG:3857 supported on MBTiles dataset");
1320 1 : return CE_Failure;
1321 : }
1322 1 : return CE_None;
1323 : }
1324 :
1325 : /************************************************************************/
1326 : /* GetMetadataDomainList() */
1327 : /************************************************************************/
1328 :
1329 0 : char **MBTilesDataset::GetMetadataDomainList()
1330 : {
1331 0 : return BuildMetadataDomainList(GDALDataset::GetMetadataDomainList(), TRUE,
1332 0 : "", nullptr);
1333 : }
1334 :
1335 : /************************************************************************/
1336 : /* GetMetadata() */
1337 : /************************************************************************/
1338 :
1339 104 : char **MBTilesDataset::GetMetadata(const char *pszDomain)
1340 : {
1341 104 : if (hDS == nullptr || (pszDomain != nullptr && !EQUAL(pszDomain, "")))
1342 29 : return GDALPamDataset::GetMetadata(pszDomain);
1343 :
1344 75 : if (bFetchedMetadata)
1345 15 : return aosList.List();
1346 :
1347 60 : bFetchedMetadata = true;
1348 60 : aosList = CPLStringList(GDALPamDataset::GetMetadata(), FALSE);
1349 :
1350 60 : OGRLayerH hSQLLyr = GDALDatasetExecuteSQL(
1351 : hDS, "SELECT name, value FROM metadata WHERE name != 'json' LIMIT 1000",
1352 : nullptr, nullptr);
1353 60 : if (hSQLLyr == nullptr)
1354 0 : return nullptr;
1355 :
1356 60 : if (OGR_FD_GetFieldCount(OGR_L_GetLayerDefn(hSQLLyr)) != 2)
1357 : {
1358 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1359 0 : return nullptr;
1360 : }
1361 :
1362 : OGRFeatureH hFeat;
1363 577 : while ((hFeat = OGR_L_GetNextFeature(hSQLLyr)) != nullptr)
1364 : {
1365 1034 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
1366 517 : OGR_F_IsFieldSetAndNotNull(hFeat, 1))
1367 : {
1368 1034 : CPLString osName = OGR_F_GetFieldAsString(hFeat, 0);
1369 1034 : CPLString osValue = OGR_F_GetFieldAsString(hFeat, 1);
1370 1034 : if (osName[0] != '\0' && !STARTS_WITH(osValue, "function(") &&
1371 517 : strstr(osValue, "<img ") == nullptr &&
1372 517 : strstr(osValue, "<p>") == nullptr &&
1373 1551 : strstr(osValue, "</p>") == nullptr &&
1374 517 : strstr(osValue, "<div") == nullptr)
1375 : {
1376 517 : aosList.AddNameValue(osName, osValue);
1377 : }
1378 : }
1379 517 : OGR_F_Destroy(hFeat);
1380 : }
1381 60 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1382 :
1383 60 : return aosList.List();
1384 : }
1385 :
1386 : /************************************************************************/
1387 : /* GetMetadataItem() */
1388 : /************************************************************************/
1389 :
1390 89 : const char *MBTilesDataset::GetMetadataItem(const char *pszName,
1391 : const char *pszDomain)
1392 : {
1393 89 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
1394 : {
1395 83 : const char *pszValue = CSLFetchNameValue(GetMetadata(), pszName);
1396 83 : if (pszValue)
1397 65 : return pszValue;
1398 : }
1399 24 : return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
1400 : }
1401 :
1402 : /************************************************************************/
1403 : /* GetLayer() */
1404 : /************************************************************************/
1405 :
1406 59 : const OGRLayer *MBTilesDataset::GetLayer(int iLayer) const
1407 :
1408 : {
1409 59 : if (iLayer < 0 || iLayer >= GetLayerCount())
1410 2 : return nullptr;
1411 57 : return m_apoLayers[iLayer].get();
1412 : }
1413 :
1414 : /************************************************************************/
1415 : /* MBTilesVectorLayer() */
1416 : /************************************************************************/
1417 :
1418 37 : MBTilesVectorLayer::MBTilesVectorLayer(
1419 : MBTilesDataset *poDS, const char *pszLayerName,
1420 : const CPLJSONObject &oFields, const CPLJSONArray &oAttributesFromTileStats,
1421 : bool bJsonField, double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
1422 37 : OGRwkbGeometryType eGeomType, bool bZoomLevelFromSpatialFilter)
1423 37 : : m_poDS(poDS), m_poFeatureDefn(new OGRFeatureDefn(pszLayerName)),
1424 74 : m_bJsonField(bJsonField)
1425 : {
1426 37 : SetDescription(pszLayerName);
1427 37 : m_poFeatureDefn->SetGeomType(eGeomType);
1428 37 : OGRSpatialReference *poSRS = new OGRSpatialReference();
1429 37 : poSRS->SetFromUserInput(SRS_EPSG_3857);
1430 37 : m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
1431 37 : poSRS->Release();
1432 37 : m_poFeatureDefn->Reference();
1433 :
1434 37 : if (m_bJsonField)
1435 : {
1436 2 : OGRFieldDefn oFieldDefnId("mvt_id", OFTInteger64);
1437 1 : m_poFeatureDefn->AddFieldDefn(&oFieldDefnId);
1438 : }
1439 : else
1440 : {
1441 36 : OGRMVTInitFields(m_poFeatureDefn, oFields, oAttributesFromTileStats);
1442 : }
1443 :
1444 37 : m_sExtent.MinX = dfMinX;
1445 37 : m_sExtent.MinY = dfMinY;
1446 37 : m_sExtent.MaxX = dfMaxX;
1447 37 : m_sExtent.MaxY = dfMaxY;
1448 :
1449 37 : m_nZoomLevel = m_poDS->m_nZoomLevel;
1450 37 : m_bZoomLevelAuto = bZoomLevelFromSpatialFilter;
1451 37 : MBTilesVectorLayer::SetSpatialFilter(nullptr);
1452 :
1453 : // If the metadata contains an empty fields object, this may be a sign
1454 : // that it doesn't know the schema. In that case check if a tile has
1455 : // attributes, and in that case create a json field.
1456 37 : if (!m_bJsonField && oFields.IsValid() && oFields.GetChildren().empty())
1457 : {
1458 8 : m_bJsonField = true;
1459 8 : OGRFeature *poSrcFeature = GetNextSrcFeature();
1460 8 : m_bJsonField = false;
1461 :
1462 8 : if (poSrcFeature)
1463 : {
1464 : // There is at least the mvt_id field
1465 8 : if (poSrcFeature->GetFieldCount() > 1)
1466 : {
1467 1 : m_bJsonField = true;
1468 : }
1469 8 : delete poSrcFeature;
1470 : }
1471 8 : MBTilesVectorLayer::ResetReading();
1472 : }
1473 :
1474 37 : if (m_bJsonField)
1475 : {
1476 4 : OGRFieldDefn oFieldDefn("json", OFTString);
1477 2 : m_poFeatureDefn->AddFieldDefn(&oFieldDefn);
1478 : }
1479 37 : }
1480 :
1481 : /************************************************************************/
1482 : /* ~MBTilesVectorLayer() */
1483 : /************************************************************************/
1484 :
1485 74 : MBTilesVectorLayer::~MBTilesVectorLayer()
1486 : {
1487 37 : m_poFeatureDefn->Release();
1488 37 : if (m_hTileIteratorLyr)
1489 15 : GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
1490 37 : if (!m_osTmpFilename.empty())
1491 : {
1492 15 : VSIUnlink(m_osTmpFilename);
1493 : }
1494 37 : if (m_hTileDS)
1495 11 : GDALClose(m_hTileDS);
1496 74 : }
1497 :
1498 : /************************************************************************/
1499 : /* TestCapability() */
1500 : /************************************************************************/
1501 :
1502 36 : int MBTilesVectorLayer::TestCapability(const char *pszCap) const
1503 : {
1504 36 : if (EQUAL(pszCap, OLCStringsAsUTF8) ||
1505 24 : EQUAL(pszCap, OLCFastSpatialFilter) || EQUAL(pszCap, OLCFastGetExtent))
1506 : {
1507 14 : return TRUE;
1508 : }
1509 22 : return FALSE;
1510 : }
1511 :
1512 : /************************************************************************/
1513 : /* IGetExtent() */
1514 : /************************************************************************/
1515 :
1516 4 : OGRErr MBTilesVectorLayer::IGetExtent(int /* iGeomField */,
1517 : OGREnvelope *psExtent, bool /* bForce */)
1518 : {
1519 4 : *psExtent = m_sExtent;
1520 4 : return OGRERR_NONE;
1521 : }
1522 :
1523 : /************************************************************************/
1524 : /* ResetReading() */
1525 : /************************************************************************/
1526 :
1527 111 : void MBTilesVectorLayer::ResetReading()
1528 : {
1529 111 : if (m_hTileDS)
1530 46 : GDALClose(m_hTileDS);
1531 111 : m_hTileDS = nullptr;
1532 111 : m_bEOF = false;
1533 111 : if (m_hTileIteratorLyr)
1534 96 : GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
1535 111 : CPLString osSQL;
1536 : osSQL.Printf("SELECT tile_column, tile_row, tile_data FROM tiles "
1537 : "WHERE zoom_level = %d "
1538 : "AND tile_column BETWEEN %d AND %d "
1539 : "AND tile_row BETWEEN %d AND %d",
1540 : m_nZoomLevel, m_nFilterMinX, m_nFilterMaxX, m_nFilterMinY,
1541 111 : m_nFilterMaxY);
1542 111 : m_hTileIteratorLyr =
1543 111 : GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
1544 111 : }
1545 :
1546 : /************************************************************************/
1547 : /* ISetSpatialFilter() */
1548 : /************************************************************************/
1549 :
1550 62 : OGRErr MBTilesVectorLayer::ISetSpatialFilter(int iGeomField,
1551 : const OGRGeometry *poGeomIn)
1552 : {
1553 62 : OGRErr eErr = OGRLayer::ISetSpatialFilter(iGeomField, poGeomIn);
1554 62 : if (eErr == OGRERR_NONE)
1555 : {
1556 62 : if (m_poFilterGeom != nullptr && m_sFilterEnvelope.MinX <= -MAX_GM &&
1557 2 : m_sFilterEnvelope.MinY <= -MAX_GM &&
1558 2 : m_sFilterEnvelope.MaxX >= MAX_GM &&
1559 2 : m_sFilterEnvelope.MaxY >= MAX_GM)
1560 : {
1561 2 : if (m_bZoomLevelAuto)
1562 : {
1563 0 : m_nZoomLevel = m_poDS->m_nMinZoomLevel;
1564 : }
1565 2 : m_nFilterMinX = 0;
1566 2 : m_nFilterMinY = 0;
1567 2 : m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
1568 2 : m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
1569 : }
1570 60 : else if (m_poFilterGeom != nullptr &&
1571 6 : m_sFilterEnvelope.MinX >= -10 * MAX_GM &&
1572 6 : m_sFilterEnvelope.MinY >= -10 * MAX_GM &&
1573 6 : m_sFilterEnvelope.MaxX <= 10 * MAX_GM &&
1574 6 : m_sFilterEnvelope.MaxY <= 10 * MAX_GM)
1575 : {
1576 6 : if (m_bZoomLevelAuto)
1577 : {
1578 : double dfExtent =
1579 0 : std::min(m_sFilterEnvelope.MaxX - m_sFilterEnvelope.MinX,
1580 0 : m_sFilterEnvelope.MaxY - m_sFilterEnvelope.MinY);
1581 0 : m_nZoomLevel = std::max(
1582 0 : m_poDS->m_nMinZoomLevel,
1583 0 : std::min(static_cast<int>(0.5 + log(2 * MAX_GM / dfExtent) /
1584 : log(2.0)),
1585 0 : m_poDS->m_nZoomLevel));
1586 0 : CPLDebug("MBTILES", "Zoom level = %d", m_nZoomLevel);
1587 : }
1588 6 : const double dfTileDim = 2 * MAX_GM / (1 << m_nZoomLevel);
1589 6 : m_nFilterMinX = std::max(
1590 12 : 0, static_cast<int>(
1591 6 : floor((m_sFilterEnvelope.MinX + MAX_GM) / dfTileDim)));
1592 6 : m_nFilterMinY = std::max(
1593 12 : 0, static_cast<int>(
1594 6 : floor((m_sFilterEnvelope.MinY + MAX_GM) / dfTileDim)));
1595 6 : m_nFilterMaxX =
1596 12 : std::min(static_cast<int>(ceil(
1597 6 : (m_sFilterEnvelope.MaxX + MAX_GM) / dfTileDim)),
1598 6 : (1 << m_nZoomLevel) - 1);
1599 6 : m_nFilterMaxY =
1600 12 : std::min(static_cast<int>(ceil(
1601 6 : (m_sFilterEnvelope.MaxY + MAX_GM) / dfTileDim)),
1602 6 : (1 << m_nZoomLevel) - 1);
1603 : }
1604 : else
1605 : {
1606 54 : if (m_bZoomLevelAuto)
1607 : {
1608 0 : m_nZoomLevel = m_poDS->m_nZoomLevel;
1609 : }
1610 54 : m_nFilterMinX = 0;
1611 54 : m_nFilterMinY = 0;
1612 54 : m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
1613 54 : m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
1614 : }
1615 : }
1616 62 : return eErr;
1617 : }
1618 :
1619 : /************************************************************************/
1620 : /* GetNextFeature() */
1621 : /************************************************************************/
1622 :
1623 159 : OGRFeature *MBTilesVectorLayer::GetNextFeature()
1624 : {
1625 : while (true)
1626 : {
1627 159 : OGRFeature *poFeature = GetNextRawFeature();
1628 159 : if (poFeature == nullptr)
1629 32 : return nullptr;
1630 :
1631 296 : if ((m_poFilterGeom == nullptr ||
1632 241 : FilterGeometry(poFeature->GetGeometryRef())) &&
1633 114 : (m_poAttrQuery == nullptr || m_poAttrQuery->Evaluate(poFeature)))
1634 : {
1635 86 : return poFeature;
1636 : }
1637 :
1638 41 : delete poFeature;
1639 41 : }
1640 : }
1641 :
1642 : /************************************************************************/
1643 : /* GetFeatureCount() */
1644 : /************************************************************************/
1645 :
1646 15 : GIntBig MBTilesVectorLayer::GetFeatureCount(int bForce)
1647 : {
1648 15 : if (m_poFilterGeom == nullptr && m_poAttrQuery == nullptr)
1649 : {
1650 9 : if (m_nFeatureCount < 0)
1651 : {
1652 1 : m_nFeatureCount = 0;
1653 1 : ResetReading();
1654 5 : while (m_hTileIteratorLyr != nullptr)
1655 : {
1656 5 : OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
1657 5 : if (hFeat == nullptr)
1658 : {
1659 1 : break;
1660 : }
1661 4 : m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
1662 : // MBTiles y origin is bottom based, whereas MVT directory
1663 : // is top based
1664 4 : m_nY =
1665 4 : (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
1666 4 : int nDataSize = 0;
1667 4 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
1668 4 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1669 4 : memcpy(pabyDataDup, pabyData, nDataSize);
1670 4 : OGR_F_Destroy(hFeat);
1671 :
1672 4 : if (!m_osTmpFilename.empty())
1673 : {
1674 3 : VSIUnlink(m_osTmpFilename);
1675 : }
1676 : m_osTmpFilename = VSIMemGenerateHiddenFilename(
1677 4 : CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
1678 4 : VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
1679 : nDataSize, true));
1680 :
1681 4 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1682 4 : if (m_hTileDS)
1683 0 : GDALClose(m_hTileDS);
1684 4 : char **papszOpenOptions = nullptr;
1685 : papszOpenOptions =
1686 4 : CSLSetNameValue(papszOpenOptions, "METADATA_FILE",
1687 4 : m_poDS->m_osMetadataMemFilename.c_str());
1688 4 : m_hTileDS =
1689 4 : GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
1690 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1691 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1692 4 : CSLDestroy(papszOpenOptions);
1693 4 : if (m_hTileDS)
1694 : {
1695 : OGRLayerH hLayer =
1696 4 : GDALDatasetGetLayerByName(m_hTileDS, GetName());
1697 4 : if (hLayer)
1698 : {
1699 4 : m_nFeatureCount += OGR_L_GetFeatureCount(hLayer, true);
1700 : }
1701 4 : GDALClose(m_hTileDS);
1702 4 : m_hTileDS = nullptr;
1703 : }
1704 : }
1705 1 : ResetReading();
1706 : }
1707 9 : return m_nFeatureCount;
1708 : }
1709 6 : return OGRLayer::GetFeatureCount(bForce);
1710 : }
1711 :
1712 : /************************************************************************/
1713 : /* GetNextSrcFeature() */
1714 : /************************************************************************/
1715 :
1716 167 : OGRFeature *MBTilesVectorLayer::GetNextSrcFeature()
1717 : {
1718 167 : if (m_bEOF)
1719 : {
1720 3 : return nullptr;
1721 : }
1722 164 : if (m_hTileIteratorLyr == nullptr)
1723 : {
1724 14 : ResetReading();
1725 14 : if (m_hTileIteratorLyr == nullptr)
1726 : {
1727 0 : return nullptr;
1728 : }
1729 : }
1730 :
1731 164 : OGRFeatureH hTileFeat = nullptr;
1732 271 : if (m_hTileDS == nullptr ||
1733 107 : (hTileFeat = OGR_L_GetNextFeature(
1734 107 : GDALDatasetGetLayerByName(m_hTileDS, GetName()))) == nullptr)
1735 : {
1736 : while (true)
1737 : {
1738 173 : OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
1739 173 : if (hFeat == nullptr)
1740 : {
1741 29 : m_bEOF = true;
1742 29 : return nullptr;
1743 : }
1744 144 : m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
1745 : // MBTiles y origin is bottom based, whereas MVT directory
1746 : // is top based
1747 144 : m_nY = (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
1748 144 : CPLDebug("MBTiles", "X=%d, Y=%d", m_nX, m_nY);
1749 :
1750 144 : int nDataSize = 0;
1751 144 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
1752 144 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1753 144 : memcpy(pabyDataDup, pabyData, nDataSize);
1754 144 : OGR_F_Destroy(hFeat);
1755 :
1756 144 : if (!m_osTmpFilename.empty())
1757 : {
1758 130 : VSIUnlink(m_osTmpFilename);
1759 : }
1760 : m_osTmpFilename = VSIMemGenerateHiddenFilename(
1761 144 : CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
1762 144 : VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
1763 : nDataSize, true));
1764 :
1765 144 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1766 144 : if (m_hTileDS)
1767 75 : GDALClose(m_hTileDS);
1768 144 : char **papszOpenOptions = nullptr;
1769 : papszOpenOptions =
1770 144 : CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", m_nX));
1771 : papszOpenOptions =
1772 144 : CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", m_nY));
1773 144 : papszOpenOptions = CSLSetNameValue(papszOpenOptions, "Z",
1774 : CPLSPrintf("%d", m_nZoomLevel));
1775 144 : papszOpenOptions = CSLSetNameValue(
1776 : papszOpenOptions, "METADATA_FILE",
1777 144 : m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
1778 144 : if (!m_poDS->m_osClip.empty())
1779 : {
1780 : papszOpenOptions =
1781 3 : CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
1782 : }
1783 144 : m_hTileDS =
1784 144 : GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
1785 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1786 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1787 144 : CSLDestroy(papszOpenOptions);
1788 144 : if (m_hTileDS)
1789 : {
1790 144 : if (GDALDatasetGetLayerByName(m_hTileDS, GetName()))
1791 : {
1792 136 : hTileFeat = OGR_L_GetNextFeature(
1793 136 : GDALDatasetGetLayerByName(m_hTileDS, GetName()));
1794 136 : if (hTileFeat)
1795 132 : break;
1796 : }
1797 12 : GDALClose(m_hTileDS);
1798 12 : m_hTileDS = nullptr;
1799 : }
1800 12 : }
1801 : }
1802 :
1803 135 : return reinterpret_cast<OGRFeature *>(hTileFeat);
1804 : }
1805 :
1806 : /************************************************************************/
1807 : /* CreateFeatureFrom() */
1808 : /************************************************************************/
1809 :
1810 : OGRFeature *
1811 129 : MBTilesVectorLayer::CreateFeatureFrom(OGRFeature *poSrcFeature) const
1812 : {
1813 :
1814 129 : return OGRMVTCreateFeatureFrom(poSrcFeature, m_poFeatureDefn, m_bJsonField,
1815 258 : GetSpatialRef());
1816 : }
1817 :
1818 : /************************************************************************/
1819 : /* GetNextRawFeature() */
1820 : /************************************************************************/
1821 :
1822 159 : OGRFeature *MBTilesVectorLayer::GetNextRawFeature()
1823 : {
1824 159 : OGRFeature *poSrcFeat = GetNextSrcFeature();
1825 159 : if (poSrcFeat == nullptr)
1826 32 : return nullptr;
1827 :
1828 127 : const GIntBig nFIDBase =
1829 127 : (static_cast<GIntBig>(m_nY) << m_nZoomLevel) | m_nX;
1830 127 : OGRFeature *poFeature = CreateFeatureFrom(poSrcFeat);
1831 127 : poFeature->SetFID((poSrcFeat->GetFID() << (2 * m_nZoomLevel)) | nFIDBase);
1832 127 : delete poSrcFeat;
1833 :
1834 127 : return poFeature;
1835 : }
1836 :
1837 : /************************************************************************/
1838 : /* GetFeature() */
1839 : /************************************************************************/
1840 :
1841 5 : OGRFeature *MBTilesVectorLayer::GetFeature(GIntBig nFID)
1842 : {
1843 5 : const int nZ = m_nZoomLevel;
1844 5 : const int nX = static_cast<int>(nFID & ((1 << nZ) - 1));
1845 5 : const int nY = static_cast<int>((nFID >> nZ) & ((1 << nZ) - 1));
1846 5 : const GIntBig nTileFID = nFID >> (2 * nZ);
1847 :
1848 10 : CPLString osSQL;
1849 : osSQL.Printf("SELECT tile_data FROM tiles "
1850 : "WHERE zoom_level = %d AND "
1851 : "tile_column = %d AND tile_row = %d",
1852 5 : m_nZoomLevel, nX, (1 << nZ) - 1 - nY);
1853 : auto hSQLLyr =
1854 5 : GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
1855 5 : if (hSQLLyr == nullptr)
1856 0 : return nullptr;
1857 5 : auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
1858 5 : if (hFeat == nullptr)
1859 : {
1860 0 : GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
1861 0 : return nullptr;
1862 : }
1863 5 : int nDataSize = 0;
1864 5 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
1865 5 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1866 5 : memcpy(pabyDataDup, pabyData, nDataSize);
1867 5 : OGR_F_Destroy(hFeat);
1868 5 : GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
1869 :
1870 : const CPLString osTmpFilename = VSIMemGenerateHiddenFilename(
1871 5 : CPLSPrintf("mvt_get_feature_%d_%d.pbf", m_nX, m_nY));
1872 5 : VSIFCloseL(
1873 : VSIFileFromMemBuffer(osTmpFilename, pabyDataDup, nDataSize, true));
1874 :
1875 5 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1876 5 : char **papszOpenOptions = nullptr;
1877 : papszOpenOptions =
1878 5 : CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", nX));
1879 : papszOpenOptions =
1880 5 : CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", nY));
1881 : papszOpenOptions =
1882 5 : CSLSetNameValue(papszOpenOptions, "Z", CPLSPrintf("%d", m_nZoomLevel));
1883 5 : papszOpenOptions = CSLSetNameValue(
1884 : papszOpenOptions, "METADATA_FILE",
1885 5 : m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
1886 5 : if (!m_poDS->m_osClip.empty())
1887 : {
1888 : papszOpenOptions =
1889 0 : CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
1890 : }
1891 5 : auto hTileDS = GDALOpenEx(("MVT:" + osTmpFilename).c_str(),
1892 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1893 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1894 5 : CSLDestroy(papszOpenOptions);
1895 :
1896 5 : OGRFeature *poFeature = nullptr;
1897 5 : if (hTileDS)
1898 : {
1899 5 : OGRLayerH hLayer = GDALDatasetGetLayerByName(hTileDS, GetName());
1900 5 : if (hLayer)
1901 : {
1902 : OGRFeature *poUnderlyingFeature = reinterpret_cast<OGRFeature *>(
1903 5 : OGR_L_GetFeature(hLayer, nTileFID));
1904 5 : if (poUnderlyingFeature)
1905 : {
1906 2 : poFeature = CreateFeatureFrom(poUnderlyingFeature);
1907 2 : poFeature->SetFID(nFID);
1908 : }
1909 5 : delete poUnderlyingFeature;
1910 : }
1911 : }
1912 5 : GDALClose(hTileDS);
1913 :
1914 5 : VSIUnlink(osTmpFilename);
1915 :
1916 5 : return poFeature;
1917 : }
1918 :
1919 : /************************************************************************/
1920 : /* InitVector() */
1921 : /************************************************************************/
1922 :
1923 32 : void MBTilesDataset::InitVector(double dfMinX, double dfMinY, double dfMaxX,
1924 : double dfMaxY, bool bZoomLevelFromSpatialFilter,
1925 : bool bJsonField)
1926 : {
1927 32 : const char *pszSQL = "SELECT value FROM metadata WHERE name = 'json'";
1928 32 : CPLDebug("MBTILES", "%s", pszSQL);
1929 64 : CPLJSONDocument oJsonDoc;
1930 64 : CPLJSONDocument oDoc;
1931 32 : auto hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
1932 32 : if (hSQLLyr)
1933 : {
1934 32 : auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
1935 32 : if (hFeat)
1936 : {
1937 32 : auto pszJson = OGR_F_GetFieldAsString(hFeat, 0);
1938 32 : oDoc.GetRoot().Add("json", pszJson);
1939 32 : CPL_IGNORE_RET_VAL(
1940 32 : oJsonDoc.LoadMemory(reinterpret_cast<const GByte *>(pszJson)));
1941 32 : OGR_F_Destroy(hFeat);
1942 : }
1943 32 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1944 : }
1945 :
1946 : m_osMetadataMemFilename =
1947 32 : VSIMemGenerateHiddenFilename("mbtiles_metadata.json");
1948 32 : oDoc.Save(m_osMetadataMemFilename);
1949 :
1950 64 : CPLJSONArray oVectorLayers;
1951 32 : oVectorLayers.Deinit();
1952 :
1953 64 : CPLJSONArray oTileStatLayers;
1954 32 : oTileStatLayers.Deinit();
1955 :
1956 32 : oVectorLayers = oJsonDoc.GetRoot().GetArray("vector_layers");
1957 :
1958 32 : oTileStatLayers = oJsonDoc.GetRoot().GetArray("tilestats/layers");
1959 :
1960 69 : for (int i = 0; i < oVectorLayers.Size(); i++)
1961 : {
1962 111 : CPLJSONObject oId = oVectorLayers[i].GetObj("id");
1963 37 : if (oId.IsValid() && oId.GetType() == CPLJSONObject::Type::String)
1964 : {
1965 37 : OGRwkbGeometryType eGeomType = wkbUnknown;
1966 37 : if (oTileStatLayers.IsValid())
1967 : {
1968 36 : eGeomType = OGRMVTFindGeomTypeFromTileStat(
1969 72 : oTileStatLayers, oId.ToString().c_str());
1970 : }
1971 :
1972 111 : CPLJSONObject oFields = oVectorLayers[i].GetObj("fields");
1973 : CPLJSONArray oAttributesFromTileStats =
1974 : OGRMVTFindAttributesFromTileStat(oTileStatLayers,
1975 74 : oId.ToString().c_str());
1976 37 : m_apoLayers.push_back(
1977 74 : std::unique_ptr<OGRLayer>(new MBTilesVectorLayer(
1978 74 : this, oId.ToString().c_str(), oFields,
1979 : oAttributesFromTileStats, bJsonField, dfMinX, dfMinY,
1980 37 : dfMaxX, dfMaxY, eGeomType, bZoomLevelFromSpatialFilter)));
1981 : }
1982 : }
1983 32 : }
1984 :
1985 : /************************************************************************/
1986 : /* Identify() */
1987 : /************************************************************************/
1988 :
1989 69574 : int MBTilesDataset::Identify(GDALOpenInfo *poOpenInfo)
1990 : {
1991 : #ifdef ENABLE_SQL_SQLITE_FORMAT
1992 69574 : if (poOpenInfo->pabyHeader &&
1993 12568 : STARTS_WITH((const char *)poOpenInfo->pabyHeader, "-- SQL MBTILES"))
1994 : {
1995 2 : return TRUE;
1996 : }
1997 : #endif
1998 :
1999 69572 : if ((poOpenInfo->IsExtensionEqualToCI("MBTILES") ||
2000 : // Allow direct Amazon S3 signed URLs that contains .mbtiles in the
2001 : // middle of the URL
2002 69292 : strstr(poOpenInfo->pszFilename, ".mbtiles") != nullptr) &&
2003 139016 : poOpenInfo->nHeaderBytes >= 1024 && poOpenInfo->pabyHeader &&
2004 153 : STARTS_WITH_CI((const char *)poOpenInfo->pabyHeader, "SQLite Format 3"))
2005 : {
2006 153 : return TRUE;
2007 : }
2008 :
2009 69418 : return FALSE;
2010 : }
2011 :
2012 : /************************************************************************/
2013 : /* MBTilesGetMinMaxZoomLevel() */
2014 : /************************************************************************/
2015 :
2016 77 : static int MBTilesGetMinMaxZoomLevel(GDALDatasetH hDS, int bHasMap,
2017 : int &nMinLevel, int &nMaxLevel)
2018 : {
2019 : OGRLayerH hSQLLyr;
2020 : OGRFeatureH hFeat;
2021 77 : int bHasMinMaxLevel = FALSE;
2022 :
2023 77 : const char *pszSQL =
2024 : "SELECT value FROM metadata WHERE name = 'minzoom' UNION ALL "
2025 : "SELECT value FROM metadata WHERE name = 'maxzoom'";
2026 77 : CPLDebug("MBTILES", "%s", pszSQL);
2027 77 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2028 77 : if (hSQLLyr)
2029 : {
2030 77 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2031 77 : if (hFeat)
2032 : {
2033 73 : int bHasMinLevel = FALSE;
2034 73 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
2035 : {
2036 73 : nMinLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
2037 73 : bHasMinLevel = TRUE;
2038 : }
2039 73 : OGR_F_Destroy(hFeat);
2040 :
2041 73 : if (bHasMinLevel)
2042 : {
2043 73 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2044 73 : if (hFeat)
2045 : {
2046 73 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
2047 : {
2048 73 : nMaxLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
2049 73 : bHasMinMaxLevel = TRUE;
2050 : }
2051 73 : OGR_F_Destroy(hFeat);
2052 : }
2053 : }
2054 : }
2055 :
2056 77 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2057 : }
2058 :
2059 77 : if (!bHasMinMaxLevel)
2060 : {
2061 : #define OPTIMIZED_FOR_VSICURL
2062 : #ifdef OPTIMIZED_FOR_VSICURL
2063 : int iLevel;
2064 40 : for (iLevel = 0; nMinLevel < 0 && iLevel <= 32; iLevel++)
2065 : {
2066 36 : pszSQL = CPLSPrintf(
2067 : "SELECT zoom_level FROM %s WHERE zoom_level = %d LIMIT 1",
2068 : (bHasMap) ? "map" : "tiles", iLevel);
2069 36 : CPLDebug("MBTILES", "%s", pszSQL);
2070 36 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2071 36 : if (hSQLLyr)
2072 : {
2073 36 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2074 36 : if (hFeat)
2075 : {
2076 3 : nMinLevel = iLevel;
2077 3 : OGR_F_Destroy(hFeat);
2078 : }
2079 36 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2080 : }
2081 : }
2082 :
2083 4 : if (nMinLevel < 0)
2084 1 : return FALSE;
2085 :
2086 99 : for (iLevel = 32; nMaxLevel < 0 && iLevel >= nMinLevel; iLevel--)
2087 : {
2088 96 : pszSQL = CPLSPrintf(
2089 : "SELECT zoom_level FROM %s WHERE zoom_level = %d LIMIT 1",
2090 : (bHasMap) ? "map" : "tiles", iLevel);
2091 96 : CPLDebug("MBTILES", "%s", pszSQL);
2092 96 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2093 96 : if (hSQLLyr)
2094 : {
2095 96 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2096 96 : if (hFeat)
2097 : {
2098 3 : nMaxLevel = iLevel;
2099 3 : bHasMinMaxLevel = TRUE;
2100 3 : OGR_F_Destroy(hFeat);
2101 : }
2102 96 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2103 : }
2104 : }
2105 : #else
2106 : pszSQL = "SELECT min(zoom_level), max(zoom_level) FROM tiles";
2107 : CPLDebug("MBTILES", "%s", pszSQL);
2108 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, NULL, nullptr);
2109 : if (hSQLLyr == NULL)
2110 : {
2111 : return FALSE;
2112 : }
2113 :
2114 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2115 : if (hFeat == NULL)
2116 : {
2117 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2118 : return FALSE;
2119 : }
2120 :
2121 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
2122 : OGR_F_IsFieldSetAndNotNull(hFeat, 1))
2123 : {
2124 : nMinLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
2125 : nMaxLevel = OGR_F_GetFieldAsInteger(hFeat, 1);
2126 : bHasMinMaxLevel = TRUE;
2127 : }
2128 :
2129 : OGR_F_Destroy(hFeat);
2130 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2131 : #endif
2132 : }
2133 :
2134 76 : return bHasMinMaxLevel;
2135 : }
2136 :
2137 : /************************************************************************/
2138 : /* MBTilesTileCoordToWorldCoord() */
2139 : /************************************************************************/
2140 :
2141 16 : static double MBTilesTileCoordToWorldCoord(double dfTileCoord, int nZoomLevel)
2142 : {
2143 16 : return -MAX_GM + 2 * MAX_GM * (dfTileCoord / (1 << nZoomLevel));
2144 : }
2145 :
2146 : /************************************************************************/
2147 : /* MBTilesWorldCoordToTileCoord() */
2148 : /************************************************************************/
2149 :
2150 240 : static double MBTilesWorldCoordToTileCoord(double dfWorldCoord, int nZoomLevel)
2151 : {
2152 240 : return (dfWorldCoord + MAX_GM) / (2 * MAX_GM) * (1 << nZoomLevel);
2153 : }
2154 :
2155 : /************************************************************************/
2156 : /* MBTilesGetBounds() */
2157 : /************************************************************************/
2158 :
2159 76 : static bool MBTilesGetBounds(GDALDatasetH hDS, bool bUseBounds, int nMaxLevel,
2160 : double &minX, double &minY, double &maxX,
2161 : double &maxY)
2162 : {
2163 76 : bool bHasBounds = false;
2164 : OGRLayerH hSQLLyr;
2165 : OGRFeatureH hFeat;
2166 :
2167 76 : if (bUseBounds)
2168 : {
2169 75 : const char *pszSQL = "SELECT value FROM metadata WHERE name = 'bounds'";
2170 75 : CPLDebug("MBTILES", "%s", pszSQL);
2171 75 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2172 75 : if (hSQLLyr)
2173 : {
2174 75 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2175 75 : if (hFeat != nullptr)
2176 : {
2177 73 : const char *pszBounds = OGR_F_GetFieldAsString(hFeat, 0);
2178 73 : char **papszTokens = CSLTokenizeString2(pszBounds, ",", 0);
2179 73 : if (CSLCount(papszTokens) != 4 ||
2180 72 : fabs(CPLAtof(papszTokens[0])) > 180 ||
2181 56 : fabs(CPLAtof(papszTokens[1])) >= 89.99 ||
2182 56 : fabs(CPLAtof(papszTokens[2])) > 180 ||
2183 56 : fabs(CPLAtof(papszTokens[3])) >= 89.99 ||
2184 201 : CPLAtof(papszTokens[0]) > CPLAtof(papszTokens[2]) ||
2185 56 : CPLAtof(papszTokens[1]) > CPLAtof(papszTokens[3]))
2186 : {
2187 17 : CPLError(CE_Warning, CPLE_AppDefined,
2188 : "Invalid value for 'bounds' metadata. Ignoring it "
2189 : "and fall back to present tile extent");
2190 : }
2191 : else
2192 : {
2193 56 : minX = CPLAtof(papszTokens[0]);
2194 56 : minY = CPLAtof(papszTokens[1]);
2195 56 : maxX = CPLAtof(papszTokens[2]);
2196 56 : maxY = CPLAtof(papszTokens[3]);
2197 56 : LongLatToSphericalMercator(&minX, &minY);
2198 56 : LongLatToSphericalMercator(&maxX, &maxY);
2199 :
2200 : // Clamp northings
2201 56 : if (maxY > MAX_GM)
2202 0 : maxY = MAX_GM;
2203 56 : if (minY < -MAX_GM)
2204 8 : minY = -MAX_GM;
2205 :
2206 56 : bHasBounds = true;
2207 : }
2208 :
2209 73 : CSLDestroy(papszTokens);
2210 :
2211 73 : OGR_F_Destroy(hFeat);
2212 : }
2213 75 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2214 : }
2215 : }
2216 :
2217 76 : if (!bHasBounds)
2218 : {
2219 : const char *pszSQL =
2220 20 : CPLSPrintf("SELECT min(tile_column), max(tile_column), "
2221 : "min(tile_row), max(tile_row) FROM tiles "
2222 : "WHERE zoom_level = %d",
2223 : nMaxLevel);
2224 20 : CPLDebug("MBTILES", "%s", pszSQL);
2225 20 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2226 20 : if (hSQLLyr == nullptr)
2227 : {
2228 0 : return false;
2229 : }
2230 :
2231 20 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2232 20 : if (hFeat == nullptr)
2233 : {
2234 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2235 0 : return false;
2236 : }
2237 :
2238 20 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
2239 4 : OGR_F_IsFieldSetAndNotNull(hFeat, 1) &&
2240 28 : OGR_F_IsFieldSetAndNotNull(hFeat, 2) &&
2241 4 : OGR_F_IsFieldSetAndNotNull(hFeat, 3))
2242 : {
2243 4 : int nMinTileCol = OGR_F_GetFieldAsInteger(hFeat, 0);
2244 4 : int nMaxTileCol = OGR_F_GetFieldAsInteger(hFeat, 1);
2245 4 : int nMinTileRow = OGR_F_GetFieldAsInteger(hFeat, 2);
2246 4 : int nMaxTileRow = OGR_F_GetFieldAsInteger(hFeat, 3);
2247 4 : if (nMaxTileCol < INT_MAX && nMaxTileRow < INT_MAX)
2248 : {
2249 4 : minX = MBTilesTileCoordToWorldCoord(nMinTileCol, nMaxLevel);
2250 4 : minY = MBTilesTileCoordToWorldCoord(nMinTileRow, nMaxLevel);
2251 4 : maxX = MBTilesTileCoordToWorldCoord(nMaxTileCol + 1, nMaxLevel);
2252 4 : maxY = MBTilesTileCoordToWorldCoord(nMaxTileRow + 1, nMaxLevel);
2253 4 : bHasBounds = true;
2254 : }
2255 : }
2256 :
2257 20 : OGR_F_Destroy(hFeat);
2258 20 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2259 : }
2260 :
2261 76 : return bHasBounds;
2262 : }
2263 :
2264 : /************************************************************************/
2265 : /* MBTilesCurlReadCbk() */
2266 : /************************************************************************/
2267 :
2268 : typedef struct
2269 : {
2270 : int nBands;
2271 : int nSize;
2272 : } TileProperties;
2273 :
2274 : /* We spy the data received by CURL for the initial request where we try */
2275 : /* to get a first tile to see its characteristics. We just need the header */
2276 : /* to determine that, so let's make VSICurl stop reading after we have found it
2277 : */
2278 :
2279 1 : static int MBTilesCurlReadCbk(CPL_UNUSED VSILFILE *fp, void *pabyBuffer,
2280 : size_t nBufferSize, void *pfnUserData)
2281 : {
2282 1 : TileProperties *psTP = static_cast<TileProperties *>(pfnUserData);
2283 :
2284 1 : const GByte abyPNGSig[] = {0x89, 0x50, 0x4E, 0x47,
2285 : 0x0D, 0x0A, 0x1A, 0x0A, /* PNG signature */
2286 : 0x00, 0x00, 0x00, 0x0D, /* IHDR length */
2287 : 0x49, 0x48, 0x44, 0x52 /* IHDR chunk */};
2288 :
2289 : /* JPEG SOF0 (Start Of Frame 0) marker */
2290 1 : const GByte abyJPEG1CompSig[] = {0xFF, 0xC0, /* marker */
2291 : 0x00, 0x0B, /* data length = 8 + 1 * 3 */
2292 : 0x08, /* depth : 8 bit */};
2293 1 : const GByte abyJPEG3CompSig[] = {0xFF, 0xC0, /* marker */
2294 : 0x00, 0x11, /* data length = 8 + 3 * 3 */
2295 : 0x08, /* depth : 8 bit */};
2296 :
2297 : int i;
2298 16369 : for (i = 0; i < (int)nBufferSize - (int)sizeof(abyPNGSig); i++)
2299 : {
2300 16368 : if (memcmp(((GByte *)pabyBuffer) + i, abyPNGSig, sizeof(abyPNGSig)) ==
2301 0 : 0 &&
2302 0 : i + sizeof(abyPNGSig) + 4 + 4 + 1 + 1 < nBufferSize)
2303 : {
2304 0 : GByte *ptr = ((GByte *)(pabyBuffer)) + i + (int)sizeof(abyPNGSig);
2305 :
2306 : int nWidth;
2307 0 : memcpy(&nWidth, ptr, 4);
2308 0 : CPL_MSBPTR32(&nWidth);
2309 0 : ptr += 4;
2310 :
2311 : int nHeight;
2312 0 : memcpy(&nHeight, ptr, 4);
2313 0 : CPL_MSBPTR32(&nHeight);
2314 0 : ptr += 4;
2315 :
2316 0 : GByte nDepth = *ptr;
2317 0 : ptr += 1;
2318 :
2319 0 : GByte nColorType = *ptr;
2320 0 : CPLDebug("MBTILES",
2321 : "PNG: nWidth=%d nHeight=%d depth=%d nColorType=%d", nWidth,
2322 : nHeight, nDepth, nColorType);
2323 :
2324 0 : psTP->nBands = -2;
2325 0 : psTP->nSize = nWidth;
2326 0 : if (nWidth == nHeight && nDepth == 8)
2327 : {
2328 0 : if (nColorType == 0)
2329 0 : psTP->nBands = 1; /* Gray */
2330 0 : else if (nColorType == 2)
2331 0 : psTP->nBands = 3; /* RGB */
2332 0 : else if (nColorType == 3)
2333 : {
2334 : /* This might also be a color table with transparency */
2335 : /* but we cannot tell ! */
2336 0 : psTP->nBands = -1;
2337 0 : return TRUE;
2338 : }
2339 0 : else if (nColorType == 4)
2340 0 : psTP->nBands = 2; /* Gray + alpha */
2341 0 : else if (nColorType == 6)
2342 0 : psTP->nBands = 4; /* RGB + alpha */
2343 : }
2344 :
2345 0 : return FALSE;
2346 : }
2347 : }
2348 :
2349 16375 : for (i = 0; i < (int)nBufferSize - ((int)sizeof(abyJPEG1CompSig) + 5); i++)
2350 : {
2351 16374 : if (memcmp(((GByte *)pabyBuffer) + i, abyJPEG1CompSig,
2352 0 : sizeof(abyJPEG1CompSig)) == 0 &&
2353 0 : ((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig) + 4] == 1)
2354 : {
2355 : GUInt16 nWidth;
2356 0 : memcpy(&nWidth, &(((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig)]),
2357 : 2);
2358 0 : CPL_MSBPTR16(&nWidth);
2359 : GUInt16 nHeight;
2360 0 : memcpy(&nHeight,
2361 0 : &(((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig) + 2]), 2);
2362 0 : CPL_MSBPTR16(&nHeight);
2363 :
2364 0 : CPLDebug("MBTILES", "JPEG: nWidth=%d nHeight=%d depth=%d nBands=%d",
2365 : nWidth, nHeight, 8, 1);
2366 :
2367 0 : psTP->nBands = -2;
2368 0 : if (nWidth == nHeight)
2369 : {
2370 0 : psTP->nSize = nWidth;
2371 0 : psTP->nBands = 1;
2372 : }
2373 :
2374 0 : return FALSE;
2375 : }
2376 16374 : else if (memcmp(((GByte *)pabyBuffer) + i, abyJPEG3CompSig,
2377 3 : sizeof(abyJPEG3CompSig)) == 0 &&
2378 3 : ((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig) + 4] == 3)
2379 : {
2380 : GUInt16 nWidth;
2381 0 : memcpy(&nWidth, &(((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig)]),
2382 : 2);
2383 0 : CPL_MSBPTR16(&nWidth);
2384 : GUInt16 nHeight;
2385 0 : memcpy(&nHeight,
2386 0 : &(((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig) + 2]), 2);
2387 0 : CPL_MSBPTR16(&nHeight);
2388 :
2389 0 : CPLDebug("MBTILES", "JPEG: nWidth=%d nHeight=%d depth=%d nBands=%d",
2390 : nWidth, nHeight, 8, 3);
2391 :
2392 0 : psTP->nBands = -2;
2393 0 : if (nWidth == nHeight)
2394 : {
2395 0 : psTP->nSize = nWidth;
2396 0 : psTP->nBands = 3;
2397 : }
2398 :
2399 0 : return FALSE;
2400 : }
2401 : }
2402 :
2403 1 : return TRUE;
2404 : }
2405 :
2406 : /************************************************************************/
2407 : /* MBTilesGetBandCountAndTileSize() */
2408 : /************************************************************************/
2409 :
2410 60 : static int MBTilesGetBandCountAndTileSize(bool bIsVSICURL, GDALDatasetH &hDS,
2411 : int nMaxLevel, int nMinTileRow,
2412 : int nMaxTileRow, int nMinTileCol,
2413 : int nMaxTileCol, int &nTileSize)
2414 : {
2415 : OGRLayerH hSQLLyr;
2416 : OGRFeatureH hFeat;
2417 60 : VSILFILE *fpCURLOGR = nullptr;
2418 60 : int bFirstSelect = TRUE;
2419 :
2420 60 : int nBands = -1;
2421 60 : nTileSize = 0;
2422 :
2423 : /* Get the VSILFILE associated with the OGR SQLite DB */
2424 120 : CPLString osDSName(GDALGetDescription(hDS));
2425 60 : if (bIsVSICURL)
2426 : {
2427 3 : auto poDS = dynamic_cast<OGRSQLiteBaseDataSource *>(
2428 6 : GDALDataset::FromHandle(hDS));
2429 3 : CPLAssert(poDS);
2430 3 : if (poDS)
2431 : {
2432 3 : fpCURLOGR = poDS->GetVSILFILE();
2433 : }
2434 : }
2435 :
2436 : const char *pszSQL =
2437 120 : CPLSPrintf("SELECT tile_data FROM tiles WHERE "
2438 : "tile_column = %d AND tile_row = %d AND zoom_level = %d",
2439 60 : nMinTileCol / 2 + nMaxTileCol / 2,
2440 60 : nMinTileRow / 2 + nMaxTileRow / 2, nMaxLevel);
2441 60 : CPLDebug("MBTILES", "%s", pszSQL);
2442 :
2443 60 : if (fpCURLOGR)
2444 : {
2445 : /* Install a spy on the file connection that will intercept */
2446 : /* PNG or JPEG headers, to interrupt their downloading */
2447 : /* once the header is found. Speeds up dataset opening. */
2448 3 : CPLErrorReset();
2449 : TileProperties tp;
2450 3 : tp.nBands = -1;
2451 3 : tp.nSize = 0;
2452 3 : VSICurlInstallReadCbk(fpCURLOGR, MBTilesCurlReadCbk, &tp, TRUE);
2453 3 : nBands = tp.nBands;
2454 3 : nTileSize = tp.nSize;
2455 :
2456 3 : CPLErrorReset();
2457 3 : CPLPushErrorHandler(CPLQuietErrorHandler);
2458 3 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2459 3 : CPLPopErrorHandler();
2460 :
2461 3 : VSICurlUninstallReadCbk(fpCURLOGR);
2462 :
2463 : /* Did the spy intercept something interesting ? */
2464 : // cppcheck-suppress knownConditionTrueFalse
2465 3 : if (nBands != -1)
2466 : {
2467 0 : CPLErrorReset();
2468 :
2469 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2470 0 : hSQLLyr = nullptr;
2471 :
2472 : // Re-open OGR SQLite DB, because with our spy we have simulated an
2473 : // I/O error that SQLite will have difficulties to recover within
2474 : // the existing connection. This will be fast because
2475 : // the /vsicurl/ cache has cached the already read blocks.
2476 0 : GDALClose(hDS);
2477 0 : hDS = MBTILESOpenSQLiteDB(osDSName.c_str(), GA_ReadOnly);
2478 0 : if (hDS == nullptr)
2479 0 : return -1;
2480 :
2481 : /* Unrecognized form of PNG. Error out */
2482 0 : if (nBands <= 0)
2483 0 : return -1;
2484 :
2485 0 : return nBands;
2486 : }
2487 3 : else if (CPLGetLastErrorType() == CE_Failure)
2488 : {
2489 0 : CPLError(CE_Failure, CPLGetLastErrorNo(), "%s",
2490 : CPLGetLastErrorMsg());
2491 : }
2492 : }
2493 : else
2494 : {
2495 57 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2496 : }
2497 :
2498 : while (true)
2499 : {
2500 73 : if (hSQLLyr == nullptr && bFirstSelect)
2501 : {
2502 13 : bFirstSelect = FALSE;
2503 13 : pszSQL = CPLSPrintf("SELECT tile_data FROM tiles WHERE "
2504 : "zoom_level = %d LIMIT 1",
2505 : nMaxLevel);
2506 13 : CPLDebug("MBTILES", "%s", pszSQL);
2507 13 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2508 13 : if (hSQLLyr == nullptr)
2509 0 : return -1;
2510 : }
2511 :
2512 73 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2513 73 : if (hFeat == nullptr)
2514 : {
2515 18 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2516 18 : hSQLLyr = nullptr;
2517 18 : if (!bFirstSelect)
2518 5 : return -1;
2519 : }
2520 : else
2521 55 : break;
2522 : }
2523 :
2524 110 : const CPLString osMemFileName(VSIMemGenerateHiddenFilename("mvt_temp.db"));
2525 :
2526 55 : int nDataSize = 0;
2527 55 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
2528 :
2529 55 : VSIFCloseL(VSIFileFromMemBuffer(osMemFileName.c_str(), pabyData, nDataSize,
2530 : FALSE));
2531 :
2532 55 : GDALDatasetH hDSTile = GDALOpenEx(osMemFileName.c_str(), GDAL_OF_RASTER,
2533 : apszAllowedDrivers, nullptr, nullptr);
2534 55 : if (hDSTile == nullptr)
2535 : {
2536 28 : VSIUnlink(osMemFileName.c_str());
2537 28 : OGR_F_Destroy(hFeat);
2538 28 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2539 28 : return -1;
2540 : }
2541 :
2542 27 : nBands = GDALGetRasterCount(hDSTile);
2543 :
2544 14 : if ((nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4) ||
2545 68 : GDALGetRasterXSize(hDSTile) != GDALGetRasterYSize(hDSTile) ||
2546 27 : GDALGetRasterDataType(GDALGetRasterBand(hDSTile, 1)) != GDT_Byte)
2547 : {
2548 0 : CPLError(CE_Failure, CPLE_NotSupported,
2549 : "Unsupported tile characteristics");
2550 0 : GDALClose(hDSTile);
2551 0 : VSIUnlink(osMemFileName.c_str());
2552 0 : OGR_F_Destroy(hFeat);
2553 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2554 0 : return -1;
2555 : }
2556 :
2557 27 : nTileSize = GDALGetRasterXSize(hDSTile);
2558 : GDALColorTableH hCT =
2559 27 : GDALGetRasterColorTable(GDALGetRasterBand(hDSTile, 1));
2560 27 : if (nBands == 1 && hCT != nullptr)
2561 : {
2562 8 : nBands = 3;
2563 8 : if (GDALGetColorEntryCount(hCT) > 0)
2564 : {
2565 : /* Typical of paletted PNG with transparency */
2566 8 : const GDALColorEntry *psEntry = GDALGetColorEntry(hCT, 0);
2567 8 : if (psEntry->c4 == 0)
2568 0 : nBands = 4;
2569 : }
2570 : }
2571 :
2572 27 : GDALClose(hDSTile);
2573 27 : VSIUnlink(osMemFileName.c_str());
2574 27 : OGR_F_Destroy(hFeat);
2575 27 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2576 :
2577 27 : return nBands;
2578 : }
2579 :
2580 : /************************************************************************/
2581 : /* Open() */
2582 : /************************************************************************/
2583 :
2584 77 : GDALDataset *MBTilesDataset::Open(GDALOpenInfo *poOpenInfo)
2585 : {
2586 154 : CPLString osFileName;
2587 154 : CPLString osTableName;
2588 :
2589 77 : if (!Identify(poOpenInfo))
2590 0 : return nullptr;
2591 :
2592 77 : if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
2593 52 : (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
2594 15 : (poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) != 0)
2595 : {
2596 0 : return nullptr;
2597 : }
2598 :
2599 : /* -------------------------------------------------------------------- */
2600 : /* Open underlying OGR DB */
2601 : /* -------------------------------------------------------------------- */
2602 :
2603 : GDALDatasetH hDS =
2604 77 : MBTILESOpenSQLiteDB(poOpenInfo->pszFilename, poOpenInfo->eAccess);
2605 :
2606 77 : MBTilesDataset *poDS = nullptr;
2607 :
2608 77 : if (hDS == nullptr)
2609 0 : goto end;
2610 :
2611 : /* -------------------------------------------------------------------- */
2612 : /* Build dataset */
2613 : /* -------------------------------------------------------------------- */
2614 : {
2615 77 : CPLString osMetadataTableName, osRasterTableName;
2616 77 : CPLString osSQL;
2617 : OGRLayerH hMetadataLyr, hRasterLyr;
2618 : OGRFeatureH hFeat;
2619 : int nBands;
2620 77 : OGRLayerH hSQLLyr = nullptr;
2621 77 : int nMinLevel = -1;
2622 77 : int nMaxLevel = -1;
2623 77 : int bHasMinMaxLevel = FALSE;
2624 : int bHasMap;
2625 :
2626 77 : osMetadataTableName = "metadata";
2627 :
2628 : hMetadataLyr =
2629 77 : GDALDatasetGetLayerByName(hDS, osMetadataTableName.c_str());
2630 77 : if (hMetadataLyr == nullptr)
2631 0 : goto end;
2632 :
2633 77 : osRasterTableName += "tiles";
2634 :
2635 77 : hRasterLyr = GDALDatasetGetLayerByName(hDS, osRasterTableName.c_str());
2636 77 : if (hRasterLyr == nullptr)
2637 0 : goto end;
2638 :
2639 77 : bHasMap = GDALDatasetGetLayerByName(hDS, "map") != nullptr;
2640 77 : if (bHasMap)
2641 : {
2642 0 : bHasMap = FALSE;
2643 :
2644 0 : hSQLLyr = GDALDatasetExecuteSQL(
2645 : hDS, "SELECT type FROM sqlite_master WHERE name = 'tiles'",
2646 : nullptr, nullptr);
2647 0 : if (hSQLLyr != nullptr)
2648 : {
2649 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2650 0 : if (hFeat)
2651 : {
2652 0 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
2653 : {
2654 0 : bHasMap = strcmp(OGR_F_GetFieldAsString(hFeat, 0),
2655 0 : "view") == 0;
2656 0 : if (!bHasMap)
2657 : {
2658 0 : CPLDebug("MBTILES", "Weird! 'tiles' is not a view, "
2659 : "but 'map' exists");
2660 : }
2661 : }
2662 0 : OGR_F_Destroy(hFeat);
2663 : }
2664 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2665 : }
2666 : }
2667 :
2668 : /* --------------------------------------------------------------------
2669 : */
2670 : /* Get minimum and maximum zoom levels */
2671 : /* --------------------------------------------------------------------
2672 : */
2673 :
2674 : bHasMinMaxLevel =
2675 77 : MBTilesGetMinMaxZoomLevel(hDS, bHasMap, nMinLevel, nMaxLevel);
2676 :
2677 : const char *pszZoomLevel =
2678 77 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "ZOOM_LEVEL");
2679 77 : if (pszZoomLevel != nullptr)
2680 0 : nMaxLevel = atoi(pszZoomLevel);
2681 :
2682 77 : if (bHasMinMaxLevel && (nMinLevel < 0 || nMinLevel > nMaxLevel))
2683 : {
2684 0 : CPLError(CE_Failure, CPLE_AppDefined,
2685 : "Inconsistent values : min(zoom_level) = %d, "
2686 : "max(zoom_level) = %d",
2687 : nMinLevel, nMaxLevel);
2688 0 : goto end;
2689 : }
2690 :
2691 77 : if (bHasMinMaxLevel && nMaxLevel > 22)
2692 : {
2693 0 : CPLError(CE_Failure, CPLE_NotSupported,
2694 : "zoom_level > 22 not supported");
2695 0 : goto end;
2696 : }
2697 :
2698 77 : if (!bHasMinMaxLevel)
2699 : {
2700 1 : CPLError(CE_Failure, CPLE_AppDefined,
2701 : "Cannot find min and max zoom_level");
2702 1 : goto end;
2703 : }
2704 :
2705 : /* --------------------------------------------------------------------
2706 : */
2707 : /* Get bounds */
2708 : /* --------------------------------------------------------------------
2709 : */
2710 76 : double dfMinX = 0.0;
2711 76 : double dfMinY = 0.0;
2712 76 : double dfMaxX = 0.0;
2713 76 : double dfMaxY = 0.0;
2714 152 : bool bUseBounds = CPLFetchBool(
2715 76 : const_cast<const char **>(poOpenInfo->papszOpenOptions),
2716 : "USE_BOUNDS", true);
2717 : const char *pszMinX =
2718 76 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINX");
2719 : const char *pszMinY =
2720 76 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINY");
2721 : const char *pszMaxX =
2722 76 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXX");
2723 : const char *pszMaxY =
2724 76 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXY");
2725 : bool bHasBounds;
2726 76 : if (pszMinX != nullptr && pszMinY != nullptr && pszMaxX != nullptr &&
2727 : pszMaxY != nullptr)
2728 : {
2729 0 : bHasBounds = true;
2730 : }
2731 : else
2732 : {
2733 76 : bHasBounds = MBTilesGetBounds(hDS, bUseBounds, nMaxLevel, dfMinX,
2734 : dfMinY, dfMaxX, dfMaxY);
2735 : }
2736 76 : if (!bHasBounds)
2737 : {
2738 16 : CPLError(CE_Failure, CPLE_AppDefined,
2739 : "Cannot find min and max tile numbers");
2740 16 : goto end;
2741 : }
2742 60 : if (pszMinX != nullptr)
2743 0 : dfMinX = CPLAtof(pszMinX);
2744 60 : if (pszMinY != nullptr)
2745 0 : dfMinY = CPLAtof(pszMinY);
2746 60 : if (pszMaxX != nullptr)
2747 0 : dfMaxX = CPLAtof(pszMaxX);
2748 60 : if (pszMaxY != nullptr)
2749 0 : dfMaxY = CPLAtof(pszMaxY);
2750 :
2751 : /* --------------------------------------------------------------------
2752 : */
2753 : /* Get number of bands */
2754 : /* --------------------------------------------------------------------
2755 : */
2756 : int nMinTileCol =
2757 60 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinX, nMaxLevel));
2758 : int nMinTileRow =
2759 60 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinY, nMaxLevel));
2760 : int nMaxTileCol =
2761 60 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxX, nMaxLevel));
2762 : int nMaxTileRow =
2763 60 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxY, nMaxLevel));
2764 60 : int nTileSize = 0;
2765 120 : nBands = MBTilesGetBandCountAndTileSize(
2766 60 : STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"), hDS,
2767 : nMaxLevel, nMinTileRow, nMaxTileRow, nMinTileCol, nMaxTileCol,
2768 : nTileSize);
2769 60 : bool bFoundRasterTile = nBands > 0;
2770 60 : if (!bFoundRasterTile)
2771 33 : nTileSize = knDEFAULT_BLOCK_SIZE;
2772 :
2773 : // Force 4 bands by default (see #6119)
2774 60 : nBands = 4;
2775 :
2776 60 : const char *pszBandCount = CSLFetchNameValueDef(
2777 60 : poOpenInfo->papszOpenOptions, "BAND_COUNT",
2778 : CPLGetConfigOption("MBTILES_BAND_COUNT", nullptr));
2779 60 : if (pszBandCount)
2780 : {
2781 1 : int nTmpBands = atoi(pszBandCount);
2782 1 : if (nTmpBands >= 1 && nTmpBands <= 4)
2783 1 : nBands = nTmpBands;
2784 : }
2785 :
2786 60 : if (poOpenInfo->eAccess == GA_Update)
2787 : {
2788 : // So that we can edit all potential overviews
2789 4 : nMinLevel = 0;
2790 : }
2791 :
2792 : /* --------------------------------------------------------------------
2793 : */
2794 : /* Set dataset attributes */
2795 : /* --------------------------------------------------------------------
2796 : */
2797 :
2798 60 : poDS = new MBTilesDataset();
2799 60 : poDS->eAccess = poOpenInfo->eAccess;
2800 60 : poDS->hDS = hDS;
2801 60 : poDS->hDB = (sqlite3 *)GDALGetInternalHandle((GDALDatasetH)hDS,
2802 : "SQLITE_HANDLE");
2803 60 : CPLAssert(poDS->hDB != nullptr);
2804 :
2805 : /* poDS will release it from now */
2806 60 : hDS = nullptr;
2807 :
2808 : poDS->m_osClip =
2809 60 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CLIP", "");
2810 60 : poDS->m_nMinZoomLevel = nMinLevel;
2811 60 : bool bRasterOK = poDS->InitRaster(nullptr, nMaxLevel, nBands, nTileSize,
2812 : dfMinX, dfMinY, dfMaxX, dfMaxY);
2813 :
2814 60 : const char *pszFormat = poDS->GetMetadataItem("format");
2815 60 : if (pszFormat != nullptr && EQUAL(pszFormat, "pbf"))
2816 : {
2817 33 : if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) == 0)
2818 : {
2819 1 : CPLDebug("MBTiles", "This files contain vector tiles, "
2820 : "but driver open in raster-only mode");
2821 1 : delete poDS;
2822 1 : return nullptr;
2823 : }
2824 64 : poDS->InitVector(dfMinX, dfMinY, dfMaxX, dfMaxY,
2825 32 : CPLFetchBool(poOpenInfo->papszOpenOptions,
2826 : "ZOOM_LEVEL_AUTO",
2827 32 : CPLTestBool(CPLGetConfigOption(
2828 : "MVT_ZOOM_LEVEL_AUTO", "NO"))),
2829 32 : CPLFetchBool(poOpenInfo->papszOpenOptions,
2830 : "JSON_FIELD", false));
2831 : }
2832 27 : else if ((pszFormat != nullptr && !EQUAL(pszFormat, "pbf")) ||
2833 : bFoundRasterTile)
2834 : {
2835 27 : if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0)
2836 : {
2837 1 : CPLDebug("MBTiles", "This files contain raster tiles, "
2838 : "but driver open in vector-only mode");
2839 1 : delete poDS;
2840 1 : return nullptr;
2841 : }
2842 : }
2843 :
2844 58 : if ((pszFormat == nullptr || !EQUAL(pszFormat, "pbf")) && !bRasterOK)
2845 : {
2846 0 : delete poDS;
2847 0 : return nullptr;
2848 : }
2849 :
2850 58 : if (poDS->eAccess == GA_Update)
2851 : {
2852 4 : if (pszFormat != nullptr &&
2853 4 : (EQUAL(pszFormat, "jpg") || EQUAL(pszFormat, "jpeg")))
2854 : {
2855 0 : poDS->m_eTF = GPKG_TF_JPEG;
2856 : }
2857 4 : else if (pszFormat != nullptr && (EQUAL(pszFormat, "webp")))
2858 : {
2859 0 : poDS->m_eTF = GPKG_TF_WEBP;
2860 : }
2861 :
2862 : const char *pszTF =
2863 4 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TILE_FORMAT");
2864 4 : if (pszTF)
2865 : {
2866 0 : poDS->m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
2867 0 : if ((pszFormat != nullptr &&
2868 0 : (EQUAL(pszFormat, "jpg") || EQUAL(pszFormat, "jpeg")) &&
2869 0 : poDS->m_eTF != GPKG_TF_JPEG) ||
2870 0 : (pszFormat != nullptr && EQUAL(pszFormat, "webp") &&
2871 0 : poDS->m_eTF != GPKG_TF_WEBP) ||
2872 0 : (pszFormat != nullptr && EQUAL(pszFormat, "png") &&
2873 0 : poDS->m_eTF == GPKG_TF_JPEG))
2874 : {
2875 0 : CPLError(CE_Warning, CPLE_AppDefined,
2876 : "Format metadata = '%s', but TILE_FORMAT='%s'",
2877 : pszFormat, pszTF);
2878 : }
2879 : }
2880 :
2881 4 : poDS->ParseCompressionOptions(poOpenInfo->papszOpenOptions);
2882 : }
2883 :
2884 : /* --------------------------------------------------------------------
2885 : */
2886 : /* Add overview levels as internal datasets */
2887 : /* --------------------------------------------------------------------
2888 : */
2889 71 : for (int iLevel = nMaxLevel - 1; iLevel >= nMinLevel; iLevel--)
2890 : {
2891 44 : MBTilesDataset *poOvrDS = new MBTilesDataset();
2892 44 : poOvrDS->ShareLockWithParentDataset(poDS);
2893 44 : poOvrDS->InitRaster(poDS, iLevel, nBands, nTileSize, dfMinX, dfMinY,
2894 : dfMaxX, dfMaxY);
2895 :
2896 88 : poDS->m_papoOverviewDS = (MBTilesDataset **)CPLRealloc(
2897 44 : poDS->m_papoOverviewDS,
2898 44 : sizeof(MBTilesDataset *) * (poDS->m_nOverviewCount + 1));
2899 44 : poDS->m_papoOverviewDS[poDS->m_nOverviewCount++] = poOvrDS;
2900 :
2901 75 : if (poOvrDS->GetRasterXSize() < 256 &&
2902 31 : poOvrDS->GetRasterYSize() < 256)
2903 : {
2904 31 : break;
2905 : }
2906 : }
2907 :
2908 : /* --------------------------------------------------------------------
2909 : */
2910 : /* Initialize any PAM information. */
2911 : /* --------------------------------------------------------------------
2912 : */
2913 58 : poDS->SetDescription(poOpenInfo->pszFilename);
2914 :
2915 58 : if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"))
2916 55 : poDS->TryLoadXML();
2917 : else
2918 : {
2919 3 : poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
2920 : }
2921 : }
2922 :
2923 75 : end:
2924 75 : if (hDS)
2925 17 : GDALClose(hDS);
2926 :
2927 75 : return poDS;
2928 : }
2929 :
2930 : /************************************************************************/
2931 : /* Create() */
2932 : /************************************************************************/
2933 :
2934 82 : GDALDataset *MBTilesDataset::Create(const char *pszFilename, int nXSize,
2935 : int nYSize, int nBandsIn, GDALDataType eDT,
2936 : char **papszOptions)
2937 : {
2938 : #ifdef HAVE_MVT_WRITE_SUPPORT
2939 82 : if (nXSize == 0 && nYSize == 0 && nBandsIn == 0 && eDT == GDT_Unknown)
2940 : {
2941 41 : char **papszOptionsMod = CSLDuplicate(papszOptions);
2942 41 : papszOptionsMod = CSLSetNameValue(papszOptionsMod, "FORMAT", "MBTILES");
2943 41 : GDALDataset *poRet = OGRMVTWriterDatasetCreate(
2944 : pszFilename, nXSize, nYSize, nBandsIn, eDT, papszOptionsMod);
2945 41 : CSLDestroy(papszOptionsMod);
2946 41 : return poRet;
2947 : }
2948 : #endif
2949 :
2950 41 : MBTilesDataset *poDS = new MBTilesDataset();
2951 41 : if (!poDS->CreateInternal(pszFilename, nXSize, nYSize, nBandsIn, eDT,
2952 : papszOptions))
2953 : {
2954 13 : delete poDS;
2955 13 : poDS = nullptr;
2956 : }
2957 41 : return poDS;
2958 : }
2959 :
2960 : /************************************************************************/
2961 : /* CreateInternal() */
2962 : /************************************************************************/
2963 :
2964 41 : bool MBTilesDataset::CreateInternal(const char *pszFilename, int nXSize,
2965 : int nYSize, int nBandsIn, GDALDataType eDT,
2966 : char **papszOptions)
2967 : {
2968 41 : if (eDT != GDT_Byte)
2969 : {
2970 0 : CPLError(CE_Failure, CPLE_NotSupported, "Only Byte supported");
2971 0 : return false;
2972 : }
2973 41 : if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 && nBandsIn != 4)
2974 : {
2975 0 : CPLError(CE_Failure, CPLE_NotSupported,
2976 : "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 "
2977 : "(RGBA) band dataset supported");
2978 0 : return false;
2979 : }
2980 :
2981 : // for test/debug purposes only. true is the nominal value
2982 41 : m_bPNGSupports2Bands =
2983 41 : CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_2BANDS", "TRUE"));
2984 41 : m_bPNGSupportsCT =
2985 41 : CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_CT", "TRUE"));
2986 41 : m_bWriteBounds = CPLFetchBool(const_cast<const char **>(papszOptions),
2987 : "WRITE_BOUNDS", true);
2988 41 : m_bWriteMinMaxZoom = CPLFetchBool(const_cast<const char **>(papszOptions),
2989 : "WRITE_MINMAXZOOM", true);
2990 : int nBlockSize = std::max(
2991 41 : 64, std::min(8192, atoi(CSLFetchNameValueDef(
2992 : papszOptions, "BLOCKSIZE",
2993 41 : CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
2994 41 : m_osBounds = CSLFetchNameValueDef(papszOptions, "BOUNDS", "");
2995 41 : m_osCenter = CSLFetchNameValueDef(papszOptions, "CENTER", "");
2996 :
2997 41 : VSIUnlink(pszFilename);
2998 41 : SetDescription(pszFilename);
2999 :
3000 : int rc;
3001 41 : if (STARTS_WITH(pszFilename, "/vsi"))
3002 : {
3003 23 : pMyVFS = OGRSQLiteCreateVFS(nullptr, nullptr);
3004 23 : sqlite3_vfs_register(pMyVFS, 0);
3005 23 : rc = sqlite3_open_v2(pszFilename, &hDB,
3006 : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
3007 23 : pMyVFS->zName);
3008 : }
3009 : else
3010 : {
3011 18 : rc = sqlite3_open(pszFilename, &hDB);
3012 : }
3013 :
3014 41 : if (rc != SQLITE_OK)
3015 : {
3016 3 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s", pszFilename);
3017 3 : return false;
3018 : }
3019 :
3020 38 : sqlite3_exec(hDB, "PRAGMA synchronous = OFF", nullptr, nullptr, nullptr);
3021 :
3022 38 : rc = sqlite3_exec(hDB,
3023 : "CREATE TABLE tiles ("
3024 : "zoom_level INTEGER NOT NULL,"
3025 : "tile_column INTEGER NOT NULL,"
3026 : "tile_row INTEGER NOT NULL,"
3027 : "tile_data BLOB NOT NULL,"
3028 : "UNIQUE (zoom_level, tile_column, tile_row) )",
3029 : nullptr, nullptr, nullptr);
3030 38 : if (rc != SQLITE_OK)
3031 : {
3032 8 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create tiles table");
3033 8 : return false;
3034 : }
3035 :
3036 30 : rc = sqlite3_exec(hDB, "CREATE TABLE metadata (name TEXT, value TEXT)",
3037 : nullptr, nullptr, nullptr);
3038 30 : if (rc != SQLITE_OK)
3039 : {
3040 2 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create metadata table");
3041 2 : return false;
3042 : }
3043 :
3044 : const std::string osName = CSLFetchNameValueDef(
3045 84 : papszOptions, "NAME", CPLGetBasenameSafe(pszFilename).c_str());
3046 28 : char *pszSQL = sqlite3_mprintf(
3047 : "INSERT INTO metadata (name, value) VALUES ('name', '%q')",
3048 : osName.c_str());
3049 28 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3050 28 : sqlite3_free(pszSQL);
3051 :
3052 28 : const char *pszType = CSLFetchNameValueDef(papszOptions, "TYPE", "overlay");
3053 28 : pszSQL = sqlite3_mprintf(
3054 : "INSERT INTO metadata (name, value) VALUES ('type', '%q')", pszType);
3055 28 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3056 28 : sqlite3_free(pszSQL);
3057 :
3058 : const std::string osDescription = CSLFetchNameValueDef(
3059 84 : papszOptions, "DESCRIPTION", CPLGetBasenameSafe(pszFilename).c_str());
3060 28 : pszSQL = sqlite3_mprintf(
3061 : "INSERT INTO metadata (name, value) VALUES ('description', '%q')",
3062 : osDescription.c_str());
3063 28 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3064 28 : sqlite3_free(pszSQL);
3065 :
3066 28 : const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
3067 28 : if (pszTF)
3068 3 : m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
3069 :
3070 28 : const char *pszVersion = CSLFetchNameValueDef(
3071 28 : papszOptions, "VERSION", (m_eTF == GPKG_TF_WEBP) ? "1.3" : "1.1");
3072 28 : pszSQL = sqlite3_mprintf(
3073 : "INSERT INTO metadata (name, value) VALUES ('version', '%q')",
3074 : pszVersion);
3075 28 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3076 28 : sqlite3_free(pszSQL);
3077 :
3078 28 : const char *pszFormat = CSLFetchNameValueDef(
3079 : papszOptions, "FORMAT", GDALMBTilesGetTileFormatName(m_eTF));
3080 28 : pszSQL = sqlite3_mprintf(
3081 : "INSERT INTO metadata (name, value) VALUES ('format', '%q')",
3082 : pszFormat);
3083 28 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3084 28 : sqlite3_free(pszSQL);
3085 :
3086 28 : m_bNew = true;
3087 28 : eAccess = GA_Update;
3088 28 : nRasterXSize = nXSize;
3089 28 : nRasterYSize = nYSize;
3090 :
3091 28 : m_pabyCachedTiles =
3092 28 : (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nBlockSize, nBlockSize);
3093 28 : if (m_pabyCachedTiles == nullptr)
3094 : {
3095 0 : return false;
3096 : }
3097 :
3098 83 : for (int i = 1; i <= nBandsIn; i++)
3099 55 : SetBand(i, new MBTilesBand(this, nBlockSize));
3100 :
3101 28 : ParseCompressionOptions(papszOptions);
3102 :
3103 28 : return true;
3104 : }
3105 :
3106 : /************************************************************************/
3107 : /* CreateCopy() */
3108 : /************************************************************************/
3109 :
3110 : typedef struct
3111 : {
3112 : const char *pszName;
3113 : GDALResampleAlg eResampleAlg;
3114 : } WarpResamplingAlg;
3115 :
3116 : static const WarpResamplingAlg asResamplingAlg[] = {
3117 : {"NEAREST", GRA_NearestNeighbour},
3118 : {"BILINEAR", GRA_Bilinear},
3119 : {"CUBIC", GRA_Cubic},
3120 : {"CUBICSPLINE", GRA_CubicSpline},
3121 : {"LANCZOS", GRA_Lanczos},
3122 : {"MODE", GRA_Mode},
3123 : {"AVERAGE", GRA_Average},
3124 : {"RMS", GRA_RMS},
3125 : };
3126 :
3127 38 : GDALDataset *MBTilesDataset::CreateCopy(const char *pszFilename,
3128 : GDALDataset *poSrcDS, int /*bStrict*/,
3129 : char **papszOptions,
3130 : GDALProgressFunc pfnProgress,
3131 : void *pProgressData)
3132 : {
3133 :
3134 38 : int nBands = poSrcDS->GetRasterCount();
3135 38 : if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
3136 : {
3137 2 : CPLError(CE_Failure, CPLE_NotSupported,
3138 : "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 "
3139 : "(RGBA) band dataset supported");
3140 2 : return nullptr;
3141 : }
3142 :
3143 36 : char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", SRS_EPSG_3857);
3144 :
3145 36 : void *hTransformArg = nullptr;
3146 :
3147 : // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
3148 : // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
3149 : // EPSG:3857.
3150 36 : GDALGeoTransform srcGT;
3151 36 : std::unique_ptr<GDALDataset> poTmpDS;
3152 36 : bool bModifiedMaxLat = false;
3153 36 : bool bModifiedMinLat = false;
3154 36 : const auto poSrcSRS = poSrcDS->GetSpatialRef();
3155 72 : if (poSrcDS->GetGeoTransform(srcGT) == CE_None && srcGT[2] == 0 &&
3156 72 : srcGT[4] == 0 && srcGT[5] < 0)
3157 : {
3158 36 : if (poSrcSRS && poSrcSRS->IsGeographic())
3159 : {
3160 30 : double maxLat = srcGT[3];
3161 30 : double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
3162 : // Corresponds to the latitude of MAX_GM
3163 30 : constexpr double MAX_LAT = 85.0511287798066;
3164 30 : if (maxLat > MAX_LAT)
3165 : {
3166 3 : maxLat = MAX_LAT;
3167 3 : bModifiedMaxLat = true;
3168 : }
3169 30 : if (minLat < -MAX_LAT)
3170 : {
3171 3 : minLat = -MAX_LAT;
3172 3 : bModifiedMinLat = true;
3173 : }
3174 30 : if (bModifiedMaxLat || bModifiedMinLat)
3175 : {
3176 6 : CPLStringList aosOptions;
3177 3 : aosOptions.AddString("-of");
3178 3 : aosOptions.AddString("VRT");
3179 3 : aosOptions.AddString("-projwin");
3180 3 : aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
3181 3 : aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
3182 : aosOptions.AddString(CPLSPrintf(
3183 3 : "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
3184 3 : aosOptions.AddString(CPLSPrintf("%.17g", minLat));
3185 : auto psOptions =
3186 3 : GDALTranslateOptionsNew(aosOptions.List(), nullptr);
3187 3 : poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
3188 : "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
3189 3 : GDALTranslateOptionsFree(psOptions);
3190 3 : if (poTmpDS)
3191 : {
3192 3 : hTransformArg = GDALCreateGenImgProjTransformer2(
3193 3 : GDALDataset::FromHandle(poTmpDS.get()), nullptr,
3194 : papszTO);
3195 : }
3196 : }
3197 : }
3198 : }
3199 36 : if (hTransformArg == nullptr)
3200 : {
3201 : hTransformArg =
3202 33 : GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
3203 : }
3204 36 : if (hTransformArg == nullptr)
3205 : {
3206 0 : CSLDestroy(papszTO);
3207 0 : return nullptr;
3208 : }
3209 :
3210 36 : GDALTransformerInfo *psInfo = (GDALTransformerInfo *)hTransformArg;
3211 36 : GDALGeoTransform gt;
3212 : double adfExtent[4];
3213 : int nXSize, nYSize;
3214 :
3215 36 : if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
3216 : gt.data(), &nXSize, &nYSize, adfExtent,
3217 36 : 0) != CE_None)
3218 : {
3219 0 : CSLDestroy(papszTO);
3220 0 : GDALDestroyGenImgProjTransformer(hTransformArg);
3221 0 : return nullptr;
3222 : }
3223 :
3224 36 : GDALDestroyGenImgProjTransformer(hTransformArg);
3225 36 : hTransformArg = nullptr;
3226 36 : poTmpDS.reset();
3227 :
3228 36 : if (bModifiedMaxLat || bModifiedMinLat)
3229 : {
3230 3 : if (bModifiedMaxLat)
3231 : {
3232 3 : const double maxNorthing = MAX_GM;
3233 3 : gt[3] = maxNorthing;
3234 3 : adfExtent[3] = maxNorthing;
3235 : }
3236 3 : if (bModifiedMinLat)
3237 : {
3238 3 : const double minNorthing = -MAX_GM;
3239 3 : adfExtent[1] = minNorthing;
3240 : }
3241 :
3242 3 : if (poSrcSRS && poSrcSRS->IsGeographic())
3243 : {
3244 3 : if (srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1] == 180)
3245 : {
3246 3 : adfExtent[2] = MAX_GM;
3247 : }
3248 : }
3249 : }
3250 :
3251 : int nZoomLevel;
3252 36 : double dfComputedRes = gt[1];
3253 36 : double dfPrevRes = 0.0;
3254 36 : double dfRes = 0.0;
3255 : int nBlockSize = std::max(
3256 36 : 64, std::min(8192, atoi(CSLFetchNameValueDef(
3257 : papszOptions, "BLOCKSIZE",
3258 36 : CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
3259 36 : const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockSize;
3260 242 : for (nZoomLevel = 0; nZoomLevel < 25; nZoomLevel++)
3261 : {
3262 242 : dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
3263 242 : if (dfComputedRes > dfRes)
3264 36 : break;
3265 206 : dfPrevRes = dfRes;
3266 : }
3267 36 : if (nZoomLevel == 25)
3268 : {
3269 0 : CPLError(CE_Failure, CPLE_AppDefined,
3270 : "Could not find an appropriate zoom level");
3271 0 : CSLDestroy(papszTO);
3272 0 : return nullptr;
3273 : }
3274 :
3275 : const char *pszZoomLevelStrategy =
3276 36 : CSLFetchNameValueDef(papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
3277 36 : if (fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
3278 : {
3279 36 : if (EQUAL(pszZoomLevelStrategy, "LOWER"))
3280 : {
3281 0 : if (nZoomLevel > 0)
3282 0 : nZoomLevel--;
3283 : }
3284 36 : else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
3285 : {
3286 : /* do nothing */
3287 : }
3288 36 : else if (nZoomLevel > 0)
3289 : {
3290 35 : if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
3291 33 : nZoomLevel--;
3292 : }
3293 : }
3294 :
3295 36 : dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
3296 :
3297 36 : double dfMinX = adfExtent[0];
3298 36 : double dfMinY = adfExtent[1];
3299 36 : double dfMaxX = adfExtent[2];
3300 36 : double dfMaxY = adfExtent[3];
3301 :
3302 36 : nXSize = (int)(0.5 + (dfMaxX - dfMinX) / dfRes);
3303 36 : nYSize = (int)(0.5 + (dfMaxY - dfMinY) / dfRes);
3304 36 : gt[1] = dfRes;
3305 36 : gt[5] = -dfRes;
3306 :
3307 36 : int nTargetBands = nBands;
3308 : /* For grey level or RGB, if there's reprojection involved, add an alpha */
3309 : /* channel */
3310 68 : if ((nBands == 1 &&
3311 36 : poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
3312 : nBands == 3)
3313 : {
3314 64 : OGRSpatialReference oSrcSRS;
3315 32 : oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
3316 32 : oSrcSRS.AutoIdentifyEPSG();
3317 39 : if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
3318 7 : atoi(oSrcSRS.GetAuthorityCode(nullptr)) != 3857)
3319 : {
3320 32 : nTargetBands++;
3321 : }
3322 : }
3323 :
3324 36 : GDALResampleAlg eResampleAlg = GRA_Bilinear;
3325 36 : const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
3326 36 : if (pszResampling)
3327 : {
3328 4 : for (size_t iAlg = 0;
3329 4 : iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
3330 : iAlg++)
3331 : {
3332 4 : if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
3333 : {
3334 4 : eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
3335 4 : break;
3336 : }
3337 : }
3338 : }
3339 :
3340 32 : if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
3341 68 : eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
3342 : {
3343 0 : CPLError(
3344 : CE_Warning, CPLE_AppDefined,
3345 : "Input dataset has a color table, which will likely lead to "
3346 : "bad results when using a resampling method other than "
3347 : "nearest neighbour or mode. Converting the dataset to 24/32 bit "
3348 : "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
3349 : }
3350 :
3351 36 : GDALDataset *poDS = Create(pszFilename, nXSize, nYSize, nTargetBands,
3352 : GDT_Byte, papszOptions);
3353 36 : if (poDS == nullptr)
3354 : {
3355 13 : CSLDestroy(papszTO);
3356 13 : return nullptr;
3357 : }
3358 23 : poDS->SetGeoTransform(gt);
3359 25 : if (nTargetBands == 1 && nBands == 1 &&
3360 2 : poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
3361 : {
3362 4 : poDS->GetRasterBand(1)->SetColorTable(
3363 2 : poSrcDS->GetRasterBand(1)->GetColorTable());
3364 : }
3365 :
3366 23 : hTransformArg = GDALCreateGenImgProjTransformer2(poSrcDS, poDS, papszTO);
3367 23 : CSLDestroy(papszTO);
3368 23 : if (hTransformArg == nullptr)
3369 : {
3370 0 : CPLError(CE_Failure, CPLE_AppDefined,
3371 : "GDALCreateGenImgProjTransformer2 failed");
3372 0 : delete poDS;
3373 0 : return nullptr;
3374 : }
3375 :
3376 : /* -------------------------------------------------------------------- */
3377 : /* Warp the transformer with a linear approximator */
3378 : /* -------------------------------------------------------------------- */
3379 23 : hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
3380 : hTransformArg, 0.125);
3381 23 : GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
3382 :
3383 : /* -------------------------------------------------------------------- */
3384 : /* Setup warp options. */
3385 : /* -------------------------------------------------------------------- */
3386 23 : GDALWarpOptions *psWO = GDALCreateWarpOptions();
3387 :
3388 23 : psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
3389 23 : psWO->eWorkingDataType = GDT_Byte;
3390 :
3391 23 : psWO->eResampleAlg = eResampleAlg;
3392 :
3393 23 : psWO->hSrcDS = poSrcDS;
3394 23 : psWO->hDstDS = poDS;
3395 :
3396 23 : psWO->pfnTransformer = GDALApproxTransform;
3397 23 : psWO->pTransformerArg = hTransformArg;
3398 :
3399 23 : psWO->pfnProgress = pfnProgress;
3400 23 : psWO->pProgressArg = pProgressData;
3401 :
3402 : /* -------------------------------------------------------------------- */
3403 : /* Setup band mapping. */
3404 : /* -------------------------------------------------------------------- */
3405 :
3406 23 : if (nBands == 2 || nBands == 4)
3407 2 : psWO->nBandCount = nBands - 1;
3408 : else
3409 21 : psWO->nBandCount = nBands;
3410 :
3411 23 : psWO->panSrcBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
3412 23 : psWO->panDstBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
3413 :
3414 52 : for (int i = 0; i < psWO->nBandCount; i++)
3415 : {
3416 29 : psWO->panSrcBands[i] = i + 1;
3417 29 : psWO->panDstBands[i] = i + 1;
3418 : }
3419 :
3420 23 : if (nBands == 2 || nBands == 4)
3421 : {
3422 2 : psWO->nSrcAlphaBand = nBands;
3423 : }
3424 23 : if (nTargetBands == 2 || nTargetBands == 4)
3425 : {
3426 21 : psWO->nDstAlphaBand = nTargetBands;
3427 : }
3428 :
3429 : /* -------------------------------------------------------------------- */
3430 : /* Initialize and execute the warp. */
3431 : /* -------------------------------------------------------------------- */
3432 23 : GDALWarpOperation oWO;
3433 :
3434 23 : CPLErr eErr = oWO.Initialize(psWO);
3435 23 : if (eErr == CE_None)
3436 : {
3437 : /*if( bMulti )
3438 : eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
3439 : else*/
3440 23 : eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
3441 : }
3442 23 : if (eErr != CE_None)
3443 : {
3444 0 : delete poDS;
3445 0 : poDS = nullptr;
3446 : }
3447 :
3448 23 : GDALDestroyTransformer(hTransformArg);
3449 23 : GDALDestroyWarpOptions(psWO);
3450 :
3451 23 : return poDS;
3452 : }
3453 :
3454 : /************************************************************************/
3455 : /* ParseCompressionOptions() */
3456 : /************************************************************************/
3457 :
3458 32 : void MBTilesDataset::ParseCompressionOptions(char **papszOptions)
3459 : {
3460 32 : const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
3461 32 : if (pszZLevel)
3462 0 : m_nZLevel = atoi(pszZLevel);
3463 :
3464 32 : const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
3465 32 : if (pszQuality)
3466 2 : m_nQuality = atoi(pszQuality);
3467 :
3468 32 : const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
3469 32 : if (pszDither)
3470 1 : m_bDither = CPLTestBool(pszDither);
3471 32 : }
3472 :
3473 : /************************************************************************/
3474 : /* IBuildOverviews() */
3475 : /************************************************************************/
3476 :
3477 4 : static int GetFloorPowerOfTwo(int n)
3478 : {
3479 4 : int p2 = 1;
3480 11 : while ((n = n >> 1) > 0)
3481 : {
3482 7 : p2 <<= 1;
3483 : }
3484 4 : return p2;
3485 : }
3486 :
3487 4 : CPLErr MBTilesDataset::IBuildOverviews(
3488 : const char *pszResampling, int nOverviews, const int *panOverviewList,
3489 : int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
3490 : void *pProgressData, CSLConstList papszOptions)
3491 : {
3492 4 : if (GetAccess() != GA_Update)
3493 : {
3494 0 : CPLError(CE_Failure, CPLE_NotSupported,
3495 : "Overview building not supported on a database opened in "
3496 : "read-only mode");
3497 0 : return CE_Failure;
3498 : }
3499 4 : if (m_poParentDS != nullptr)
3500 : {
3501 0 : CPLError(CE_Failure, CPLE_NotSupported,
3502 : "Overview building not supported on overview dataset");
3503 0 : return CE_Failure;
3504 : }
3505 :
3506 4 : if (nOverviews == 0)
3507 : {
3508 2 : for (int i = 0; i < m_nOverviewCount; i++)
3509 1 : m_papoOverviewDS[i]->FlushCache(false);
3510 1 : char *pszSQL = sqlite3_mprintf(
3511 : "DELETE FROM 'tiles' WHERE zoom_level < %d", m_nZoomLevel);
3512 1 : char *pszErrMsg = nullptr;
3513 1 : int ret = sqlite3_exec(hDB, pszSQL, nullptr, nullptr, &pszErrMsg);
3514 1 : sqlite3_free(pszSQL);
3515 1 : if (ret != SQLITE_OK)
3516 : {
3517 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failure: %s",
3518 0 : pszErrMsg ? pszErrMsg : "");
3519 0 : sqlite3_free(pszErrMsg);
3520 0 : return CE_Failure;
3521 : }
3522 :
3523 1 : int nRows = 0;
3524 1 : int nCols = 0;
3525 1 : char **papszResult = nullptr;
3526 1 : sqlite3_get_table(
3527 : hDB, "SELECT * FROM metadata WHERE name = 'minzoom' LIMIT 2",
3528 : &papszResult, &nRows, &nCols, nullptr);
3529 1 : sqlite3_free_table(papszResult);
3530 1 : if (nRows == 1)
3531 : {
3532 1 : pszSQL = sqlite3_mprintf(
3533 : "UPDATE metadata SET value = %d WHERE name = 'minzoom'",
3534 : m_nZoomLevel);
3535 1 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3536 1 : sqlite3_free(pszSQL);
3537 : }
3538 :
3539 1 : return CE_None;
3540 : }
3541 :
3542 3 : if (nBandsIn != nBands)
3543 : {
3544 0 : CPLError(CE_Failure, CPLE_NotSupported,
3545 : "Generation of overviews only"
3546 : "supported when operating on all bands.");
3547 0 : return CE_Failure;
3548 : }
3549 :
3550 3 : if (m_nOverviewCount == 0)
3551 : {
3552 0 : CPLError(CE_Failure, CPLE_AppDefined,
3553 : "Image too small to support overviews");
3554 0 : return CE_Failure;
3555 : }
3556 :
3557 3 : FlushCache(false);
3558 :
3559 24 : const auto GetOverviewIndex = [](int nVal)
3560 : {
3561 24 : int iOvr = -1;
3562 66 : while (nVal > 1)
3563 : {
3564 42 : nVal >>= 1;
3565 42 : iOvr++;
3566 : }
3567 24 : return iOvr;
3568 : };
3569 :
3570 7 : for (int i = 0; i < nOverviews; i++)
3571 : {
3572 4 : if (panOverviewList[i] < 2)
3573 : {
3574 0 : CPLError(CE_Failure, CPLE_IllegalArg,
3575 0 : "Overview factor '%d' must be >= 2", panOverviewList[i]);
3576 0 : return CE_Failure;
3577 : }
3578 :
3579 4 : if (GetFloorPowerOfTwo(panOverviewList[i]) != panOverviewList[i])
3580 : {
3581 0 : CPLError(CE_Failure, CPLE_IllegalArg,
3582 : "Overview factor '%d' is not a power of 2",
3583 0 : panOverviewList[i]);
3584 0 : return CE_Failure;
3585 : }
3586 4 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3587 4 : if (iOvr >= m_nOverviewCount)
3588 : {
3589 1 : CPLDebug("MBTILES",
3590 : "Requested overview factor %d leads to too small overview "
3591 : "and will be ignored",
3592 1 : panOverviewList[i]);
3593 : }
3594 : }
3595 :
3596 : GDALRasterBand ***papapoOverviewBands =
3597 3 : (GDALRasterBand ***)CPLCalloc(sizeof(void *), nBands);
3598 3 : int iCurOverview = 0;
3599 15 : for (int iBand = 0; iBand < nBands; iBand++)
3600 : {
3601 24 : papapoOverviewBands[iBand] =
3602 12 : (GDALRasterBand **)CPLCalloc(sizeof(void *), nOverviews);
3603 12 : iCurOverview = 0;
3604 28 : for (int i = 0; i < nOverviews; i++)
3605 : {
3606 16 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3607 16 : if (iOvr < m_nOverviewCount)
3608 : {
3609 12 : MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
3610 24 : papapoOverviewBands[iBand][iCurOverview] =
3611 12 : poODS->GetRasterBand(iBand + 1);
3612 12 : iCurOverview++;
3613 : }
3614 : }
3615 : }
3616 :
3617 6 : CPLErr eErr = GDALRegenerateOverviewsMultiBand(
3618 3 : nBands, papoBands, iCurOverview, papapoOverviewBands, pszResampling,
3619 : pfnProgress, pProgressData, papszOptions);
3620 :
3621 15 : for (int iBand = 0; iBand < nBands; iBand++)
3622 : {
3623 12 : CPLFree(papapoOverviewBands[iBand]);
3624 : }
3625 3 : CPLFree(papapoOverviewBands);
3626 :
3627 3 : if (eErr == CE_None)
3628 : {
3629 : // Determine new minzoom value from the existing one and the new
3630 : // requested overview levels
3631 3 : int nMinZoom = m_nZoomLevel;
3632 3 : bool bHasMinZoomMetadata = false;
3633 3 : int nRows = 0;
3634 3 : int nCols = 0;
3635 3 : char **papszResult = nullptr;
3636 3 : sqlite3_get_table(
3637 : hDB, "SELECT value FROM metadata WHERE name = 'minzoom' LIMIT 2",
3638 : &papszResult, &nRows, &nCols, nullptr);
3639 3 : if (nRows == 1 && nCols == 1 && papszResult[1])
3640 : {
3641 3 : bHasMinZoomMetadata = true;
3642 3 : nMinZoom = atoi(papszResult[1]);
3643 : }
3644 3 : sqlite3_free_table(papszResult);
3645 3 : if (bHasMinZoomMetadata)
3646 : {
3647 7 : for (int i = 0; i < nOverviews; i++)
3648 : {
3649 4 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3650 4 : if (iOvr < m_nOverviewCount)
3651 : {
3652 3 : const MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
3653 3 : nMinZoom = std::min(nMinZoom, poODS->m_nZoomLevel);
3654 : }
3655 : }
3656 :
3657 3 : char *pszSQL = sqlite3_mprintf(
3658 : "UPDATE metadata SET value = '%d' WHERE name = 'minzoom'",
3659 : nMinZoom);
3660 3 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3661 3 : sqlite3_free(pszSQL);
3662 : }
3663 : }
3664 :
3665 3 : return eErr;
3666 : }
3667 :
3668 : /************************************************************************/
3669 : /* GDALRegister_MBTiles() */
3670 : /************************************************************************/
3671 :
3672 2024 : void GDALRegister_MBTiles()
3673 :
3674 : {
3675 2024 : if (!GDAL_CHECK_VERSION("MBTiles driver"))
3676 0 : return;
3677 :
3678 2024 : if (GDALGetDriverByName("MBTiles") != nullptr)
3679 283 : return;
3680 :
3681 1741 : GDALDriver *poDriver = new GDALDriver();
3682 :
3683 1741 : poDriver->SetDescription("MBTiles");
3684 1741 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
3685 1741 : poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
3686 1741 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "MBTiles");
3687 1741 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC,
3688 1741 : "drivers/raster/mbtiles.html");
3689 1741 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "mbtiles");
3690 1741 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES, "Byte");
3691 :
3692 : #define COMPRESSION_OPTIONS \
3693 : " <Option name='TILE_FORMAT' scope='raster' type='string-select' " \
3694 : "description='Format to use to create tiles' default='PNG'>" \
3695 : " <Value>PNG</Value>" \
3696 : " <Value>PNG8</Value>" \
3697 : " <Value>JPEG</Value>" \
3698 : " <Value>WEBP</Value>" \
3699 : " </Option>" \
3700 : " <Option name='QUALITY' scope='raster' type='int' min='1' max='100' " \
3701 : "description='Quality for JPEG and WEBP tiles' default='75'/>" \
3702 : " <Option name='ZLEVEL' scope='raster' type='int' min='1' max='9' " \
3703 : "description='DEFLATE compression level for PNG tiles' default='6'/>" \
3704 : " <Option name='DITHER' scope='raster' type='boolean' " \
3705 : "description='Whether to apply Floyd-Steinberg dithering (for " \
3706 : "TILE_FORMAT=PNG8)' default='NO'/>"
3707 :
3708 1741 : poDriver->SetMetadataItem(
3709 : GDAL_DMD_OPENOPTIONLIST,
3710 : "<OpenOptionList>"
3711 : " <Option name='ZOOM_LEVEL' scope='raster,vector' type='integer' "
3712 : "description='Zoom level of full resolution. If not specified, maximum "
3713 : "non-empty zoom level'/>"
3714 : " <Option name='BAND_COUNT' scope='raster' type='string-select' "
3715 : "description='Number of raster bands' default='AUTO'>"
3716 : " <Value>AUTO</Value>"
3717 : " <Value>1</Value>"
3718 : " <Value>2</Value>"
3719 : " <Value>3</Value>"
3720 : " <Value>4</Value>"
3721 : " </Option>"
3722 : " <Option name='MINX' scope='raster,vector' type='float' "
3723 : "description='Minimum X of area of interest'/>"
3724 : " <Option name='MINY' scope='raster,vector' type='float' "
3725 : "description='Minimum Y of area of interest'/>"
3726 : " <Option name='MAXX' scope='raster,vector' type='float' "
3727 : "description='Maximum X of area of interest'/>"
3728 : " <Option name='MAXY' scope='raster,vector' type='float' "
3729 : "description='Maximum Y of area of interest'/>"
3730 : " <Option name='USE_BOUNDS' scope='raster,vector' type='boolean' "
3731 : "description='Whether to use the bounds metadata, when available, to "
3732 : "determine the AOI' default='YES'/>" COMPRESSION_OPTIONS
3733 : " <Option name='CLIP' scope='vector' type='boolean' "
3734 : "description='Whether to clip geometries to tile extent' "
3735 : "default='YES'/>"
3736 : " <Option name='ZOOM_LEVEL_AUTO' scope='vector' type='boolean' "
3737 : "description='Whether to auto-select the zoom level for vector layers "
3738 : "according to spatial filter extent. Only for display purpose' "
3739 : "default='NO'/>"
3740 : " <Option name='JSON_FIELD' scope='vector' type='boolean' "
3741 : "description='For vector layers, "
3742 : "whether to put all attributes as a serialized JSon dictionary'/>"
3743 1741 : "</OpenOptionList>");
3744 :
3745 1741 : poDriver->SetMetadataItem(
3746 : GDAL_DMD_CREATIONOPTIONLIST,
3747 : "<CreationOptionList>"
3748 : " <Option name='NAME' scope='raster,vector' type='string' "
3749 : "description='Tileset name'/>"
3750 : " <Option name='DESCRIPTION' scope='raster,vector' type='string' "
3751 : "description='A description of the layer'/>"
3752 : " <Option name='TYPE' scope='raster,vector' type='string-select' "
3753 : "description='Layer type' default='overlay'>"
3754 : " <Value>overlay</Value>"
3755 : " <Value>baselayer</Value>"
3756 : " </Option>"
3757 : " <Option name='VERSION' scope='raster' type='string' "
3758 : "description='The version of the tileset, as a plain number' "
3759 : "default='1.1'/>"
3760 : " <Option name='BLOCKSIZE' scope='raster' type='int' "
3761 : "description='Block size in pixels' default='256' min='64' "
3762 : "max='8192'/>" COMPRESSION_OPTIONS
3763 : " <Option name='ZOOM_LEVEL_STRATEGY' scope='raster' "
3764 : "type='string-select' description='Strategy to determine zoom level.' "
3765 : "default='AUTO'>"
3766 : " <Value>AUTO</Value>"
3767 : " <Value>LOWER</Value>"
3768 : " <Value>UPPER</Value>"
3769 : " </Option>"
3770 : " <Option name='RESAMPLING' scope='raster' type='string-select' "
3771 : "description='Resampling algorithm.' default='BILINEAR'>"
3772 : " <Value>NEAREST</Value>"
3773 : " <Value>BILINEAR</Value>"
3774 : " <Value>CUBIC</Value>"
3775 : " <Value>CUBICSPLINE</Value>"
3776 : " <Value>LANCZOS</Value>"
3777 : " <Value>MODE</Value>"
3778 : " <Value>AVERAGE</Value>"
3779 : " </Option>"
3780 : " <Option name='WRITE_BOUNDS' scope='raster' type='boolean' "
3781 : "description='Whether to write the bounds metadata' default='YES'/>"
3782 : " <Option name='WRITE_MINMAXZOOM' scope='raster' type='boolean' "
3783 : "description='Whether to write the minzoom and maxzoom metadata' "
3784 : "default='YES'/>"
3785 : " <Option name='BOUNDS' scope='raster,vector' type='string' "
3786 : "description='Override default value for bounds metadata item'/>"
3787 : " <Option name='CENTER' scope='raster,vector' type='string' "
3788 : "description='Override default value for center metadata item'/>"
3789 : #ifdef HAVE_MVT_WRITE_SUPPORT
3790 : MVT_MBTILES_COMMON_DSCO
3791 : #endif
3792 1741 : "</CreationOptionList>");
3793 1741 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
3794 :
3795 : #ifdef HAVE_MVT_WRITE_SUPPORT
3796 1741 : poDriver->SetMetadataItem(GDAL_DCAP_CREATE_FIELD, "YES");
3797 1741 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES,
3798 1741 : "Integer Integer64 Real String");
3799 1741 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATASUBTYPES,
3800 1741 : "Boolean Float32");
3801 :
3802 1741 : poDriver->SetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST, MVT_LCO);
3803 : #endif
3804 :
3805 : #ifdef ENABLE_SQL_SQLITE_FORMAT
3806 1741 : poDriver->SetMetadataItem("ENABLE_SQL_SQLITE_FORMAT", "YES");
3807 : #endif
3808 1741 : poDriver->SetMetadataItem(GDAL_DMD_SUPPORTED_SQL_DIALECTS, "SQLITE OGRSQL");
3809 :
3810 1741 : poDriver->pfnOpen = MBTilesDataset::Open;
3811 1741 : poDriver->pfnIdentify = MBTilesDataset::Identify;
3812 1741 : poDriver->pfnCreateCopy = MBTilesDataset::CreateCopy;
3813 1741 : poDriver->pfnCreate = MBTilesDataset::Create;
3814 :
3815 1741 : GetGDALDriverManager()->RegisterDriver(poDriver);
3816 : }
|