diff --git a/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj b/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj
index d11a40d..b6e9ac0 100644
--- a/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj
+++ b/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj
@@ -57,6 +57,7 @@
+
diff --git a/src/MapWinGIS.Core/include/mapwingis/gdal/GdalAlgorithmRunner.h b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalAlgorithmRunner.h
index b339b51..867a9f5 100644
--- a/src/MapWinGIS.Core/include/mapwingis/gdal/GdalAlgorithmRunner.h
+++ b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalAlgorithmRunner.h
@@ -57,9 +57,15 @@ namespace mwg
[[nodiscard]] bool SetArgument(std::string_view name, double value);
/// Sets a list of real-valued algorithm argument values.
[[nodiscard]] bool SetArgument(std::string_view name, const std::vector& value);
+ /// Sets a list of integer-valued algorithm argument values.
+ [[nodiscard]] bool SetArgument(std::string_view name, const std::vector& value);
/// Sets a list of string-valued algorithm argument values.
[[nodiscard]] bool SetArgument(std::string_view name, const std::vector& value);
+ /// Validates configured values using the instantiated GDAL algorithm's
+ /// argument metadata and constraints.
+ [[nodiscard]] bool ValidateArguments();
+
/// Parses GDAL-style command-line flags for this algorithm.
[[nodiscard]] bool ParseCommandLineArgs(const std::vector& args);
diff --git a/src/MapWinGIS.Core/include/mapwingis/gdal/GdalTypedOptions.h b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalTypedOptions.h
new file mode 100644
index 0000000..e984456
--- /dev/null
+++ b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalTypedOptions.h
@@ -0,0 +1,375 @@
+// SPDX-License-Identifier: MPL-2.0
+
+/**
+ * @file GdalTypedOptions.h
+ * @brief Declares typed options for common GDAL algorithms.
+ *
+ * The option structures convert native values to GDAL algorithm arguments.
+ * GDAL remains responsible for validating supported arguments and constraints.
+ */
+#pragma once
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "mapwingis/core/Api.h"
+
+namespace mwg
+{
+ class GdalAlgorithmRunner;
+
+ /**
+ * @defgroup GdalTypedOptions Typed GDAL algorithm options
+ * @brief Value types that copy native values into GDAL algorithm arguments.
+ *
+ * Each ToArgs() returns an independent, owning argument list. Paths become
+ * UTF-8 strings. Conversion does not initialize GDAL, open datasets, or
+ * validate required values, supported formats, or argument combinations.
+ * Required paths are emitted even when empty.
+ *
+ * Unset optional fields and empty non-optional vectors are omitted.
+ * On a new runner, omitted arguments retain the instantiated GDAL
+ * algorithm's defaults. An optional bool set to false is emitted explicitly.
+ * Other present optional values, including empty strings, are emitted.
+ * RasterReprojectOptions also omits empty inputNoData and outputNoData lists.
+ * GDAL defines format inference and all other algorithm-specific defaults.
+ *
+ * Pass the result to ConfigureGdalAlgorithm() with the matching algorithm.
+ * Configuration can open input datasets. Run() performs execution separately.
+ * Configuration and execution failures return false with diagnostics in
+ * GdalAlgorithmRunner::Errors(). ToArgs() does not report invalid options.
+ *
+ * @par Thread safety and cost
+ * Concurrent ToArgs() calls are safe if no thread modifies the source
+ * struct or its members. Mutation of a shared struct is not thread-safe
+ * without external synchronization. Conversion copies the supplied values,
+ * with time and memory proportional to their total size.
+ *
+ * @par Exceptions from ToArgs()
+ * Exceptions from allocation and filesystem path conversion propagate to
+ * the caller. No GDAL diagnostic is recorded for these exceptions.
+ * @throws std::bad_alloc If memory allocation fails.
+ * @throws std::runtime_error If numeric formatting fails in
+ * RasterReprojectOptions or RasterMosaicOptions.
+ */
+
+ using GdalAlgorithmArgumentValue =
+ std::variant,
+ std::vector, std::vector>;
+
+ /// One named, strongly typed GDAL algorithm argument.
+ struct MWG_CORE_API GdalAlgorithmArgument
+ {
+ std::string name;
+ GdalAlgorithmArgumentValue value;
+ };
+
+ using GdalAlgorithmArguments = std::vector;
+
+ /**
+ * @brief Sets typed arguments and validates them with the instantiated GDAL algorithm.
+ *
+ * Use a new runner for the matching algorithm. Arguments are applied in
+ * order, without rollback on failure. Validation can open input datasets.
+ * Returns false for rejected arguments or validation failure, with
+ * diagnostics in runner.Errors(). Does not execute the algorithm.
+ *
+ * Not thread-safe for a shared runner. The argument list is read-only.
+ * Allocation and diagnostic-capture exceptions propagate to the caller.
+ */
+ [[nodiscard]] MWG_CORE_API bool ConfigureGdalAlgorithm(
+ GdalAlgorithmRunner& runner, const GdalAlgorithmArguments& arguments);
+
+ /// Options for GDAL raster format conversion.
+ ///
+ /// Requires input and output dataset paths. Unset fields follow the
+ /// @ref GdalTypedOptions "shared conversion contract".
+ /// GDAL 3.12's raster convert algorithm
+ /// does not expose raster translate's window, band, or data-type options.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterConvertOptions
+ {
+ std::filesystem::path input;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::optional overwrite;
+ std::optional append;
+ std::vector inputFormats;
+ std::vector creationOptions;
+ std::vector openOptions;
+
+ /// Copies values for `raster convert`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for reprojecting a raster dataset.
+ ///
+ /// Requires input and output dataset paths. sourceCrs overrides the input
+ /// coordinate reference system (CRS). Set targetCrs to request a different CRS.
+ /// An unset sourceCrs uses the input dataset's CRS.
+ /// GDAL determines omitted output bounds and dimensions from the input.
+ /// resolution is {x, y} in target CRS units. size is {width, height} in pixels.
+ /// boundingBox is {xmin, ymin, xmax, ymax}, in target CRS units unless
+ /// boundingBoxCrs is set.
+ /// Mutually exclusive choices, such as target resolution and target size,
+ /// are validated by the instantiated GDAL algorithm.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterReprojectOptions
+ {
+ std::filesystem::path input;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::optional sourceCrs;
+ std::optional targetCrs;
+ std::optional overwrite;
+ std::optional append;
+ std::optional> resolution;
+ std::optional> size;
+ std::optional> boundingBox;
+ std::optional boundingBoxCrs;
+ std::optional resampling;
+ std::optional> inputNoData;
+ std::optional> outputNoData;
+ std::optional targetAlignedPixels;
+ std::vector inputFormats;
+ std::vector creationOptions;
+ std::vector openOptions;
+
+ /// Copies values for `raster reproject`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for converting vector datasets and layers.
+ ///
+ /// Requires input and output dataset paths. Empty inputLayers leaves layer
+ /// selection to GDAL. Set outputLayer to override the output layer name.
+ /// Dataset and layer creation options depend on the selected output driver.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API VectorConvertOptions
+ {
+ std::filesystem::path input;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::vector inputLayers;
+ std::optional outputLayer;
+ std::optional overwrite;
+ std::optional update;
+ std::optional overwriteLayer;
+ std::optional append;
+ std::optional skipErrors;
+ std::vector inputFormats;
+ std::vector creationOptions;
+ std::vector layerCreationOptions;
+ std::vector openOptions;
+
+ /// Copies values for `vector convert`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for building raster overviews.
+ ///
+ /// Requires an input dataset path. Execution updates that dataset in place.
+ /// Explicit levels are integer reduction factors of at least two.
+ /// If levels is empty, GDAL refreshes existing levels or selects levels
+ /// using minimumSize. An unset minimumSize leaves GDAL's default unchanged.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterOverviewAddOptions
+ {
+ std::filesystem::path input;
+ std::vector levels;
+ std::optional resampling;
+ std::optional minimumSize;
+ std::vector creationOptions;
+ std::vector openOptions;
+
+ /// Copies values for `raster overview add`. See @ref GdalTypedOptions
+ /// for defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for reporting raster metadata and optional statistics.
+ ///
+ /// Requires an input dataset path. No output dataset path is needed.
+ /// Unset report flags and outputFormat retain GDAL's report defaults.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterInfoOptions
+ {
+ std::filesystem::path input;
+ std::optional outputFormat;
+ std::optional minMax;
+ std::optional computeStatistics;
+ std::optional approximateStatistics;
+ std::optional computeHistogram;
+ std::optional checksum;
+ std::vector inputFormats;
+ std::vector openOptions;
+
+ /// Copies values for `raster info`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for reporting vector dataset and layer metadata.
+ ///
+ /// Requires an input dataset path. No output dataset path is needed.
+ /// Set layer to select a layer. Unset report flags, filters, and outputFormat
+ /// retain GDAL's report defaults.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API VectorInfoOptions
+ {
+ std::filesystem::path input;
+ std::optional outputFormat;
+ std::optional layer;
+ std::optional summary;
+ std::optional features;
+ std::optional limit;
+ std::optional where;
+ std::optional sql;
+ std::vector inputFormats;
+ std::vector openOptions;
+
+ /// Copies values for `vector info`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for combining multiple raster datasets.
+ ///
+ /// Requires at least one input path and an output dataset path.
+ /// bands contains one-based GDAL band numbers, not feature indexes.
+ /// resolution accepts a GDAL strategy string or {x, y} pixel sizes.
+ /// boundingBox is {xmin, ymin, xmax, ymax} in the input CRS.
+ /// Unset resolution and bounds leave output grid selection to GDAL.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterMosaicOptions
+ {
+ std::vector inputs;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::optional overwrite;
+ std::optional append;
+ std::optional> bands;
+ std::optional>> resolution;
+ std::optional> boundingBox;
+ std::optional> inputNoData;
+ std::optional> outputNoData;
+ std::vector creationOptions;
+ std::vector inputFormats;
+ std::vector openOptions;
+
+ /// Copies values for `raster mosaic`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for clipping a vector dataset by bounds, geometry, or a template.
+ ///
+ /// Requires input and output paths and exactly one of boundingBox, geometry,
+ /// or like. boundingBox is {xmin, ymin, xmax, ymax} in the input CRS unless
+ /// boundingBoxCrs is set. geometry accepts WKT or GeoJSON.
+ /// like supplies the template dataset path. GDAL validates clip choices
+ /// and resolves omitted geometry CRS and layer selection.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API VectorClipOptions
+ {
+ std::filesystem::path input;
+ std::filesystem::path output;
+ std::optional like;
+ std::optional inputLayer;
+ std::optional likeLayer;
+ std::optional likeWhere;
+ std::optional outputLayer;
+ std::optional outputFormat;
+ std::optional overwrite;
+ std::optional update;
+ std::optional overwriteLayer;
+ std::optional append;
+ std::optional> boundingBox;
+ std::optional boundingBoxCrs;
+ std::optional geometry;
+ std::optional geometryCrs;
+ std::optional skipErrors;
+ std::vector creationOptions;
+ std::vector layerCreationOptions;
+ std::vector openOptions;
+
+ /// Copies values for `vector clip`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for clipping a raster dataset by bounds, geometry, or a template.
+ ///
+ /// Requires input and output paths and exactly one clip selector: boundingBox,
+ /// window, geometry, or like. window is {xOffset, yOffset, width, height}
+ /// in pixels, with zero-based offsets from the top-left corner.
+ /// boundingBox is {xmin, ymin, xmax, ymax} in the input CRS unless
+ /// boundingBoxCrs is set. geometry accepts WKT or GeoJSON.
+ /// GDAL validates selector combinations and resolves omitted CRS values.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterClipOptions
+ {
+ std::filesystem::path input;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::optional overwrite;
+ std::optional append;
+ std::optional> boundingBox;
+ std::optional boundingBoxCrs;
+ std::optional> window;
+ std::optional geometry;
+ std::optional geometryCrs;
+ std::optional like;
+ std::optional likeLayer;
+ std::optional likeSql;
+ std::optional likeWhere;
+ std::optional onlyBoundingBox;
+ std::optional allowBoundingBoxOutsideSource;
+ std::vector creationOptions;
+ std::vector inputFormats;
+ std::vector openOptions;
+
+ /// Copies values for `raster clip`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+
+ /// Options for calculating a raster from an expression and input datasets.
+ ///
+ /// Requires nonempty expressions and inputs and an output dataset path.
+ /// GDAL evaluates expressions in order using its selected dialect.
+ /// With one unnamed input, expressions refer to that dataset as X.
+ /// Multiple inputs use GDAL's NAME=path notation in inputs.
+ /// Unset dialect, data type, and nodata fields retain GDAL's defaults.
+ /// @ingroup GdalTypedOptions
+ struct MWG_CORE_API RasterCalcOptions
+ {
+ std::vector expressions;
+ std::vector inputs;
+ std::filesystem::path output;
+ std::optional outputFormat;
+ std::optional outputDataType;
+ std::optional overwrite;
+ std::optional append;
+ std::optional outputNoData;
+ std::optional dialect;
+ std::optional noCheckCrs;
+ std::optional noCheckExtent;
+ std::optional propagateNoData;
+ std::optional flatten;
+ std::vector creationOptions;
+ std::vector inputFormats;
+ std::vector openOptions;
+
+ /// Copies values for `raster calc`. See @ref GdalTypedOptions for
+ /// defaults, validation, exceptions, and thread-safety requirements.
+ [[nodiscard]] GdalAlgorithmArguments ToArgs() const;
+ };
+}
diff --git a/src/MwGdalCore/GdalAlgorithmRunner.cpp b/src/MwGdalCore/GdalAlgorithmRunner.cpp
index 2a609bf..7a61ee2 100644
--- a/src/MwGdalCore/GdalAlgorithmRunner.cpp
+++ b/src/MwGdalCore/GdalAlgorithmRunner.cpp
@@ -222,6 +222,14 @@ namespace mwg
_impl->configurationValid, name, value);
}
+ bool GdalAlgorithmRunner::SetArgument(const std::string_view name, const std::vector& value)
+ {
+ if (!CanConfigure(name))
+ return false;
+ return SetArgumentValue(_impl->algorithm.get(), _impl->errors,
+ _impl->configurationValid, name, value);
+ }
+
bool GdalAlgorithmRunner::SetArgument(const std::string_view name,
const std::vector& value)
{
@@ -261,6 +269,30 @@ namespace mwg
return succeeded;
}
+ bool GdalAlgorithmRunner::ValidateArguments()
+ {
+ if (_impl->runAttempted)
+ {
+ AddError(_impl->errors, "GDAL algorithm arguments cannot be validated after Run().");
+ return false;
+ }
+ if (_impl->algorithm == nullptr || !_impl->configurationValid)
+ return false;
+
+ GdalErrorScope scope;
+ const std::size_t previousCount = _impl->errors.size();
+ const bool succeeded = _impl->algorithm->ValidateArguments();
+ AppendErrors(_impl->errors, scope);
+ scope.RethrowCaptureException();
+ if (!succeeded)
+ {
+ AddFailureIfNoDiagnostic(_impl->errors, previousCount,
+ "GDAL algorithm argument validation failed.");
+ _impl->configurationValid = false;
+ }
+ return succeeded;
+ }
+
bool GdalAlgorithmRunner::Run(GdalProgressAdapter::Callback progress,
const GdalCancellationToken* cancellationToken)
{
diff --git a/src/MwGdalCore/GdalTypedOptions.cpp b/src/MwGdalCore/GdalTypedOptions.cpp
new file mode 100644
index 0000000..e75f1bb
--- /dev/null
+++ b/src/MwGdalCore/GdalTypedOptions.cpp
@@ -0,0 +1,342 @@
+// SPDX-License-Identifier: MPL-2.0
+
+/**
+ * @file GdalTypedOptions.cpp
+ * @brief Converts typed GDAL algorithm options to validated arguments.
+ *
+ * Implements the high-priority raster and vector option structures and
+ * applies their values through the generic algorithm runner.
+ */
+#include "mapwingis/gdal/GdalTypedOptions.h"
+
+#include "mapwingis/gdal/GdalAlgorithmRunner.h"
+#include "internal/Utf8.h"
+
+#include
+#include
+#include
+#include
+#include
+
+namespace mwg
+{
+ namespace
+ {
+ void AddPath(GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::filesystem::path& value)
+ {
+ arguments.push_back({std::string(name), detail::ToUtf8(value)});
+ }
+
+ void AddPaths(GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::vector& values)
+ {
+ if (values.empty())
+ return;
+
+ std::vector paths;
+ paths.reserve(values.size());
+ for (const std::filesystem::path& value : values)
+ paths.push_back(detail::ToUtf8(value));
+ arguments.push_back({std::string(name), std::move(paths)});
+ }
+
+ template
+ void AddOptional(GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::optional& value)
+ {
+ if (value.has_value())
+ arguments.push_back({std::string(name), *value});
+ }
+
+ template
+ void AddArray(GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::optional>& value)
+ {
+ if (!value.has_value())
+ return;
+
+ std::vector values(value->begin(), value->end());
+ arguments.push_back({std::string(name), std::move(values)});
+ }
+
+ void AddOptions(GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::vector& values)
+ {
+ if (!values.empty())
+ arguments.push_back({std::string(name), values});
+ }
+
+ std::string FormatDouble(const double value)
+ {
+ char buffer[64];
+ const auto [end, error] =
+ std::to_chars(buffer, buffer + sizeof(buffer), value,
+ std::chars_format::general,
+ std::numeric_limits::max_digits10);
+ if (error != std::errc{})
+ throw std::runtime_error("Could not format a GDAL option value.");
+ return {buffer, end};
+ }
+
+ void AddNumericStringList(
+ GdalAlgorithmArguments& arguments,
+ const std::string_view name,
+ const std::optional>& values)
+ {
+ if (!values.has_value() || values->empty())
+ return;
+
+ std::vector strings;
+ strings.reserve(values->size());
+ for (const double value : *values)
+ strings.push_back(FormatDouble(value));
+ arguments.push_back({std::string(name), std::move(strings)});
+ }
+
+ void AddMosaicResolution(
+ GdalAlgorithmArguments& arguments,
+ const std::optional>>& resolution)
+ {
+ if (!resolution.has_value())
+ return;
+
+ std::visit(
+ [&arguments](const auto& value)
+ {
+ using Value = std::decay_t;
+ if constexpr (std::is_same_v)
+ {
+ arguments.push_back({"resolution", value});
+ }
+ else
+ {
+ std::string text = FormatDouble(value[0]);
+ text += ',';
+ text += FormatDouble(value[1]);
+ arguments.push_back({"resolution", std::move(text)});
+ }
+ },
+ *resolution);
+ }
+ }
+
+ bool ConfigureGdalAlgorithm(GdalAlgorithmRunner& runner,
+ const GdalAlgorithmArguments& arguments)
+ {
+ for (const GdalAlgorithmArgument& argument : arguments)
+ {
+ const bool set = std::visit(
+ [&runner, &argument](const auto& value)
+ {
+ return runner.SetArgument(argument.name, value);
+ },
+ argument.value);
+ if (!set)
+ return false;
+ }
+ return runner.ValidateArguments();
+ }
+
+ GdalAlgorithmArguments RasterConvertOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "append", append);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterReprojectOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "src-crs", sourceCrs);
+ AddOptional(arguments, "dst-crs", targetCrs);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "append", append);
+ AddArray(arguments, "resolution", resolution);
+ AddArray(arguments, "size", size);
+ AddArray(arguments, "bbox", boundingBox);
+ AddOptional(arguments, "bbox-crs", boundingBoxCrs);
+ AddOptional(arguments, "resampling", resampling);
+ AddNumericStringList(arguments, "src-nodata", inputNoData);
+ AddNumericStringList(arguments, "dst-nodata", outputNoData);
+ AddOptional(arguments, "target-aligned-pixels", targetAlignedPixels);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments VectorConvertOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptions(arguments, "input-layer", inputLayers);
+ AddOptional(arguments, "output-layer", outputLayer);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "update", update);
+ AddOptional(arguments, "overwrite-layer", overwriteLayer);
+ AddOptional(arguments, "append", append);
+ AddOptional(arguments, "skip-errors", skipErrors);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "layer-creation-option", layerCreationOptions);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterOverviewAddOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "dataset", input);
+ if (!levels.empty())
+ arguments.push_back({"levels", levels});
+ AddOptional(arguments, "resampling", resampling);
+ AddOptional(arguments, "min-size", minimumSize);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterInfoOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "dataset", input);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "min-max", minMax);
+ AddOptional(arguments, "stats", computeStatistics);
+ AddOptional(arguments, "approx-stats", approximateStatistics);
+ AddOptional(arguments, "hist", computeHistogram);
+ AddOptional(arguments, "checksum", checksum);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments VectorInfoOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "input-layer", layer);
+ AddOptional(arguments, "summary", summary);
+ AddOptional(arguments, "features", features);
+ AddOptional(arguments, "limit", limit);
+ AddOptional(arguments, "where", where);
+ AddOptional(arguments, "sql", sql);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterMosaicOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPaths(arguments, "input", inputs);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "append", append);
+ AddOptional(arguments, "band", bands);
+ AddMosaicResolution(arguments, resolution);
+ AddArray(arguments, "bbox", boundingBox);
+ AddOptional(arguments, "src-nodata", inputNoData);
+ AddOptional(arguments, "dst-nodata", outputNoData);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments VectorClipOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddPath(arguments, "output", output);
+ if (like.has_value())
+ AddPath(arguments, "like", *like);
+ AddOptional(arguments, "input-layer", inputLayer);
+ AddOptional(arguments, "like-layer", likeLayer);
+ AddOptional(arguments, "like-where", likeWhere);
+ AddOptional(arguments, "output-layer", outputLayer);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "update", update);
+ AddOptional(arguments, "overwrite-layer", overwriteLayer);
+ AddOptional(arguments, "append", append);
+ AddArray(arguments, "bbox", boundingBox);
+ AddOptional(arguments, "bbox-crs", boundingBoxCrs);
+ AddOptional(arguments, "geometry", geometry);
+ AddOptional(arguments, "geometry-crs", geometryCrs);
+ AddOptional(arguments, "skip-errors", skipErrors);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "layer-creation-option", layerCreationOptions);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterClipOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddPath(arguments, "input", input);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "append", append);
+ AddArray(arguments, "bbox", boundingBox);
+ AddOptional(arguments, "bbox-crs", boundingBoxCrs);
+ AddArray(arguments, "window", window);
+ AddOptional(arguments, "geometry", geometry);
+ AddOptional(arguments, "geometry-crs", geometryCrs);
+ if (like.has_value())
+ AddPath(arguments, "like", *like);
+ AddOptional(arguments, "like-layer", likeLayer);
+ AddOptional(arguments, "like-sql", likeSql);
+ AddOptional(arguments, "like-where", likeWhere);
+ AddOptional(arguments, "only-bbox", onlyBoundingBox);
+ AddOptional(arguments, "allow-bbox-outside-source", allowBoundingBoxOutsideSource);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+
+ GdalAlgorithmArguments RasterCalcOptions::ToArgs() const
+ {
+ GdalAlgorithmArguments arguments;
+ AddOptions(arguments, "calc", expressions);
+ AddPaths(arguments, "input", inputs);
+ AddPath(arguments, "output", output);
+ AddOptional(arguments, "output-format", outputFormat);
+ AddOptional(arguments, "output-data-type", outputDataType);
+ AddOptional(arguments, "overwrite", overwrite);
+ AddOptional(arguments, "append", append);
+ AddOptional(arguments, "nodata", outputNoData);
+ AddOptional(arguments, "dialect", dialect);
+ AddOptional(arguments, "no-check-srs", noCheckCrs);
+ AddOptional(arguments, "no-check-extent", noCheckExtent);
+ AddOptional(arguments, "propagate-nodata", propagateNoData);
+ AddOptional(arguments, "flatten", flatten);
+ AddOptions(arguments, "creation-option", creationOptions);
+ AddOptions(arguments, "input-format", inputFormats);
+ AddOptions(arguments, "open-option", openOptions);
+ return arguments;
+ }
+}
diff --git a/src/MwGdalCore/MwGdalCore.vcxproj b/src/MwGdalCore/MwGdalCore.vcxproj
index 5b2ba63..80d64e4 100644
--- a/src/MwGdalCore/MwGdalCore.vcxproj
+++ b/src/MwGdalCore/MwGdalCore.vcxproj
@@ -41,7 +41,7 @@
- ..\MapWinGIS.Core\include;%(AdditionalIncludeDirectories)
+ ..\MapWinGIS.Core\include;..\MapWinGIS.Core\src;%(AdditionalIncludeDirectories)
MWG_CORE_BUILD;%(PreprocessorDefinitions)
@@ -49,11 +49,13 @@
+
+
diff --git a/tests/MapWinGIS.Core.Tests/GdalTypedOptionsTests.cpp b/tests/MapWinGIS.Core.Tests/GdalTypedOptionsTests.cpp
new file mode 100644
index 0000000..60c2f50
--- /dev/null
+++ b/tests/MapWinGIS.Core.Tests/GdalTypedOptionsTests.cpp
@@ -0,0 +1,577 @@
+// SPDX-License-Identifier: MPL-2.0
+
+/**
+ * @file GdalTypedOptionsTests.cpp
+ * @brief Tests conversion and execution of typed GDAL algorithm options.
+ *
+ * Verifies option names and value types against GDAL metadata and checks
+ * vector conversion and clipping, raster conversion, clipping, reprojection,
+ * mosaicking, argument validation, and failure reporting.
+ */
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+#include "mapwingis/gdal/GdalAlgorithmRunner.h"
+#include "mapwingis/gdal/GdalEnvironment.h"
+#include "mapwingis/gdal/GdalTypedOptions.h"
+#include "TestData.h"
+
+using namespace mwg;
+
+namespace
+{
+ std::string ToUtf8(const std::filesystem::path& path)
+ {
+ const std::u8string utf8 = path.u8string();
+ return {reinterpret_cast(utf8.data()), utf8.size()};
+ }
+
+ std::string LastError(const GdalAlgorithmRunner& runner)
+ {
+ return runner.Errors().empty() ? std::string{} : runner.Errors().back().message;
+ }
+
+ GdalDatasetPtr OpenOutput(const std::filesystem::path& path, const unsigned int flags)
+ {
+ return GdalDatasetPtr(static_cast(
+ GDALOpenEx(ToUtf8(path).c_str(), flags, nullptr, nullptr, nullptr)));
+ }
+
+ void ExpectRasterGrid(GDALDataset& dataset, const int width, const int height,
+ const char* epsg, const std::array& expectedTransform)
+ {
+ EXPECT_EQ(dataset.GetRasterXSize(), width);
+ EXPECT_EQ(dataset.GetRasterYSize(), height);
+ EXPECT_EQ(dataset.GetRasterCount(), 1);
+ const OGRSpatialReference* srs = dataset.GetSpatialRef();
+ ASSERT_NE(srs, nullptr);
+ EXPECT_STREQ(srs->GetAuthorityName(nullptr), "EPSG");
+ EXPECT_STREQ(srs->GetAuthorityCode(nullptr), epsg);
+
+ std::array transform{};
+ ASSERT_EQ(dataset.GetGeoTransform(transform.data()), CE_None);
+ for (std::size_t i = 0; i < transform.size(); ++i)
+ EXPECT_NEAR(transform[i], expectedTransform[i], 1e-8) << i;
+ }
+
+ void ExpectPixels(GDALDataset& dataset, const std::vector& expected)
+ {
+ GDALRasterBand* band = dataset.GetRasterBand(1);
+ ASSERT_NE(band, nullptr);
+ EXPECT_EQ(band->GetRasterDataType(), GDT_Byte);
+ const int width = dataset.GetRasterXSize();
+ const int height = dataset.GetRasterYSize();
+ std::vector pixels(static_cast(width) *
+ static_cast(height));
+ ASSERT_EQ(band->RasterIO(GF_Read, 0, 0, width, height, pixels.data(),
+ width, height, GDT_Byte, 0, 0), CE_None);
+ EXPECT_EQ(pixels, expected);
+ }
+
+ void ExpectArgumentsExist(const std::string_view algorithmPath,
+ const GdalAlgorithmArguments& arguments)
+ {
+ GdalAlgorithmRunner runner(algorithmPath);
+ ASSERT_FALSE(runner.UsageAsJson().empty()) << algorithmPath;
+ for (const GdalAlgorithmArgument& argument : arguments)
+ {
+ const bool configured = std::visit(
+ [&runner, &argument](const auto& value)
+ {
+ return runner.SetArgument(argument.name, value);
+ },
+ argument.value);
+ EXPECT_TRUE(configured)
+ << algorithmPath << ": " << argument.name << ": "
+ << (runner.Errors().empty() ? std::string{} : runner.Errors().back().message);
+ }
+ }
+
+ void ExpectArgumentsValid(const std::string_view algorithmPath,
+ const GdalAlgorithmArguments& arguments)
+ {
+ GdalAlgorithmRunner runner(algorithmPath);
+ ASSERT_FALSE(runner.UsageAsJson().empty()) << algorithmPath;
+ EXPECT_TRUE(ConfigureGdalAlgorithm(runner, arguments))
+ << algorithmPath << ": "
+ << (runner.Errors().empty() ? std::string{} : runner.Errors().back().message);
+ }
+}
+
+TEST(GdalTypedOptions, EmitsMetadataRecognizedArgumentsForPriorityAlgorithms)
+{
+ GdalEnvironment::Initialize();
+
+ RasterConvertOptions rasterConvert;
+ rasterConvert.input = "input.tif";
+ rasterConvert.output = "output.tif";
+ rasterConvert.outputFormat = "GTiff";
+ rasterConvert.overwrite = true;
+ rasterConvert.append = false;
+ rasterConvert.inputFormats = {"GTiff"};
+ rasterConvert.creationOptions = {"TILED=YES"};
+ rasterConvert.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster convert", rasterConvert.ToArgs());
+
+ RasterReprojectOptions reproject;
+ reproject.input = "input.tif";
+ reproject.output = "output.tif";
+ reproject.outputFormat = "GTiff";
+ reproject.sourceCrs = "EPSG:4326";
+ reproject.targetCrs = "EPSG:3857";
+ reproject.overwrite = true;
+ reproject.append = false;
+ reproject.resolution = std::array{1, 1};
+ reproject.size = std::array{12, 8};
+ reproject.boundingBox = std::array{-1, -1, 1, 1};
+ reproject.boundingBoxCrs = "EPSG:3857";
+ reproject.resampling = "nearest";
+ reproject.inputNoData = std::vector{0};
+ reproject.outputNoData = std::vector{255};
+ reproject.targetAlignedPixels = true;
+ reproject.creationOptions = {"TILED=YES"};
+ reproject.inputFormats = {"GTiff"};
+ reproject.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster reproject", reproject.ToArgs());
+
+ VectorConvertOptions vectorConvert;
+ vectorConvert.input = "input.gpkg";
+ vectorConvert.output = "output.geojson";
+ vectorConvert.outputFormat = "GeoJSON";
+ vectorConvert.inputLayers = {"provinces"};
+ vectorConvert.outputLayer = "converted";
+ vectorConvert.overwrite = true;
+ vectorConvert.update = false;
+ vectorConvert.overwriteLayer = false;
+ vectorConvert.append = false;
+ vectorConvert.skipErrors = false;
+ vectorConvert.inputFormats = {"GPKG"};
+ vectorConvert.creationOptions = {"RFC7946=YES"};
+ vectorConvert.layerCreationOptions = {"COORDINATE_PRECISION=6"};
+ vectorConvert.openOptions = {"LIST_ALL_TABLES=YES"};
+ ExpectArgumentsExist("vector convert", vectorConvert.ToArgs());
+
+ RasterOverviewAddOptions overviews;
+ overviews.input = "input.tif";
+ overviews.levels = {2, 4};
+ overviews.resampling = "average";
+ overviews.minimumSize = 256;
+ overviews.creationOptions = {"COMPRESS_OVERVIEW=DEFLATE"};
+ overviews.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster overview add", overviews.ToArgs());
+
+ RasterInfoOptions rasterInfo;
+ rasterInfo.input = "input.tif";
+ rasterInfo.outputFormat = "json";
+ rasterInfo.minMax = true;
+ rasterInfo.computeStatistics = true;
+ rasterInfo.approximateStatistics = false;
+ rasterInfo.computeHistogram = false;
+ rasterInfo.checksum = true;
+ rasterInfo.inputFormats = {"GTiff"};
+ rasterInfo.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster info", rasterInfo.ToArgs());
+
+ VectorInfoOptions vectorInfo;
+ vectorInfo.input = "input.gpkg";
+ vectorInfo.layer = "provinces";
+ vectorInfo.summary = true;
+ vectorInfo.features = false;
+ vectorInfo.limit = 5;
+ vectorInfo.where = "ID > 0";
+ vectorInfo.sql = "SELECT * FROM provinces";
+ vectorInfo.inputFormats = {"GPKG"};
+ vectorInfo.openOptions = {"LIST_ALL_TABLES=YES"};
+ ExpectArgumentsExist("vector info", vectorInfo.ToArgs());
+
+ RasterMosaicOptions mosaic;
+ mosaic.inputs = {"first.tif", "second.tif"};
+ mosaic.output = "mosaic.tif";
+ mosaic.outputFormat = "GTiff";
+ mosaic.overwrite = true;
+ mosaic.append = false;
+ mosaic.bands = std::vector{1};
+ mosaic.resolution = std::array{1, 1};
+ mosaic.boundingBox = std::array{0, 0, 10, 10};
+ mosaic.inputNoData = std::vector{0};
+ mosaic.outputNoData = std::vector{255};
+ mosaic.creationOptions = {"TILED=YES"};
+ mosaic.inputFormats = {"GTiff"};
+ mosaic.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster mosaic", mosaic.ToArgs());
+
+ VectorClipOptions vectorClip;
+ vectorClip.input = "input.gpkg";
+ vectorClip.output = "clipped.gpkg";
+ vectorClip.like = "overlay.gpkg";
+ vectorClip.inputLayer = "provinces";
+ vectorClip.likeLayer = "boundary";
+ vectorClip.likeWhere = "ID > 0";
+ vectorClip.outputLayer = "clipped";
+ vectorClip.outputFormat = "GPKG";
+ vectorClip.overwrite = true;
+ vectorClip.update = false;
+ vectorClip.overwriteLayer = false;
+ vectorClip.append = false;
+ vectorClip.boundingBox = std::array{0, 0, 10, 10};
+ vectorClip.boundingBoxCrs = "EPSG:28992";
+ vectorClip.geometry = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))";
+ vectorClip.geometryCrs = "EPSG:28992";
+ vectorClip.skipErrors = false;
+ vectorClip.creationOptions = {"SPATIAL_INDEX=YES"};
+ vectorClip.layerCreationOptions = {"GEOMETRY_NAME=geom"};
+ vectorClip.openOptions = {"LIST_ALL_TABLES=YES"};
+ ExpectArgumentsExist("vector clip", vectorClip.ToArgs());
+
+ RasterClipOptions rasterClip;
+ rasterClip.input = "input.tif";
+ rasterClip.output = "clipped.tif";
+ rasterClip.outputFormat = "GTiff";
+ rasterClip.overwrite = true;
+ rasterClip.append = false;
+ rasterClip.boundingBox = std::array{0, 0, 10, 10};
+ rasterClip.boundingBoxCrs = "EPSG:4326";
+ rasterClip.window = std::array{0, 0, 10, 10};
+ rasterClip.geometry = "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))";
+ rasterClip.geometryCrs = "EPSG:4326";
+ rasterClip.like = "cutline.gpkg";
+ rasterClip.likeLayer = "boundary";
+ rasterClip.likeSql = "SELECT * FROM boundary";
+ rasterClip.likeWhere = "ID > 0";
+ rasterClip.onlyBoundingBox = false;
+ rasterClip.allowBoundingBoxOutsideSource = true;
+ rasterClip.creationOptions = {"TILED=YES"};
+ rasterClip.inputFormats = {"GTiff"};
+ rasterClip.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster clip", rasterClip.ToArgs());
+
+ RasterCalcOptions rasterCalc;
+ rasterCalc.expressions = {"X + 1", "X - 1"};
+ rasterCalc.inputs = {"input.tif"};
+ rasterCalc.output = "calculated.tif";
+ rasterCalc.outputFormat = "GTiff";
+ rasterCalc.outputDataType = "Byte";
+ rasterCalc.overwrite = true;
+ rasterCalc.append = false;
+ rasterCalc.outputNoData = 255;
+ rasterCalc.dialect = "builtin";
+ rasterCalc.noCheckCrs = false;
+ rasterCalc.noCheckExtent = false;
+ rasterCalc.propagateNoData = true;
+ rasterCalc.flatten = false;
+ rasterCalc.creationOptions = {"TILED=YES"};
+ rasterCalc.inputFormats = {"GTiff"};
+ rasterCalc.openOptions = {"NUM_THREADS=1"};
+ ExpectArgumentsExist("raster calc", rasterCalc.ToArgs());
+}
+
+TEST(GdalTypedOptions, ValidatesMinimumArgumentsForEachPriorityAlgorithm)
+{
+ GdalEnvironment::Initialize();
+
+ test::TempDirectory directory;
+ const std::filesystem::path raster = test::MakeRaster(directory.Path());
+ const std::filesystem::path vector =
+ test::MakeProvincesDataset(directory.Path(), "typed.gpkg");
+
+ RasterConvertOptions rasterConvert;
+ rasterConvert.input = raster;
+ rasterConvert.output = directory.Path() / "converted.tif";
+ ExpectArgumentsValid("raster convert", rasterConvert.ToArgs());
+
+ RasterReprojectOptions reproject;
+ reproject.input = raster;
+ reproject.output = directory.Path() / "reprojected.tif";
+ reproject.sourceCrs = "EPSG:4326";
+ reproject.targetCrs = "EPSG:3857";
+ ExpectArgumentsValid("raster reproject", reproject.ToArgs());
+
+ VectorConvertOptions vectorConvert;
+ vectorConvert.input = vector;
+ vectorConvert.output = directory.Path() / "converted.geojson";
+ ExpectArgumentsValid("vector convert", vectorConvert.ToArgs());
+
+ RasterOverviewAddOptions overviews;
+ overviews.input = raster;
+ overviews.levels = {2};
+ ExpectArgumentsValid("raster overview add", overviews.ToArgs());
+
+ RasterInfoOptions rasterInfo;
+ rasterInfo.input = raster;
+ ExpectArgumentsValid("raster info", rasterInfo.ToArgs());
+
+ VectorInfoOptions vectorInfo;
+ vectorInfo.input = vector;
+ ExpectArgumentsValid("vector info", vectorInfo.ToArgs());
+
+ RasterMosaicOptions mosaic;
+ mosaic.inputs = {raster};
+ mosaic.output = directory.Path() / "mosaic.tif";
+ ExpectArgumentsValid("raster mosaic", mosaic.ToArgs());
+
+ VectorClipOptions vectorClip;
+ vectorClip.input = vector;
+ vectorClip.output = directory.Path() / "clipped.gpkg";
+ vectorClip.boundingBox = std::array{100000, 400000, 104000, 401000};
+ ExpectArgumentsValid("vector clip", vectorClip.ToArgs());
+
+ RasterClipOptions rasterClip;
+ rasterClip.input = raster;
+ rasterClip.output = directory.Path() / "raster-clipped.tif";
+ rasterClip.boundingBox = std::array{0, 0, 10, 8};
+ ExpectArgumentsValid("raster clip", rasterClip.ToArgs());
+
+ RasterCalcOptions rasterCalc;
+ rasterCalc.expressions = {"X + 1"};
+ rasterCalc.inputs = {raster};
+ rasterCalc.output = directory.Path() / "calculated.tif";
+ ExpectArgumentsValid("raster calc", rasterCalc.ToArgs());
+}
+
+TEST(GdalTypedOptions, ConvertsRasterToPngAndReturnsTheOutputDataset)
+{
+ GdalEnvironment::Initialize();
+ GdalEnvironment::QuietScope quiet;
+ test::TempDirectory directory;
+ const std::filesystem::path input =
+ test::MakeRaster(directory.Path(), std::filesystem::path(u8"typed-ε
₯ε.tif"));
+ const std::filesystem::path output =
+ directory.Path() / std::filesystem::path(u8"typed-εΊε.png");
+
+ RasterConvertOptions options;
+ options.input = input;
+ options.output = output;
+ options.outputFormat = "PNG";
+
+ GdalAlgorithmRunner runner("raster convert");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs()));
+ ASSERT_TRUE(runner.Run());
+
+ GdalDatasetPtr dataset = runner.TakeOutputDataset();
+ ASSERT_NE(dataset, nullptr);
+ EXPECT_EQ(dataset->GetRasterXSize(), 12);
+ EXPECT_EQ(dataset->GetRasterYSize(), 8);
+ std::uint8_t pixel = 0;
+ ASSERT_EQ(dataset->GetRasterBand(1)->RasterIO(GF_Read, 0, 0, 1, 1,
+ &pixel, 1, 1, GDT_Byte, 0, 0),
+ CE_None);
+ EXPECT_EQ(pixel, 42);
+ EXPECT_TRUE(std::filesystem::exists(output));
+}
+
+TEST(GdalTypedOptions, ConvertsVectorLayersAndPreservesAttributes)
+{
+ test::TempDirectory directory;
+ VectorConvertOptions options;
+ options.input = test::MakeProvincesDataset(directory.Path(), "input.gpkg");
+ options.output = directory.Path() / "converted.geojson";
+ options.outputFormat = "GeoJSON";
+ options.inputLayers = {test::Provinces::kLayerName};
+ options.outputLayer = "converted";
+
+ {
+ GdalAlgorithmRunner runner("vector convert");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs())) << LastError(runner);
+ ASSERT_TRUE(runner.Run()) << LastError(runner);
+ }
+
+ EXPECT_TRUE(std::filesystem::exists(options.output));
+ GdalDatasetPtr dataset = OpenOutput(options.output, GDAL_OF_VECTOR);
+ ASSERT_NE(dataset, nullptr);
+ EXPECT_STREQ(dataset->GetDriver()->GetDescription(), "GeoJSON");
+ EXPECT_EQ(dataset->GetLayerCount(), 1);
+ OGRLayer* layer = dataset->GetLayerByName("converted");
+ ASSERT_NE(layer, nullptr);
+ EXPECT_EQ(layer->GetFeatureCount(), test::Provinces::kFeatureCount);
+ ASSERT_NE(layer->GetSpatialRef(), nullptr);
+ EXPECT_STREQ(layer->GetSpatialRef()->GetAuthorityCode(nullptr), "28992");
+ EXPECT_EQ(layer->GetLayerDefn()->GetFieldCount(), 5);
+
+ for (int i = 0; i < test::Provinces::kFeatureCount; ++i)
+ {
+ OGRFeatureUniquePtr feature(layer->GetNextFeature());
+ ASSERT_NE(feature, nullptr);
+ EXPECT_EQ(feature->GetFieldAsInteger(test::Provinces::kIdField), i + 1);
+ EXPECT_DOUBLE_EQ(feature->GetFieldAsDouble(test::Provinces::kAreaField), 1.0);
+ if (i == 2)
+ EXPECT_STREQ(feature->GetFieldAsString(test::Provinces::kNameField),
+ test::Provinces::kNonAsciiName);
+ if (i == test::Provinces::kNullFeature)
+ EXPECT_FALSE(feature->IsFieldSetAndNotNull(
+ feature->GetFieldIndex(test::Provinces::kNameField)));
+
+ OGRGeometry* geometry = feature->GetGeometryRef();
+ ASSERT_NE(geometry, nullptr);
+ EXPECT_NEAR(OGR_G_Area(OGRGeometry::ToHandle(geometry)), 1000000.0, 1e-6);
+ }
+
+ OGREnvelope extent;
+ ASSERT_EQ(layer->GetExtent(&extent), OGRERR_NONE);
+ EXPECT_DOUBLE_EQ(extent.MinX, test::Provinces::kMinX);
+ EXPECT_DOUBLE_EQ(extent.MinY, test::Provinces::kMinY);
+ EXPECT_DOUBLE_EQ(extent.MaxX, test::Provinces::kMaxX);
+ EXPECT_DOUBLE_EQ(extent.MaxY, test::Provinces::kMaxY);
+}
+
+TEST(GdalTypedOptions, ClipsVectorGeometriesAndPreservesTheirAttributes)
+{
+ test::TempDirectory directory;
+ VectorClipOptions options;
+ options.input = test::MakeProvincesDataset(directory.Path(), "input.gpkg");
+ options.output = directory.Path() / "clipped.gpkg";
+ options.outputFormat = "GPKG";
+ options.inputLayer = test::Provinces::kLayerName;
+ options.outputLayer = "clipped";
+ options.boundingBox = std::array{100500, 400250, 101500, 400750};
+ options.boundingBoxCrs = "EPSG:28992";
+
+ {
+ GdalAlgorithmRunner runner("vector clip");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs())) << LastError(runner);
+ ASSERT_TRUE(runner.Run()) << LastError(runner);
+ }
+
+ EXPECT_TRUE(std::filesystem::exists(options.output));
+ GdalDatasetPtr dataset = OpenOutput(options.output, GDAL_OF_VECTOR);
+ ASSERT_NE(dataset, nullptr);
+ OGRLayer* layer = dataset->GetLayerByName("clipped");
+ ASSERT_NE(layer, nullptr);
+ EXPECT_EQ(layer->GetFeatureCount(), 2);
+ ASSERT_NE(layer->GetSpatialRef(), nullptr);
+ EXPECT_STREQ(layer->GetSpatialRef()->GetAuthorityCode(nullptr), "28992");
+ for (int i = 0; i < 2; ++i)
+ {
+ OGRFeatureUniquePtr feature(layer->GetNextFeature());
+ ASSERT_NE(feature, nullptr);
+ EXPECT_EQ(feature->GetFieldAsInteger(test::Provinces::kIdField), i + 1);
+ EXPECT_STREQ(feature->GetFieldAsString(test::Provinces::kNameField),
+ i == 0 ? "Noord" : "Oost");
+ OGRGeometry* geometry = feature->GetGeometryRef();
+ ASSERT_NE(geometry, nullptr);
+ EXPECT_NEAR(OGR_G_Area(OGRGeometry::ToHandle(geometry)), 250000.0, 1e-6);
+ }
+
+ OGREnvelope extent;
+ ASSERT_EQ(layer->GetExtent(&extent), OGRERR_NONE);
+ EXPECT_DOUBLE_EQ(extent.MinX, 100500);
+ EXPECT_DOUBLE_EQ(extent.MinY, 400250);
+ EXPECT_DOUBLE_EQ(extent.MaxX, 101500);
+ EXPECT_DOUBLE_EQ(extent.MaxY, 400750);
+}
+
+TEST(GdalTypedOptions, ClipsRasterToAPixelWindow)
+{
+ test::TempDirectory directory;
+ RasterClipOptions options;
+ options.input = test::MakeRaster(directory.Path());
+ options.output = directory.Path() / "clipped.tif";
+ options.outputFormat = "GTiff";
+ options.window = std::array{2, 1, 5, 3};
+ options.creationOptions = {"COMPRESS=LZW"};
+
+ {
+ GdalAlgorithmRunner runner("raster clip");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs())) << LastError(runner);
+ ASSERT_TRUE(runner.Run()) << LastError(runner);
+ }
+
+ EXPECT_TRUE(std::filesystem::exists(options.output));
+ GdalDatasetPtr dataset = OpenOutput(options.output, GDAL_OF_RASTER);
+ ASSERT_NE(dataset, nullptr);
+ ExpectRasterGrid(*dataset, 5, 3, "4326", {2, 1, 0, 7, 0, -1});
+ EXPECT_STREQ(dataset->GetMetadataItem("COMPRESSION", "IMAGE_STRUCTURE"), "LZW");
+ ExpectPixels(*dataset, std::vector(15, 42));
+}
+
+TEST(GdalTypedOptions, ReprojectsRasterToTheRequestedCrsBoundsAndSize)
+{
+ test::TempDirectory directory;
+ RasterReprojectOptions options;
+ options.input = test::MakeRaster(directory.Path());
+ options.output = directory.Path() / "reprojected.tif";
+ options.outputFormat = "GTiff";
+ options.targetCrs = "EPSG:3857";
+ options.boundingBox = std::array{0, 0, 1200000, 800000};
+ options.boundingBoxCrs = "EPSG:3857";
+ options.size = std::array{6, 4};
+ options.resampling = "nearest";
+ options.outputNoData = std::vector{255};
+
+ {
+ GdalAlgorithmRunner runner("raster reproject");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs())) << LastError(runner);
+ ASSERT_TRUE(runner.Run()) << LastError(runner);
+ }
+
+ EXPECT_TRUE(std::filesystem::exists(options.output));
+ GdalDatasetPtr dataset = OpenOutput(options.output, GDAL_OF_RASTER);
+ ASSERT_NE(dataset, nullptr);
+ ExpectRasterGrid(*dataset, 6, 4, "3857", {0, 200000, 0, 800000, 0, -200000});
+ ExpectPixels(*dataset, std::vector(24, 42));
+ GDALRasterBand* band = dataset->GetRasterBand(1);
+ ASSERT_NE(band, nullptr);
+ int hasNoData = false;
+ EXPECT_DOUBLE_EQ(band->GetNoDataValue(&hasNoData), 255);
+ EXPECT_TRUE(hasNoData);
+}
+
+TEST(GdalTypedOptions, MosaicsAdjacentRastersAtTheRequestedResolution)
+{
+ test::TempDirectory directory;
+ RasterMosaicOptions options;
+ options.inputs = {test::MakeRaster(directory.Path(), "left.tif"),
+ test::MakeRaster(directory.Path(), "right.tif", 12, 84)};
+ options.output = directory.Path() / "mosaic.tif";
+ options.outputFormat = "GTiff";
+ options.bands = std::vector{1};
+ options.resolution = std::array{0.5, 0.5};
+ options.boundingBox = std::array{0, 0, 24, 8};
+
+ {
+ GdalAlgorithmRunner runner("raster mosaic");
+ ASSERT_TRUE(ConfigureGdalAlgorithm(runner, options.ToArgs())) << LastError(runner);
+ ASSERT_TRUE(runner.Run()) << LastError(runner);
+ }
+
+ EXPECT_TRUE(std::filesystem::exists(options.output));
+ GdalDatasetPtr dataset = OpenOutput(options.output, GDAL_OF_RASTER);
+ ASSERT_NE(dataset, nullptr);
+ ExpectRasterGrid(*dataset, 48, 16, "4326", {0, 0.5, 0, 8, 0, -0.5});
+ std::vector expected;
+ expected.reserve(48 * 16);
+ for (int row = 0; row < 16; ++row)
+ {
+ for (int column = 0; column < 48; ++column)
+ expected.push_back(column < 24 ? 42 : 84);
+ }
+ ExpectPixels(*dataset, expected);
+}
+
+TEST(GdalTypedOptions, RejectsUnknownAndMutuallyExclusiveArguments)
+{
+ GdalEnvironment::Initialize();
+ test::TempDirectory directory;
+
+ GdalAlgorithmRunner unknown("raster convert");
+ EXPECT_FALSE(ConfigureGdalAlgorithm(
+ unknown, GdalAlgorithmArguments{{"not-a-gdal-option", std::string("value")}}));
+ ASSERT_FALSE(unknown.Errors().empty());
+
+ RasterConvertOptions conflicting;
+ conflicting.input = test::MakeRaster(directory.Path());
+ conflicting.output = directory.Path() / "conflicting.tif";
+ conflicting.overwrite = true;
+ conflicting.append = true;
+ GdalAlgorithmRunner invalid("raster convert");
+ EXPECT_FALSE(ConfigureGdalAlgorithm(invalid, conflicting.ToArgs()));
+ ASSERT_FALSE(invalid.Errors().empty());
+}
diff --git a/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj
index 8fe5a2d..6d05d1c 100644
--- a/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj
+++ b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj
@@ -56,6 +56,7 @@
+
diff --git a/tests/MapWinGIS.Core.Tests/TestData.cpp b/tests/MapWinGIS.Core.Tests/TestData.cpp
index 7b743e0..dadc3ee 100644
--- a/tests/MapWinGIS.Core.Tests/TestData.cpp
+++ b/tests/MapWinGIS.Core.Tests/TestData.cpp
@@ -2,15 +2,16 @@
/**
* @file TestData.cpp
- * @brief Implements shared vector test fixture helpers.
+ * @brief Implements shared raster and vector test fixture helpers.
*
- * Manages temporary directories and creates polygon datasets with attributes,
- * null values, and projections for the core tests.
+ * Manages temporary directories and creates georeferenced rasters and polygon
+ * datasets with attributes, null values, and projections for the core tests.
*/
#include "TestData.h"
#include
#include
+#include
#include
#include
@@ -47,6 +48,45 @@ namespace mwg::test
std::filesystem::remove_all(_path, ignored);
}
+ std::filesystem::path MakeRaster(const std::filesystem::path& directory,
+ const std::filesystem::path& fileName,
+ const double originX,
+ const std::uint8_t pixelValue)
+ {
+ GdalEnvironment::Initialize();
+ constexpr int kWidth = 12;
+ constexpr int kHeight = 8;
+ const std::filesystem::path path = directory / fileName;
+ GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
+ if (driver == nullptr)
+ throw std::runtime_error("GTiff driver is not available");
+
+ GDALDatasetUniquePtr dataset(
+ driver->Create(ToUtf8(path).c_str(), kWidth, kHeight, 1, GDT_Byte, nullptr));
+ if (dataset == nullptr)
+ throw std::runtime_error("Could not create the test raster");
+
+ double transform[] = {originX, 1, 0, 8, 0, -1};
+ OGRSpatialReference srs;
+ if (srs.importFromEPSG(4326) != OGRERR_NONE ||
+ dataset->SetSpatialRef(&srs) != CE_None ||
+ dataset->SetGeoTransform(transform) != CE_None)
+ {
+ throw std::runtime_error("Could not georeference the test raster");
+ }
+
+ std::vector pixels(static_cast(kWidth * kHeight), pixelValue);
+ if (dataset->GetRasterBand(1)->RasterIO(GF_Write, 0, 0, kWidth, kHeight,
+ pixels.data(), kWidth, kHeight,
+ GDT_Byte, 0, 0) != CE_None)
+ {
+ throw std::runtime_error("Could not write the test raster");
+ }
+ if (dataset->FlushCache() != CE_None)
+ throw std::runtime_error("Could not flush the test raster");
+ return path;
+ }
+
std::filesystem::path MakeProvincesDataset(const std::filesystem::path& directory,
const std::string& fileName)
{
diff --git a/tests/MapWinGIS.Core.Tests/TestData.h b/tests/MapWinGIS.Core.Tests/TestData.h
index 29f4a1b..2ffab7e 100644
--- a/tests/MapWinGIS.Core.Tests/TestData.h
+++ b/tests/MapWinGIS.Core.Tests/TestData.h
@@ -2,18 +2,27 @@
/**
* @file TestData.h
- * @brief Declares shared vector test data and fixture helpers.
+ * @brief Declares shared raster and vector test data and fixture helpers.
*
* Provides generated dataset metadata, temporary-directory support, and
- * helpers for creating Shapefile and GeoPackage fixtures.
+ * helpers for creating GeoTIFF, Shapefile, and GeoPackage fixtures.
*/
#pragma once
+#include
#include
#include
namespace mwg::test
{
+ /// Writes a 12-by-8, single-band Byte GeoTIFF in EPSG:4326.
+ /// Pixels have the given value. Each pixel spans one degree, with the
+ /// top-left corner at (originX, 8) and rows running south.
+ std::filesystem::path MakeRaster(const std::filesystem::path& directory,
+ const std::filesystem::path& fileName = "raster.tif",
+ double originX = 0.0,
+ std::uint8_t pixelValue = 42);
+
/// Describes the projected polygon layer written by MakeProvincesDataset().
struct Provinces
{