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