3 // dem.c -- DEM management class
5 // Written by Curtis Olson, started March 1998.
7 // Copyright (C) 1998 Curtis L. Olson - curt@me.umn.edu
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 // (Log is kept at end of this file)
31 #include <ctype.h> // isspace()
32 #include <stdlib.h> // atoi()
33 #include <math.h> // rint()
36 #include <sys/stat.h> // stat()
39 # include <unistd.h> // stat()
43 // #include <zlib/zlib.h>
44 #include <Misc/fgstream.hxx>
45 #include <Misc/strutils.hxx>
46 #include <Include/compiler.h>
47 FG_USING_NAMESPACE(std);
50 #include "leastsqs.hxx"
52 #include <Include/fg_constants.h>
55 #define MAX_EX_NODES 10000
61 # define MKDIR(a) mkdir(a)
63 # define MKDIR(a) mkdir(a,S_IRWXU) // I am just guessing at this flag (NHV)
64 # endif // __BORLANDC__
69 fgDEM::fgDEM( void ) {
70 // printf("class fgDEM CONstructor called.\n");
71 dem_data = new float[DEM_SIZE_1][DEM_SIZE_1];
72 output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
79 // return the file path name ( foo/bar/file.ext = foo/bar )
80 static void extract_path ( const char *in, char *base) {
87 while ( (i >= 0) && (in[i] != '/') ) {
95 // Make a subdirectory
96 static int my_mkdir (const char *dir) {
100 printf ("mk_dir() ");
102 result = stat (dir, &stat_buf);
106 result = stat (dir, &stat_buf);
108 printf ("problem creating %s\n", dir);
110 printf ("%s created\n", dir);
113 printf ("%s already exists\n", dir);
124 int fgDEM::open ( const string& file ) {
125 // open input file (or read from stdin)
127 printf("Loading DEM data file: stdin\n");
129 // fd = gzdopen(STDIN_FILENO, "r");
130 printf("Not yet ported ...\n");
133 in = new fg_gzifstream( file );
135 cout << "Cannot open " << file << endl;
138 cout << "Loading DEM data file: " << file << endl;
146 int fgDEM::close () {
147 // the fg_gzifstream doesn't seem to have a close()
155 // return next token from input stream
156 string fgDEM::next_token() {
159 in->stream() >> token;
161 // cout << " returning " + token + "\n";
167 // return next integer from input stream
168 int fgDEM::next_int() {
171 in->stream() >> result;
177 // return next double from input stream
178 double fgDEM::next_double() {
181 in->stream() >> result;
187 // return next exponential num from input stream
188 double fgDEM::next_exp() {
194 token = next_token();
197 const char* p = token.c_str();
201 for ( ; *p != 0; ++p )
209 return ::atof( buf );
211 sscanf(token.c_str(), "%lfD%d", &mantissa, &exp);
213 // cout << " Mantissa = " << mantissa << " Exp = " << exp << "\n";
217 for ( i = 1; i <= exp; i++ ) {
220 } else if ( exp < 0 ) {
221 for ( i = -1; i >= exp; i-- ) {
226 return( (int)rint(mantissa * (double)acc) );
231 // read and parse DEM "A" record
232 int fgDEM::read_a_record() {
239 // get the name field (144 characters)
240 for ( i = 0; i < 144; i++ ) {
245 // clean off the trailing whitespace
247 cout << " Quad name field: " << name << endl;
249 // DEM level code, 3 reflects processing by DMA
251 cout << " DEM level code = " << inum << "\n";
257 // Pattern code, 1 indicates a regular elevation pattern
259 cout << " Pattern code = " << inum << "\n";
261 // Planimetric reference system code, 0 indicates geographic
262 // coordinate system.
264 cout << " Planimetric reference code = " << inum << "\n";
268 cout << " Zone code = " << inum << "\n";
270 // Map projection parameters (ignored)
271 for ( i = 0; i < 15; i++ ) {
273 // printf("%d: %f\n",i,dnum);
276 // Units code, 3 represents arc-seconds as the unit of measure for
277 // ground planimetric coordinates throughout the file.
280 cout << " Unknown (X,Y) units code = " << inum << "!\n";
284 // Units code; 2 represents meters as the unit of measure for
285 // elevation coordinates throughout the file.
288 cout << " Unknown (Z) units code = " << inum << "!\n";
292 // Number (n) of sides in the polygon which defines the coverage of
293 // the DEM file (usually equal to 4).
296 cout << " Unknown polygon dimension = " << inum << "!\n";
300 // Ground coordinates of bounding box in arc-seconds
301 dem_x1 = originx = next_exp();
302 dem_y1 = originy = next_exp();
303 cout << " Origin = (" << originx << "," << originy << ")\n";
314 // Minimum/maximum elevations in meters
317 cout << " Elevation range " << dem_z1 << " to " << dem_z2 << "\n";
319 // Counterclockwise angle from the primary axis of ground
320 // planimetric referenced to the primary axis of the DEM local
322 token = next_token();
324 // Accuracy code; 0 indicates that a record of accuracy does not
325 // exist and that no record type C will follow.
327 // DEM spacial resolution. Usually (3,3,1) (3,6,1) or (3,9,1)
328 // depending on latitude
330 // I will eventually have to do something with this for data at
331 // higher latitudes */
332 token = next_token();
333 cout << " accuracy & spacial resolution string = " << token << endl;
335 cout << " length = " << i << "\n";
338 inum = atoi( token.substr( 0, i - 36 ) );
339 row_step = atof( token.substr( i - 36, 12 ) );
340 col_step = atof( token.substr( i - 24, 12 ) );
341 //token.substr( 25, 12 )
343 ptr = token.c_str() + i - 12;
344 cout << " last field = " << ptr << " = " << atof(ptr) << "\n";
348 col_step = atof(ptr);
349 cout << " last field = " << ptr << " = " << col_step << "\n";
353 row_step = atof(ptr);
354 cout << " last field = " << ptr << " = " << row_step << "\n";
357 // accuracy code = atod(token)
361 cout << " Accuracy code = " << inum << "\n";
363 cout << " column step = " << col_step <<
364 " row step = " << row_step << "\n";
366 // dimension of arrays to follow (1)
367 token = next_token();
369 // number of profiles
370 dem_num_profiles = cols = next_int();
371 cout << " Expecting " << dem_num_profiles << " profiles\n";
377 // read and parse DEM "B" record
378 void fgDEM::read_b_record( ) {
382 // row / column id of this profile
383 prof_row = next_int();
384 prof_col = next_int();
385 // printf("col id = %d row id = %d\n", prof_col, prof_row);
387 // Number of columns and rows (elevations) in this profile
388 prof_num_rows = rows = next_int();
389 prof_num_cols = next_int();
390 // printf(" profile num rows = %d\n", prof_num_rows);
392 // Ground planimetric coordinates (arc-seconds) of the first
393 // elevation in the profile
394 prof_x1 = next_exp();
395 prof_y1 = next_exp();
396 // printf(" Starting at %.2f %.2f\n", prof_x1, prof_y1);
398 // Elevation of local datum for the profile. Always zero for
399 // 1-degree DEM, the reference is mean sea level.
400 token = next_token();
402 // Minimum and maximum elevations for the profile.
403 token = next_token();
404 token = next_token();
406 // One (usually) dimensional array (prof_num_cols,1) of elevations
407 for ( i = 0; i < prof_num_rows; i++ ) {
408 prof_data = next_int();
409 dem_data[cur_col][i] = (float)prof_data;
415 int fgDEM::parse( ) {
420 if ( !read_a_record() ) {
424 for ( i = 0; i < dem_num_profiles; i++ ) {
425 // printf("Ready to read next b record\n");
429 if ( cur_col % 100 == 0 ) {
430 cout << " loaded " << cur_col << " profiles of data\n";
434 cout << " Done parsing\n";
440 // return the current altitude based on mesh data. We should rewrite
441 // this to interpolate exact values, but for now this is good enough
442 double fgDEM::interpolate_altitude( double lon, double lat ) {
443 // we expect incoming (lon,lat) to be in arcsec for now
445 double xlocal, ylocal, dx, dy, zA, zB, elev;
446 int x1, x2, x3, y1, y2, y3;
450 /* determine if we are in the lower triangle or the upper triangle
458 then calculate our end points
461 xlocal = (lon - originx) / col_step;
462 ylocal = (lat - originy) / row_step;
464 xindex = (int)(xlocal);
465 yindex = (int)(ylocal);
467 // printf("xindex = %d yindex = %d\n", xindex, yindex);
469 if ( xindex + 1 == cols ) {
473 if ( yindex + 1 == rows ) {
477 if ( (xindex < 0) || (xindex + 1 >= cols) ||
478 (yindex < 0) || (yindex + 1 >= rows) ) {
482 dx = xlocal - xindex;
483 dy = ylocal - yindex;
487 // printf(" Lower triangle\n");
491 z1 = dem_data[x1][y1];
495 z2 = dem_data[x2][y2];
499 z3 = dem_data[x3][y3];
501 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
502 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
503 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
504 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
506 zA = dx * (z2 - z1) + z1;
507 zB = dx * (z3 - z1) + z1;
509 // printf(" zA = %.2f zB = %.2f\n", zA, zB);
511 if ( dx > FG_EPSILON ) {
512 elev = dy * (zB - zA) / dx + zA;
518 // printf(" Upper triangle\n");
522 z1 = dem_data[x1][y1];
526 z2 = dem_data[x2][y2];
530 z3 = dem_data[x3][y3];
532 // printf(" dx = %.2f dy = %.2f\n", dx, dy);
533 // printf(" (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
534 // printf(" (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
535 // printf(" (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
537 zA = dy * (z2 - z1) + z1;
538 zB = dy * (z3 - z1) + z1;
540 // printf(" zA = %.2f zB = %.2f\n", zA, zB );
541 // printf(" xB - xA = %.2f\n", col_step * dy / row_step);
543 if ( dy > FG_EPSILON ) {
544 elev = dx * (zB - zA) / dy + zA;
554 // Use least squares to fit a simpler data set to dem data
555 void fgDEM::fit( double error, fgBUCKET *p ) {
556 double x[DEM_SIZE_1], y[DEM_SIZE_1];
557 double m, b, ave_error, max_error;
559 int n, row, start, end;
560 int colmin, colmax, rowmin, rowmax;
562 // FILE *dem, *fit, *fit1;
564 printf("Initializing output mesh structure\n");
567 // determine dimensions
568 colmin = p->x * ( (cols - 1) / 8);
569 colmax = colmin + ( (cols - 1) / 8);
570 rowmin = p->y * ( (rows - 1) / 8);
571 rowmax = rowmin + ( (rows - 1) / 8);
572 printf("Fitting region = %d,%d to %d,%d\n", colmin, rowmin, colmax, rowmax);
574 // include the corners explicitly
575 outputmesh_set_pt(colmin, rowmin, dem_data[colmin][rowmin]);
576 outputmesh_set_pt(colmin, rowmax, dem_data[colmin][rowmax]);
577 outputmesh_set_pt(colmax, rowmax, dem_data[colmax][rowmax]);
578 outputmesh_set_pt(colmax, rowmin, dem_data[colmax][rowmin]);
580 printf("Beginning best fit procedure\n");
582 for ( row = rowmin; row <= rowmax; row++ ) {
583 // fit = fopen("fit.dat", "w");
584 // fit1 = fopen("fit1.dat", "w");
588 // printf(" fitting row = %d\n", row);
590 while ( start < colmax ) {
594 x[(end - start) - 1] = 0.0 + ( start * col_step );
595 y[(end - start) - 1] = dem_data[start][row];
597 while ( (end <= colmax) && good_fit ) {
598 n = (end - start) + 1;
599 // printf("Least square of first %d points\n", n);
600 x[end - start] = 0.0 + ( end * col_step );
601 y[end - start] = dem_data[end][row];
602 least_squares(x, y, n, &m, &b);
603 ave_error = least_squares_error(x, y, n, m, b);
604 max_error = least_squares_max_error(x, y, n, m, b);
607 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
608 start, end, ave_error, max_error, m, b);
610 f = fopen("gnuplot.dat", "w");
611 for ( j = 0; j <= end; j++) {
612 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
615 for ( j = start; j <= end; j++) {
616 fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ),
621 printf("Please hit return: "); gets(junk);
624 if ( max_error > error ) {
632 // error exceeded the threshold, back up
633 end -= 2; // back "end" up to the last good enough fit
634 n--; // back "n" up appropriately too
636 // we popped out of the above loop while still within
637 // the error threshold, so we must be at the end of
642 least_squares(x, y, n, &m, &b);
643 ave_error = least_squares_error(x, y, n, m, b);
644 max_error = least_squares_max_error(x, y, n, m, b);
648 printf("%d - %d ave error = %.2f max error = %.2f y = %.2f*x + %.2f\n",
649 start, end, ave_error, max_error, m, b);
652 fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
653 fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
656 if ( start > colmin ) {
657 // skip this for the first line segment
659 outputmesh_set_pt(start, row, (lasty + cury) / 2);
660 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
663 lasty = m * x[end-start] + b;
671 dem = fopen("gnuplot.dat", "w");
672 for ( j = 0; j < DEM_SIZE_1; j++) {
673 fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ),
679 // NOTICE, this is for testing only. This instance of
680 // output_nodes should be removed. It should be called only
681 // once at the end once all the nodes have been generated.
682 // newmesh_output_nodes(&nm, "mesh.node");
683 // printf("Please hit return: "); gets(junk);
686 // outputmesh_output_nodes(fg_root, p);
690 // Initialize output mesh structure
691 void fgDEM::outputmesh_init( void ) {
694 for ( j = 0; j < DEM_SIZE_1; j++ ) {
695 for ( i = 0; i < DEM_SIZE_1; i++ ) {
696 output_data[i][j] = -9999.0;
702 // Get the value of a mesh node
703 double fgDEM::outputmesh_get_pt( int i, int j ) {
704 return ( output_data[i][j] );
708 // Set the value of a mesh node
709 void fgDEM::outputmesh_set_pt( int i, int j, double value ) {
710 // printf("Setting data[%d][%d] = %.2f\n", i, j, value);
711 output_data[i][j] = value;
715 // Write out a node file that can be used by the "triangle" program.
716 // Check for an optional "index.node.ex" file in case there is a .poly
717 // file to go along with this node file. Include these nodes first
718 // since they are referenced by position from the .poly file.
719 void fgDEM::outputmesh_output_nodes( const string& fg_root, fgBUCKET *p ) {
720 double exnodes[MAX_EX_NODES][3];
721 struct stat stat_buf;
723 char base_path[256], file[256], exfile[256];
730 int colmin, colmax, rowmin, rowmax;
731 int i, j, count, excount, result;
733 // determine dimensions
734 colmin = p->x * ( (cols - 1) / 8);
735 colmax = colmin + ( (cols - 1) / 8);
736 rowmin = p->y * ( (rows - 1) / 8);
737 rowmax = rowmin + ( (rows - 1) / 8);
738 cout << " dumping region = " << colmin << "," << rowmin << " to " <<
739 colmax << "," << rowmax << "\n";
741 // generate the base directory
742 fgBucketGenBasePath(p, base_path);
743 cout << "fg_root = " << fg_root << " Base Path = " << base_path << endl;
744 dir = fg_root + "/Scenery/" + base_path;
745 cout << "Dir = " << dir << endl;
747 // stat() directory and create if needed
749 result = stat(dir.c_str(), &stat_buf);
750 if ( result != 0 && errno == ENOENT ) {
751 cout << "Creating directory\n";
755 command = "mkdir -p " + dir + "\n";
756 system( command.c_str() );
761 // Cygwin crashes when trying to output to node file
762 // explicitly making directory structure seems OK on Win95
764 extract_path (base_path, tmp_path);
766 dir = fg_root + "/Scenery";
767 if (my_mkdir ( dir.c_str() )) { exit (-1); }
769 dir = fg_root + "/Scenery/" + tmp_path;
770 if (my_mkdir ( dir.c_str() )) { exit (-1); }
772 dir = fg_root + "/Scenery/" + base_path;
773 if (my_mkdir ( dir.c_str() )) { exit (-1); }
779 // assume directory exists
782 // get index and generate output file name
783 index = fgBucketGenIndex(p);
784 sprintf(file, "%s/%ld.node", dir.c_str(), index);
786 // get (optional) extra node file name (in case there is matching
788 strcpy(exfile, file);
789 strcat(exfile, ".ex");
791 // load extra nodes if they exist
793 if ( (fd = fopen(exfile, "r")) != NULL ) {
795 fscanf(fd, "%d %d %d %d", &excount, &junki, &junki, &junki);
797 if ( excount > MAX_EX_NODES - 1 ) {
798 printf("Error, too many 'extra' nodes, increase array size\n");
801 printf(" Expecting %d 'extra' nodes\n", excount);
804 for ( i = 1; i <= excount; i++ ) {
805 fscanf(fd, "%d %lf %lf %lf\n", &junki,
806 &exnodes[i][0], &exnodes[i][1], &exnodes[i][2]);
807 printf("(extra) %d %.2f %.2f %.2f\n",
808 i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
813 printf("Creating node file: %s\n", file);
814 fd = fopen(file, "w");
816 // first count regular nodes to generate header
818 for ( j = rowmin; j <= rowmax; j++ ) {
819 for ( i = colmin; i <= colmax; i++ ) {
820 if ( output_data[i][j] > -9000.0 ) {
824 // printf(" count = %d\n", count);
826 fprintf(fd, "%d 2 1 0\n", count + excount);
828 // now write out extra node data
829 for ( i = 1; i <= excount; i++ ) {
830 fprintf(fd, "%d %.2f %.2f %.2f\n",
831 i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
834 // write out actual node data
836 for ( j = rowmin; j <= rowmax; j++ ) {
837 for ( i = colmin; i <= colmax; i++ ) {
838 if ( output_data[i][j] > -9000.0 ) {
839 fprintf(fd, "%d %.2f %.2f %.2f\n",
841 originx + (double)i * col_step,
842 originy + (double)j * row_step,
846 // printf(" count = %d\n", count);
853 fgDEM::~fgDEM( void ) {
854 // printf("class fgDEM DEstructor called.\n");
856 delete [] output_data;
861 // Revision 1.20 1998/10/28 19:38:20 curt
862 // Elliminate some unnecessary win32 specific stuff (by Norman Vine)
864 // Revision 1.19 1998/10/22 21:59:19 curt
865 // Fixed a couple subtle bugs that resulted from some of my c++ conversions.
866 // One bug could cause a segfault on certain input, and the other bug could
867 // cause the whole procedure to go balistic and generate huge files (also only
868 // on rare input combinations.)
870 // Revision 1.18 1998/10/18 01:17:09 curt
873 // Revision 1.17 1998/10/16 19:08:12 curt
874 // Portability updates from Bernie Bright.
876 // Revision 1.16 1998/10/02 21:41:39 curt
879 // Revision 1.15 1998/09/21 20:53:59 curt
880 // minor tweaks to clean a few additional things up after the rewrite.
882 // Revision 1.14 1998/09/19 17:59:45 curt
883 // Use c++ streams (fg_gzifstream). Also converted many character arrays to
886 // Revision 1.13 1998/09/09 16:24:04 curt
887 // Fixed a bug in the handling of exclude files which was causing
888 // a crash by calling fclose() on an invalid file handle.
890 // Revision 1.12 1998/08/24 20:03:31 curt
891 // Eliminated a possible memory overrun error.
892 // Use the proper free() rather than the incorrect delete().
894 // Revision 1.11 1998/07/20 12:46:11 curt
895 // When outputing to a .node file, first check for an optional
896 // "index.node.ex" file in case there is a .poly file to go along with this
897 // node file. Include these nodes first since they are referenced by position
898 // from the .poly file. This is my first pass at adding an area "cutout"
899 // feature to the terrain generation pipeline.
901 // Revision 1.10 1998/07/13 20:58:02 curt
904 // Revision 1.9 1998/07/13 15:29:49 curt
905 // Added #ifdef HAVE_CONFIG_H
907 // Revision 1.8 1998/07/04 00:47:18 curt
908 // typedef'd struct fgBUCKET.
910 // Revision 1.7 1998/06/05 18:14:39 curt
911 // Abort out early when reading the "A" record if it doesn't look like
912 // a proper DEM file.
914 // Revision 1.6 1998/05/02 01:49:21 curt
915 // Fixed a bug where the wrong variable was being initialized.
917 // Revision 1.5 1998/04/25 15:00:32 curt
918 // Changed "r" to "rb" in gzopen() options. This fixes bad behavior in win32.
920 // Revision 1.4 1998/04/22 13:14:46 curt
921 // Fixed a bug in zlib usage.
923 // Revision 1.3 1998/04/18 03:53:05 curt
924 // Added zlib support.
926 // Revision 1.2 1998/04/14 02:43:27 curt
927 // Used "new" to auto-allocate large DEM parsing arrays in class constructor.
929 // Revision 1.1 1998/04/08 22:57:22 curt
930 // Adopted Gnu automake/autoconf system.
932 // Revision 1.3 1998/04/06 21:09:41 curt
933 // Additional win32 support.
934 // Fixed a bad bug in dem file parsing that was causing the output to be
935 // flipped about x = y.
937 // Revision 1.2 1998/03/23 20:35:41 curt
938 // Updated to use FG_EPSILON
940 // Revision 1.1 1998/03/19 02:54:47 curt
941 // Reorganized into a class lib called fgDEM.
943 // Revision 1.1 1998/03/19 01:46:28 curt