]> git.mxchange.org Git - flightgear.git/blob - Array/array.cxx
Removed forced -g compile flag.
[flightgear.git] / Array / array.cxx
1 // array.cxx -- Array management class
2 //
3 // Written by Curtis Olson, started March 1998.
4 //
5 // Copyright (C) 1998 - 1999  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 // #ifdef HAVE_SYS_STAT_H
37 // #  include <sys/stat.h> // stat()
38 // #endif
39 // #ifdef FG_HAVE_STD_INCLUDES
40 // #  include <cerrno>
41 // #else
42 // #  include <errno.h>
43 // #endif
44 // #ifdef HAVE_UNISTD_H
45 // # include <unistd.h>   // stat()
46 // #endif
47
48 #include STL_STRING
49
50 #include <Include/fg_constants.h>
51 #include <Misc/fgstream.hxx>
52 #include <Misc/strutils.hxx>
53 #include <Math/leastsqs.hxx>
54
55 #include "array.hxx"
56
57 FG_USING_STD(string);
58
59
60 FGArray::FGArray( void ) {
61     // cout << "class FGArray CONstructor called." << endl;
62     in_data = new float[ARRAY_SIZE_1][ARRAY_SIZE_1];
63     out_data = new float[ARRAY_SIZE_1][ARRAY_SIZE_1];
64 }
65
66
67 FGArray::FGArray( const string &file ) {
68     // cout << "class FGArray CONstructor called." << endl;
69     in_data = new float[ARRAY_SIZE_1][ARRAY_SIZE_1];
70     out_data = new float[ARRAY_SIZE_1][ARRAY_SIZE_1];
71
72     FGArray::open(file);
73 }
74
75
76 // open an Array file
77 int
78 FGArray::open( const string& file ) {
79     // open input file (or read from stdin)
80     if ( file ==  "-" ) {
81         cout << "  Opening array data pipe from stdin" << endl;
82         // fd = stdin;
83         // fd = gzdopen(STDIN_FILENO, "r");
84         cout << "  Not yet ported ..." << endl;
85         return 0;
86     } else {
87         in = new fg_gzifstream( file );
88         if ( !(*in) ) {
89             cout << "  Cannot open " << file << endl;
90             return 0;
91         }
92         cout << "  Opening array data file: " << file << endl;
93     }
94
95     return 1;
96 }
97
98
99 // close an Array file
100 int
101 FGArray::close() {
102     // the fg_gzifstream doesn't seem to have a close()
103
104     delete in;
105
106     return 1;
107 }
108
109
110 // parse Array file
111 int
112 FGArray::parse() {
113     *in >> originx >> originy;
114     *in >> cols >> col_step;
115     *in >> rows >> row_step;
116
117     cout << "    origin  = " << originx << "  " << originy << endl;
118     cout << "    cols = " << cols << "  rows = " << rows << endl;
119     cout << "    col_step = " << col_step << "  row_step = " << row_step <<endl;
120
121     for ( int i = 0; i < cols; i++ ) {
122         for ( int j = 0; j < rows; j++ ) {
123             *in >> in_data[i][j];
124         }
125     }
126
127     cout << "    Done parsing\n";
128
129     return 1;
130 }
131
132
133 // Initialize output mesh structure
134 void FGArray::outputmesh_init( void ) {
135     int i, j;
136     
137     for ( j = 0; j < ARRAY_SIZE_1; j++ ) {
138         for ( i = 0; i < ARRAY_SIZE_1; i++ ) {
139             out_data[i][j] = -9999.0;
140         }
141     }
142 }
143
144
145 // Get the value of a mesh node
146 double FGArray::outputmesh_get_pt( int i, int j ) {
147     return ( out_data[i][j] );
148 }
149
150
151 // Set the value of a mesh node
152 void FGArray::outputmesh_set_pt( int i, int j, double value ) {
153     // cout << "Setting data[" << i << "][" << j << "] = " << value << endl;
154    out_data[i][j] = value;
155 }
156
157
158 // Use least squares to fit a simpler data set to dem data
159 void FGArray::fit( double error ) {
160     double x[ARRAY_SIZE_1], y[ARRAY_SIZE_1];
161     double m, b, max_error, error_sq;
162     double x1, y1;
163     // double ave_error;
164     double cury, lasty;
165     int n, row, start, end;
166     int colmin, colmax, rowmin, rowmax;
167     bool good_fit;
168     // FILE *dem, *fit, *fit1;
169
170     error_sq = error * error;
171
172     cout << "  Initializing output mesh structure" << endl;
173     outputmesh_init();
174
175     // determine dimensions
176     colmin = 0;
177     colmax = cols;
178     rowmin = 0;
179     rowmax = rows;
180     cout << "  Fitting region = " << colmin << "," << rowmin << " to " 
181          << colmax << "," << rowmax << endl;;
182     
183     // include the corners explicitly
184     outputmesh_set_pt(colmin, rowmin, in_data[colmin][rowmin]);
185     outputmesh_set_pt(colmin, rowmax, in_data[colmin][rowmax]);
186     outputmesh_set_pt(colmax, rowmax, in_data[colmax][rowmax]);
187     outputmesh_set_pt(colmax, rowmin, in_data[colmax][rowmin]);
188
189     cout << "  Beginning best fit procedure" << endl;
190     lasty = 0;
191
192     for ( row = rowmin; row < rowmax; row++ ) {
193         // fit  = fopen("fit.dat",  "w");
194         // fit1 = fopen("fit1.dat", "w");
195
196         start = colmin;
197
198         // cout << "    fitting row = " << row << endl;
199
200         while ( start < colmax - 1 ) {
201             end = start + 1;
202             good_fit = true;
203
204             x[0] = start * col_step;
205             y[0] = in_data[start][row];
206
207             x[1] = end * col_step;
208             y[1] = in_data[end][row];
209
210             n = 2;
211
212             // cout << "Least square of first 2 points" << endl;
213             least_squares(x, y, n, &m, &b);
214
215             end++;
216
217             while ( (end < colmax) && good_fit ) {
218                 ++n;
219                 // cout << "Least square of first " << n << " points" << endl;
220                 x[n-1] = x1 = end * col_step;
221                 y[n-1] = y1 = in_data[end][row];
222                 least_squares_update(x1, y1, &m, &b);
223                 // ave_error = least_squares_error(x, y, n, m, b);
224                 max_error = least_squares_max_error(x, y, n, m, b);
225
226                 /*
227                 printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
228                 start, end, ave_error, max_error, m, b);
229                 
230                 f = fopen("gnuplot.dat", "w");
231                 for ( j = 0; j <= end; j++) {
232                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
233                             in_data[row][j]);
234                 }
235                 for ( j = start; j <= end; j++) {
236                     fprintf(f, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
237                             in_data[row][j]);
238                 }
239                 fclose(f);
240
241                 printf("Please hit return: "); gets(junk);
242                 */
243
244                 if ( max_error > error_sq ) {
245                     good_fit = false;
246                 }
247                 
248                 end++;
249             }
250
251             if ( !good_fit ) {
252                 // error exceeded the threshold, back up
253                 end -= 2;  // back "end" up to the last good enough fit
254                 n--;       // back "n" up appropriately too
255             } else {
256                 // we popped out of the above loop while still within
257                 // the error threshold, so we must be at the end of
258                 // the data set
259                 end--;
260             }
261             
262             least_squares(x, y, n, &m, &b);
263             // ave_error = least_squares_error(x, y, n, m, b);
264             max_error = least_squares_max_error(x, y, n, m, b);
265
266             /*
267             printf("\n");
268             printf("%d - %d  ave error = %.2f  max error = %.2f  y = %.2f*x + %.2f\n", 
269                    start, end, ave_error, max_error, m, b);
270             printf("\n");
271
272             fprintf(fit1, "%.2f %.2f\n", x[0], m * x[0] + b);
273             fprintf(fit1, "%.2f %.2f\n", x[end-start], m * x[end-start] + b);
274             */
275
276             if ( start > colmin ) {
277                 // skip this for the first line segment
278                 cury = m * x[0] + b;
279                 outputmesh_set_pt(start, row, (lasty + cury) / 2);
280                 // fprintf(fit, "%.2f %.2f\n", x[0], (lasty + cury) / 2);
281             }
282
283             lasty = m * x[end-start] + b;
284             start = end;
285         }
286
287         /*
288         fclose(fit);
289         fclose(fit1);
290
291         dem = fopen("gnuplot.dat", "w");
292         for ( j = 0; j < ARRAY_SIZE_1; j++) {
293             fprintf(dem, "%.2f %.2f\n", 0.0 + ( j * col_step ), 
294                     in_data[j][row]);
295         } 
296         fclose(dem);
297         */
298
299         // NOTICE, this is for testing only.  This instance of
300         // output_nodes should be removed.  It should be called only
301         // once at the end once all the nodes have been generated.
302         // newmesh_output_nodes(&nm, "mesh.node");
303         // printf("Please hit return: "); gets(junk);
304     }
305
306     // outputmesh_output_nodes(fg_root, p);
307 }
308
309
310 // return the current altitude based on grid data.  We should rewrite
311 // this to interpolate exact values, but for now this is good enough
312 double FGArray::interpolate_altitude( double lon, double lat ) {
313     // we expect incoming (lon,lat) to be in arcsec for now
314
315     double xlocal, ylocal, dx, dy, zA, zB, elev;
316     int x1, x2, x3, y1, y2, y3;
317     float z1, z2, z3;
318     int xindex, yindex;
319
320     /* determine if we are in the lower triangle or the upper triangle 
321        ______
322        |   /|
323        |  / |
324        | /  |
325        |/   |
326        ------
327
328        then calculate our end points
329      */
330
331     xlocal = (lon - originx) / col_step;
332     ylocal = (lat - originy) / row_step;
333
334     xindex = (int)(xlocal);
335     yindex = (int)(ylocal);
336
337     // printf("xindex = %d  yindex = %d\n", xindex, yindex);
338
339     if ( xindex + 1 == cols ) {
340         xindex--;
341     }
342
343     if ( yindex + 1 == rows ) {
344         yindex--;
345     }
346
347     if ( (xindex < 0) || (xindex + 1 >= cols) ||
348          (yindex < 0) || (yindex + 1 >= rows) ) {
349         cout << "WARNING: Attempt to interpolate value outside of array!!!" 
350              << endl;
351         return(-9999);
352     }
353
354     dx = xlocal - xindex;
355     dy = ylocal - yindex;
356
357     if ( dx > dy ) {
358         // lower triangle
359         // printf("  Lower triangle\n");
360
361         x1 = xindex; 
362         y1 = yindex; 
363         z1 = in_data[x1][y1];
364
365         x2 = xindex + 1; 
366         y2 = yindex; 
367         z2 = in_data[x2][y2];
368                                   
369         x3 = xindex + 1; 
370         y3 = yindex + 1; 
371         z3 = in_data[x3][y3];
372
373         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
374         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
375         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
376         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
377
378         zA = dx * (z2 - z1) + z1;
379         zB = dx * (z3 - z1) + z1;
380         
381         // printf("  zA = %.2f  zB = %.2f\n", zA, zB);
382
383         if ( dx > FG_EPSILON ) {
384             elev = dy * (zB - zA) / dx + zA;
385         } else {
386             elev = zA;
387         }
388     } else {
389         // upper triangle
390         // printf("  Upper triangle\n");
391
392         x1 = xindex; 
393         y1 = yindex; 
394         z1 = in_data[x1][y1];
395
396         x2 = xindex; 
397         y2 = yindex + 1; 
398         z2 = in_data[x2][y2];
399                                   
400         x3 = xindex + 1; 
401         y3 = yindex + 1; 
402         z3 = in_data[x3][y3];
403
404         // printf("  dx = %.2f  dy = %.2f\n", dx, dy);
405         // printf("  (x1,y1,z1) = (%d,%d,%d)\n", x1, y1, z1);
406         // printf("  (x2,y2,z2) = (%d,%d,%d)\n", x2, y2, z2);
407         // printf("  (x3,y3,z3) = (%d,%d,%d)\n", x3, y3, z3);
408  
409         zA = dy * (z2 - z1) + z1;
410         zB = dy * (z3 - z1) + z1;
411         
412         // printf("  zA = %.2f  zB = %.2f\n", zA, zB );
413         // printf("  xB - xA = %.2f\n", col_step * dy / row_step);
414
415         if ( dy > FG_EPSILON ) {
416             elev = dx * (zB - zA) / dy    + zA;
417         } else {
418             elev = zA;
419         }
420     }
421
422     return(elev);
423 }
424
425
426 #if 0
427 // Write out a node file that can be used by the "triangle" program.
428 // Check for an optional "index.node.ex" file in case there is a .poly
429 // file to go along with this node file.  Include these nodes first
430 // since they are referenced by position from the .poly file.
431 void FGArray::outputmesh_output_nodes( const string& fg_root, FGBucket& p )
432 {
433     double exnodes[MAX_EX_NODES][3];
434     struct stat stat_buf;
435     string dir;
436     char file[256], exfile[256];
437 #ifdef WIN32
438     char tmp_path[256];
439 #endif
440     string command;
441     FILE *fd;
442     long int index;
443     int colmin, colmax, rowmin, rowmax;
444     int i, j, count, excount, result;
445
446     // determine dimensions
447     colmin = p.get_x() * ( (cols - 1) / 8);
448     colmax = colmin + ( (cols - 1) / 8);
449     rowmin = p.get_y() * ( (rows - 1) / 8);
450     rowmax = rowmin + ( (rows - 1) / 8);
451     cout << "  dumping region = " << colmin << "," << rowmin << " to " <<
452         colmax << "," << rowmax << "\n";
453
454     // generate the base directory
455     string base_path = p.gen_base_path();
456     cout << "  fg_root = " << fg_root << "  Base Path = " << base_path << endl;
457     dir = fg_root + "/Scenery/" + base_path;
458     cout << "  Dir = " << dir << endl;
459     
460     // stat() directory and create if needed
461     errno = 0;
462     result = stat(dir.c_str(), &stat_buf);
463     if ( result != 0 && errno == ENOENT ) {
464         cout << "  Creating directory\n";
465
466         command = "mkdir -p " + dir + "\n";
467         system( command.c_str() );
468     } else {
469         // assume directory exists
470     }
471
472     // get index and generate output file name
473     index = p.gen_index();
474     sprintf(file, "%s/%ld.node", dir.c_str(), index);
475
476     // get (optional) extra node file name (in case there is matching
477     // .poly file.
478     strcpy(exfile, file);
479     strcat(exfile, ".ex");
480
481     // load extra nodes if they exist
482     excount = 0;
483     if ( (fd = fopen(exfile, "r")) != NULL ) {
484         int junki;
485         fscanf(fd, "%d %d %d %d", &excount, &junki, &junki, &junki);
486
487         if ( excount > MAX_EX_NODES - 1 ) {
488             printf("Error, too many 'extra' nodes, increase array size\n");
489             exit(-1);
490         } else {
491             printf("    Expecting %d 'extra' nodes\n", excount);
492         }
493
494         for ( i = 1; i <= excount; i++ ) {
495             fscanf(fd, "%d %lf %lf %lf\n", &junki, 
496                    &exnodes[i][0], &exnodes[i][1], &exnodes[i][2]);
497             printf("(extra) %d %.2f %.2f %.2f\n", 
498                     i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
499         }
500         fclose(fd);
501     }
502
503     printf("Creating node file:  %s\n", file);
504     fd = fopen(file, "w");
505
506     // first count regular nodes to generate header
507     count = 0;
508     for ( j = rowmin; j <= rowmax; j++ ) {
509         for ( i = colmin; i <= colmax; i++ ) {
510             if ( out_data[i][j] > -9000.0 ) {
511                 count++;
512             }
513         }
514         // printf("    count = %d\n", count);
515     }
516     fprintf(fd, "%d 2 1 0\n", count + excount);
517
518     // now write out extra node data
519     for ( i = 1; i <= excount; i++ ) {
520         fprintf(fd, "%d %.2f %.2f %.2f\n", 
521                 i, exnodes[i][0], exnodes[i][1], exnodes[i][2]);
522     }
523
524     // write out actual node data
525     count = excount + 1;
526     for ( j = rowmin; j <= rowmax; j++ ) {
527         for ( i = colmin; i <= colmax; i++ ) {
528             if ( out_data[i][j] > -9000.0 ) {
529                 fprintf(fd, "%d %.2f %.2f %.2f\n", 
530                         count++, 
531                         originx + (double)i * col_step, 
532                         originy + (double)j * row_step,
533                         out_data[i][j]);
534             }
535         }
536         // printf("    count = %d\n", count);
537     }
538
539     fclose(fd);
540 }
541 #endif
542
543
544 FGArray::~FGArray( void ) {
545     // printf("class FGArray DEstructor called.\n");
546     delete [] in_data;
547     delete [] out_data;
548 }
549
550
551 // $Log$
552 // Revision 1.3  1999/03/17 23:48:17  curt
553 // Removed forced -g compile flag.
554 // Fixed a couple compiler warnings.
555 //
556 // Revision 1.2  1999/03/13 23:50:26  curt
557 // Tweaked output formatting a bit.
558 //
559 // Revision 1.1  1999/03/13 18:45:02  curt
560 // Initial revision. (derived from libDEM.a code.)
561 //