Debian Codegraph @

raster3d/r3.in.ascii/main.c

raw
1 /***************************************************************************
2 *
3 * MODULE: r3.in.ascii
4 *
5 * AUTHOR(S): Roman Waupotitsch, Michael Shapiro, Helena Mitasova,
6 * Bill Brown, Lubos Mitas, Jaro Hofierka, Soeren Gebbert
7 *
8 * PURPOSE: Convert a 3D ASCII raster text file into a (binary) 3D raster
9 * map layer
10 *
11 * COPYRIGHT: (C) 2005 by the GRASS Development Team
12 *
13 * This program is free software under the GNU General Public
14 * License (>=v2). Read the file COPYING that comes with GRASS
15 * for details.
16 *
17 *****************************************************************************/
18
19 #include <stdio.h>
20 #include <unistd.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <grass/gis.h>
24 #include <grass/raster3d.h>
25 #include <grass/glocale.h>
26
27 #define ROW_ORDER_NORTH_TO_SOUTH 1
28 #define ROW_ORDER_SOUTH_TO_NORTH 2
29 #define DEPTH_ORDER_BOTTOM_TO_TOP 3
30 #define DEPTH_ORDER_TOP_TO_BOTTOM 4
31
32 /*- prototypes --------------------------------------------------------------*/
33
34 static void fatalError(char *errorMsg); /*Simple Error message */
35
36 static void setParams(void); /*Fill the paramType structure */
37
38 /*Puts the userdefined parameters into easier handable variables */
39 static void getParams(char **input, char **output, int *convertNull,
40 char *nullValue);
41
42 /* copy content of one file into another (taken form r.in.ascii) */
43 static int file_cpy(FILE *, FILE *);
44
45 /*reads a g3d ascii-file headerfile-string */
46 static void readHeaderString(FILE *fp, char *valueString, double *value);
47
48 static FILE *openAscii(char *asciiFile,
49 RASTER3D_Region *region); /*open the g3d ascii file */
50
51 /*This function does all the work, it reads the values from the g3d ascii-file
52 and put it into an g3d-map */
53 static void asciiToG3d(FILE *fp, RASTER3D_Region *region, int convertNull,
54 char *nullValue);
55
56 /*---------------------------------------------------------------------------*/
57
58 /* global variables */
59 void *map = NULL;
60 int rowOrder;
61 int depthOrder;
62
63 /*---------------------------------------------------------------------------*/
64 void fatalError(char *errorMsg)
65 {
66 if (map != NULL) {
67 /* should unopen map here! */
68 Rast3d_close(map);
69 }
70
71 Rast3d_fatal_error("%s", errorMsg);
72 }
73
74 /*---------------------------------------------------------------------------*/
75
76 typedef struct {
77 struct Option *input, *output, *nv;
78 } paramType;
79
80 static paramType param;
81
82 static void setParams(void)
83 {
84 param.input = G_define_standard_option(G_OPT_F_INPUT);
85 param.input->required = YES;
86 param.input->label = _("Name of input file to be imported");
87 param.input->description = _("'-' for standard input");
88
89 param.output = G_define_standard_option(G_OPT_R3_OUTPUT);
90
91 param.nv = G_define_standard_option(G_OPT_M_NULL_VALUE);
92 param.nv->answer = "*";
93 param.nv->description = /* TODO: '*' or 'none' in the msg ?? */
94 _("String representing NULL value data cell (use 'none' if no such "
95 "value)");
96 }
97
98 /*---------------------------------------------------------------------------*/
99
100 void getParams(char **input, char **output, int *convertNull, char *nullValue)
101 {
102 *input = param.input->answer;
103 *output = param.output->answer;
104 *convertNull = (strcmp(param.nv->answer, "none") != 0);
105 if (*convertNull)
106 if (sscanf(param.nv->answer, "%s", nullValue) != 1)
107 fatalError("getParams: NULL-value value invalid");
108
109 G_debug(3, "getParams: input: %s, output: %s", *input, *output);
110 }
111
112 /*---------------------------------------------------------------------------*/
113
114 static int file_cpy(FILE *from, FILE *to)
115 {
116 char buf[BUFSIZ];
117 size_t size;
118 int written = 0;
119
120 while (1) {
121 size = fread(buf, 1, BUFSIZ, from);
122 if (!size) {
123 if (written) {
124 fflush(to);
125 G_fseek(to, 0L, SEEK_SET);
126 }
127 return 0;
128 }
129 if (!fwrite(buf, 1, size, to)) {
130 G_warning(_("Unable to write to file"));
131 return -1;
132 }
133 written = 1;
134 }
135 /* NOTREACHED */
136 return -1;
137 }
138
139 void readHeaderString(FILE *fp, char *valueString, double *value)
140 {
141 static char format[100];
142 char line_buff[1024];
143
144 /* to avoid buffer overflows we use G_snprintf */
145 snprintf(format, 100, "%s %%lf", valueString);
146 G_getl2(line_buff, 1024, fp);
147 if (sscanf(line_buff, format, value) != 1) {
148 /* this would be ideal to merge if Rast3d_close could be solved */
149 G_warning("Bad value for '%s': %s", valueString, line_buff);
150 fatalError("readHeaderString: header value invalid");
151 }
152 }
153
154 /*---------------------------------------------------------------------------*/
155
156 FILE *openAscii(char *asciiFile, RASTER3D_Region *region)
157 {
158 FILE *fp;
159 char *tmp_file;
160 double tmp;
161 char buff[1024];
162 char line_buff[1024];
163
164 G_debug(3, "openAscii: opens the ascii file and reads the header");
165
166 if (strcmp(asciiFile, "-") == 0) {
167 tmp_file = G_tempfile();
168 if (NULL == (fp = fopen(tmp_file, "w+")))
169 G_fatal_error(_("Unable to open temporary file <%s>"), tmp_file);
170 unlink(tmp_file);
171 if (0 > file_cpy(stdin, fp))
172 G_fatal_error(_("Unable to read input from stdin"));
173 }
174 else {
175 fp = fopen(asciiFile, "r");
176 }
177 if (fp == NULL) {
178 perror(asciiFile);
179 G_usage();
180 exit(EXIT_FAILURE);
181 }
182
183 /* Initialize the default order */
184 rowOrder = ROW_ORDER_NORTH_TO_SOUTH;
185 depthOrder = DEPTH_ORDER_BOTTOM_TO_TOP;
186
187 /* Read the first line and check for grass version */
188 G_getl2(line_buff, 1024, fp);
189
190 /* First check for new ascii format */
191 if (sscanf(line_buff, "version: %s", buff) == 1) {
192 G_message("Found version information: %s\n", buff);
193 if (G_strcasecmp(buff, "grass7") == 0) {
194
195 /* Parse the row and depth order */
196 G_getl2(line_buff, 1024, fp);
197 if (sscanf(line_buff, "order: %s", buff) != 1)
198 fatalError("Unable to parse the row and depth order");
199
200 if (G_strcasecmp(buff, "nsbt") == 0) {
201 rowOrder = ROW_ORDER_NORTH_TO_SOUTH;
202 depthOrder = DEPTH_ORDER_BOTTOM_TO_TOP;
203 G_message("Found north -> south, bottom -> top order (nsbt)");
204 }
205 if (G_strcasecmp(buff, "snbt") == 0) {
206 rowOrder = ROW_ORDER_SOUTH_TO_NORTH;
207 depthOrder = DEPTH_ORDER_BOTTOM_TO_TOP;
208 G_message("Found south -> north, bottom -> top order (snbt)");
209 }
210 if (G_strcasecmp(buff, "nstb") == 0) {
211 rowOrder = ROW_ORDER_NORTH_TO_SOUTH;
212 depthOrder = DEPTH_ORDER_TOP_TO_BOTTOM;
213 G_message("Found north -> south, top -> bottom order (nstb)");
214 }
215 if (G_strcasecmp(buff, "sntb") == 0) {
216 rowOrder = ROW_ORDER_SOUTH_TO_NORTH;
217 depthOrder = DEPTH_ORDER_TOP_TO_BOTTOM;
218 G_message("Found south -> north, top -> bottom order (sntb)");
219 }
220 }
221 else {
222 G_fatal_error(_("Unsupported GRASS version %s"), buff);
223 }
224 }
225 else {
226 /* Rewind the stream if no grass version info found */
227 rewind(fp);
228 }
229
230 Rast3d_get_window(region);
231
232 readHeaderString(fp, "north:", &(region->north));
233 readHeaderString(fp, "south:", &(region->south));
234 readHeaderString(fp, "east:", &(region->east));
235 readHeaderString(fp, "west:", &(region->west));
236 readHeaderString(fp, "top:", &(region->top));
237 readHeaderString(fp, "bottom:", &(region->bottom));
238 readHeaderString(fp, "rows:", &tmp);
239 region->rows = (int)tmp;
240 readHeaderString(fp, "cols:", &tmp);
241 region->cols = (int)tmp;
242 readHeaderString(fp, "levels:", &tmp);
243 region->depths = (int)tmp;
244
245 return fp;
246 }
247
248 /*---------------------------------------------------------------------------*/
249
250 void asciiToG3d(FILE *fp, RASTER3D_Region *region, int convertNull,
251 char *nullValue)
252 {
253 int x, y, z;
254 int col, row, depth;
255 double value;
256 char buff[256];
257 int tileX, tileY, tileZ;
258
259 Rast3d_get_tile_dimensions_map(map, &tileX, &tileY, &tileZ);
260 Rast3d_min_unlocked(map, RASTER3D_USE_CACHE_X);
261
262 Rast3d_autolock_on(map);
263 Rast3d_unlock_all(map);
264 G_message(_("Loading data ... (%dx%dx%d)"), region->cols, region->rows,
265 region->depths);
266
267 G_debug(
268 3,
269 "asciiToG3d: writing the 3D raster map, with rows %i cols %i depths %i",
270 region->rows, region->cols, region->depths);
271
272 for (z = 0; z < region->depths; z++) {
273 G_percent(z, region->depths, 1);
274
275 if ((z % tileZ) == 0)
276 Rast3d_unlock_all(map);
277
278 for (y = 0; y < region->rows; y++) /* go south to north */
279 for (x = 0; x < region->cols; x++) {
280
281 /* From west to east */
282 col = x;
283 /* The default is to read rows from north to south */
284 row = y;
285 /* From bottom to the top */
286 depth = z;
287
288 /* Read rows as from south to north */
289 if (rowOrder == ROW_ORDER_SOUTH_TO_NORTH)
290 row = region->rows - y - 1;
291
292 /* Read XY layer from top to bottom */
293 if (depthOrder == DEPTH_ORDER_TOP_TO_BOTTOM)
294 depth = region->depths - z - 1;
295
296 if (fscanf(fp, "%s", buff) != 1) {
297 if (feof(fp))
298 G_warning(
299 _("End of file reached while still loading data."));
300 G_debug(3,
301 "missing data at col=%d row=%d depth=%d "
302 "last_value=[%.4f]",
303 x + 1, y + 1, z + 1, value);
304 fatalError("asciiToG3d: read failed");
305 }
306
307 /* Check for null value */
308 if (convertNull &&
309 strncmp(buff, nullValue, strlen(nullValue)) == 0) {
310 Rast3d_set_null_value(&value, 1, DCELL_TYPE);
311 }
312 else {
313 if (sscanf(buff, "%lf", &value) != 1) {
314 G_warning(_("Invalid value detected"
315 " (at col=%d row=%d depth=%d): %s"),
316 x + 1, y + 1, z + 1, buff);
317 fatalError("asciiToG3d: read failed");
318 }
319 }
320 /* Write the data */
321 Rast3d_put_double(map, col, row, depth, value);
322 }
323 }
324
325 if (fscanf(fp, "%lf", &value) == 1) {
326 G_warning(_("Data exists in input file after fully importing "
327 "expected data. [%.4f ...]"),
328 value);
329 }
330
331 if (!Rast3d_flush_all_tiles(map))
332 fatalError("asciiTog3d: error flushing tiles");
333
334 Rast3d_autolock_off(map);
335 Rast3d_unlock_all(map);
336
337 G_percent(1, 1, 1);
338 }
339
340 /*---------------------------------------------------------------------------*/
341
342 int main(int argc, char *argv[])
343 {
344 char *input, *output;
345 int convertNull;
346 char nullValue[256];
347 int useTypeDefault, type, useCompressionDefault, doCompression;
348 int usePrecisionDefault, precision, useDimensionDefault, tileX, tileY,
349 tileZ;
350 RASTER3D_Region region;
351 FILE *fp;
352 struct GModule *module;
353 struct History history;
354
355 map = NULL;
356
357 G_gisinit(argv[0]);
358 module = G_define_module();
359 G_add_keyword(_("raster3d"));
360 G_add_keyword(_("import"));
361 G_add_keyword(_("voxel"));
362 G_add_keyword(_("conversion"));
363 G_add_keyword("ASCII");
364 module->description = _(
365 "Converts a 3D ASCII raster text file into a (binary) 3D raster map.");
366
367 setParams();
368 Rast3d_set_standard3d_input_params();
369
370 if (G_parser(argc, argv))
371 exit(EXIT_FAILURE);
372
373 getParams(&input, &output, &convertNull, nullValue);
374 if (!Rast3d_get_standard3d_params(
375 &useTypeDefault, &type, &useCompressionDefault, &doCompression,
376 &usePrecisionDefault, &precision, &useDimensionDefault, &tileX,
377 &tileY, &tileZ))
378 fatalError("Error getting standard parameters");
379
380 Rast3d_init_defaults();
381
382 fp = openAscii(input, &region);
383
384 /*Open the new RASTER3D map */
385 map = Rast3d_open_new_param(output, RASTER3D_TILE_SAME_AS_FILE,
386 RASTER3D_USE_CACHE_XY, &region, type,
387 doCompression, precision, tileX, tileY, tileZ);
388
389 if (map == NULL)
390 fatalError(_("Unable to open 3D raster map"));
391
392 /*Create the new RASTER3D Map */
393 asciiToG3d(fp, &region, convertNull, nullValue);
394
395 if (!Rast3d_close(map))
396 fatalError(_("Unable to close 3D raster map"));
397
398 /* write input name to map history */
399 Rast3d_read_history(output, G_mapset(), &history);
400 Rast_command_history(&history);
401 Rast_set_history(&history, HIST_DATSRC_1, input);
402 Rast3d_write_history(output, &history);
403
404 map = NULL;
405 if (fclose(fp))
406 fatalError(_("Unable to close ASCII file"));
407
408 return EXIT_SUCCESS;
409 }