File: gdalalg_vector_check_geometry.cpp

package info (click to toggle)
gdal 3.12.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 92,292 kB
  • sloc: cpp: 1,223,498; ansic: 206,434; python: 26,278; java: 6,001; xml: 4,769; sh: 3,855; cs: 2,513; yacc: 1,306; makefile: 214
file content (373 lines) | stat: -rw-r--r-- 13,373 bytes parent folder | download
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/******************************************************************************
*
 * Project:  GDAL
 * Purpose:  "gdal vector check-geometry" subcommand
 * Author:   Daniel Baston
 *
 ******************************************************************************
 * Copyright (c) 2025, ISciences LLC
 *
 * SPDX-License-Identifier: MIT
 ****************************************************************************/

#include "gdalalg_vector_check_geometry.h"

#include "cpl_error.h"
#include "gdal_priv.h"
#include "gdalalg_vector_geom.h"
#include "ogr_geometry.h"
#include "ogr_geos.h"

#include <cinttypes>

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

//! @cond Doxygen_Suppress

GDALVectorCheckGeometryAlgorithm::GDALVectorCheckGeometryAlgorithm(
    bool standaloneStep)
    : GDALVectorPipelineStepAlgorithm(NAME, DESCRIPTION, HELP_URL,
                                      standaloneStep)
{
    AddArg("include-field", 0,
           _("Fields from input layer to include in output"), &m_includeFields);

    AddArg("include-valid", 0,
           _("Include valid inputs in output, with empty geometry"),
           &m_includeValid);

    AddArg("geometry-field", 0, _("Name of geometry field to check"),
           &m_geomField);
}

#ifdef HAVE_GEOS

class GDALInvalidLocationLayer final : public GDALVectorPipelineOutputLayer
{
  private:
    static constexpr const char *ERROR_DESCRIPTION_FIELD = "error";

  public:
    GDALInvalidLocationLayer(OGRLayer &layer,
                             const std::vector<int> &srcFieldIndices,
                             bool bSingleLayerOutput, int srcGeomField,
                             bool skipValid)
        : GDALVectorPipelineOutputLayer(layer),
          m_defn(OGRFeatureDefn::CreateFeatureDefn(
              bSingleLayerOutput ? "error_location"
                                 : std::string("error_location_")
                                       .append(layer.GetDescription())
                                       .c_str())),
          m_geosContext(OGRGeometry::createGEOSContext()),
          m_srcGeomField(srcGeomField), m_skipValid(skipValid)
    {
        m_defn->Reference();

        if (!srcFieldIndices.empty())
        {
            const OGRFeatureDefn &srcDefn = *layer.GetLayerDefn();
            m_srcFieldMap.resize(srcDefn.GetFieldCount(), -1);
            int iDstField = 0;
            for (int iSrcField : srcFieldIndices)
            {
                m_defn->AddFieldDefn(srcDefn.GetFieldDefn(iSrcField));
                m_srcFieldMap[iSrcField] = iDstField++;
            }
        }

        auto poDescriptionFieldDefn =
            std::make_unique<OGRFieldDefn>(ERROR_DESCRIPTION_FIELD, OFTString);
        m_defn->AddFieldDefn(std::move(poDescriptionFieldDefn));

        m_defn->GetGeomFieldDefn(0)->SetSpatialRef(
            m_srcLayer.GetLayerDefn()
                ->GetGeomFieldDefn(m_srcGeomField)
                ->GetSpatialRef());
    }

    ~GDALInvalidLocationLayer() override;

    int TestCapability(const char *) const override
    {
        return false;
    }

    const OGRFeatureDefn *GetLayerDefn() const override
    {
        return m_defn;
    }

    std::unique_ptr<OGRFeature> CreateFeatureFromLastError() const
    {
        auto poErrorFeature = std::make_unique<OGRFeature>(m_defn);

        std::string msg = CPLGetLastErrorMsg();

        // Trim GEOS exception name
        const auto subMsgPos = msg.find(": ");
        if (subMsgPos != std::string::npos)
        {
            msg = msg.substr(subMsgPos + strlen(": "));
        }

        // Trim newline from end of GEOS exception message
        if (!msg.empty() && msg.back() == '\n')
        {
            msg.pop_back();
        }

        poErrorFeature->SetField(ERROR_DESCRIPTION_FIELD, msg.c_str());

        CPLErrorReset();

        return poErrorFeature;
    }

    void TranslateFeature(
        std::unique_ptr<OGRFeature> poSrcFeature,
        std::vector<std::unique_ptr<OGRFeature>> &apoOutputFeatures) override
    {
        const OGRGeometry *poGeom =
            poSrcFeature->GetGeomFieldRef(m_srcGeomField);
        std::unique_ptr<OGRFeature> poErrorFeature;

        if (poGeom)
        {
            if (poGeom->getDimension() < 1)
            {
                CPLErrorOnce(CE_Warning, CPLE_AppDefined,
                             "Point geometry passed to 'gdal vector "
                             "check-geometry'. Point geometries are "
                             "always valid/simple.");
            }
            else
            {
                auto eType = wkbFlatten(poGeom->getGeometryType());
                GEOSGeometry *poGeosGeom = poGeom->exportToGEOS(m_geosContext);

                if (!poGeosGeom)
                {
                    // Try to find a useful message / coordinate from
                    // GEOS exception message.
                    poErrorFeature = CreateFeatureFromLastError();

                    if (eType == wkbPolygon)
                    {
                        const OGRLinearRing *poRing =
                            poGeom->toPolygon()->getExteriorRing();
                        if (poRing != nullptr && !poRing->IsEmpty())
                        {
                            auto poPoint = std::make_unique<OGRPoint>();
                            poRing->StartPoint(poPoint.get());
                            poErrorFeature->SetGeometry(std::move(poPoint));
                        }
                        else
                        {
                            // TODO get a point from somewhere else?
                        }
                    }
                }
                else
                {
                    char *pszReason = nullptr;
                    GEOSGeometry *location = nullptr;
                    char ret = 1;
                    bool warnAboutGeosVersion = false;
                    bool checkedSimple = false;

                    if (eType == wkbPolygon || eType == wkbMultiPolygon ||
                        eType == wkbCurvePolygon || eType == wkbMultiSurface ||
                        eType == wkbGeometryCollection)
                    {
                        ret = GEOSisValidDetail_r(m_geosContext, poGeosGeom, 0,
                                                  &pszReason, &location);
                    }

                    if (eType == wkbLineString || eType == wkbMultiLineString ||
                        eType == wkbCircularString ||
                        eType == wkbCompoundCurve ||
                        (ret == 1 && eType == wkbGeometryCollection))
                    {
                        checkedSimple = true;
#if GEOS_VERSION_MAJOR > 3 ||                                                  \
    (GEOS_VERSION_MAJOR == 3 && GEOS_VERSION_MINOR >= 14)
                        ret = GEOSisSimpleDetail_r(m_geosContext, poGeosGeom, 1,
                                                   &location);
#else
                        ret = GEOSisSimple_r(m_geosContext, poGeosGeom);
                        warnAboutGeosVersion = true;
#endif
                    }

                    GEOSGeom_destroy_r(m_geosContext, poGeosGeom);
                    if (ret == 0)
                    {
                        if (warnAboutGeosVersion)
                        {
                            CPLErrorOnce(
                                CE_Warning, CPLE_AppDefined,
                                "Detected a non-simple linear geometry, but "
                                "cannot output self-intersection points "
                                "because GEOS library version is < 3.14.");
                        }

                        poErrorFeature = std::make_unique<OGRFeature>(m_defn);
                        if (pszReason == nullptr)
                        {
                            if (checkedSimple)
                            {
                                poErrorFeature->SetField(
                                    ERROR_DESCRIPTION_FIELD,
                                    "self-intersection");
                            }
                        }
                        else
                        {
                            poErrorFeature->SetField(ERROR_DESCRIPTION_FIELD,
                                                     pszReason);
                            GEOSFree_r(m_geosContext, pszReason);
                        }

                        if (location != nullptr)
                        {
                            std::unique_ptr<OGRGeometry> poErrorGeom(
                                OGRGeometryFactory::createFromGEOS(
                                    m_geosContext, location));
                            GEOSGeom_destroy_r(m_geosContext, location);

                            poErrorGeom->assignSpatialReference(
                                m_srcLayer.GetLayerDefn()
                                    ->GetGeomFieldDefn(m_srcGeomField)
                                    ->GetSpatialRef());

                            poErrorFeature->SetGeometry(std::move(poErrorGeom));
                        }
                    }
                    else if (ret == 2)
                    {
                        poErrorFeature = CreateFeatureFromLastError();
                    }
                }
            }
        }

        if (!poErrorFeature && !m_skipValid)
        {
            poErrorFeature = std::make_unique<OGRFeature>(m_defn);
            // TODO Set geometry to POINT EMPTY ?
        }

        if (poErrorFeature)
        {
            if (!m_srcFieldMap.empty())
            {
                poErrorFeature->SetFieldsFrom(
                    poSrcFeature.get(), m_srcFieldMap.data(), false, false);
            }
            poErrorFeature->SetFID(poSrcFeature->GetFID());
            apoOutputFeatures.push_back(std::move(poErrorFeature));
        }
    }

    CPL_DISALLOW_COPY_ASSIGN(GDALInvalidLocationLayer)

  private:
    std::vector<int> m_srcFieldMap{};
    OGRFeatureDefn *const m_defn;
    const GEOSContextHandle_t m_geosContext;
    const int m_srcGeomField;
    const bool m_skipValid;
};

GDALInvalidLocationLayer::~GDALInvalidLocationLayer()
{
    m_defn->Release();
    finishGEOS_r(m_geosContext);
}

#endif

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

    const bool bSingleLayerOutput = m_inputLayerNames.empty()
                                        ? poSrcDS->GetLayerCount() == 1
                                        : m_inputLayerNames.size() == 1;

    auto outDS = std::make_unique<GDALVectorPipelineOutputDataset>(*poSrcDS);
    for (auto &&poSrcLayer : poSrcDS->GetLayers())
    {
        if (m_inputLayerNames.empty() ||
            std::find(m_inputLayerNames.begin(), m_inputLayerNames.end(),
                      poSrcLayer->GetDescription()) != m_inputLayerNames.end())
        {
            const auto poSrcLayerDefn = poSrcLayer->GetLayerDefn();
            if (poSrcLayerDefn->GetGeomFieldCount() == 0)
            {
                if (m_inputLayerNames.empty())
                    continue;
                ReportError(CE_Failure, CPLE_AppDefined,
                            "Specified layer '%s' has no geometry field",
                            poSrcLayer->GetDescription());
                return false;
            }

            const int geomFieldIndex =
                m_geomField.empty()
                    ? 0
                    : poSrcLayerDefn->GetGeomFieldIndex(m_geomField.c_str());

            if (geomFieldIndex == -1)
            {
                ReportError(CE_Failure, CPLE_AppDefined,
                            "Specified geometry field '%s' does not exist in "
                            "layer '%s'",
                            m_geomField.c_str(), poSrcLayer->GetDescription());
                return false;
            }

            std::vector<int> includeFieldIndices;
            for (const auto &fieldName : m_includeFields)
            {
                auto iSrcField =
                    poSrcLayerDefn->GetFieldIndex(fieldName.c_str());
                if (iSrcField == -1)
                {
                    ReportError(
                        CE_Failure, CPLE_AppDefined,
                        "Specified field '%s' does not exist in layer '%s'",
                        fieldName.c_str(), poSrcLayer->GetDescription());
                    return false;
                }
                includeFieldIndices.push_back(iSrcField);
            }

            outDS->AddLayer(*poSrcLayer,
                            std::make_unique<GDALInvalidLocationLayer>(
                                *poSrcLayer, includeFieldIndices,
                                bSingleLayerOutput, geomFieldIndex,
                                !m_includeValid));
        }
    }

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

    return true;
#else
    ReportError(CE_Failure, CPLE_AppDefined,
                "%s requires GDAL to be built against the GEOS library.", NAME);
    return false;
#endif
}

GDALVectorCheckGeometryAlgorithmStandalone::
    ~GDALVectorCheckGeometryAlgorithmStandalone() = default;

//! @endcond