래스터, 타일, 고도
이 장은 세 가지를 다룹니다. 래스터는 격자의 칸(픽셀)마다 값을 담은 데이터입니다. 이 장은 래스터를 열어 정보와 픽셀을 읽고, NoData를 다루고, 지도 레이어로 칠하고, 메모리에서 만들어 GeoTIFF 파일로 저장하는 방법을 설명합니다. 고도는 숫자 래스터의 값을 높이로 보고 경도와 위도로 읽는 방법입니다. 타일은 미리 잘라 둔 영상 조각의 모음입니다. 이 장은 먼저 데이터를 얻는 소스의 종류를 정리하고, 래스터와 고도를 설명한 뒤 타일을 설명합니다.
래스터와 고도 부분의 코드는 sdk_samples의 raster 예제에서 가져왔습니다. 실행할 때는 데이터 폴더를 첫 인자로, 그림을 남길 폴더를 선택 인자로 줍니다(<실행 파일> <sdk_samples/data 폴더> [<출력 폴더>]). 출력 폴더를 주면 그 폴더에 raster.bmp(640x480, 96 dpi)를 남기고, 주지 않으면 임시 폴더에 씁니다. 예제는 고도 래스터 harbor_dem.tif와 harbor_town.gpkg를 읽기 전용으로 열고, 새로 만드는 GeoTIFF 파일은 임시 폴더에 쓴 뒤 끝날 때 임시 폴더를 지웁니다. 데이터 폴더의 파일은 바뀌지 않습니다. 이 장은 시작하기의 호환성 확인과 공급자 등록이 끝났다고 가정합니다(초기화와 종료).
harbor_dem.tif는 220 x 140 픽셀, 밴드 하나, Float32, EPSG:4326의 가상 지형입니다. 값은 언덕 하나를 만드는 식 h = 120 * exp(-(((lon - 10.07) / 0.02)^2 + ((lat - 50.04) / 0.012)^2))(미터)로 정했고, 왼쪽 위 20 x 20 픽셀은 NoData(-9999)입니다. 예제는 읽은 값을 이 식과 비교합니다.
C#에서 없는 것. 관리 래퍼에는 고도 소스, 픽셀 창 읽기와 쓰기(ReadBlock, WriteBlock), 래스터 메타데이터, 밴드 통계, 범위 래스터 레이어의 음영기복 멤버가 없습니다. 그래서 C# 예제는 고도를 읽는 단계와 메타데이터 단계를 건너뛰고, 픽셀은 한 픽셀씩 읽고 쓰며, 음영기복은 레이어 서비스로 켭니다. 각 절이 그 차이를 적습니다.
지도 뷰를 만들고 크기를 정하고 프레임을 기다려 복사하는 방법은 7장에, 레이어의 공통 속성과 그리는 순서는 8장에 있습니다. 커널 밀도 분석과 히트맵은 이 장에서 다루지 않습니다.
소스 종류
래스터와 타일을 주는 소스는 파일(또는 메모리)에서 여는 것과 네트워크로 여는 것으로 나뉩니다. 네트워크 소스는 예제가 없으며, 이 장은 코드에서 확인한 사실만 적습니다.
| 구분 | 소스 | 여는 방법 | 얻는 것 |
|---|---|---|---|
| 파일 | GeoTIFF (.tif, .tiff) |
geotiff://<경로>, 또는 확장자가 .tif, .tiff인 경로 |
래스터 데이터 소스. 읽기만 합니다 |
| 메모리 | 메모리 래스터 | 메모리 데이터셋(C++ glsCreateMemoryDataset, C# glsDataset.CreateMemory())에서 CreateRasterDataSource |
래스터 데이터 소스. 픽셀을 쓸 수 있습니다(래스터 만들기) |
| 파일 | MBTiles (.mbtiles) |
mbtiles://<경로>, 또는 확장자가 .mbtiles인 경로 |
타일 데이터셋(타일 데이터셋 열기). 메타데이터의 타일 형식(format)이 PNG, JPEG, WebP이면 데이터 소스도 하나 있습니다. 쓰기로 열면 타일을 쓸 수 있습니다(타일 쓰기) |
| 네트워크 | 원격 GeoTIFF (COG) | 경로(질의와 조각 제외)가 .tif, .tiff로 끝나고 {가 없는 http://, https:// 주소, 또는 geotiff:// 뒤에 http(s):// 주소 |
첫 영상이 숫자 단일 밴드이면 래스터 데이터 소스, RGB 영상이면 타일 데이터셋 |
| 네트워크 | XYZ 타일 | {x}, {y}, {z}가 든 http://, https:// 주소 |
타일 데이터셋(네트워크 소스) |
| 네트워크 | WMTS | wmts:// 뒤에 능력 문서 주소, {TileMatrix}, {TileCol}, {TileRow}가 든 주소, 또는 질의에 service=WMTS가 든 주소 |
타일 데이터셋 |
| 네트워크 | WMS | wms:// 뒤에 주소, 또는 질의에 service=WMS가 든 주소 |
지도 영상 소스. 타일이 아니라 화면마다 영상 한 장을 받습니다 |
| 네트워크 | 벡터 타일 | vectortile://open?styleUrl=<스타일 주소> |
벡터 타일 데이터셋(지형 타일과 벡터 타일) |
열기와 정보
GeoTIFF 파일은 읽기 전용 열기로 엽니다(데이터셋 열기). URI는 geotiff:// 뒤에 경로를 UTF-8 문자열로, 구분자는 /로 붙입니다. GeoTIFF 공급자는 픽셀을 쓰지 않습니다(WriteBlock은 NotSupported).
래스터 데이터 소스는 데이터셋에서 번호나 이름으로 엽니다. 번호에 데이터 소스가 없으면 NotFound, 그 데이터 소스가 래스터가 아니면 InvalidArgument로 실패합니다. 돌려받은 래퍼는 호출자가 반납합니다. 예제 파일의 데이터 소스는 하나입니다.
정보는 다음과 같이 읽습니다.
| 정보 | 뜻 |
|---|---|
| 너비, 높이 | 픽셀 수 |
| 밴드 수, 밴드 | 밴드는 1부터 셉니다. 밴드마다 자료형(glsRasterDataType)과 NoData 값이 있습니다 |
| 좌표계 | 래스터의 좌표계 |
| 범위 | 격자 전체를 덮는 사각형, 래스터 좌표계의 좌표 |
| 지오트랜스폼 | 픽셀 위치를 지도 좌표로 바꾸는 계수 여섯 개(픽셀 읽기) |
glsRasterDataType의 값은 고정되어 있습니다(값이 고정된 열거형). 예제 파일은 220 x 140, 밴드 1개, Float32, EPSG:4326, 범위는 경도 9.995~10.105, 위도 49.995~50.065, 지오트랜스폼은 원점 (9.995, 50.065), 픽셀 크기 0.0005 x -0.0005, NoData는 -9999입니다.
glsOpenDatasetReadOnly로 열고, OpenRasterDataSource(index, &source) 또는 OpenRasterDataSourceByName(name, &source)로 데이터 소스를 얻어 glsReleaseRasterDataSource로 반납합니다. 정보는 GetWidth, GetHeight, GetBandCount, GetBand(1, &band)(glsReleaseRasterBand로 반납, 없는 번호는 NotFound), GetCrs(돌려받은 좌표계는 glsReleaseSpatialReference로 반납), GetExtent, GetGeoTransform으로 읽습니다. 밴드의 GetNoDataValue(&hasValue, &value)는 NoData가 없으면 hasValue를 false로 줍니다.
// A GeoTIFF file opens through the "geotiff://" URI with the path as UTF-8
// text with forward slashes. The file holds one raster data source; the
// caller owns the wrapper OpenRasterDataSource returns.
static bool openRaster(const std::filesystem::path& file, DatasetPtr& dataset, RasterPtr& raster)
{
GDK::glsDataset* rawDataset = nullptr;
if (!succeeded(GDK::glsOpenDatasetReadOnly(geotiffUri(file).c_str(), &rawDataset))) {
return false;
}
dataset.reset(rawDataset);
int count = 0;
GDK::glsRasterDataSource* rawRaster = nullptr;
if (!succeeded(dataset->GetDataSourceCount(&count)) ||
!succeeded(dataset->OpenRasterDataSource(0, &rawRaster))) {
return false;
}
raster.reset(rawRaster);
std::printf("[sample] opened read-only: %s, %d data source\n", file.filename().string().c_str(), count);
return count == 1 || unexpected("expected one data source");
}
// Size, band count and data type, the coordinate system, the extent and the
// geotransform describe the grid. Bands are numbered from 1. The NoData value
// is a property of the band.
static bool rasterInfo(Raster& r)
{
int width = 0;
int height = 0;
int bands = 0;
GDK::glsRasterBand* rawBand = nullptr;
if (!succeeded(r.source.GetWidth(&width)) || !succeeded(r.source.GetHeight(&height)) ||
!succeeded(r.source.GetBandCount(&bands)) || !succeeded(r.source.GetBand(1, &rawBand))) {
return false;
}
BandPtr band(rawBand, GDK::glsReleaseRasterBand);
GDK::glsRasterDataType type = GDK::glsRasterDataType::Unknown;
bool hasNoData = false;
double noData = 0;
GDK::glsSpatialReference* rawSrs = nullptr;
if (!succeeded(band->GetDataType(&type)) || !succeeded(band->GetNoDataValue(&hasNoData, &noData)) ||
!succeeded(r.source.GetCrs(&rawSrs))) {
return false;
}
SrsPtr srs(rawSrs, GDK::glsReleaseSpatialReference);
int epsg = 0;
GDK::glsEnvelope e;
if (!succeeded(srs->GetEpsgCode(&epsg)) || !succeeded(r.source.GetExtent(&e)) ||
!succeeded(r.source.GetGeoTransform(&r.transform))) {
return false;
}
const GDK::glsGeoTransform& t = r.transform;
std::printf("[sample] raster: %d x %d, %d band, %s, EPSG:%d\n", width, height, bands, dataTypeName(type), epsg);
std::printf("[sample] extent %.3f %.3f %.3f %.3f\n", e.MinX, e.MinY, e.MaxX, e.MaxY);
std::printf("[sample] geotransform: origin %.4f %.4f, pixel %.4f x %.4f\n", t.Gt0, t.Gt3, t.Gt1, t.Gt5);
std::printf("[sample] NoData: %s, %.1f\n", yesNo(hasNoData), noData);
return (width == kDemWidth && height == kDemHeight && bands == 1 && type == GDK::glsRasterDataType::Float32 &&
epsg == 4326 && near(e.MinX, 9.995, 1e-9) && near(e.MinY, 49.995, 1e-9) && near(e.MaxX, 10.105, 1e-9) &&
near(e.MaxY, 50.065, 1e-9) && near(t.Gt0, kDemWest, 1e-9) && near(t.Gt3, kDemNorth, 1e-9) &&
near(t.Gt1, kDemPixel, 1e-12) && near(t.Gt5, -kDemPixel, 1e-12) && t.Gt2 == 0 && t.Gt4 == 0 &&
hasNoData && noData == kNoData) ||
unexpected("expected the raster of data/README.md");
}
메타데이터와 통계. GetMetadataCount, GetMetadataKey, GetMetadataValue, GetMetadataValueAt는 공급자가 붙인 문자열 쌍을 읽습니다. 키와 값은 공급자마다 다르며, 없는 키는 NotFound입니다. 밴드의 GetStatistics(approxOk, ...)는 최솟값, 최댓값, 평균, 표준편차를 주는데, 공급자가 통계를 주지 않으면 성공하면서 hasValue가 false입니다. GeoTIFF 공급자는 통계를 주지 않습니다. 메모리 래스터는 NoData와 유한하지 않은 값을 빼고 계산하며, approxOk가 true이고 픽셀이 100개보다 많으면 열 픽셀마다 하나만 봅니다.
// The metadata keys and values depend on the provider. The band statistics
// are optional: the GeoTIFF provider reports none.
static bool rasterMetadata(Raster& r)
{
const std::string provider = sample::readString([&](char* buf, size_t size, size_t* required) {
return r.source.GetMetadataValue("provider", buf, size, required);
});
const std::string tiled = sample::readString([&](char* buf, size_t size, size_t* required) {
return r.source.GetMetadataValue("isTiled", buf, size, required);
});
GDK::glsRasterBand* rawBand = nullptr;
if (!succeeded(r.source.GetBand(1, &rawBand))) {
return false;
}
BandPtr band(rawBand, GDK::glsReleaseRasterBand);
bool hasStatistics = true;
double minValue = 0, maxValue = 0, mean = 0, stdDev = 0;
if (!succeeded(band->GetStatistics(false, &hasStatistics, &minValue, &maxValue, &mean, &stdDev))) {
return false;
}
std::printf("[sample] metadata: provider %s, tiled %s; statistics available %s\n", provider.c_str(),
tiled.c_str(), yesNo(hasStatistics));
return (provider == "geotiff" && tiled == "true" && !hasStatistics) ||
unexpected("expected GeoTIFF metadata and no statistics");
}
픽셀 읽기
좌표 규약. 픽셀은 열(c, 왼쪽부터)과 행(r, 위부터)으로 가리키며 둘 다 0부터 셉니다. 지오트랜스폼은 픽셀의 모서리를 지도 좌표로 바꿉니다.
X = Gt0 + c * Gt1 + r * Gt2
Y = Gt3 + c * Gt4 + r * Gt5
(c, r)에 0.5씩 더하면 픽셀 중심입니다. 북쪽이 위인 래스터는 Gt2와 Gt4가 0이고 Gt5가 음수이므로, 행 0이 북쪽 끝입니다. 이때 지도 좌표 (X, Y)가 든 픽셀은 c = floor((X - Gt0) / Gt1), r = floor((Y - Gt3) / Gt5)입니다. 예제 파일에서 열 149, 행 49의 중심은 (10.06975, 50.04025)입니다.
창 읽기. C++의 ReadBlock(xOff, yOff, xSize, ySize, buffer, bufferSize)는 픽셀 창 하나를 호출자의 버퍼에 복사합니다. 이 절은 밴드가 하나인 숫자 래스터를 다룹니다.
- 위의 행부터 한 행씩, 행 안에서는 왼쪽부터 채웁니다. 행 사이에 빈 바이트는 없습니다.
- 픽셀은 밴드의 자료형 그대로(예제는 4바이트
float) 옵니다. 다른 형으로 바꾸어 주지 않습니다. - 버퍼는
xSize * ySize * 픽셀 바이트 수이상이어야 하며, 작으면InvalidArgument입니다. - GeoTIFF에서 창이 래스터 밖으로 조금이라도 나가면
InvalidArgument입니다. 메모리 래스터는 밖에 놓인 부분을 0으로 채웁니다. - 원래 해상도만 읽습니다. 축소본(피라미드)은 지도 레이어와 고도 소스가 씁니다.
한 픽셀 읽기. ReadPixelRaw(x, y, ...)는 밴드 1의 픽셀 하나를 자료형 그대로의 바이트로 읽습니다. 래스터 밖의 위치는 InvalidArgument입니다.
예제는 언덕 꼭대기 옆의 3 x 3 픽셀(열 148~150, 행 48~50)을 읽어 아홉 값이 모두 각 픽셀 중심에서 계산한 식의 값과 같은지(차이 0.001 이하) 확인합니다. 가운데 픽셀(149, 49)의 값은 119.929입니다.
ReadPixelRaw(x, y, outBuf, outBufSize, &written)는 읽은 바이트 수를 written에 줍니다.
// ReadBlock copies a window of pixels into the caller's buffer, row by row
// from the top, in the band's data type (here 4-byte floats). Column c and
// row r cover the map area that starts at Gt0 + c * Gt1, Gt3 + r * Gt5; the
// pixel center is half a pixel further. The window here is the 3 x 3 pixels
// around column 149, row 49, next to the hill top.
static bool readPixels(Raster& r)
{
const int c0 = 148;
const int r0 = 48;
float values[9] = {};
if (!succeeded(r.source.ReadBlock(c0, r0, 3, 3, values, sizeof(values)))) {
return false;
}
int matching = 0;
for (int row = 0; row < 3; ++row) {
for (int column = 0; column < 3; ++column) {
const double lon = r.transform.Gt0 + (c0 + column + 0.5) * r.transform.Gt1;
const double lat = r.transform.Gt3 + (r0 + row + 0.5) * r.transform.Gt5;
if (near(values[row * 3 + column], demHeight(lon, lat), 1e-3)) {
++matching;
}
}
}
const double centerLon = r.transform.Gt0 + (149 + 0.5) * r.transform.Gt1;
const double centerLat = r.transform.Gt3 + (49 + 0.5) * r.transform.Gt5;
std::printf("[sample] 3 x 3 pixels at column 148, row 48: %d of 9 match the formula\n", matching);
std::printf("[sample] pixel (149, 49): center %.5f %.5f, value %.3f\n", centerLon, centerLat, values[4]);
return (matching == 9 && near(centerLon, 10.06975, 1e-9) && near(centerLat, 50.04025, 1e-9) &&
near(values[4], demHeight(centerLon, centerLat), 1e-3)) ||
unexpected("expected the pixels of the formula");
}
NoData
NoData는 "이 픽셀에는 값이 없다"는 표시로 쓰는 값이며 밴드의 속성입니다(열기와 정보). 픽셀을 읽으면 NoData 픽셀도 저장된 값(예제는 -9999) 그대로 나옵니다. 읽는 쪽이 밴드의 NoData 값과 비교해 가려냅니다. Float32 래스터는 값을 float으로 저장하므로 float끼리 비교합니다.
NoData는 다음에서 값이 없는 것으로 다뤄집니다.
- 그리기. 범위 래스터와 값 래스터 레이어는 밴드의 NoData 값과 같은 픽셀을 그리지 않습니다(투명). 범위 래스터 레이어는 스타일의 NoData 값과 같은 픽셀도 그리지 않습니다(범위 스타일).
- 통계. 메모리 래스터의 통계는 NoData 픽셀을 뺍니다(열기와 정보).
- 고도. 고도 소스는 NoData 픽셀과 NaN 픽셀을 값이 없는 것으로 다룹니다(값이 없는 곳).
예제는 NoData 블록의 모서리에 걸친 4 x 4 픽셀(열 18~21, 행 18~21)을 읽어 NoData 4개, 값 12개를 확인하고, 래스터 밖의 픽셀(220, 0)을 읽어 InvalidArgument로 거절되는 것을 확인합니다.
// NoData pixels are read like any other pixel: they hold the NoData value,
// so compare with the band's value. A window or pixel that does not lie
// inside the raster is not read; the call fails with InvalidArgument.
static bool noDataPixels(Raster& r)
{
const int c0 = kNoDataBlock - 2;
const int r0 = kNoDataBlock - 2;
float values[16] = {};
if (!succeeded(r.source.ReadBlock(c0, r0, 4, 4, values, sizeof(values)))) {
return false;
}
int noData = 0;
for (float v : values) {
if (v == kNoData) {
++noData;
}
}
std::printf("[sample] 4 x 4 pixels at column 18, row 18: %d NoData, %d with a value\n", noData, 16 - noData);
float outside = 0;
size_t written = 0;
const GDK::glsStatus status = r.source.ReadPixelRaw(kDemWidth, 0, &outside, sizeof(outside), &written);
const bool rejected = status.Code == GDK::glsResultCode::InvalidArgument;
if (!status.IsOk() && !rejected) {
return succeeded(status); // another failure: print it and stop
}
std::printf("[sample] pixel (220, 0), outside the raster: %s\n", rejected ? "InvalidArgument" : "not rejected");
return (noData == 4 && rejected) || unexpected("expected 4 NoData pixels and a rejected read");
}
래스터 레이어
래스터를 지도에 그리는 레이어는 세 종류입니다.
| 종류 | 그리는 데이터 | 색을 정하는 방법 | C++ | C# |
|---|---|---|---|---|
Raster |
영상: 밴드 1이 Byte나 Bgra32인 래스터 |
픽셀이 가진 색 그대로 | glsCreateRasterLayer |
new glsRasterLayer(source) |
RangeRaster |
연속된 숫자 값(고도, 온도 등) | 정렬된 색 단계 | glsCreateRangeRasterLayer |
new glsRangeRasterLayer(source) |
ValueRaster |
몇 가지 정해진 숫자 값(토지 피복 코드 등) | 값마다 색을 정한 표 | glsCreateValueRasterLayer |
new glsValueRasterLayer(source) |
Raster 레이어는 숫자 자료형(Int16, Float32 등)의 래스터를 그리지 않습니다. 숫자 래스터는 RangeRaster나 ValueRaster로 그립니다. ValueRaster는 픽셀 값과 표의 값의 차이가 max(1e-9, |표의 값| x 1e-6) 이하인 첫 항목의 색을 쓰고, 맞는 항목이 없으면 기본 색(DefaultColor, 기본값 투명)을 씁니다.
만들기. 레이어는 래스터 데이터 소스를 함께 가지므로, 만든 뒤에는 데이터 소스 래퍼를 반납해도 됩니다. 지도에 더하는 규칙과 id는 피처 레이어와 같습니다(8장). 이렇게 직접 만든 레이어는 공급자의 축소본을 쓰지 않고 원래 해상도만 읽습니다. 새 범위 래스터 레이어에는 색 단계가 없고 색 모드는 Gradient입니다. 색 단계가 없으면 아무 픽셀도 보이지 않으므로(스타일의 NoData 색, 기본값 투명) 색 단계를 넣어야 합니다.
기본 레이어. 워크스페이스의 AddDataset으로 래스터 데이터셋을 더하면(7장) 래스터 데이터 소스마다 기본 레이어가 생깁니다. 밴드 1이 숫자 자료형(Byte와 Bgra32가 아닌 것)이면 RangeRaster 레이어이고, 그 밖에는 Raster 레이어입니다. 기본 레이어는 공급자의 축소본이 있으면 함께 씁니다. 기본 RangeRaster 레이어의 스타일은 다음과 같습니다.
- 색 모드
Classified, 값의 최솟값부터 최댓값까지를 열 구간으로 나눈 회색 열 단계(검정부터 흰색까지)입니다. - 최솟값과 최댓값은 공급자가 주는 통계에서, 통계가 없으면 축소본 가운데 가장 거친 것 전체(400만 픽셀 이하일 때)에서, 그것도 안 되면 래스터의 일부를 읽은 표본에서 구합니다. NoData 픽셀은 빼고 셉니다. 어느 방법으로도 구하지 못하면 0~255를 열 구간으로 나눕니다.
- 밴드에 NoData 값이 있으면 그 값이 스타일의 NoData 값이 됩니다.
예제는 범위 래스터 레이어를 만들어 id elevation으로 지도에 더한 뒤, 그 위에 harbor_town.gpkg의 세 레이어를 올리고(스타일은 8장 예제와 같은 파일) 구역 레이어의 불투명도를 0.5로 낮춰 고도가 비쳐 보이게 합니다. 지도의 레이어는 4개입니다.
glsCreateRangeRasterLayer(source, &layer)로 만들고 glsReleaseRangeRasterLayer(또는 glsReleaseMapLayer)로 반납합니다. 레이어의 데이터 소스는 GetDataSource로 다시 얻을 수 있으며, 돌려받은 래퍼는 반납합니다.
// A range raster layer draws a numeric raster through a color ramp. A new
// layer has no color stops yet. It shares the raster data source, and the map
// keeps the layer, so both wrappers can be released after AddLayer. The
// Harbor Town layers go on top; their districts are made half transparent so
// that the elevation shows through.
static bool rangeLayer(Raster& r, GDK::glsDataset& vectors, GDK::glsMapView& view,
const std::filesystem::path& stylesDir)
{
GDK::glsRangeRasterLayer* raw = nullptr;
if (!succeeded(GDK::glsCreateRangeRasterLayer(&r.source, &raw))) {
return false;
}
RangeLayerPtr layer(raw, GDK::glsReleaseRangeRasterLayer);
int stops = -1;
GDK::glsRangeRasterColorMode mode = GDK::glsRangeRasterColorMode::Classified;
if (!succeeded(layer->GetColorStopCount(&stops)) || !succeeded(layer->GetColorMode(&mode)) ||
!succeeded(layer->SetId(kElevationLayer)) || !succeeded(view.AddLayer(layer.get()))) {
return false;
}
layer.reset();
if (!sample::addHarborLayers(vectors, view, stylesDir.u8string())) {
return false; // addHarborLayers has printed why
}
LayerPtr districts = findLayer(view, "districts");
int count = 0;
if (!districts || !succeeded(districts->SetOpacity(0.5f)) || !succeeded(view.GetLayerCount(&count))) {
return false;
}
std::printf("[sample] new range raster layer: %d color stops, %s; map layers %d\n", stops,
mode == GDK::glsRangeRasterColorMode::Gradient ? "Gradient" : "Classified", count);
return (stops == 0 && mode == GDK::glsRangeRasterColorMode::Gradient && count == 4) ||
unexpected("expected an empty gradient and four layers");
}
범위 스타일과 색 단계
색 단계. 색 단계(C++ glsColorStop, C# glsRasterStyleEntry)는 값, 색(0xAARRGGBB), 범례 문구의 묶음입니다. 단계는 값의 오름차순이어야 하며(같은 값은 허용), 그렇지 않으면 설정이 실패하고 레이어는 그대로입니다.
색 모드.
Gradient: 값의 양옆 두 단계 사이에서 색을 섞습니다.Classified: 단계마다 그 값에서 시작해 다음 단계의 값 직전까지가 한 구간이고, 마지막 구간은 위로 끝이 없습니다.
스타일의 나머지. NoData 값(기본값 NaN), NoData 색(기본값 투명), Clamp(기본값 true)가 있습니다.
- 스타일의 NoData 값과 같은 픽셀은 그리지 않습니다. 기본값 NaN은 NaN 픽셀을 그리지 않는다는 뜻입니다. 밴드의 NoData 픽셀은 이 값과 관계없이 그리지 않습니다.
Clamp가true이면 첫 단계보다 작은 값은 첫 단계의 색, (Gradient에서) 마지막 단계보다 큰 값은 마지막 단계의 색으로 그립니다.false이면 그런 값을 NoData 색으로 그리며,Gradient에서는 첫 단계나 마지막 단계와 같은 값도 NoData 색입니다(Classified에서는 첫 단계보다 작은 값만). 단계가 없을 때도 NoData 색입니다.
다시 그리기. 지도에 있는 레이어의 스타일을 바꾸면 지도 뷰가 새 그리기를 예약합니다. 프레임을 기다리는 방법은 7장에 있습니다.
예제는 0미터 초록(0xFF2E7D32), 60미터 노랑(0xFFF9D84A), 120미터 갈색(0xFF8D5524)의 세 단계를 Gradient로 넣습니다.
SetColorStops(stops, count), GetColorStopCount, GetColorStops(out, capacity, &written), SetColorMode, GetColorMode, 스타일의 나머지는 glsRangeRasterStyle을 받는 GetStyle, SetStyle입니다. 정렬되지 않은 단계는 InvalidArgument입니다. 지도에서 id로 꺼낸 레이어는 dynamic_cast<glsRangeRasterLayer*>로 바꿔 씁니다. glsColorStop의 Legend는 고정 크기의 UTF-8 문자 배열입니다.
// The stops must be sorted by value. In Gradient mode a value between two
// stops gets a color between theirs; with Clamp (the default) a value below
// the first or above the last stop gets that stop's color. NoData pixels are
// not drawn. A layer found by id is returned as a wrapper of its own kind.
static bool colorStops(GDK::glsMapView& view)
{
LayerPtr layer = findLayer(view, kElevationLayer);
if (!layer) {
return false;
}
auto* elevation = dynamic_cast<GDK::glsRangeRasterLayer*>(layer.get());
if (elevation == nullptr) {
return unexpected("expected a range raster layer");
}
GDK::glsColorStop stops[3];
stops[0].Value = 0;
stops[0].Color = kLowColor;
stops[1].Value = 60;
stops[1].Color = kMidColor;
stops[2].Value = 120;
stops[2].Color = kHighColor;
int count = 0;
if (!succeeded(elevation->SetColorStops(stops, 3)) ||
!succeeded(elevation->SetColorMode(GDK::glsRangeRasterColorMode::Gradient)) ||
!succeeded(elevation->GetColorStopCount(&count))) {
return false;
}
std::printf("[sample] color stops: %d (0 m, 60 m, 120 m)\n", count);
return count == 3 || unexpected("expected three color stops");
}
그려서 확인하기. 예제는 640x480, 96 dpi로 크기를 정하고 ZoomToLayer("elevation", 0)으로 래스터 전체에 맞춘 뒤, 프레임을 기다려 복사하고 raster.bmp로 씁니다(7장). 그림에는 초록 바탕 위에 노랑과 갈색으로 칠한 언덕이 반투명한 구역 아래로 보이고, 그 위에 도로와 장소가 있습니다. 왼쪽 위 NoData 구석은 칠해지지 않아 래스터 밖과 같은 바탕색입니다. 예제는 화면 픽셀 하나씩을 읽어 다음을 확인합니다.
- 구역의 구멍 안(다른 레이어가 래스터를 덮지 않는 곳)에 있는 래스터 픽셀(열 99, 행 39, 높이 약 20미터)의 중심에서, 화면 픽셀이 그 높이에 대해 색 단계가 주는 색과 채널마다 2 이내로 같습니다.
- 구역 밖, 래스터 가장자리의 낮은 땅은 첫 단계의 색(
0xFF2E7D32)과 정확히 같습니다. 그 위에 다른 레이어가 없기 때문입니다. - 불투명도 0.5로 그린 구역 아래의 낮은 땅(높이 약 0.003미터)은 구역의 채움색(
0xFFDCE9F5)과 그 높이의 색 단계 색을 반씩 섞은 색과 채널마다 2 이내로 같습니다. 언덕 위의 점(역시 구역 아래)은 이 색과 다릅니다. - NoData 구석의 픽셀이 래스터 밖의 픽셀과 같고 첫 단계의 색이 아닙니다. NoData 픽셀을 값으로 그렸다면 -9999가 첫 단계보다 작고
Clamp가 켜져 있으므로 첫 단계의 색이 되었을 것입니다.
// The map view starts with no size: Resize first, then fit the view to the
// raster. Where no other layer covers the raster, at the center of a raster
// pixel on the slope inside the hole of a district, the screen pixel has the
// ramp color for that pixel's height (two levels of rounding allowed), and the
// low ground at the raster edge has exactly the first stop's color. The low
// ground under a district drawn at opacity 0.5 has the half-and-half mix of
// the district fill (0xFFDCE9F5) and the ramp color (two levels allowed), and
// the hill under a district differs from it. The NoData corner shows what lies
// beyond the raster: a NoData pixel drawn as a value would get the first
// stop's color, because -9999 lies below the first stop and Clamp is on.
static bool renderToFile(GDK::glsMapView& view, const std::filesystem::path& folder,
std::vector<unsigned char>& pixels)
{
if (!succeeded(view.Resize(kWidth, kHeight, kDpi, kDpi)) || !succeeded(view.ZoomToLayer(kElevationLayer, 0))) {
return false;
}
if (!sample::waitForFrame(view, kRenderTimeoutMs)) {
return false; // waitForFrame has printed why
}
if (!sample::copyFrame(view, kWidth, kHeight, pixels)) {
std::printf("[sample] copy frame failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
if (!sample::writeBmp((folder / "raster.bmp").u8string(), pixels.data(), kWidth, kHeight)) {
std::printf("[sample] could not write raster.bmp\n");
return false;
}
std::printf("[sample] wrote raster.bmp\n");
CheckPoints p;
if (!checkPoints(view, p)) {
return false;
}
const bool visible = onScreen(p.slope) && onScreen(p.hill) && onScreen(p.low) && onScreen(p.edge) &&
onScreen(p.noData) && onScreen(p.outside);
const double slopeHeight = demHeight(kSlope.X, kSlope.Y);
const bool slopeMatches = colorNear(pixelAt(pixels, p.slope), rampColor(slopeHeight), 2);
const bool edgeIsLow = pixelAt(pixels, p.edge) == kLowColor;
const bool lowIsHalfMix =
colorNear(pixelAt(pixels, p.low), mixColor(kDistrictFill, rampColor(demHeight(kLow.X, kLow.Y)), 0.5), 2);
const bool hillDiffers = pixelAt(pixels, p.hill) != pixelAt(pixels, p.low);
const bool noDataShowsBeyond = pixelAt(pixels, p.noData) == pixelAt(pixels, p.outside) &&
pixelAt(pixels, p.noData) != kLowColor;
std::printf("[sample] slope at %.0f m has its ramp color: %s; edge has the low color: %s\n", slopeHeight,
yesNo(slopeMatches), yesNo(edgeIsLow));
std::printf("[sample] under a district: low ground is the half mix %s, hill differs %s\n", yesNo(lowIsHalfMix),
yesNo(hillDiffers));
std::printf("[sample] NoData corner shows the background: %s\n", yesNo(noDataShowsBeyond));
return (visible && slopeMatches && edgeIsLow && lowIsHalfMix && hillDiffers && noDataShowsBeyond) ||
unexpected("expected the elevation colors in the frame");
}
음영기복
음영기복은 지형의 기울기에 빛을 비춘 것처럼 밝기를 더해 그립니다. 범위 래스터 레이어의 그리기 설정이며, 저장된 값은 바꾸지 않습니다. 설정은 glsRasterHillshadeSettingsV1(C# glsRasterHillshadeSettings)의 필드입니다.
| 필드 | 뜻 | 허용 범위 (기본값) |
|---|---|---|
Mode |
0 끄기, 1 회색(색 단계 대신 밝기만), 2 색 음영(색 단계의 색을 기울기에 따라 어둡게) | 0~2 (0) |
AzimuthDegrees |
빛이 오는 방향. 북쪽에서 시계 방향의 도 | 0 이상 360 미만 (315) |
AltitudeDegrees |
빛의 높이. 지평선에서 잰 도 | 0~90 (45) |
ZFactor |
높이를 부풀리는 배수 | 0 초과 100 이하 (1) |
Strength |
색 음영에서 어둡게 하는 정도. 0이면 색 단계 그대로 | 0~1 (0.5) |
VerticalUnit |
값의 높이 단위. 0 자동(공급자가 알려 준 밴드의 단위, 없으면 미터. 모르는 단위이면 NotSupported), 1 미터, 2 국제 피트, 3 미국 측량 피트, 4 직접(CustomMetresPerUnit, 0 초과) |
0~4 (0) |
ValueTransform, ValueScale, ValueOffset |
저장된 값을 높이로 바꾸는 배율과 더할 값. 0 자동(공급자가 알려 준 값, 없으면 배율 1과 0), 1 직접(ValueScale, ValueOffset) |
0~1 (0). 배율 0 초과 (1, 0) |
EdgePolicy |
0 엄격: 둘레 3 x 3 픽셀 중 값이 없는 것이 있으면 그 픽셀을 그리지 않음. 래스터 밖은 값이 없는 것으로 보므로 래스터의 맨 바깥 한 줄 픽셀은 언제나 그려지지 않습니다. 1 어림: 남은 값으로 기울기를 어림 | 0~1 (0) |
- 범위를 벗어난 값은
InvalidArgument로 거절됩니다. - 켜는 설정(
Mode가 0이 아니고 지금 설정과 다를 때)은 래스터도 확인합니다. 밴드가 하나인 숫자(Byte아님) 래스터이고, 격자가 북쪽이 위이며 회전하지 않았고, 좌표계가 유효하며 지구 중심 좌표계가 아니어야 합니다. 그렇지 않으면NotSupported입니다. - 수평 거리는 래스터의 좌표계와 관계없이 미터로 계산하므로, 예제처럼 경위도 래스터에도 쓸 수 있습니다. 위도 85도를 넘는 곳의 픽셀은 그리지 않습니다.
- 지금 화면에 필요한 픽셀이 너무 많아 읽기 또는 출력 영상의 예상량이 각각 64 MiB 한도를 넘으면, 더 거친 축소본으로 음영기복을 시도합니다. 사용할 축소본이 없거나 모두 한도를 넘으면, 가시 영역을 저해상도로 표본 추출해 음영 없이 색 단계로 표시합니다. 이때도 요청한 원본 바이트 합계와 출력 영상은 각각 한도 이내입니다(공급자 내부의 디코딩 메모리·네트워크 전송량과는 별도). 확대하거나 축소본이 있는 레이어(공급자에 축소본이 있을 때 워크스페이스의 기본 레이어)를 쓰면 더 자세한 음영기복을 볼 수 있습니다.
- 그릴 때 래스터가 음영기복을 지원하지 않는 것으로 드러나거나, 레이어가 이 버전이 적용할 수 없는 저장된 설정을 보존하고 있으면, 음영 없이 색 단계로 그립니다. 픽셀을 읽지 못했거나 그리기가 취소되면 그 그리기에서 레이어는 아무것도 그리지 않습니다.
- 마지막 그리기가 사용한 음영 모드는 C++
GetDisplayedHillshadeMode로 확인합니다. 색 단계만으로 그렸거나 그리기가 실패했으면 0입니다.
예제는 색 음영(2), 방향 315도, 높이 45도, 세기 0.5를 켜고 다시 그립니다. 스타일을 바꾸어도 지도의 범위는 그대로인데 예제의 프레임 기다리기 도우미는 뷰 좌표만 비교하므로, 예제는 지도 중심을 옮겼다가 되돌린 뒤 기다립니다. CompletedFrameGeneration을 RenderGeneration과 비교하는 도우미(7장의 판정)라면 이 단계가 필요 없습니다. 다시 그린 프레임은 처음 프레임과 다르고, 구역 밖 래스터 가장자리의 낮은 땅도 어두워졌습니다(평평한 땅도 빛이 비스듬하므로 어두워집니다).
미리보기. glsRasterHillshadePreviewSession(C#도 같은 이름)은 지도에 있는 범위 래스터 레이어의 설정을 바꾸지 않고, 주어진 스타일과 음영기복 설정으로 그린 그림을 따로 만듭니다. 그림은 세션의 작업 스레드가 자기 지도 뷰로 그리며, 만들기, 요청, 결과 확인은 지도 뷰를 다루는 스레드에서 부르도록 되어 있습니다. 자세한 사용법은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다.
GetHillshadeSettings(&settings)로 지금 설정을 읽어 고친 뒤 SetHillshadeSettings(&settings)로 넣습니다. 구조체의 StructSize와 Version은 기본값 그대로 둡니다. 스타일, 색 단계, 색 모드, 음영기복을 한 번에 바꾸려면 SetRenderingSettings를 씁니다.
// Hillshade shades the colors by the slope as lit from a direction
// (azimuth, degrees clockwise from north) and a height (altitude, degrees
// above the horizon). ColorRelief darkens the ramp colors by Strength (0 to
// 1). The vertical unit Auto takes the band's unit, meters when it has none.
// The view is moved away and back so that waitForFrame waits for a frame
// drawn with the new setting. GetDisplayedHillshadeMode tells what the last
// frame drew.
static bool hillshade(GDK::glsMapView& view, const std::vector<unsigned char>& before)
{
LayerPtr layer = findLayer(view, kElevationLayer);
if (!layer) {
return false;
}
auto* elevation = dynamic_cast<GDK::glsRangeRasterLayer*>(layer.get());
if (elevation == nullptr) {
return unexpected("expected a range raster layer");
}
GDK::glsRasterHillshadeSettingsV1 settings;
if (!succeeded(elevation->GetHillshadeSettings(&settings))) {
return false;
}
settings.Mode = kHillshadeColorRelief;
settings.AzimuthDegrees = 315;
settings.AltitudeDegrees = 45;
settings.Strength = 0.5;
double x = 0;
double y = 0;
if (!succeeded(elevation->SetHillshadeSettings(&settings)) || !succeeded(view.GetCenter(&x, &y)) ||
!succeeded(view.SetCenter(x + 0.01, y)) || !sample::waitForFrame(view, kRenderTimeoutMs) ||
!succeeded(view.SetCenter(x, y)) || !sample::waitForFrame(view, kRenderTimeoutMs)) {
return false;
}
std::vector<unsigned char> after;
if (!sample::copyFrame(view, kWidth, kHeight, after)) {
std::printf("[sample] copy frame failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
CheckPoints p;
if (!checkPoints(view, p)) {
return false;
}
const bool frameChanged = after != before;
const bool edgeChanged = pixelAt(after, p.edge) != pixelAt(before, p.edge);
std::printf("[sample] hillshade on: frame changed %s, low ground shaded %s\n", yesNo(frameChanged),
yesNo(edgeChanged));
int32_t displayed = 0;
if (!succeeded(elevation->GetDisplayedHillshadeMode(&displayed))) {
return false;
}
std::printf("[sample] displayed hillshade mode: %d\n", displayed);
return (frameChanged && edgeChanged && displayed == kHillshadeColorRelief) ||
unexpected("expected a shaded frame");
}
고도 읽기 (C++)
고도 소스 glsRasterElevationSource는 숫자 래스터의 값을 높이로 보고 WGS84 경도와 위도(EPSG:4326)로 읽습니다. 래스터가 투영 좌표계이면 안에서 바꿉니다. C#에는 고도 소스가 없습니다.
여는 방법.
- 데이터셋에서:
glsDataset::OpenRasterElevationSource(&source, &found)는 데이터셋에서 밴드가 하나인 숫자(Byte아님) 래스터 가운데 좌표계가 있는 첫 데이터 소스로 소스를 엽니다. 그런 래스터가 없으면 실패가 아니라found가false입니다. 공급자에게 축소본이 있으면 함께 씁니다. - 레이어에서:
glsRangeRasterLayer::OpenElevationSource,glsValueRasterLayer::OpenElevationSource는 그 레이어의 래스터와, 레이어가 가진 축소본으로 엽니다. 래스터가 맞지 않으면NotSupported입니다. 직접 만든 레이어는 축소본이 없으므로 원래 해상도만 읽습니다.
둘 다 glsReleaseRasterElevationSource로 반납합니다.
읽기.
ElevationAt(lon, lat, cachedOnly, &found, &elevation): 점을 둘러싼 네 픽셀 중심 사이를 쌍선형으로 보간한 높이입니다(값의 단위 그대로, 예제는 미터). 래스터의 가장자리 위의 점은 안쪽으로 봅니다.ElevationAtStatus: 값이 없을 때 이유를 함께 줍니다(값이 없는 곳).- 레벨: 레벨 0이 원래 해상도이고, 1부터는 축소본입니다.
GetLevelCount가 레벨 수,LevelForSpacing(간격 m, 위도, &level, &resolution)이 그 간격보다 성기지 않은 가장 거친 레벨(원래 해상도도 더 성기면 0)과 그 레벨의 픽셀 크기(미터)를 줍니다.ElevationAtLevel은 그 레벨에서 읽으며, 마지막보다 큰 레벨은 마지막 레벨로 읽습니다. GetLonLatExtent: 래스터의 범위를 경위도로 줍니다.- 픽셀은 256 x 256 블록으로 읽어 소스 안에 캐시하므로, 가까운 점들을 읽으면 같은 데이터를 다시 읽지 않습니다.
cachedOnly가true이면 캐시에 없는 블록을 읽지 않고 "캐시에 없음"으로 답합니다.
스레드와 수명. 한 소스를 여러 스레드에서 함께 불러도 됩니다. 반납은 모든 호출이 돌아온 뒤에 합니다. 소스는 래스터 데이터 소스를 함께 가지므로, 그것을 연 데이터셋이나 레이어 래퍼를 반납한 뒤에도 쓸 수 있습니다. 로컬 GeoTIFF는 데이터셋을 반납한 뒤에 읽어야 하면 파일을 다시 엽니다. 원격 GeoTIFF는 다릅니다. 워크스페이스가 그 데이터셋을 닫으면(데이터셋을 빼거나 워크스페이스를 닫을 때 등) 그 뒤로 캐시에 없는 블록을 읽는 호출은 IOError로, FindMaximumElevation은 Cancelled로 실패합니다. 소스가 답해야 하는 동안은 데이터셋을 워크스페이스에 남겨 두세요.
예제 파일은 512 픽셀보다 작아 축소본이 없으므로 레벨은 1개이고, 100미터 간격에는 레벨 0(픽셀 크기 55.66 m)이 골라집니다. 예제는 세 점을 읽어 식과 비교합니다. 쌍선형 보간은 픽셀 중심이 아닌 점에서 식과 조금 다릅니다. 이 언덕에서 그 차이는 0.07미터를 넘지 않으므로 허용 오차는 0.1미터입니다.
| 점 | 위치 | 읽은 값 | 식의 값 |
|---|---|---|---|
| (10.07, 50.04) | 꼭대기, 네 픽셀이 만나는 모서리 | 119.93 | 120.00 |
| (10.05025, 50.03025) | 픽셀 중심 | 23.39 | 23.39 |
| (10.06, 50.035) | 비탈, 네 픽셀이 만나는 모서리 | 78.53 | 78.56 |
// An elevation source reads heights at WGS84 longitude/latitude points. It
// interpolates bilinearly between the four pixel centers around the point,
// so a point between pixels differs from the formula by up to about 0.07 m
// here; 0.1 m is the tolerance. Level 0 is the full resolution.
static bool elevationSource(GDK::glsDataset& dataset)
{
GDK::glsRasterElevationSource* raw = nullptr;
bool found = false;
if (!succeeded(dataset.OpenRasterElevationSource(&raw, &found))) {
return false;
}
ElevationPtr source(raw);
if (!found) {
return unexpected("expected an elevation source");
}
int levels = 0;
int level = -1;
double resolution = 0;
if (!succeeded(source->GetLevelCount(&levels)) ||
!succeeded(source->LevelForSpacing(100.0, 50.04, &level, &resolution))) {
return false;
}
std::printf("[sample] elevation source: %d level, level for 100 m spacing %d (%.2f m per pixel)\n", levels,
level, resolution);
bool ok = levels == 1 && level == 0 && near(resolution, 55.66, 0.01);
const double points[3][2] = {{10.07, 50.04}, {10.05025, 50.03025}, {10.06, 50.035}};
for (const auto& point : points) {
bool hasValue = false;
double height = 0;
if (!succeeded(source->ElevationAt(point[0], point[1], false, &hasValue, &height))) {
return false;
}
const double expected = demHeight(point[0], point[1]);
std::printf("[sample] elevation at %.5f %.5f: %s %.2f m (formula %.2f m)\n", point[0], point[1],
yesNo(hasValue), height, expected);
ok = ok && hasValue && near(height, expected, 0.1);
}
return ok || unexpected("expected the heights of the formula");
}
값이 없는 곳
값이 없는 것은 실패가 아닙니다. 읽기 호출은 성공하고 값이 없다고 알립니다. ElevationAt은 found가 false이고 높이는 0입니다. ElevationAtStatus는 이유를 glsRasterElevationStatus로 줍니다(값은 고정, 값이 고정된 열거형).
| 상태 | 뜻 | 높이 |
|---|---|---|
Value |
값이 있습니다 | 보간한 높이 |
OutOfRange |
점이 래스터 밖입니다(가장자리는 안) | 0 |
NoData |
둘러싼 네 픽셀이 모두 NoData나 NaN입니다 | 0 |
NotCached |
cachedOnly일 때 필요한 블록이 캐시에 없습니다 |
0 |
둘러싼 네 픽셀 중 일부만 값이 없으면 보간하지 않고, 값이 있는 픽셀 중 점에 가장 가까운 픽셀의 값을 줍니다. 블록을 읽지 못하면 IOError로 실패합니다.
가장 높은 곳. FindMaximumElevation(&lonLatExtent, &found, &lonLat, &elevation)은 경위도 사각형 안에 중심이 든 픽셀 가운데 가장 높은 유효 픽셀을 찾아, 그 픽셀 중심과 값을 줍니다. 사각형이 한 방향으로라도 픽셀 하나보다 좁으면 그 방향으로는 사각형 가운데에 가장 가까운 픽셀을 보며, 이때는 중심이 사각형 밖이어도 그 픽셀을 씁니다. 4096 x 4096 픽셀 안에 드는 가장 고운 레벨을 읽으며, 그런 레벨이 없으면 InvalidArgument입니다. 값이 같은 픽셀이 여럿이면 더 북쪽, 그다음 더 서쪽의 픽셀을 고릅니다. 사각형이 래스터를 벗어나거나 사각형 안에 유효한 값이 없으면 found가 false(성공)이고, 좌표와 높이는 0입니다. 사각형의 좌표가 유한하지 않으면 InvalidArgument입니다.
예제는 래스터 밖의 점(10.2, 50.03)에서 OutOfRange, NoData 구석의 점(10.0, 50.06)에서 NoData를 확인하고, 그 점의 ElevationAt이 found가 false인 것도 확인합니다. 이어서 레이어에서 연 고도 소스로 래스터 전체에서 가장 높은 곳을 찾습니다. 꼭대기는 높이가 같은 네 픽셀이 만나는 모서리이므로 결과는 그중 한 픽셀의 중심이며, 꼭대기에서 반 픽셀 안에 있고 값은 그 픽셀의 값(119.93)입니다. 래스터에서 먼 사각형은 아무것도 찾지 않습니다.
// No value is not a failure: the call succeeds and says why there is none.
// OutOfRange is outside the raster, NoData is where the surrounding pixels
// are NoData. The height is 0 then. ElevationAt says only found or not.
static bool elevationOutside(GDK::glsDataset& dataset)
{
GDK::glsRasterElevationSource* raw = nullptr;
bool found = false;
if (!succeeded(dataset.OpenRasterElevationSource(&raw, &found))) {
return false;
}
ElevationPtr source(raw);
if (!found) {
return unexpected("expected an elevation source");
}
GDK::glsRasterElevationStatus outside = GDK::glsRasterElevationStatus::Value;
GDK::glsRasterElevationStatus noData = GDK::glsRasterElevationStatus::Value;
double outsideHeight = -1;
double noDataHeight = -1;
bool hasValue = true;
double height = -1;
if (!succeeded(source->ElevationAtStatus(10.2, 50.03, false, &outside, &outsideHeight)) ||
!succeeded(source->ElevationAtStatus(10.0, 50.06, false, &noData, &noDataHeight)) ||
!succeeded(source->ElevationAt(10.0, 50.06, false, &hasValue, &height))) {
return false;
}
std::printf("[sample] at 10.2 50.03 (outside): %s, %.2f m\n", elevationStatusName(outside), outsideHeight);
std::printf("[sample] at 10.0 50.06 (NoData corner): %s, %.2f m; ElevationAt found %s\n",
elevationStatusName(noData), noDataHeight, yesNo(hasValue));
return (outside == GDK::glsRasterElevationStatus::OutOfRange && outsideHeight == 0 &&
noData == GDK::glsRasterElevationStatus::NoData && noDataHeight == 0 && !hasValue) ||
unexpected("expected OutOfRange and NoData");
}
// A layer opens an elevation source over its own raster too. The search
// returns the center of the highest valid pixel inside a longitude/latitude
// rectangle. The hill top lies on the corner of four pixels of the same
// height, so the result is one of them, within half a pixel of the top. A
// rectangle that misses the raster finds nothing and is not an error.
static bool highestPoint(GDK::glsMapView& view)
{
LayerPtr layer = findLayer(view, kElevationLayer);
if (!layer) {
return false;
}
auto* elevation = dynamic_cast<GDK::glsRangeRasterLayer*>(layer.get());
if (elevation == nullptr) {
return unexpected("expected a range raster layer");
}
GDK::glsRasterElevationSource* raw = nullptr;
if (!succeeded(elevation->OpenElevationSource(&raw))) {
return false;
}
ElevationPtr source(raw);
GDK::glsEnvelope extent;
bool found = false;
GDK::glsMapPoint top;
double height = 0;
if (!succeeded(source->GetLonLatExtent(&extent)) ||
!succeeded(source->FindMaximumElevation(&extent, &found, &top, &height))) {
return false;
}
std::printf("[sample] highest point: %s, %.3f %.3f, %.2f m\n", yesNo(found), top.X, top.Y, height);
const GDK::glsEnvelope away{11.0, 51.0, 11.1, 51.1};
bool foundAway = true;
GDK::glsMapPoint where;
double awayHeight = -1;
if (!succeeded(source->FindMaximumElevation(&away, &foundAway, &where, &awayHeight))) {
return false;
}
std::printf("[sample] highest point in a rectangle away from the raster: %s\n", yesNo(foundAway));
return (found && near(top.X, 10.07, kDemPixel * 0.5 + 1e-9) && near(top.Y, 50.04, kDemPixel * 0.5 + 1e-9) &&
near(height, demHeight(top.X, top.Y), 1e-3) && !foundAway) ||
unexpected("expected the hill top");
}
래스터 만들기와 저장
래스터 데이터 소스는 메모리 데이터셋에서만 만들 수 있습니다. 다른 데이터셋의 CreateRasterDataSource는 NotSupported이며, GeoTIFF 공급자도 파일을 새로 만들지 않습니다. 메모리 래스터를 파일로 남기는 방법은 ExportGeoTiff입니다.
만들기. CreateRasterDataSource(name, width, height, dataType, geoTransform, epsg)는 이름, 크기, 자료형, 지오트랜스폼, 좌표계로 래스터를 만듭니다. 빈 이름이나 0 이하의 크기는 거절됩니다. EPSG 0은 좌표계를 모른다는 뜻입니다.
픽셀 쓰기. 쓴 픽셀은 메모리에만 있습니다.
SetPixels: 모든 픽셀을 바꿉니다. 위의 행부터 한 행씩이며, 데이터 크기는 정확히너비 x 높이 x 픽셀 바이트 수여야 합니다.- C++
WriteBlock: 픽셀 창 하나를 씁니다(버퍼 규칙은ReadBlock과 같음). 메모리 래스터는 래스터 밖에 놓인 부분을 버립니다. WritePixelRaw: 픽셀 하나를 자료형 그대로의 바이트로 씁니다.SetNoDataValue(hasValue, value): 밴드의 NoData 값을 정하거나(hasValue가false이면) 지웁니다.Float32래스터는 값을float으로 반올림해 둡니다. 메모리 래스터가 아니면NotSupported입니다.
GeoTIFF로 저장. ExportGeoTiff(path)는 메모리 래스터를 새 GeoTIFF 파일로 저장합니다. 경로는 UTF-8 문자열입니다.
Float32메모리 래스터만 저장합니다(그 밖에는NotSupported).- 격자는 북쪽이 위이고 회전하지 않아야 하며(
Gt1양수,Gt5음수,Gt2와Gt4가 0) 그렇지 않으면InvalidArgument입니다. - 좌표계는 EPSG 코드가 있는 지리 좌표계나 투영 좌표계여야 합니다(그 밖에는
NotSupported). - 파일을 둘 폴더가 없으면
InvalidArgument입니다. - 같은 이름의 파일이 이미 있으면
AlreadyExists로 거절하고 그 파일을 건드리지 않습니다. 덮어쓰려면 먼저 지웁니다. - 이 프로세스가 그 경로의 GeoTIFF를 열어 두고 있으면(그 파일의 데이터셋이나 거기서 얻은 데이터 소스, 고도 소스가 남아 있는 동안)
AlreadyExists가 아니라InvalidArgument로 거절하며, 이때도 파일을 건드리지 않습니다. 예제가 두 번째 저장 전에 파일을 닫는 것은 이 때문입니다. - NoData 값은 저장하는 순간의 밴드 값을 씁니다.
- 파일은 256 x 256 타일과 Deflate 압축으로 씁니다. 너비나 높이가 512 픽셀보다 크면 반씩 줄인 축소본도 함께 씁니다.
- 같은 폴더의 임시 파일에 다 쓴 뒤 이름을 붙이며, 실패하면 임시 파일을 지웁니다.
예제 데이터의 harbor_dem.tif도 이 방법으로 만들었습니다. 다음은 데이터를 만드는 make_data 예제의 코드입니다(C++만 있음). 메모리에 220 x 140 Float32 래스터를 만들어 식의 값과 NoData 블록을 넣고 저장합니다.
// Builds the elevation raster in memory and saves it as a GeoTIFF file. An
// existing file is removed first: the export never replaces a file.
bool CreateRaster(const std::filesystem::path& file)
{
std::error_code ec;
std::filesystem::remove(file, ec);
// A memory dataset holds the raster while it is filled.
GDK::glsDataset* rawDataset = nullptr;
if (!GDK::glsCreateMemoryDataset(&rawDataset).IsOk()) {
std::printf("[sample] create memory dataset failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
DatasetPtr dataset(rawDataset, GDK::glsReleaseDataset);
// The geotransform maps pixel corners to coordinates: Gt0/Gt3 are the
// top-left corner of pixel (0, 0), Gt1 the pixel width and Gt5 the pixel
// height, negative because rows run from north to south.
GDK::glsGeoTransform transform;
transform.Gt0 = kDemWest;
transform.Gt1 = kDemPixelSize;
transform.Gt2 = 0.0;
transform.Gt3 = kDemNorth;
transform.Gt4 = 0.0;
transform.Gt5 = -kDemPixelSize;
GDK::glsRasterDataSource* rawRaster = nullptr;
if (!dataset->CreateRasterDataSource("elevation", kDemWidth, kDemHeight, GDK::glsRasterDataType::Float32,
&transform, 4326, &rawRaster).IsOk()) {
std::printf("[sample] create raster failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
RasterPtr raster(rawRaster, GDK::glsReleaseRasterDataSource);
// The pixels row by row from the top row, one float per pixel: the height
// at each pixel centre, and the NoData value in the top-left block.
std::vector<float> pixels(static_cast<size_t>(kDemWidth) * kDemHeight);
for (int row = 0; row < kDemHeight; ++row) {
for (int column = 0; column < kDemWidth; ++column) {
const double lon = kDemWest + (column + 0.5) * kDemPixelSize;
const double lat = kDemNorth - (row + 0.5) * kDemPixelSize;
const bool noData = column < kDemNoDataSize && row < kDemNoDataSize;
pixels[static_cast<size_t>(row) * kDemWidth + column] =
noData ? kDemNoData : static_cast<float>(demHeight(lon, lat));
}
}
if (!raster->SetPixels(pixels.data(), pixels.size() * sizeof(float)).IsOk() ||
!raster->SetNoDataValue(true, kDemNoData).IsOk()) {
std::printf("[sample] writing the raster failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
// The path is UTF-8 text.
const std::string path = file.u8string();
if (!raster->ExportGeoTiff(path.c_str()).IsOk()) {
std::printf("[sample] GeoTIFF export failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
return true;
}
raster 예제는 메모리에 4 x 3 Float32 래스터를 만들어 값 0~11을 넣고(왼쪽 위는 NoData -9999), 행 1의 두 픽셀을 100과 101로 바꾸고 NoData 값을 정한 뒤 임시 폴더에 copy.tif로 저장합니다. 파일을 읽기 전용으로 다시 열어 12개 값과 NoData 값이 같은지 확인합니다. 그다음 메모리 래스터의 한 픽셀(열 3, 행 2)을 555로 바꾸고 같은 경로로 다시 저장하면 AlreadyExists로 거절되며, 파일을 다시 열어 그 픽셀이 처음 값 11 그대로인 것을 확인합니다.
glsCreateMemoryDataset(&dataset)으로 메모리 데이터셋을 만들고, CreateRasterDataSource의 지오트랜스폼은 포인터로 넘깁니다(빌린 값, nullptr도 됨). 좌표계 객체로 만들려면 CreateRasterDataSourceWithSrs를 씁니다. 두 번째 저장의 결과는 glsStatus의 Code로 확인합니다.
// Raster data sources are created on a memory dataset. The pixels are
// replaced with SetPixels (row by row from the top) or written by window
// with WriteBlock. ExportGeoTiff saves a Float32 memory raster as a new
// GeoTIFF file; it never replaces an existing file. Here the copy is read back
// and compared, and a second export to the same path is refused while the
// memory raster has changed: the file keeps its value.
static bool writeCopy(const std::filesystem::path& folder)
{
GDK::glsDataset* rawMemory = nullptr;
if (!succeeded(GDK::glsCreateMemoryDataset(&rawMemory))) {
return false;
}
DatasetPtr memory(rawMemory);
GDK::glsGeoTransform transform;
transform.Gt0 = 10.0;
transform.Gt1 = 0.01;
transform.Gt3 = 50.06;
transform.Gt5 = -0.01;
GDK::glsRasterDataSource* rawRaster = nullptr;
if (!succeeded(memory->CreateRasterDataSource("copy", 4, 3, GDK::glsRasterDataType::Float32, &transform, 4326,
&rawRaster))) {
return false;
}
RasterPtr raster(rawRaster);
std::vector<float> values(12);
for (int i = 0; i < 12; ++i) {
values[static_cast<size_t>(i)] = static_cast<float>(i);
}
values[0] = static_cast<float>(kNoData);
const float twoPixels[2] = {100.0f, 101.0f}; // row 1, columns 1 and 2
if (!succeeded(raster->SetPixels(values.data(), values.size() * sizeof(float))) ||
!succeeded(raster->WriteBlock(1, 1, 2, 1, twoPixels, sizeof(twoPixels))) ||
!succeeded(raster->SetNoDataValue(true, kNoData))) {
return false;
}
values[5] = twoPixels[0];
values[6] = twoPixels[1];
const std::filesystem::path file = folder / "copy.tif";
if (!succeeded(raster->ExportGeoTiff(file.u8string().c_str()))) {
return false;
}
std::printf("[sample] memory raster 4 x 3 Float32 saved as copy.tif\n");
DatasetPtr copy;
RasterPtr read;
if (!openRaster(file, copy, read)) {
return false;
}
std::vector<float> back(12);
GDK::glsRasterBand* rawBand = nullptr;
if (!succeeded(read->ReadBlock(0, 0, 4, 3, back.data(), back.size() * sizeof(float))) ||
!succeeded(read->GetBand(1, &rawBand))) {
return false;
}
BandPtr band(rawBand, GDK::glsReleaseRasterBand);
bool hasNoData = false;
double noData = 0;
if (!succeeded(band->GetNoDataValue(&hasNoData, &noData))) {
return false;
}
int equal = 0;
for (size_t i = 0; i < back.size(); ++i) {
if (back[i] == values[i]) {
++equal;
}
}
std::printf("[sample] read back: %d of 12 values equal, NoData %s %.1f\n", equal, yesNo(hasNoData), noData);
band.reset();
read.reset();
// Close the file before the second export: while the process has the file
// open as a GeoTIFF, an export to its path is refused with InvalidArgument
// instead of AlreadyExists (the file is left alone in both cases).
copy.reset();
const float changed = 555.0f;
if (!succeeded(raster->WriteBlock(3, 2, 1, 1, &changed, sizeof(changed)))) {
return false;
}
const GDK::glsStatus again = raster->ExportGeoTiff(file.u8string().c_str());
const bool refused = again.Code == GDK::glsResultCode::AlreadyExists;
if (!again.IsOk() && !refused) {
return succeeded(again); // another failure: print it and stop
}
std::printf("[sample] export to the same path again: %s\n", refused ? "AlreadyExists" : "not refused");
if (!openRaster(file, copy, read)) {
return false;
}
float kept = 0;
if (!succeeded(read->ReadBlock(3, 2, 1, 1, &kept, sizeof(kept)))) {
return false;
}
std::printf("[sample] the file still has %.1f at column 3, row 2\n", kept);
return (equal == 12 && hasNoData && noData == kNoData && refused && kept == values[11]) ||
unexpected("expected the values written and the file kept");
}
타일
타일 부분의 코드는 sdk_samples의 tiles 예제에서 가져왔습니다. 실행 방법은 raster 예제와 같고(<실행 파일> <sdk_samples/data 폴더> [<출력 폴더>]), 출력 폴더를 주면 그 폴더에 tiles.bmp(640x480, 96 dpi)를 남기고, 주지 않으면 임시 폴더에 씁니다. 예제는 harbor_tiles.mbtiles와 harbor_town.gpkg를 읽기 전용으로 열고, C++ 예제가 새로 만드는 타일 파일은 임시 폴더에 씁니다. 임시 폴더는 끝날 때 지웁니다. 데이터 폴더의 파일은 바뀌지 않습니다.
harbor_tiles.mbtiles는 Harbor Town 범위(경도 10.00~10.10, 위도 50.00~50.06)를 덮는 줌 11~13의 PNG 타일 15개를 담은 MBTiles 파일입니다. 타일마다 키에서 정해지는 무늬가 있어 픽셀 색으로 어느 타일인지 알 수 있습니다. 배경색은 줌마다 다르고(11 #E8F0FF, 12 #E8FFE8, 13 #FFF4E0), 전경색 #203040으로 테두리 한 줄을 칠하고, 키의 X가 짝수이면 왼쪽 위 사분면을, 홀수이면 오른쪽 위 사분면을, 키의 Y가 짝수이면 아래쪽 절반의 가로줄 하나(y 190~193)를 칠했습니다. 픽셀 좌표는 타일 왼쪽 위가 (0, 0)입니다. 자세한 내용은 sdk_samples/data/README.md에 있습니다.
C#에서 없는 것. 관리 래퍼의 glsTileDataset에는 타일 행렬 정보(GetTileMatrixSetInfo, GetTileMatrix, GetCrs), 저장 방식(GetStorageAxisOrigin), 사각형에 대한 키 범위(GetTileRangeForExtent), 키가 덮는 범위(GetTileExtent), 타일 쓰기와 지우기, 변경 알림과 도착 알림이 없고, 타일을 영상으로 푸는 멤버도 없습니다. 그래서 C# 예제는 키 범위를 Web Mercator 타일 공식으로 계산하고, 타일을 푸는 단계와 쓰는 단계를 건너뜁니다. 각 절이 그 차이를 적습니다.
타일 데이터셋 열기
MBTiles 파일은 읽기 전용 열기로 엽니다(데이터셋 열기). URI는 mbtiles:// 뒤에 경로를 UTF-8 문자열로, 구분자는 /로 붙입니다. 확장자가 .mbtiles인 경로도 됩니다. 없는 파일은 열리지 않습니다(새 파일은 타일 쓰기에서 만듭니다). 읽기 전용으로 연 파일은 바뀌지 않습니다. 쓰기로 열면 SDK가 파일을 WAL 방식으로 바꾸고, 열려 있는 동안 같은 폴더에 -wal, -shm 파일을 둡니다.
타일은 데이터셋을 타일 데이터셋으로 보아 읽습니다. AsTileDataset은 공급자에 타일이 없으면 실패가 아니라 "없음"으로 답합니다. 돌려받은 타일 데이터셋은 데이터셋을 함께 가지므로 둘 중 어느 것을 먼저 반납해도 됩니다. MBTiles는 메타데이터의 타일 형식(format)이 PNG, JPEG, WebP일 때 데이터 소스도 하나 보여 주지만(타일 바이트는 보지 않으므로 format이 없거나 모르는 값이면 보여 주지 않습니다), 타일은 타일 데이터셋으로 읽습니다.
타일 인덱스가 없는 파일. MBTiles의 tiles 표에 (zoom_level, tile_column, tile_row) 인덱스가 없으면, 열 때 SDK 로그에 경고를 남기고 타일을 찾을 때마다 표 전체를 훑습니다. 한 번 찾는 데 쓰는 작업량에 한도가 있어, 작은 파일은 그대로 읽히지만, 큰 파일은 한도를 넘는 순간부터 표를 더 찾지 않습니다(그때 SDK 로그에 경고를 남깁니다). 그 뒤로 HasTile은 모든 키에 false이고, ReadTile은 그 데이터셋이 이미 읽어 메모리에 둔 타일만 주고 나머지 키에는 실패 대신 없는 타일과 같은 결과를 줍니다. 그 파일로 만든 타일 레이어의 메타데이터 값 tile_index가 missing이면 인덱스가 없는 파일입니다(있으면 present). 쓰기로 열어 SQL로 인덱스를 만들면(CREATE UNIQUE INDEX tile_index ON tiles(zoom_level, tile_column, tile_row)) 다시 읽힙니다.
glsDataset::AsTileDataset(&tiles, &found)는 타일이 없으면 found가 false이고 tiles는 nullptr입니다. 돌려받은 glsTileDataset은 glsReleaseTileDataset으로 반납합니다.
// An MBTiles file opens through the "mbtiles://" URI with the path as UTF-8
// text with forward slashes. AsTileDataset views the dataset as a tile
// dataset; found is false (not an error) when the provider has no tiles. The
// tile dataset shares the dataset, so either can be released first.
static bool openTiles(const std::filesystem::path& file, DatasetPtr& dataset, TilesPtr& tiles)
{
GDK::glsDataset* rawDataset = nullptr;
if (!succeeded(GDK::glsOpenDatasetReadOnly(mbtilesUri(file).c_str(), &rawDataset))) {
return false;
}
dataset.reset(rawDataset);
GDK::glsTileDataset* rawTiles = nullptr;
bool found = false;
if (!succeeded(dataset->AsTileDataset(&rawTiles, &found))) {
return false;
}
tiles.reset(rawTiles);
std::printf("[sample] opened read-only: %s, tile dataset %s\n", file.filename().string().c_str(), yesNo(found));
return found || unexpected("expected a tile dataset");
}
타일 키와 범위
타일 키. 타일은 키(glsTileKey의 Z, X, Y)로 가리킵니다. Z는 줌, X는 서쪽부터 센 열, Y는 북쪽(위)부터 센 행이며 모두 0부터 셉니다. 공개 API의 키는 파일이 행을 어떻게 저장하든 이 규약을 따릅니다.
저장 방식. GetStorageAxisOrigin은 파일이 행을 어느 쪽부터 세어 저장하는지 알려 줍니다. MBTiles는 metadata 표의 scheme 값을 따릅니다. 값이 xyz이면 위부터(TopLeft) 세어 키 Y를 행 번호로 그대로 저장하고, tms이거나 행이 없거나 SDK가 모르는 값이면 아래부터(BottomLeft) 세어 키 Y의 타일을 행 2^Z - 1 - Y에 저장합니다. scheme에는 SDK가 아는 다른 값도 있으며, 그런 파일은 다른 타일 격자와 다른 행, 줌 번호 규칙을 쓸 수 있습니다. 이 변환은 SDK가 하므로, 키를 쓰는 코드는 저장 방식을 몰라도 됩니다. 저장 방식이 필요한 것은 SQL로 tiles 표를 직접 읽을 때입니다. 예제 파일에는 scheme 행이 없어 BottomLeft입니다.
줌 범위와 형식. scheme이 xyz나 tms이거나 없는 MBTiles 파일에서 GetMinZoom, GetMaxZoom, GetTileFormat은 메타데이터(minzoom, maxzoom, format)의 값입니다. minzoom이나 maxzoom 행이 없으면 0입니다. 타일 표에 실제로 있는 줌을 세지 않으므로, 타일을 쓸 때 메타데이터도 맞춰 두어야 합니다. glsTileFormat은 Unknown, Png, Jpeg, Webp, Pbf(벡터 타일), Binary입니다.
타일 행렬 집합. 줌마다의 격자는 타일 행렬 집합이 정합니다. scheme이 xyz나 tms이거나 없는 MBTiles 파일은 Web Mercator 타일 체계(WebMercatorQuad, EPSG:3857, 줌 0~22)를 씁니다. 줌 z의 격자는 2^z x 2^z개의 256 x 256 타일이고, 원점은 세계의 왼쪽 위(-20037508.34, 20037508.34)이며, 타일 한 픽셀은 2 x 20037508.34 / (256 x 2^z)미터입니다(줌 11 약 76.44미터, 12 약 38.22미터, 13 약 19.11미터). scheme의 다른 값 가운데에는 다른 타일 격자를 뜻하는 것도 있고, 다른 격자를 쓰는 데이터셋도 있으므로, 격자는 GetTileMatrixSetInfo와 GetTileMatrix로 확인합니다. 행렬 집합은 파일에 타일이 있는 줌과 관계없이 모든 줌을 보여 줍니다.
범위. 다음 호출의 사각형과 좌표는 모두 타일 격자의 좌표계(GetCrs, 예제는 EPSG:3857 미터)입니다.
| 호출 | 결과 |
|---|---|
GetBounds3857 |
데이터의 범위(EPSG:3857). MBTiles는 메타데이터 bounds(경위도)를 바꾼 값이고, bounds 행이 없으면 경도 -180~180, 위도 -85.0511~85.0511을 바꾼 값입니다 |
GetTileRange(zoom) |
그 줌의 모든 키. 범위는 양끝을 포함하며, MinX가 MaxX보다 크면 비어 있다는 뜻입니다. 행렬 집합에 없는 줌은 빈 범위입니다 |
GetTileRangeForExtent(zoom, extent) |
그 줌에서 사각형과 겹치는 타일의 키. 격자 밖은 잘라 내고, 사각형이 격자와 겹치지 않거나 유효하지 않으면 빈 범위입니다. 사각형의 끝이 타일 경계와 딱 맞으면 그 너머의 타일은 넣지 않습니다 |
GetTileExtent(key) |
키가 덮는 사각형. 행렬 집합에 없는 줌이나 격자 밖의 키는 성공하면서 MinX가 MaxX보다 큰 사각형을 줍니다 |
HasTile(key) |
파일에 그 타일이 있는지 |
예제는 줌 12의 키 범위(X, Y 모두 0~4095)와, Harbor Town 범위에 대한 키 범위(X 2161~2162, Y 1388~1389)를 얻어 네 키의 타일이 모두 있는지 확인합니다. C++ 예제는 행렬 정보와 저장 방식을 확인하고, 키 12/2161/1388이 덮는 사각형을 공식으로 계산한 값과 비교합니다.
GetCrs가 돌려준 좌표계는 glsReleaseSpatialReference로 반납합니다. GetTileMatrix(zoom, &matrix, &found)는 행렬 집합에 없는 줌이면 found가 false입니다.
// The format, the zoom range and the bounds come from the file's metadata.
// The bounds are in Web Mercator meters (EPSG:3857). The tile matrix set
// describes the grid of every zoom level, whatever zoom levels the file has
// tiles for. GetStorageAxisOrigin tells how the file stores rows; tile keys
// count rows from the top either way.
static bool tileInfo(GDK::glsTileDataset& tiles)
{
GDK::glsTileFormat format = GDK::glsTileFormat::Unknown;
int minZoom = -1;
int maxZoom = -1;
GDK::glsEnvelope b;
if (!succeeded(tiles.GetTileFormat(&format)) || !succeeded(tiles.GetMinZoom(&minZoom)) ||
!succeeded(tiles.GetMaxZoom(&maxZoom)) || !succeeded(tiles.GetBounds3857(&b))) {
return false;
}
std::printf("[sample] tiles: %s, zoom %d-%d\n", formatName(format), minZoom, maxZoom);
std::printf("[sample] bounds in EPSG:3857: %.1f %.1f %.1f %.1f\n", b.MinX, b.MinY, b.MaxX, b.MaxY);
const GDK::glsMapPoint sw = mercator(kWest, kSouth);
const GDK::glsMapPoint ne = mercator(kEast, kNorth);
bool ok = format == GDK::glsTileFormat::Png && minZoom == kMinZoom && maxZoom == kMaxZoom &&
near(b.MinX, sw.X, 0.01) && near(b.MinY, sw.Y, 0.01) && near(b.MaxX, ne.X, 0.01) &&
near(b.MaxY, ne.Y, 0.01);
GDK::glsTileMatrixSetInfo set;
GDK::glsTileMatrix matrix;
bool hasMatrix = false;
GDK::glsTileAxisOrigin origin = GDK::glsTileAxisOrigin::TopLeft;
GDK::glsSpatialReference* rawSrs = nullptr;
if (!succeeded(tiles.GetTileMatrixSetInfo(&set)) || !succeeded(tiles.GetTileMatrix(kZoom, &matrix, &hasMatrix)) ||
!succeeded(tiles.GetStorageAxisOrigin(&origin)) || !succeeded(tiles.GetCrs(&rawSrs))) {
return false;
}
SrsPtr srs(rawSrs, GDK::glsReleaseSpatialReference);
int epsg = 0;
if (!succeeded(srs->GetEpsgCode(&epsg))) {
return false;
}
std::printf("[sample] matrix set %s, EPSG:%d, zoom %d-%d; zoom 12: %d x %d tiles of %d x %d; rows stored %s\n",
set.Id, epsg, set.MinZoom, set.MaxZoom, matrix.MatrixWidth, matrix.MatrixHeight, matrix.TileWidth,
matrix.TileHeight, originName(origin));
ok = ok && std::strcmp(set.Id, "WebMercatorQuad") == 0 && epsg == 3857 && set.SrsEpsg == 3857 &&
set.MinZoom == 0 && set.MaxZoom == 22 && hasMatrix && matrix.MatrixWidth == 4096 &&
matrix.MatrixHeight == 4096 && matrix.TileWidth == kTileSize && matrix.TileHeight == kTileSize &&
origin == GDK::glsTileAxisOrigin::BottomLeft;
return ok || unexpected("expected the tile file of data/README.md");
}
// GetTileRange gives every key of a zoom level, GetTileRangeForExtent the keys
// whose tiles touch an extent given in the tile CRS (here EPSG:3857 meters).
// Ranges are inclusive; MinX greater than MaxX means none. Keys count columns
// from the west and rows from the north. GetTileExtent gives the area of one
// key in the tile CRS. HasTile tells whether the file holds that tile.
static bool tileRange(GDK::glsTileDataset& tiles)
{
GDK::glsTileRange all;
if (!succeeded(tiles.GetTileRange(kZoom, &all))) {
return false;
}
const GDK::glsMapPoint sw = mercator(kWest, kSouth);
const GDK::glsMapPoint ne = mercator(kEast, kNorth);
const GDK::glsEnvelope town{sw.X, sw.Y, ne.X, ne.Y};
GDK::glsTileRange r;
if (!succeeded(tiles.GetTileRangeForExtent(kZoom, &town, &r))) {
return false;
}
int keys = 0;
int present = 0;
for (int y = r.MinY; y <= r.MaxY; ++y) {
for (int x = r.MinX; x <= r.MaxX; ++x) {
bool has = false;
if (!succeeded(tiles.HasTile(GDK::glsTileKey{kZoom, x, y}, &has))) {
return false;
}
++keys;
present += has ? 1 : 0;
}
}
std::printf("[sample] zoom 12 keys: X %d-%d, Y %d-%d\n", all.MinX, all.MaxX, all.MinY, all.MaxY);
std::printf("[sample] Harbor Town at zoom 12: X %d-%d, Y %d-%d, %d of %d tiles present\n", r.MinX, r.MaxX, r.MinY,
r.MaxY, present, keys);
bool ok = all.MinX == 0 && all.MaxX == 4095 && all.MinY == 0 && all.MaxY == 4095 && r.MinX == kMinX &&
r.MaxX == kMaxX && r.MinY == kMinY && r.MaxY == kMaxY && keys == 4 && present == 4;
// The tile of the first key spans one 4096th of the world in each direction.
GDK::glsEnvelope e;
if (!succeeded(tiles.GetTileExtent(GDK::glsTileKey{kZoom, kMinX, kMinY}, &e))) {
return false;
}
const double span = 2.0 * kHalfWorld / 4096.0;
std::printf("[sample] tile 12/%d/%d covers %.1f %.1f %.1f %.1f\n", kMinX, kMinY, e.MinX, e.MinY, e.MaxX, e.MaxY);
ok = ok && near(e.MinX, -kHalfWorld + kMinX * span, 0.01) && near(e.MaxY, kHalfWorld - kMinY * span, 0.01) &&
near(e.MaxX - e.MinX, span, 0.01) && near(e.MaxY - e.MinY, span, 0.01);
return ok || unexpected("expected the keys of data/README.md");
}
타일 읽기와 풀기
바이트 읽기. ReadTile은 파일에 저장된 타일의 바이트를 그대로 복사해 줍니다. 예제 파일에서는 PNG 파일 하나입니다. MBTiles에서 함께 돌려주는 형식은 바이트를 살펴서 얻은 것이 아니라 파일의 타일 형식(메타데이터 format)입니다.
영상으로 풀기 (C++). 바이트를 픽셀로 푸는 방법은 두 가지입니다.
- 타일 데이터 소스(
glsTileDataSource)의ReadTileImage: 키로 타일을 읽어 풉니다. 타일 데이터 소스는 줌 하나의 타일을 읽습니다.OpenTileDataSourceForZoom(zoom)은 그 줌의 소스를 열며, MBTiles에서 파일의 줌 범위 밖이면NotFound입니다.OpenTileDataSource는 기본 소스이며, MBTiles에서는 가장 고운 줌(maxzoom)의 소스입니다. MBTiles의 소스는 자기 줌이 아닌 키를 "타일 없음"으로 답합니다. glsDecodeTileImage(data, size, ...): 이미 가진 바이트를 풉니다. 같은 일을 하는glsTileDataSource::DecodeTileImage도 있습니다.
푼 픽셀은 위의 행부터 한 행씩, 행 사이에 빈 바이트 없이 픽셀당 4바이트이며, 픽셀 형식(glsPixelFormat)과 너비, 높이를 함께 돌려줍니다. 지금 구현은 PNG, JPEG, WebP 같은 영상을 Bgra32Premultiplied(B, G, R, A 순서, 미리 곱한 알파)로 풉니다. 돌려받은 형식을 확인하고 쓰세요. 풀 수 없는 바이트는 IOError, 빈 데이터는 InvalidArgument입니다.
버퍼 규약. ReadTile, ReadTileImage, glsDecodeTileImage는 두 번 부릅니다. 버퍼 없이(nullptr, 크기 0) 불러 필요한 크기를 얻고, 그 크기의 버퍼로 다시 부릅니다. 버퍼가 필요한 크기보다 작으면 InvalidArgument입니다.
예제는 키 12/2161/1388의 타일을 읽어 PNG 머리 바이트를 확인합니다. C++ 예제는 이어서 줌 12의 타일 데이터 소스로 같은 타일을 풀어 256 x 256 Bgra32Premultiplied인 것을 확인하고, 네 점, 왼쪽 위 사분면 (64, 64), 오른쪽 위 사분면 (192, 64), 가로줄 (128, 192), 테두리 (0, 160)의 색을 키에서 계산한 무늬의 색과 비교합니다. 이 타일은 X가 홀수, Y가 짝수이므로 첫 점만 배경색이고 나머지는 전경색입니다. 키의 행 방향이 뒤집혀 있었다면 다른 타일이나 없는 타일을 읽게 되어 이 비교가 실패합니다. 마지막으로 ReadTile로 읽은 바이트를 glsDecodeTileImage로 푼 결과가 같은지 확인합니다.
ReadTile(key, &format, buf, bufSize, &requiredSize, &found)의 format과 found는 nullptr로 둘 수 있습니다. OpenTileDataSource, OpenTileDataSourceForZoom이 돌려준 소스는 glsReleaseTileDataSource로 반납합니다.
// ReadTile copies the tile's stored bytes, here a PNG file. Call it once with
// no buffer to get the size, then with a buffer of that size. The format it
// reports is the file's tile format.
static bool readTile(GDK::glsTileDataset& tiles, std::vector<uint8_t>& png)
{
const GDK::glsTileKey key{kZoom, kMinX, kMinY};
size_t size = 0;
bool found = false;
GDK::glsTileFormat format = GDK::glsTileFormat::Unknown;
if (!succeeded(tiles.ReadTile(key, &format, nullptr, 0, &size, &found))) {
return false;
}
png.assign(size, 0);
if (found && !succeeded(tiles.ReadTile(key, &format, png.data(), png.size(), &size, &found))) {
return false;
}
const uint8_t signature[8] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
const bool isPng = png.size() > 8 && std::memcmp(png.data(), signature, 8) == 0;
std::printf("[sample] tile %s: found %s, %s, PNG signature %s\n", keyText(key).c_str(), yesNo(found),
formatName(format), yesNo(isPng));
return (found && format == GDK::glsTileFormat::Png && isPng) || unexpected("expected a PNG tile");
}
// A tile data source reads the tiles of one zoom level. ReadTileImage reads
// a tile and decodes it to pixels: rows from the top, no padding, 4 bytes per
// pixel in the format it reports. glsDecodeTileImage decodes bytes the caller
// already has. Both follow the two-call size pattern. The pixels are checked
// against the tile pattern computed from the key.
static bool decodeTile(GDK::glsTileDataset& tiles, const std::vector<uint8_t>& png)
{
GDK::glsTileDataSource* rawSource = nullptr;
if (!succeeded(tiles.OpenTileDataSourceForZoom(kZoom, &rawSource))) {
return false;
}
TileSourcePtr source(rawSource);
const GDK::glsTileKey key{kZoom, kMinX, kMinY};
size_t size = 0;
int width = 0;
int height = 0;
GDK::glsPixelFormat format = GDK::glsPixelFormat::Unknown;
bool found = false;
if (!succeeded(source->ReadTileImage(key, nullptr, 0, &size, &width, &height, &format, &found))) {
return false;
}
std::vector<uint8_t> pixels(size);
if (found && !succeeded(source->ReadTileImage(key, pixels.data(), pixels.size(), &size, &width, &height,
&format, &found))) {
return false;
}
std::printf("[sample] decoded tile %s: %d x %d, %s\n", keyText(key).c_str(), width, height,
pixelFormatName(format));
if (!found || width != kTileSize || height != kTileSize || format != GDK::glsPixelFormat::Bgra32Premultiplied ||
pixels.size() != static_cast<size_t>(kTileSize) * kTileSize * 4) {
return unexpected("expected a 256 x 256 BGRA tile");
}
// Top-left quadrant, top-right quadrant, the band of even rows, the border.
const int points[4][2] = {{64, 64}, {192, 64}, {128, 192}, {0, 160}};
int matching = 0;
for (const auto& point : points) {
const uint8_t* q = pixels.data() + (static_cast<size_t>(point[1]) * kTileSize + point[0]) * 4;
const uint32_t rgb = static_cast<uint32_t>(q[0]) | (static_cast<uint32_t>(q[1]) << 8) |
(static_cast<uint32_t>(q[2]) << 16);
if (q[3] == 255 && rgb == patternColor(key.Z, key.X, key.Y, point[0], point[1])) {
++matching;
}
}
std::vector<uint8_t> again;
size_t againSize = 0;
if (!succeeded(GDK::glsDecodeTileImage(png.data(), png.size(), nullptr, 0, &againSize, &width, &height, &format))) {
return false;
}
again.resize(againSize);
if (!succeeded(GDK::glsDecodeTileImage(png.data(), png.size(), again.data(), again.size(), &againSize, &width,
&height, &format))) {
return false;
}
const bool same = again == pixels;
std::printf("[sample] pattern pixels: %d of 4 match the key; glsDecodeTileImage gives the same pixels: %s\n",
matching, yesNo(same));
return (matching == 4 && same) || unexpected("expected the pattern of the key");
}
없는 타일
타일이 없는 키를 읽는 것은 실패가 아닙니다. HasTile은 false이고, ReadTile은 성공하면서 "없음"으로 답합니다. 데이터 옆의 키, 파일에 없는 줌의 키, 격자 밖의 키가 모두 그렇습니다.
| 호출 | C++ | C# |
|---|---|---|
ReadTile |
Ok, found false, 필요한 크기 0, 형식 Unknown |
null, 형식 Unknown |
ReadTileImage |
Ok, found false, 크기 0, 너비와 높이 0, 픽셀 형식 Unknown |
없음 |
MBTiles에서는 타일을 찾는 일 자체가 실패해도(데이터셋이 닫혔거나, 인덱스가 없는 큰 파일에서 읽기가 멈췄을 때 등) HasTile과 ReadTile은 같은 "없음"으로 답합니다. 이 가운데 SDK 로그에 남는 것은 인덱스가 없는 큰 파일에서 읽기가 멈춘 경우뿐이며, 그 경우는 타일 레이어의 메타데이터 값 tile_index가 missing인 것으로도 알 수 있습니다. 닫힌 데이터셋이나 데이터베이스 오류는 로그 없이 "없음"이 됩니다. 네트워크 소스의 "없음"은 뜻이 다릅니다(네트워크 소스).
예제는 데이터 옆의 키 12/2160/1388과 줌 10의 키 10/540/347을 읽어, 두 키 모두 HasTile이 false이고 ReadTile이 "없음"과 형식 Unknown으로 답하는 것을 확인합니다.
// A key with no tile is not an error: HasTile gives false, and ReadTile
// succeeds with found false, size 0 and format Unknown. That holds for a key
// next to the data and for a zoom level the file does not have.
static bool missingTile(GDK::glsTileDataset& tiles)
{
const GDK::glsTileKey keys[2] = {{kZoom, kMinX - 1, kMinY}, {10, kMinX / 4, kMinY / 4}};
const char* const what[2] = {"next to the data", "zoom 10"};
bool ok = true;
for (int i = 0; i < 2; ++i) {
bool has = true;
bool found = true;
size_t size = 1;
GDK::glsTileFormat format = GDK::glsTileFormat::Png;
if (!succeeded(tiles.HasTile(keys[i], &has)) ||
!succeeded(tiles.ReadTile(keys[i], &format, nullptr, 0, &size, &found))) {
return false;
}
std::printf("[sample] tile %s (%s): HasTile %s, ReadTile found %s, format %s\n", keyText(keys[i]).c_str(),
what[i], yesNo(has), yesNo(found), formatName(format));
ok = ok && !has && !found && size == 0 && format == GDK::glsTileFormat::Unknown;
}
return ok || unexpected("expected no tile");
}
타일 레이어
만들기. 타일 레이어(Tile)는 타일 데이터셋의 타일을 지도에 그립니다. 레이어는 데이터셋을 함께 가지므로, 만든 뒤에는 데이터셋 래퍼를 반납해도 됩니다. 지도에 더하는 규칙과 id는 다른 레이어와 같습니다(8장). 레이어를 만들려면 데이터셋에 래스터 타일 소스가 있어야 합니다. 벡터 타일(Pbf) MBTiles처럼 그런 소스가 없으면 InvalidArgument입니다.
바탕 레이어와 오버레이. 타일 레이어는 바탕 레이어이거나 오버레이입니다. MBTiles는 메타데이터 type이 overlay(대소문자 무관)일 때 오버레이이고, 그 밖의 값이거나 행이 없으면 바탕 레이어입니다. 만든 레이어가 어느 쪽인지는 GetTileInfo의 IsOverlay로 확인합니다.
- 불투명도가 1인 바탕 레이어는, 타일 격자가 화면 전체를 덮으면 타일을 그리지 않은 자리를 흰색으로 채웁니다. 그 아래의 레이어는 보이지 않습니다.
- 오버레이, 불투명도가 1보다 작은 레이어, 화면이 타일 격자 밖까지 보이는 경우에는 타일이 없는 자리가 투명합니다.
줌 규칙. 타일 레이어는 한 번 그릴 때 줌 하나의 타일을 씁니다. 지도의 해상도를 타일 격자의 좌표계 단위로 재어(DPI가 96이 아니면 해상도 x DPI / 96) 각 줌의 타일 해상도와 비교하고, 다음과 같이 고릅니다.
- 파일의 줌 범위(
minzoom~maxzoom) 가운데, 타일 해상도가 지도의 해상도보다 거칠지 않은 가장 거친 줌을 씁니다. - 지도가 가장 고운 줌보다 더 고우면 가장 고운 줌의 타일을 늘려 그립니다.
- 지도가 가장 거친 줌보다 거칠면 레이어를 그리지 않습니다. 바탕 레이어라도 흰색으로 채우지 않습니다.
고른 줌의 타일이 없는 자리는, 더 거친 줌(파일의 가장 거친 줌까지, 최대 네 단계)에 타일이 있으면 그 일부를 늘려 채웁니다.
타일 부재와 프레임 완성. 로컬 MBTiles에서 없는 타일은 읽기가 끝난 빈 자리로 처리합니다. 파일 범위 밖이나 군데군데 빠진 타일 때문에 프레임이 계속 미완성으로 남지 않습니다. 더 거친 줌의 타일로 채운 자리도 완료할 수 있습니다. 원격 타일은 다운로드와 재시도를 기다리는 동안 미완성이며, 데이터 없음이나 영구 실패가 확정되면 완료할 수 있습니다. 단, 대체할 상위 타일을 아직 내려받는 중이면 그 요청도 기다립니다. 7장의 판정식(HasCompletedFrame이고 CompletedFrameMatchesCurrentView)으로 완료를 확인하고, 네트워크 지연이나 재시도에 대비해 기다리는 코드에는 시간 제한을 두세요. 진행 중 화면은 CurrentViewPreview로 복사합니다(7장). 타일 레이어가 로컬 파일만 쓰면 없는 타일 때문에 완성이 끝없이 미뤄지는 일은 없습니다. 예제의 화면에도 파일에 줌 13 타일이 없는 키(데이터의 동쪽)가 보이지만 프레임은 완성되고, 그 자리는 파일에 있는 더 거친 줌의 타일로 채워집니다.
지도 좌표계. 타일 레이어가 있는 지도는 타일 격자의 좌표계를 씁니다(7장). 예제 지도는 EPSG:3857이 되고, 경위도인 Harbor Town 레이어는 그 좌표계로 바뀌어 그려집니다. SetCrs로 지도의 좌표계를 다르게 정하면 타일을 지도 좌표계로 변환해 그립니다. ZoomToLayer는 맞춘 결과가 가장 거친 줌보다 거칠면, 그 줌이 그려지는 해상도까지 확대합니다.
스타일. C++ glsTileLayer의 GetStyle, SetStyle은 glsRasterRenderStyle(보간 방법, 밝기, 대비, 밴드 번호)을 읽고 씁니다. 타일을 그릴 때 쓰이는 것은 보간 방법뿐이고, 밝기, 대비, 밴드 번호는 저장되고 읽히기만 합니다.
예제는 타일 레이어를 id tiles로 지도에 더하고, 그 위에 harbor_town.gpkg의 세 레이어를 올린 뒤 구역 레이어의 불투명도를 0.5로 낮춰 타일이 비쳐 보이게 합니다. 레이어 정보는 바탕 레이어, 줌 11~13, 타일 크기 256, WebMercatorQuad, BottomLeft이고 지도는 EPSG:3857입니다.
glsCreateTileLayer에는 두 가지가 있습니다. glsCreateTileLayer(glsDataset*, &layer)는 데이터셋이 타일 데이터셋이 아니면 InvalidArgument이고, glsCreateTileLayer(glsTileDataset*, &layer)는 이미 얻은 타일 데이터셋으로 만듭니다. 만들어지는 레이어는 같습니다. glsReleaseTileLayer(또는 glsReleaseMapLayer)로 반납합니다. GetTileInfo(glsTileLayerInfo)와 GetTileMetadataValue는 glsMapLayer의 멤버이며, 타일 레이어가 아니면 InvalidArgument입니다.
// A tile layer draws the tiles of a tile dataset; it shares the dataset, and
// the map keeps the layer, so both wrappers can be released after AddLayer.
// A file whose metadata "type" is not "overlay" is a base layer. With a tile
// layer on it, the map takes the tile grid's coordinate system. The Harbor
// Town layers go on top; their districts are made half transparent so that
// the tiles show through.
static bool tileLayer(GDK::glsTileDataset& tiles, GDK::glsDataset& vectors, GDK::glsMapView& view,
const std::filesystem::path& stylesDir)
{
GDK::glsTileLayer* raw = nullptr;
if (!succeeded(GDK::glsCreateTileLayer(&tiles, &raw))) {
return false;
}
TileLayerPtr layer(raw, GDK::glsReleaseTileLayer);
GDK::glsTileLayerInfo info;
if (!succeeded(layer->SetId(kTileLayer)) || !succeeded(layer->GetTileInfo(&info)) ||
!succeeded(view.AddLayer(layer.get()))) {
return false;
}
layer.reset();
if (!sample::addHarborLayers(vectors, view, stylesDir.u8string())) {
return false; // addHarborLayers has printed why
}
LayerPtr districts = findLayer(view, "districts");
int count = 0;
GDK::glsSpatialReference* rawSrs = nullptr;
if (!districts || !succeeded(districts->SetOpacity(0.5f)) || !succeeded(view.GetLayerCount(&count)) ||
!succeeded(view.GetCrs(&rawSrs))) {
return false;
}
SrsPtr srs(rawSrs, GDK::glsReleaseSpatialReference);
int epsg = 0;
if (srs && !succeeded(srs->GetEpsgCode(&epsg))) {
return false;
}
std::printf("[sample] tile layer: overlay %s, zoom %d-%d, tile size %d, %s, rows stored %s\n",
yesNo(info.IsOverlay), info.MinZoom, info.MaxZoom, info.TileSize, info.TileMatrixSetId,
originName(info.TileAxisOrigin));
std::printf("[sample] map layers %d, map CRS EPSG:%d\n", count, epsg);
return (!info.IsOverlay && info.MinZoom == kMinZoom && info.MaxZoom == kMaxZoom && info.TileSize == kTileSize &&
std::strcmp(info.TileMatrixSetId, "WebMercatorQuad") == 0 &&
info.TileAxisOrigin == GDK::glsTileAxisOrigin::BottomLeft && count == 4 && epsg == 3857) ||
unexpected("expected a base tile layer under four layers in EPSG:3857");
}
그려서 확인하기. 예제는 640x480, 96 dpi로 크기를 정하고 ZoomToLayer("tiles", 0)으로 레이어에 맞춥니다. 해상도는 약 21.66미터이고, 줌 13(약 19.11미터)이 이보다 거칠지 않은 가장 거친 줌이므로 줌 13의 타일이 그려집니다. 이 화면의 동쪽 끝에는 파일에 줌 13 타일(X 4323~4325)이 없는 키가 보이지만(타일 부재와 프레임 완성), 프레임을 기다리면 완성 프레임이 옵니다. 예제는 그 프레임을 복사해 tiles.bmp로 씁니다. 그림에는 반투명한 구역 아래로 줌 13 타일의 무늬(연한 주황 배경 위의 짙은 남색 사분면, 가로줄, 테두리)가 보이고, 그 위에 도로와 장소가 있습니다. 동쪽 끝의 좁은 띠에는 더 거친 줌의 타일을 늘린 무늬가 보입니다.
예제는 마을 밖의 다섯 점(다른 레이어가 타일을 덮지 않는 곳)에서 화면 픽셀의 색을 읽어, 그 점의 줌 13 키와 타일 안의 픽셀 위치로 계산한 무늬의 색과 정확히 같은지 확인합니다. 세 점은 사분면과 배경에 있고, 두 점은 행을 가립니다. 짝수 행 타일 13/4325/2776의 가로줄 가운데(타일 픽셀 (224, 192), 전경색)와, 그 아래 홀수 행 타일 13/4325/2777의 같은 자리(배경색)입니다. 행이 한 칸 어긋나면 두 색이 바뀌고, 저장된 행을 뒤집지 않고 읽으면 이 키들에 타일이 없어 색이 맞지 않습니다. 가로줄은 화면에서 약 3.5픽셀 높이이므로, 예제는 가로줄 한가운데를 담은 화면 픽셀을 읽습니다. 또 데이터 동쪽의 두 점(10.110, 50.003)과 (10.110, 50.012)는 파일에 그 자리의 줌 13 타일도, 줌 12 타일도 없으므로 줌 11 타일 11/1081/694로 채워집니다. 예제는 두 점의 색이 줌 11 타일의 무늬에서 계산한 색, 곧 앞의 점은 배경색, 뒤의 점은 오른쪽 위 사분면의 전경색과 같은지 확인합니다. 짝인 이 두 점은 다른 타일(짝수 열인 11/1080/694)이나 좌우로 뒤집힌 자리, 남북으로 약 10 타일 픽셀 넘게 어긋난 자리로 채웠다면 맞지 않습니다. 끝으로 해상도를 200미터로 바꿔(줌 11의 약 76.44미터보다 거침) 다시 그리고, 프레임에 줌 배경색 픽셀이 하나도 없는 것을 확인합니다.
// The map view starts with no size: Resize first, then fit the view to the
// tile layer. The layer draws one zoom level, chosen from the resolution, so
// the expected color of a screen point follows from its key and the pattern.
// The fitted view also shows keys east of the data for which the file has no
// tile at that level: the frame still completes, and there the layer fills in
// from a coarser level the file has. Zoomed out beyond the coarsest level, the
// layer draws nothing.
static bool renderToFile(GDK::glsMapView& view, const std::filesystem::path& folder)
{
if (!succeeded(view.Resize(kWidth, kHeight, kDpi, kDpi)) || !succeeded(view.ZoomToLayer(kTileLayer, 0))) {
return false;
}
if (!sample::waitForFrame(view, kRenderTimeoutMs)) {
return false; // waitForFrame has printed why
}
std::vector<unsigned char> pixels;
if (!sample::copyFrame(view, kWidth, kHeight, pixels)) {
std::printf("[sample] copy frame failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
if (!sample::writeBmp((folder / "tiles.bmp").u8string(), pixels.data(), kWidth, kHeight)) {
std::printf("[sample] could not write tiles.bmp\n");
return false;
}
std::printf("[sample] wrote tiles.bmp\n");
double resolution = 0;
if (!succeeded(view.GetResolution(&resolution))) {
return false;
}
const int zoom = drawnZoom(resolution);
std::vector<GDK::glsMapPoint> points;
for (const auto& point : kCheckPoints) {
points.push_back(mercator(point[0], point[1]));
}
// The band is 4 tile pixels, about 3.5 screen pixels high here. The screen
// pixel read is the one that holds the band's middle, so its center lies
// within half a screen pixel (about 0.6 tile pixel) of it, inside the band.
points.push_back(tilePoint(13, kBandColumn, kEvenRow, kBandX + 0.5, kBandY));
points.push_back(tilePoint(13, kBandColumn, kEvenRow + 1, kBandX + 0.5, kBandY));
int matching = 0;
for (const GDK::glsMapPoint& m : points) {
GDK::glsScreenPoint s;
if (!succeeded(view.WorldToScreen(m.X, m.Y, &s))) {
return false;
}
const TilePixel t = tilePixel(m, zoom);
if (zoom != 0 && screenColor(pixels, s) == patternColor(zoom, t.column, t.row, t.x, t.y)) {
++matching;
}
}
const bool bandDiffers = patternColor(13, kBandColumn, kEvenRow, kBandX, kBandY) !=
patternColor(13, kBandColumn, kEvenRow + 1, kBandX, kBandY);
std::printf("[sample] %.2f m per pixel selects zoom %d; %d of 5 map points have the color of their tile\n",
resolution, zoom, matching);
int eastMatching = 0;
uint32_t eastExpected[2] = {0, 0};
for (int i = 0; i < 2; ++i) {
const GDK::glsMapPoint east = mercator(kFallbackPoints[i][0], kFallbackPoints[i][1]);
GDK::glsScreenPoint eastScreen;
if (!succeeded(view.WorldToScreen(east.X, east.Y, &eastScreen))) {
return false;
}
const TilePixel parent = tilePixel(east, kMinZoom);
eastExpected[i] = patternColor(kMinZoom, parent.column, parent.row, parent.x, parent.y);
// Off the screen, screenColor gives a value no tile color equals.
const bool outsideFinerTiles = tilePixel(east, 13).column > kLastColumn13 &&
tilePixel(east, 12).column > kLastColumn12;
if (outsideFinerTiles && screenColor(pixels, eastScreen) == eastExpected[i]) {
++eastMatching;
}
}
const bool fallback = eastMatching == 2 && eastExpected[0] == background(kMinZoom) &&
eastExpected[1] == kForeground;
std::printf("[sample] east of the zoom 13 and 12 tiles: %d of 2 points have the colors of the zoom 11 tile\n",
eastMatching);
// 200 m per pixel is coarser than the zoom 11 tiles (76.44 m per pixel).
if (!succeeded(view.SetResolution(200.0)) || !sample::waitForFrame(view, kRenderTimeoutMs)) {
return false;
}
if (!sample::copyFrame(view, kWidth, kHeight, pixels)) {
std::printf("[sample] copy frame failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
const int tilePixels = countTileBackgrounds(pixels);
std::printf("[sample] at 200 m per pixel, coarser than zoom 11: tile pixels %d\n", tilePixels);
return (zoom == 13 && matching == 5 && bandDiffers && fallback && drawnZoom(200.0) == 0 && tilePixels == 0) ||
unexpected("expected the tiles of zoom 13, zoom 11 east of the data, and none when zoomed out");
}
타일 쓰기 (C++)
새 파일. glsCreateDataset("mbtiles://<경로>", &dataset)는 새 MBTiles 파일을 만들고 쓰기로 엽니다. 그 경로에 파일이 이미 있으면 지우고 새로 만듭니다. 새 파일의 metadata 표에는 name(파일 이름에서 확장자를 뺀 것), format(png), minzoom(0), maxzoom(14)가 있고 scheme 행은 없으므로 행을 아래부터 셉니다. 기존 파일에 쓰려면 glsOpenDataset으로 엽니다. 쓰기로 열 수 없는 파일(읽기 전용 파일 등)은 읽기 전용으로 열리며, 그때 쓰기는 실패합니다.
메타데이터. MBTiles의 메타데이터는 SQL로만 씁니다(glsSqlExecutor, 5장). SQL을 실행하면 SDK가 메타데이터를 다시 읽으므로, 그 뒤의 GetMinZoom 등은 바뀐 값을 줍니다.
쓰기와 지우기. C++ glsTileDataset의 멤버입니다.
WriteTile(key, format, data, size): 키에 바이트를 그대로 저장합니다. 그 키에 타일이 있으면 바꿉니다. SDK는 바이트가 영상인지, 형식 인자가 파일의 형식과 맞는지 확인하지 않으며, 읽을 때 보고하는 형식은 파일의 형식입니다. 줌 범위나bounds메타데이터도 바꾸지 않으므로 필요하면 SQL로 맞춥니다.DeleteTile(key): 그 키의 타일을 지웁니다. 타일이 없는 키도 성공합니다.- 읽기 전용으로 연 파일에 쓰거나 지우면 실패합니다(
DbError).
변경 알림. AddTileMutatedListener(callback, userData, &token)로 등록한 함수는 WriteTile이나 DeleteTile이 성공할 때마다(타일이 없는 키를 지울 때도) 불리고, RemoveTileMutatedListener(token)으로 뗍니다. MBTiles에서는 쓴 스레드에서, 변경이 저장된 뒤에 불립니다. SQL로 바꾼 타일은 알리지 않습니다. 콜백이 받은 키는 콜백 안에서만 쓸 수 있습니다(스레드).
예제 데이터의 harbor_tiles.mbtiles는 이 방법으로 만들었습니다. 다음은 데이터를 만드는 make_data 예제의 코드입니다(C++만 있음). 새 파일을 만들고 메타데이터를 SQL로 쓴 뒤, 범위를 덮는 키마다 PNG 타일을 씁니다.
// Creates an MBTiles file, writes its metadata, and writes one PNG tile for
// every tile key of zoom levels 11 to 13 that covers the Harbor Town extent.
// An existing file is removed first. On success *outDataset is the open
// dataset; the caller releases it with glsReleaseDataset().
bool WriteTiles(const std::filesystem::path& file, GDK::glsDataset** outDataset)
{
std::error_code ec;
for (const char* suffix : {"", "-wal", "-shm", "-journal"}) {
std::filesystem::path old = file;
old += suffix;
std::filesystem::remove(old, ec);
}
// The URI is "mbtiles://" plus the path as UTF-8 text with forward slashes.
const std::string uri = "mbtiles://" + file.generic_u8string();
GDK::glsDataset* rawDataset = nullptr;
if (!GDK::glsCreateDataset(uri.c_str(), &rawDataset).IsOk()) {
std::printf("[sample] create tile dataset failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
DatasetPtr dataset(rawDataset, GDK::glsReleaseDataset);
// MBTiles keeps its metadata in the "metadata" table, written with SQL.
// A new file already has the rows name (the file name), format (png),
// minzoom (0) and maxzoom (14); INSERT OR REPLACE overwrites them. The
// bounds are longitude/latitude: west, south, east, north.
GDK::glsSqlExecutor* rawExecutor = nullptr;
if (!dataset->CreateSqlExecutor(&rawExecutor).IsOk()) {
std::printf("[sample] create SQL executor failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
SqlExecutorPtr executor(rawExecutor, GDK::glsReleaseSqlExecutor);
const char* const metadataSql =
"INSERT OR REPLACE INTO metadata (name, value) VALUES "
"('name', 'Harbor Town tiles'), ('format', 'png'), ('minzoom', '11'), "
"('maxzoom', '13'), ('bounds', '10.0,50.0,10.1,50.06'), ('type', 'baselayer')";
if (!executor->ExecuteNonQuery(metadataSql).IsOk()) {
std::printf("[sample] writing the tile metadata failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
GDK::glsTileDataset* rawTiles = nullptr;
bool isTileDataset = false;
if (!dataset->AsTileDataset(&rawTiles, &isTileDataset).IsOk() || !isTileDataset) {
std::printf("[sample] the dataset has no tile view: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
TileDatasetPtr tiles(rawTiles, GDK::glsReleaseTileDataset);
// The tile keys come from the tile matrix: the bounds in Web Mercator
// metres, then the key range that covers them at each zoom level.
GDK::glsEnvelope bounds;
if (!tiles->GetBounds3857(&bounds).IsOk()) {
std::printf("[sample] reading the tile bounds failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
for (int zoom = kTileMinZoom; zoom <= kTileMaxZoom; ++zoom) {
GDK::glsTileRange range;
if (!tiles->GetTileRangeForExtent(zoom, &bounds, &range).IsOk() || range.MinX > range.MaxX) {
std::printf("[sample] no tile range at zoom %d: %s\n", zoom, GDK::glsGetLastErrorMessage());
return false;
}
for (int y = range.MinY; y <= range.MaxY; ++y) {
for (int x = range.MinX; x <= range.MaxX; ++x) {
// Keys count from the top-left tile of the zoom level.
GDK::glsTileKey key;
key.Z = zoom;
key.X = x;
key.Y = y;
const std::vector<uint8_t> png = encodeTilePng(zoom, x, y);
if (!tiles->WriteTile(key, GDK::glsTileFormat::Png, png.data(), png.size()).IsOk()) {
std::printf("[sample] writing tile %d/%d/%d failed: %s\n", zoom, x, y,
GDK::glsGetLastErrorMessage());
return false;
}
}
}
}
if (!dataset->Flush().IsOk()) {
std::printf("[sample] flush failed: %s\n", GDK::glsGetLastErrorMessage());
return false;
}
*outDataset = dataset.release();
return true;
}
tiles 예제는 임시 폴더에 새 타일 파일 copy.mbtiles를 만들어 저장 방식이 BottomLeft인 것을 확인하고, 앞에서 읽은 타일의 바이트를 키 12/0/0에 씁니다. 다시 읽은 바이트가 같은 것을 확인합니다. ReadTile은 데이터셋이 메모리에 둔 사본으로 답할 수 있으므로, SQL로 파일에서 저장 행이 4095(2^12 - 1 - 0)이고 저장된 바이트가 쓴 바이트와 같은 것도 확인한 뒤 그 타일을 지우고 HasTile이 false인 것을 확인합니다. 변경 알림은 쓰기와 지우기에 한 번씩, 모두 쓴 스레드에서 옵니다. 예제는 파일을 연 래퍼를 모두 반납한 뒤 임시 폴더를 지웁니다.
C#에는 타일을 쓰거나 지우는 멤버와 변경 알림이 없어 C# 예제에는 이 단계가 없습니다.
// glsCreateDataset with an "mbtiles://" URI creates a new tile file (an
// existing file at the path is replaced) and opens it for writing. WriteTile
// stores the bytes as given under a key and replaces a tile already there;
// DeleteTile removes it. The change listener is called after each write or
// delete; for MBTiles that is on the thread that wrote, after the call has
// stored the change. A new file without a "scheme" metadata row stores rows
// from the bottom: key row Y is stored as row 2^zoom - 1 - Y.
static bool writeTileCopy(const std::filesystem::path& folder, const std::vector<uint8_t>& png)
{
GDK::glsDataset* rawDataset = nullptr;
if (!succeeded(GDK::glsCreateDataset(mbtilesUri(folder / "copy.mbtiles").c_str(), &rawDataset))) {
return false;
}
DatasetPtr dataset(rawDataset);
GDK::glsTileDataset* rawTiles = nullptr;
bool found = false;
if (!succeeded(dataset->AsTileDataset(&rawTiles, &found))) {
return false;
}
TilesPtr tiles(rawTiles);
if (!found) {
return unexpected("expected a tile dataset");
}
GDK::glsTileAxisOrigin origin = GDK::glsTileAxisOrigin::TopLeft;
if (!succeeded(tiles->GetStorageAxisOrigin(&origin))) {
return false;
}
std::printf("[sample] new tile file copy.mbtiles: rows stored %s\n", originName(origin));
Changes changes;
changes.writer = std::this_thread::get_id();
const GDK::glsTileMutatedCallback onChange = [](const GDK::glsTileKey*, void* userData) {
auto* c = static_cast<Changes*>(userData);
++c->calls;
c->onWriter += std::this_thread::get_id() == c->writer ? 1 : 0;
};
uint64_t token = 0;
if (!succeeded(tiles->AddTileMutatedListener(onChange, &changes, &token))) {
return false;
}
const GDK::glsTileKey key{kZoom, 0, 0};
if (!succeeded(tiles->WriteTile(key, GDK::glsTileFormat::Png, png.data(), png.size()))) {
return false;
}
size_t size = 0;
bool readBack = false;
if (!succeeded(tiles->ReadTile(key, nullptr, nullptr, 0, &size, &readBack))) {
return false;
}
std::vector<uint8_t> back(size);
if (readBack && !succeeded(tiles->ReadTile(key, nullptr, back.data(), back.size(), &size, &readBack))) {
return false;
}
// ReadTile may answer from the dataset's memory, so the stored row and the
// stored bytes (as hexadecimal text) are also read from the file with SQL.
GDK::glsSqlExecutor* rawExecutor = nullptr;
if (!succeeded(dataset->CreateSqlExecutor(&rawExecutor))) {
return false;
}
SqlExecutorPtr executor(rawExecutor, GDK::glsReleaseSqlExecutor);
GDK::glsSqlCursor* rawCursor = nullptr;
if (!succeeded(executor->ExecuteQuery(
"SELECT tile_row, hex(tile_data) FROM tiles WHERE zoom_level = 12 AND tile_column = 0", &rawCursor))) {
return false;
}
SqlCursorPtr cursor(rawCursor, GDK::glsReleaseSqlCursor);
bool hasRow = false;
GDK::glsAttributeValue rowCell;
GDK::glsAttributeValue dataCell;
if (!succeeded(cursor->Next(&hasRow)) ||
(hasRow && (!succeeded(cursor->GetValue(0, &rowCell)) || !succeeded(cursor->GetValue(1, &dataCell))))) {
return false;
}
const int64_t storedRow = !hasRow ? -1
: rowCell.Type == GDK::glsAttributeValueType::Int64 ? rowCell.Int64Value
: rowCell.Type == GDK::glsAttributeValueType::Int32 ? rowCell.Int32Value
: -1;
const std::string storedHex =
hasRow && dataCell.Type == GDK::glsAttributeValueType::String && dataCell.StringValue
? dataCell.StringValue : "";
cursor.reset();
executor.reset();
const bool storedSame = storedHex == hexText(png);
std::printf("[sample] wrote tile %s and read it back: same bytes %s; stored row %lld, stored bytes equal %s\n",
keyText(key).c_str(), yesNo(readBack && back == png), static_cast<long long>(storedRow),
yesNo(storedSame));
bool has = true;
if (!succeeded(tiles->DeleteTile(key)) || !succeeded(tiles->HasTile(key, &has)) ||
!succeeded(tiles->RemoveTileMutatedListener(token))) {
return false;
}
std::printf("[sample] deleted tile %s: HasTile %s; change listener called %d times, %d on the writing thread\n",
keyText(key).c_str(), yesNo(has), changes.calls, changes.onWriter);
return (origin == GDK::glsTileAxisOrigin::BottomLeft && readBack && back == png && storedRow == 4095 &&
storedSame && !has &&
changes.calls == 2 && changes.onWriter == 2) ||
unexpected("expected the tile written, stored bottom-up and deleted");
}
네트워크 소스
타일과 지도 영상은 네트워크 서비스에서도 받습니다. 예제는 네트워크를 쓰지 않으므로 이 절에는 예제가 없으며, 코드에서 확인한 내용만 적습니다. 주소의 example.com은 자리 표시입니다.
| 소스 | URI | 주요 옵션 |
|---|---|---|
| XYZ 타일 | https://example.com/tiles/{z}/{x}/{y}.png |
질의 인자로 줍니다. scheme(xyz 기본값, tms 등), minzoom과 maxzoom(또는 zmin, zmax), role(overlay 또는 basemap), timeoutMs(기본값 10000), maxCache(512), maxConcurrent(8). 이 인자들은 요청 주소에서 빠집니다. 타일 형식은 주소에 든 확장자(.png, .jpg, .jpeg, .webp, .pbf)로 정하고, 없으면 PNG입니다 |
| WMTS | wmts://https://example.com/wmts?SERVICE=WMTS&REQUEST=GetCapabilities#layer=<레이어>&matrixSet=<id>, 또는 {TileMatrix}, {TileCol}, {TileRow}가 든 주소, 또는 질의에 service=WMTS가 든 주소 |
layer, style, matrixSet(tileMatrixSet), format, version과 XYZ의 minzoom, timeoutMs 등. wmts:// 형식에서는 # 뒤에 씁니다 |
| WMS | wms://https://example.com/wms?layers=<레이어>, 또는 질의에 service=WMS가 든 주소 |
layers, styles, format, transparent, crs, version, timeoutMs 등 |
| 원격 GeoTIFF | 소스 종류 참고 | |
| 벡터 타일 | vectortile://open?styleUrl=<URL 인코딩한 스타일 주소> (mvt://도 됨) |
scheme(xyz 기본값 또는 tms), url, sourceId |
읽기는 기다리지 않습니다. XYZ, WMTS, RGB 원격 GeoTIFF의 타일 데이터셋에서 ReadTile은 네트워크를 기다리지 않습니다. 이미 받은 타일이면 바로 주고, 아니면 내려받기를 요청하고 "없음"으로 답합니다. 타일은 나중에 도착합니다. HasTile도 내려받기 전에 답하며, XYZ와 WMTS는 모든 키에, 원격 GeoTIFF는 격자 안의 모든 키에 true입니다. 그래서 네트워크 소스의 "없음"은 "아직 없음"일 수 있습니다. 이 데이터셋들은 타일 쓰기와 지우기가 NotSupported입니다. 숫자 단일 밴드 원격 GeoTIFF(래스터 데이터 소스)는 읽기가 네트워크를 기다리고, WMS는 지도 뷰가 그릴 때 화면에 맞는 영상 한 장을, 받아 둔 같은 요청이 없으면 요청하고 응답을 기다립니다.
도착 알림. C++ AddTileAvailableListener(callback, userData, &token)로 등록한 함수는 XYZ, WMTS, RGB 원격 GeoTIFF에서는 키의 내려받기가 데이터와 함께 성공했을 때와, 서버가 그 키에 데이터가 없다고 답했을 때에만 내려받기 작업 스레드에서 불리며, 여러 스레드에서 겹쳐 불릴 수 있습니다. 내려받기가 실패했거나 다시 시도할 예정인 동안에는 불리지 않으므로, 알림을 기다리는 코드에도 시간 제한을 두세요. 벡터 타일 데이터셋은 그리던 타일이 도착했을 때와 그 타일을 얻지 못했을 때 자기의 내려받기·해석 작업 스레드에서 부릅니다. MBTiles는 등록이 성공하지만 토큰이 0이고 함수를 부르지 않습니다. 콜백 안에서 막지 말고, 키는 복사해 보관합니다(스레드). RemoveTileAvailableListener(token)으로 뗍니다. 등록은 glsTileDataset을 반납해도 남아 있고, 떼는 호출은 다른 스레드에서 이미 진행 중인 호출을 기다리지 않으며 뗀 직후에 호출이 하나 더 시작될 수도 있으므로, userData는 그런 호출보다 오래 살아 있어야 합니다.
지도 뷰의 다시 그리기. 지도 뷰는 자기가 가진 타일 레이어의 데이터셋에 도착 알림과 부재 확정 알림을 스스로 등록해, 여러 알림을 모아 다시 그립니다. 응용 프로그램이 따로 등록할 것은 없습니다. XYZ·WMTS와 RGB 원격 GeoTIFF는 다운로드 대기와 확정된 부재를 구분합니다. 서버에 데이터가 없거나 영구 실패한 타일은 프레임 완료를 막지 않으며, 재시도 가능한 실패는 계속 대기로 남습니다. 워크스페이스의 타일 준비 콜백 SetTileReadyCallback(C++)은 등록할 때 워크스페이스에 있는 XYZ와 WMTS 데이터셋에만 걸리므로, 그런 데이터셋을 더한 뒤에는 다시 등록합니다.
지형 타일과 벡터 타일
다음은 이름과 하는 일만 적습니다. 자세한 사용법은 C++ API 레퍼런스와 .NET API 레퍼런스에 있습니다.
- 지형 타일. 높이를 RGB 색으로 담은 타일입니다(
glsTerrainEncoding의MapboxTerrainRgb,Terrarium).glsTileDataset::OpenTerrainTileDataSource가 여는glsTerrainTileDataSource는 경위도 점의 높이(ElevationAt), 선을 따라 고르게 뽑은 높이(ReadElevationProfile), 사각형 안의 가장 높은 곳(FindMaximumElevation), 타일 하나의 높이 격자(ReadTileElevations)를 미터로 읽습니다. MBTiles는 지형이 아닌 래스터 타일 파일에서도 이 소스가 열리므로, 지형 파일인지는 그 파일로 만든 타일 레이어의 메타데이터 값terrain_rgb(C++GetTileMetadataValue, C#GetMetadataValue)로 확인합니다. 파일의 메타데이터에 지형 표시가 있으면true입니다.glsCreateTerrainRgbLayer가 만드는 레이어의 종류는Tile입니다. C#에는glsTileDataset.OpenTerrainTileDataSource()(지형 소스가 아니면null)와glsTerrainTileDataSource가 있고, 지형 레이어를 만드는 클래스는 없습니다. - 벡터 타일. 지오메트리와 속성을 담은 타일(
Pbf)을 스타일 문서에 따라 그립니다.glsDataset::AsVectorTileDataset이 주는glsVectorTileDataset은 스타일 JSON을 읽고 다시 불러오며,glsCreateVectorTileLayer가VectorTile레이어를 만듭니다. C#에는glsDataset.AsVectorTileDataset()과glsVectorTileDataset이 있고, 벡터 타일 레이어를 만드는 클래스는 없습니다.
다음 장
다음은 13장 내보내기와 가져오기입니다. 벡터 데이터를 Shapefile, GeoJSON, FlatGeobuf 파일로 내보내고 다른 파일이나 데이터베이스의 테이블을 GeoPackage로 가져오는 방법, 형식을 오가며 값이 어떻게 바뀌는지를 설명합니다.