-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathgdal_rasterize_lib.cpp
1568 lines (1383 loc) · 56.8 KB
/
gdal_rasterize_lib.cpp
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
*
* Project: GDAL Utilities
* Purpose: Rasterize OGR shapes into a GDAL raster.
* Author: Frank Warmerdam <warmerdam@pobox.com>
*
******************************************************************************
* Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
* Copyright (c) 2008-2015, Even Rouault <even dot rouault at spatialys dot com>
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "gdal_utils.h"
#include "gdal_utils_priv.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include "commonutils.h"
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_progress.h"
#include "cpl_string.h"
#include "gdal.h"
#include "gdal_alg.h"
#include "gdal_priv.h"
#include "ogr_api.h"
#include "ogr_core.h"
#include "ogr_srs_api.h"
#include "gdalargumentparser.h"
/************************************************************************/
/* GDALRasterizeOptions() */
/************************************************************************/
struct GDALRasterizeOptions
{
std::vector<int> anBandList{};
std::vector<double> adfBurnValues{};
bool bInverse = false;
std::string osFormat{};
bool b3D = false;
GDALProgressFunc pfnProgress = GDALDummyProgress;
void *pProgressData = nullptr;
std::vector<std::string> aosLayers{};
std::string osSQL{};
std::string osDialect{};
std::string osBurnAttribute{};
std::string osWHERE{};
CPLStringList aosRasterizeOptions{};
CPLStringList aosTO{};
double dfXRes = 0;
double dfYRes = 0;
CPLStringList aosCreationOptions{};
GDALDataType eOutputType = GDT_Unknown;
std::vector<double> adfInitVals{};
std::string osNoData{};
OGREnvelope sEnvelop{};
int nXSize = 0;
int nYSize = 0;
OGRSpatialReference oOutputSRS{};
bool bTargetAlignedPixels = false;
bool bCreateOutput = false;
};
/************************************************************************/
/* GDALRasterizeOptionsGetParser() */
/************************************************************************/
static std::unique_ptr<GDALArgumentParser>
GDALRasterizeOptionsGetParser(GDALRasterizeOptions *psOptions,
GDALRasterizeOptionsForBinary *psOptionsForBinary)
{
auto argParser = std::make_unique<GDALArgumentParser>(
"gdal_rasterize", /* bForBinary=*/psOptionsForBinary != nullptr);
argParser->add_description(_("Burns vector geometries into a raster."));
argParser->add_epilog(
_("This program burns vector geometries (points, lines, and polygons) "
"into the raster band(s) of a raster image."));
// Dealt manually as argparse::nargs_pattern::at_least_one is problematic
argParser->add_argument("-b")
.metavar("<band>")
.append()
.scan<'i', int>()
//.nargs(argparse::nargs_pattern::at_least_one)
.help(_("The band(s) to burn values into."));
argParser->add_argument("-i")
.flag()
.store_into(psOptions->bInverse)
.help(_("Invert rasterization."));
argParser->add_argument("-at")
.flag()
.action(
[psOptions](const std::string &) {
psOptions->aosRasterizeOptions.SetNameValue("ALL_TOUCHED",
"TRUE");
})
.help(_("Enables the ALL_TOUCHED rasterization option."));
// Mutually exclusive options: -burn, -3d, -a
{
// Required if options for binary
auto &group = argParser->add_mutually_exclusive_group(
psOptionsForBinary != nullptr);
// Dealt manually as argparse::nargs_pattern::at_least_one is problematic
group.add_argument("-burn")
.metavar("<value>")
.scan<'g', double>()
.append()
//.nargs(argparse::nargs_pattern::at_least_one)
.help(_("A fixed value to burn into the raster band(s)."));
group.add_argument("-a")
.metavar("<attribute_name>")
.store_into(psOptions->osBurnAttribute)
.help(_("Name of the field in the input layer to get the burn "
"values from."));
group.add_argument("-3d")
.flag()
.store_into(psOptions->b3D)
.action(
[psOptions](const std::string &) {
psOptions->aosRasterizeOptions.SetNameValue(
"BURN_VALUE_FROM", "Z");
})
.help(_("Indicates that a burn value should be extracted from the "
"\"Z\" values of the feature."));
}
argParser->add_argument("-add")
.flag()
.action(
[psOptions](const std::string &) {
psOptions->aosRasterizeOptions.SetNameValue("MERGE_ALG", "ADD");
})
.help(_("Instead of burning a new value, this adds the new value to "
"the existing raster."));
// Undocumented
argParser->add_argument("-chunkysize")
.flag()
.hidden()
.action(
[psOptions](const std::string &s) {
psOptions->aosRasterizeOptions.SetNameValue("CHUNKYSIZE",
s.c_str());
});
// Mutually exclusive -l, -sql
{
auto &group = argParser->add_mutually_exclusive_group(false);
group.add_argument("-l")
.metavar("<layer_name>")
.append()
.store_into(psOptions->aosLayers)
.help(_("Name of the layer(s) to process."));
group.add_argument("-sql")
.metavar("<sql_statement>")
.store_into(psOptions->osSQL)
.action(
[psOptions](const std::string &sql)
{
GByte *pabyRet = nullptr;
if (!sql.empty() && sql.at(0) == '@' &&
VSIIngestFile(nullptr, sql.substr(1).c_str(), &pabyRet,
nullptr, 1024 * 1024))
{
GDALRemoveBOM(pabyRet);
char *pszSQLStatement =
reinterpret_cast<char *>(pabyRet);
psOptions->osSQL = CPLStrdup(
CPLRemoveSQLComments(pszSQLStatement).c_str());
VSIFree(pszSQLStatement);
}
})
.help(
_("An SQL statement to be evaluated against the datasource to "
"produce a virtual layer of features to be burned in."));
}
argParser->add_argument("-where")
.metavar("<expression>")
.store_into(psOptions->osWHERE)
.help(_("An optional SQL WHERE style query expression to be applied to "
"select features "
"to burn in from the input layer(s)."));
argParser->add_argument("-dialect")
.metavar("<sql_dialect>")
.store_into(psOptions->osDialect)
.help(_("The SQL dialect to use for the SQL expression."));
// Store later
argParser->add_argument("-a_nodata")
.metavar("<value>")
.help(_("Assign a specified nodata value to output bands."));
// Dealt manually as argparse::nargs_pattern::at_least_one is problematic
argParser->add_argument("-init")
.metavar("<value>")
.append()
//.nargs(argparse::nargs_pattern::at_least_one)
.scan<'g', double>()
.help(_("Initialize the output bands to the specified value."));
argParser->add_argument("-a_srs")
.metavar("<srs_def>")
.action(
[psOptions](const std::string &osOutputSRSDef)
{
if (psOptions->oOutputSRS.SetFromUserInput(
osOutputSRSDef.c_str()) != OGRERR_NONE)
{
throw std::invalid_argument(
std::string("Failed to process SRS definition: ")
.append(osOutputSRSDef));
}
psOptions->bCreateOutput = true;
})
.help(_("The spatial reference system to use for the output raster."));
argParser->add_argument("-to")
.metavar("<NAME>=<VALUE>")
.append()
.action([psOptions](const std::string &s)
{ psOptions->aosTO.AddString(s.c_str()); })
.help(_("Set a transformer option."));
// Store later
argParser->add_argument("-te")
.metavar("<xmin> <ymin> <xmax> <ymax>")
.nargs(4)
.scan<'g', double>()
.help(_("Set georeferenced extents of output file to be created."));
// Mutex with tr
{
auto &group = argParser->add_mutually_exclusive_group(false);
// Store later
group.add_argument("-tr")
.metavar("<xres> <yres>")
.nargs(2)
.scan<'g', double>()
.help(
_("Set output file resolution in target georeferenced units."));
// Store later
// Note: this is supposed to be int but for backward compatibility, we
// use double
auto &arg = group.add_argument("-ts")
.metavar("<width> <height>")
.nargs(2)
.scan<'g', double>()
.help(_("Set output file size in pixels and lines."));
argParser->add_hidden_alias_for(arg, "-outsize");
}
argParser->add_argument("-tap")
.flag()
.store_into(psOptions->bTargetAlignedPixels)
.action([psOptions](const std::string &)
{ psOptions->bCreateOutput = true; })
.help(_("Align the coordinates of the extent to the values of the "
"output raster."));
argParser->add_argument("-optim")
.metavar("AUTO|VECTOR|RASTER")
.action(
[psOptions](const std::string &s) {
psOptions->aosRasterizeOptions.SetNameValue("OPTIM", s.c_str());
})
.help(_("Force the algorithm used."));
argParser->add_creation_options_argument(psOptions->aosCreationOptions)
.action([psOptions](const std::string &)
{ psOptions->bCreateOutput = true; });
argParser->add_output_type_argument(psOptions->eOutputType)
.action([psOptions](const std::string &)
{ psOptions->bCreateOutput = true; });
argParser->add_output_format_argument(psOptions->osFormat)
.action([psOptions](const std::string &)
{ psOptions->bCreateOutput = true; });
// Written that way so that in library mode, users can still use the -q
// switch, even if it has no effect
argParser->add_quiet_argument(
psOptionsForBinary ? &(psOptionsForBinary->bQuiet) : nullptr);
if (psOptionsForBinary)
{
argParser->add_open_options_argument(
psOptionsForBinary->aosOpenOptions);
argParser->add_argument("src_datasource")
.metavar("<src_datasource>")
.store_into(psOptionsForBinary->osSource)
.help(_("Any vector supported readable datasource."));
argParser->add_argument("dst_filename")
.metavar("<dst_filename>")
.store_into(psOptionsForBinary->osDest)
.help(_("The GDAL raster supported output file."));
}
return argParser;
}
/************************************************************************/
/* GDALRasterizeAppGetParserUsage() */
/************************************************************************/
std::string GDALRasterizeAppGetParserUsage()
{
try
{
GDALRasterizeOptions sOptions;
GDALRasterizeOptionsForBinary sOptionsForBinary;
auto argParser =
GDALRasterizeOptionsGetParser(&sOptions, &sOptionsForBinary);
return argParser->usage();
}
catch (const std::exception &err)
{
CPLError(CE_Failure, CPLE_AppDefined, "Unexpected exception: %s",
err.what());
return std::string();
}
}
/************************************************************************/
/* InvertGeometries() */
/************************************************************************/
static void InvertGeometries(GDALDatasetH hDstDS,
std::vector<OGRGeometryH> &ahGeometries)
{
OGRMultiPolygon *poInvertMP = new OGRMultiPolygon();
/* -------------------------------------------------------------------- */
/* Create a ring that is a bit outside the raster dataset. */
/* -------------------------------------------------------------------- */
const int brx = GDALGetRasterXSize(hDstDS) + 2;
const int bry = GDALGetRasterYSize(hDstDS) + 2;
double adfGeoTransform[6] = {};
GDALGetGeoTransform(hDstDS, adfGeoTransform);
auto poUniverseRing = std::make_unique<OGRLinearRing>();
poUniverseRing->addPoint(
adfGeoTransform[0] + -2 * adfGeoTransform[1] + -2 * adfGeoTransform[2],
adfGeoTransform[3] + -2 * adfGeoTransform[4] + -2 * adfGeoTransform[5]);
poUniverseRing->addPoint(adfGeoTransform[0] + brx * adfGeoTransform[1] +
-2 * adfGeoTransform[2],
adfGeoTransform[3] + brx * adfGeoTransform[4] +
-2 * adfGeoTransform[5]);
poUniverseRing->addPoint(adfGeoTransform[0] + brx * adfGeoTransform[1] +
bry * adfGeoTransform[2],
adfGeoTransform[3] + brx * adfGeoTransform[4] +
bry * adfGeoTransform[5]);
poUniverseRing->addPoint(adfGeoTransform[0] + -2 * adfGeoTransform[1] +
bry * adfGeoTransform[2],
adfGeoTransform[3] + -2 * adfGeoTransform[4] +
bry * adfGeoTransform[5]);
poUniverseRing->addPoint(
adfGeoTransform[0] + -2 * adfGeoTransform[1] + -2 * adfGeoTransform[2],
adfGeoTransform[3] + -2 * adfGeoTransform[4] + -2 * adfGeoTransform[5]);
auto poUniversePoly = std::make_unique<OGRPolygon>();
poUniversePoly->addRing(std::move(poUniverseRing));
poInvertMP->addGeometry(std::move(poUniversePoly));
bool bFoundNonPoly = false;
// If we have GEOS, use it to "subtract" each polygon from the universe
// multipolygon
if (OGRGeometryFactory::haveGEOS())
{
OGRGeometry *poInvertMPAsGeom = poInvertMP;
poInvertMP = nullptr;
CPL_IGNORE_RET_VAL(poInvertMP);
for (unsigned int iGeom = 0; iGeom < ahGeometries.size(); iGeom++)
{
auto poGeom = OGRGeometry::FromHandle(ahGeometries[iGeom]);
const auto eGType = OGR_GT_Flatten(poGeom->getGeometryType());
if (eGType != wkbPolygon && eGType != wkbMultiPolygon)
{
if (!bFoundNonPoly)
{
bFoundNonPoly = true;
CPLError(CE_Warning, CPLE_AppDefined,
"Ignoring non-polygon geometries in -i mode");
}
}
else
{
auto poNewGeom = poInvertMPAsGeom->Difference(poGeom);
if (poNewGeom)
{
delete poInvertMPAsGeom;
poInvertMPAsGeom = poNewGeom;
}
}
delete poGeom;
}
ahGeometries.resize(1);
ahGeometries[0] = OGRGeometry::ToHandle(poInvertMPAsGeom);
return;
}
OGRPolygon &hUniversePoly =
*poInvertMP->getGeometryRef(poInvertMP->getNumGeometries() - 1);
/* -------------------------------------------------------------------- */
/* If we don't have GEOS, add outer rings of polygons as inner */
/* rings of poUniversePoly and inner rings as sub-polygons. Note */
/* that this only works properly if the polygons are disjoint, in */
/* the sense that the outer ring of any polygon is not inside the */
/* outer ring of another one. So the scenario of */
/* https://github.com/OSGeo/gdal/issues/8689 with an "island" in */
/* the middle of a hole will not work properly. */
/* -------------------------------------------------------------------- */
for (unsigned int iGeom = 0; iGeom < ahGeometries.size(); iGeom++)
{
const auto eGType =
OGR_GT_Flatten(OGR_G_GetGeometryType(ahGeometries[iGeom]));
if (eGType != wkbPolygon && eGType != wkbMultiPolygon)
{
if (!bFoundNonPoly)
{
bFoundNonPoly = true;
CPLError(CE_Warning, CPLE_AppDefined,
"Ignoring non-polygon geometries in -i mode");
}
OGR_G_DestroyGeometry(ahGeometries[iGeom]);
continue;
}
const auto ProcessPoly =
[&hUniversePoly, poInvertMP](OGRPolygon *poPoly)
{
for (int i = poPoly->getNumInteriorRings() - 1; i >= 0; --i)
{
auto poNewPoly = std::make_unique<OGRPolygon>();
std::unique_ptr<OGRLinearRing> poRing(
poPoly->stealInteriorRing(i));
poNewPoly->addRing(std::move(poRing));
poInvertMP->addGeometry(std::move(poNewPoly));
}
std::unique_ptr<OGRLinearRing> poShell(poPoly->stealExteriorRing());
hUniversePoly.addRing(std::move(poShell));
};
if (eGType == wkbPolygon)
{
auto poPoly =
OGRGeometry::FromHandle(ahGeometries[iGeom])->toPolygon();
ProcessPoly(poPoly);
delete poPoly;
}
else
{
auto poMulti =
OGRGeometry::FromHandle(ahGeometries[iGeom])->toMultiPolygon();
for (auto *poPoly : *poMulti)
{
ProcessPoly(poPoly);
}
delete poMulti;
}
}
ahGeometries.resize(1);
ahGeometries[0] = OGRGeometry::ToHandle(poInvertMP);
}
/************************************************************************/
/* ProcessLayer() */
/* */
/* Process all the features in a layer selection, collecting */
/* geometries and burn values. */
/************************************************************************/
static CPLErr ProcessLayer(OGRLayerH hSrcLayer, bool bSRSIsSet,
GDALDatasetH hDstDS,
const std::vector<int> &anBandList,
const std::vector<double> &adfBurnValues, bool b3D,
bool bInverse, const std::string &osBurnAttribute,
CSLConstList papszRasterizeOptions,
CSLConstList papszTO, GDALProgressFunc pfnProgress,
void *pProgressData)
{
/* -------------------------------------------------------------------- */
/* Checkout that SRS are the same. */
/* If -a_srs is specified, skip the test */
/* -------------------------------------------------------------------- */
OGRCoordinateTransformationH hCT = nullptr;
if (!bSRSIsSet)
{
OGRSpatialReferenceH hDstSRS = GDALGetSpatialRef(hDstDS);
if (hDstSRS)
hDstSRS = OSRClone(hDstSRS);
else if (GDALGetMetadata(hDstDS, "RPC") != nullptr)
{
hDstSRS = OSRNewSpatialReference(nullptr);
CPL_IGNORE_RET_VAL(
OSRSetFromUserInput(hDstSRS, SRS_WKT_WGS84_LAT_LONG));
OSRSetAxisMappingStrategy(hDstSRS, OAMS_TRADITIONAL_GIS_ORDER);
}
OGRSpatialReferenceH hSrcSRS = OGR_L_GetSpatialRef(hSrcLayer);
if (hDstSRS != nullptr && hSrcSRS != nullptr)
{
if (OSRIsSame(hSrcSRS, hDstSRS) == FALSE)
{
hCT = OCTNewCoordinateTransformation(hSrcSRS, hDstSRS);
if (hCT == nullptr)
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output raster dataset and the input vector "
"layer do not have the same SRS.\n"
"And reprojection of input data did not work. "
"Results might be incorrect.");
}
}
}
else if (hDstSRS != nullptr && hSrcSRS == nullptr)
{
CPLError(CE_Warning, CPLE_AppDefined,
"The output raster dataset has a SRS, but the input "
"vector layer SRS is unknown.\n"
"Ensure input vector has the same SRS, otherwise results "
"might be incorrect.");
}
else if (hDstSRS == nullptr && hSrcSRS != nullptr)
{
CPLError(CE_Warning, CPLE_AppDefined,
"The input vector layer has a SRS, but the output raster "
"dataset SRS is unknown.\n"
"Ensure output raster dataset has the same SRS, otherwise "
"results might be incorrect.");
}
if (hDstSRS != nullptr)
{
OSRDestroySpatialReference(hDstSRS);
}
}
/* -------------------------------------------------------------------- */
/* Get field index, and check. */
/* -------------------------------------------------------------------- */
int iBurnField = -1;
bool bUseInt64 = false;
if (!osBurnAttribute.empty())
{
OGRFeatureDefnH hLayerDefn = OGR_L_GetLayerDefn(hSrcLayer);
iBurnField = OGR_FD_GetFieldIndex(hLayerDefn, osBurnAttribute.c_str());
if (iBurnField == -1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to find field %s on layer %s.",
osBurnAttribute.c_str(),
OGR_FD_GetName(OGR_L_GetLayerDefn(hSrcLayer)));
if (hCT != nullptr)
OCTDestroyCoordinateTransformation(hCT);
return CE_Failure;
}
if (OGR_Fld_GetType(OGR_FD_GetFieldDefn(hLayerDefn, iBurnField)) ==
OFTInteger64)
{
GDALRasterBandH hBand = GDALGetRasterBand(hDstDS, anBandList[0]);
if (hBand && GDALGetRasterDataType(hBand) == GDT_Int64)
{
bUseInt64 = true;
}
}
}
/* -------------------------------------------------------------------- */
/* Collect the geometries from this layer, and build list of */
/* burn values. */
/* -------------------------------------------------------------------- */
OGRFeatureH hFeat = nullptr;
std::vector<OGRGeometryH> ahGeometries;
std::vector<double> adfFullBurnValues;
std::vector<int64_t> anFullBurnValues;
OGR_L_ResetReading(hSrcLayer);
while ((hFeat = OGR_L_GetNextFeature(hSrcLayer)) != nullptr)
{
OGRGeometryH hGeom = OGR_F_StealGeometry(hFeat);
if (hGeom == nullptr)
{
OGR_F_Destroy(hFeat);
continue;
}
if (hCT != nullptr)
{
if (OGR_G_Transform(hGeom, hCT) != OGRERR_NONE)
{
OGR_F_Destroy(hFeat);
OGR_G_DestroyGeometry(hGeom);
continue;
}
}
ahGeometries.push_back(hGeom);
for (unsigned int iBand = 0; iBand < anBandList.size(); iBand++)
{
if (!adfBurnValues.empty())
adfFullBurnValues.push_back(adfBurnValues[std::min(
iBand,
static_cast<unsigned int>(adfBurnValues.size()) - 1)]);
else if (!osBurnAttribute.empty())
{
if (bUseInt64)
anFullBurnValues.push_back(
OGR_F_GetFieldAsInteger64(hFeat, iBurnField));
else
adfFullBurnValues.push_back(
OGR_F_GetFieldAsDouble(hFeat, iBurnField));
}
else if (b3D)
{
/* Points and Lines will have their "z" values collected at the
point and line levels respectively. Not implemented for
polygons */
adfFullBurnValues.push_back(0.0);
}
}
OGR_F_Destroy(hFeat);
}
if (hCT != nullptr)
OCTDestroyCoordinateTransformation(hCT);
/* -------------------------------------------------------------------- */
/* If we are in inverse mode, we add one extra ring around the */
/* whole dataset to invert the concept of insideness and then */
/* merge everything into one geometry collection. */
/* -------------------------------------------------------------------- */
if (bInverse)
{
if (ahGeometries.empty())
{
for (unsigned int iBand = 0; iBand < anBandList.size(); iBand++)
{
if (!adfBurnValues.empty())
adfFullBurnValues.push_back(adfBurnValues[std::min(
iBand,
static_cast<unsigned int>(adfBurnValues.size()) - 1)]);
else /* FIXME? Not sure what to do exactly in the else case, but
we must insert a value */
{
adfFullBurnValues.push_back(0.0);
anFullBurnValues.push_back(0);
}
}
}
InvertGeometries(hDstDS, ahGeometries);
}
/* -------------------------------------------------------------------- */
/* If we have transformer options, create the transformer here */
/* Coordinate transformation to the target SRS has already been */
/* done, so we just need to convert to target raster space. */
/* Note: this is somewhat identical to what is done in */
/* GDALRasterizeGeometries() itself, except we can pass transformer*/
/* options. */
/* -------------------------------------------------------------------- */
void *pTransformArg = nullptr;
GDALTransformerFunc pfnTransformer = nullptr;
CPLErr eErr = CE_None;
if (papszTO != nullptr)
{
GDALDataset *poDS = GDALDataset::FromHandle(hDstDS);
char **papszTransformerOptions = CSLDuplicate(papszTO);
double adfGeoTransform[6] = {0.0};
if (poDS->GetGeoTransform(adfGeoTransform) != CE_None &&
poDS->GetGCPCount() == 0 && poDS->GetMetadata("RPC") == nullptr)
{
papszTransformerOptions = CSLSetNameValue(
papszTransformerOptions, "DST_METHOD", "NO_GEOTRANSFORM");
}
pTransformArg = GDALCreateGenImgProjTransformer2(
nullptr, hDstDS, papszTransformerOptions);
CSLDestroy(papszTransformerOptions);
pfnTransformer = GDALGenImgProjTransform;
if (pTransformArg == nullptr)
{
eErr = CE_Failure;
}
}
/* -------------------------------------------------------------------- */
/* Perform the burn. */
/* -------------------------------------------------------------------- */
if (eErr == CE_None)
{
if (bUseInt64)
{
eErr = GDALRasterizeGeometriesInt64(
hDstDS, static_cast<int>(anBandList.size()), anBandList.data(),
static_cast<int>(ahGeometries.size()), ahGeometries.data(),
pfnTransformer, pTransformArg, anFullBurnValues.data(),
papszRasterizeOptions, pfnProgress, pProgressData);
}
else
{
eErr = GDALRasterizeGeometries(
hDstDS, static_cast<int>(anBandList.size()), anBandList.data(),
static_cast<int>(ahGeometries.size()), ahGeometries.data(),
pfnTransformer, pTransformArg, adfFullBurnValues.data(),
papszRasterizeOptions, pfnProgress, pProgressData);
}
}
/* -------------------------------------------------------------------- */
/* Cleanup */
/* -------------------------------------------------------------------- */
if (pTransformArg)
GDALDestroyTransformer(pTransformArg);
for (int iGeom = static_cast<int>(ahGeometries.size()) - 1; iGeom >= 0;
iGeom--)
OGR_G_DestroyGeometry(ahGeometries[iGeom]);
return eErr;
}
/************************************************************************/
/* CreateOutputDataset() */
/************************************************************************/
static GDALDatasetH CreateOutputDataset(
const std::vector<OGRLayerH> &ahLayers, OGRSpatialReferenceH hSRS,
OGREnvelope sEnvelop, GDALDriverH hDriver, const char *pszDest, int nXSize,
int nYSize, double dfXRes, double dfYRes, bool bTargetAlignedPixels,
int nBandCount, GDALDataType eOutputType, CSLConstList papszCreationOptions,
const std::vector<double> &adfInitVals, const char *pszNoData)
{
bool bFirstLayer = true;
char *pszWKT = nullptr;
const bool bBoundsSpecifiedByUser = sEnvelop.IsInit();
for (unsigned int i = 0; i < ahLayers.size(); i++)
{
OGRLayerH hLayer = ahLayers[i];
if (!bBoundsSpecifiedByUser)
{
OGREnvelope sLayerEnvelop;
if (OGR_L_GetExtent(hLayer, &sLayerEnvelop, TRUE) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot get layer extent");
return nullptr;
}
/* Voluntarily increase the extent by a half-pixel size to avoid */
/* missing points on the border */
if (!bTargetAlignedPixels && dfXRes != 0 && dfYRes != 0)
{
sLayerEnvelop.MinX -= dfXRes / 2;
sLayerEnvelop.MaxX += dfXRes / 2;
sLayerEnvelop.MinY -= dfYRes / 2;
sLayerEnvelop.MaxY += dfYRes / 2;
}
sEnvelop.Merge(sLayerEnvelop);
}
if (bFirstLayer)
{
if (hSRS == nullptr)
hSRS = OGR_L_GetSpatialRef(hLayer);
bFirstLayer = false;
}
}
if (!sEnvelop.IsInit())
{
CPLError(CE_Failure, CPLE_AppDefined, "Could not determine bounds");
return nullptr;
}
if (dfXRes == 0 && dfYRes == 0)
{
if (nXSize == 0 || nYSize == 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Size and resolutions are missing");
return nullptr;
}
dfXRes = (sEnvelop.MaxX - sEnvelop.MinX) / nXSize;
dfYRes = (sEnvelop.MaxY - sEnvelop.MinY) / nYSize;
}
else if (bTargetAlignedPixels && dfXRes != 0 && dfYRes != 0)
{
sEnvelop.MinX = floor(sEnvelop.MinX / dfXRes) * dfXRes;
sEnvelop.MaxX = ceil(sEnvelop.MaxX / dfXRes) * dfXRes;
sEnvelop.MinY = floor(sEnvelop.MinY / dfYRes) * dfYRes;
sEnvelop.MaxY = ceil(sEnvelop.MaxY / dfYRes) * dfYRes;
}
if (dfXRes == 0 || dfYRes == 0)
{
CPLError(CE_Failure, CPLE_AppDefined, "Could not determine bounds");
return nullptr;
}
double adfProjection[6] = {sEnvelop.MinX, dfXRes, 0.0,
sEnvelop.MaxY, 0.0, -dfYRes};
if (nXSize == 0 && nYSize == 0)
{
// coverity[divide_by_zero]
const double dfXSize = 0.5 + (sEnvelop.MaxX - sEnvelop.MinX) / dfXRes;
// coverity[divide_by_zero]
const double dfYSize = 0.5 + (sEnvelop.MaxY - sEnvelop.MinY) / dfYRes;
if (dfXSize > std::numeric_limits<int>::max() ||
dfXSize < std::numeric_limits<int>::min() ||
dfYSize > std::numeric_limits<int>::max() ||
dfYSize < std::numeric_limits<int>::min())
{
CPLError(CE_Failure, CPLE_AppDefined,
"Invalid computed output raster size: %f x %f", dfXSize,
dfYSize);
return nullptr;
}
nXSize = static_cast<int>(dfXSize);
nYSize = static_cast<int>(dfYSize);
}
GDALDatasetH hDstDS =
GDALCreate(hDriver, pszDest, nXSize, nYSize, nBandCount, eOutputType,
papszCreationOptions);
if (hDstDS == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot create %s", pszDest);
return nullptr;
}
GDALSetGeoTransform(hDstDS, adfProjection);
if (hSRS)
OSRExportToWkt(hSRS, &pszWKT);
if (pszWKT)
GDALSetProjection(hDstDS, pszWKT);
CPLFree(pszWKT);
/*if( nBandCount == 3 || nBandCount == 4 )
{
for( int iBand = 0; iBand < nBandCount; iBand++ )
{
GDALRasterBandH hBand = GDALGetRasterBand(hDstDS, iBand + 1);
GDALSetRasterColorInterpretation(hBand,
(GDALColorInterp)(GCI_RedBand + iBand));
}
}*/
if (pszNoData)
{
for (int iBand = 0; iBand < nBandCount; iBand++)
{
GDALRasterBandH hBand = GDALGetRasterBand(hDstDS, iBand + 1);
if (GDALGetRasterDataType(hBand) == GDT_Int64)
GDALSetRasterNoDataValueAsInt64(hBand,
CPLAtoGIntBig(pszNoData));
else
GDALSetRasterNoDataValue(hBand, CPLAtof(pszNoData));
}
}
if (!adfInitVals.empty())
{
for (int iBand = 0;
iBand < std::min(nBandCount, static_cast<int>(adfInitVals.size()));
iBand++)
{
GDALRasterBandH hBand = GDALGetRasterBand(hDstDS, iBand + 1);
GDALFillRaster(hBand, adfInitVals[iBand], 0);
}
}
return hDstDS;
}
/************************************************************************/
/* GDALRasterize() */
/************************************************************************/
/* clang-format off */
/**
* Burns vector geometries into a raster
*
* This is the equivalent of the
* <a href="/programs/gdal_rasterize.html">gdal_rasterize</a> utility.
*
* GDALRasterizeOptions* must be allocated and freed with
* GDALRasterizeOptionsNew() and GDALRasterizeOptionsFree() respectively.
* pszDest and hDstDS cannot be used at the same time.
*
* @param pszDest the destination dataset path or NULL.
* @param hDstDS the destination dataset or NULL.
* @param hSrcDataset the source dataset handle.
* @param psOptionsIn the options struct returned by GDALRasterizeOptionsNew()
* or NULL.
* @param pbUsageError pointer to an integer output variable to store if any
* usage error has occurred or NULL.
* @return the output dataset (new dataset that must be closed using
* GDALClose(), or hDstDS is not NULL) or NULL in case of error.
*
* @since GDAL 2.1
*/
/* clang-format on */
GDALDatasetH GDALRasterize(const char *pszDest, GDALDatasetH hDstDS,
GDALDatasetH hSrcDataset,
const GDALRasterizeOptions *psOptionsIn,
int *pbUsageError)
{
if (pszDest == nullptr && hDstDS == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"pszDest == NULL && hDstDS == NULL");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
if (hSrcDataset == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined, "hSrcDataset== NULL");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
if (hDstDS != nullptr && psOptionsIn && psOptionsIn->bCreateOutput)
{
CPLError(CE_Failure, CPLE_AppDefined,
"hDstDS != NULL but options that imply creating a new dataset "
"have been set.");
if (pbUsageError)
*pbUsageError = TRUE;
return nullptr;
}
std::unique_ptr<GDALRasterizeOptions, decltype(&GDALRasterizeOptionsFree)>
psOptionsToFree(nullptr, GDALRasterizeOptionsFree);
const GDALRasterizeOptions *psOptions = psOptionsIn;
if (psOptions == nullptr)
{
psOptionsToFree.reset(GDALRasterizeOptionsNew(nullptr, nullptr));
psOptions = psOptionsToFree.get();
}