Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions MapWinGIS6.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
<Folder Name="/tests/">
<Project Path="tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj" Id="2b6a9a3b-0c5e-4e6e-9e31-3e8f5a2d1c02" />
</Folder>
<Folder Name="/samples/">
<Project Path="samples/Cpp/Translate.vcxproj" Id="2b6a9a3b-0c5e-4e6e-9e31-3e8f5a2d1c03" />
</Folder>
<Folder Name="/build/">
<File Path="Directory.Build.props" />
<File Path="Directory.Build.targets" />
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,12 @@ For additional configurations, dependency features, and troubleshooting, see
|---|---|
| `src/MapWinGIS.Core/` | The core engine. Public headers in `include/mapwingis/` |
| `tests/MapWinGIS.Core.Tests/` | C++ unit tests (GoogleTest) |
| `samples/Cpp/` | Buildable native C++ examples |
| `build/` | Shared MSBuild props, vcpkg triplets and scripts |
| `docs/` | Build, architecture, coding, porting and testing documentation |
| `docs/` | Build, architecture, coding, GDAL integration, porting and testing documentation |

See [GDAL integration](docs/gdal-integration.md) for GDAL setup, API examples,
progress handling, migration notes, and limitations.

## License

Expand Down
2 changes: 2 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ up automatically).
tests. Each has four polygons in EPSG:28992, all five field types, null
values, and UTF-8 names. Tests edit their own generated datasets.
- Wrap expected GDAL noise in `GdalEnvironment::QuietScope`.
- Tests use local generated data and do not require network access by default.
Set `MWG_RUN_NETWORK_GDAL_TESTS=1` to enable the public `/vsicurl/` COG test.
200 changes: 200 additions & 0 deletions docs/gdal-integration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
# GDAL integration

MapWinGIS6 provides a native C++20 interface to GDAL through
`MapWinGIS.Core.dll`. `MwGdalCore` implements GDAL algorithm execution;
`MapWinGIS.Core` configures GDAL's runtime data paths and exposes the public
headers under `mapwingis/gdal/`. The Core DLL does not use COM, ATL, or MFC.

## Requirements and runtime setup

MapWinGIS6 requires GDAL 3.12.4 or later. The vcpkg manifest pins the version
used by this repository. GDAL headers and libraries come from vcpkg; do not
install another GDAL SDK beside the application. See [GDAL versioning](gdal-version.md)
and [Building MapWinGIS6](BUILDING.md) for dependency and build instructions.

`GdalEnvironment::Initialize()` registers drivers once and points GDAL and PROJ
to the runtime data deployed beside `MapWinGIS.Core.dll`. Call it before direct
GDAL use; the MapWinGIS GDAL APIs initialize the environment as needed. The
driver set depends on the vcpkg build features. Check availability at runtime
with `GdalEnvironment::HasRasterDriver()` or `HasVectorDriver()`. An absent
driver or unsupported algorithm produces GDAL diagnostics; it is not silently
substituted.

The DLL API exchanges C++ standard-library types across the DLL boundary.
Consumers must use the same MSVC toolset and CRT as the Core DLL.

## Generic algorithms and typed options

Use `GdalAlgorithmRunner` when you need an algorithm supported by the
installed GDAL build. Its path is the GDAL algorithm name, and
`UsageAsJson()` exposes the installed algorithm's own argument metadata:

```cpp
mwg::GdalEnvironment::Initialize();
mwg::GdalAlgorithmRunner runner("raster convert");
const std::string metadata = runner.UsageAsJson();
```

Pass arguments with the typed `SetArgument()` overloads or
`ParseCommandLineArgs()`, then call `Run()`. The runner validates arguments
against GDAL's metadata and captures warnings and failures in `Errors()`.
`Result()` returns a snapshot without transferring output datasets;
`TakeOutputDataset()` transfers ownership of an output dataset.

For common operations, use a typed options structure. This example converts
an input raster to GeoTIFF and reports captured diagnostics on failure:

```cpp
mwg::RasterConvertOptions options;
options.input = inputPath;
options.output = outputPath;
options.outputFormat = "GTiff";
options.creationOptions = {"COMPRESS=LZW"};

mwg::GdalAlgorithmRunner runner("raster convert");
if (!mwg::ConfigureGdalAlgorithm(runner, options.ToArgs()) || !runner.Run())
{
const auto result = runner.Result();
std::cerr << result.DetailedErrorMsg() << '\n';
}
```

The typed structures cover raster conversion, clipping, reprojection,
mosaicking, calculation and overviews, plus vector conversion and clipping.
They translate values to GDAL arguments; GDAL remains responsible for
algorithm-specific validation, driver support and defaults. To see the current
option list for an installed algorithm, inspect `UsageAsJson()` instead of
copying an option list into application documentation.

## Progress and cancellation

Progress callbacks execute synchronously on the thread running GDAL. Return
`false` to cancel. A cancellation token can also be cancelled from another
thread and must remain alive until the operation returns:

```cpp
mwg::GdalCancellationToken cancellation;
const auto progress = [](double fraction, std::string_view message)
{
std::cout << fraction << ": " << message << '\n';
return true;
};

const bool succeeded = runner.Run(progress, &cancellation);
```

Use the token with `WriteCog()` or `RunPipeline()` in the same way. Not every
GDAL algorithm reports progress, so cancellation may not interrupt those
algorithms promptly. Cancellation can leave partial output files. Callbacks
must not start another GDAL operation or wait on a thread that needs the GDAL
execution lock; callback exceptions are returned as operation failures.

## Errors and logging

Runner and convenience-operation results own their diagnostic lists.
`Succeeded()` is true only if GDAL execution and finalization succeed.
`LastErrorCode()` and `ErrorMsg()` select the last failure or fatal diagnostic;
warnings alone do not make a successful operation fail. Use
`DetailedErrorMsg()` or `AllErrors()` when the full diagnostic context matters.

Install an optional process-wide handler with
`GdalEnvironment::SetLogHandler()`. Diagnostics are delivered on the thread
that raises them. Handlers must not re-enter GDAL or wait for GDAL work on
another thread. The callback boundary does not permit exceptions to cross into
GDAL; captured logger exceptions are rethrown by the operation after GDAL
returns.

## In-memory datasets and pipelines

`RunPipeline()` passes each step's output dataset directly to the next step.
Later steps omit the `input` argument. Keep the returned result alive while
using its output dataset; it retains intermediate datasets required by VRT
outputs. Choose output formats such as `MEM` for in-memory raster processing
or `VRT` for virtual datasets when the algorithm supports them:

```cpp
mwg::RasterConvertOptions options;
options.input = inputPath;
options.outputFormat = "MEM";

mwg::GdalPipelineStep step{
{"raster", "convert"},
options.ToArgs()
};
const auto result = mwg::RunPipeline({step});
```

`WriteCog()` is the convenience operation for Cloud-Optimized GeoTIFF output.
The COG driver and the GDAL build determine which creation options are
available. VRT files can refer to source datasets; keep their sources
available for as long as the VRT needs them.

## Cloud and virtual filesystem paths

GDAL virtual filesystem paths such as `/vsicurl/`, `/vsis3/`, `/vsizip/`,
`/vsiaz/`, and `/vsimem/` are accepted as UTF-8 paths when the selected driver
supports them. Cloud access depends on the GDAL build, network access and
provider configuration. Use GDAL's supported credential mechanisms or
configuration options. `GdalConfig::SetOption()` changes process-wide
configuration; `ScopedGdalConfigOption` restores the previous value at scope
exit but does not isolate concurrent changes to the same option. Never put
credentials in paths, source code, tests or logs.

## GDAL 3 axis order

GDAL 3 honors the axis order defined by a coordinate reference system's
authority when using OGR spatial-reference and coordinate-transformation APIs.
For example, EPSG:4326 is latitude then longitude according to its authority
definition. MapWinGIS6 does not install a global axis-order override; GDAL
algorithms apply their own documented behavior.

For direct OGR transformations that must use traditional GIS X/Y order, set
the strategy on the spatial reference objects before creating the
transformation:

```cpp
OGRSpatialReference srs;
srs.importFromEPSG(4326);
srs.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
```

Apply the same intended convention to both source and target spatial
references. This is an explicit per-object choice, not a process-wide
compatibility setting. Check the selected algorithm's usage metadata for
algorithm-specific CRS options.

## Migration and examples

MapWinGIS5's COM `GdalUtils` is not yet exposed by MapWinGIS6's ActiveX layer.
Use the native runner and typed options for new C++ code. A deprecated native
`GdalUtils` bridge is available for gradual migration; it is not
binary-compatible with the v5 COM object. See [GDAL migration](gdal-migration.md)
for operation examples and API differences.

The solution builds the runnable C++ example
[`samples/Cpp/translate.cpp`](../samples/Cpp/translate.cpp). Run it with
`bin\Debug\x64\translate.exe <input-raster> <output-raster>`.
There is no C# sample yet: the Core DLL has no managed binding or C ABI, and
the ActiveX layer does not expose the GDAL API to C#.

## Limitations and troubleshooting

- Driver and algorithm availability varies with the vcpkg feature set. Check
`HasRasterDriver()`, `HasVectorDriver()`, and `UsageAsJson()` at runtime.
- The runner serializes its GDAL algorithm calls, but returned datasets and
direct GDAL calls are not covered by that lock. Synchronize access to shared
datasets and process-wide configuration yourself.
- Native Core objects are not thread-safe unless their API says otherwise.
Progress and logging callbacks run synchronously on the operation thread.
- If initialization reports missing GDAL or PROJ data, rebuild with runtime
data deployment enabled. The data directories are placed beside the DLL;
do not set `GDAL_DATA` or `PROJ_LIB` as a workaround.
- If a cloud path fails, confirm the driver, protocol support, credentials,
network access and GDAL configuration for the installed build.
- If a conversion fails, inspect all captured diagnostics; an installed GDAL
build may not include the requested output driver or algorithm.

The automated tests create small raster and vector fixtures under temporary
directories and remove them after each test. They do not depend on network
data unless `MWG_RUN_NETWORK_GDAL_TESTS=1` is set for the opt-in public COG
test.
63 changes: 63 additions & 0 deletions samples/Cpp/Translate.vcxproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>

<PropertyGroup Label="Globals">
<ProjectGuid>{2B6A9A3B-0C5E-4E6E-9E31-3E8F5A2D1C03}</ProjectGuid>
<RootNamespace>MapWinGISTranslateSample</RootNamespace>
<ProjectName>TranslateSample</ProjectName>
<TargetName>translate</TargetName>
</PropertyGroup>

<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />

<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
</PropertyGroup>

<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />

<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>

<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>$(MwgRepoRoot)src\MapWinGIS.Core\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
</Link>
</ItemDefinitionGroup>

<ItemGroup>
<ClCompile Include="translate.cpp" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MapWinGIS.Core\MapWinGIS.Core.vcxproj">
<Project>{2B6A9A3B-0C5E-4E6E-9E31-3E8F5A2D1C01}</Project>
</ProjectReference>
</ItemGroup>

<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />

</Project>
46 changes: 46 additions & 0 deletions samples/Cpp/translate.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MPL-2.0

/**
* @file translate.cpp
* @brief Converts a raster dataset with the typed GDAL API.
*/
#include <exception>
#include <filesystem>
#include <iostream>

#include "mapwingis/gdal/GdalAlgorithmRunner.h"
#include "mapwingis/gdal/GdalEnvironment.h"
#include "mapwingis/gdal/GdalTypedOptions.h"

int wmain(const int argc, wchar_t* argv[])
{
if (argc != 3)
{
std::wcerr << L"Usage: translate <input-raster> <output-raster>\n";
return 2;
}

try
{
mwg::GdalEnvironment::Initialize();

mwg::RasterConvertOptions options;
options.input = std::filesystem::path(argv[1]);
options.output = std::filesystem::path(argv[2]);
options.outputFormat = "GTiff";

mwg::GdalAlgorithmRunner runner("raster convert");
if (!mwg::ConfigureGdalAlgorithm(runner, options.ToArgs()) || !runner.Run())
{
std::cerr << runner.Result().DetailedErrorMsg() << '\n';
return 1;
}

return 0;
}
catch (const std::exception& error)
{
std::cerr << error.what() << '\n';
return 1;
}
}
22 changes: 22 additions & 0 deletions tests/MapWinGIS.Core.Tests/GdalTypedOptionsTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,28 @@ TEST(GdalTypedOptions, ConvertsRasterToPngAndReturnsTheOutputDataset)
EXPECT_TRUE(std::filesystem::exists(output));
}

TEST(GdalTypedOptions, ReportsUnavailableOutputDriver)
{
GdalEnvironment::Initialize();
GdalEnvironment::QuietScope quiet;
test::TempDirectory directory;

RasterConvertOptions options;
options.input = test::MakeRaster(directory.Path());
options.output = directory.Path() / "unavailable-driver.out";
options.outputFormat = "MWG_DRIVER_NOT_INSTALLED";

GdalAlgorithmRunner runner("raster convert");
const bool configured = ConfigureGdalAlgorithm(runner, options.ToArgs());
if (configured)
EXPECT_FALSE(runner.Run());

EXPECT_FALSE(runner.Result().Succeeded());
ASSERT_FALSE(runner.Errors().empty());
EXPECT_FALSE(runner.Errors().back().message.empty());
EXPECT_FALSE(std::filesystem::exists(options.output));
}

TEST(GdalTypedOptions, ConvertsVectorLayersAndPreservesAttributes)
{
test::TempDirectory directory;
Expand Down
Loading