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 : #include "mbtiles.h"
33 :
34 : #include <math.h>
35 : #include <algorithm>
36 : #include <memory>
37 : #include <vector>
38 :
39 : static const char *const apszAllowedDrivers[] = {"JPEG", "PNG", "WEBP",
40 : nullptr};
41 :
42 : #define SRS_EPSG_3857 \
43 : "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS " \
44 : "84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS " \
45 : "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[" \
46 : "\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]" \
47 : ",UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]]," \
48 : "AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[" \
49 : "\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_" \
50 : "easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[" \
51 : "\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION[" \
52 : "\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 " \
53 : "+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext " \
54 : "+no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]"
55 :
56 : #define SPHERICAL_RADIUS 6378137.0
57 : #define MAX_GM (SPHERICAL_RADIUS * M_PI) // 20037508.342789244
58 :
59 : // TileMatrixSet origin : caution this is in GeoPackage / WMTS convention ! That
60 : // is upper-left corner
61 : #define TMS_ORIGIN_X -MAX_GM
62 : #define TMS_ORIGIN_Y MAX_GM
63 :
64 : #if defined(DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) || \
65 : defined(ALLOW_FORMAT_DUMPS)
66 : // Enable accepting a SQL dump (starting with a "-- SQL MBTILES" line) as a
67 : // valid file. This makes fuzzer life easier
68 : #define ENABLE_SQL_SQLITE_FORMAT
69 : #endif
70 :
71 : constexpr int knDEFAULT_BLOCK_SIZE = 256;
72 :
73 : class MBTilesBand;
74 :
75 : /************************************************************************/
76 : /* MBTILESOpenSQLiteDB() */
77 : /************************************************************************/
78 :
79 81 : static GDALDatasetH MBTILESOpenSQLiteDB(const char *pszFilename,
80 : GDALAccess eAccess)
81 : {
82 81 : const char *l_apszAllowedDrivers[] = {"SQLITE", nullptr};
83 162 : return GDALOpenEx((CPLString("SQLITE:") + pszFilename).c_str(),
84 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL |
85 : ((eAccess == GA_Update) ? GDAL_OF_UPDATE : 0),
86 162 : l_apszAllowedDrivers, nullptr, nullptr);
87 : }
88 :
89 : /************************************************************************/
90 : /* ==================================================================== */
91 : /* MBTilesDataset */
92 : /* ==================================================================== */
93 : /************************************************************************/
94 :
95 : class MBTilesDataset final : public GDALPamDataset,
96 : public GDALGPKGMBTilesLikePseudoDataset
97 : {
98 : friend class MBTilesBand;
99 : friend class MBTilesVectorLayer;
100 :
101 : public:
102 : MBTilesDataset();
103 :
104 : ~MBTilesDataset() override;
105 :
106 : CPLErr GetGeoTransform(GDALGeoTransform >) const override;
107 : CPLErr SetGeoTransform(const GDALGeoTransform >) override;
108 : const OGRSpatialReference *GetSpatialRef() const override;
109 : CPLErr SetSpatialRef(const OGRSpatialReference *poSRS) override;
110 :
111 : char **GetMetadataDomainList() override;
112 : CSLConstList GetMetadata(const char *pszDomain = "") override;
113 : virtual const char *GetMetadataItem(const char *pszName,
114 : const char *pszDomain = "") override;
115 :
116 : CPLErr IBuildOverviews(const char *pszResampling, int nOverviews,
117 : const int *panOverviewList, int nBandsIn,
118 : const int * /* panBandList */,
119 : GDALProgressFunc pfnProgress, void *pProgressData,
120 : CSLConstList papszOptions) override;
121 :
122 1956 : int GetLayerCount() const override
123 : {
124 1956 : return static_cast<int>(m_apoLayers.size());
125 : }
126 :
127 : const OGRLayer *GetLayer(int) const override;
128 :
129 : static GDALDataset *Open(GDALOpenInfo *);
130 : static int Identify(GDALOpenInfo *);
131 : static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
132 : int nBandsIn, GDALDataType eDT,
133 : CSLConstList papszOptions);
134 : static GDALDataset *CreateCopy(const char *pszFilename,
135 : GDALDataset *poSrcDS, int bStrict,
136 : CSLConstList papszOptions,
137 : GDALProgressFunc pfnProgress,
138 : void *pProgressData);
139 :
140 : char *FindKey(int iPixel, int iLine);
141 :
142 : bool HasNonEmptyGrids();
143 :
144 : private:
145 : bool m_bWriteBounds;
146 : CPLString m_osBounds;
147 : CPLString m_osCenter;
148 : bool m_bWriteMinMaxZoom;
149 : MBTilesDataset *poMainDS;
150 : bool m_bGeoTransformValid;
151 : GDALGeoTransform m_gt{};
152 : int m_nMinZoomLevel = 0;
153 : OGRSpatialReference m_oSRS{};
154 :
155 : int m_nOverviewCount;
156 : MBTilesDataset **m_papoOverviewDS;
157 :
158 : GDALDatasetH hDS;
159 : sqlite3 *hDB;
160 :
161 : sqlite3_vfs *pMyVFS;
162 :
163 : bool bFetchedMetadata;
164 : CPLStringList aosList;
165 :
166 : int nHasNonEmptyGrids;
167 :
168 : bool m_bInFlushCache;
169 :
170 : CPLString m_osMetadataMemFilename;
171 : CPLString m_osClip;
172 : std::vector<std::unique_ptr<OGRLayer>> m_apoLayers;
173 :
174 : void ParseCompressionOptions(CSLConstList papszOptions);
175 : CPLErr FinalizeRasterRegistration();
176 : void ComputeTileAndPixelShifts();
177 : bool InitRaster(MBTilesDataset *poParentDS, int nZoomLevel, int nBandCount,
178 : int nTileSize, double dfGDALMinX, double dfGDALMinY,
179 : double dfGDALMaxX, double dfGDALMaxY);
180 :
181 : bool CreateInternal(const char *pszFilename, int nXSize, int nYSize,
182 : int nBandsIn, GDALDataType eDT,
183 : CSLConstList papszOptions);
184 : void InitVector(double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
185 : bool bZoomLevelFromSpatialFilter, bool bJsonField);
186 :
187 : protected:
188 : // Coming from GDALGPKGMBTilesLikePseudoDataset
189 :
190 : CPLErr IFlushCacheWithErrCode(bool bAtClosing) override;
191 :
192 2766 : int IGetRasterCount() override
193 : {
194 2766 : return nBands;
195 : }
196 :
197 4763 : GDALRasterBand *IGetRasterBand(int nBand) override
198 : {
199 4763 : return GetRasterBand(nBand);
200 : }
201 :
202 765 : sqlite3 *IGetDB() override
203 : {
204 765 : return hDB;
205 : }
206 :
207 1578 : bool IGetUpdate() override
208 : {
209 1578 : return eAccess == GA_Update;
210 : }
211 :
212 : bool ICanIWriteBlock() override;
213 : OGRErr IStartTransaction() override;
214 : OGRErr ICommitTransaction() override;
215 :
216 32 : const char *IGetFilename() override
217 : {
218 32 : return GetDescription();
219 : }
220 :
221 : int GetRowFromIntoTopConvention(int nRow) override;
222 : };
223 :
224 : /************************************************************************/
225 : /* ==================================================================== */
226 : /* MBTilesVectorLayer */
227 : /* ==================================================================== */
228 : /************************************************************************/
229 :
230 : class MBTilesVectorLayer final : public OGRLayer
231 : {
232 : MBTilesDataset *m_poDS = nullptr;
233 : OGRFeatureDefn *m_poFeatureDefn = nullptr;
234 : OGRLayerH m_hTileIteratorLyr = nullptr;
235 : bool m_bEOF = false;
236 : CPLString m_osTmpFilename;
237 : GDALDatasetH m_hTileDS = nullptr;
238 : GIntBig m_nFeatureCount = -1;
239 : int m_nX = 0;
240 : int m_nY = 0;
241 : OGREnvelope m_sExtent;
242 : int m_nFilterMinX = 0;
243 : int m_nFilterMinY = 0;
244 : int m_nFilterMaxX = 0;
245 : int m_nFilterMaxY = 0;
246 : int m_nZoomLevel = 0;
247 : bool m_bZoomLevelAuto = false;
248 : bool m_bJsonField = false;
249 :
250 : OGRFeature *GetNextRawFeature();
251 : OGRFeature *GetNextSrcFeature();
252 : OGRFeature *CreateFeatureFrom(OGRFeature *poSrcFeature) const;
253 :
254 : public:
255 : MBTilesVectorLayer(MBTilesDataset *poDS, const char *pszLayerName,
256 : const CPLJSONObject &oFields,
257 : const CPLJSONArray &oAttributesFromTileStats,
258 : bool bJsonField, double dfMinX, double dfMinY,
259 : double dfMaxX, double dfMaxY,
260 : OGRwkbGeometryType eGeomType,
261 : bool bZoomLevelFromSpatialFilter);
262 : ~MBTilesVectorLayer() override;
263 :
264 : void ResetReading() override;
265 : OGRFeature *GetNextFeature() override;
266 :
267 751 : const OGRFeatureDefn *GetLayerDefn() const override
268 : {
269 751 : return m_poFeatureDefn;
270 : }
271 :
272 : GIntBig GetFeatureCount(int bForce) override;
273 : int TestCapability(const char *) const override;
274 :
275 : OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
276 : bool bForce) override;
277 :
278 : virtual OGRErr ISetSpatialFilter(int iGeomField,
279 : const OGRGeometry *poGeom) override;
280 :
281 : OGRFeature *GetFeature(GIntBig nFID) override;
282 : };
283 :
284 : /************************************************************************/
285 : /* ==================================================================== */
286 : /* MBTilesBand */
287 : /* ==================================================================== */
288 : /************************************************************************/
289 :
290 : class MBTilesBand final : public GDALGPKGMBTilesLikeRasterBand
291 : {
292 : friend class MBTilesDataset;
293 :
294 : CPLString osLocationInfo;
295 :
296 : public:
297 : explicit MBTilesBand(MBTilesDataset *poDS, int nTileSize);
298 :
299 : int GetOverviewCount() override;
300 : GDALRasterBand *GetOverview(int nLevel) override;
301 :
302 : char **GetMetadataDomainList() override;
303 : virtual const char *GetMetadataItem(const char *pszName,
304 : const char *pszDomain = "") override;
305 : };
306 :
307 : /************************************************************************/
308 : /* MBTilesBand() */
309 : /************************************************************************/
310 :
311 1294 : MBTilesBand::MBTilesBand(MBTilesDataset *poDSIn, int nTileSize)
312 1294 : : GDALGPKGMBTilesLikeRasterBand(poDSIn, nTileSize, nTileSize)
313 : {
314 1294 : }
315 :
316 : /************************************************************************/
317 : /* utf8decode() */
318 : /************************************************************************/
319 :
320 0 : static unsigned utf8decode(const char *p, const char *end, int *len)
321 : {
322 0 : unsigned char c = *(unsigned char *)p;
323 0 : if (c < 0x80)
324 : {
325 0 : *len = 1;
326 0 : return c;
327 : }
328 0 : else if (c < 0xc2)
329 : {
330 0 : goto FAIL;
331 : }
332 0 : if (p + 1 >= end || (p[1] & 0xc0) != 0x80)
333 0 : goto FAIL;
334 0 : if (c < 0xe0)
335 : {
336 0 : *len = 2;
337 0 : return ((p[0] & 0x1f) << 6) + ((p[1] & 0x3f));
338 : }
339 0 : else if (c == 0xe0)
340 : {
341 0 : if (((unsigned char *)p)[1] < 0xa0)
342 0 : goto FAIL;
343 0 : goto UTF8_3;
344 : }
345 : #if STRICT_RFC3629
346 : else if (c == 0xed)
347 : {
348 : // RFC 3629 says surrogate chars are illegal.
349 : if (((unsigned char *)p)[1] >= 0xa0)
350 : goto FAIL;
351 : goto UTF8_3;
352 : }
353 : else if (c == 0xef)
354 : {
355 : // 0xfffe and 0xffff are also illegal characters
356 : if (((unsigned char *)p)[1] == 0xbf && ((unsigned char *)p)[2] >= 0xbe)
357 : goto FAIL;
358 : goto UTF8_3;
359 : }
360 : #endif
361 0 : else if (c < 0xf0)
362 : {
363 0 : UTF8_3:
364 0 : if (p + 2 >= end || (p[2] & 0xc0) != 0x80)
365 0 : goto FAIL;
366 0 : *len = 3;
367 0 : return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + ((p[2] & 0x3f));
368 : }
369 0 : else if (c == 0xf0)
370 : {
371 0 : if (((unsigned char *)p)[1] < 0x90)
372 0 : goto FAIL;
373 0 : goto UTF8_4;
374 : }
375 0 : else if (c < 0xf4)
376 : {
377 0 : UTF8_4:
378 0 : if (p + 3 >= end || (p[2] & 0xc0) != 0x80 || (p[3] & 0xc0) != 0x80)
379 0 : goto FAIL;
380 0 : *len = 4;
381 : #if STRICT_RFC3629
382 : // RFC 3629 says all codes ending in fffe or ffff are illegal:
383 : if ((p[1] & 0xf) == 0xf && ((unsigned char *)p)[2] == 0xbf &&
384 : ((unsigned char *)p)[3] >= 0xbe)
385 : goto FAIL;
386 : #endif
387 0 : return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) +
388 0 : ((p[2] & 0x3f) << 6) + ((p[3] & 0x3f));
389 : }
390 0 : else if (c == 0xf4)
391 : {
392 0 : if (((unsigned char *)p)[1] > 0x8f)
393 0 : goto FAIL; // after 0x10ffff
394 0 : goto UTF8_4;
395 : }
396 : else
397 : {
398 0 : FAIL:
399 0 : *len = 1;
400 0 : return 0xfffd; // Unicode REPLACEMENT CHARACTER
401 : }
402 : }
403 :
404 : /************************************************************************/
405 : /* HasNonEmptyGrids() */
406 : /************************************************************************/
407 :
408 0 : bool MBTilesDataset::HasNonEmptyGrids()
409 : {
410 : OGRLayerH hSQLLyr;
411 : OGRFeatureH hFeat;
412 :
413 0 : if (poMainDS)
414 0 : return poMainDS->HasNonEmptyGrids();
415 :
416 0 : if (nHasNonEmptyGrids >= 0)
417 0 : return nHasNonEmptyGrids != FALSE;
418 :
419 0 : nHasNonEmptyGrids = false;
420 :
421 0 : if (GDALDatasetGetLayerByName(hDS, "grids") == nullptr)
422 0 : return false;
423 :
424 0 : const char *pszSQL = "SELECT type FROM sqlite_master WHERE name = 'grids'";
425 0 : CPLDebug("MBTILES", "%s", pszSQL);
426 0 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
427 0 : if (hSQLLyr == nullptr)
428 0 : return false;
429 :
430 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
431 0 : if (hFeat == nullptr || !OGR_F_IsFieldSetAndNotNull(hFeat, 0))
432 : {
433 0 : OGR_F_Destroy(hFeat);
434 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
435 0 : return false;
436 : }
437 :
438 0 : bool bGridsIsView = strcmp(OGR_F_GetFieldAsString(hFeat, 0), "view") == 0;
439 :
440 0 : OGR_F_Destroy(hFeat);
441 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
442 :
443 0 : nHasNonEmptyGrids = TRUE;
444 :
445 : /* In the case 'grids' is a view (and a join between the 'map' and
446 : * 'grid_utfgrid' layers */
447 : /* the cost of evaluating a join is very long, even if grid_utfgrid is empty
448 : */
449 : /* so check it is not empty */
450 0 : if (bGridsIsView)
451 : {
452 : OGRLayerH hGridUTFGridLyr;
453 0 : hGridUTFGridLyr = GDALDatasetGetLayerByName(hDS, "grid_utfgrid");
454 0 : if (hGridUTFGridLyr != nullptr)
455 : {
456 0 : OGR_L_ResetReading(hGridUTFGridLyr);
457 0 : hFeat = OGR_L_GetNextFeature(hGridUTFGridLyr);
458 0 : OGR_F_Destroy(hFeat);
459 :
460 0 : nHasNonEmptyGrids = hFeat != nullptr;
461 : }
462 : }
463 :
464 0 : return nHasNonEmptyGrids != FALSE;
465 : }
466 :
467 : /************************************************************************/
468 : /* FindKey() */
469 : /************************************************************************/
470 :
471 0 : char *MBTilesDataset::FindKey(int iPixel, int iLine)
472 : {
473 : int nBlockXSize;
474 : int nBlockYSize;
475 0 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
476 :
477 : // Compute shift between GDAL origin and TileMatrixSet origin
478 : // Caution this is in GeoPackage / WMTS convention ! That is upper-left
479 : // corner
480 0 : const int nShiftXPixels =
481 0 : (int)floor(0.5 + (m_gt.xorig - TMS_ORIGIN_X) / m_gt.xscale);
482 0 : const int nShiftYPixelsFromGPKGOrigin =
483 0 : (int)floor(0.5 + (m_gt.yorig - TMS_ORIGIN_Y) / m_gt.yscale);
484 :
485 0 : const int iLineFromGPKGOrigin = iLine + nShiftYPixelsFromGPKGOrigin;
486 0 : const int iLineFromMBTilesOrigin =
487 0 : m_nTileMatrixHeight * nBlockYSize - 1 - iLineFromGPKGOrigin;
488 0 : const int iPixelFromMBTilesOrigin = iPixel + nShiftXPixels;
489 :
490 0 : const int nTileColumn = iPixelFromMBTilesOrigin / nBlockXSize;
491 0 : const int nTileRow = iLineFromMBTilesOrigin / nBlockYSize;
492 0 : int nColInTile = iPixelFromMBTilesOrigin % nBlockXSize;
493 0 : int nRowInTile = nBlockYSize - 1 - (iLineFromMBTilesOrigin % nBlockYSize);
494 :
495 0 : char *pszKey = nullptr;
496 :
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 : OGRLayerH hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
508 0 : if (hSQLLyr == nullptr)
509 0 : return nullptr;
510 :
511 0 : OGRFeatureH 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 : OGR_F_Destroy(hFeat);
668 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
669 :
670 0 : return pszKey;
671 : }
672 :
673 : /************************************************************************/
674 : /* GetMetadataDomainList() */
675 : /************************************************************************/
676 :
677 0 : char **MBTilesBand::GetMetadataDomainList()
678 : {
679 0 : return CSLAddString(GDALPamRasterBand::GetMetadataDomainList(),
680 0 : "LocationInfo");
681 : }
682 :
683 : /************************************************************************/
684 : /* GetMetadataItem() */
685 : /************************************************************************/
686 :
687 57 : const char *MBTilesBand::GetMetadataItem(const char *pszName,
688 : const char *pszDomain)
689 : {
690 57 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
691 :
692 : /* ==================================================================== */
693 : /* LocationInfo handling. */
694 : /* ==================================================================== */
695 57 : if (poGDS->hDS != nullptr && pszDomain != nullptr &&
696 20 : EQUAL(pszDomain, "LocationInfo") &&
697 0 : (STARTS_WITH_CI(pszName, "Pixel_") ||
698 0 : STARTS_WITH_CI(pszName, "GeoPixel_")))
699 : {
700 : int iPixel, iLine;
701 :
702 0 : if (!poGDS->HasNonEmptyGrids())
703 0 : return nullptr;
704 :
705 : /* --------------------------------------------------------------------
706 : */
707 : /* What pixel are we aiming at? */
708 : /* --------------------------------------------------------------------
709 : */
710 0 : if (STARTS_WITH_CI(pszName, "Pixel_"))
711 : {
712 0 : if (sscanf(pszName + 6, "%d_%d", &iPixel, &iLine) != 2)
713 0 : return nullptr;
714 : }
715 0 : else if (STARTS_WITH_CI(pszName, "GeoPixel_"))
716 : {
717 0 : GDALGeoTransform gt;
718 0 : GDALGeoTransform invGT;
719 : double dfGeoX, dfGeoY;
720 :
721 0 : dfGeoX = CPLAtof(pszName + 9);
722 0 : const char *pszUnderscore = strchr(pszName + 9, '_');
723 0 : if (!pszUnderscore)
724 0 : return nullptr;
725 0 : dfGeoY = CPLAtof(pszUnderscore + 1);
726 :
727 0 : if (GetDataset() == nullptr)
728 0 : return nullptr;
729 :
730 0 : if (GetDataset()->GetGeoTransform(gt) != CE_None)
731 0 : return nullptr;
732 :
733 0 : if (!GDALInvGeoTransform(gt.data(), invGT.data()))
734 0 : return nullptr;
735 :
736 0 : iPixel =
737 0 : (int)floor(invGT[0] + invGT[1] * dfGeoX + invGT[2] * dfGeoY);
738 0 : iLine =
739 0 : (int)floor(invGT[3] + invGT[4] * dfGeoX + invGT[5] * dfGeoY);
740 : }
741 : else
742 0 : return nullptr;
743 :
744 0 : if (iPixel < 0 || iLine < 0 || iPixel >= GetXSize() ||
745 0 : iLine >= GetYSize())
746 0 : return nullptr;
747 :
748 0 : char *pszKey = poGDS->FindKey(iPixel, iLine);
749 :
750 0 : if (pszKey != nullptr)
751 : {
752 : // CPLDebug("MBTILES", "Key = %s", pszKey);
753 :
754 0 : osLocationInfo = "<LocationInfo>";
755 0 : osLocationInfo += "<Key>";
756 : char *pszXMLEscaped =
757 0 : CPLEscapeString(pszKey, -1, CPLES_XML_BUT_QUOTES);
758 0 : osLocationInfo += pszXMLEscaped;
759 0 : CPLFree(pszXMLEscaped);
760 0 : osLocationInfo += "</Key>";
761 :
762 0 : if (GDALDatasetGetLayerByName(poGDS->hDS, "grid_data") != nullptr &&
763 0 : strchr(pszKey, '\'') == nullptr)
764 : {
765 : OGRLayerH hSQLLyr;
766 : OGRFeatureH hFeat;
767 :
768 : const char *pszSQL =
769 0 : CPLSPrintf("SELECT key_json FROM keymap WHERE "
770 : "key_name = '%s'",
771 : pszKey);
772 0 : CPLDebug("MBTILES", "%s", pszSQL);
773 : hSQLLyr =
774 0 : GDALDatasetExecuteSQL(poGDS->hDS, pszSQL, nullptr, nullptr);
775 0 : if (hSQLLyr)
776 : {
777 0 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
778 0 : if (hFeat != nullptr &&
779 0 : OGR_F_IsFieldSetAndNotNull(hFeat, 0))
780 : {
781 0 : const char *pszJSon = OGR_F_GetFieldAsString(hFeat, 0);
782 : // CPLDebug("MBTILES", "JSon = %s", pszJSon);
783 :
784 0 : osLocationInfo += "<JSon>";
785 : #ifdef CPLES_XML_BUT_QUOTES
786 : pszXMLEscaped =
787 0 : CPLEscapeString(pszJSon, -1, CPLES_XML_BUT_QUOTES);
788 : #else
789 : pszXMLEscaped = CPLEscapeString(pszJSon, -1, CPLES_XML);
790 : #endif
791 0 : osLocationInfo += pszXMLEscaped;
792 0 : CPLFree(pszXMLEscaped);
793 0 : osLocationInfo += "</JSon>";
794 : }
795 0 : OGR_F_Destroy(hFeat);
796 : }
797 0 : GDALDatasetReleaseResultSet(poGDS->hDS, hSQLLyr);
798 : }
799 :
800 0 : osLocationInfo += "</LocationInfo>";
801 :
802 0 : CPLFree(pszKey);
803 :
804 0 : return osLocationInfo.c_str();
805 : }
806 :
807 0 : return nullptr;
808 : }
809 : else
810 57 : return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
811 : }
812 :
813 : /************************************************************************/
814 : /* GetOverviewCount() */
815 : /************************************************************************/
816 :
817 9 : int MBTilesBand::GetOverviewCount()
818 : {
819 9 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
820 :
821 9 : if (poGDS->m_nOverviewCount >= 1)
822 5 : return poGDS->m_nOverviewCount;
823 : else
824 4 : return GDALPamRasterBand::GetOverviewCount();
825 : }
826 :
827 : /************************************************************************/
828 : /* GetOverview() */
829 : /************************************************************************/
830 :
831 7 : GDALRasterBand *MBTilesBand::GetOverview(int nLevel)
832 : {
833 7 : MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
834 :
835 7 : if (poGDS->m_nOverviewCount == 0)
836 0 : return GDALPamRasterBand::GetOverview(nLevel);
837 :
838 7 : if (nLevel < 0 || nLevel >= poGDS->m_nOverviewCount)
839 0 : return nullptr;
840 :
841 7 : GDALDataset *poOvrDS = poGDS->m_papoOverviewDS[nLevel];
842 7 : if (poOvrDS)
843 7 : return poOvrDS->GetRasterBand(nBand);
844 : else
845 0 : return nullptr;
846 : }
847 :
848 : /************************************************************************/
849 : /* MBTilesDataset() */
850 : /************************************************************************/
851 :
852 462 : MBTilesDataset::MBTilesDataset()
853 : {
854 462 : m_bWriteBounds = true;
855 462 : m_bWriteMinMaxZoom = true;
856 462 : poMainDS = nullptr;
857 462 : m_nOverviewCount = 0;
858 462 : hDS = nullptr;
859 462 : m_papoOverviewDS = nullptr;
860 462 : bFetchedMetadata = false;
861 462 : nHasNonEmptyGrids = -1;
862 462 : hDB = nullptr;
863 462 : pMyVFS = nullptr;
864 :
865 462 : m_bGeoTransformValid = false;
866 462 : m_bInFlushCache = false;
867 :
868 462 : m_osRasterTable = "tiles";
869 462 : m_eTF = GPKG_TF_PNG;
870 :
871 462 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
872 462 : m_oSRS.importFromEPSG(3857);
873 462 : }
874 :
875 : /************************************************************************/
876 : /* ~MBTilesDataset() */
877 : /************************************************************************/
878 :
879 924 : MBTilesDataset::~MBTilesDataset()
880 : {
881 : // Need to explicitly clear it before close hDS
882 462 : m_apoLayers.clear();
883 :
884 462 : FlushCache(true);
885 :
886 462 : if (poMainDS == nullptr)
887 : {
888 116 : if (m_papoOverviewDS)
889 : {
890 417 : for (int i = 0; i < m_nOverviewCount; i++)
891 346 : delete m_papoOverviewDS[i];
892 71 : CPLFree(m_papoOverviewDS);
893 : }
894 :
895 116 : if (hDS != nullptr)
896 : {
897 64 : GDALClose(hDS);
898 64 : hDB = nullptr;
899 : }
900 116 : if (hDB != nullptr)
901 : {
902 52 : sqlite3_close(hDB);
903 :
904 52 : if (pMyVFS)
905 : {
906 26 : sqlite3_vfs_unregister(pMyVFS);
907 26 : CPLFree(pMyVFS->pAppData);
908 26 : CPLFree(pMyVFS);
909 : }
910 : }
911 : }
912 :
913 462 : if (!m_osMetadataMemFilename.empty())
914 : {
915 33 : VSIUnlink(m_osMetadataMemFilename);
916 : }
917 924 : }
918 :
919 : /************************************************************************/
920 : /* IStartTransaction() */
921 : /************************************************************************/
922 :
923 38 : OGRErr MBTilesDataset::IStartTransaction()
924 : {
925 38 : char *pszErrMsg = nullptr;
926 38 : const int rc = sqlite3_exec(hDB, "BEGIN", nullptr, nullptr, &pszErrMsg);
927 38 : if (rc != SQLITE_OK)
928 : {
929 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
930 : "BEGIN", pszErrMsg);
931 0 : sqlite3_free(pszErrMsg);
932 0 : return OGRERR_FAILURE;
933 : }
934 :
935 38 : return OGRERR_NONE;
936 : }
937 :
938 : /************************************************************************/
939 : /* ICommitTransaction() */
940 : /************************************************************************/
941 :
942 38 : OGRErr MBTilesDataset::ICommitTransaction()
943 : {
944 38 : char *pszErrMsg = nullptr;
945 38 : const int rc = sqlite3_exec(hDB, "COMMIT", nullptr, nullptr, &pszErrMsg);
946 38 : if (rc != SQLITE_OK)
947 : {
948 0 : CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
949 : "COMMIT", pszErrMsg);
950 0 : sqlite3_free(pszErrMsg);
951 0 : return OGRERR_FAILURE;
952 : }
953 :
954 38 : return OGRERR_NONE;
955 : }
956 :
957 : /************************************************************************/
958 : /* ICanIWriteBlock() */
959 : /************************************************************************/
960 :
961 248 : bool MBTilesDataset::ICanIWriteBlock()
962 : {
963 248 : if (eAccess != GA_Update)
964 : {
965 0 : CPLError(
966 : CE_Failure, CPLE_NotSupported,
967 : "IWriteBlock() not supported on dataset opened in read-only mode");
968 0 : return false;
969 : }
970 :
971 248 : if (!m_bGeoTransformValid)
972 : {
973 0 : CPLError(CE_Failure, CPLE_NotSupported,
974 : "IWriteBlock() not supported if georeferencing not set");
975 0 : return false;
976 : }
977 248 : return true;
978 : }
979 :
980 : /************************************************************************/
981 : /* IFlushCacheWithErrCode() */
982 : /************************************************************************/
983 :
984 5620 : CPLErr MBTilesDataset::IFlushCacheWithErrCode(bool bAtClosing)
985 :
986 : {
987 5620 : if (m_bInFlushCache)
988 4264 : return CE_None;
989 1356 : m_bInFlushCache = true;
990 : // Short circuit GDALPamDataset to avoid serialization to .aux.xml
991 1356 : GDALDataset::FlushCache(bAtClosing);
992 :
993 1356 : CPLErr eErr = FlushTiles();
994 :
995 1356 : m_bInFlushCache = false;
996 1356 : return eErr;
997 : }
998 :
999 : /************************************************************************/
1000 : /* ICanIWriteBlock() */
1001 : /************************************************************************/
1002 :
1003 765 : int MBTilesDataset::GetRowFromIntoTopConvention(int nRow)
1004 : {
1005 765 : return m_nTileMatrixHeight - 1 - nRow;
1006 : }
1007 :
1008 : /************************************************************************/
1009 : /* GetGeoTransform() */
1010 : /************************************************************************/
1011 :
1012 41 : CPLErr MBTilesDataset::GetGeoTransform(GDALGeoTransform >) const
1013 : {
1014 41 : gt = m_gt;
1015 41 : return (m_bGeoTransformValid) ? CE_None : CE_Failure;
1016 : }
1017 :
1018 : /************************************************************************/
1019 : /* SphericalMercatorToLongLat() */
1020 : /************************************************************************/
1021 :
1022 99 : static void SphericalMercatorToLongLat(double *x, double *y)
1023 : {
1024 99 : double lng = *x / SPHERICAL_RADIUS / M_PI * 180;
1025 99 : double lat = 2 * (atan(exp(*y / SPHERICAL_RADIUS)) - M_PI / 4) / M_PI * 180;
1026 99 : *x = lng;
1027 99 : *y = lat;
1028 99 : }
1029 :
1030 : /************************************************************************/
1031 : /* LongLatToSphericalMercator() */
1032 : /************************************************************************/
1033 :
1034 120 : static void LongLatToSphericalMercator(double *x, double *y)
1035 : {
1036 120 : double X = SPHERICAL_RADIUS * (*x) / 180 * M_PI;
1037 120 : double Y = SPHERICAL_RADIUS * log(tan(M_PI / 4 + 0.5 * (*y) / 180 * M_PI));
1038 120 : *x = X;
1039 120 : *y = Y;
1040 120 : }
1041 :
1042 : /************************************************************************/
1043 : /* SetGeoTransform() */
1044 : /************************************************************************/
1045 :
1046 38 : CPLErr MBTilesDataset::SetGeoTransform(const GDALGeoTransform >)
1047 : {
1048 38 : if (eAccess != GA_Update)
1049 : {
1050 1 : CPLError(CE_Failure, CPLE_NotSupported,
1051 : "SetGeoTransform() not supported on read-only dataset");
1052 1 : return CE_Failure;
1053 : }
1054 37 : if (m_bGeoTransformValid)
1055 : {
1056 1 : CPLError(CE_Failure, CPLE_NotSupported,
1057 : "Cannot modify geotransform once set");
1058 1 : return CE_Failure;
1059 : }
1060 36 : if (gt.xrot != 0.0 || gt.yrot != 0 || gt.yscale > 0.0)
1061 : {
1062 1 : CPLError(CE_Failure, CPLE_NotSupported,
1063 : "Only north-up non rotated geotransform supported");
1064 1 : return CE_Failure;
1065 : }
1066 :
1067 35 : if (m_bWriteBounds)
1068 : {
1069 66 : CPLString osBounds(m_osBounds);
1070 33 : if (osBounds.empty())
1071 : {
1072 33 : double minx = gt.xorig;
1073 33 : double miny = gt.yorig + nRasterYSize * gt.yscale;
1074 33 : double maxx = gt.xorig + nRasterXSize * gt.xscale;
1075 33 : double maxy = gt.yorig;
1076 :
1077 33 : SphericalMercatorToLongLat(&minx, &miny);
1078 33 : SphericalMercatorToLongLat(&maxx, &maxy);
1079 33 : if (fabs(minx + 180) < 1e-7)
1080 : {
1081 3 : minx = -180.0;
1082 : }
1083 33 : if (fabs(maxx - 180) < 1e-7)
1084 : {
1085 3 : maxx = 180.0;
1086 : }
1087 :
1088 : // Clamp latitude so that when transformed back to EPSG:3857, we
1089 : // don't have too big northings
1090 33 : double tmpx = 0.0;
1091 33 : double ok_maxy = MAX_GM;
1092 33 : SphericalMercatorToLongLat(&tmpx, &ok_maxy);
1093 33 : if (maxy > ok_maxy)
1094 0 : maxy = ok_maxy;
1095 33 : if (miny < -ok_maxy)
1096 0 : miny = -ok_maxy;
1097 :
1098 33 : osBounds.Printf("%.17g,%.17g,%.17g,%.17g", minx, miny, maxx, maxy);
1099 : }
1100 :
1101 33 : char *pszSQL = sqlite3_mprintf(
1102 : "INSERT INTO metadata (name, value) VALUES ('bounds', '%q')",
1103 : osBounds.c_str());
1104 33 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1105 33 : sqlite3_free(pszSQL);
1106 :
1107 33 : if (!m_osCenter.empty())
1108 : {
1109 0 : pszSQL = sqlite3_mprintf(
1110 : "INSERT INTO metadata (name, value) VALUES ('center', '%q')",
1111 : m_osCenter.c_str());
1112 0 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1113 0 : sqlite3_free(pszSQL);
1114 : }
1115 : }
1116 :
1117 : int nBlockXSize;
1118 : int nBlockYSize;
1119 35 : GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
1120 35 : const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockXSize;
1121 35 : const double dfPixelYSizeZoomLevel0 = 2 * MAX_GM / nBlockYSize;
1122 361 : for (m_nZoomLevel = 0; m_nZoomLevel < 25; m_nZoomLevel++)
1123 : {
1124 360 : double dfExpectedPixelXSize =
1125 360 : dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
1126 360 : double dfExpectedPixelYSize =
1127 360 : dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
1128 360 : if (fabs(gt.xscale - dfExpectedPixelXSize) <
1129 360 : 1e-8 * dfExpectedPixelXSize &&
1130 34 : fabs(fabs(gt.yscale) - dfExpectedPixelYSize) <
1131 34 : 1e-8 * dfExpectedPixelYSize)
1132 : {
1133 34 : break;
1134 : }
1135 : }
1136 35 : if (m_nZoomLevel == 25)
1137 : {
1138 1 : m_nZoomLevel = -1;
1139 1 : CPLError(CE_Failure, CPLE_NotSupported,
1140 : "Could not find an appropriate zoom level that matches raster "
1141 : "pixel size");
1142 1 : return CE_Failure;
1143 : }
1144 :
1145 34 : m_gt = gt;
1146 34 : m_bGeoTransformValid = true;
1147 :
1148 34 : return FinalizeRasterRegistration();
1149 : }
1150 :
1151 : /************************************************************************/
1152 : /* ComputeTileAndPixelShifts() */
1153 : /************************************************************************/
1154 :
1155 444 : void MBTilesDataset::ComputeTileAndPixelShifts()
1156 : {
1157 : int nTileWidth, nTileHeight;
1158 444 : GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
1159 :
1160 : // Compute shift between GDAL origin and TileMatrixSet origin
1161 : // Caution this is in GeoPackage / WMTS convention ! That is upper-left
1162 : // corner
1163 444 : int nShiftXPixels =
1164 444 : (int)floor(0.5 + (m_gt.xorig - TMS_ORIGIN_X) / m_gt.xscale);
1165 444 : m_nShiftXTiles = (int)floor(1.0 * nShiftXPixels / nTileWidth);
1166 444 : m_nShiftXPixelsMod =
1167 444 : ((nShiftXPixels % nTileWidth) + nTileWidth) % nTileWidth;
1168 444 : int nShiftYPixels =
1169 444 : (int)floor(0.5 + (m_gt.yorig - TMS_ORIGIN_Y) / m_gt.yscale);
1170 444 : m_nShiftYTiles = (int)floor(1.0 * nShiftYPixels / nTileHeight);
1171 444 : m_nShiftYPixelsMod =
1172 444 : ((nShiftYPixels % nTileHeight) + nTileHeight) % nTileHeight;
1173 444 : }
1174 :
1175 : /************************************************************************/
1176 : /* FinalizeRasterRegistration() */
1177 : /************************************************************************/
1178 :
1179 34 : CPLErr MBTilesDataset::FinalizeRasterRegistration()
1180 : {
1181 34 : m_nTileMatrixWidth = (1 << m_nZoomLevel);
1182 34 : m_nTileMatrixHeight = (1 << m_nZoomLevel);
1183 :
1184 34 : ComputeTileAndPixelShifts();
1185 :
1186 34 : double dfGDALMinX = m_gt.xorig;
1187 34 : double dfGDALMinY = m_gt.yorig + nRasterYSize * m_gt.yscale;
1188 34 : double dfGDALMaxX = m_gt.xorig + nRasterXSize * m_gt.xscale;
1189 34 : double dfGDALMaxY = m_gt.yorig;
1190 :
1191 34 : m_nOverviewCount = m_nZoomLevel;
1192 68 : m_papoOverviewDS = (MBTilesDataset **)CPLCalloc(sizeof(MBTilesDataset *),
1193 34 : m_nOverviewCount);
1194 :
1195 34 : if (m_bWriteMinMaxZoom)
1196 : {
1197 34 : char *pszSQL = sqlite3_mprintf(
1198 : "INSERT INTO metadata (name, value) VALUES ('minzoom', '%d')",
1199 : m_nZoomLevel);
1200 34 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1201 34 : sqlite3_free(pszSQL);
1202 34 : pszSQL = sqlite3_mprintf(
1203 : "INSERT INTO metadata (name, value) VALUES ('maxzoom', '%d')",
1204 : m_nZoomLevel);
1205 34 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
1206 34 : sqlite3_free(pszSQL);
1207 : }
1208 :
1209 335 : for (int i = 0; i < m_nOverviewCount; i++)
1210 : {
1211 301 : MBTilesDataset *poOvrDS = new MBTilesDataset();
1212 301 : poOvrDS->ShareLockWithParentDataset(this);
1213 : int nBlockSize;
1214 301 : GetRasterBand(1)->GetBlockSize(&nBlockSize, &nBlockSize);
1215 301 : poOvrDS->InitRaster(this, i, nBands, nBlockSize, dfGDALMinX, dfGDALMinY,
1216 : dfGDALMaxX, dfGDALMaxY);
1217 :
1218 301 : m_papoOverviewDS[m_nZoomLevel - 1 - i] = poOvrDS;
1219 : }
1220 :
1221 34 : return CE_None;
1222 : }
1223 :
1224 : /************************************************************************/
1225 : /* InitRaster() */
1226 : /************************************************************************/
1227 :
1228 410 : bool MBTilesDataset::InitRaster(MBTilesDataset *poParentDS, int nZoomLevel,
1229 : int nBandCount, int nTileSize,
1230 : double dfGDALMinX, double dfGDALMinY,
1231 : double dfGDALMaxX, double dfGDALMaxY)
1232 : {
1233 410 : m_nZoomLevel = nZoomLevel;
1234 410 : m_nTileMatrixWidth = 1 << nZoomLevel;
1235 410 : m_nTileMatrixHeight = 1 << nZoomLevel;
1236 :
1237 410 : const int nTileWidth = nTileSize;
1238 410 : const int nTileHeight = nTileSize;
1239 410 : const double dfPixelXSize = 2 * MAX_GM / nTileWidth / (1 << nZoomLevel);
1240 410 : const double dfPixelYSize = 2 * MAX_GM / nTileHeight / (1 << nZoomLevel);
1241 :
1242 410 : m_bGeoTransformValid = true;
1243 410 : m_gt.xorig = dfGDALMinX;
1244 410 : m_gt.xscale = dfPixelXSize;
1245 410 : m_gt.yorig = dfGDALMaxY;
1246 410 : m_gt.yscale = -dfPixelYSize;
1247 410 : double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
1248 410 : double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
1249 410 : if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
1250 0 : return false;
1251 410 : nRasterXSize = (int)dfRasterXSize;
1252 410 : nRasterYSize = (int)dfRasterYSize;
1253 :
1254 410 : m_pabyCachedTiles =
1255 410 : (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nTileWidth, nTileHeight);
1256 410 : if (m_pabyCachedTiles == nullptr)
1257 : {
1258 0 : return false;
1259 : }
1260 :
1261 410 : if (poParentDS)
1262 : {
1263 346 : eAccess = poParentDS->eAccess;
1264 : }
1265 :
1266 1619 : for (int i = 1; i <= nBandCount; i++)
1267 1209 : SetBand(i, new MBTilesBand(this, nTileSize));
1268 :
1269 410 : ComputeTileAndPixelShifts();
1270 :
1271 410 : GDALDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
1272 410 : GDALDataset::SetMetadataItem("ZOOM_LEVEL", CPLSPrintf("%d", m_nZoomLevel));
1273 :
1274 410 : if (poParentDS)
1275 : {
1276 346 : m_poParentDS = poParentDS;
1277 346 : poMainDS = poParentDS;
1278 346 : hDS = poParentDS->hDS;
1279 346 : hDB = poParentDS->hDB;
1280 346 : m_eTF = poParentDS->m_eTF;
1281 346 : m_nQuality = poParentDS->m_nQuality;
1282 346 : m_nZLevel = poParentDS->m_nZLevel;
1283 346 : m_bDither = poParentDS->m_bDither;
1284 346 : m_osWHERE = poParentDS->m_osWHERE;
1285 346 : SetDescription(CPLSPrintf("%s - zoom_level=%d",
1286 346 : poParentDS->GetDescription(), m_nZoomLevel));
1287 : }
1288 :
1289 410 : return true;
1290 : }
1291 :
1292 : /************************************************************************/
1293 : /* GetSpatialRef() */
1294 : /************************************************************************/
1295 :
1296 3 : const OGRSpatialReference *MBTilesDataset::GetSpatialRef() const
1297 : {
1298 3 : return &m_oSRS;
1299 : }
1300 :
1301 : /************************************************************************/
1302 : /* SetSpatialRef() */
1303 : /************************************************************************/
1304 :
1305 3 : CPLErr MBTilesDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
1306 : {
1307 3 : if (eAccess != GA_Update)
1308 : {
1309 1 : CPLError(CE_Failure, CPLE_NotSupported,
1310 : "SetSpatialRef() not supported on read-only dataset");
1311 1 : return CE_Failure;
1312 : }
1313 :
1314 2 : if (poSRS == nullptr || poSRS->GetAuthorityName() == nullptr ||
1315 1 : !EQUAL(poSRS->GetAuthorityName(), "EPSG") ||
1316 5 : poSRS->GetAuthorityCode() == nullptr ||
1317 1 : !EQUAL(poSRS->GetAuthorityCode(), "3857"))
1318 : {
1319 1 : CPLError(CE_Failure, CPLE_NotSupported,
1320 : "Only EPSG:3857 supported on MBTiles dataset");
1321 1 : return CE_Failure;
1322 : }
1323 1 : return CE_None;
1324 : }
1325 :
1326 : /************************************************************************/
1327 : /* GetMetadataDomainList() */
1328 : /************************************************************************/
1329 :
1330 0 : char **MBTilesDataset::GetMetadataDomainList()
1331 : {
1332 0 : return BuildMetadataDomainList(GDALDataset::GetMetadataDomainList(), TRUE,
1333 0 : "", nullptr);
1334 : }
1335 :
1336 : /************************************************************************/
1337 : /* GetMetadata() */
1338 : /************************************************************************/
1339 :
1340 111 : CSLConstList MBTilesDataset::GetMetadata(const char *pszDomain)
1341 : {
1342 111 : if (hDS == nullptr || (pszDomain != nullptr && !EQUAL(pszDomain, "")))
1343 32 : return GDALPamDataset::GetMetadata(pszDomain);
1344 :
1345 79 : if (bFetchedMetadata)
1346 15 : return aosList.List();
1347 :
1348 64 : bFetchedMetadata = true;
1349 64 : aosList = CPLStringList(GDALPamDataset::GetMetadata());
1350 :
1351 64 : OGRLayerH hSQLLyr = GDALDatasetExecuteSQL(
1352 : hDS, "SELECT name, value FROM metadata WHERE name != 'json' LIMIT 1000",
1353 : nullptr, nullptr);
1354 64 : if (hSQLLyr == nullptr)
1355 0 : return nullptr;
1356 :
1357 64 : if (OGR_FD_GetFieldCount(OGR_L_GetLayerDefn(hSQLLyr)) != 2)
1358 : {
1359 0 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1360 0 : return nullptr;
1361 : }
1362 :
1363 : OGRFeatureH hFeat;
1364 615 : while ((hFeat = OGR_L_GetNextFeature(hSQLLyr)) != nullptr)
1365 : {
1366 1102 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
1367 551 : OGR_F_IsFieldSetAndNotNull(hFeat, 1))
1368 : {
1369 1102 : CPLString osName = OGR_F_GetFieldAsString(hFeat, 0);
1370 1102 : CPLString osValue = OGR_F_GetFieldAsString(hFeat, 1);
1371 1102 : if (osName[0] != '\0' && !STARTS_WITH(osValue, "function(") &&
1372 551 : strstr(osValue, "<img ") == nullptr &&
1373 551 : strstr(osValue, "<p>") == nullptr &&
1374 1653 : strstr(osValue, "</p>") == nullptr &&
1375 551 : strstr(osValue, "<div") == nullptr)
1376 : {
1377 551 : aosList.AddNameValue(osName, osValue);
1378 : }
1379 : }
1380 551 : OGR_F_Destroy(hFeat);
1381 : }
1382 64 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1383 :
1384 64 : return aosList.List();
1385 : }
1386 :
1387 : /************************************************************************/
1388 : /* GetMetadataItem() */
1389 : /************************************************************************/
1390 :
1391 119 : const char *MBTilesDataset::GetMetadataItem(const char *pszName,
1392 : const char *pszDomain)
1393 : {
1394 119 : if (pszDomain == nullptr || EQUAL(pszDomain, ""))
1395 : {
1396 90 : const char *pszValue = CSLFetchNameValue(GetMetadata(), pszName);
1397 90 : if (pszValue)
1398 69 : return pszValue;
1399 : }
1400 50 : return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
1401 : }
1402 :
1403 : /************************************************************************/
1404 : /* GetLayer() */
1405 : /************************************************************************/
1406 :
1407 60 : const OGRLayer *MBTilesDataset::GetLayer(int iLayer) const
1408 :
1409 : {
1410 60 : if (iLayer < 0 || iLayer >= GetLayerCount())
1411 2 : return nullptr;
1412 58 : return m_apoLayers[iLayer].get();
1413 : }
1414 :
1415 : /************************************************************************/
1416 : /* MBTilesVectorLayer() */
1417 : /************************************************************************/
1418 :
1419 38 : MBTilesVectorLayer::MBTilesVectorLayer(
1420 : MBTilesDataset *poDS, const char *pszLayerName,
1421 : const CPLJSONObject &oFields, const CPLJSONArray &oAttributesFromTileStats,
1422 : bool bJsonField, double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
1423 38 : OGRwkbGeometryType eGeomType, bool bZoomLevelFromSpatialFilter)
1424 38 : : m_poDS(poDS), m_poFeatureDefn(new OGRFeatureDefn(pszLayerName)),
1425 76 : m_bJsonField(bJsonField)
1426 : {
1427 38 : SetDescription(pszLayerName);
1428 38 : m_poFeatureDefn->SetGeomType(eGeomType);
1429 38 : OGRSpatialReference *poSRS = new OGRSpatialReference();
1430 38 : poSRS->SetFromUserInput(SRS_EPSG_3857);
1431 38 : m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
1432 38 : poSRS->Release();
1433 38 : m_poFeatureDefn->Reference();
1434 :
1435 38 : if (m_bJsonField)
1436 : {
1437 2 : OGRFieldDefn oFieldDefnId("mvt_id", OFTInteger64);
1438 1 : m_poFeatureDefn->AddFieldDefn(&oFieldDefnId);
1439 : }
1440 : else
1441 : {
1442 37 : OGRMVTInitFields(m_poFeatureDefn, oFields, oAttributesFromTileStats);
1443 : }
1444 :
1445 38 : m_sExtent.MinX = dfMinX;
1446 38 : m_sExtent.MinY = dfMinY;
1447 38 : m_sExtent.MaxX = dfMaxX;
1448 38 : m_sExtent.MaxY = dfMaxY;
1449 :
1450 38 : m_nZoomLevel = m_poDS->m_nZoomLevel;
1451 38 : m_bZoomLevelAuto = bZoomLevelFromSpatialFilter;
1452 38 : MBTilesVectorLayer::SetSpatialFilter(nullptr);
1453 :
1454 : // If the metadata contains an empty fields object, this may be a sign
1455 : // that it doesn't know the schema. In that case check if a tile has
1456 : // attributes, and in that case create a json field.
1457 38 : if (!m_bJsonField && oFields.IsValid() && oFields.GetChildren().empty())
1458 : {
1459 8 : m_bJsonField = true;
1460 8 : OGRFeature *poSrcFeature = GetNextSrcFeature();
1461 8 : m_bJsonField = false;
1462 :
1463 8 : if (poSrcFeature)
1464 : {
1465 : // There is at least the mvt_id field
1466 8 : if (poSrcFeature->GetFieldCount() > 1)
1467 : {
1468 1 : m_bJsonField = true;
1469 : }
1470 8 : delete poSrcFeature;
1471 : }
1472 8 : MBTilesVectorLayer::ResetReading();
1473 : }
1474 :
1475 38 : if (m_bJsonField)
1476 : {
1477 4 : OGRFieldDefn oFieldDefn("json", OFTString);
1478 2 : m_poFeatureDefn->AddFieldDefn(&oFieldDefn);
1479 : }
1480 38 : }
1481 :
1482 : /************************************************************************/
1483 : /* ~MBTilesVectorLayer() */
1484 : /************************************************************************/
1485 :
1486 76 : MBTilesVectorLayer::~MBTilesVectorLayer()
1487 : {
1488 38 : m_poFeatureDefn->Release();
1489 38 : if (m_hTileIteratorLyr)
1490 15 : GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
1491 38 : if (!m_osTmpFilename.empty())
1492 : {
1493 15 : VSIUnlink(m_osTmpFilename);
1494 : }
1495 38 : if (m_hTileDS)
1496 11 : GDALClose(m_hTileDS);
1497 76 : }
1498 :
1499 : /************************************************************************/
1500 : /* TestCapability() */
1501 : /************************************************************************/
1502 :
1503 36 : int MBTilesVectorLayer::TestCapability(const char *pszCap) const
1504 : {
1505 36 : if (EQUAL(pszCap, OLCStringsAsUTF8) ||
1506 24 : EQUAL(pszCap, OLCFastSpatialFilter) || EQUAL(pszCap, OLCFastGetExtent))
1507 : {
1508 14 : return TRUE;
1509 : }
1510 22 : return FALSE;
1511 : }
1512 :
1513 : /************************************************************************/
1514 : /* IGetExtent() */
1515 : /************************************************************************/
1516 :
1517 4 : OGRErr MBTilesVectorLayer::IGetExtent(int /* iGeomField */,
1518 : OGREnvelope *psExtent, bool /* bForce */)
1519 : {
1520 4 : *psExtent = m_sExtent;
1521 4 : return OGRERR_NONE;
1522 : }
1523 :
1524 : /************************************************************************/
1525 : /* ResetReading() */
1526 : /************************************************************************/
1527 :
1528 111 : void MBTilesVectorLayer::ResetReading()
1529 : {
1530 111 : if (m_hTileDS)
1531 46 : GDALClose(m_hTileDS);
1532 111 : m_hTileDS = nullptr;
1533 111 : m_bEOF = false;
1534 111 : if (m_hTileIteratorLyr)
1535 96 : GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
1536 111 : CPLString osSQL;
1537 : osSQL.Printf("SELECT tile_column, tile_row, tile_data FROM tiles "
1538 : "WHERE zoom_level = %d "
1539 : "AND tile_column BETWEEN %d AND %d "
1540 : "AND tile_row BETWEEN %d AND %d",
1541 : m_nZoomLevel, m_nFilterMinX, m_nFilterMaxX, m_nFilterMinY,
1542 111 : m_nFilterMaxY);
1543 111 : m_hTileIteratorLyr =
1544 111 : GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
1545 111 : }
1546 :
1547 : /************************************************************************/
1548 : /* ISetSpatialFilter() */
1549 : /************************************************************************/
1550 :
1551 62 : OGRErr MBTilesVectorLayer::ISetSpatialFilter(int iGeomField,
1552 : const OGRGeometry *poGeomIn)
1553 : {
1554 62 : OGRErr eErr = OGRLayer::ISetSpatialFilter(iGeomField, poGeomIn);
1555 62 : if (eErr == OGRERR_NONE)
1556 : {
1557 62 : if (m_poFilterGeom != nullptr && m_sFilterEnvelope.MinX <= -MAX_GM &&
1558 2 : m_sFilterEnvelope.MinY <= -MAX_GM &&
1559 2 : m_sFilterEnvelope.MaxX >= MAX_GM &&
1560 2 : m_sFilterEnvelope.MaxY >= MAX_GM)
1561 : {
1562 2 : if (m_bZoomLevelAuto)
1563 : {
1564 0 : m_nZoomLevel = m_poDS->m_nMinZoomLevel;
1565 : }
1566 2 : m_nFilterMinX = 0;
1567 2 : m_nFilterMinY = 0;
1568 2 : m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
1569 2 : m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
1570 : }
1571 60 : else if (m_poFilterGeom != nullptr &&
1572 6 : m_sFilterEnvelope.MinX >= -10 * MAX_GM &&
1573 6 : m_sFilterEnvelope.MinY >= -10 * MAX_GM &&
1574 6 : m_sFilterEnvelope.MaxX <= 10 * MAX_GM &&
1575 6 : m_sFilterEnvelope.MaxY <= 10 * MAX_GM)
1576 : {
1577 6 : if (m_bZoomLevelAuto)
1578 : {
1579 : double dfExtent =
1580 0 : std::min(m_sFilterEnvelope.MaxX - m_sFilterEnvelope.MinX,
1581 0 : m_sFilterEnvelope.MaxY - m_sFilterEnvelope.MinY);
1582 0 : m_nZoomLevel = std::max(
1583 0 : m_poDS->m_nMinZoomLevel,
1584 0 : std::min(static_cast<int>(0.5 + log(2 * MAX_GM / dfExtent) /
1585 : log(2.0)),
1586 0 : m_poDS->m_nZoomLevel));
1587 0 : CPLDebug("MBTILES", "Zoom level = %d", m_nZoomLevel);
1588 : }
1589 6 : const double dfTileDim = 2 * MAX_GM / (1 << m_nZoomLevel);
1590 6 : m_nFilterMinX = std::max(
1591 12 : 0, static_cast<int>(
1592 6 : floor((m_sFilterEnvelope.MinX + MAX_GM) / dfTileDim)));
1593 6 : m_nFilterMinY = std::max(
1594 12 : 0, static_cast<int>(
1595 6 : floor((m_sFilterEnvelope.MinY + MAX_GM) / dfTileDim)));
1596 6 : m_nFilterMaxX =
1597 12 : std::min(static_cast<int>(ceil(
1598 6 : (m_sFilterEnvelope.MaxX + MAX_GM) / dfTileDim)),
1599 6 : (1 << m_nZoomLevel) - 1);
1600 6 : m_nFilterMaxY =
1601 12 : std::min(static_cast<int>(ceil(
1602 6 : (m_sFilterEnvelope.MaxY + MAX_GM) / dfTileDim)),
1603 6 : (1 << m_nZoomLevel) - 1);
1604 : }
1605 : else
1606 : {
1607 54 : if (m_bZoomLevelAuto)
1608 : {
1609 0 : m_nZoomLevel = m_poDS->m_nZoomLevel;
1610 : }
1611 54 : m_nFilterMinX = 0;
1612 54 : m_nFilterMinY = 0;
1613 54 : m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
1614 54 : m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
1615 : }
1616 : }
1617 62 : return eErr;
1618 : }
1619 :
1620 : /************************************************************************/
1621 : /* GetNextFeature() */
1622 : /************************************************************************/
1623 :
1624 159 : OGRFeature *MBTilesVectorLayer::GetNextFeature()
1625 : {
1626 : while (true)
1627 : {
1628 159 : OGRFeature *poFeature = GetNextRawFeature();
1629 159 : if (poFeature == nullptr)
1630 32 : return nullptr;
1631 :
1632 296 : if ((m_poFilterGeom == nullptr ||
1633 241 : FilterGeometry(poFeature->GetGeometryRef())) &&
1634 114 : (m_poAttrQuery == nullptr || m_poAttrQuery->Evaluate(poFeature)))
1635 : {
1636 86 : return poFeature;
1637 : }
1638 :
1639 41 : delete poFeature;
1640 41 : }
1641 : }
1642 :
1643 : /************************************************************************/
1644 : /* GetFeatureCount() */
1645 : /************************************************************************/
1646 :
1647 15 : GIntBig MBTilesVectorLayer::GetFeatureCount(int bForce)
1648 : {
1649 15 : if (m_poFilterGeom == nullptr && m_poAttrQuery == nullptr)
1650 : {
1651 9 : if (m_nFeatureCount < 0)
1652 : {
1653 1 : m_nFeatureCount = 0;
1654 1 : ResetReading();
1655 5 : while (m_hTileIteratorLyr != nullptr)
1656 : {
1657 5 : OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
1658 5 : if (hFeat == nullptr)
1659 : {
1660 1 : break;
1661 : }
1662 4 : m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
1663 : // MBTiles y origin is bottom based, whereas MVT directory
1664 : // is top based
1665 4 : m_nY =
1666 4 : (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
1667 4 : int nDataSize = 0;
1668 4 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
1669 4 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1670 4 : memcpy(pabyDataDup, pabyData, nDataSize);
1671 4 : OGR_F_Destroy(hFeat);
1672 :
1673 4 : if (!m_osTmpFilename.empty())
1674 : {
1675 3 : VSIUnlink(m_osTmpFilename);
1676 : }
1677 : m_osTmpFilename = VSIMemGenerateHiddenFilename(
1678 4 : CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
1679 4 : VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
1680 : nDataSize, true));
1681 :
1682 4 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1683 4 : if (m_hTileDS)
1684 0 : GDALClose(m_hTileDS);
1685 4 : char **papszOpenOptions = nullptr;
1686 : papszOpenOptions =
1687 4 : CSLSetNameValue(papszOpenOptions, "METADATA_FILE",
1688 4 : m_poDS->m_osMetadataMemFilename.c_str());
1689 4 : m_hTileDS =
1690 4 : GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
1691 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1692 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1693 4 : CSLDestroy(papszOpenOptions);
1694 4 : if (m_hTileDS)
1695 : {
1696 : OGRLayerH hLayer =
1697 4 : GDALDatasetGetLayerByName(m_hTileDS, GetName());
1698 4 : if (hLayer)
1699 : {
1700 4 : m_nFeatureCount += OGR_L_GetFeatureCount(hLayer, true);
1701 : }
1702 4 : GDALClose(m_hTileDS);
1703 4 : m_hTileDS = nullptr;
1704 : }
1705 : }
1706 1 : ResetReading();
1707 : }
1708 9 : return m_nFeatureCount;
1709 : }
1710 6 : return OGRLayer::GetFeatureCount(bForce);
1711 : }
1712 :
1713 : /************************************************************************/
1714 : /* GetNextSrcFeature() */
1715 : /************************************************************************/
1716 :
1717 167 : OGRFeature *MBTilesVectorLayer::GetNextSrcFeature()
1718 : {
1719 167 : if (m_bEOF)
1720 : {
1721 3 : return nullptr;
1722 : }
1723 164 : if (m_hTileIteratorLyr == nullptr)
1724 : {
1725 14 : ResetReading();
1726 14 : if (m_hTileIteratorLyr == nullptr)
1727 : {
1728 0 : return nullptr;
1729 : }
1730 : }
1731 :
1732 164 : OGRFeatureH hTileFeat = nullptr;
1733 271 : if (m_hTileDS == nullptr ||
1734 107 : (hTileFeat = OGR_L_GetNextFeature(
1735 107 : GDALDatasetGetLayerByName(m_hTileDS, GetName()))) == nullptr)
1736 : {
1737 : while (true)
1738 : {
1739 173 : OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
1740 173 : if (hFeat == nullptr)
1741 : {
1742 29 : m_bEOF = true;
1743 29 : return nullptr;
1744 : }
1745 144 : m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
1746 : // MBTiles y origin is bottom based, whereas MVT directory
1747 : // is top based
1748 144 : m_nY = (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
1749 144 : CPLDebug("MBTiles", "X=%d, Y=%d", m_nX, m_nY);
1750 :
1751 144 : int nDataSize = 0;
1752 144 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
1753 144 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1754 144 : memcpy(pabyDataDup, pabyData, nDataSize);
1755 144 : OGR_F_Destroy(hFeat);
1756 :
1757 144 : if (!m_osTmpFilename.empty())
1758 : {
1759 130 : VSIUnlink(m_osTmpFilename);
1760 : }
1761 : m_osTmpFilename = VSIMemGenerateHiddenFilename(
1762 144 : CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
1763 144 : VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
1764 : nDataSize, true));
1765 :
1766 144 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1767 144 : if (m_hTileDS)
1768 75 : GDALClose(m_hTileDS);
1769 144 : char **papszOpenOptions = nullptr;
1770 : papszOpenOptions =
1771 144 : CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", m_nX));
1772 : papszOpenOptions =
1773 144 : CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", m_nY));
1774 144 : papszOpenOptions = CSLSetNameValue(papszOpenOptions, "Z",
1775 : CPLSPrintf("%d", m_nZoomLevel));
1776 144 : papszOpenOptions = CSLSetNameValue(
1777 : papszOpenOptions, "METADATA_FILE",
1778 144 : m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
1779 144 : if (!m_poDS->m_osClip.empty())
1780 : {
1781 : papszOpenOptions =
1782 3 : CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
1783 : }
1784 144 : m_hTileDS =
1785 144 : GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
1786 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1787 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1788 144 : CSLDestroy(papszOpenOptions);
1789 144 : if (m_hTileDS)
1790 : {
1791 144 : if (GDALDatasetGetLayerByName(m_hTileDS, GetName()))
1792 : {
1793 136 : hTileFeat = OGR_L_GetNextFeature(
1794 136 : GDALDatasetGetLayerByName(m_hTileDS, GetName()));
1795 136 : if (hTileFeat)
1796 132 : break;
1797 : }
1798 12 : GDALClose(m_hTileDS);
1799 12 : m_hTileDS = nullptr;
1800 : }
1801 12 : }
1802 : }
1803 :
1804 135 : return reinterpret_cast<OGRFeature *>(hTileFeat);
1805 : }
1806 :
1807 : /************************************************************************/
1808 : /* CreateFeatureFrom() */
1809 : /************************************************************************/
1810 :
1811 : OGRFeature *
1812 129 : MBTilesVectorLayer::CreateFeatureFrom(OGRFeature *poSrcFeature) const
1813 : {
1814 :
1815 129 : return OGRMVTCreateFeatureFrom(poSrcFeature, m_poFeatureDefn, m_bJsonField,
1816 258 : GetSpatialRef());
1817 : }
1818 :
1819 : /************************************************************************/
1820 : /* GetNextRawFeature() */
1821 : /************************************************************************/
1822 :
1823 159 : OGRFeature *MBTilesVectorLayer::GetNextRawFeature()
1824 : {
1825 159 : OGRFeature *poSrcFeat = GetNextSrcFeature();
1826 159 : if (poSrcFeat == nullptr)
1827 32 : return nullptr;
1828 :
1829 127 : const GIntBig nFIDBase =
1830 127 : (static_cast<GIntBig>(m_nY) << m_nZoomLevel) | m_nX;
1831 127 : OGRFeature *poFeature = CreateFeatureFrom(poSrcFeat);
1832 127 : poFeature->SetFID((poSrcFeat->GetFID() << (2 * m_nZoomLevel)) | nFIDBase);
1833 127 : delete poSrcFeat;
1834 :
1835 127 : return poFeature;
1836 : }
1837 :
1838 : /************************************************************************/
1839 : /* GetFeature() */
1840 : /************************************************************************/
1841 :
1842 5 : OGRFeature *MBTilesVectorLayer::GetFeature(GIntBig nFID)
1843 : {
1844 5 : const int nZ = m_nZoomLevel;
1845 5 : const int nX = static_cast<int>(nFID & ((1 << nZ) - 1));
1846 5 : const int nY = static_cast<int>((nFID >> nZ) & ((1 << nZ) - 1));
1847 5 : const GIntBig nTileFID = nFID >> (2 * nZ);
1848 :
1849 10 : CPLString osSQL;
1850 : osSQL.Printf("SELECT tile_data FROM tiles "
1851 : "WHERE zoom_level = %d AND "
1852 : "tile_column = %d AND tile_row = %d",
1853 5 : m_nZoomLevel, nX, (1 << nZ) - 1 - nY);
1854 : auto hSQLLyr =
1855 5 : GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
1856 5 : if (hSQLLyr == nullptr)
1857 0 : return nullptr;
1858 5 : auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
1859 5 : if (hFeat == nullptr)
1860 : {
1861 0 : GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
1862 0 : return nullptr;
1863 : }
1864 5 : int nDataSize = 0;
1865 5 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
1866 5 : GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
1867 5 : memcpy(pabyDataDup, pabyData, nDataSize);
1868 5 : OGR_F_Destroy(hFeat);
1869 5 : GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
1870 :
1871 : const CPLString osTmpFilename = VSIMemGenerateHiddenFilename(
1872 5 : CPLSPrintf("mvt_get_feature_%d_%d.pbf", m_nX, m_nY));
1873 5 : VSIFCloseL(
1874 : VSIFileFromMemBuffer(osTmpFilename, pabyDataDup, nDataSize, true));
1875 :
1876 5 : const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
1877 5 : char **papszOpenOptions = nullptr;
1878 : papszOpenOptions =
1879 5 : CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", nX));
1880 : papszOpenOptions =
1881 5 : CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", nY));
1882 : papszOpenOptions =
1883 5 : CSLSetNameValue(papszOpenOptions, "Z", CPLSPrintf("%d", m_nZoomLevel));
1884 5 : papszOpenOptions = CSLSetNameValue(
1885 : papszOpenOptions, "METADATA_FILE",
1886 5 : m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
1887 5 : if (!m_poDS->m_osClip.empty())
1888 : {
1889 : papszOpenOptions =
1890 0 : CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
1891 : }
1892 5 : auto hTileDS = GDALOpenEx(("MVT:" + osTmpFilename).c_str(),
1893 : GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
1894 : l_apszAllowedDrivers, papszOpenOptions, nullptr);
1895 5 : CSLDestroy(papszOpenOptions);
1896 :
1897 5 : OGRFeature *poFeature = nullptr;
1898 5 : if (hTileDS)
1899 : {
1900 5 : OGRLayerH hLayer = GDALDatasetGetLayerByName(hTileDS, GetName());
1901 5 : if (hLayer)
1902 : {
1903 : OGRFeature *poUnderlyingFeature = reinterpret_cast<OGRFeature *>(
1904 5 : OGR_L_GetFeature(hLayer, nTileFID));
1905 5 : if (poUnderlyingFeature)
1906 : {
1907 2 : poFeature = CreateFeatureFrom(poUnderlyingFeature);
1908 2 : poFeature->SetFID(nFID);
1909 : }
1910 5 : delete poUnderlyingFeature;
1911 : }
1912 : }
1913 5 : GDALClose(hTileDS);
1914 :
1915 5 : VSIUnlink(osTmpFilename);
1916 :
1917 5 : return poFeature;
1918 : }
1919 :
1920 : /************************************************************************/
1921 : /* InitVector() */
1922 : /************************************************************************/
1923 :
1924 33 : void MBTilesDataset::InitVector(double dfMinX, double dfMinY, double dfMaxX,
1925 : double dfMaxY, bool bZoomLevelFromSpatialFilter,
1926 : bool bJsonField)
1927 : {
1928 33 : const char *pszSQL = "SELECT value FROM metadata WHERE name = 'json'";
1929 33 : CPLDebug("MBTILES", "%s", pszSQL);
1930 66 : CPLJSONDocument oJsonDoc;
1931 66 : CPLJSONDocument oDoc;
1932 33 : auto hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
1933 33 : if (hSQLLyr)
1934 : {
1935 33 : auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
1936 33 : if (hFeat)
1937 : {
1938 33 : auto pszJson = OGR_F_GetFieldAsString(hFeat, 0);
1939 33 : oDoc.GetRoot().Add("json", pszJson);
1940 33 : CPL_IGNORE_RET_VAL(
1941 33 : oJsonDoc.LoadMemory(reinterpret_cast<const GByte *>(pszJson)));
1942 33 : OGR_F_Destroy(hFeat);
1943 : }
1944 33 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
1945 : }
1946 :
1947 : m_osMetadataMemFilename =
1948 33 : VSIMemGenerateHiddenFilename("mbtiles_metadata.json");
1949 33 : oDoc.Save(m_osMetadataMemFilename);
1950 :
1951 66 : CPLJSONArray oVectorLayers;
1952 33 : oVectorLayers.Deinit();
1953 :
1954 66 : CPLJSONArray oTileStatLayers;
1955 33 : oTileStatLayers.Deinit();
1956 :
1957 33 : oVectorLayers = oJsonDoc.GetRoot().GetArray("vector_layers");
1958 :
1959 33 : oTileStatLayers = oJsonDoc.GetRoot().GetArray("tilestats/layers");
1960 :
1961 71 : for (int i = 0; i < oVectorLayers.Size(); i++)
1962 : {
1963 114 : CPLJSONObject oId = oVectorLayers[i].GetObj("id");
1964 38 : if (oId.IsValid() && oId.GetType() == CPLJSONObject::Type::String)
1965 : {
1966 38 : OGRwkbGeometryType eGeomType = wkbUnknown;
1967 38 : if (oTileStatLayers.IsValid())
1968 : {
1969 37 : eGeomType = OGRMVTFindGeomTypeFromTileStat(
1970 74 : oTileStatLayers, oId.ToString().c_str());
1971 : }
1972 :
1973 114 : CPLJSONObject oFields = oVectorLayers[i].GetObj("fields");
1974 : CPLJSONArray oAttributesFromTileStats =
1975 : OGRMVTFindAttributesFromTileStat(oTileStatLayers,
1976 76 : oId.ToString().c_str());
1977 38 : m_apoLayers.push_back(std::make_unique<MBTilesVectorLayer>(
1978 76 : this, oId.ToString().c_str(), oFields, oAttributesFromTileStats,
1979 : bJsonField, dfMinX, dfMinY, dfMaxX, dfMaxY, eGeomType,
1980 : bZoomLevelFromSpatialFilter));
1981 : }
1982 : }
1983 33 : }
1984 :
1985 : /************************************************************************/
1986 : /* Identify() */
1987 : /************************************************************************/
1988 :
1989 75404 : int MBTilesDataset::Identify(GDALOpenInfo *poOpenInfo)
1990 : {
1991 : #ifdef ENABLE_SQL_SQLITE_FORMAT
1992 75404 : if (poOpenInfo->pabyHeader &&
1993 15025 : STARTS_WITH((const char *)poOpenInfo->pabyHeader, "-- SQL MBTILES"))
1994 : {
1995 2 : return TRUE;
1996 : }
1997 : #endif
1998 :
1999 75402 : if ((poOpenInfo->IsExtensionEqualToCI("MBTILES") ||
2000 : // Allow direct Amazon S3 signed URLs that contains .mbtiles in the
2001 : // middle of the URL
2002 75067 : strstr(poOpenInfo->pszFilename, ".mbtiles") != nullptr) &&
2003 150630 : poOpenInfo->nHeaderBytes >= 1024 && poOpenInfo->pabyHeader &&
2004 161 : STARTS_WITH_CI((const char *)poOpenInfo->pabyHeader, "SQLite Format 3"))
2005 : {
2006 161 : return TRUE;
2007 : }
2008 :
2009 75241 : return FALSE;
2010 : }
2011 :
2012 : /************************************************************************/
2013 : /* MBTilesGetMinMaxZoomLevel() */
2014 : /************************************************************************/
2015 :
2016 81 : static int MBTilesGetMinMaxZoomLevel(GDALDatasetH hDS, int bHasMap,
2017 : int &nMinLevel, int &nMaxLevel)
2018 : {
2019 : OGRLayerH hSQLLyr;
2020 : OGRFeatureH hFeat;
2021 81 : int bHasMinMaxLevel = FALSE;
2022 :
2023 81 : const char *pszSQL =
2024 : "SELECT value FROM metadata WHERE name = 'minzoom' UNION ALL "
2025 : "SELECT value FROM metadata WHERE name = 'maxzoom'";
2026 81 : CPLDebug("MBTILES", "%s", pszSQL);
2027 81 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2028 81 : if (hSQLLyr)
2029 : {
2030 81 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2031 81 : if (hFeat)
2032 : {
2033 77 : int bHasMinLevel = FALSE;
2034 77 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
2035 : {
2036 77 : nMinLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
2037 77 : bHasMinLevel = TRUE;
2038 : }
2039 77 : OGR_F_Destroy(hFeat);
2040 :
2041 77 : if (bHasMinLevel)
2042 : {
2043 77 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2044 77 : if (hFeat)
2045 : {
2046 77 : if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
2047 : {
2048 77 : nMaxLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
2049 77 : bHasMinMaxLevel = TRUE;
2050 : }
2051 77 : OGR_F_Destroy(hFeat);
2052 : }
2053 : }
2054 : }
2055 :
2056 81 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2057 : }
2058 :
2059 81 : 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 80 : 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 256 : static double MBTilesWorldCoordToTileCoord(double dfWorldCoord, int nZoomLevel)
2151 : {
2152 256 : return (dfWorldCoord + MAX_GM) / (2 * MAX_GM) * (1 << nZoomLevel);
2153 : }
2154 :
2155 : /************************************************************************/
2156 : /* MBTilesGetBounds() */
2157 : /************************************************************************/
2158 :
2159 80 : static bool MBTilesGetBounds(GDALDatasetH hDS, bool bUseBounds, int nMaxLevel,
2160 : double &minX, double &minY, double &maxX,
2161 : double &maxY)
2162 : {
2163 80 : bool bHasBounds = false;
2164 : OGRLayerH hSQLLyr;
2165 : OGRFeatureH hFeat;
2166 :
2167 80 : if (bUseBounds)
2168 : {
2169 79 : const char *pszSQL = "SELECT value FROM metadata WHERE name = 'bounds'";
2170 79 : CPLDebug("MBTILES", "%s", pszSQL);
2171 79 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2172 79 : if (hSQLLyr)
2173 : {
2174 79 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2175 79 : if (hFeat != nullptr)
2176 : {
2177 77 : const char *pszBounds = OGR_F_GetFieldAsString(hFeat, 0);
2178 77 : char **papszTokens = CSLTokenizeString2(pszBounds, ",", 0);
2179 77 : if (CSLCount(papszTokens) != 4 ||
2180 76 : fabs(CPLAtof(papszTokens[0])) > 180 ||
2181 60 : fabs(CPLAtof(papszTokens[1])) >= 89.99 ||
2182 60 : fabs(CPLAtof(papszTokens[2])) > 180 ||
2183 60 : fabs(CPLAtof(papszTokens[3])) >= 89.99 ||
2184 213 : CPLAtof(papszTokens[0]) > CPLAtof(papszTokens[2]) ||
2185 60 : 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 60 : minX = CPLAtof(papszTokens[0]);
2194 60 : minY = CPLAtof(papszTokens[1]);
2195 60 : maxX = CPLAtof(papszTokens[2]);
2196 60 : maxY = CPLAtof(papszTokens[3]);
2197 60 : LongLatToSphericalMercator(&minX, &minY);
2198 60 : LongLatToSphericalMercator(&maxX, &maxY);
2199 :
2200 : // Clamp northings
2201 60 : if (maxY > MAX_GM)
2202 0 : maxY = MAX_GM;
2203 60 : if (minY < -MAX_GM)
2204 8 : minY = -MAX_GM;
2205 :
2206 60 : bHasBounds = true;
2207 : }
2208 :
2209 77 : CSLDestroy(papszTokens);
2210 :
2211 77 : OGR_F_Destroy(hFeat);
2212 : }
2213 79 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2214 : }
2215 : }
2216 :
2217 80 : 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 80 : 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 64 : 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 64 : VSILFILE *fpCURLOGR = nullptr;
2418 64 : int bFirstSelect = TRUE;
2419 :
2420 64 : int nBands = -1;
2421 64 : nTileSize = 0;
2422 :
2423 : /* Get the VSILFILE associated with the OGR SQLite DB */
2424 128 : CPLString osDSName(GDALGetDescription(hDS));
2425 64 : 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 128 : CPLSPrintf("SELECT tile_data FROM tiles WHERE "
2438 : "tile_column = %d AND tile_row = %d AND zoom_level = %d",
2439 64 : nMinTileCol / 2 + nMaxTileCol / 2,
2440 64 : nMinTileRow / 2 + nMaxTileRow / 2, nMaxLevel);
2441 64 : CPLDebug("MBTILES", "%s", pszSQL);
2442 :
2443 64 : 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 61 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2496 : }
2497 :
2498 : while (true)
2499 : {
2500 81 : if (hSQLLyr == nullptr && bFirstSelect)
2501 : {
2502 17 : bFirstSelect = FALSE;
2503 17 : pszSQL = CPLSPrintf("SELECT tile_data FROM tiles WHERE "
2504 : "zoom_level = %d LIMIT 1",
2505 : nMaxLevel);
2506 17 : CPLDebug("MBTILES", "%s", pszSQL);
2507 17 : hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
2508 17 : if (hSQLLyr == nullptr)
2509 0 : return -1;
2510 : }
2511 :
2512 81 : hFeat = OGR_L_GetNextFeature(hSQLLyr);
2513 81 : if (hFeat == nullptr)
2514 : {
2515 23 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2516 23 : hSQLLyr = nullptr;
2517 23 : if (!bFirstSelect)
2518 6 : return -1;
2519 : }
2520 : else
2521 58 : break;
2522 : }
2523 :
2524 116 : const CPLString osMemFileName(VSIMemGenerateHiddenFilename("mvt_temp.db"));
2525 :
2526 58 : int nDataSize = 0;
2527 58 : GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
2528 :
2529 58 : VSIFCloseL(VSIFileFromMemBuffer(osMemFileName.c_str(), pabyData, nDataSize,
2530 : FALSE));
2531 :
2532 58 : GDALDatasetH hDSTile = GDALOpenEx(osMemFileName.c_str(), GDAL_OF_RASTER,
2533 : apszAllowedDrivers, nullptr, nullptr);
2534 58 : 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 30 : nBands = GDALGetRasterCount(hDSTile);
2543 :
2544 17 : if ((nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4) ||
2545 77 : GDALGetRasterXSize(hDSTile) != GDALGetRasterYSize(hDSTile) ||
2546 30 : GDALGetRasterDataType(GDALGetRasterBand(hDSTile, 1)) != GDT_UInt8)
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 30 : nTileSize = GDALGetRasterXSize(hDSTile);
2558 : GDALColorTableH hCT =
2559 30 : GDALGetRasterColorTable(GDALGetRasterBand(hDSTile, 1));
2560 30 : 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 30 : GDALClose(hDSTile);
2573 30 : VSIUnlink(osMemFileName.c_str());
2574 30 : OGR_F_Destroy(hFeat);
2575 30 : GDALDatasetReleaseResultSet(hDS, hSQLLyr);
2576 :
2577 30 : return nBands;
2578 : }
2579 :
2580 : /************************************************************************/
2581 : /* Open() */
2582 : /************************************************************************/
2583 :
2584 81 : GDALDataset *MBTilesDataset::Open(GDALOpenInfo *poOpenInfo)
2585 : {
2586 162 : CPLString osFileName;
2587 162 : CPLString osTableName;
2588 :
2589 81 : if (!Identify(poOpenInfo))
2590 0 : return nullptr;
2591 :
2592 81 : if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
2593 53 : (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
2594 16 : (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 81 : MBTILESOpenSQLiteDB(poOpenInfo->pszFilename, poOpenInfo->eAccess);
2605 :
2606 81 : MBTilesDataset *poDS = nullptr;
2607 :
2608 81 : if (hDS == nullptr)
2609 0 : goto end;
2610 :
2611 : /* -------------------------------------------------------------------- */
2612 : /* Build dataset */
2613 : /* -------------------------------------------------------------------- */
2614 : {
2615 81 : CPLString osMetadataTableName, osRasterTableName;
2616 81 : CPLString osSQL;
2617 : OGRLayerH hMetadataLyr, hRasterLyr;
2618 : OGRFeatureH hFeat;
2619 : int nBands;
2620 81 : OGRLayerH hSQLLyr = nullptr;
2621 81 : int nMinLevel = -1;
2622 81 : int nMaxLevel = -1;
2623 81 : int bHasMinMaxLevel = FALSE;
2624 : int bHasMap;
2625 :
2626 81 : osMetadataTableName = "metadata";
2627 :
2628 : hMetadataLyr =
2629 81 : GDALDatasetGetLayerByName(hDS, osMetadataTableName.c_str());
2630 81 : if (hMetadataLyr == nullptr)
2631 0 : goto end;
2632 :
2633 81 : osRasterTableName += "tiles";
2634 :
2635 81 : hRasterLyr = GDALDatasetGetLayerByName(hDS, osRasterTableName.c_str());
2636 81 : if (hRasterLyr == nullptr)
2637 0 : goto end;
2638 :
2639 81 : bHasMap = GDALDatasetGetLayerByName(hDS, "map") != nullptr;
2640 81 : 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 81 : MBTilesGetMinMaxZoomLevel(hDS, bHasMap, nMinLevel, nMaxLevel);
2676 :
2677 : const char *pszZoomLevel =
2678 81 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "ZOOM_LEVEL");
2679 81 : if (pszZoomLevel != nullptr)
2680 0 : nMaxLevel = atoi(pszZoomLevel);
2681 :
2682 81 : 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 81 : 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 81 : 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 80 : double dfMinX = 0.0;
2711 80 : double dfMinY = 0.0;
2712 80 : double dfMaxX = 0.0;
2713 80 : double dfMaxY = 0.0;
2714 160 : bool bUseBounds = CPLFetchBool(
2715 80 : const_cast<const char **>(poOpenInfo->papszOpenOptions),
2716 : "USE_BOUNDS", true);
2717 : const char *pszMinX =
2718 80 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINX");
2719 : const char *pszMinY =
2720 80 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINY");
2721 : const char *pszMaxX =
2722 80 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXX");
2723 : const char *pszMaxY =
2724 80 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXY");
2725 : bool bHasBounds;
2726 80 : if (pszMinX != nullptr && pszMinY != nullptr && pszMaxX != nullptr &&
2727 : pszMaxY != nullptr)
2728 : {
2729 0 : bHasBounds = true;
2730 : }
2731 : else
2732 : {
2733 80 : bHasBounds = MBTilesGetBounds(hDS, bUseBounds, nMaxLevel, dfMinX,
2734 : dfMinY, dfMaxX, dfMaxY);
2735 : }
2736 80 : if (!bHasBounds)
2737 : {
2738 16 : CPLError(CE_Failure, CPLE_AppDefined,
2739 : "Cannot find min and max tile numbers");
2740 16 : goto end;
2741 : }
2742 64 : if (pszMinX != nullptr)
2743 0 : dfMinX = CPLAtof(pszMinX);
2744 64 : if (pszMinY != nullptr)
2745 0 : dfMinY = CPLAtof(pszMinY);
2746 64 : if (pszMaxX != nullptr)
2747 0 : dfMaxX = CPLAtof(pszMaxX);
2748 64 : if (pszMaxY != nullptr)
2749 0 : dfMaxY = CPLAtof(pszMaxY);
2750 :
2751 : /* --------------------------------------------------------------------
2752 : */
2753 : /* Get number of bands */
2754 : /* --------------------------------------------------------------------
2755 : */
2756 : int nMinTileCol =
2757 64 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinX, nMaxLevel));
2758 : int nMinTileRow =
2759 64 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinY, nMaxLevel));
2760 : int nMaxTileCol =
2761 64 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxX, nMaxLevel));
2762 : int nMaxTileRow =
2763 64 : static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxY, nMaxLevel));
2764 64 : int nTileSize = 0;
2765 128 : nBands = MBTilesGetBandCountAndTileSize(
2766 64 : STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"), hDS,
2767 : nMaxLevel, nMinTileRow, nMaxTileRow, nMinTileCol, nMaxTileCol,
2768 : nTileSize);
2769 64 : bool bFoundRasterTile = nBands > 0;
2770 64 : if (!bFoundRasterTile)
2771 34 : nTileSize = knDEFAULT_BLOCK_SIZE;
2772 :
2773 : // Force 4 bands by default (see #6119)
2774 64 : nBands = 4;
2775 :
2776 64 : const char *pszBandCount = CSLFetchNameValueDef(
2777 64 : poOpenInfo->papszOpenOptions, "BAND_COUNT",
2778 : CPLGetConfigOption("MBTILES_BAND_COUNT", nullptr));
2779 64 : if (pszBandCount)
2780 : {
2781 1 : int nTmpBands = atoi(pszBandCount);
2782 1 : if (nTmpBands >= 1 && nTmpBands <= 4)
2783 1 : nBands = nTmpBands;
2784 : }
2785 :
2786 64 : 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 64 : poDS = new MBTilesDataset();
2799 64 : poDS->eAccess = poOpenInfo->eAccess;
2800 64 : poDS->hDS = hDS;
2801 64 : poDS->hDB = (sqlite3 *)GDALGetInternalHandle((GDALDatasetH)hDS,
2802 : "SQLITE_HANDLE");
2803 64 : CPLAssert(poDS->hDB != nullptr);
2804 :
2805 : /* poDS will release it from now */
2806 64 : hDS = nullptr;
2807 :
2808 : poDS->m_osClip =
2809 64 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CLIP", "");
2810 64 : poDS->m_nMinZoomLevel = nMinLevel;
2811 64 : bool bRasterOK = poDS->InitRaster(nullptr, nMaxLevel, nBands, nTileSize,
2812 : dfMinX, dfMinY, dfMaxX, dfMaxY);
2813 :
2814 64 : const char *pszFormat = poDS->GetMetadataItem("format");
2815 64 : if (pszFormat != nullptr && EQUAL(pszFormat, "pbf"))
2816 : {
2817 34 : 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 66 : poDS->InitVector(dfMinX, dfMinY, dfMaxX, dfMaxY,
2825 33 : CPLFetchBool(poOpenInfo->papszOpenOptions,
2826 : "ZOOM_LEVEL_AUTO",
2827 33 : CPLTestBool(CPLGetConfigOption(
2828 : "MVT_ZOOM_LEVEL_AUTO", "NO"))),
2829 33 : CPLFetchBool(poOpenInfo->papszOpenOptions,
2830 : "JSON_FIELD", false));
2831 : }
2832 30 : else if ((pszFormat != nullptr && !EQUAL(pszFormat, "pbf")) ||
2833 : bFoundRasterTile)
2834 : {
2835 30 : 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 62 : if ((pszFormat == nullptr || !EQUAL(pszFormat, "pbf")) && !bRasterOK)
2845 : {
2846 0 : delete poDS;
2847 0 : return nullptr;
2848 : }
2849 :
2850 62 : 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 75 : for (int iLevel = nMaxLevel - 1; iLevel >= nMinLevel; iLevel--)
2890 : {
2891 45 : MBTilesDataset *poOvrDS = new MBTilesDataset();
2892 45 : poOvrDS->ShareLockWithParentDataset(poDS);
2893 45 : poOvrDS->InitRaster(poDS, iLevel, nBands, nTileSize, dfMinX, dfMinY,
2894 : dfMaxX, dfMaxY);
2895 :
2896 90 : poDS->m_papoOverviewDS = (MBTilesDataset **)CPLRealloc(
2897 45 : poDS->m_papoOverviewDS,
2898 45 : sizeof(MBTilesDataset *) * (poDS->m_nOverviewCount + 1));
2899 45 : poDS->m_papoOverviewDS[poDS->m_nOverviewCount++] = poOvrDS;
2900 :
2901 77 : if (poOvrDS->GetRasterXSize() < 256 &&
2902 32 : poOvrDS->GetRasterYSize() < 256)
2903 : {
2904 32 : break;
2905 : }
2906 : }
2907 :
2908 : /* --------------------------------------------------------------------
2909 : */
2910 : /* Initialize any PAM information. */
2911 : /* --------------------------------------------------------------------
2912 : */
2913 62 : poDS->SetDescription(poOpenInfo->pszFilename);
2914 :
2915 62 : if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"))
2916 59 : poDS->TryLoadXML();
2917 : else
2918 : {
2919 3 : poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
2920 : }
2921 : }
2922 :
2923 79 : end:
2924 79 : if (hDS)
2925 17 : GDALClose(hDS);
2926 :
2927 79 : return poDS;
2928 : }
2929 :
2930 : /************************************************************************/
2931 : /* Create() */
2932 : /************************************************************************/
2933 :
2934 93 : GDALDataset *MBTilesDataset::Create(const char *pszFilename, int nXSize,
2935 : int nYSize, int nBandsIn, GDALDataType eDT,
2936 : CSLConstList papszOptions)
2937 : {
2938 : #ifdef HAVE_MVT_WRITE_SUPPORT
2939 93 : 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 52 : MBTilesDataset *poDS = new MBTilesDataset();
2951 52 : if (!poDS->CreateInternal(pszFilename, nXSize, nYSize, nBandsIn, eDT,
2952 : papszOptions))
2953 : {
2954 14 : delete poDS;
2955 14 : poDS = nullptr;
2956 : }
2957 52 : return poDS;
2958 : }
2959 :
2960 : /************************************************************************/
2961 : /* CreateInternal() */
2962 : /************************************************************************/
2963 :
2964 52 : bool MBTilesDataset::CreateInternal(const char *pszFilename, int nXSize,
2965 : int nYSize, int nBandsIn, GDALDataType eDT,
2966 : CSLConstList papszOptions)
2967 : {
2968 52 : if (eDT != GDT_UInt8)
2969 : {
2970 0 : CPLError(CE_Failure, CPLE_NotSupported, "Only Byte supported");
2971 0 : return false;
2972 : }
2973 52 : 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 52 : m_bPNGSupports2Bands =
2983 52 : CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_2BANDS", "TRUE"));
2984 52 : m_bPNGSupportsCT =
2985 52 : CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_CT", "TRUE"));
2986 52 : m_bWriteBounds = CPLFetchBool(const_cast<const char **>(papszOptions),
2987 : "WRITE_BOUNDS", true);
2988 52 : m_bWriteMinMaxZoom = CPLFetchBool(const_cast<const char **>(papszOptions),
2989 : "WRITE_MINMAXZOOM", true);
2990 : int nBlockSize = std::max(
2991 52 : 64, std::min(8192, atoi(CSLFetchNameValueDef(
2992 : papszOptions, "BLOCKSIZE",
2993 52 : CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
2994 52 : m_osBounds = CSLFetchNameValueDef(papszOptions, "BOUNDS", "");
2995 52 : m_osCenter = CSLFetchNameValueDef(papszOptions, "CENTER", "");
2996 :
2997 52 : VSIUnlink(pszFilename);
2998 52 : SetDescription(pszFilename);
2999 :
3000 : int rc;
3001 52 : if (STARTS_WITH(pszFilename, "/vsi"))
3002 : {
3003 26 : pMyVFS = OGRSQLiteCreateVFS(nullptr, nullptr);
3004 26 : sqlite3_vfs_register(pMyVFS, 0);
3005 26 : rc = sqlite3_open_v2(pszFilename, &hDB,
3006 : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
3007 26 : pMyVFS->zName);
3008 : }
3009 : else
3010 : {
3011 26 : rc = sqlite3_open(pszFilename, &hDB);
3012 : }
3013 :
3014 52 : if (rc != SQLITE_OK)
3015 : {
3016 4 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s", pszFilename);
3017 4 : return false;
3018 : }
3019 :
3020 48 : sqlite3_exec(hDB, "PRAGMA synchronous = OFF", nullptr, nullptr, nullptr);
3021 :
3022 48 : 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 48 : if (rc != SQLITE_OK)
3031 : {
3032 8 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create tiles table");
3033 8 : return false;
3034 : }
3035 :
3036 40 : rc = sqlite3_exec(hDB, "CREATE TABLE metadata (name TEXT, value TEXT)",
3037 : nullptr, nullptr, nullptr);
3038 40 : 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 114 : papszOptions, "NAME", CPLGetBasenameSafe(pszFilename).c_str());
3046 38 : char *pszSQL = sqlite3_mprintf(
3047 : "INSERT INTO metadata (name, value) VALUES ('name', '%q')",
3048 : osName.c_str());
3049 38 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3050 38 : sqlite3_free(pszSQL);
3051 :
3052 38 : const char *pszType = CSLFetchNameValueDef(papszOptions, "TYPE", "overlay");
3053 38 : pszSQL = sqlite3_mprintf(
3054 : "INSERT INTO metadata (name, value) VALUES ('type', '%q')", pszType);
3055 38 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3056 38 : sqlite3_free(pszSQL);
3057 :
3058 : const std::string osDescription = CSLFetchNameValueDef(
3059 114 : papszOptions, "DESCRIPTION", CPLGetBasenameSafe(pszFilename).c_str());
3060 38 : pszSQL = sqlite3_mprintf(
3061 : "INSERT INTO metadata (name, value) VALUES ('description', '%q')",
3062 : osDescription.c_str());
3063 38 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3064 38 : sqlite3_free(pszSQL);
3065 :
3066 : const std::string osElevationType =
3067 76 : CSLFetchNameValueDef(papszOptions, "ELEVATION_TYPE", "");
3068 38 : if (!osElevationType.empty())
3069 : {
3070 0 : pszSQL = sqlite3_mprintf("INSERT INTO metadata (name, value) VALUES "
3071 : "('elevation_type', '%q')",
3072 : osElevationType.c_str());
3073 0 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3074 0 : sqlite3_free(pszSQL);
3075 : }
3076 :
3077 38 : const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
3078 38 : if (pszTF)
3079 13 : m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
3080 :
3081 38 : const char *pszVersion = CSLFetchNameValueDef(
3082 38 : papszOptions, "VERSION", (m_eTF == GPKG_TF_WEBP) ? "1.3" : "1.1");
3083 38 : pszSQL = sqlite3_mprintf(
3084 : "INSERT INTO metadata (name, value) VALUES ('version', '%q')",
3085 : pszVersion);
3086 38 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3087 38 : sqlite3_free(pszSQL);
3088 :
3089 38 : const char *pszFormat = CSLFetchNameValueDef(
3090 : papszOptions, "FORMAT", GDALMBTilesGetTileFormatName(m_eTF));
3091 38 : pszSQL = sqlite3_mprintf(
3092 : "INSERT INTO metadata (name, value) VALUES ('format', '%q')",
3093 : pszFormat);
3094 38 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3095 38 : sqlite3_free(pszSQL);
3096 :
3097 38 : m_bNew = true;
3098 38 : eAccess = GA_Update;
3099 38 : nRasterXSize = nXSize;
3100 38 : nRasterYSize = nYSize;
3101 :
3102 38 : m_pabyCachedTiles =
3103 38 : (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nBlockSize, nBlockSize);
3104 38 : if (m_pabyCachedTiles == nullptr)
3105 : {
3106 0 : return false;
3107 : }
3108 :
3109 123 : for (int i = 1; i <= nBandsIn; i++)
3110 85 : SetBand(i, new MBTilesBand(this, nBlockSize));
3111 :
3112 38 : ParseCompressionOptions(papszOptions);
3113 :
3114 38 : return true;
3115 : }
3116 :
3117 : /************************************************************************/
3118 : /* CreateCopy() */
3119 : /************************************************************************/
3120 :
3121 : typedef struct
3122 : {
3123 : const char *pszName;
3124 : GDALResampleAlg eResampleAlg;
3125 : } WarpResamplingAlg;
3126 :
3127 : static const WarpResamplingAlg asResamplingAlg[] = {
3128 : {"NEAREST", GRA_NearestNeighbour},
3129 : {"BILINEAR", GRA_Bilinear},
3130 : {"CUBIC", GRA_Cubic},
3131 : {"CUBICSPLINE", GRA_CubicSpline},
3132 : {"LANCZOS", GRA_Lanczos},
3133 : {"MODE", GRA_Mode},
3134 : {"AVERAGE", GRA_Average},
3135 : {"RMS", GRA_RMS},
3136 : };
3137 :
3138 49 : GDALDataset *MBTilesDataset::CreateCopy(const char *pszFilename,
3139 : GDALDataset *poSrcDS, int /*bStrict*/,
3140 : CSLConstList papszOptions,
3141 : GDALProgressFunc pfnProgress,
3142 : void *pProgressData)
3143 : {
3144 :
3145 49 : int nBands = poSrcDS->GetRasterCount();
3146 49 : if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
3147 : {
3148 2 : CPLError(CE_Failure, CPLE_NotSupported,
3149 : "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 "
3150 : "(RGBA) band dataset supported");
3151 2 : return nullptr;
3152 : }
3153 :
3154 47 : char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", SRS_EPSG_3857);
3155 :
3156 47 : void *hTransformArg = nullptr;
3157 :
3158 : // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
3159 : // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
3160 : // EPSG:3857.
3161 47 : GDALGeoTransform srcGT;
3162 47 : std::unique_ptr<GDALDataset> poTmpDS;
3163 47 : bool bModifiedMaxLat = false;
3164 47 : bool bModifiedMinLat = false;
3165 47 : const auto poSrcSRS = poSrcDS->GetSpatialRef();
3166 94 : if (poSrcDS->GetGeoTransform(srcGT) == CE_None && srcGT[2] == 0 &&
3167 94 : srcGT[4] == 0 && srcGT[5] < 0)
3168 : {
3169 47 : if (poSrcSRS && poSrcSRS->IsGeographic())
3170 : {
3171 31 : double maxLat = srcGT[3];
3172 31 : double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
3173 : // Corresponds to the latitude of MAX_GM
3174 31 : constexpr double MAX_LAT = 85.0511287798066;
3175 31 : if (maxLat > MAX_LAT)
3176 : {
3177 3 : maxLat = MAX_LAT;
3178 3 : bModifiedMaxLat = true;
3179 : }
3180 31 : if (minLat < -MAX_LAT)
3181 : {
3182 3 : minLat = -MAX_LAT;
3183 3 : bModifiedMinLat = true;
3184 : }
3185 31 : if (bModifiedMaxLat || bModifiedMinLat)
3186 : {
3187 6 : CPLStringList aosOptions;
3188 3 : aosOptions.AddString("-of");
3189 3 : aosOptions.AddString("VRT");
3190 3 : aosOptions.AddString("-projwin");
3191 3 : aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
3192 3 : aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
3193 : aosOptions.AddString(CPLSPrintf(
3194 3 : "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
3195 3 : aosOptions.AddString(CPLSPrintf("%.17g", minLat));
3196 : auto psOptions =
3197 3 : GDALTranslateOptionsNew(aosOptions.List(), nullptr);
3198 3 : poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
3199 : "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
3200 3 : GDALTranslateOptionsFree(psOptions);
3201 3 : if (poTmpDS)
3202 : {
3203 3 : hTransformArg = GDALCreateGenImgProjTransformer2(
3204 3 : GDALDataset::FromHandle(poTmpDS.get()), nullptr,
3205 : papszTO);
3206 : }
3207 : }
3208 : }
3209 : }
3210 47 : if (hTransformArg == nullptr)
3211 : {
3212 : hTransformArg =
3213 44 : GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
3214 : }
3215 47 : if (hTransformArg == nullptr)
3216 : {
3217 0 : CSLDestroy(papszTO);
3218 0 : return nullptr;
3219 : }
3220 :
3221 47 : GDALTransformerInfo *psInfo = (GDALTransformerInfo *)hTransformArg;
3222 47 : GDALGeoTransform gt;
3223 : double adfExtent[4];
3224 : int nXSize, nYSize;
3225 :
3226 47 : if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
3227 : gt.data(), &nXSize, &nYSize, adfExtent,
3228 47 : 0) != CE_None)
3229 : {
3230 0 : CSLDestroy(papszTO);
3231 0 : GDALDestroyGenImgProjTransformer(hTransformArg);
3232 0 : return nullptr;
3233 : }
3234 :
3235 47 : GDALDestroyGenImgProjTransformer(hTransformArg);
3236 47 : hTransformArg = nullptr;
3237 47 : poTmpDS.reset();
3238 :
3239 47 : if (bModifiedMaxLat || bModifiedMinLat)
3240 : {
3241 3 : if (bModifiedMaxLat)
3242 : {
3243 3 : const double maxNorthing = MAX_GM;
3244 3 : gt.yorig = maxNorthing;
3245 3 : adfExtent[3] = maxNorthing;
3246 : }
3247 3 : if (bModifiedMinLat)
3248 : {
3249 3 : const double minNorthing = -MAX_GM;
3250 3 : adfExtent[1] = minNorthing;
3251 : }
3252 :
3253 3 : if (poSrcSRS && poSrcSRS->IsGeographic())
3254 : {
3255 3 : if (srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1] == 180)
3256 : {
3257 3 : adfExtent[2] = MAX_GM;
3258 : }
3259 : }
3260 : }
3261 :
3262 : int nZoomLevel;
3263 47 : double dfComputedRes = gt.xscale;
3264 47 : double dfPrevRes = 0.0;
3265 47 : double dfRes = 0.0;
3266 : int nBlockSize = std::max(
3267 47 : 64, std::min(8192, atoi(CSLFetchNameValueDef(
3268 : papszOptions, "BLOCKSIZE",
3269 47 : CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
3270 47 : const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockSize;
3271 444 : for (nZoomLevel = 0; nZoomLevel < 25; nZoomLevel++)
3272 : {
3273 444 : dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
3274 444 : if (dfComputedRes > dfRes)
3275 47 : break;
3276 397 : dfPrevRes = dfRes;
3277 : }
3278 47 : if (nZoomLevel == 25)
3279 : {
3280 0 : CPLError(CE_Failure, CPLE_AppDefined,
3281 : "Could not find an appropriate zoom level");
3282 0 : CSLDestroy(papszTO);
3283 0 : return nullptr;
3284 : }
3285 :
3286 : const char *pszZoomLevelStrategy =
3287 47 : CSLFetchNameValueDef(papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
3288 47 : if (fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
3289 : {
3290 47 : if (EQUAL(pszZoomLevelStrategy, "LOWER"))
3291 : {
3292 3 : if (nZoomLevel > 0)
3293 3 : nZoomLevel--;
3294 : }
3295 44 : else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
3296 : {
3297 : /* do nothing */
3298 : }
3299 44 : else if (nZoomLevel > 0)
3300 : {
3301 43 : if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
3302 41 : nZoomLevel--;
3303 : }
3304 : }
3305 :
3306 47 : dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
3307 :
3308 47 : double dfMinX = adfExtent[0];
3309 47 : double dfMinY = adfExtent[1];
3310 47 : double dfMaxX = adfExtent[2];
3311 47 : double dfMaxY = adfExtent[3];
3312 :
3313 47 : nXSize = (int)(0.5 + (dfMaxX - dfMinX) / dfRes);
3314 47 : nYSize = (int)(0.5 + (dfMaxY - dfMinY) / dfRes);
3315 47 : gt.xscale = dfRes;
3316 47 : gt.yscale = -dfRes;
3317 :
3318 47 : int nTargetBands = nBands;
3319 : /* For grey level or RGB, if there's reprojection involved, add an alpha */
3320 : /* channel */
3321 80 : if ((nBands == 1 &&
3322 47 : poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
3323 : nBands == 3)
3324 : {
3325 86 : OGRSpatialReference oSrcSRS;
3326 43 : oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
3327 43 : oSrcSRS.AutoIdentifyEPSG();
3328 60 : if (oSrcSRS.GetAuthorityCode() == nullptr ||
3329 17 : atoi(oSrcSRS.GetAuthorityCode()) != 3857)
3330 : {
3331 33 : nTargetBands++;
3332 : }
3333 : }
3334 :
3335 47 : GDALResampleAlg eResampleAlg = GRA_Bilinear;
3336 47 : const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
3337 47 : if (pszResampling)
3338 : {
3339 4 : for (size_t iAlg = 0;
3340 4 : iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
3341 : iAlg++)
3342 : {
3343 4 : if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
3344 : {
3345 4 : eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
3346 4 : break;
3347 : }
3348 : }
3349 : }
3350 :
3351 33 : if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
3352 80 : eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
3353 : {
3354 0 : CPLError(
3355 : CE_Warning, CPLE_AppDefined,
3356 : "Input dataset has a color table, which will likely lead to "
3357 : "bad results when using a resampling method other than "
3358 : "nearest neighbour or mode. Converting the dataset to 24/32 bit "
3359 : "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
3360 : }
3361 :
3362 47 : GDALDataset *poDS = Create(pszFilename, nXSize, nYSize, nTargetBands,
3363 : GDT_UInt8, papszOptions);
3364 47 : if (poDS == nullptr)
3365 : {
3366 14 : CSLDestroy(papszTO);
3367 14 : return nullptr;
3368 : }
3369 33 : poDS->SetGeoTransform(gt);
3370 35 : if (nTargetBands == 1 && nBands == 1 &&
3371 2 : poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
3372 : {
3373 4 : poDS->GetRasterBand(1)->SetColorTable(
3374 2 : poSrcDS->GetRasterBand(1)->GetColorTable());
3375 : }
3376 :
3377 33 : hTransformArg = GDALCreateGenImgProjTransformer2(poSrcDS, poDS, papszTO);
3378 33 : CSLDestroy(papszTO);
3379 33 : if (hTransformArg == nullptr)
3380 : {
3381 0 : CPLError(CE_Failure, CPLE_AppDefined,
3382 : "GDALCreateGenImgProjTransformer2 failed");
3383 0 : delete poDS;
3384 0 : return nullptr;
3385 : }
3386 :
3387 : /* -------------------------------------------------------------------- */
3388 : /* Warp the transformer with a linear approximator */
3389 : /* -------------------------------------------------------------------- */
3390 33 : hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
3391 : hTransformArg, 0.125);
3392 33 : GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
3393 :
3394 : /* -------------------------------------------------------------------- */
3395 : /* Setup warp options. */
3396 : /* -------------------------------------------------------------------- */
3397 33 : GDALWarpOptions *psWO = GDALCreateWarpOptions();
3398 :
3399 33 : psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
3400 33 : psWO->eWorkingDataType = GDT_UInt8;
3401 :
3402 33 : psWO->eResampleAlg = eResampleAlg;
3403 :
3404 33 : psWO->hSrcDS = poSrcDS;
3405 33 : psWO->hDstDS = poDS;
3406 :
3407 33 : psWO->pfnTransformer = GDALApproxTransform;
3408 33 : psWO->pTransformerArg = hTransformArg;
3409 :
3410 33 : psWO->pfnProgress = pfnProgress;
3411 33 : psWO->pProgressArg = pProgressData;
3412 :
3413 : /* -------------------------------------------------------------------- */
3414 : /* Setup band mapping. */
3415 : /* -------------------------------------------------------------------- */
3416 :
3417 33 : if (nBands == 2 || nBands == 4)
3418 2 : psWO->nBandCount = nBands - 1;
3419 : else
3420 31 : psWO->nBandCount = nBands;
3421 :
3422 33 : psWO->panSrcBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
3423 33 : psWO->panDstBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
3424 :
3425 92 : for (int i = 0; i < psWO->nBandCount; i++)
3426 : {
3427 59 : psWO->panSrcBands[i] = i + 1;
3428 59 : psWO->panDstBands[i] = i + 1;
3429 : }
3430 :
3431 33 : if (nBands == 2 || nBands == 4)
3432 : {
3433 2 : psWO->nSrcAlphaBand = nBands;
3434 : }
3435 33 : if (nTargetBands == 2 || nTargetBands == 4)
3436 : {
3437 21 : psWO->nDstAlphaBand = nTargetBands;
3438 : }
3439 :
3440 : /* -------------------------------------------------------------------- */
3441 : /* Initialize and execute the warp. */
3442 : /* -------------------------------------------------------------------- */
3443 33 : GDALWarpOperation oWO;
3444 :
3445 33 : CPLErr eErr = oWO.Initialize(psWO);
3446 33 : if (eErr == CE_None)
3447 : {
3448 : /*if( bMulti )
3449 : eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
3450 : else*/
3451 33 : eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
3452 : }
3453 33 : if (eErr != CE_None)
3454 : {
3455 0 : delete poDS;
3456 0 : poDS = nullptr;
3457 : }
3458 :
3459 33 : GDALDestroyTransformer(hTransformArg);
3460 33 : GDALDestroyWarpOptions(psWO);
3461 :
3462 33 : return poDS;
3463 : }
3464 :
3465 : /************************************************************************/
3466 : /* ParseCompressionOptions() */
3467 : /************************************************************************/
3468 :
3469 42 : void MBTilesDataset::ParseCompressionOptions(CSLConstList papszOptions)
3470 : {
3471 42 : const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
3472 42 : if (pszZLevel)
3473 0 : m_nZLevel = atoi(pszZLevel);
3474 :
3475 42 : const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
3476 42 : if (pszQuality)
3477 2 : m_nQuality = atoi(pszQuality);
3478 :
3479 42 : const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
3480 42 : if (pszDither)
3481 1 : m_bDither = CPLTestBool(pszDither);
3482 42 : }
3483 :
3484 : /************************************************************************/
3485 : /* IBuildOverviews() */
3486 : /************************************************************************/
3487 :
3488 8 : static int GetFloorPowerOfTwo(int n)
3489 : {
3490 8 : int p2 = 1;
3491 20 : while ((n = n >> 1) > 0)
3492 : {
3493 12 : p2 <<= 1;
3494 : }
3495 8 : return p2;
3496 : }
3497 :
3498 7 : CPLErr MBTilesDataset::IBuildOverviews(
3499 : const char *pszResampling, int nOverviews, const int *panOverviewList,
3500 : int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
3501 : void *pProgressData, CSLConstList papszOptions)
3502 : {
3503 7 : if (GetAccess() != GA_Update)
3504 : {
3505 0 : CPLError(CE_Failure, CPLE_NotSupported,
3506 : "Overview building not supported on a database opened in "
3507 : "read-only mode");
3508 0 : return CE_Failure;
3509 : }
3510 7 : if (m_poParentDS != nullptr)
3511 : {
3512 0 : CPLError(CE_Failure, CPLE_NotSupported,
3513 : "Overview building not supported on overview dataset");
3514 0 : return CE_Failure;
3515 : }
3516 :
3517 7 : if (nOverviews == 0)
3518 : {
3519 2 : for (int i = 0; i < m_nOverviewCount; i++)
3520 1 : m_papoOverviewDS[i]->FlushCache(false);
3521 1 : char *pszSQL = sqlite3_mprintf(
3522 : "DELETE FROM 'tiles' WHERE zoom_level < %d", m_nZoomLevel);
3523 1 : char *pszErrMsg = nullptr;
3524 1 : int ret = sqlite3_exec(hDB, pszSQL, nullptr, nullptr, &pszErrMsg);
3525 1 : sqlite3_free(pszSQL);
3526 1 : if (ret != SQLITE_OK)
3527 : {
3528 0 : CPLError(CE_Failure, CPLE_AppDefined, "Failure: %s",
3529 0 : pszErrMsg ? pszErrMsg : "");
3530 0 : sqlite3_free(pszErrMsg);
3531 0 : return CE_Failure;
3532 : }
3533 :
3534 1 : int nRows = 0;
3535 1 : int nCols = 0;
3536 1 : char **papszResult = nullptr;
3537 1 : sqlite3_get_table(
3538 : hDB, "SELECT * FROM metadata WHERE name = 'minzoom' LIMIT 2",
3539 : &papszResult, &nRows, &nCols, nullptr);
3540 1 : sqlite3_free_table(papszResult);
3541 1 : if (nRows == 1)
3542 : {
3543 1 : pszSQL = sqlite3_mprintf(
3544 : "UPDATE metadata SET value = %d WHERE name = 'minzoom'",
3545 : m_nZoomLevel);
3546 1 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3547 1 : sqlite3_free(pszSQL);
3548 : }
3549 :
3550 1 : return CE_None;
3551 : }
3552 :
3553 6 : if (nBandsIn != nBands)
3554 : {
3555 0 : CPLError(CE_Failure, CPLE_NotSupported,
3556 : "Generation of overviews only"
3557 : "supported when operating on all bands.");
3558 0 : return CE_Failure;
3559 : }
3560 :
3561 6 : if (m_nOverviewCount == 0)
3562 : {
3563 0 : CPLError(CE_Failure, CPLE_AppDefined,
3564 : "Image too small to support overviews");
3565 0 : return CE_Failure;
3566 : }
3567 :
3568 6 : FlushCache(false);
3569 :
3570 44 : const auto GetOverviewIndex = [](int nVal)
3571 : {
3572 44 : int iOvr = -1;
3573 111 : while (nVal > 1)
3574 : {
3575 67 : nVal >>= 1;
3576 67 : iOvr++;
3577 : }
3578 44 : return iOvr;
3579 : };
3580 :
3581 14 : for (int i = 0; i < nOverviews; i++)
3582 : {
3583 8 : if (panOverviewList[i] < 2)
3584 : {
3585 0 : CPLError(CE_Failure, CPLE_IllegalArg,
3586 0 : "Overview factor '%d' must be >= 2", panOverviewList[i]);
3587 0 : return CE_Failure;
3588 : }
3589 :
3590 8 : if (GetFloorPowerOfTwo(panOverviewList[i]) != panOverviewList[i])
3591 : {
3592 0 : CPLError(CE_Failure, CPLE_IllegalArg,
3593 : "Overview factor '%d' is not a power of 2",
3594 0 : panOverviewList[i]);
3595 0 : return CE_Failure;
3596 : }
3597 8 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3598 8 : if (iOvr >= m_nOverviewCount)
3599 : {
3600 1 : CPLDebug("MBTILES",
3601 : "Requested overview factor %d leads to too small overview "
3602 : "and will be ignored",
3603 1 : panOverviewList[i]);
3604 : }
3605 : }
3606 :
3607 : GDALRasterBand ***papapoOverviewBands =
3608 6 : (GDALRasterBand ***)CPLCalloc(sizeof(void *), nBands);
3609 6 : int iCurOverview = 0;
3610 27 : for (int iBand = 0; iBand < nBands; iBand++)
3611 : {
3612 42 : papapoOverviewBands[iBand] =
3613 21 : (GDALRasterBand **)CPLCalloc(sizeof(void *), nOverviews);
3614 21 : iCurOverview = 0;
3615 49 : for (int i = 0; i < nOverviews; i++)
3616 : {
3617 28 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3618 28 : if (iOvr < m_nOverviewCount)
3619 : {
3620 24 : MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
3621 48 : papapoOverviewBands[iBand][iCurOverview] =
3622 24 : poODS->GetRasterBand(iBand + 1);
3623 24 : iCurOverview++;
3624 : }
3625 : }
3626 : }
3627 :
3628 12 : CPLErr eErr = GDALRegenerateOverviewsMultiBand(
3629 6 : nBands, papoBands, iCurOverview, papapoOverviewBands, pszResampling,
3630 : pfnProgress, pProgressData, papszOptions);
3631 :
3632 27 : for (int iBand = 0; iBand < nBands; iBand++)
3633 : {
3634 21 : CPLFree(papapoOverviewBands[iBand]);
3635 : }
3636 6 : CPLFree(papapoOverviewBands);
3637 :
3638 6 : if (eErr == CE_None)
3639 : {
3640 : // Determine new minzoom value from the existing one and the new
3641 : // requested overview levels
3642 6 : int nMinZoom = m_nZoomLevel;
3643 6 : bool bHasMinZoomMetadata = false;
3644 6 : int nRows = 0;
3645 6 : int nCols = 0;
3646 6 : char **papszResult = nullptr;
3647 6 : sqlite3_get_table(
3648 : hDB, "SELECT value FROM metadata WHERE name = 'minzoom' LIMIT 2",
3649 : &papszResult, &nRows, &nCols, nullptr);
3650 6 : if (nRows == 1 && nCols == 1 && papszResult[1])
3651 : {
3652 6 : bHasMinZoomMetadata = true;
3653 6 : nMinZoom = atoi(papszResult[1]);
3654 : }
3655 6 : sqlite3_free_table(papszResult);
3656 6 : if (bHasMinZoomMetadata)
3657 : {
3658 14 : for (int i = 0; i < nOverviews; i++)
3659 : {
3660 8 : const int iOvr = GetOverviewIndex(panOverviewList[i]);
3661 8 : if (iOvr < m_nOverviewCount)
3662 : {
3663 7 : const MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
3664 7 : nMinZoom = std::min(nMinZoom, poODS->m_nZoomLevel);
3665 : }
3666 : }
3667 :
3668 6 : char *pszSQL = sqlite3_mprintf(
3669 : "UPDATE metadata SET value = '%d' WHERE name = 'minzoom'",
3670 : nMinZoom);
3671 6 : sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
3672 6 : sqlite3_free(pszSQL);
3673 : }
3674 : }
3675 :
3676 6 : return eErr;
3677 : }
3678 :
3679 : /************************************************************************/
3680 : /* GDALRegister_MBTiles() */
3681 : /************************************************************************/
3682 :
3683 2126 : void GDALRegister_MBTiles()
3684 :
3685 : {
3686 2126 : if (!GDAL_CHECK_VERSION("MBTiles driver"))
3687 0 : return;
3688 :
3689 2126 : if (GDALGetDriverByName("MBTiles") != nullptr)
3690 263 : return;
3691 :
3692 1863 : GDALDriver *poDriver = new GDALDriver();
3693 :
3694 1863 : poDriver->SetDescription("MBTiles");
3695 1863 : poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
3696 1863 : poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
3697 1863 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "MBTiles");
3698 1863 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC,
3699 1863 : "drivers/raster/mbtiles.html");
3700 1863 : poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "mbtiles");
3701 1863 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES, "Byte");
3702 :
3703 1863 : poDriver->SetMetadataItem(
3704 : GDAL_DMD_OPENOPTIONLIST,
3705 : "<OpenOptionList>"
3706 : " <Option name='ZOOM_LEVEL' scope='raster,vector' type='integer' "
3707 : "description='Zoom level of full resolution. If not specified, maximum "
3708 : "non-empty zoom level'/>"
3709 : " <Option name='BAND_COUNT' scope='raster' type='string-select' "
3710 : "description='Number of raster bands' default='AUTO'>"
3711 : " <Value>AUTO</Value>"
3712 : " <Value>1</Value>"
3713 : " <Value>2</Value>"
3714 : " <Value>3</Value>"
3715 : " <Value>4</Value>"
3716 : " </Option>"
3717 : " <Option name='MINX' scope='raster,vector' type='float' "
3718 : "description='Minimum X of area of interest'/>"
3719 : " <Option name='MINY' scope='raster,vector' type='float' "
3720 : "description='Minimum Y of area of interest'/>"
3721 : " <Option name='MAXX' scope='raster,vector' type='float' "
3722 : "description='Maximum X of area of interest'/>"
3723 : " <Option name='MAXY' scope='raster,vector' type='float' "
3724 : "description='Maximum Y of area of interest'/>"
3725 : " <Option name='USE_BOUNDS' scope='raster,vector' type='boolean' "
3726 : "description='Whether to use the bounds metadata, when available, to "
3727 : "determine the AOI' default='YES'/>" MBTILES_COMPRESSION_OPTIONS
3728 : " <Option name='CLIP' scope='vector' type='boolean' "
3729 : "description='Whether to clip geometries to tile extent' "
3730 : "default='YES'/>"
3731 : " <Option name='ZOOM_LEVEL_AUTO' scope='vector' type='boolean' "
3732 : "description='Whether to auto-select the zoom level for vector layers "
3733 : "according to spatial filter extent. Only for display purpose' "
3734 : "default='NO'/>"
3735 : " <Option name='JSON_FIELD' scope='vector' type='boolean' "
3736 : "description='For vector layers, "
3737 : "whether to put all attributes as a serialized JSon dictionary'/>"
3738 1863 : "</OpenOptionList>");
3739 :
3740 1863 : poDriver->SetMetadataItem(
3741 : GDAL_DMD_CREATIONOPTIONLIST,
3742 : "<CreationOptionList>" MBTILES_RASTER_CREATION_OPTIONS
3743 : #ifdef HAVE_MVT_WRITE_SUPPORT
3744 : MVT_MBTILES_COMMON_DSCO
3745 : #endif
3746 1863 : "</CreationOptionList>");
3747 1863 : poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
3748 :
3749 : #ifdef HAVE_MVT_WRITE_SUPPORT
3750 1863 : poDriver->SetMetadataItem(GDAL_DCAP_CREATE_FIELD, "YES");
3751 1863 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES,
3752 1863 : "Integer Integer64 Real String");
3753 1863 : poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATASUBTYPES,
3754 1863 : "Boolean Float32");
3755 :
3756 1863 : poDriver->SetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST, MVT_LCO);
3757 : #endif
3758 :
3759 : #ifdef ENABLE_SQL_SQLITE_FORMAT
3760 1863 : poDriver->SetMetadataItem("ENABLE_SQL_SQLITE_FORMAT", "YES");
3761 : #endif
3762 1863 : poDriver->SetMetadataItem(GDAL_DMD_SUPPORTED_SQL_DIALECTS, "SQLITE OGRSQL");
3763 :
3764 1863 : poDriver->pfnOpen = MBTilesDataset::Open;
3765 1863 : poDriver->pfnIdentify = MBTilesDataset::Identify;
3766 1863 : poDriver->pfnCreateCopy = MBTilesDataset::CreateCopy;
3767 1863 : poDriver->pfnCreate = MBTilesDataset::Create;
3768 :
3769 1863 : GetGDALDriverManager()->RegisterDriver(poDriver);
3770 : }
|