Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: GDAL
4 : * Purpose: gdal "raster footprint" subcommand
5 : * Author: Even Rouault <even dot rouault at spatialys.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2025, Even Rouault <even dot rouault at spatialys.com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "gdalalg_raster_footprint.h"
14 :
15 : #include "cpl_conv.h"
16 :
17 : #include "gdal_priv.h"
18 : #include "gdal_utils.h"
19 :
20 : //! @cond Doxygen_Suppress
21 :
22 : #ifndef _
23 : #define _(x) (x)
24 : #endif
25 :
26 : /************************************************************************/
27 : /* GDALRasterFootprintAlgorithm::GDALRasterFootprintAlgorithm() */
28 : /************************************************************************/
29 :
30 94 : GDALRasterFootprintAlgorithm::GDALRasterFootprintAlgorithm(bool standaloneStep)
31 : : GDALPipelineStepAlgorithm(
32 : NAME, DESCRIPTION, HELP_URL,
33 0 : ConstructorOptions()
34 94 : .SetStandaloneStep(standaloneStep)
35 188 : .SetOutputFormatCreateCapability(GDAL_DCAP_CREATE))
36 : {
37 94 : AddProgressArg();
38 :
39 94 : if (standaloneStep)
40 : {
41 79 : AddOpenOptionsArg(&m_openOptions).SetAvailableInPipelineStep(false);
42 79 : AddInputFormatsArg(&m_inputFormats)
43 237 : .AddMetadataItem(GAAMDI_REQUIRED_CAPABILITIES, {GDAL_DCAP_RASTER})
44 79 : .SetAvailableInPipelineStep(false);
45 79 : AddInputDatasetArg(&m_inputDataset, GDAL_OF_RASTER)
46 79 : .SetAvailableInPipelineStep(false);
47 :
48 79 : AddOutputDatasetArg(&m_outputDataset, GDAL_OF_VECTOR)
49 79 : .SetDatasetInputFlags(GADV_NAME | GADV_OBJECT)
50 79 : .SetAvailableInPipelineStep(false);
51 : AddOutputFormatArg(&m_format, /* bStreamAllowed = */ false,
52 79 : /* bGDALGAllowed = */ false)
53 : .AddMetadataItem(GAAMDI_REQUIRED_CAPABILITIES,
54 316 : {GDAL_DCAP_VECTOR, GDAL_DCAP_CREATE})
55 79 : .SetAvailableInPipelineStep(false);
56 79 : AddCreationOptionsArg(&m_creationOptions)
57 79 : .SetAvailableInPipelineStep(false);
58 79 : AddLayerCreationOptionsArg(&m_layerCreationOptions)
59 79 : .SetAvailableInPipelineStep(false);
60 79 : AddUpdateArg(&m_update)
61 79 : .SetAvailableInPipelineStep(false)
62 79 : .SetHidden(); // needed for correct append execution
63 79 : AddAppendLayerArg(&m_appendLayer).SetAvailableInPipelineStep(false);
64 79 : AddOverwriteArg(&m_overwrite).SetAvailableInPipelineStep(false);
65 : }
66 : else
67 : {
68 15 : AddRasterHiddenInputDatasetArg();
69 : }
70 :
71 94 : m_outputLayerName = "footprint";
72 : AddArg(GDAL_ARG_NAME_OUTPUT_LAYER, 0, _("Output layer name"),
73 188 : &m_outputLayerName)
74 94 : .SetDefault(m_outputLayerName);
75 :
76 94 : AddBandArg(&m_bands);
77 : AddArg("combine-bands", 0,
78 : _("Defines how the mask bands of the selected bands are combined to "
79 : "generate a single mask band, before being vectorized."),
80 188 : &m_combineBands)
81 94 : .SetChoices("union", "intersection")
82 94 : .SetDefault(m_combineBands);
83 : AddArg("overview", 0, _("Which overview level of source file must be used"),
84 188 : &m_overview)
85 188 : .SetMutualExclusionGroup("overview-srcnodata")
86 94 : .SetMinValueIncluded(0);
87 : AddArg("src-nodata", 0, _("Set nodata values for input bands."),
88 188 : &m_srcNoData)
89 94 : .SetMinCount(1)
90 94 : .SetRepeatedArgAllowed(false)
91 94 : .SetMutualExclusionGroup("overview-srcnodata");
92 : AddArg("coordinate-system", 0, _("Target coordinate system"),
93 188 : &m_coordinateSystem)
94 94 : .SetChoices("georeferenced", "pixel");
95 188 : AddArg("dst-crs", 0, _("Destination CRS"), &m_dstCrs)
96 188 : .SetIsCRSArg()
97 94 : .AddHiddenAlias("t_srs");
98 : AddArg("split-multipolygons", 0,
99 : _("Whether to split multipolygons as several features each with one "
100 : "single polygon"),
101 94 : &m_splitMultiPolygons);
102 : AddArg("convex-hull", 0,
103 : _("Whether to compute the convex hull of the footprint"),
104 94 : &m_convexHull);
105 : AddArg("densify-distance", 0,
106 : _("Maximum distance between 2 consecutive points of the output "
107 : "geometry."),
108 188 : &m_densifyVal)
109 94 : .SetMinValueExcluded(0);
110 : AddArg(
111 : "simplify-tolerance", 0,
112 : _("Tolerance used to merge consecutive points of the output geometry."),
113 188 : &m_simplifyVal)
114 94 : .SetMinValueExcluded(0);
115 : AddArg("min-ring-area", 0, _("Minimum value for the area of a ring"),
116 188 : &m_minRingArea)
117 94 : .SetMinValueIncluded(0);
118 : AddArg("max-points", 0,
119 188 : _("Maximum number of points of each output geometry"), &m_maxPoints)
120 94 : .SetDefault(m_maxPoints)
121 : .AddValidationAction(
122 11 : [this]()
123 : {
124 3 : if (m_maxPoints != "unlimited")
125 : {
126 3 : char *endptr = nullptr;
127 : const auto nVal =
128 3 : std::strtoll(m_maxPoints.c_str(), &endptr, 10);
129 5 : if (nVal < 4 ||
130 2 : endptr != m_maxPoints.c_str() + m_maxPoints.size())
131 : {
132 1 : ReportError(
133 : CE_Failure, CPLE_IllegalArg,
134 : "Value of 'max-points' should be a positive "
135 : "integer greater or equal to 4, or 'unlimited'");
136 1 : return false;
137 : }
138 : }
139 2 : return true;
140 94 : });
141 : AddArg("location-field", 0,
142 : _("Name of the field where the path of the input dataset will be "
143 : "stored."),
144 188 : &m_locationField)
145 94 : .SetDefault(m_locationField)
146 94 : .SetMutualExclusionGroup("location");
147 : AddArg("no-location-field", 0,
148 : _("Disable creating a field with the path of the input dataset"),
149 188 : &m_noLocation)
150 94 : .SetMutualExclusionGroup("location");
151 94 : AddAbsolutePathArg(&m_writeAbsolutePaths);
152 :
153 94 : AddValidationAction(
154 108 : [this]
155 : {
156 35 : if (m_inputDataset.size() == 1)
157 : {
158 34 : if (auto poSrcDS = m_inputDataset[0].GetDatasetRef())
159 : {
160 : const int nOvrCount =
161 34 : poSrcDS->GetRasterBand(1)->GetOverviewCount();
162 37 : if (m_overview >= 0 && poSrcDS->GetRasterCount() > 0 &&
163 3 : m_overview >= nOvrCount)
164 : {
165 2 : if (nOvrCount == 0)
166 : {
167 1 : ReportError(
168 : CE_Failure, CPLE_IllegalArg,
169 : "Source dataset has no overviews. "
170 : "Argument 'overview' should not be specified.");
171 : }
172 : else
173 : {
174 1 : ReportError(
175 : CE_Failure, CPLE_IllegalArg,
176 : "Source dataset has only %d overview levels. "
177 : "'overview' "
178 : "value should be strictly lower than this "
179 : "number.",
180 : nOvrCount);
181 : }
182 2 : return false;
183 : }
184 : }
185 : }
186 33 : return true;
187 : });
188 94 : }
189 :
190 : /************************************************************************/
191 : /* GDALRasterFootprintAlgorithm::RunImpl() */
192 : /************************************************************************/
193 :
194 30 : bool GDALRasterFootprintAlgorithm::RunImpl(GDALProgressFunc pfnProgress,
195 : void *pProgressData)
196 : {
197 30 : GDALPipelineStepRunContext stepCtxt;
198 30 : stepCtxt.m_pfnProgress = pfnProgress;
199 30 : stepCtxt.m_pProgressData = pProgressData;
200 30 : return RunPreStepPipelineValidations() && RunStep(stepCtxt);
201 : }
202 :
203 : /************************************************************************/
204 : /* GDALRasterFootprintAlgorithm::RunStep() */
205 : /************************************************************************/
206 :
207 31 : bool GDALRasterFootprintAlgorithm::RunStep(GDALPipelineStepRunContext &ctxt)
208 : {
209 31 : auto poSrcDS = m_inputDataset[0].GetDatasetRef();
210 31 : CPLAssert(poSrcDS);
211 :
212 62 : CPLStringList aosOptions;
213 :
214 62 : std::string outputFilename;
215 31 : if (m_standaloneStep)
216 : {
217 30 : outputFilename = m_outputDataset.GetName();
218 30 : if (!m_format.empty())
219 : {
220 25 : aosOptions.AddString("-of");
221 25 : aosOptions.AddString(m_format.c_str());
222 : }
223 :
224 31 : for (const auto &co : m_creationOptions)
225 : {
226 1 : aosOptions.push_back("-dsco");
227 1 : aosOptions.push_back(co.c_str());
228 : }
229 :
230 31 : for (const auto &co : m_layerCreationOptions)
231 : {
232 1 : aosOptions.push_back("-lco");
233 1 : aosOptions.push_back(co.c_str());
234 : }
235 : }
236 : else
237 : {
238 1 : if (GetGDALDriverManager()->GetDriverByName("GPKG"))
239 : {
240 1 : aosOptions.AddString("-of");
241 1 : aosOptions.AddString("GPKG");
242 :
243 : outputFilename =
244 1 : CPLGenerateTempFilenameSafe("_footprint") + ".gpkg";
245 : }
246 : else
247 : {
248 0 : aosOptions.AddString("-of");
249 0 : aosOptions.AddString("MEM");
250 : }
251 : }
252 :
253 37 : for (int band : m_bands)
254 : {
255 6 : aosOptions.push_back("-b");
256 6 : aosOptions.push_back(CPLSPrintf("%d", band));
257 : }
258 :
259 31 : aosOptions.push_back("-combine_bands");
260 31 : aosOptions.push_back(m_combineBands);
261 :
262 31 : if (m_overview >= 0)
263 : {
264 1 : aosOptions.push_back("-ovr");
265 1 : aosOptions.push_back(CPLSPrintf("%d", m_overview));
266 : }
267 :
268 31 : if (!m_srcNoData.empty())
269 : {
270 2 : aosOptions.push_back("-srcnodata");
271 4 : std::string s;
272 5 : for (double v : m_srcNoData)
273 : {
274 3 : if (!s.empty())
275 1 : s += " ";
276 3 : s += CPLSPrintf("%.17g", v);
277 : }
278 2 : aosOptions.push_back(s);
279 : }
280 :
281 31 : if (m_coordinateSystem == "pixel")
282 : {
283 1 : aosOptions.push_back("-t_cs");
284 1 : aosOptions.push_back("pixel");
285 : }
286 30 : else if (m_coordinateSystem == "georeferenced")
287 : {
288 1 : aosOptions.push_back("-t_cs");
289 1 : aosOptions.push_back("georef");
290 : }
291 :
292 31 : if (!m_dstCrs.empty())
293 : {
294 1 : aosOptions.push_back("-t_srs");
295 1 : aosOptions.push_back(m_dstCrs);
296 : }
297 :
298 31 : if (GetArg(GDAL_ARG_NAME_OUTPUT_LAYER)->IsExplicitlySet())
299 : {
300 5 : aosOptions.push_back("-lyr_name");
301 5 : aosOptions.push_back(m_outputLayerName.c_str());
302 : }
303 :
304 31 : if (m_splitMultiPolygons)
305 1 : aosOptions.push_back("-split_polys");
306 :
307 31 : if (m_convexHull)
308 1 : aosOptions.push_back("-convex_hull");
309 :
310 31 : if (m_densifyVal > 0)
311 : {
312 1 : aosOptions.push_back("-densify");
313 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_densifyVal));
314 : }
315 :
316 31 : if (m_simplifyVal > 0)
317 : {
318 1 : aosOptions.push_back("-simplify");
319 1 : aosOptions.push_back(CPLSPrintf("%.17g", m_simplifyVal));
320 : }
321 :
322 31 : aosOptions.push_back("-min_ring_area");
323 31 : aosOptions.push_back(CPLSPrintf("%.17g", m_minRingArea));
324 :
325 31 : aosOptions.push_back("-max_points");
326 31 : aosOptions.push_back(m_maxPoints);
327 :
328 31 : if (m_noLocation)
329 : {
330 1 : aosOptions.push_back("-no_location");
331 : }
332 : else
333 : {
334 30 : aosOptions.push_back("-location_field_name");
335 30 : aosOptions.push_back(m_locationField);
336 :
337 30 : if (m_writeAbsolutePaths)
338 1 : aosOptions.push_back("-write_absolute_path");
339 : }
340 :
341 31 : bool bOK = false;
342 : std::unique_ptr<GDALFootprintOptions, decltype(&GDALFootprintOptionsFree)>
343 : psOptions{GDALFootprintOptionsNew(aosOptions.List(), nullptr),
344 31 : GDALFootprintOptionsFree};
345 31 : if (psOptions)
346 : {
347 31 : GDALFootprintOptionsSetProgress(psOptions.get(), ctxt.m_pfnProgress,
348 : ctxt.m_pProgressData);
349 :
350 31 : GDALDatasetH hSrcDS = GDALDataset::ToHandle(poSrcDS);
351 : GDALDatasetH hDstDS =
352 31 : GDALDataset::ToHandle(m_outputDataset.GetDatasetRef());
353 31 : auto poRetDS = GDALDataset::FromHandle(GDALFootprint(
354 31 : outputFilename.c_str(), hDstDS, hSrcDS, psOptions.get(), nullptr));
355 31 : bOK = poRetDS != nullptr;
356 31 : if (bOK && !hDstDS)
357 : {
358 28 : if (poRetDS && !m_standaloneStep && !outputFilename.empty())
359 : {
360 1 : bOK = poRetDS->FlushCache() == CE_None;
361 : #if !defined(__APPLE__)
362 : // For some unknown reason, unlinking the file on MacOSX
363 : // leads to later "disk I/O error". See https://github.com/OSGeo/gdal/issues/13794
364 1 : VSIUnlink(outputFilename.c_str());
365 : #endif
366 1 : poRetDS->MarkSuppressOnClose();
367 : }
368 28 : m_outputDataset.Set(std::unique_ptr<GDALDataset>(poRetDS));
369 : }
370 : }
371 :
372 62 : return bOK;
373 : }
374 :
375 : GDALRasterFootprintAlgorithmStandalone::
376 : ~GDALRasterFootprintAlgorithmStandalone() = default;
377 :
378 : //! @endcond
|