File: rt_gdal.c

package info (click to toggle)
postgis 3.5.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 70,052 kB
  • sloc: ansic: 162,204; sql: 93,950; xml: 53,121; cpp: 12,646; perl: 5,658; sh: 5,369; makefile: 3,434; python: 1,205; yacc: 447; lex: 151; pascal: 58
file content (305 lines) | stat: -rw-r--r-- 9,618 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
/*
 *
 * WKTRaster - Raster Types for PostGIS
 * http://trac.osgeo.org/postgis/wiki/WKTRaster
 *
 * Copyright (C) 2021 Paul Ramsey <pramsey@cleverelephant.ca>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "../../postgis_config.h"
/* #define POSTGIS_DEBUG_LEVEL 4 */

#include "librtcore.h"
#include "librtcore_internal.h"
#include "stringbuffer.h"

/******************************************************************************
* rt_raster_gdal_contour()
******************************************************************************/

typedef struct
{
	struct {
		GDALDatasetH ds;
		GDALDriverH drv;
		int destroy_drv;
	} src;

	struct {
		OGRSFDriverH drv;
		OGRDataSourceH ds;
		OGRLayerH lyr;
		int srid;
		OGRwkbGeometryType gtype;
	} dst;

} _rti_contour_arg;


/* ---------------------------------------------------------------- */
/*  GDAL progress callback for interrupt handling */
/* ---------------------------------------------------------------- */

int rt_util_gdal_progress_func(
	double dfComplete,
	const char *pszMessage,
	void *pProgressArg)
{
	(void)dfComplete;
	(void)pszMessage;

	if (_lwgeom_interrupt_requested)
	{
		// rtwarn("%s interrupted at %g", (const char*)pProgressArg, dfComplete);
		_lwgeom_interrupt_requested = 0;
		return FALSE;
	}
	else
		return TRUE;
}

static void
_rti_contour_arg_init(_rti_contour_arg* arg)
{
	memset(arg, 0, sizeof(_rti_contour_arg));
	return;
}


static int
_rti_contour_arg_destroy(_rti_contour_arg* arg)
{
	if(arg->src.ds != NULL)
		GDALClose(arg->src.ds);

	if (arg->src.drv != NULL && arg->src.destroy_drv) {
		GDALDeregisterDriver(arg->src.drv);
		GDALDestroyDriver(arg->src.drv);
	}

	if (arg->dst.ds != NULL)
		OGR_DS_Destroy(arg->dst.ds);

	return FALSE;
}



/**
 * Return palloc'ed list of contours.
 * @param src_raster : raster to generate contour from
 * @param src_band : band to use as input
 * @param src_srid : srid of raster
 * @param src_srs : Coordinate reference system string for raster
 * @param options : CSList of OPTION=VALUE strings for the
 *   contour routine, see https://gdal.org/api/gdal_alg.html?highlight=contour#_CPPv419GDALContourGenerate15GDALRasterBandHddiPdidPvii16GDALProgressFuncPv
 * @param ncontours : Output parameter for length of contour list
 * @param contours : Output palloc'ed list of contours, caller to free
 */
int rt_raster_gdal_contour(
	/* input parameters */
	rt_raster src_raster,
	int src_band,
	int src_srid,
	const char* src_srs,
	double contour_interval,
	double contour_base,
	int fixed_level_count,
	double *fixed_levels,
	int polygonize,
	/* output parameters */
	size_t *ncontours,
	struct rt_contour_t **contours
	)
{
	CPLErr cplerr;
	OGRErr ogrerr;
	GDALRasterBandH hBand;
	int nfeatures = 0, i = 0;
	OGRFeatureH hFeat;

	/* For building out options list */
	stringbuffer_t sb;
	char **papszOptList = NULL;
	const char* elev_field = polygonize ? "ELEV_FIELD_MIN" : "ELEV_FIELD";

	_rti_contour_arg arg;
	_rti_contour_arg_init(&arg);

	/* Load raster into GDAL memory */
	arg.src.ds = rt_raster_to_gdal_mem(src_raster, src_srs, NULL, NULL, 0, &(arg.src.drv), &(arg.src.destroy_drv));
	/* Extract the desired band */
	hBand = GDALGetRasterBand(arg.src.ds, src_band);

	/* Set up the OGR destination data store */
	arg.dst.srid = src_srid;
	arg.dst.drv = OGRGetDriverByName("Memory");
	if (!arg.dst.drv)
		return _rti_contour_arg_destroy(&arg);

	arg.dst.ds = OGR_Dr_CreateDataSource(arg.dst.drv, "contour_ds", NULL);
	if (!arg.dst.ds)
		return _rti_contour_arg_destroy(&arg);

	/* Polygonize is 2.4+ only */
#if POSTGIS_GDAL_VERSION >= 24
	arg.dst.gtype = polygonize ? wkbPolygon : wkbLineString;
#else
	arg.dst.gtype = wkbLineString;
#endif

	/* Layer has geometry, elevation, id */
	arg.dst.lyr = OGR_DS_CreateLayer(arg.dst.ds, "contours", NULL, arg.dst.gtype, NULL);
	if (!arg.dst.lyr)
		return _rti_contour_arg_destroy(&arg);

	/* ID field */
	OGRFieldDefnH hFldId = OGR_Fld_Create("id", OFTInteger);
	ogrerr = OGR_L_CreateField(arg.dst.lyr, hFldId, TRUE);
	if (ogrerr != OGRERR_NONE)
		return _rti_contour_arg_destroy(&arg);

	/* ELEVATION field */
	OGRFieldDefnH hFldElevation = OGR_Fld_Create("elevation", OFTReal);
	ogrerr = OGR_L_CreateField(arg.dst.lyr, hFldElevation, TRUE);
	if (ogrerr != OGRERR_NONE)
		return _rti_contour_arg_destroy(&arg);

	int use_no_data = 0;
	double no_data_value = GDALGetRasterNoDataValue(hBand, &use_no_data);

	// LEVEL_INTERVAL=f
	//   The elevation interval between contours generated.
	// LEVEL_BASE=f
	//   The "base" relative to which contour intervals are applied. This is normally zero, but could be different. To generate 10m contours at 5, 15, 25, ... the LEVEL_BASE would be 5.
	// LEVEL_EXP_BASE=f
	//   If greater than 0, contour levels are generated on an exponential scale. Levels will then be generated by LEVEL_EXP_BASE^k where k is a positive integer.
	// FIXED_LEVELS=f[,f]*
	//   The list of fixed contour levels at which contours should be generated. This option has precedence on LEVEL_INTERVAL
	// NODATA=f
	//   The value to use as a "nodata" value. That is, a pixel value which should be ignored in generating contours as if the value of the pixel were not known.
	// ID_FIELD=d
	//   This will be used as a field index to indicate where a unique id should be written for each feature (contour) written.
	// ELEV_FIELD=d
	//   This will be used as a field index to indicate where the elevation value of the contour should be written. Only used in line contouring mode.
	// ELEV_FIELD_MIN=d
	//   This will be used as a field index to indicate where the minimum elevation value of the polygon contour should be written. Only used in polygonal contouring mode.
	// ELEV_FIELD_MAX=d
	//   This will be used as a field index to indicate where the maximum elevation value of the polygon contour should be written. Only used in polygonal contouring mode.
	// POLYGONIZE=YES|NO

	/* Options strings list */
	stringbuffer_init(&sb);

	if (use_no_data)
		stringbuffer_aprintf(&sb, "NODATA=%g ", no_data_value);

	if (fixed_level_count > 0) {
		int i = 0;
		stringbuffer_append(&sb, "FIXED_LEVELS=");
		for (i = 0; i < fixed_level_count; i++) {
			if (i) stringbuffer_append_char(&sb, ',');
			stringbuffer_aprintf(&sb, "%g", fixed_levels[i]);
		}
		stringbuffer_append_char(&sb, ' ');
	}
	else {
		stringbuffer_aprintf(&sb, "LEVEL_INTERVAL=%g ", contour_interval);
		stringbuffer_aprintf(&sb, "LEVEL_BASE=%g ", contour_base);
	}

	stringbuffer_aprintf(&sb, "ID_FIELD=%d ", 0);
	stringbuffer_aprintf(&sb, "%s=%d ", elev_field, 1);

	stringbuffer_aprintf(&sb, "POLYGONIZE=%s ", polygonize ? "YES" : "NO");

	papszOptList = CSLTokenizeString(stringbuffer_getstring(&sb));

	// CPLSetConfigOption("OGR_GEOMETRY_ACCEPT_UNCLOSED_RING", "NO");

	/* Run the contouring routine, filling up the OGR layer */
	cplerr = GDALContourGenerateEx(
		hBand,
		arg.dst.lyr,
		papszOptList,      // Options
		rt_util_gdal_progress_func,  // GDALProgressFunc pfnProgress
		(void*)"GDALContourGenerateEx" // void *pProgressArg
		);

	// /* Run the contouring routine, filling up the OGR layer */
	// cplerr = GDALContourGenerate(
	// 	hBand,
	// 	contour_interval, contour_base,
	// 	fixed_level_count, fixed_levels,
	// 	use_no_data, no_data_value,
	// 	arg.dst.lyr, 0, 1, // OGRLayer, idFieldNum, elevFieldNum
	// 	NULL,              // GDALProgressFunc pfnProgress
	// 	NULL               // void *pProgressArg
	// 	);

	if (cplerr >= CE_Failure) {
		return _rti_contour_arg_destroy(&arg); // FALSE
	}

	/* Convert the OGR layer into PostGIS geometries */
	nfeatures = OGR_L_GetFeatureCount(arg.dst.lyr, TRUE);
	if (nfeatures < 0)
		return _rti_contour_arg_destroy(&arg);

	*contours = rtalloc(sizeof(struct rt_contour_t) * nfeatures);
	OGR_L_ResetReading(arg.dst.lyr);
	while ((hFeat = OGR_L_GetNextFeature(arg.dst.lyr))) {
		size_t szWkb;
		unsigned char *bufWkb;
		struct rt_contour_t contour;
		OGRGeometryH hGeom;
		LWGEOM *geom;

		/* Somehow we're still iterating, should not happen. */
		if(i >= nfeatures) break;

		/* Store elevation/id */
		contour.id = OGR_F_GetFieldAsInteger(hFeat, 0);
		contour.elevation = OGR_F_GetFieldAsDouble(hFeat, 1);
		/* Convert OGR geometry to LWGEOM via WKB */
		if (!(hGeom = OGR_F_GetGeometryRef(hFeat))) continue;
		szWkb = OGR_G_WkbSize(hGeom);
		bufWkb = rtalloc(szWkb);
		if (OGR_G_ExportToWkb(hGeom, wkbNDR, bufWkb) != OGRERR_NONE) continue;
		/* Reclaim feature and associated geometry memory */
		OGR_F_Destroy(hFeat);
		geom = lwgeom_from_wkb(bufWkb, szWkb, LW_PARSER_CHECK_NONE);
		if (!geom) rterror("%s: invalid wkb", __func__);
		lwgeom_set_srid(geom, arg.dst.srid);
		contour.geom = gserialized_from_lwgeom(geom, NULL);
		lwgeom_free(geom);
		rtdealloc(bufWkb);
		(*contours)[i++] = contour;
	}

	/* Return total number of contours saved */
	*ncontours = i;

	/* Free all the non-database allocated structures */
	_rti_contour_arg_destroy(&arg);
	stringbuffer_release(&sb);

	/* Done */
	return TRUE;
}