File: gdalalg_vector_geom.cpp

package info (click to toggle)
gdal 3.12.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 92,396 kB
  • sloc: cpp: 1,224,305; ansic: 206,456; python: 26,284; java: 6,001; xml: 4,769; sh: 3,869; cs: 2,513; yacc: 1,306; makefile: 214
file content (356 lines) | stat: -rw-r--r-- 12,163 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/******************************************************************************
 *
 * Project:  GDAL
 * Purpose:  "geom" step of "vector pipeline", or "gdal vector geom" standalone
 * Author:   Even Rouault <even dot rouault at spatialys.com>
 *
 ******************************************************************************
 * Copyright (c) 2025, Even Rouault <even dot rouault at spatialys.com>
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "gdalalg_vector_geom.h"
#include "gdalalg_vector_set_geom_type.h"
#include "gdalalg_vector_explode_collections.h"
#include "gdalalg_vector_make_valid.h"
#include "gdalalg_vector_segmentize.h"
#include "gdalalg_vector_simplify.h"
#include "gdalalg_vector_buffer.h"
#include "gdalalg_vector_swap_xy.h"

#include <cinttypes>

//! @cond Doxygen_Suppress

#ifndef _
#define _(x) (x)
#endif

/************************************************************************/
/*           GDALVectorGeomAlgorithm::GDALVectorGeomAlgorithm()         */
/************************************************************************/

GDALVectorGeomAlgorithm::GDALVectorGeomAlgorithm(bool standaloneStep)
    : GDALVectorPipelineStepAlgorithm(NAME, DESCRIPTION, HELP_URL,
                                      /* standaloneStep = */ false)
{
    m_hidden = true;

    RegisterSubAlgorithm<GDALVectorSetGeomTypeAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorExplodeCollectionsAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorMakeValidAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorSegmentizeAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorSimplifyAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorBufferAlgorithm>(standaloneStep);
    RegisterSubAlgorithm<GDALVectorSwapXYAlgorithm>(standaloneStep);
}

/************************************************************************/
/*              GDALVectorGeomAlgorithm::WarnIfDeprecated()             */
/************************************************************************/

void GDALVectorGeomAlgorithm::WarnIfDeprecated()
{
    ReportError(CE_Warning, CPLE_AppDefined,
                "'gdal vector geom' is deprecated in GDAL 3.12, and will be "
                "removed in GDAL 3.13. Is subcommands are directly available "
                "under 'gdal vector'");
}

/************************************************************************/
/*                GDALVectorGeomAlgorithm::RunStep()                    */
/************************************************************************/

bool GDALVectorGeomAlgorithm::RunStep(GDALPipelineStepRunContext &)
{
    CPLError(CE_Failure, CPLE_AppDefined,
             "The Run() method should not be called directly on the \"gdal "
             "vector geom\" program.");
    return false;
}

/************************************************************************/
/*                 GDALVectorGeomAbstractAlgorithm()                    */
/************************************************************************/

GDALVectorGeomAbstractAlgorithm::GDALVectorGeomAbstractAlgorithm(
    const std::string &name, const std::string &description,
    const std::string &helpURL, bool standaloneStep, OptionsBase &opts)
    : GDALVectorPipelineStepAlgorithm(name, description, helpURL,
                                      standaloneStep),
      m_activeLayer(opts.m_activeLayer)
{
    AddActiveLayerArg(&opts.m_activeLayer);
    AddArg("active-geometry", 0,
           _("Geometry field name to which to restrict the processing (if not "
             "specified, all)"),
           &opts.m_geomField);
}

/************************************************************************/
/*               GDALVectorGeomAbstractAlgorithm::RunStep()             */
/************************************************************************/

bool GDALVectorGeomAbstractAlgorithm::RunStep(GDALPipelineStepRunContext &)
{
    auto poSrcDS = m_inputDataset[0].GetDatasetRef();
    CPLAssert(poSrcDS);
    CPLAssert(m_outputDataset.GetName().empty());
    CPLAssert(!m_outputDataset.GetDatasetRef());

    auto outDS = std::make_unique<GDALVectorPipelineOutputDataset>(*poSrcDS);

    for (auto &&poSrcLayer : poSrcDS->GetLayers())
    {
        if (m_activeLayer.empty() ||
            m_activeLayer == poSrcLayer->GetDescription())
        {
            outDS->AddLayer(*poSrcLayer, CreateAlgLayer(*poSrcLayer));
        }
        else
        {
            outDS->AddLayer(
                *poSrcLayer,
                std::make_unique<GDALVectorPipelinePassthroughLayer>(
                    *poSrcLayer));
        }
    }

    m_outputDataset.Set(std::move(outDS));

    return true;
}

GDALVectorGeomAlgorithmStandalone::~GDALVectorGeomAlgorithmStandalone() =
    default;

#ifdef HAVE_GEOS

/************************************************************************/
/*                    GDALGeosNonStreamingAlgorithmDataset              */
/************************************************************************/

GDALGeosNonStreamingAlgorithmDataset::GDALGeosNonStreamingAlgorithmDataset()
    : m_poGeosContext{OGRGeometry::createGEOSContext()}
{
}

GDALGeosNonStreamingAlgorithmDataset::~GDALGeosNonStreamingAlgorithmDataset()
{
    Cleanup();
    if (m_poGeosContext != nullptr)
    {
        finishGEOS_r(m_poGeosContext);
    }
}

void GDALGeosNonStreamingAlgorithmDataset::Cleanup()
{
    m_apoFeatures.clear();

    if (m_poGeosContext != nullptr)
    {
        for (auto &poGeom : m_apoGeosInputs)
        {
            GEOSGeom_destroy_r(m_poGeosContext, poGeom);
        }
        m_apoGeosInputs.clear();

        if (m_poGeosContext != nullptr)
        {
            GEOSGeom_destroy_r(m_poGeosContext, m_poGeosResultAsCollection);
            m_poGeosResultAsCollection = nullptr;
        }

        for (size_t i = 0; i < m_nGeosResultSize; i++)
        {
            GEOSGeom_destroy_r(m_poGeosContext, m_papoGeosResults[i]);
        }
        m_nGeosResultSize = 0;

        if (m_papoGeosResults != nullptr)
        {
            GEOSFree_r(m_poGeosContext, m_papoGeosResults);
            m_papoGeosResults = nullptr;
        }
    }
}

bool GDALGeosNonStreamingAlgorithmDataset::ConvertInputsToGeos(
    OGRLayer &srcLayer, OGRLayer &dstLayer, bool sameDefn)
{
    for (auto &feature : srcLayer)
    {
        const OGRGeometry *poSrcGeom =
            feature->GetGeomFieldRef(m_sourceGeometryField);

        if (PolygonsOnly())
        {
            const auto eFGType = poSrcGeom
                                     ? wkbFlatten(poSrcGeom->getGeometryType())
                                     : wkbUnknown;
            if (eFGType != wkbPolygon && eFGType != wkbMultiPolygon &&
                eFGType != wkbCurvePolygon && eFGType != wkbMultiSurface)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Coverage checking can only be performed on "
                         "polygonal geometries. Feature %" PRId64
                         " does not have one",
                         static_cast<int64_t>(feature->GetFID()));
                return false;
            }
        }

        if (poSrcGeom)
        {
            GEOSGeometry *geosGeom =
                poSrcGeom->exportToGEOS(m_poGeosContext, false);
            if (!geosGeom)
            {
                // should not happen normally
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Geometry of feature %" PRId64
                         " failed to convert to GEOS",
                         static_cast<int64_t>(feature->GetFID()));
                return false;
            }

            m_apoGeosInputs.push_back(geosGeom);
        }
        else
        {
            m_apoGeosInputs.push_back(GEOSGeom_createEmptyCollection_r(
                m_poGeosContext, GEOS_GEOMETRYCOLLECTION));
        }

        feature->SetGeometry(nullptr);  // free some memory

        if (sameDefn)
        {
            feature->SetFDefnUnsafe(dstLayer.GetLayerDefn());
            m_apoFeatures.push_back(
                std::unique_ptr<OGRFeature>(feature.release()));
        }
        else
        {
            auto newFeature =
                std::make_unique<OGRFeature>(dstLayer.GetLayerDefn());
            newFeature->SetFrom(feature.get(), true);
            newFeature->SetFID(feature->GetFID());
            m_apoFeatures.push_back(std::move(newFeature));
        }
    }

    return true;
}

bool GDALGeosNonStreamingAlgorithmDataset::ConvertOutputsFromGeos(
    OGRLayer &dstLayer)
{
    const OGRSpatialReference *poResultSRS =
        dstLayer.GetLayerDefn()->GetGeomFieldDefn(0)->GetSpatialRef();

// GEOSGeom_releaseCollection allows us to take ownership of the contents of
// a GeometryCollection. We can then incrementally free the geometries as
// we write them to features. It requires GEOS >= 3.12.
#if GEOS_VERSION_MAJOR > 3 ||                                                  \
    (GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 12)
#define GDAL_GEOS_NON_STREAMING_ALGORITHM_DATASET_INCREMENTAL
#endif

    const auto eLayerGeomType = dstLayer.GetLayerDefn()->GetGeomType();

#ifdef GDAL_GEOS_NON_STREAMING_ALGORITHM_DATASET_INCREMENTAL
    m_nGeosResultSize =
        GEOSGetNumGeometries_r(m_poGeosContext, m_poGeosResultAsCollection);
    m_papoGeosResults = GEOSGeom_releaseCollection_r(
        m_poGeosContext, m_poGeosResultAsCollection, &m_nGeosResultSize);
    GEOSGeom_destroy_r(m_poGeosContext, m_poGeosResultAsCollection);
    m_poGeosResultAsCollection = nullptr;
    CPLAssert(m_apoFeatures.size() == m_nGeosResultSize);

    // Create features with the modified geometries
    for (size_t i = 0; i < m_apoFeatures.size(); i++)
    {
        GEOSGeometry *poGeosResult = m_papoGeosResults[i];
#else
    auto nGeoms =
        GEOSGetNumGeometries_r(m_poGeosContext, m_poGeosResultAsCollection);
    for (decltype(nGeoms) i = 0; i < nGeoms; i++)
    {
        GEOSGeometry *poGeosResult = const_cast<GEOSGeometry *>(
            GEOSGetGeometryN_r(m_poGeosContext, m_poGeosResultAsCollection, i));
#endif
        std::unique_ptr<OGRGeometry> poResultGeom;

        bool skipFeature =
            SkipEmpty() && GEOSisEmpty_r(m_poGeosContext, poGeosResult);

        if (!skipFeature)
        {
            poResultGeom.reset(OGRGeometryFactory::createFromGEOS(
                m_poGeosContext, poGeosResult));

            if (poResultGeom && eLayerGeomType != wkbUnknown &&
                wkbFlatten(poResultGeom->getGeometryType()) !=
                    wkbFlatten(eLayerGeomType))
            {
                poResultGeom.reset(OGRGeometryFactory::forceTo(
                    poResultGeom.release(), eLayerGeomType));
            }

            if (poResultGeom == nullptr)
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "Failed to convert result from GEOS");
                return false;
            }
        }

#ifdef GDAL_GEOS_NON_STREAMING_ALGORITHM_DATASET_INCREMENTAL
        GEOSGeom_destroy_r(m_poGeosContext, m_papoGeosResults[i]);
        m_papoGeosResults[i] = nullptr;
#undef GDAL_GEOS_NON_STREAMING_ALGORITHM_DATASET_INCREMENTAL
#endif

        if (!skipFeature)
        {
            poResultGeom->assignSpatialReference(poResultSRS);
            m_apoFeatures[i]->SetGeometry(std::move(poResultGeom));

            if (dstLayer.CreateFeature(m_apoFeatures[i].get()) != CE_None)
            {
                return false;
            }
        }

        m_apoFeatures[i].reset();
    }

    return true;
}

bool GDALGeosNonStreamingAlgorithmDataset::Process(OGRLayer &srcLayer,
                                                   OGRLayer &dstLayer)
{
    Cleanup();

    bool sameDefn = dstLayer.GetLayerDefn()->IsSame(srcLayer.GetLayerDefn());

    if (!ConvertInputsToGeos(srcLayer, dstLayer, sameDefn))
    {
        return false;
    }

    if (!ProcessGeos() || m_poGeosResultAsCollection == nullptr)
    {
        return false;
    }

    return ConvertOutputsFromGeos(dstLayer);
}

#endif

//! @endcond