]> git.mxchange.org Git - flightgear.git/blob - DEM/dem.cxx
Moved point interpolation and least squares fitting to contruction program
[flightgear.git] / DEM / dem.cxx
1 // dem.cxx -- DEM management class
2 //
3 // Written by Curtis Olson, started March 1998.
4 //
5 // Copyright (C) 1998  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22 // (Log is kept at end of this file)
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <Include/compiler.h>
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
37 #ifdef HAVE_SYS_STAT_H
38 #  include <sys/stat.h> // stat()
39 #endif
40
41 #ifdef FG_HAVE_STD_INCLUDES
42 #  include <cerrno>
43 #else
44 #  include <errno.h>
45 #endif
46
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>   // stat()
49 #endif
50
51 #include <Misc/fgstream.hxx>
52 #include <Misc/strutils.hxx>
53 #include <Include/fg_constants.h>
54
55 #include "dem.hxx"
56
57
58 #define MAX_EX_NODES 10000
59
60 #if 0
61 #ifdef WIN32
62 # ifdef __BORLANDC__
63 #  include <dir.h>
64 #  define MKDIR(a) mkdir(a)
65 # else
66 #  define MKDIR(a) mkdir(a,S_IRWXU)  // I am just guessing at this flag (NHV)
67 # endif // __BORLANDC__
68 #endif // WIN32
69 #endif //0
70
71
72 FGDem::FGDem( void ) {
73     // cout << "class FGDem CONstructor called." << endl;
74     dem_data = new float[DEM_SIZE_1][DEM_SIZE_1];
75     output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
76 }
77
78
79 FGDem::FGDem( const string &file ) {
80     // cout << "class FGDem CONstructor called." << endl;
81     dem_data = new float[DEM_SIZE_1][DEM_SIZE_1];
82     output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
83
84     FGDem::open(file);
85 }
86
87
88 // open a DEM file
89 int
90 FGDem::open ( const string& file ) {
91     // open input file (or read from stdin)
92     if ( file ==  "-" ) {
93         printf("Loading DEM data file: stdin\n");
94         // fd = stdin;
95         // fd = gzdopen(STDIN_FILENO, "r");
96         printf("Not yet ported ...\n");
97         return 0;
98     } else {
99         in = new fg_gzifstream( file );
100         if ( !(*in) ) {
101             cout << "Cannot open " << file << endl;
102             return 0;
103         }
104         cout << "Loading DEM data file: " << file << endl;
105     }
106
107     return 1;
108 }
109
110
111 // close a DEM file
112 int
113 FGDem::close () {
114     // the fg_gzifstream doesn't seem to have a close()
115
116     delete in;
117
118     return 1;
119 }
120
121
122 // return next token from input stream
123 string
124 FGDem::next_token() {
125     string token;
126
127     *in >> token;
128
129     // cout << "    returning " + token + "\n";
130
131     return token;
132 }
133
134
135 // return next integer from input stream
136 int
137 FGDem::next_int() {
138     int result;
139     
140     *in >> result;
141
142     return result;
143 }
144
145
146 // return next double from input stream
147 double
148 FGDem::next_double() {
149     double result;
150
151     *in >> result;
152
153     return result;
154 }
155
156
157 // return next exponential num from input stream
158 double
159 FGDem::next_exp() {
160     string token;
161
162     token = next_token();
163
164     const char* p = token.c_str();
165     char buf[64];
166     char* bp = buf;
167     
168     for ( ; *p != 0; ++p )
169     {
170         if ( *p == 'D' )
171             *bp++ = 'E';
172         else
173             *bp++ = *p;
174     }
175     *bp = 0;
176     return ::atof( buf );
177 }
178
179
180 // read and parse DEM "A" record
181 int
182 FGDem::read_a_record() {
183     int i, inum;
184     double dnum;
185     string name, token;
186     char c;
187
188     // get the name field (144 characters)
189     for ( i = 0; i < 144; i++ ) {
190         in->get(c);
191         name += c;
192     }
193   
194     // clean off the trailing whitespace
195     name = trim(name);
196     cout << "    Quad name field: " << name << endl;
197
198     // DEM level code, 3 reflects processing by DMA
199     inum = next_int();
200     cout << "    DEM level code = " << inum << "\n";
201
202     if ( inum > 3 ) {
203         return 0;
204     }
205
206     // Pattern code, 1 indicates a regular elevation pattern
207     inum = next_int();
208     cout << "    Pattern code = " << inum << "\n";
209
210     // Planimetric reference system code, 0 indicates geographic
211     // coordinate system.
212     inum = next_int();
213     cout << "    Planimetric reference code = " << inum << "\n";
214
215     // Zone code
216     inum = next_int();
217     cout << "    Zone code = " << inum << "\n";
218
219     // Map projection parameters (ignored)
220     for ( i = 0; i < 15; i++ ) {
221         dnum = next_exp();
222         // printf("%d: %f\n",i,dnum);
223     }
224
225     // Units code, 3 represents arc-seconds as the unit of measure for
226     // ground planimetric coordinates throughout the file.
227     inum = next_int();
228     if ( inum != 3 ) {
229         cout << "    Unknown (X,Y) units code = " << inum << "!\n";
230         exit(-1);
231     }
232
233     // Units code; 2 represents meters as the unit of measure for
234     // elevation coordinates throughout the file.
235     inum = next_int();
236     if ( inum != 2 ) {
237         cout << "    Unknown (Z) units code = " << inum << "!\n";
238         exit(-1);
239     }
240
241     // Number (n) of sides in the polygon which defines the coverage of
242     // the DEM file (usually equal to 4).
243     inum = next_int();
244     if ( inum != 4 ) {
245         cout << "    Unknown polygon dimension = " << inum << "!\n";
246         exit(-1);
247     }
248
249     // Ground coordinates of bounding box in arc-seconds
250     dem_x1 = originx = next_exp();
251     dem_y1 = originy = next_exp();
252     cout << "    Origin = (" << originx << "," << originy << ")\n";
253
254     dem_x2 = next_exp();
255     dem_y2 = next_exp();
256
257     dem_x3 = next_exp();
258     dem_y3 = next_exp();
259
260     dem_x4 = next_exp();
261     dem_y4 = next_exp();
262
263     // Minimum/maximum elevations in meters
264     dem_z1 = next_exp();
265     dem_z2 = next_exp();
266     cout << "    Elevation range " << dem_z1 << " to " << dem_z2 << "\n";
267
268     // Counterclockwise angle from the primary axis of ground
269     // planimetric referenced to the primary axis of the DEM local
270     // reference system.
271     token = next_token();
272
273     // Accuracy code; 0 indicates that a record of accuracy does not
274     // exist and that no record type C will follow.
275
276     // DEM spacial resolution.  Usually (3,3,1) (3,6,1) or (3,9,1)
277     // depending on latitude
278
279     // I will eventually have to do something with this for data at
280     // higher latitudes */
281     token = next_token();
282     cout << "    accuracy & spacial resolution string = " << token << endl;
283     i = token.length();
284     cout << "    length = " << i << "\n";
285
286     inum = atoi( token.substr( 0, i - 36 ) );
287     row_step = atof( token.substr( i - 24, 12 ) );
288     col_step = atof( token.substr( i - 36, 12 ) );
289     cout << "    Accuracy code = " << inum << "\n";
290     cout << "    column step = " << col_step << 
291         "  row step = " << row_step << "\n";
292
293     // dimension of arrays to follow (1)
294     token = next_token();
295
296     // number of profiles
297     dem_num_profiles = cols = next_int();
298     cout << "    Expecting " << dem_num_profiles << " profiles\n";
299
300     return 1;
301 }
302
303
304 // read and parse DEM "B" record
305 void
306 FGDem::read_b_record( ) {
307     string token;
308     int i;
309
310     // row / column id of this profile
311     prof_row = next_int();
312     prof_col = next_int();
313     // printf("col id = %d  row id = %d\n", prof_col, prof_row);
314
315     // Number of columns and rows (elevations) in this profile
316     prof_num_rows = rows = next_int();
317     prof_num_cols = next_int();
318     // printf("    profile num rows = %d\n", prof_num_rows);
319
320     // Ground planimetric coordinates (arc-seconds) of the first
321     // elevation in the profile
322     prof_x1 = next_exp();
323     prof_y1 = next_exp();
324     // printf("    Starting at %.2f %.2f\n", prof_x1, prof_y1);
325
326     // Elevation of local datum for the profile.  Always zero for
327     // 1-degree DEM, the reference is mean sea level.
328     token = next_token();
329
330     // Minimum and maximum elevations for the profile.
331     token = next_token();
332     token = next_token();
333
334     // One (usually) dimensional array (prof_num_cols,1) of elevations
335     for ( i = 0; i < prof_num_rows; i++ ) {
336         prof_data = next_int();
337         dem_data[cur_col][i] = (float)prof_data;
338     }
339 }
340
341
342 // parse dem file
343 int
344 FGDem::parse( ) {
345     int i;
346
347     cur_col = 0;
348
349     if ( !read_a_record() ) {
350         return(0);
351     }
352
353     for ( i = 0; i < dem_num_profiles; i++ ) {
354         // printf("Ready to read next b record\n");
355         read_b_record();
356         cur_col++;
357
358         if ( cur_col % 100 == 0 ) {
359             cout << "    loaded " << cur_col << " profiles of data\n";
360         }
361     }
362
363     cout << "    Done parsing\n";
364
365     return 1;
366 }
367
368
369 // write out the area of data covered by the specified bucket.  Data
370 // is written out column by column starting at the lower left hand
371 // corner.
372 int
373 FGDem::write_area( const string& root, FGBucket& b, bool compress ) {
374     char tile_name[256];
375
376     // calculate some boundaries
377     double min_x = ( b.get_center_lon() - 0.5 * b.get_width() ) * 3600.0;
378     double max_x = ( b.get_center_lon() + 0.5 * b.get_width() ) * 3600.0;
379
380     double min_y = ( b.get_center_lat() - 0.5 * b.get_height() ) * 3600.0;
381     double max_y = ( b.get_center_lat() + 0.5 * b.get_height() ) * 3600.0;
382
383     cout << b << endl;
384     cout << "width = " << b.get_width() << " height = " << b.get_height() 
385          << endl;
386
387     int start_x = (int)((min_x - originx) / col_step);
388     int span_x = (int)(b.get_width() * 3600.0 / col_step);
389
390     int start_y = (int)((min_y - originy) / row_step);
391     int span_y = (int)(b.get_height() * 3600.0 / row_step);
392
393     cout << "start_x = " << start_x << "  span_x = " << span_x << endl;
394     cout << "start_y = " << start_y << "  span_y = " << span_y << endl;
395
396     // Do a simple sanity checking.  But, please, please be nice to
397     // this write_area() routine and feed it buckets that coincide
398     // well with the underlying grid structure and spacing.
399
400     if ( ( min_x < originx )
401          || ( max_x > originx + cols * col_step )
402          || ( min_y < originy )
403          || ( max_y > originy + rows * row_step ) ) {
404         cout << "  ERROR: bucket at least partially outside DEM data range!" <<
405             endl;
406         return 0;
407     }
408
409     // generate output file name
410     string base = b.gen_base_path();
411     string path = root + "/Scenery/" + base;
412     string command = "mkdir -p " + path;
413     system( command.c_str() );
414
415     long int b_index = b.gen_index();
416     sprintf(tile_name, "%ld", b_index);
417     string demfile = path + "/" + tile_name + ".dem";
418     cout << "demfile = " << demfile << endl;
419
420     // write the file
421     FILE *fp;
422     if ( (fp = fopen(demfile.c_str(), "w")) == NULL ) {
423         cout << "cannot open " << demfile << " for writing!" << endl;
424         exit(-1);
425     }
426
427     fprintf( fp, "%d %d\n", (int)min_x, (int)min_y );
428     fprintf( fp, "%d %d %d %d\n", span_x + 1, (int)col_step, 
429              span_y + 1, (int)row_step );
430     for ( int i = start_x; i <= start_x + span_x; ++i ) {
431         for ( int j = start_y; j <= start_y + span_y; ++j ) {
432             fprintf( fp, "%d ", (int)dem_data[i][j] );
433         }
434         fprintf( fp, "\n" );
435     }
436     fclose(fp);
437
438     if ( compress ) {
439         string command = "gzip --best -f " + demfile;
440         system( command.c_str() );
441     }
442
443     return 1;
444 }
445
446
447 #if 0
448
449 // return the current altitude based on grid data.  We should rewrite
450 // this to interpolate exact values, but for now this is good enough
451 double FGDem::interpolate_altitude( double lon, double lat ) {
452     // we expect incoming (lon,lat) to be in arcsec for now
453
454     double xlocal, ylocal, dx, dy, zA, zB, elev;
455     int x1, x2, x3, y1, y2, y3;
456     float z1, z2, z3;
457     int xindex, yindex;
458
459     /* determine if we are in the lower triangle or the upper triangle 
460        ______
461        |   /|
462        |  / |
463        | /  |
464        |/   |
465        ------
466
467        then calculate our end points
468      */
469
470     xlocal = (lon - originx) / col_step;
471     ylocal = (lat - originy) / row_step;
472
473     xindex = (int)(xlocal);
474     yindex = (int)(ylocal);
475
476     // printf("xindex = %d  yindex = %d\n", xindex, yindex);
477
478     if ( xindex + 1 == cols ) {
479         xindex--;
480     }
481
482     if ( yindex + 1 == rows ) {
483         yindex--;
484     }
485
486     if ( (xindex < 0) || (xindex + 1 >= cols) ||
487          (yindex < 0) || (yindex + 1 >= rows) ) {
488         return(-9999);
489     }
490
491     dx = xlocal - xindex;
492     dy = ylocal - yindex;
493
494     if ( dx > dy ) {
495         // lower triangle
496         // printf("  Lower triangle\n");
497
498         x1 = xindex; 
499         y1 = yindex; 
500         z1 = dem_data[x1][y1];
501
502         x2 = xindex + 1; 
503         y2 = yindex; 
504         z2 = dem_data[x2][y2];
505                                   
506         x3 = xindex + 1; 
507         y3 = yindex + 1; 
508         z3 = dem_data[x3][y3];
509
510         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
511         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
512         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
513         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
514
515         zA = dx * (z2 - z1) + z1;
516         zB = dx * (z3 - z1) + z1;
517         
518         // printf("  zA = %.2f  zB = %.2f\n", zA, zB);
519
520         if ( dx > FG_EPSILON ) {
521             elev = dy * (zB - zA) / dx + zA;
522         } else {
523             elev = zA;
524         }
525     } else {
526         // upper triangle
527         // printf("  Upper triangle\n");
528
529         x1 = xindex; 
530         y1 = yindex; 
531         z1 = dem_data[x1][y1];
532
533         x2 = xindex; 
534         y2 = yindex + 1; 
535         z2 = dem_data[x2][y2];
536                                   
537         x3 = xindex + 1; 
538         y3 = yindex + 1; 
539         z3 = dem_data[x3][y3];
540
541         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
542         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
543         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
544         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
545  
546         zA = dy * (z2 - z1) + z1;
547         zB = dy * (z3 - z1) + z1;
548         
549         // printf("  zA = %.2f  zB = %.2f\n", zA, zB );
550         // printf("  xB - xA = %.2f\n", col_step * dy / row_step);
551
552         if ( dy > FG_EPSILON ) {
553             elev = dx * (zB - zA) / dy    + zA;
554         } else {
555             elev = zA;
556         }
557     }
558
559     return(elev);
560 }
561
562
563 // Use least squares to fit a simpler data set to dem data
564 void FGDem::fit( double error, FGBucket& p ) {
565     double x[DEM_SIZE_1], y[DEM_SIZE_1];
566     double m, b, ave_error, max_error;
567     double cury, lasty;
568     int n, row, start, end;
569     int colmin, colmax, rowmin, rowmax;
570     bool good_fit;
571     // FILE *dem, *fit, *fit1;
572
573     printf("Initializing output mesh structure\n");
574     outputmesh_init();
575
576     // determine dimensions
577     colmin = p.get_x() * ( (cols - 1) / 8);
578     colmax = colmin + ( (cols - 1) / 8);
579     rowmin = p.get_y() * ( (rows - 1) / 8);
580     rowmax = rowmin + ( (rows - 1) / 8);
581     printf("Fitting region = %d,%d to %d,%d\n", colmin, rowmin, colmax, rowmax);
582     
583     // include the corners explicitly
584     outputmesh_set_pt(colmin, rowmin, dem_data[colmin][rowmin]);
585     outputmesh_set_pt(colmin, rowmax, dem_data[colmin][rowmax]);
586     outputmesh_set_pt(colmax, rowmax, dem_data[colmax][rowmax]);
587     outputmesh_set_pt(colmax, rowmin, dem_data[colmax][rowmin]);
588
589     printf("Beginning best fit procedure\n");
590
591     for ( row = rowmin; row <= rowmax; row++ ) {
592         // fit  = fopen("fit.dat",  "w");
593         // fit1 = fopen("fit1.dat", "w");
594
595         start = colmin;
596
597         // printf("    fitting row = %d\n", row);
598
599         while ( start < colmax ) {
600             end = start + 1;
601             good_fit = true;
602
603             x[(end - start) - 1] = 0.0 + ( start * col_step );
604             y[(end - start) - 1] = dem_data[start][row];
605
606             while ( (end <= colmax) && good_fit ) {
607                 n = (end - start) + 1;
608                 // printf("Least square of first %d points\n", n);
609                 x[end - start] = 0.0 + ( end * col_step );
610                 y[end - start] = dem_data[end][row];
611                 least_squares(x, y, n, &m, &b);
612                 ave_error = least_squares_error(x, y, n, m, b);
613                 max_error = least_squares_max_error(x, y, n, m, b);
614
615                 /*
616                 printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
617                 start, end, ave_error, max_error, m, b);
618                 
619                 f = fopen("gnuplot.dat", "w");
620                 for ( j = 0; j <= end; j++) {
621                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
622                             dem_data[row][j]);
623                 }
624                 for ( j = start; j <= end; j++) {
625                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
626                             dem_data[row][j]);
627                 }
628                 fclose(f);
629
630                 printf("Please hit return: "); gets(junk);
631                 */
632
633                 if ( max_error > error ) {
634                     good_fit = false;
635                 }
636                 
637                 end++;
638             }
639
640             if ( !good_fit ) {
641                 // error exceeded the threshold, back up
642                 end -= 2;  // back "end" up to the last good enough fit
643                 n--;       // back "n" up appropriately too
644             } else {
645                 // we popped out of the above loop while still within
646                 // the error threshold, so we must be at the end of
647                 // the data set
648                 end--;
649             }
650             
651             least_squares(x, y, n, &m, &b);
652             ave_error = least_squares_error(x, y, n, m, b);
653             max_error = least_squares_max_error(x, y, n, m, b);
654
655             /*
656             printf("\n");
657             printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
658                    start, end, ave_error, max_error, m, b);
659             printf("\n");
660
661             fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
662             fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
663             */
664
665             if ( start > colmin ) {
666                 // skip this for the first line segment
667                 cury = m * x[0] + b;
668                 outputmesh_set_pt(start, row, (lasty + cury) / 2);
669                 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
670             }
671
672             lasty = m * x[end-start] + b;
673             start = end;
674         }
675
676         /*
677         fclose(fit);
678         fclose(fit1);
679
680         dem = fopen("gnuplot.dat", "w");
681         for ( j = 0; j < DEM_SIZE_1; j++) {
682             fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
683                     dem_data[j][row]);
684         } 
685         fclose(dem);
686         */
687
688         // NOTICE, this is for testing only.  This instance of
689         // output_nodes should be removed.  It should be called only
690         // once at the end once all the nodes have been generated.
691         // newmesh_output_nodes(&nm, "mesh.node");
692         // printf("Please hit return: "); gets(junk);
693     }
694
695     // outputmesh_output_nodes(fg_root, p);
696 }
697
698
699 // Initialize output mesh structure
700 void FGDem::outputmesh_init( void ) {
701     int i, j;
702     
703     for ( j = 0; j < DEM_SIZE_1; j++ ) {
704         for ( i = 0; i < DEM_SIZE_1; i++ ) {
705             output_data[i][j] = -9999.0;
706         }
707     }
708 }
709
710
711 // Get the value of a mesh node
712 double FGDem::outputmesh_get_pt( int i, int j ) {
713     return ( output_data[i][j] );
714 }
715
716
717 // Set the value of a mesh node
718 void FGDem::outputmesh_set_pt( int i, int j, double value ) {
719     // printf("Setting data[%d][%d] = %.2f\n", i, j, value);
720    output_data[i][j] = value;
721 }
722
723
724 // Write out a node file that can be used by the "triangle" program.
725 // Check for an optional "index.node.ex" file in case there is a .poly
726 // file to go along with this node file.  Include these nodes first
727 // since they are referenced by position from the .poly file.
728 void FGDem::outputmesh_output_nodes( const string& fg_root, FGBucket& p )
729 {
730     double exnodes[MAX_EX_NODES][3];
731     struct stat stat_buf;
732     string dir;
733     char file[256], exfile[256];
734 #ifdef WIN32
735     char tmp_path[256];
736 #endif
737     string command;
738     FILE *fd;
739     long int index;
740     int colmin, colmax, rowmin, rowmax;
741     int i, j, count, excount, result;
742
743     // determine dimensions
744     colmin = p.get_x() * ( (cols - 1) / 8);
745     colmax = colmin + ( (cols - 1) / 8);
746     rowmin = p.get_y() * ( (rows - 1) / 8);
747     rowmax = rowmin + ( (rows - 1) / 8);
748     cout << "  dumping region = " << colmin << "," << rowmin << " to " <<
749         colmax << "," << rowmax << "\n";
750
751     // generate the base directory
752     string base_path = p.gen_base_path();
753     cout << "fg_root = " << fg_root << "  Base Path = " << base_path << endl;
754     dir = fg_root + "/Scenery/" + base_path;
755     cout << "Dir = " << dir << endl;
756     
757     // stat() directory and create if needed
758     errno = 0;
759     result = stat(dir.c_str(), &stat_buf);
760     if ( result != 0 && errno == ENOENT ) {
761         cout << "Creating directory\n";
762
763 // #ifndef WIN32
764
765         command = "mkdir -p " + dir + "\n";
766         system( command.c_str() );
767
768 #if 0
769 // #else // WIN32
770
771         // Cygwin crashes when trying to output to node file
772         // explicitly making directory structure seems OK on Win95
773
774         extract_path (base_path, tmp_path);
775
776         dir = fg_root + "/Scenery";
777         if (my_mkdir ( dir.c_str() )) { exit (-1); }
778
779         dir = fg_root + "/Scenery/" + tmp_path;
780         if (my_mkdir ( dir.c_str() )) { exit (-1); }
781
782         dir = fg_root + "/Scenery/" + base_path;
783         if (my_mkdir ( dir.c_str() )) { exit (-1); }
784
785 // #endif // WIN32
786 #endif //0
787
788     } else {
789         // assume directory exists
790     }
791
792     // get index and generate output file name
793     index = p.gen_index();
794     sprintf(file, "%s/%ld.node", dir.c_str(), index);
795
796     // get (optional) extra node file name (in case there is matching
797     // .poly file.
798     strcpy(exfile, file);
799     strcat(exfile, ".ex");
800
801     // load extra nodes if they exist
802     excount = 0;
803     if ( (fd = fopen(exfile, "r")) != NULL ) {
804         int junki;
805         fscanf(fd, "%d %d %d %d", &excount, &junki, &junki, &junki);
806
807         if ( excount > MAX_EX_NODES - 1 ) {
808             printf("Error, too many 'extra' nodes, increase array size\n");
809             exit(-1);
810         } else {
811             printf("    Expecting %d 'extra' nodes\n", excount);
812         }
813
814         for ( i = 1; i <= excount; i++ ) {
815             fscanf(fd, "%d %lf %lf %lf\n", &junki, 
816                    &exnodes[i][0], &exnodes[i][1], &exnodes[i][2]);
817             printf("(extra) %d %.2f %.2f %.2f\n", 
818                     i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
819         }
820         fclose(fd);
821     }
822
823     printf("Creating node file:  %s\n", file);
824     fd = fopen(file, "w");
825
826     // first count regular nodes to generate header
827     count = 0;
828     for ( j = rowmin; j <= rowmax; j++ ) {
829         for ( i = colmin; i <= colmax; i++ ) {
830             if ( output_data[i][j] > -9000.0 ) {
831                 count++;
832             }
833         }
834         // printf("    count = %d\n", count);
835     }
836     fprintf(fd, "%d 2 1 0\n", count + excount);
837
838     // now write out extra node data
839     for ( i = 1; i <= excount; i++ ) {
840         fprintf(fd, "%d %.2f %.2f %.2f\n", 
841                 i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
842     }
843
844     // write out actual node data
845     count = excount + 1;
846     for ( j = rowmin; j <= rowmax; j++ ) {
847         for ( i = colmin; i <= colmax; i++ ) {
848             if ( output_data[i][j] > -9000.0 ) {
849                 fprintf(fd, "%d %.2f %.2f %.2f\n", 
850                         count++, 
851                         originx + (double)i * col_step, 
852                         originy + (double)j * row_step,
853                         output_data[i][j]);
854             }
855         }
856         // printf("    count = %d\n", count);
857     }
858
859     fclose(fd);
860 }
861 #endif
862
863
864 FGDem::~FGDem( void ) {
865     // printf("class FGDem DEstructor called.\n");
866     delete [] dem_data;
867     delete [] output_data;
868 }
869
870
871 // $Log$
872 // Revision 1.26  1999/03/13 17:40:37  curt
873 // Moved point interpolation and least squares fitting to contruction program
874 // area.
875 // Moved leastsqs.* to Lib/Math/
876 //
877 // Revision 1.25  1999/03/12 22:53:07  curt
878 // Added a routine to dump out the portion of the dem data covered by a
879 // specified bucket.  Other changes related to needs of scenery tools overhaul.
880 //
881 // Revision 1.24  1999/03/11 23:31:56  curt
882 // Tweaks to use newbucket.hxx
883 //
884 // Revision 1.23  1999/03/10 01:09:12  curt
885 // Tweaks to go along with scenery tools overhaul.
886 // Added a new constructor that accepts the file name.
887 //
888 // Revision 1.22  1999/01/19 20:56:56  curt
889 // MacOS portability changes contributed by "Robert Puyol" <puyol@abvent.fr>
890 //
891 // Revision 1.21  1998/11/06 14:04:32  curt
892 // Changes due to updates in fgstream.
893 //
894 // Revision 1.20  1998/10/28 19:38:20  curt
895 // Elliminate some unnecessary win32 specific stuff (by Norman Vine)
896 //
897 // Revision 1.19  1998/10/22 21:59:19  curt
898 // Fixed a couple subtle bugs that resulted from some of my c++ conversions.
899 // One bug could cause a segfault on certain input, and the other bug could
900 // cause the whole procedure to go balistic and generate huge files (also only
901 // on rare input combinations.)
902 //
903 // Revision 1.18  1998/10/18 01:17:09  curt
904 // Point3D tweaks.
905 //
906 // Revision 1.17  1998/10/16 19:08:12  curt
907 // Portability updates from Bernie Bright.
908 //
909 // Revision 1.16  1998/10/02 21:41:39  curt
910 // Fixes for win32.
911 //
912 // Revision 1.15  1998/09/21 20:53:59  curt
913 // minor tweaks to clean a few additional things up after the rewrite.
914 //
915 // Revision 1.14  1998/09/19 17:59:45  curt
916 // Use c++ streams (fg_gzifstream).  Also converted many character arrays to
917 // the string class.
918 //
919 // Revision 1.13  1998/09/09 16:24:04  curt
920 // Fixed a bug in the handling of exclude files which was causing
921 // a crash by calling fclose() on an invalid file handle.
922 //
923 // Revision 1.12  1998/08/24 20:03:31  curt
924 // Eliminated a possible memory overrun error.
925 // Use the proper free() rather than the incorrect delete().
926 //
927 // Revision 1.11  1998/07/20 12:46:11  curt
928 // When outputing to a .node file, first check for an optional
929 // "index.node.ex" file in case there is a .poly file to go along with this
930 // node file.  Include these nodes first since they are referenced by position
931 // from the .poly file.  This is my first pass at adding an area "cutout"
932 // feature to the terrain generation pipeline.
933 //
934 // Revision 1.10  1998/07/13 20:58:02  curt
935 // .
936 //
937 // Revision 1.9  1998/07/13 15:29:49  curt
938 // Added #ifdef HAVE_CONFIG_H
939 //
940 // Revision 1.8  1998/07/04 00:47:18  curt
941 // typedef'd struct fgBUCKET.
942 //
943 // Revision 1.7  1998/06/05 18:14:39  curt
944 // Abort out early when reading the "A" record if it doesn't look like
945 // a proper DEM file.
946 //
947 // Revision 1.6  1998/05/02 01:49:21  curt
948 // Fixed a bug where the wrong variable was being initialized.
949 //
950 // Revision 1.5  1998/04/25 15:00:32  curt
951 // Changed "r" to "rb" in gzopen() options.  This fixes bad behavior in win32.
952 //
953 // Revision 1.4  1998/04/22 13:14:46  curt
954 // Fixed a bug in zlib usage.
955 //
956 // Revision 1.3  1998/04/18 03:53:05  curt
957 // Added zlib support.
958 //
959 // Revision 1.2  1998/04/14 02:43:27  curt
960 // Used "new" to auto-allocate large DEM parsing arrays in class constructor.
961 //
962 // Revision 1.1  1998/04/08 22:57:22  curt
963 // Adopted Gnu automake/autoconf system.
964 //
965 // Revision 1.3  1998/04/06 21:09:41  curt
966 // Additional win32 support.
967 // Fixed a bad bug in dem file parsing that was causing the output to be
968 // flipped about x = y.
969 //
970 // Revision 1.2  1998/03/23 20:35:41  curt
971 // Updated to use FG_EPSILON
972 //
973 // Revision 1.1  1998/03/19 02:54:47  curt
974 // Reorganized into a class lib called fgDEM.
975 //
976 // Revision 1.1  1998/03/19 01:46:28  curt
977 // Initial revision.
978 //