./
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
29 / 29
100.0%
Branches:
45 / 61
73.8%
Functions:
2 / 2, 6 excl
100.0%

include/terraingen/raster/geotiff/geotiff.h
Line Branch Exec Source
1 // SPDX-License-Identifier: BSD-3-Clause
2
3 /// @file
4 /// @brief Reading and writing GeoTIFF rasters, with their projection keys and band scaling.
5 #pragma once
6
7 #include "terraingen/raster/cell_loops.h"
8 #include "terraingen/raster/geo_transform.h"
9 #include "terraingen/raster/raster.h"
10
11 #include <cstddef>
12 #include <cstdint>
13 #include <filesystem>
14 #include <memory>
15 #include <optional>
16 #include <stdexcept>
17 #include <string>
18 #include <vector>
19
20 namespace terraingen {
21
22 /// A GeoTIFF that cannot be read or written, with the reason.
23 class GeoTiffError : public std::runtime_error {
24 public:
25
8/8
✓ Branch 1 taken 39 times.
✓ Branch 5 taken 2 times.
✓ Branch 9 taken 1 time.
✓ Branch 13 taken 2 times.
✓ Branch 13 taken 50 times.
✓ Branch 17 taken 1 time.
✓ Branch 21 taken 4 times.
✓ Branch 25 taken 3 times.
102 using std::runtime_error::runtime_error;
26 };
27
28 /// A GeoTIFF's projection as raw GeoKey tags, written back unchanged.
29 ///
30 /// Projections are not interpreted.
31
1/1
✓ Branch 1 taken 27 times.
826 struct GeoKeys {
32 std::vector<std::uint16_t> directory; ///< GeoKeyDirectoryTag (34735).
33 std::vector<double> doubleParams; ///< GeoDoubleParamsTag (34736).
34 std::string asciiParams; ///< GeoAsciiParamsTag (34737).
35
36 /// Whether there are no keys (the directory is empty).
37 361 bool Empty() const {
38
6/8
✗ Branch 0 not taken.
✓ Branch 0 taken 56 times.
✓ Branch 1 taken 1 time.
✓ Branch 1 taken 76 times.
✗ Branch 2 not taken.
✓ Branch 2 taken 80 times.
✓ Branch 3 taken 23 times.
✓ Branch 3 taken 119 times.
361 return directory.empty();
39 }
40
41 /// Whether GTRasterTypeGeoKey is PixelIsPoint: pixel coordinates name pixel centers rather
42 /// than pixel areas.
43 bool PixelIsPoint() const;
44
45 /// Whether GTModelTypeGeoKey is geographic: coordinates are angles rather than a projection's
46 /// linear units.
47 bool IsGeographic() const;
48
49 /// Memberwise equality.
50 229 bool operator==(const GeoKeys& other) const {
51
2/4
✓ Branch 0 taken 229 times.
✗ Branch 1 not taken.
✓ Branch 3 taken 229 times.
✗ Branch 4 not taken.
229 return directory == other.directory && doubleParams == other.doubleParams &&
52 229 asciiParams == other.asciiParams;
53 }
54 bool operator!=(const GeoKeys& other) const {
55 return !(*this == other);
56 }
57 };
58
59 /// Compression schemes this library reads and writes; others are reported as unsupported.
60 enum class TiffCompression {
61 None, ///< Code 1.
62 Lzw, ///< Code 5, with TIFF 6.0's early code-width change.
63 PackBits, ///< Code 32773; read only.
64 Deflate, ///< Codes 8 and 32946 (zlib streams), decoded and encoded with miniz.
65 };
66
67 /// How sample bits are interpreted.
68 enum class TiffSampleFormat { UnsignedInteger, SignedInteger, Float };
69
70 /// A band's scale and offset: a sample `s` stands for `s * scale + offset`, as GDAL's band
71 /// SCALE and OFFSET metadata say.
72
2/2
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 162 times.
1071 struct BandScaling {
73 double scale = 1.0; ///< Multiplier of the stored sample.
74 double offset = 0.0; ///< Added after scaling.
75
76 /// Whether the scaling leaves samples unchanged (scale 1 and offset 0).
77 291 bool Identity() const {
78
9/12
<unknown function 72>:
✓ Branch 0 taken 40 times.
✓ Branch 1 taken 5 times.
✓ Branch 2 taken 40 times.
✗ Branch 3 not taken.
✓ Branch 4 taken 234 times.
✓ Branch 5 taken 10 times.
✗ Branch 6 not taken.
✓ Branch 7 taken 234 times.
<unknown function 77>:
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 1 time.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 time.
291 return scale == 1.0 && offset == 0.0;
79 }
80
81 /// Memberwise equality.
82 4 bool operator==(const BandScaling& other) const {
83
2/4
✓ Branch 0 taken 4 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 4 times.
✗ Branch 3 not taken.
4 return scale == other.scale && offset == other.offset;
84 }
85 bool operator!=(const BandScaling& other) const {
86 return !(*this == other);
87 }
88 };
89
90 /// The layout and georeferencing of a GeoTIFF's first image.
91
5/10
✗ Branch 2 not taken.
✓ Branch 3 taken 1 time.
✗ Branch 6 not taken.
✓ Branch 7 taken 1 time.
✗ Branch 7 not taken.
✓ Branch 8 taken 1 time.
✗ Branch 11 not taken.
✓ Branch 12 taken 1 time.
✗ Branch 14 not taken.
✓ Branch 15 taken 1 time.
328 struct GeoTiffInfo {
92 /// Size and pixel-to-world transform, the identity without one; for PixelIsPoint the transform
93 /// is shifted half a pixel to name the first pixel's corner, as GDAL does.
94 RasterGrid grid;
95 std::size_t bands = 0; ///< Samples per pixel.
96 int bitsPerSample = 0; ///< Bits of each sample.
97 /// How samples are stored.
98 TiffSampleFormat sampleFormat = TiffSampleFormat::UnsignedInteger;
99 /// How the image data is compressed.
100 TiffCompression compression = TiffCompression::None;
101 int predictor = 1; ///< 1 none, 2 horizontal differencing, 3 floating point.
102 bool tiled = false; ///< Tiles rather than strips.
103 bool bigTiff = false; ///< BigTIFF rather than classic TIFF.
104 bool bigEndian = false; ///< Big-endian ("MM") byte order.
105 bool georeferenced = false; ///< Whether the file has a transform.
106 std::optional<double> noData; ///< From the GDAL_NODATA tag (42113).
107 /// One per band, from the GDAL_METADATA tag (42112); `ReadGeoTiff` returns raw samples.
108 std::vector<BandScaling> bandScaling;
109 GeoKeys geoKeys; ///< The projection keys.
110 };
111
112 /// Reads the layout and georeferencing of a GeoTIFF's first image without its pixels.
113 ///
114 /// Classic TIFF and BigTIFF in either byte order.
115 /// @throws GeoTiffError for unreadable or malformed files.
116 GeoTiffInfo ReadGeoTiffInfo(const std::filesystem::path& path);
117
118 /// A raster read from a GeoTIFF with the projection keys to write it back with.
119
10/12
<unknown function 77>:
✓ Branch 2 taken 1 time.
✓ Branch 3 taken 1 time.
terraingen::GeoKeys::operator==(terraingen::GeoKeys const&) const:
✓ Branch 5 taken 1 time.
✗ Branch 9 not taken.
✓ Branch 10 taken 1 time.
✓ Branch 28 taken 1 time.
✗ Branch 36 not taken.
✓ Branch 37 taken 1 time.
✓ Branch 65 taken 25 times.
✓ Branch 78 taken 3 times.
✓ Branch 83 taken 3 times.
✓ Branch 88 taken 3 times.
332 struct GeoTiff {
120 Raster<float> raster; ///< The band read, with the file's transform and no-data value.
121 GeoKeys geoKeys; ///< The file's projection keys.
122 };
123
124 /// Reads one band of a GeoTIFF's first image as `float` samples, with the file's transform,
125 /// no-data value and GeoKeys.
126 ///
127 /// Strips or tiles, chunky or planar bands, 8- to 64-bit integer and 32- and 64-bit float samples,
128 /// LZW, Deflate or PackBits, with or without a predictor. Band scaling is not applied.
129 /// @param band The band, from 0.
130 /// @throws GeoTiffError for unreadable, malformed or unsupported files, or a missing band.
131 GeoTiff ReadGeoTiff(const std::filesystem::path& path, std::size_t band = 0);
132
133 /// Reads one band of a window of a GeoTIFF's first image as `ReadGeoTiff` reads it, decoding only
134 /// the strips or tiles that meet the window; the raster's transform starts at the window's first
135 /// cell.
136 /// @param band The band, from 0.
137 /// @param window The cells to read; clipped to the image.
138 /// @throws GeoTiffError as `ReadGeoTiff`.
139 /// @throws std::invalid_argument for a window that is empty once clipped.
140 GeoTiff ReadGeoTiffWindow(const std::filesystem::path& path, std::size_t band,
141 const PixelWindow& window);
142
143 /// One band of a GeoTIFF's first image read a block at a time from the file held open, a block
144 /// being a tile or a strip spanning every column; blocks hold the samples `ReadGeoTiff` reads.
145 /// Thread-safe.
146 class GeoTiffBlockReader {
147 public:
148 /// Opens the file and reads its layout.
149 /// @param band The band, from 0.
150 /// @throws GeoTiffError as `ReadGeoTiff`.
151 GeoTiffBlockReader(const std::filesystem::path& path, std::size_t band);
152 ~GeoTiffBlockReader();
153
154 GeoTiffBlockReader(const GeoTiffBlockReader&) = delete;
155 GeoTiffBlockReader& operator=(const GeoTiffBlockReader&) = delete;
156
157 /// The layout and georeferencing of the image.
158 const GeoTiffInfo& Info() const;
159
160 /// Columns of a block: a tile's, or the image's for strips.
161 std::size_t BlockWidth() const;
162
163 /// Rows of a block.
164 std::size_t BlockHeight() const;
165
166 /// The cells of block (`col`, `row`), counted in blocks, clipped to the image, with their
167 /// transform and the file's no-data value.
168 /// @throws GeoTiffError as `ReadGeoTiff`.
169 /// @throws std::invalid_argument for a block beyond the image.
170 Raster<float> ReadBlock(std::size_t col, std::size_t row) const;
171
172 private:
173 struct State;
174 std::unique_ptr<State> m_state;
175 };
176
177 /// GeoKeys for longitude and latitude in degrees on a sphere, such as a planet or moon.
178 ///
179 /// A user-defined geographic CRS with both axes `radius` and pixel-is-area rasters.
180 /// @param radius The sphere's radius in meters; positive and finite.
181 /// @throws std::invalid_argument unless `radius` is positive and finite.
182 GeoKeys GeographicSphereKeys(double radius);
183
184 /// Settings for `WriteGeoTiff`.
185 1 struct GeoTiffWriteOptions {
186 /// `None`, `Lzw` or `Deflate`; compressed files use the floating-point predictor.
187 TiffCompression compression = TiffCompression::Lzw;
188 /// Tile width and height in pixels; a positive multiple of 16.
189 std::uint32_t tileSize = 256;
190 /// Always write BigTIFF; otherwise BigTIFF is used only when the file could exceed 4 GiB.
191 bool bigTiff = false;
192 };
193
194 /// Writes a raster as a tiled, little-endian float32 GeoTIFF with its transform and its no-data
195 /// value as GDAL_NODATA, edge tiles padded with the no-data value or 0.
196 /// @param geoKeys The projection keys, as `ReadGeoTiff` returned them.
197 /// @throws GeoTiffError for an empty raster, invalid options, or a file that cannot be written.
198 void WriteGeoTiff(const std::filesystem::path& path, const Raster<float>& raster,
199 const GeoKeys& geoKeys = {}, const GeoTiffWriteOptions& options = {});
200
201 /// Writes rasters as one GeoTIFF of as many float32 bands.
202 ///
203 /// Several bands are stored band after band (planar configuration 2), with the first band's
204 /// transform and no-data value; otherwise as `WriteGeoTiff` for one raster.
205 /// @param bands The bands; at least one, all on one grid.
206 /// @throws GeoTiffError as for one raster, or for no bands or bands on different grids.
207 void WriteGeoTiff(const std::filesystem::path& path, const std::vector<Raster<float>>& bands,
208 const GeoKeys& geoKeys = {}, const GeoTiffWriteOptions& options = {});
209
210 } // namespace terraingen
211