]> git.mxchange.org Git - flightgear.git/blob - DEM/dem.cxx
Changes due to updates in fgstream.
[flightgear.git] / DEM / dem.cxx
1 // -*- Mode: C++ -*-
2 //
3 // dem.c -- DEM management class
4 //
5 // Written by Curtis Olson, started March 1998.
6 //
7 // Copyright (C) 1998  Curtis L. Olson  - curt@me.umn.edu
8 //
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.
13 //
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.
18 //
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.
22 //
23 // $Id$
24 // (Log is kept at end of this file)
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include <ctype.h>    // isspace()
32 #include <stdlib.h>   // atoi()
33 #include <math.h>     // rint()
34 #include <stdio.h>
35 #include <string.h>
36 #include <sys/stat.h> // stat()
37 #include <errno.h>
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>   // stat()
40 #endif
41 #include <string>
42
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);
48
49 #include "dem.hxx"
50 #include "leastsqs.hxx"
51
52 #include <Include/fg_constants.h>
53
54
55 #define MAX_EX_NODES 10000
56
57 #if 0
58 #ifdef WIN32
59 # ifdef __BORLANDC__
60 #  include <dir.h>
61 #  define MKDIR(a) mkdir(a)
62 # else
63 #  define MKDIR(a) mkdir(a,S_IRWXU)  // I am just guessing at this flag (NHV)
64 # endif // __BORLANDC__
65 #endif // WIN32
66 #endif //0
67
68
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];
73 }
74
75
76 #if 0
77 #ifdef WIN32
78
79 // return the file path name ( foo/bar/file.ext = foo/bar )
80 static void extract_path ( const char *in, char *base) {
81     int len, i;
82     
83     len = strlen (in);
84     strcpy (base, in);
85
86     i = len - 1;
87     while ( (i >= 0) && (in[i] != '/') ) {
88         i--;
89     }
90
91     base[i] = '\0';
92 }
93
94
95 // Make a subdirectory
96 static int my_mkdir (const char *dir) {
97     struct stat stat_buf;
98     int result;
99
100     printf ("mk_dir() ");
101
102     result = stat (dir, &stat_buf);
103
104     if (result != 0) {
105         MKDIR (dir);
106         result = stat (dir, &stat_buf);
107         if (result != 0) {
108             printf ("problem creating %s\n", dir);
109         } else {
110             printf ("%s created\n", dir);
111         }
112     } else {
113         printf ("%s already exists\n", dir);
114     }
115
116     return (result);
117 }
118
119 #endif // WIN32
120 #endif //0
121
122
123 // open a DEM file
124 int fgDEM::open ( const string& file ) {
125     // open input file (or read from stdin)
126     if ( file ==  "-" ) {
127         printf("Loading DEM data file: stdin\n");
128         // fd = stdin;
129         // fd = gzdopen(STDIN_FILENO, "r");
130         printf("Not yet ported ...\n");
131         return 0;
132     } else {
133         in = new fg_gzifstream( file );
134         if ( !(*in) ) {
135             cout << "Cannot open " << file << endl;
136             return 0;
137         }
138         cout << "Loading DEM data file: " << file << endl;
139     }
140
141     return 1;
142 }
143
144
145 // close a DEM file
146 int fgDEM::close () {
147     // the fg_gzifstream doesn't seem to have a close()
148
149     delete in;
150
151     return 1;
152 }
153
154
155 // return next token from input stream
156 string fgDEM::next_token() {
157     string token;
158
159     *in >> token;
160
161     // cout << "    returning " + token + "\n";
162
163     return token;
164 }
165
166
167 // return next integer from input stream
168 int fgDEM::next_int() {
169     int result;
170     
171     *in >> result;
172
173     return result;
174 }
175
176
177 // return next double from input stream
178 double fgDEM::next_double() {
179     double result;
180
181     *in >> result;
182
183     return result;
184 }
185
186
187 // return next exponential num from input stream
188 double fgDEM::next_exp() {
189     string token;
190     double mantissa;
191     int exp, acc;
192     int i;
193
194     token = next_token();
195
196 #if 1
197     const char* p = token.c_str();
198     char buf[64];
199     char* bp = buf;
200     
201     for ( ; *p != 0; ++p )
202     {
203         if ( *p == 'D' )
204             *bp++ = 'E';
205         else
206             *bp++ = *p;
207     }
208     *bp = 0;
209     return ::atof( buf );
210 #else
211     sscanf(token.c_str(), "%lfD%d", &mantissa, &exp);
212
213     // cout << "    Mantissa = " << mantissa << "  Exp = " << exp << "\n";
214
215     acc = 1;
216     if ( exp > 0 ) {
217         for ( i = 1; i <= exp; i++ ) {
218             acc *= 10;
219         }
220     } else if ( exp < 0 ) {
221         for ( i = -1; i >= exp; i-- ) {
222             acc /= 10;
223         }
224     }
225
226     return( (int)rint(mantissa * (double)acc) );
227 #endif
228 }
229
230
231 // read and parse DEM "A" record
232 int fgDEM::read_a_record() {
233     int i, inum;
234     double dnum;
235     string name, token;
236     char c;
237     char *ptr;
238
239     // get the name field (144 characters)
240     for ( i = 0; i < 144; i++ ) {
241         in->get(c);
242         name += c;
243     }
244   
245     // clean off the trailing whitespace
246     name = trim(name);
247     cout << "    Quad name field: " << name << endl;
248
249     // DEM level code, 3 reflects processing by DMA
250     inum = next_int();
251     cout << "    DEM level code = " << inum << "\n";
252
253     if ( inum > 3 ) {
254         return 0;
255     }
256
257     // Pattern code, 1 indicates a regular elevation pattern
258     inum = next_int();
259     cout << "    Pattern code = " << inum << "\n";
260
261     // Planimetric reference system code, 0 indicates geographic
262     // coordinate system.
263     inum = next_int();
264     cout << "    Planimetric reference code = " << inum << "\n";
265
266     // Zone code
267     inum = next_int();
268     cout << "    Zone code = " << inum << "\n";
269
270     // Map projection parameters (ignored)
271     for ( i = 0; i < 15; i++ ) {
272         dnum = next_exp();
273         // printf("%d: %f\n",i,dnum);
274     }
275
276     // Units code, 3 represents arc-seconds as the unit of measure for
277     // ground planimetric coordinates throughout the file.
278     inum = next_int();
279     if ( inum != 3 ) {
280         cout << "    Unknown (X,Y) units code = " << inum << "!\n";
281         exit(-1);
282     }
283
284     // Units code; 2 represents meters as the unit of measure for
285     // elevation coordinates throughout the file.
286     inum = next_int();
287     if ( inum != 2 ) {
288         cout << "    Unknown (Z) units code = " << inum << "!\n";
289         exit(-1);
290     }
291
292     // Number (n) of sides in the polygon which defines the coverage of
293     // the DEM file (usually equal to 4).
294     inum = next_int();
295     if ( inum != 4 ) {
296         cout << "    Unknown polygon dimension = " << inum << "!\n";
297         exit(-1);
298     }
299
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";
304
305     dem_x2 = next_exp();
306     dem_y2 = next_exp();
307
308     dem_x3 = next_exp();
309     dem_y3 = next_exp();
310
311     dem_x4 = next_exp();
312     dem_y4 = next_exp();
313
314     // Minimum/maximum elevations in meters
315     dem_z1 = next_exp();
316     dem_z2 = next_exp();
317     cout << "    Elevation range " << dem_z1 << " to " << dem_z2 << "\n";
318
319     // Counterclockwise angle from the primary axis of ground
320     // planimetric referenced to the primary axis of the DEM local
321     // reference system.
322     token = next_token();
323
324     // Accuracy code; 0 indicates that a record of accuracy does not
325     // exist and that no record type C will follow.
326
327     // DEM spacial resolution.  Usually (3,3,1) (3,6,1) or (3,9,1)
328     // depending on latitude
329
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;
334     i = token.length();
335     cout << "    length = " << i << "\n";
336
337 #if 1
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 )
342 #else
343     ptr = token.c_str() + i - 12;
344     cout << "    last field = " << ptr << " = " << atof(ptr) << "\n";
345     ptr[0] = '\0';
346
347     ptr = ptr - 12;
348     col_step = atof(ptr);
349     cout << "    last field = " << ptr << " = " << col_step << "\n";
350     ptr[0] = '\0';
351
352     ptr = ptr - 12;
353     row_step = atof(ptr);
354     cout << "    last field = " << ptr << " = " << row_step << "\n";
355     ptr[0] = '\0';
356
357     // accuracy code = atod(token)
358     ptr = ptr - 12;
359     inum = atoi(ptr);
360 #endif
361     cout << "    Accuracy code = " << inum << "\n";
362
363     cout << "    column step = " << col_step << 
364         "  row step = " << row_step << "\n";
365
366     // dimension of arrays to follow (1)
367     token = next_token();
368
369     // number of profiles
370     dem_num_profiles = cols = next_int();
371     cout << "    Expecting " << dem_num_profiles << " profiles\n";
372
373     return 1;
374 }
375
376
377 // read and parse DEM "B" record
378 void fgDEM::read_b_record( ) {
379     string token;
380     int i;
381
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);
386
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);
391
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);
397
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();
401
402     // Minimum and maximum elevations for the profile.
403     token = next_token();
404     token = next_token();
405
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;
410     }
411 }
412
413
414 // parse dem file
415 int fgDEM::parse( ) {
416     int i;
417
418     cur_col = 0;
419
420     if ( !read_a_record() ) {
421         return(0);
422     }
423
424     for ( i = 0; i < dem_num_profiles; i++ ) {
425         // printf("Ready to read next b record\n");
426         read_b_record();
427         cur_col++;
428
429         if ( cur_col % 100 == 0 ) {
430             cout << "    loaded " << cur_col << " profiles of data\n";
431         }
432     }
433
434     cout << "    Done parsing\n";
435
436     return 1;
437 }
438
439
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
444
445     double xlocal, ylocal, dx, dy, zA, zB, elev;
446     int x1, x2, x3, y1, y2, y3;
447     float z1, z2, z3;
448     int xindex, yindex;
449
450     /* determine if we are in the lower triangle or the upper triangle 
451        ______
452        |   /|
453        |  / |
454        | /  |
455        |/   |
456        ------
457
458        then calculate our end points
459      */
460
461     xlocal = (lon - originx) / col_step;
462     ylocal = (lat - originy) / row_step;
463
464     xindex = (int)(xlocal);
465     yindex = (int)(ylocal);
466
467     // printf("xindex = %d  yindex = %d\n", xindex, yindex);
468
469     if ( xindex + 1 == cols ) {
470         xindex--;
471     }
472
473     if ( yindex + 1 == rows ) {
474         yindex--;
475     }
476
477     if ( (xindex < 0) || (xindex + 1 >= cols) ||
478          (yindex < 0) || (yindex + 1 >= rows) ) {
479         return(-9999);
480     }
481
482     dx = xlocal - xindex;
483     dy = ylocal - yindex;
484
485     if ( dx > dy ) {
486         // lower triangle
487         // printf("  Lower triangle\n");
488
489         x1 = xindex; 
490         y1 = yindex; 
491         z1 = dem_data[x1][y1];
492
493         x2 = xindex + 1; 
494         y2 = yindex; 
495         z2 = dem_data[x2][y2];
496                                   
497         x3 = xindex + 1; 
498         y3 = yindex + 1; 
499         z3 = dem_data[x3][y3];
500
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);
505
506         zA = dx * (z2 - z1) + z1;
507         zB = dx * (z3 - z1) + z1;
508         
509         // printf("  zA = %.2f  zB = %.2f\n", zA, zB);
510
511         if ( dx > FG_EPSILON ) {
512             elev = dy * (zB - zA) / dx + zA;
513         } else {
514             elev = zA;
515         }
516     } else {
517         // upper triangle
518         // printf("  Upper triangle\n");
519
520         x1 = xindex; 
521         y1 = yindex; 
522         z1 = dem_data[x1][y1];
523
524         x2 = xindex; 
525         y2 = yindex + 1; 
526         z2 = dem_data[x2][y2];
527                                   
528         x3 = xindex + 1; 
529         y3 = yindex + 1; 
530         z3 = dem_data[x3][y3];
531
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);
536  
537         zA = dy * (z2 - z1) + z1;
538         zB = dy * (z3 - z1) + z1;
539         
540         // printf("  zA = %.2f  zB = %.2f\n", zA, zB );
541         // printf("  xB - xA = %.2f\n", col_step * dy / row_step);
542
543         if ( dy > FG_EPSILON ) {
544             elev = dx * (zB - zA) / dy    + zA;
545         } else {
546             elev = zA;
547         }
548     }
549
550     return(elev);
551 }
552
553
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;
558     double cury, lasty;
559     int n, row, start, end;
560     int colmin, colmax, rowmin, rowmax;
561     bool good_fit;
562     // FILE *dem, *fit, *fit1;
563
564     printf("Initializing output mesh structure\n");
565     outputmesh_init();
566
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);
573     
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]);
579
580     printf("Beginning best fit procedure\n");
581
582     for ( row = rowmin; row <= rowmax; row++ ) {
583         // fit  = fopen("fit.dat",  "w");
584         // fit1 = fopen("fit1.dat", "w");
585
586         start = colmin;
587
588         // printf("    fitting row = %d\n", row);
589
590         while ( start < colmax ) {
591             end = start + 1;
592             good_fit = true;
593
594             x[(end - start) - 1] = 0.0 + ( start * col_step );
595             y[(end - start) - 1] = dem_data[start][row];
596
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);
605
606                 /*
607                 printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
608                 start, end, ave_error, max_error, m, b);
609                 
610                 f = fopen("gnuplot.dat", "w");
611                 for ( j = 0; j <= end; j++) {
612                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
613                             dem_data[row][j]);
614                 }
615                 for ( j = start; j <= end; j++) {
616                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
617                             dem_data[row][j]);
618                 }
619                 fclose(f);
620
621                 printf("Please hit return: "); gets(junk);
622                 */
623
624                 if ( max_error > error ) {
625                     good_fit = false;
626                 }
627                 
628                 end++;
629             }
630
631             if ( !good_fit ) {
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
635             } else {
636                 // we popped out of the above loop while still within
637                 // the error threshold, so we must be at the end of
638                 // the data set
639                 end--;
640             }
641             
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);
645
646             /*
647             printf("\n");
648             printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
649                    start, end, ave_error, max_error, m, b);
650             printf("\n");
651
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);
654             */
655
656             if ( start > colmin ) {
657                 // skip this for the first line segment
658                 cury = m * x[0] + b;
659                 outputmesh_set_pt(start, row, (lasty + cury) / 2);
660                 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
661             }
662
663             lasty = m * x[end-start] + b;
664             start = end;
665         }
666
667         /*
668         fclose(fit);
669         fclose(fit1);
670
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 ), 
674                     dem_data[j][row]);
675         } 
676         fclose(dem);
677         */
678
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);
684     }
685
686     // outputmesh_output_nodes(fg_root, p);
687 }
688
689
690 // Initialize output mesh structure
691 void fgDEM::outputmesh_init( void ) {
692     int i, j;
693     
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;
697         }
698     }
699 }
700
701
702 // Get the value of a mesh node
703 double fgDEM::outputmesh_get_pt( int i, int j ) {
704     return ( output_data[i][j] );
705 }
706
707
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;
712 }
713
714
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;
722     string dir;
723     char base_path[256], file[256], exfile[256];
724 #ifdef WIN32
725     char tmp_path[256];
726 #endif
727     string command;
728     FILE *fd;
729     long int index;
730     int colmin, colmax, rowmin, rowmax;
731     int i, j, count, excount, result;
732
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";
740
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;
746     
747     // stat() directory and create if needed
748     errno = 0;
749     result = stat(dir.c_str(), &stat_buf);
750     if ( result != 0 && errno == ENOENT ) {
751         cout << "Creating directory\n";
752
753 // #ifndef WIN32
754
755         command = "mkdir -p " + dir + "\n";
756         system( command.c_str() );
757
758 #if 0
759 // #else // WIN32
760
761         // Cygwin crashes when trying to output to node file
762         // explicitly making directory structure seems OK on Win95
763
764         extract_path (base_path, tmp_path);
765
766         dir = fg_root + "/Scenery";
767         if (my_mkdir ( dir.c_str() )) { exit (-1); }
768
769         dir = fg_root + "/Scenery/" + tmp_path;
770         if (my_mkdir ( dir.c_str() )) { exit (-1); }
771
772         dir = fg_root + "/Scenery/" + base_path;
773         if (my_mkdir ( dir.c_str() )) { exit (-1); }
774
775 // #endif // WIN32
776 #endif //0
777
778     } else {
779         // assume directory exists
780     }
781
782     // get index and generate output file name
783     index = fgBucketGenIndex(p);
784     sprintf(file, "%s/%ld.node", dir.c_str(), index);
785
786     // get (optional) extra node file name (in case there is matching
787     // .poly file.
788     strcpy(exfile, file);
789     strcat(exfile, ".ex");
790
791     // load extra nodes if they exist
792     excount = 0;
793     if ( (fd = fopen(exfile, "r")) != NULL ) {
794         int junki;
795         fscanf(fd, "%d %d %d %d", &excount, &junki, &junki, &junki);
796
797         if ( excount > MAX_EX_NODES - 1 ) {
798             printf("Error, too many 'extra' nodes, increase array size\n");
799             exit(-1);
800         } else {
801             printf("    Expecting %d 'extra' nodes\n", excount);
802         }
803
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]);
809         }
810         fclose(fd);
811     }
812
813     printf("Creating node file:  %s\n", file);
814     fd = fopen(file, "w");
815
816     // first count regular nodes to generate header
817     count = 0;
818     for ( j = rowmin; j <= rowmax; j++ ) {
819         for ( i = colmin; i <= colmax; i++ ) {
820             if ( output_data[i][j] > -9000.0 ) {
821                 count++;
822             }
823         }
824         // printf("    count = %d\n", count);
825     }
826     fprintf(fd, "%d 2 1 0\n", count + excount);
827
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]);
832     }
833
834     // write out actual node data
835     count = excount + 1;
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", 
840                         count++, 
841                         originx + (double)i * col_step, 
842                         originy + (double)j * row_step,
843                         output_data[i][j]);
844             }
845         }
846         // printf("    count = %d\n", count);
847     }
848
849     fclose(fd);
850 }
851
852
853 fgDEM::~fgDEM( void ) {
854     // printf("class fgDEM DEstructor called.\n");
855     delete [] dem_data;
856     delete [] output_data;
857 }
858
859
860 // $Log$
861 // Revision 1.21  1998/11/06 14:04:32  curt
862 // Changes due to updates in fgstream.
863 //
864 // Revision 1.20  1998/10/28 19:38:20  curt
865 // Elliminate some unnecessary win32 specific stuff (by Norman Vine)
866 //
867 // Revision 1.19  1998/10/22 21:59:19  curt
868 // Fixed a couple subtle bugs that resulted from some of my c++ conversions.
869 // One bug could cause a segfault on certain input, and the other bug could
870 // cause the whole procedure to go balistic and generate huge files (also only
871 // on rare input combinations.)
872 //
873 // Revision 1.18  1998/10/18 01:17:09  curt
874 // Point3D tweaks.
875 //
876 // Revision 1.17  1998/10/16 19:08:12  curt
877 // Portability updates from Bernie Bright.
878 //
879 // Revision 1.16  1998/10/02 21:41:39  curt
880 // Fixes for win32.
881 //
882 // Revision 1.15  1998/09/21 20:53:59  curt
883 // minor tweaks to clean a few additional things up after the rewrite.
884 //
885 // Revision 1.14  1998/09/19 17:59:45  curt
886 // Use c++ streams (fg_gzifstream).  Also converted many character arrays to
887 // the string class.
888 //
889 // Revision 1.13  1998/09/09 16:24:04  curt
890 // Fixed a bug in the handling of exclude files which was causing
891 // a crash by calling fclose() on an invalid file handle.
892 //
893 // Revision 1.12  1998/08/24 20:03:31  curt
894 // Eliminated a possible memory overrun error.
895 // Use the proper free() rather than the incorrect delete().
896 //
897 // Revision 1.11  1998/07/20 12:46:11  curt
898 // When outputing to a .node file, first check for an optional
899 // "index.node.ex" file in case there is a .poly file to go along with this
900 // node file.  Include these nodes first since they are referenced by position
901 // from the .poly file.  This is my first pass at adding an area "cutout"
902 // feature to the terrain generation pipeline.
903 //
904 // Revision 1.10  1998/07/13 20:58:02  curt
905 // .
906 //
907 // Revision 1.9  1998/07/13 15:29:49  curt
908 // Added #ifdef HAVE_CONFIG_H
909 //
910 // Revision 1.8  1998/07/04 00:47:18  curt
911 // typedef'd struct fgBUCKET.
912 //
913 // Revision 1.7  1998/06/05 18:14:39  curt
914 // Abort out early when reading the "A" record if it doesn't look like
915 // a proper DEM file.
916 //
917 // Revision 1.6  1998/05/02 01:49:21  curt
918 // Fixed a bug where the wrong variable was being initialized.
919 //
920 // Revision 1.5  1998/04/25 15:00:32  curt
921 // Changed "r" to "rb" in gzopen() options.  This fixes bad behavior in win32.
922 //
923 // Revision 1.4  1998/04/22 13:14:46  curt
924 // Fixed a bug in zlib usage.
925 //
926 // Revision 1.3  1998/04/18 03:53:05  curt
927 // Added zlib support.
928 //
929 // Revision 1.2  1998/04/14 02:43:27  curt
930 // Used "new" to auto-allocate large DEM parsing arrays in class constructor.
931 //
932 // Revision 1.1  1998/04/08 22:57:22  curt
933 // Adopted Gnu automake/autoconf system.
934 //
935 // Revision 1.3  1998/04/06 21:09:41  curt
936 // Additional win32 support.
937 // Fixed a bad bug in dem file parsing that was causing the output to be
938 // flipped about x = y.
939 //
940 // Revision 1.2  1998/03/23 20:35:41  curt
941 // Updated to use FG_EPSILON
942 //
943 // Revision 1.1  1998/03/19 02:54:47  curt
944 // Reorganized into a class lib called fgDEM.
945 //
946 // Revision 1.1  1998/03/19 01:46:28  curt
947 // Initial revision.
948 //