]> git.mxchange.org Git - flightgear.git/blob - src/Main/options.cxx
Restructure option/config handling code, to avoid multiple scans & parses for special...
[flightgear.git] / src / Main / options.cxx
1 // options.cxx -- class to handle command line options
2 //
3 // Written by Curtis Olson, started April 1998.
4 //
5 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33
34 #include <boost/foreach.hpp>
35
36 #include <math.h>               // rint()
37 #include <stdio.h>
38 #include <stdlib.h>             // atof(), atoi()
39 #include <string.h>             // strcmp()
40 #include <algorithm>
41
42 #include <iostream>
43 #include <string>
44
45 #include <simgear/math/sg_random.h>
46 #include <simgear/props/props_io.hxx>
47 #include <simgear/misc/sgstream.hxx>
48 #include <simgear/misc/sg_path.hxx>
49 #include <simgear/scene/material/mat.hxx>
50 #include <simgear/sound/soundmgr_openal.hxx>
51 #include <simgear/misc/strutils.hxx>
52 #include <Autopilot/route_mgr.hxx>
53 #include <GUI/gui.h>
54
55 #include "globals.hxx"
56 #include "fg_init.hxx"
57 #include "fg_props.hxx"
58 #include "options.hxx"
59 #include "util.hxx"
60 #include "viewmgr.hxx"
61 #include <Main/viewer.hxx>
62 #include <Environment/presets.hxx>
63
64 #include <osg/Version>
65
66 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
67 #  include <Include/version.h>
68 #  include <simgear/version.h>
69 #else
70 #  include <Include/no_version.h>
71 #endif
72
73 #ifdef __APPLE__
74 #  include <CoreFoundation/CoreFoundation.h>
75 #endif
76
77 using std::string;
78 using std::sort;
79 using std::cout;
80 using std::cerr;
81 using std::endl;
82
83 #define NEW_DEFAULT_MODEL_HZ 120
84
85 // defined in bootstrap.cxx
86 extern char *homedir;
87 extern char *hostname;
88
89 enum
90 {
91     FG_OPTIONS_OK = 0,
92     FG_OPTIONS_HELP = 1,
93     FG_OPTIONS_ERROR = 2,
94     FG_OPTIONS_EXIT = 3,
95     FG_OPTIONS_VERBOSE_HELP = 4,
96     FG_OPTIONS_SHOW_AIRCRAFT = 5,
97     FG_OPTIONS_SHOW_SOUND_DEVICES = 6
98 };
99
100 static flightgear::Options* shared_instance = NULL;
101
102 static double
103 atof( const string& str )
104 {
105     return ::atof( str.c_str() );
106 }
107
108 static int
109 atoi( const string& str )
110 {
111     return ::atoi( str.c_str() );
112 }
113
114 static int fgSetupProxy( const char *arg );
115
116 /**
117  * Set a few fail-safe default property values.
118  *
119  * These should all be set in $FG_ROOT/preferences.xml, but just
120  * in case, we provide some initial sane values here. This method
121  * should be invoked *before* reading any init files.
122  */
123 static void
124 fgSetDefaults ()
125 {
126
127                                 // Position (deliberately out of range)
128     fgSetDouble("/position/longitude-deg", 9999.0);
129     fgSetDouble("/position/latitude-deg", 9999.0);
130     fgSetDouble("/position/altitude-ft", -9999.0);
131
132                                 // Orientation
133     fgSetDouble("/orientation/heading-deg", 9999.0);
134     fgSetDouble("/orientation/roll-deg", 0.0);
135     fgSetDouble("/orientation/pitch-deg", 0.424);
136
137                                 // Velocities
138     fgSetDouble("/velocities/uBody-fps", 0.0);
139     fgSetDouble("/velocities/vBody-fps", 0.0);
140     fgSetDouble("/velocities/wBody-fps", 0.0);
141     fgSetDouble("/velocities/speed-north-fps", 0.0);
142     fgSetDouble("/velocities/speed-east-fps", 0.0);
143     fgSetDouble("/velocities/speed-down-fps", 0.0);
144     fgSetDouble("/velocities/airspeed-kt", 0.0);
145     fgSetDouble("/velocities/mach", 0.0);
146
147                                 // Presets
148     fgSetDouble("/sim/presets/longitude-deg", 9999.0);
149     fgSetDouble("/sim/presets/latitude-deg", 9999.0);
150     fgSetDouble("/sim/presets/altitude-ft", -9999.0);
151
152     fgSetDouble("/sim/presets/heading-deg", 9999.0);
153     fgSetDouble("/sim/presets/roll-deg", 0.0);
154     fgSetDouble("/sim/presets/pitch-deg", 0.424);
155
156     fgSetString("/sim/presets/speed-set", "knots");
157     fgSetDouble("/sim/presets/airspeed-kt", 0.0);
158     fgSetDouble("/sim/presets/mach", 0.0);
159     fgSetDouble("/sim/presets/uBody-fps", 0.0);
160     fgSetDouble("/sim/presets/vBody-fps", 0.0);
161     fgSetDouble("/sim/presets/wBody-fps", 0.0);
162     fgSetDouble("/sim/presets/speed-north-fps", 0.0);
163     fgSetDouble("/sim/presets/speed-east-fps", 0.0);
164     fgSetDouble("/sim/presets/speed-down-fps", 0.0);
165
166     fgSetBool("/sim/presets/onground", true);
167     fgSetBool("/sim/presets/trim", false);
168
169                                 // Miscellaneous
170     fgSetBool("/sim/startup/game-mode", false);
171     fgSetBool("/sim/startup/splash-screen", true);
172     fgSetBool("/sim/startup/intro-music", true);
173     // we want mouse-pointer to have an undefined value if nothing is
174     // specified so we can do the right thing for voodoo-1/2 cards.
175     // fgSetString("/sim/startup/mouse-pointer", "disabled");
176     fgSetString("/sim/control-mode", "joystick");
177     fgSetBool("/sim/auto-coordination", false);
178 #if defined(WIN32)
179     fgSetString("/sim/startup/browser-app", "webrun.bat");
180 #elif defined(__APPLE__)
181     fgSetString("/sim/startup/browser-app", "open");
182 #elif defined(sgi)
183     fgSetString("/sim/startup/browser-app", "launchWebJumper");
184 #else
185     envp = ::getenv( "WEBBROWSER" );
186     if (!envp) envp = "netscape";
187     fgSetString("/sim/startup/browser-app", envp);
188 #endif
189     fgSetString("/sim/logging/priority", "alert");
190
191                                 // Features
192     fgSetBool("/sim/hud/color/antialiased", false);
193     fgSetBool("/sim/hud/enable3d[1]", true);
194     fgSetBool("/sim/hud/visibility[1]", false);
195     fgSetBool("/sim/panel/visibility", true);
196     fgSetBool("/sim/sound/enabled", true);
197     fgSetBool("/sim/sound/working", true);
198
199                                 // Flight Model options
200     fgSetString("/sim/flight-model", "jsb");
201     fgSetString("/sim/aero", "c172");
202     fgSetInt("/sim/model-hz", NEW_DEFAULT_MODEL_HZ);
203     fgSetInt("/sim/speed-up", 1);
204
205                                 // Rendering options
206     fgSetString("/sim/rendering/fog", "nicest");
207     fgSetBool("/environment/clouds/status", true);
208     fgSetBool("/sim/startup/fullscreen", false);
209     fgSetBool("/sim/rendering/shading", true);
210     fgSetBool("/sim/rendering/skyblend", true);
211     fgSetBool("/sim/rendering/textures", true);
212     fgTie( "/sim/rendering/filtering", SGGetTextureFilter, SGSetTextureFilter, false);
213     fgSetInt("/sim/rendering/filtering", 1);
214     fgSetBool("/sim/rendering/wireframe", false);
215     fgSetBool("/sim/rendering/horizon-effect", false);
216     fgSetBool("/sim/rendering/enhanced-lighting", false);
217     fgSetBool("/sim/rendering/distance-attenuation", false);
218     fgSetBool("/sim/rendering/specular-highlight", true);
219     fgSetString("/sim/rendering/materials-file", "materials.xml");
220     fgSetInt("/sim/startup/xsize", 800);
221     fgSetInt("/sim/startup/ysize", 600);
222     fgSetInt("/sim/rendering/bits-per-pixel", 16);
223     fgSetString("/sim/view-mode", "pilot");
224     fgSetDouble("/sim/current-view/heading-offset-deg", 0);
225
226                                 // HUD options
227     fgSetString("/sim/startup/units", "feet");
228     fgSetString("/sim/hud/frame-stat-type", "tris");
229
230                                 // Time options
231     fgSetInt("/sim/startup/time-offset", 0);
232     fgSetString("/sim/startup/time-offset-type", "system-offset");
233     fgSetLong("/sim/time/cur-time-override", 0);
234
235                                 // Freeze options
236     fgSetBool("/sim/freeze/master", false);
237     fgSetBool("/sim/freeze/position", false);
238     fgSetBool("/sim/freeze/clock", false);
239     fgSetBool("/sim/freeze/fuel", false);
240
241     fgSetString("/sim/multiplay/callsign", "callsign");
242     fgSetString("/sim/multiplay/rxhost", "");
243     fgSetString("/sim/multiplay/txhost", "");
244     fgSetInt("/sim/multiplay/rxport", 0);
245     fgSetInt("/sim/multiplay/txport", 0);
246     
247     fgSetString("/sim/version/flightgear", FLIGHTGEAR_VERSION);
248     fgSetString("/sim/version/simgear", SG_STRINGIZE(SIMGEAR_VERSION));
249     fgSetString("/sim/version/openscenegraph", osgGetVersion());
250     fgSetString("/sim/version/revision", REVISION);
251     fgSetInt("/sim/version/build-number", HUDSON_BUILD_NUMBER);
252     fgSetString("/sim/version/build-id", HUDSON_BUILD_ID);
253   
254   char* envp = ::getenv( "http_proxy" );
255     if( envp != NULL )
256       fgSetupProxy( envp );
257 }
258
259 static bool
260 parse_wind (const string &wind, double * min_hdg, double * max_hdg,
261             double * speed, double * gust)
262 {
263   string::size_type pos = wind.find('@');
264   if (pos == string::npos)
265     return false;
266   string dir = wind.substr(0, pos);
267   string spd = wind.substr(pos+1);
268   pos = dir.find(':');
269   if (pos == string::npos) {
270     *min_hdg = *max_hdg = atof(dir.c_str());
271   } else {
272     *min_hdg = atof(dir.substr(0,pos).c_str());
273     *max_hdg = atof(dir.substr(pos+1).c_str());
274   }
275   pos = spd.find(':');
276   if (pos == string::npos) {
277     *speed = *gust = atof(spd.c_str());
278   } else {
279     *speed = atof(spd.substr(0,pos).c_str());
280     *gust = atof(spd.substr(pos+1).c_str());
281   }
282   return true;
283 }
284
285 // parse a time string ([+/-]%f[:%f[:%f]]) into hours
286 static double
287 parse_time(const string& time_in) {
288     char *time_str, num[256];
289     double hours, minutes, seconds;
290     double result = 0.0;
291     int sign = 1;
292     int i;
293
294     time_str = (char *)time_in.c_str();
295
296     // printf("parse_time(): %s\n", time_str);
297
298     // check for sign
299     if ( strlen(time_str) ) {
300         if ( time_str[0] == '+' ) {
301             sign = 1;
302             time_str++;
303         } else if ( time_str[0] == '-' ) {
304             sign = -1;
305             time_str++;
306         }
307     }
308     // printf("sign = %d\n", sign);
309
310     // get hours
311     if ( strlen(time_str) ) {
312         i = 0;
313         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
314             num[i] = time_str[0];
315             time_str++;
316             i++;
317         }
318         if ( time_str[0] == ':' ) {
319             time_str++;
320         }
321         num[i] = '\0';
322         hours = atof(num);
323         // printf("hours = %.2lf\n", hours);
324
325         result += hours;
326     }
327
328     // get minutes
329     if ( strlen(time_str) ) {
330         i = 0;
331         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
332             num[i] = time_str[0];
333             time_str++;
334             i++;
335         }
336         if ( time_str[0] == ':' ) {
337             time_str++;
338         }
339         num[i] = '\0';
340         minutes = atof(num);
341         // printf("minutes = %.2lf\n", minutes);
342
343         result += minutes / 60.0;
344     }
345
346     // get seconds
347     if ( strlen(time_str) ) {
348         i = 0;
349         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
350             num[i] = time_str[0];
351             time_str++;
352             i++;
353         }
354         num[i] = '\0';
355         seconds = atof(num);
356         // printf("seconds = %.2lf\n", seconds);
357
358         result += seconds / 3600.0;
359     }
360
361     SG_LOG( SG_GENERAL, SG_INFO, " parse_time() = " << sign * result );
362
363     return(sign * result);
364 }
365
366
367 // parse a date string (yyyy:mm:dd:hh:mm:ss) into a time_t (seconds)
368 static long int
369 parse_date( const string& date)
370 {
371     struct tm gmt;
372     char * date_str, num[256];
373     int i;
374     // initialize to zero
375     gmt.tm_sec = 0;
376     gmt.tm_min = 0;
377     gmt.tm_hour = 0;
378     gmt.tm_mday = 0;
379     gmt.tm_mon = 0;
380     gmt.tm_year = 0;
381     gmt.tm_isdst = 0; // ignore daylight savings time for the moment
382     date_str = (char *)date.c_str();
383     // get year
384     if ( strlen(date_str) ) {
385         i = 0;
386         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
387             num[i] = date_str[0];
388             date_str++;
389             i++;
390         }
391         if ( date_str[0] == ':' ) {
392             date_str++;
393         }
394         num[i] = '\0';
395         gmt.tm_year = atoi(num) - 1900;
396     }
397     // get month
398     if ( strlen(date_str) ) {
399         i = 0;
400         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
401             num[i] = date_str[0];
402             date_str++;
403             i++;
404         }
405         if ( date_str[0] == ':' ) {
406             date_str++;
407         }
408         num[i] = '\0';
409         gmt.tm_mon = atoi(num) -1;
410     }
411     // get day
412     if ( strlen(date_str) ) {
413         i = 0;
414         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
415             num[i] = date_str[0];
416             date_str++;
417             i++;
418         }
419         if ( date_str[0] == ':' ) {
420             date_str++;
421         }
422         num[i] = '\0';
423         gmt.tm_mday = atoi(num);
424     }
425     // get hour
426     if ( strlen(date_str) ) {
427         i = 0;
428         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
429             num[i] = date_str[0];
430             date_str++;
431             i++;
432         }
433         if ( date_str[0] == ':' ) {
434             date_str++;
435         }
436         num[i] = '\0';
437         gmt.tm_hour = atoi(num);
438     }
439     // get minute
440     if ( strlen(date_str) ) {
441         i = 0;
442         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
443             num[i] = date_str[0];
444             date_str++;
445             i++;
446         }
447         if ( date_str[0] == ':' ) {
448             date_str++;
449         }
450         num[i] = '\0';
451         gmt.tm_min = atoi(num);
452     }
453     // get second
454     if ( strlen(date_str) ) {
455         i = 0;
456         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
457             num[i] = date_str[0];
458             date_str++;
459             i++;
460         }
461         if ( date_str[0] == ':' ) {
462             date_str++;
463         }
464         num[i] = '\0';
465         gmt.tm_sec = atoi(num);
466     }
467     time_t theTime = sgTimeGetGMT( gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
468                                    gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
469     //printf ("Date is %s\n", ctime(&theTime));
470     //printf ("in seconds that is %d\n", theTime);
471     //exit(1);
472     return (theTime);
473 }
474
475
476 // parse angle in the form of [+/-]ddd:mm:ss into degrees
477 static double
478 parse_degree( const string& degree_str) {
479     double result = parse_time( degree_str );
480
481     // printf("Degree = %.4f\n", result);
482
483     return(result);
484 }
485
486
487 // parse time offset string into seconds
488 static int
489 parse_time_offset( const string& time_str) {
490     int result;
491
492     // printf("time offset = %s\n", time_str);
493
494 #ifdef HAVE_RINT
495     result = (int)rint(parse_time(time_str) * 3600.0);
496 #else
497     result = (int)(parse_time(time_str) * 3600.0);
498 #endif
499
500     // printf("parse_time_offset(): %d\n", result);
501
502     return( result );
503 }
504
505
506 // Parse --fov=x.xx type option
507 static double
508 parse_fov( const string& arg ) {
509     double fov = atof(arg);
510
511     if ( fov < FG_FOV_MIN ) { fov = FG_FOV_MIN; }
512     if ( fov > FG_FOV_MAX ) { fov = FG_FOV_MAX; }
513
514     fgSetDouble("/sim/view[0]/config/default-field-of-view-deg", fov);
515
516     // printf("parse_fov(): result = %.4f\n", fov);
517
518     return fov;
519 }
520
521
522 // Parse I/O channel option
523 //
524 // Format is "--protocol=medium,direction,hz,medium_options,..."
525 //
526 //   protocol = { native, nmea, garmin, AV400, AV400Sim, fgfs, rul, pve, etc. }
527 //   medium = { serial, socket, file, etc. }
528 //   direction = { in, out, bi }
529 //   hz = number of times to process channel per second (floating
530 //        point values are ok.
531 //
532 // Serial example "--nmea=serial,dir,hz,device,baud" where
533 //
534 //  device = OS device name of serial line to be open()'ed
535 //  baud = {300, 1200, 2400, ..., 230400}
536 //
537 // Socket exacmple "--native=socket,dir,hz,machine,port,style" where
538 //
539 //  machine = machine name or ip address if client (leave empty if server)
540 //  port = port, leave empty to let system choose
541 //  style = tcp or udp
542 //
543 // File example "--garmin=file,dir,hz,filename" where
544 //
545 //  filename = file system file name
546
547 static bool
548 add_channel( const string& type, const string& channel_str ) {
549     // This check is neccessary to prevent fgviewer from segfaulting when given
550     // weird options. (It doesn't run the full initailization)
551     if(!globals->get_channel_options_list())
552     {
553         SG_LOG(SG_GENERAL, SG_ALERT, "Option " << type << "=" << channel_str
554                                      << " ignored.");
555         return false;
556     }
557     SG_LOG(SG_GENERAL, SG_INFO, "Channel string = " << channel_str );
558     globals->get_channel_options_list()->push_back( type + "," + channel_str );
559     return true;
560 }
561
562 static int
563 fgOptLanguage( const char *arg )
564 {
565     globals->set_locale( fgInitLocale( arg ) );
566     return FG_OPTIONS_OK;
567 }
568
569 static void
570 clearLocation ()
571 {
572     fgSetString("/sim/presets/airport-id", "");
573     fgSetString("/sim/presets/vor-id", "");
574     fgSetString("/sim/presets/ndb-id", "");
575     fgSetString("/sim/presets/carrier", "");
576     fgSetString("/sim/presets/parkpos", "");
577     fgSetString("/sim/presets/fix", "");
578 }
579
580 static int
581 fgOptVOR( const char * arg )
582 {
583     clearLocation();
584     fgSetString("/sim/presets/vor-id", arg);
585     return FG_OPTIONS_OK;
586 }
587
588 static int
589 fgOptNDB( const char * arg )
590 {
591     clearLocation();
592     fgSetString("/sim/presets/ndb-id", arg);
593     return FG_OPTIONS_OK;
594 }
595
596 static int
597 fgOptCarrier( const char * arg )
598 {
599     clearLocation();
600     fgSetString("/sim/presets/carrier", arg);
601     return FG_OPTIONS_OK;
602 }
603
604 static int
605 fgOptParkpos( const char * arg )
606 {
607     fgSetString("/sim/presets/parkpos", arg);
608     return FG_OPTIONS_OK;
609 }
610
611 static int
612 fgOptFIX( const char * arg )
613 {
614     clearLocation();
615     fgSetString("/sim/presets/fix", arg);
616     return FG_OPTIONS_OK;
617 }
618
619 static int
620 fgOptLon( const char *arg )
621 {
622     clearLocation();
623     fgSetDouble("/sim/presets/longitude-deg", parse_degree( arg ));
624     fgSetDouble("/position/longitude-deg", parse_degree( arg ));
625     return FG_OPTIONS_OK;
626 }
627
628 static int
629 fgOptLat( const char *arg )
630 {
631     clearLocation();
632     fgSetDouble("/sim/presets/latitude-deg", parse_degree( arg ));
633     fgSetDouble("/position/latitude-deg", parse_degree( arg ));
634     return FG_OPTIONS_OK;
635 }
636
637 static int
638 fgOptAltitude( const char *arg )
639 {
640     fgSetBool("/sim/presets/onground", false);
641     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
642         fgSetDouble("/sim/presets/altitude-ft", atof( arg ));
643     else
644         fgSetDouble("/sim/presets/altitude-ft",
645                     atof( arg ) * SG_METER_TO_FEET);
646     return FG_OPTIONS_OK;
647 }
648
649 static int
650 fgOptUBody( const char *arg )
651 {
652     fgSetString("/sim/presets/speed-set", "UVW");
653     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
654         fgSetDouble("/sim/presets/uBody-fps", atof( arg ));
655     else
656         fgSetDouble("/sim/presets/uBody-fps",
657                     atof( arg ) * SG_METER_TO_FEET);
658     return FG_OPTIONS_OK;
659 }
660
661 static int
662 fgOptVBody( const char *arg )
663 {
664     fgSetString("/sim/presets/speed-set", "UVW");
665     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
666         fgSetDouble("/sim/presets/vBody-fps", atof( arg ));
667     else
668         fgSetDouble("/sim/presets/vBody-fps",
669                             atof( arg ) * SG_METER_TO_FEET);
670     return FG_OPTIONS_OK;
671 }
672
673 static int
674 fgOptWBody( const char *arg )
675 {
676     fgSetString("/sim/presets/speed-set", "UVW");
677     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
678         fgSetDouble("/sim/presets/wBody-fps", atof(arg));
679     else
680         fgSetDouble("/sim/presets/wBody-fps",
681                             atof(arg) * SG_METER_TO_FEET);
682     return FG_OPTIONS_OK;
683 }
684
685 static int
686 fgOptVNorth( const char *arg )
687 {
688     fgSetString("/sim/presets/speed-set", "NED");
689     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
690         fgSetDouble("/sim/presets/speed-north-fps", atof( arg ));
691     else
692         fgSetDouble("/sim/presets/speed-north-fps",
693                             atof( arg ) * SG_METER_TO_FEET);
694     return FG_OPTIONS_OK;
695 }
696
697 static int
698 fgOptVEast( const char *arg )
699 {
700     fgSetString("/sim/presets/speed-set", "NED");
701     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
702         fgSetDouble("/sim/presets/speed-east-fps", atof(arg));
703     else
704         fgSetDouble("/sim/presets/speed-east-fps",
705                     atof(arg) * SG_METER_TO_FEET);
706     return FG_OPTIONS_OK;
707 }
708
709 static int
710 fgOptVDown( const char *arg )
711 {
712     fgSetString("/sim/presets/speed-set", "NED");
713     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
714         fgSetDouble("/sim/presets/speed-down-fps", atof(arg));
715     else
716         fgSetDouble("/sim/presets/speed-down-fps",
717                             atof(arg) * SG_METER_TO_FEET);
718     return FG_OPTIONS_OK;
719 }
720
721 static int
722 fgOptVc( const char *arg )
723 {
724     // fgSetString("/sim/presets/speed-set", "knots");
725     // fgSetDouble("/velocities/airspeed-kt", atof(arg.substr(5)));
726     fgSetString("/sim/presets/speed-set", "knots");
727     fgSetDouble("/sim/presets/airspeed-kt", atof(arg));
728     return FG_OPTIONS_OK;
729 }
730
731 static int
732 fgOptMach( const char *arg )
733 {
734     fgSetString("/sim/presets/speed-set", "mach");
735     fgSetDouble("/sim/presets/mach", atof(arg));
736     return FG_OPTIONS_OK;
737 }
738
739 static int
740 fgOptRoc( const char *arg )
741 {
742     fgSetDouble("/velocities/vertical-speed-fps", atof(arg)/60);
743     return FG_OPTIONS_OK;
744 }
745
746 static int
747 fgOptFgScenery( const char *arg )
748 {
749     globals->append_fg_scenery(arg);
750     return FG_OPTIONS_OK;
751 }
752
753 static int
754 fgOptFov( const char *arg )
755 {
756     parse_fov( arg );
757     return FG_OPTIONS_OK;
758 }
759
760 static int
761 fgOptGeometry( const char *arg )
762 {
763     bool geometry_ok = true;
764     int xsize = 0, ysize = 0;
765     string geometry = arg;
766     string::size_type i = geometry.find('x');
767
768     if (i != string::npos) {
769         xsize = atoi(geometry.substr(0, i));
770         ysize = atoi(geometry.substr(i+1));
771     } else {
772         geometry_ok = false;
773     }
774
775     if ( xsize <= 0 || ysize <= 0 ) {
776         xsize = 640;
777         ysize = 480;
778         geometry_ok = false;
779     }
780
781     if ( !geometry_ok ) {
782         SG_LOG( SG_GENERAL, SG_ALERT, "Unknown geometry: " << geometry );
783         SG_LOG( SG_GENERAL, SG_ALERT,
784                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
785     } else {
786         SG_LOG( SG_GENERAL, SG_INFO,
787                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
788         fgSetInt("/sim/startup/xsize", xsize);
789         fgSetInt("/sim/startup/ysize", ysize);
790     }
791     return FG_OPTIONS_OK;
792 }
793
794 static int
795 fgOptBpp( const char *arg )
796 {
797     string bits_per_pix = arg;
798     if ( bits_per_pix == "16" ) {
799         fgSetInt("/sim/rendering/bits-per-pixel", 16);
800     } else if ( bits_per_pix == "24" ) {
801         fgSetInt("/sim/rendering/bits-per-pixel", 24);
802     } else if ( bits_per_pix == "32" ) {
803         fgSetInt("/sim/rendering/bits-per-pixel", 32);
804     } else {
805         SG_LOG(SG_GENERAL, SG_ALERT, "Unsupported bpp " << bits_per_pix);
806     }
807     return FG_OPTIONS_OK;
808 }
809
810 static int
811 fgOptTimeOffset( const char *arg )
812 {
813     fgSetInt("/sim/startup/time-offset",
814                 parse_time_offset( arg ));
815     fgSetString("/sim/startup/time-offset-type", "system-offset");
816     return FG_OPTIONS_OK;
817 }
818
819 static int
820 fgOptStartDateSys( const char *arg )
821 {
822     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
823     fgSetString("/sim/startup/time-offset-type", "system");
824     return FG_OPTIONS_OK;
825 }
826
827 static int
828 fgOptStartDateLat( const char *arg )
829 {
830     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
831     fgSetString("/sim/startup/time-offset-type", "latitude");
832     return FG_OPTIONS_OK;
833 }
834
835 static int
836 fgOptStartDateGmt( const char *arg )
837 {
838     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
839     fgSetString("/sim/startup/time-offset-type", "gmt");
840     return FG_OPTIONS_OK;
841 }
842
843 static int
844 fgSetupProxy( const char *arg )
845 {
846     string options = simgear::strutils::strip( arg );
847     string host, port, auth;
848     string::size_type pos;
849
850     // this is NURLP - NURLP is not an url parser
851     if( simgear::strutils::starts_with( options, "http://" ) )
852         options = options.substr( 7 );
853     if( simgear::strutils::ends_with( options, "/" ) )
854         options = options.substr( 0, options.length() - 1 );
855
856     host = port = auth = "";
857     if ((pos = options.find("@")) != string::npos)
858         auth = options.substr(0, pos++);
859     else
860         pos = 0;
861
862     host = options.substr(pos, options.size());
863     if ((pos = host.find(":")) != string::npos) {
864         port = host.substr(++pos, host.size());
865         host.erase(--pos, host.size());
866     }
867
868     fgSetString("/sim/presets/proxy/host", host.c_str());
869     fgSetString("/sim/presets/proxy/port", port.c_str());
870     fgSetString("/sim/presets/proxy/authentication", auth.c_str());
871
872     return FG_OPTIONS_OK;
873 }
874
875 static int
876 fgOptTraceRead( const char *arg )
877 {
878     string name = arg;
879     SG_LOG(SG_GENERAL, SG_INFO, "Tracing reads for property " << name);
880     fgGetNode(name.c_str(), true)
881         ->setAttribute(SGPropertyNode::TRACE_READ, true);
882     return FG_OPTIONS_OK;
883 }
884
885 static int
886 fgOptLogLevel( const char *arg )
887 {
888     fgSetString("/sim/logging/classes", "all");
889     fgSetString("/sim/logging/priority", arg);
890
891     string priority = arg;
892     logbuf::set_log_classes(SG_ALL);
893     if (priority == "bulk") {
894       logbuf::set_log_priority(SG_BULK);
895     } else if (priority == "debug") {
896       logbuf::set_log_priority(SG_DEBUG);
897     } else if (priority == "info") {
898       logbuf::set_log_priority(SG_INFO);
899     } else if (priority == "warn") {
900       logbuf::set_log_priority(SG_WARN);
901     } else if (priority == "alert") {
902       logbuf::set_log_priority(SG_ALERT);
903     } else {
904       SG_LOG(SG_GENERAL, SG_WARN, "Unknown logging priority " << priority);
905     }
906     SG_LOG(SG_GENERAL, SG_DEBUG, "Logging priority is " << priority);
907
908     return FG_OPTIONS_OK;
909 }
910
911
912 static int
913 fgOptTraceWrite( const char *arg )
914 {
915     string name = arg;
916     SG_LOG(SG_GENERAL, SG_INFO, "Tracing writes for property " << name);
917     fgGetNode(name.c_str(), true)
918         ->setAttribute(SGPropertyNode::TRACE_WRITE, true);
919     return FG_OPTIONS_OK;
920 }
921
922 static int
923 fgOptViewOffset( const char *arg )
924 {
925     // $$$ begin - added VS Renganathan, 14 Oct 2K
926     // for multi-window outside window imagery
927     string woffset = arg;
928     double default_view_offset = 0.0;
929     if ( woffset == "LEFT" ) {
930             default_view_offset = SGD_PI * 0.25;
931     } else if ( woffset == "RIGHT" ) {
932         default_view_offset = SGD_PI * 1.75;
933     } else if ( woffset == "CENTER" ) {
934         default_view_offset = 0.00;
935     } else {
936         default_view_offset = atof( woffset.c_str() ) * SGD_DEGREES_TO_RADIANS;
937     }
938     /* apparently not used (CLO, 11 Jun 2002)
939         FGViewer *pilot_view =
940             (FGViewer *)globals->get_viewmgr()->get_view( 0 ); */
941     // this will work without calls to the viewer...
942     fgSetDouble( "/sim/current-view/heading-offset-deg",
943                     default_view_offset  * SGD_RADIANS_TO_DEGREES );
944     // $$$ end - added VS Renganathan, 14 Oct 2K
945     return FG_OPTIONS_OK;
946 }
947
948 static int
949 fgOptVisibilityMeters( const char *arg )
950 {
951     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) );
952     return FG_OPTIONS_OK;
953 }
954
955 static int
956 fgOptVisibilityMiles( const char *arg )
957 {
958     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) * 5280.0 * SG_FEET_TO_METER );
959     return FG_OPTIONS_OK;
960 }
961
962 static int
963 fgOptRandomWind( const char *arg )
964 {
965     double min_hdg = sg_random() * 360.0;
966     double max_hdg = min_hdg + (20 - sqrt(sg_random() * 400));
967     double speed = sg_random() * sg_random() * 40;
968     double gust = speed + (10 - sqrt(sg_random() * 100));
969     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
970     return FG_OPTIONS_OK;
971 }
972
973 static int
974 fgOptWind( const char *arg )
975 {
976     double min_hdg = 0.0, max_hdg = 0.0, speed = 0.0, gust = 0.0;
977     if (!parse_wind( arg, &min_hdg, &max_hdg, &speed, &gust)) {
978         SG_LOG( SG_GENERAL, SG_ALERT, "bad wind value " << arg );
979         return FG_OPTIONS_ERROR;
980     }
981     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
982     return FG_OPTIONS_OK;
983 }
984
985 static int
986 fgOptTurbulence( const char *arg )
987 {
988     Environment::Presets::TurbulenceSingleton::instance()->preset( atof(arg) );
989     return FG_OPTIONS_OK;
990 }
991
992 static int
993 fgOptCeiling( const char *arg )
994 {
995     double elevation, thickness;
996     string spec = arg;
997     string::size_type pos = spec.find(':');
998     if (pos == string::npos) {
999         elevation = atof(spec.c_str());
1000         thickness = 2000;
1001     } else {
1002         elevation = atof(spec.substr(0, pos).c_str());
1003         thickness = atof(spec.substr(pos + 1).c_str());
1004     }
1005     Environment::Presets::CeilingSingleton::instance()->preset( elevation, thickness );
1006     return FG_OPTIONS_OK;
1007 }
1008
1009 static int
1010 fgOptWp( const char *arg )
1011 {
1012     string_list *waypoints = globals->get_initial_waypoints();
1013     if (!waypoints) {
1014         waypoints = new string_list;
1015         globals->set_initial_waypoints(waypoints);
1016     }
1017     waypoints->push_back(arg);
1018     return FG_OPTIONS_OK;
1019 }
1020
1021 static int
1022 fgOptConfig( const char *arg )
1023 {
1024     string file = arg;
1025     try {
1026         readProperties(file, globals->get_props());
1027     } catch (const sg_exception &e) {
1028         string message = "Error loading config file: ";
1029         message += e.getFormattedMessage() + e.getOrigin();
1030         SG_LOG(SG_INPUT, SG_ALERT, message);
1031         exit(2);
1032     }
1033     return FG_OPTIONS_OK;
1034 }
1035
1036 static bool
1037 parse_colon (const string &s, double * val1, double * val2)
1038 {
1039     string::size_type pos = s.find(':');
1040     if (pos == string::npos) {
1041         *val2 = atof(s);
1042         return false;
1043     } else {
1044         *val1 = atof(s.substr(0, pos).c_str());
1045         *val2 = atof(s.substr(pos+1).c_str());
1046         return true;
1047     }
1048 }
1049
1050
1051 static int
1052 fgOptFailure( const char * arg )
1053 {
1054     string a = arg;
1055     if (a == "pitot") {
1056         fgSetBool("/systems/pitot/serviceable", false);
1057     } else if (a == "static") {
1058         fgSetBool("/systems/static/serviceable", false);
1059     } else if (a == "vacuum") {
1060         fgSetBool("/systems/vacuum/serviceable", false);
1061     } else if (a == "electrical") {
1062         fgSetBool("/systems/electrical/serviceable", false);
1063     } else {
1064         SG_LOG(SG_INPUT, SG_ALERT, "Unknown failure mode: " << a);
1065         return FG_OPTIONS_ERROR;
1066     }
1067
1068     return FG_OPTIONS_OK;
1069 }
1070
1071
1072 static int
1073 fgOptNAV1( const char * arg )
1074 {
1075     double radial, freq;
1076     if (parse_colon(arg, &radial, &freq))
1077         fgSetDouble("/instrumentation/nav[0]/radials/selected-deg", radial);
1078     fgSetDouble("/instrumentation/nav[0]/frequencies/selected-mhz", freq);
1079     return FG_OPTIONS_OK;
1080 }
1081
1082 static int
1083 fgOptNAV2( const char * arg )
1084 {
1085     double radial, freq;
1086     if (parse_colon(arg, &radial, &freq))
1087         fgSetDouble("/instrumentation/nav[1]/radials/selected-deg", radial);
1088     fgSetDouble("/instrumentation/nav[1]/frequencies/selected-mhz", freq);
1089     return FG_OPTIONS_OK;
1090 }
1091
1092 static int
1093 fgOptADF1( const char * arg )
1094 {
1095     double rot, freq;
1096     if (parse_colon(arg, &rot, &freq))
1097         fgSetDouble("/instrumentation/adf[0]/rotation-deg", rot);
1098     fgSetDouble("/instrumentation/adf[0]/frequencies/selected-khz", freq);
1099     return FG_OPTIONS_OK;
1100 }
1101
1102 static int
1103 fgOptADF2( const char * arg )
1104 {
1105     double rot, freq;
1106     if (parse_colon(arg, &rot, &freq))
1107         fgSetDouble("/instrumentation/adf[1]/rotation-deg", rot);
1108     fgSetDouble("/instrumentation/adf[1]/frequencies/selected-khz", freq);
1109     return FG_OPTIONS_OK;
1110 }
1111
1112 static int
1113 fgOptDME( const char *arg )
1114 {
1115     string opt = arg;
1116     if (opt == "nav1") {
1117         fgSetInt("/instrumentation/dme/switch-position", 1);
1118         fgSetString("/instrumentation/dme/frequencies/source",
1119                     "/instrumentation/nav[0]/frequencies/selected-mhz");
1120     } else if (opt == "nav2") {
1121         fgSetInt("/instrumentation/dme/switch-position", 3);
1122         fgSetString("/instrumentation/dme/frequencies/source",
1123                     "/instrumentation/nav[1]/frequencies/selected-mhz");
1124     } else {
1125         double frequency = atof(arg);
1126         if (frequency==0.0)
1127         {
1128             SG_LOG(SG_INPUT, SG_ALERT, "Invalid DME frequency: '" << arg << "'.");
1129             return FG_OPTIONS_ERROR;
1130         }
1131         fgSetInt("/instrumentation/dme/switch-position", 2);
1132         fgSetString("/instrumentation/dme/frequencies/source",
1133                     "/instrumentation/dme/frequencies/selected-mhz");
1134         fgSetDouble("/instrumentation/dme/frequencies/selected-mhz", frequency);
1135     }
1136     return FG_OPTIONS_OK;
1137 }
1138
1139 static int
1140 fgOptLivery( const char *arg )
1141 {
1142     string opt = arg;
1143     string livery_path = "livery/" + opt;
1144     fgSetString("/sim/model/texture-path", livery_path.c_str() );
1145     return FG_OPTIONS_OK;
1146 }
1147
1148 static int
1149 fgOptScenario( const char *arg )
1150 {
1151     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1152     vector<SGPropertyNode_ptr> scenarii = ai_node->getChildren( "scenario" );
1153     int index = -1;
1154     for ( size_t i = 0; i < scenarii.size(); ++i ) {
1155         int ind = scenarii[i]->getIndex();
1156         if ( index < ind ) {
1157             index = ind;
1158         }
1159     }
1160     SGPropertyNode_ptr scenario = ai_node->getNode( "scenario", index + 1, true );
1161     scenario->setStringValue( arg );
1162     ai_node->setBoolValue( "enabled", true );
1163     return FG_OPTIONS_OK;
1164 }
1165
1166 static int
1167 fgOptNoScenarios( const char *arg )
1168 {
1169     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1170     ai_node->removeChildren("scenario",false);
1171     ai_node->setBoolValue( "enabled", false );
1172     return FG_OPTIONS_OK;
1173 }
1174
1175 static int
1176 fgOptRunway( const char *arg )
1177 {
1178     fgSetString("/sim/presets/runway", arg );
1179     fgSetBool("/sim/presets/runway-requested", true );
1180     return FG_OPTIONS_OK;
1181 }
1182
1183 static int
1184 fgOptParking( const char *arg )
1185 {
1186     cerr << "Processing argument " << arg << endl;
1187     fgSetString("/sim/presets/parking", arg );
1188     fgSetBool  ("/sim/presets/parking-requested", true );
1189     return FG_OPTIONS_OK;
1190 }
1191
1192 static int
1193 fgOptVersion( const char *arg )
1194 {
1195     cerr << "FlightGear version: " << FLIGHTGEAR_VERSION << endl;
1196     cerr << "Revision: " << REVISION << endl;
1197     cerr << "Build-Id: " << HUDSON_BUILD_ID << endl;
1198     cerr << "FG_ROOT=" << globals->get_fg_root() << endl;
1199     cerr << "FG_HOME=" << fgGetString("/sim/fg-home") << endl;
1200     cerr << "FG_SCENERY=";
1201
1202     int didsome = 0;
1203     string_list scn = globals->get_fg_scenery();
1204     for (string_list::const_iterator it = scn.begin(); it != scn.end(); it++)
1205     {
1206         if (didsome) cerr << ":";
1207         didsome++;
1208         cerr << *it;
1209     }
1210     cerr << endl;
1211     cerr << "SimGear version: " << SG_STRINGIZE(SIMGEAR_VERSION) << endl;
1212     cerr << "PLIB version: " << PLIB_VERSION << endl;
1213     return FG_OPTIONS_EXIT;
1214 }
1215
1216 static int
1217 fgOptCallSign(const char * arg)
1218 {
1219     int i;
1220     char callsign[11];
1221     strncpy(callsign,arg,10);
1222     callsign[10]=0;
1223     for (i=0;callsign[i];i++)
1224     {
1225         char c = callsign[i];
1226         if (c >= 'A' && c <= 'Z') continue;
1227         if (c >= 'a' && c <= 'z') continue;
1228         if (c >= '0' && c <= '9') continue;
1229         if (c == '-' || c == '_') continue;
1230         // convert any other illegal characters
1231         callsign[i]='-';
1232     }
1233     fgSetString("sim/multiplay/callsign", callsign );
1234     return FG_OPTIONS_OK;
1235 }
1236
1237
1238 // Set a property for the --prop: option. Syntax: --prop:[<type>:]<name>=<value>
1239 // <type> can be "double" etc. but also only the first letter "d".
1240 // Examples:  --prop:alpha=1  --prop:bool:beta=true  --prop:d:gamma=0.123
1241 static int
1242 fgOptSetProperty(const char* raw)
1243 {
1244   string arg(raw);
1245   string::size_type pos = arg.find('=');
1246   if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
1247     return FG_OPTIONS_ERROR;
1248   
1249   string name = arg.substr(0, pos);
1250   string value = arg.substr(pos + 1);
1251   string type;
1252   pos = name.find(':');
1253   
1254   if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
1255     type = name.substr(0, pos);
1256     name = name.substr(pos + 1);
1257   }
1258   SGPropertyNode *n = fgGetNode(name.c_str(), true);
1259   
1260   bool writable = n->getAttribute(SGPropertyNode::WRITE);
1261   if (!writable)
1262     n->setAttribute(SGPropertyNode::WRITE, true);
1263   
1264   bool ret = false;
1265   if (type.empty())
1266     ret = n->setUnspecifiedValue(value.c_str());
1267   else if (type == "s" || type == "string")
1268     ret = n->setStringValue(value.c_str());
1269   else if (type == "d" || type == "double")
1270     ret = n->setDoubleValue(strtod(value.c_str(), 0));
1271   else if (type == "f" || type == "float")
1272     ret = n->setFloatValue(atof(value.c_str()));
1273   else if (type == "l" || type == "long")
1274     ret =  n->setLongValue(strtol(value.c_str(), 0, 0));
1275   else if (type == "i" || type == "int")
1276     ret =  n->setIntValue(atoi(value.c_str()));
1277   else if (type == "b" || type == "bool")
1278     ret =  n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
1279   
1280   if (!writable)
1281     n->setAttribute(SGPropertyNode::WRITE, false);
1282   return ret ? FG_OPTIONS_OK : FG_OPTIONS_ERROR;
1283 }
1284
1285
1286
1287 /*
1288    option       has_param type        property         b_param s_param  func
1289
1290 where:
1291  option    : name of the option
1292  has_param : option is --name=value if true or --name if false
1293  type      : OPTION_BOOL    - property is a boolean
1294              OPTION_STRING  - property is a string
1295              OPTION_DOUBLE  - property is a double
1296              OPTION_INT     - property is an integer
1297              OPTION_CHANNEL - name of option is the name of a channel
1298              OPTION_FUNC    - the option trigger a function
1299  b_param   : if type==OPTION_BOOL,
1300              value set to the property (has_param is false for boolean)
1301  s_param   : if type==OPTION_STRING,
1302              value set to the property if has_param is false
1303  func      : function called if type==OPTION_FUNC. if has_param is true,
1304              the value is passed to the function as a string, otherwise,
1305              s_param is passed.
1306
1307     For OPTION_DOUBLE and OPTION_INT, the parameter value is converted into a
1308     double or an integer and set to the property.
1309
1310     For OPTION_CHANNEL, add_channel is called with the parameter value as the
1311     argument.
1312 */
1313
1314 enum OptionType { OPTION_BOOL = 0, OPTION_STRING, OPTION_DOUBLE, OPTION_INT, OPTION_CHANNEL, OPTION_FUNC, OPTION_IGNORE };
1315 const int OPTION_MULTI = 1 << 17;
1316
1317 struct OptionDesc {
1318     const char *option;
1319     bool has_param;
1320     int type;
1321     const char *property;
1322     bool b_param;
1323     const char *s_param;
1324     int (*func)( const char * );
1325     } fgOptionArray[] = {
1326
1327     {"language",                     true,  OPTION_FUNC,   "", false, "", fgOptLanguage },
1328     {"disable-game-mode",            false, OPTION_BOOL,   "/sim/startup/game-mode", false, "", 0 },
1329     {"enable-game-mode",             false, OPTION_BOOL,   "/sim/startup/game-mode", true, "", 0 },
1330     {"disable-splash-screen",        false, OPTION_BOOL,   "/sim/startup/splash-screen", false, "", 0 },
1331     {"enable-splash-screen",         false, OPTION_BOOL,   "/sim/startup/splash-screen", true, "", 0 },
1332     {"disable-intro-music",          false, OPTION_BOOL,   "/sim/startup/intro-music", false, "", 0 },
1333     {"enable-intro-music",           false, OPTION_BOOL,   "/sim/startup/intro-music", true, "", 0 },
1334     {"disable-mouse-pointer",        false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "disabled", 0 },
1335     {"enable-mouse-pointer",         false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "enabled", 0 },
1336     {"disable-random-objects",       false, OPTION_BOOL,   "/sim/rendering/random-objects", false, "", 0 },
1337     {"enable-random-objects",        false, OPTION_BOOL,   "/sim/rendering/random-objects", true, "", 0 },
1338     {"disable-real-weather-fetch",   false, OPTION_BOOL,   "/environment/realwx/enabled", false, "", 0 },
1339     {"enable-real-weather-fetch",    false, OPTION_BOOL,   "/environment/realwx/enabled", true,  "", 0 },
1340     {"metar",                        true,  OPTION_STRING, "/environment/metar/data", false, "", 0 },
1341     {"disable-ai-models",            false, OPTION_BOOL,   "/sim/ai/enabled", false, "", 0 },
1342     {"enable-ai-models",             false, OPTION_BOOL,   "/sim/ai/enabled", true, "", 0 },
1343     {"disable-ai-traffic",           false, OPTION_BOOL,   "/sim/traffic-manager/enabled", false, "", 0 },
1344     {"enable-ai-traffic",            false, OPTION_BOOL,   "/sim/traffic-manager/enabled", true,  "", 0 },
1345     {"disable-freeze",               false, OPTION_BOOL,   "/sim/freeze/master", false, "", 0 },
1346     {"enable-freeze",                false, OPTION_BOOL,   "/sim/freeze/master", true, "", 0 },
1347     {"disable-fuel-freeze",          false, OPTION_BOOL,   "/sim/freeze/fuel", false, "", 0 },
1348     {"enable-fuel-freeze",           false, OPTION_BOOL,   "/sim/freeze/fuel", true, "", 0 },
1349     {"disable-clock-freeze",         false, OPTION_BOOL,   "/sim/freeze/clock", false, "", 0 },
1350     {"enable-clock-freeze",          false, OPTION_BOOL,   "/sim/freeze/clock", true, "", 0 },
1351     {"disable-hud-3d",               false, OPTION_BOOL,   "/sim/hud/enable3d[1]", false, "", 0 },
1352     {"enable-hud-3d",                false, OPTION_BOOL,   "/sim/hud/enable3d[1]", true, "", 0 },
1353     {"disable-anti-alias-hud",       false, OPTION_BOOL,   "/sim/hud/color/antialiased", false, "", 0 },
1354     {"enable-anti-alias-hud",        false, OPTION_BOOL,   "/sim/hud/color/antialiased", true, "", 0 },
1355     {"control",                      true,  OPTION_STRING, "/sim/control-mode", false, "", 0 },
1356     {"disable-auto-coordination",    false, OPTION_BOOL,   "/sim/auto-coordination", false, "", 0 },
1357     {"enable-auto-coordination",     false, OPTION_BOOL,   "/sim/auto-coordination", true, "", 0 },
1358     {"browser-app",                  true,  OPTION_STRING, "/sim/startup/browser-app", false, "", 0 },
1359     {"disable-hud",                  false, OPTION_BOOL,   "/sim/hud/visibility[1]", false, "", 0 },
1360     {"enable-hud",                   false, OPTION_BOOL,   "/sim/hud/visibility[1]", true, "", 0 },
1361     {"disable-panel",                false, OPTION_BOOL,   "/sim/panel/visibility", false, "", 0 },
1362     {"enable-panel",                 false, OPTION_BOOL,   "/sim/panel/visibility", true, "", 0 },
1363     {"disable-sound",                false, OPTION_BOOL,   "/sim/sound/working", false, "", 0 },
1364     {"enable-sound",                 false, OPTION_BOOL,   "/sim/sound/working", true, "", 0 },
1365     {"sound-device",                 true,  OPTION_STRING, "/sim/sound/device-name", false, "", 0 },
1366     {"airport",                      true,  OPTION_STRING, "/sim/presets/airport-id", false, "", 0 },
1367     {"runway",                       true,  OPTION_FUNC,   "", false, "", fgOptRunway },
1368     {"vor",                          true,  OPTION_FUNC,   "", false, "", fgOptVOR },
1369     {"vor-frequency",                true,  OPTION_DOUBLE, "/sim/presets/vor-freq", false, "", fgOptVOR },
1370     {"ndb",                          true,  OPTION_FUNC,   "", false, "", fgOptNDB },
1371     {"ndb-frequency",                true,  OPTION_DOUBLE, "/sim/presets/ndb-freq", false, "", fgOptVOR },
1372     {"carrier",                      true,  OPTION_FUNC,   "", false, "", fgOptCarrier },
1373     {"parkpos",                      true,  OPTION_FUNC,   "", false, "", fgOptParkpos },
1374     {"fix",                          true,  OPTION_FUNC,   "", false, "", fgOptFIX },
1375     {"offset-distance",              true,  OPTION_DOUBLE, "/sim/presets/offset-distance-nm", false, "", 0 },
1376     {"offset-azimuth",               true,  OPTION_DOUBLE, "/sim/presets/offset-azimuth-deg", false, "", 0 },
1377     {"lon",                          true,  OPTION_FUNC,   "", false, "", fgOptLon },
1378     {"lat",                          true,  OPTION_FUNC,   "", false, "", fgOptLat },
1379     {"altitude",                     true,  OPTION_FUNC,   "", false, "", fgOptAltitude },
1380     {"uBody",                        true,  OPTION_FUNC,   "", false, "", fgOptUBody },
1381     {"vBody",                        true,  OPTION_FUNC,   "", false, "", fgOptVBody },
1382     {"wBody",                        true,  OPTION_FUNC,   "", false, "", fgOptWBody },
1383     {"vNorth",                       true,  OPTION_FUNC,   "", false, "", fgOptVNorth },
1384     {"vEast",                        true,  OPTION_FUNC,   "", false, "", fgOptVEast },
1385     {"vDown",                        true,  OPTION_FUNC,   "", false, "", fgOptVDown },
1386     {"vc",                           true,  OPTION_FUNC,   "", false, "", fgOptVc },
1387     {"mach",                         true,  OPTION_FUNC,   "", false, "", fgOptMach },
1388     {"heading",                      true,  OPTION_DOUBLE, "/sim/presets/heading-deg", false, "", 0 },
1389     {"roll",                         true,  OPTION_DOUBLE, "/sim/presets/roll-deg", false, "", 0 },
1390     {"pitch",                        true,  OPTION_DOUBLE, "/sim/presets/pitch-deg", false, "", 0 },
1391     {"glideslope",                   true,  OPTION_DOUBLE, "/sim/presets/glideslope-deg", false, "", 0 },
1392     {"roc",                          true,  OPTION_FUNC,   "", false, "", fgOptRoc },
1393     {"fg-root",                      true,  OPTION_IGNORE,   "", false, "", 0 },
1394     {"fg-scenery",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFgScenery },
1395     {"fg-aircraft",                  true,  OPTION_IGNORE | OPTION_MULTI,   "", false, "", 0 },
1396     {"fdm",                          true,  OPTION_STRING, "/sim/flight-model", false, "", 0 },
1397     {"aero",                         true,  OPTION_STRING, "/sim/aero", false, "", 0 },
1398     {"aircraft-dir",                 true,  OPTION_STRING, "/sim/aircraft-dir", false, "", 0 },
1399     {"model-hz",                     true,  OPTION_INT,    "/sim/model-hz", false, "", 0 },
1400     {"speed",                        true,  OPTION_INT,    "/sim/speed-up", false, "", 0 },
1401     {"trim",                         false, OPTION_BOOL,   "/sim/presets/trim", true, "", 0 },
1402     {"notrim",                       false, OPTION_BOOL,   "/sim/presets/trim", false, "", 0 },
1403     {"on-ground",                    false, OPTION_BOOL,   "/sim/presets/onground", true, "", 0 },
1404     {"in-air",                       false, OPTION_BOOL,   "/sim/presets/onground", false, "", 0 },
1405     {"fog-disable",                  false, OPTION_STRING, "/sim/rendering/fog", false, "disabled", 0 },
1406     {"fog-fastest",                  false, OPTION_STRING, "/sim/rendering/fog", false, "fastest", 0 },
1407     {"fog-nicest",                   false, OPTION_STRING, "/sim/rendering/fog", false, "nicest", 0 },
1408     {"disable-horizon-effect",       false, OPTION_BOOL,   "/sim/rendering/horizon-effect", false, "", 0 },
1409     {"enable-horizon-effect",        false, OPTION_BOOL,   "/sim/rendering/horizon-effect", true, "", 0 },
1410     {"disable-enhanced-lighting",    false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", false, "", 0 },
1411     {"enable-enhanced-lighting",     false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", true, "", 0 },
1412     {"disable-distance-attenuation", false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", false, "", 0 },
1413     {"enable-distance-attenuation",  false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", true, "", 0 },
1414     {"disable-specular-highlight",   false, OPTION_BOOL,   "/sim/rendering/specular-highlight", false, "", 0 },
1415     {"enable-specular-highlight",    false, OPTION_BOOL,   "/sim/rendering/specular-highlight", true, "", 0 },
1416     {"disable-clouds",               false, OPTION_BOOL,   "/environment/clouds/status", false, "", 0 },
1417     {"enable-clouds",                false, OPTION_BOOL,   "/environment/clouds/status", true, "", 0 },
1418     {"disable-clouds3d",             false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", false, "", 0 },
1419     {"enable-clouds3d",              false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", true, "", 0 },
1420     {"fov",                          true,  OPTION_FUNC,   "", false, "", fgOptFov },
1421     {"aspect-ratio-multiplier",      true,  OPTION_DOUBLE, "/sim/current-view/aspect-ratio-multiplier", false, "", 0 },
1422     {"disable-fullscreen",           false, OPTION_BOOL,   "/sim/startup/fullscreen", false, "", 0 },
1423     {"enable-fullscreen",            false, OPTION_BOOL,   "/sim/startup/fullscreen", true, "", 0 },
1424     {"disable-save-on-exit",         false, OPTION_BOOL,   "/sim/startup/save-on-exit", false, "", 0 },
1425     {"enable-save-on-exit",          false, OPTION_BOOL,   "/sim/startup/save-on-exit", true, "", 0 },
1426     {"shading-flat",                 false, OPTION_BOOL,   "/sim/rendering/shading", false, "", 0 },
1427     {"shading-smooth",               false, OPTION_BOOL,   "/sim/rendering/shading", true, "", 0 },
1428     {"disable-skyblend",             false, OPTION_BOOL,   "/sim/rendering/skyblend", false, "", 0 },
1429     {"enable-skyblend",              false, OPTION_BOOL,   "/sim/rendering/skyblend", true, "", 0 },
1430     {"disable-textures",             false, OPTION_BOOL,   "/sim/rendering/textures", false, "", 0 },
1431     {"enable-textures",              false, OPTION_BOOL,   "/sim/rendering/textures", true, "", 0 },
1432     {"texture-filtering",            false, OPTION_INT,    "/sim/rendering/filtering", 1, "", 0 },
1433     {"disable-wireframe",            false, OPTION_BOOL,   "/sim/rendering/wireframe", false, "", 0 },
1434     {"enable-wireframe",             false, OPTION_BOOL,   "/sim/rendering/wireframe", true, "", 0 },
1435     {"materials-file",               true,  OPTION_STRING, "/sim/rendering/materials-file", false, "", 0 },
1436     {"disable-terrasync",            false, OPTION_BOOL,   "/sim/terrasync/enabled", false, "", 0 },
1437     {"enable-terrasync",             false, OPTION_BOOL,   "/sim/terrasync/enabled", true, "", 0 },
1438     {"terrasync-dir",                true,  OPTION_STRING, "/sim/terrasync/scenery-dir", false, "", 0 },
1439     {"geometry",                     true,  OPTION_FUNC,   "", false, "", fgOptGeometry },
1440     {"bpp",                          true,  OPTION_FUNC,   "", false, "", fgOptBpp },
1441     {"units-feet",                   false, OPTION_STRING, "/sim/startup/units", false, "feet", 0 },
1442     {"units-meters",                 false, OPTION_STRING, "/sim/startup/units", false, "meters", 0 },
1443     {"timeofday",                    true,  OPTION_STRING, "/sim/startup/time-offset-type", false, "noon", 0 },
1444     {"season",                       true,  OPTION_STRING, "/sim/startup/season", false, "summer", 0 },
1445     {"time-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptTimeOffset },
1446     {"time-match-real",              false, OPTION_STRING, "/sim/startup/time-offset-type", false, "system-offset", 0 },
1447     {"time-match-local",             false, OPTION_STRING, "/sim/startup/time-offset-type", false, "latitude-offset", 0 },
1448     {"start-date-sys",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateSys },
1449     {"start-date-lat",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateLat },
1450     {"start-date-gmt",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateGmt },
1451     {"hud-tris",                     false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "tris", 0 },
1452     {"hud-culled",                   false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "culled", 0 },
1453     {"atcsim",                       true,  OPTION_CHANNEL, "", false, "dummy", 0 },
1454     {"atlas",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1455     {"httpd",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1456 #ifdef FG_JPEG_SERVER
1457     {"jpg-httpd",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1458 #endif
1459     {"native",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1460     {"native-ctrls",                 true,  OPTION_CHANNEL, "", false, "", 0 },
1461     {"native-fdm",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1462     {"native-gui",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1463     {"opengc",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1464     {"AV400",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1465     {"AV400Sim",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1466     {"AV400WSimA",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1467     {"AV400WSimB",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1468     {"garmin",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1469     {"nmea",                         true,  OPTION_CHANNEL, "", false, "", 0 },
1470     {"generic",                      true,  OPTION_CHANNEL, "", false, "", 0 },
1471     {"props",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1472     {"telnet",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1473     {"pve",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1474     {"ray",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1475     {"rul",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1476     {"joyclient",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1477     {"jsclient",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1478     {"proxy",                        true,  OPTION_FUNC,    "", false, "", fgSetupProxy },
1479     {"callsign",                     true,  OPTION_FUNC,    "", false, "", fgOptCallSign},
1480     {"multiplay",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1481 #ifdef FG_HAVE_HLA
1482     {"hla",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1483 #endif
1484     {"trace-read",                   true,  OPTION_FUNC,   "", false, "", fgOptTraceRead },
1485     {"trace-write",                  true,  OPTION_FUNC,   "", false, "", fgOptTraceWrite },
1486     {"log-level",                    true,  OPTION_FUNC,   "", false, "", fgOptLogLevel },
1487     {"view-offset",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptViewOffset },
1488     {"visibility",                   true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMeters },
1489     {"visibility-miles",             true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMiles },
1490     {"random-wind",                  false, OPTION_FUNC,   "", false, "", fgOptRandomWind },
1491     {"wind",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWind },
1492     {"turbulence",                   true,  OPTION_FUNC,   "", false, "", fgOptTurbulence },
1493     {"ceiling",                      true,  OPTION_FUNC,   "", false, "", fgOptCeiling },
1494     {"wp",                           true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWp },
1495     {"flight-plan",                  true,  OPTION_STRING,   "/autopilot/route-manager/file-path", false, "", NULL },
1496     {"config",                       true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptConfig },
1497     {"aircraft",                     true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1498     {"vehicle",                      true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1499     {"failure",                      true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFailure },
1500     {"com1",                         true,  OPTION_DOUBLE, "/instrumentation/comm[0]/frequencies/selected-mhz", false, "", 0 },
1501     {"com2",                         true,  OPTION_DOUBLE, "/instrumentation/comm[1]/frequencies/selected-mhz", false, "", 0 },
1502     {"nav1",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV1 },
1503     {"nav2",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV2 },
1504     {"adf", /*legacy*/               true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1505     {"adf1",                         true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1506     {"adf2",                         true,  OPTION_FUNC,   "", false, "", fgOptADF2 },
1507     {"dme",                          true,  OPTION_FUNC,   "", false, "", fgOptDME },
1508     {"min-status",                   true,  OPTION_STRING,  "/sim/aircraft-min-status", false, "all", 0 },
1509     {"livery",                       true,  OPTION_FUNC,   "", false, "", fgOptLivery },
1510     {"ai-scenario",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptScenario },
1511     {"disable-ai-scenarios",         false, OPTION_FUNC,   "", false, "", fgOptNoScenarios},
1512     {"parking-id",                   true,  OPTION_FUNC,   "", false, "", fgOptParking  },
1513     {"version",                      false, OPTION_FUNC,   "", false, "", fgOptVersion },
1514     {"enable-fpe",                   false, OPTION_IGNORE,   "", false, "", 0},
1515     {"fgviewer",                     false, OPTION_IGNORE,   "", false, "", 0},
1516     {"prop",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptSetProperty},
1517     {0}
1518 };
1519
1520
1521 namespace flightgear
1522 {
1523
1524 /**
1525  * internal storage of a value->option binding
1526  */
1527 class OptionValue 
1528 {
1529 public:
1530   OptionValue(OptionDesc* d, const string& v) :
1531     desc(d), value(v)
1532   {;}
1533   
1534   OptionDesc* desc;
1535   string value;
1536 };
1537
1538 typedef std::vector<OptionValue> OptionValueVec;
1539 typedef std::map<string, OptionDesc*> OptionDescDict;
1540   
1541 class Options::OptionsPrivate
1542 {
1543 public:
1544   
1545   OptionValueVec::const_iterator findValue(const string& key) const
1546   {
1547     OptionValueVec::const_iterator it = values.begin();
1548     for (; it != values.end(); ++it) {
1549       if (it->desc->option == key) {
1550         return it;
1551       }
1552     } // of set values iteration
1553     
1554     return it; // not found
1555   }
1556   
1557   OptionDesc* findOption(const string& key) const
1558   {
1559     OptionDescDict::const_iterator it = options.find(key);
1560     if (it == options.end()) {
1561       return NULL;
1562     }
1563     
1564     return it->second;
1565   }
1566   
1567   int processOption(OptionDesc* desc, const string& arg_value)
1568   {
1569     switch ( desc->type & 0xffff ) {
1570       case OPTION_BOOL:
1571         fgSetBool( desc->property, desc->b_param );
1572         break;
1573       case OPTION_STRING:
1574         if ( desc->has_param && !arg_value.empty() ) {
1575           fgSetString( desc->property, arg_value.c_str() );
1576         } else if ( !desc->has_param && arg_value.empty() ) {
1577           fgSetString( desc->property, desc->s_param );
1578         } else if ( desc->has_param ) {
1579           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1580           return FG_OPTIONS_ERROR;
1581         } else {
1582           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1583           return FG_OPTIONS_ERROR;
1584         }
1585         break;
1586       case OPTION_DOUBLE:
1587         if ( !arg_value.empty() ) {
1588           fgSetDouble( desc->property, atof( arg_value ) );
1589         } else {
1590           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1591           return FG_OPTIONS_ERROR;
1592         }
1593         break;
1594       case OPTION_INT:
1595         if ( !arg_value.empty() ) {
1596           fgSetInt( desc->property, atoi( arg_value ) );
1597         } else {
1598           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1599           return FG_OPTIONS_ERROR;
1600         }
1601         break;
1602       case OPTION_CHANNEL:
1603         // XXX return value of add_channel should be checked?
1604         if ( desc->has_param && !arg_value.empty() ) {
1605           add_channel( desc->option, arg_value );
1606         } else if ( !desc->has_param && arg_value.empty() ) {
1607           add_channel( desc->option, desc->s_param );
1608         } else if ( desc->has_param ) {
1609           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1610           return FG_OPTIONS_ERROR;
1611         } else {
1612           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1613           return FG_OPTIONS_ERROR;
1614         }
1615         break;
1616       case OPTION_FUNC:
1617         if ( desc->has_param && !arg_value.empty() ) {
1618           return desc->func( arg_value.c_str() );
1619         } else if ( !desc->has_param && arg_value.empty() ) {
1620           return desc->func( desc->s_param );
1621         } else if ( desc->has_param ) {
1622           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1623           return FG_OPTIONS_ERROR;
1624         } else {
1625           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1626           return FG_OPTIONS_ERROR;
1627         }
1628         break;
1629         
1630       case OPTION_IGNORE:
1631         break;
1632     }
1633     
1634     return FG_OPTIONS_OK;
1635   }
1636   
1637   bool showHelp,
1638     verbose,
1639     showAircraft;
1640   OptionDescDict options;
1641   OptionValueVec values;
1642   simgear::PathList propertyFiles;
1643 };
1644   
1645 Options* Options::sharedInstance()
1646 {
1647   if (shared_instance == NULL) {
1648     shared_instance = new Options;
1649   }
1650   
1651   return shared_instance;
1652 }
1653   
1654 Options::Options() :
1655   p(new OptionsPrivate())
1656 {
1657   p->showHelp = false;
1658   p->verbose = false;
1659   p->showAircraft = false;
1660   
1661 // build option map
1662   OptionDesc *desc = &fgOptionArray[ 0 ];
1663   while ( desc->option != 0 ) {
1664     p->options[ desc->option ] = desc++;
1665   }
1666 }
1667   
1668 Options::~Options()
1669 {
1670 }
1671   
1672 void Options::init(int argc, char **argv)
1673 {
1674   fgSetDefaults();
1675   
1676 // first, process the command line
1677   bool inOptions = true;
1678   for (int i=1; i<argc; ++i) {
1679     if (inOptions && (argv[i][0] == '-')) {
1680       if (strcmp(argv[i], "--") == 0) { // end of options delimiter
1681         inOptions = true;
1682         continue;
1683       }
1684       
1685       int result = parseOption(argv[i]);
1686       processArgResult(result);
1687     } else {
1688     // XML properties file
1689       SGPath f(argv[i]);
1690       if (!f.exists()) {
1691         SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f.str());
1692         return;
1693       }
1694       
1695       p->propertyFiles.push_back(f);
1696     }
1697   } // of arguments iteration
1698   
1699 // then config files
1700   SGPath config;
1701   
1702   if( homedir && hostname && strlen(hostname) > 0 ) {
1703     // Check for ~/.fgfsrc.hostname
1704     config.set(homedir);
1705     config.append(".fgfsrc");
1706     config.concat( "." );
1707     config.concat( hostname );
1708     readConfig(config);
1709   }
1710   
1711 // Check for ~/.fgfsrc
1712   if( homedir ) {
1713     config.set(homedir);
1714     config.append(".fgfsrc");
1715     readConfig(config);
1716   }
1717   
1718 // setup FG_ROOT
1719   setupRoot();
1720   
1721 // system.fgfsrc handling
1722   if( hostname && strlen(hostname) > 0 ) {
1723     config.set(globals->get_fg_root());
1724     config.append( "system.fgfsrc" );
1725     config.concat( "." );
1726     config.concat( hostname );
1727     readConfig(config);
1728   }
1729
1730   config.set(globals->get_fg_root());
1731   config.append( "system.fgfsrc" );
1732   readConfig(config);
1733 }
1734   
1735 void Options::initAircraft()
1736 {
1737   BOOST_FOREACH(const string& paths, valuesForOption("fg-aircraft")) {
1738     globals->append_aircraft_paths(paths);
1739   }
1740   
1741   const char* envp = ::getenv("FG_AIRCRAFT");
1742   if (envp) {
1743     globals->append_aircraft_paths(envp);
1744   }
1745
1746   string aircraft;
1747   if (isOptionSet("aircraft")) {
1748     aircraft = valueForOption("aircraft");
1749   } else if (isOptionSet("vehicle")) {
1750     aircraft = valueForOption("vehicle");
1751   }
1752     
1753   if (!aircraft.empty()) {
1754     SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
1755     fgSetString("/sim/aircraft", aircraft.c_str() );
1756   } else {
1757     SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
1758   }
1759   
1760   if (p->showAircraft) {
1761     fgOptLogLevel( "alert" );
1762     SGPath path( globals->get_fg_root() );
1763     path.append("Aircraft");
1764     fgShowAircraft(path);
1765     exit(0);
1766   }
1767 }
1768   
1769 void Options::processArgResult(int result)
1770 {
1771   if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
1772     p->showHelp = true;
1773   else if (result == FG_OPTIONS_VERBOSE_HELP)
1774     p->verbose = true;
1775   else if (result == FG_OPTIONS_SHOW_AIRCRAFT) {
1776     p->showAircraft = true;    
1777   } else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
1778     SGSoundMgr smgr;
1779     
1780     smgr.init();
1781     string vendor = smgr.get_vendor();
1782     string renderer = smgr.get_renderer();
1783     cout << renderer << " provided by " << vendor << endl;
1784     cout << endl << "No. Device" << endl;
1785     
1786     vector <const char*>devices = smgr.get_available_devices();
1787     for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
1788       cout << i << ".  \"" << devices[i] << "\"" << endl;
1789     }
1790     devices.clear();
1791     exit(0);
1792   } else if (result == FG_OPTIONS_EXIT) {
1793     exit(0);
1794   }
1795 }
1796   
1797 void Options::readConfig(const SGPath& path)
1798 {
1799   sg_gzifstream in( path.str() );
1800   if ( !in.is_open() ) {
1801     return;
1802   }
1803   
1804   SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path.str() );
1805   
1806   in >> skipcomment;
1807   while ( ! in.eof() ) {
1808     string line;
1809     getline( in, line, '\n' );
1810     
1811     // catch extraneous (DOS) line ending character
1812     int i;
1813     for (i = line.length(); i > 0; i--)
1814       if (line[i - 1] > 32)
1815         break;
1816     line = line.substr( 0, i );
1817     
1818     if ( parseOption( line ) == FG_OPTIONS_ERROR ) {
1819       cerr << endl << "Config file parse error: " << path.str() << " '"
1820       << line << "'" << endl;
1821             p->showHelp = true;
1822     }
1823     in >> skipcomment;
1824   }
1825
1826 }
1827   
1828 int Options::parseOption(const string& s)
1829 {
1830   if ((s == "--help") || (s=="-h")) {
1831     return FG_OPTIONS_HELP;
1832   } else if ( (s == "--verbose") || (s == "-v") ) {
1833     // verbose help/usage request
1834     return FG_OPTIONS_VERBOSE_HELP;
1835   } else if (s.find("-psn") == 0) {
1836     // on Mac, when launched from the GUI, we are passed the ProcessSerialNumber
1837     // as an argument (and no others). Silently ignore the argument here.
1838     return FG_OPTIONS_OK;
1839   } else if ( s.find( "--show-aircraft") == 0) {
1840     return(FG_OPTIONS_SHOW_AIRCRAFT);
1841   } else if ( s.find( "--show-sound-devices") == 0) {
1842     return(FG_OPTIONS_SHOW_SOUND_DEVICES);
1843   } else if ( s.find( "--prop:") == 0) {
1844     // property setting has a slightly different syntax, so fudge things
1845     OptionDesc* desc = p->findOption("prop");
1846     if (s.find("=", 7) == string::npos) { // no equals token
1847       SG_LOG(SG_GENERAL, SG_ALERT, "malformed property option:" << s);
1848       return FG_OPTIONS_ERROR;
1849     }
1850     
1851     p->values.push_back(OptionValue(desc, s.substr(7)));
1852     return FG_OPTIONS_OK;
1853   } else if ( s.find( "--" ) == 0 ) {
1854     size_t eqPos = s.find( '=' );
1855     string key, value;
1856     if (eqPos == string::npos) {
1857       key = s.substr(2);
1858     } else {
1859       key = s.substr( 2, eqPos - 2 );
1860       value = s.substr( eqPos + 1);
1861     }
1862     
1863     return addOption(key, value);
1864   } else {
1865     SG_LOG(SG_GENERAL, SG_ALERT, "unknown option:" << s);
1866     return FG_OPTIONS_ERROR;
1867   }
1868 }
1869   
1870 int Options::addOption(const string &key, const string &value)
1871 {
1872   OptionDesc* desc = p->findOption(key);
1873   if (!desc) {
1874     return FG_OPTIONS_ERROR;
1875   }
1876   
1877   if (!(desc->type & OPTION_MULTI)) {
1878     OptionValueVec::const_iterator it = p->findValue(key);
1879     if (it != p->values.end()) {
1880       SG_LOG(SG_GENERAL, SG_INFO, "multiple values forbidden for option:" << key << ", ignoring:" << value);
1881       return FG_OPTIONS_OK;
1882     }
1883   }
1884   
1885   p->values.push_back(OptionValue(desc, value));
1886   return FG_OPTIONS_OK;
1887 }
1888   
1889 bool Options::isOptionSet(const string &key) const
1890 {
1891   OptionValueVec::const_iterator it = p->findValue(key);
1892   return (it != p->values.end());
1893 }
1894   
1895 string Options::valueForOption(const string& key, const string& defValue) const
1896 {
1897   OptionValueVec::const_iterator it = p->findValue(key);
1898   if (it == p->values.end()) {
1899     return defValue;
1900   }
1901   
1902   return it->value;
1903 }
1904
1905 string_list Options::valuesForOption(const std::string& key) const
1906 {
1907   string_list result;
1908   OptionValueVec::const_iterator it = p->values.begin();
1909   for (; it != p->values.end(); ++it) {
1910     if (it->desc->option == key) {
1911       result.push_back(it->value);
1912     }
1913   }
1914   
1915   return result;
1916 }
1917   
1918 void Options::processOptions()
1919 {
1920   // now FG_ROOT is setup, process various command line options that bail us
1921   // out quickly, but rely on aircraft / root settings
1922   if (p->showHelp) {
1923     showUsage();
1924     exit(0);
1925   }
1926   
1927   BOOST_FOREACH(const OptionValue& v, p->values) {
1928     int result = p->processOption(v.desc, v.value);
1929     if (result == FG_OPTIONS_ERROR) {
1930       showUsage();
1931       exit(-1);
1932     }
1933   }
1934   
1935   BOOST_FOREACH(const SGPath& file, p->propertyFiles) {
1936     if (!file.exists()) {
1937       SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << file.str());
1938       continue;
1939     }
1940     
1941     SG_LOG(SG_GENERAL, SG_INFO,
1942            "Reading command-line property file " << file.str());
1943           readProperties(file.str(), globals->get_props());
1944   }
1945
1946 // now options are process, do supplemental fixup
1947   const char *envp = ::getenv( "FG_SCENERY" );
1948   if (envp) {
1949     globals->append_fg_scenery(envp);
1950   }
1951   
1952   if (globals->get_fg_scenery().empty()) {
1953   // no scenery paths set *at all*, use the data in FG_ROOT
1954     SGPath root(globals->get_fg_root());
1955     root.append("Scenery");
1956     globals->append_fg_scenery(root.str());
1957   }
1958 }
1959   
1960 void Options::showUsage() const
1961 {
1962   fgOptLogLevel( "alert" );
1963   
1964   SGPropertyNode *locale = globals->get_locale();
1965   SGPropertyNode options_root;
1966   
1967   SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1968   cout << endl;
1969   
1970   try {
1971     fgLoadProps("options.xml", &options_root);
1972   } catch (const sg_exception &) {
1973     cout << "Unable to read the help file." << endl;
1974     cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
1975     cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
1976     cout << "by adding --fg-root=path as a program argument." << endl;
1977     
1978     exit(-1);
1979   }
1980   
1981   SGPropertyNode *options = options_root.getNode("options");
1982   if (!options) {
1983     SG_LOG( SG_GENERAL, SG_ALERT,
1984            "Error reading options.xml: <options> directive not found." );
1985     exit(-1);
1986   }
1987   
1988   SGPropertyNode *usage = locale->getNode(options->getStringValue("usage"));
1989   if (usage) {
1990     cout << "Usage: " << usage->getStringValue() << endl;
1991   }
1992   
1993   vector<SGPropertyNode_ptr>section = options->getChildren("section");
1994   for (unsigned int j = 0; j < section.size(); j++) {
1995     string msg = "";
1996     
1997     vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
1998     for (unsigned int k = 0; k < option.size(); k++) {
1999       
2000       SGPropertyNode *name = option[k]->getNode("name");
2001       SGPropertyNode *short_name = option[k]->getNode("short");
2002       SGPropertyNode *key = option[k]->getNode("key");
2003       SGPropertyNode *arg = option[k]->getNode("arg");
2004       bool brief = option[k]->getNode("brief") != 0;
2005       
2006       if ((brief || p->verbose) && name) {
2007         string tmp = name->getStringValue();
2008         
2009         if (key){
2010           tmp.append(":");
2011           tmp.append(key->getStringValue());
2012         }
2013         if (arg) {
2014           tmp.append("=");
2015           tmp.append(arg->getStringValue());
2016         }
2017         if (short_name) {
2018           tmp.append(", -");
2019           tmp.append(short_name->getStringValue());
2020         }
2021         
2022         if (tmp.size() <= 25) {
2023           msg+= "   --";
2024           msg += tmp;
2025           msg.append( 27-tmp.size(), ' ');
2026         } else {
2027           msg += "\n   --";
2028           msg += tmp + '\n';
2029           msg.append(32, ' ');
2030         }
2031         // There may be more than one <description> tag assosiated
2032         // with one option
2033         
2034         vector<SGPropertyNode_ptr> desc;
2035         desc = option[k]->getChildren("description");
2036         if (desc.size() > 0) {
2037           for ( unsigned int l = 0; l < desc.size(); l++) {
2038             
2039             // There may be more than one translation line.
2040             
2041             string t = desc[l]->getStringValue();
2042             SGPropertyNode *n = locale->getNode("strings");
2043             vector<SGPropertyNode_ptr>trans_desc =
2044             n->getChildren(t.substr(8).c_str());
2045             
2046             for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
2047               string t_str = trans_desc[m]->getStringValue();
2048               
2049               if ((m > 0) || ((l > 0) && m == 0)) {
2050                 msg.append( 32, ' ');
2051               }
2052               
2053               // If the string is too large to fit on the screen,
2054               // then split it up in several pieces.
2055               
2056               while ( t_str.size() > 47 ) {
2057                 
2058                 string::size_type m = t_str.rfind(' ', 47);
2059                 msg += t_str.substr(0, m) + '\n';
2060                 msg.append( 32, ' ');
2061                 
2062                 t_str.erase(t_str.begin(), t_str.begin() + m + 1);
2063               }
2064               msg += t_str + '\n';
2065             }
2066           }
2067         }
2068       }
2069     }
2070     
2071     SGPropertyNode *name;
2072     name = locale->getNode(section[j]->getStringValue("name"));
2073     
2074     if (!msg.empty() && name) {
2075       cout << endl << name->getStringValue() << ":" << endl;
2076       cout << msg;
2077       msg.erase();
2078     }
2079   }
2080   
2081   if ( !p->verbose ) {
2082     cout << endl;
2083     cout << "For a complete list of options use --help --verbose" << endl;
2084   }
2085 #ifdef _MSC_VER
2086   cout << "Hit a key to continue..." << endl;
2087   cin.get();
2088 #endif
2089 }
2090   
2091 #if defined(__CYGWIN__)
2092 string Options::platformDefaultRoot() const
2093 {
2094   return "../data";
2095 }
2096
2097 #elif defined(_WIN32)
2098 string Options::platformDefaultRoot() const
2099 {
2100   return "..\\data";
2101 }
2102 #elif defined(__APPLE__)
2103 string Options::platformDefaultRoot() const
2104 {
2105   /*
2106    The following code looks for the base package inside the application 
2107    bundle, in the standard Contents/Resources location. 
2108    */
2109   CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
2110   
2111   // look for a 'data' subdir
2112   CFURLRef dataDir = CFURLCreateCopyAppendingPathComponent(NULL, resourcesUrl, CFSTR("data"), true);
2113   
2114   // now convert down to a path, and the a c-string
2115   CFStringRef path = CFURLCopyFileSystemPath(dataDir, kCFURLPOSIXPathStyle);
2116   string root = CFStringGetCStringPtr(path, CFStringGetSystemEncoding());
2117   
2118   CFRelease(resourcesUrl);
2119   CFRelease(dataDir);
2120   CFRelease(path);
2121   
2122   return root;
2123 }
2124 #else
2125 string Options::platformDefaultRoot() const
2126 {
2127   return PKGLIBDIR;
2128 }
2129 #endif
2130   
2131 void Options::setupRoot()
2132 {
2133   string root;
2134   if (isOptionSet("fg-root")) {
2135     root = valueForOption("fg-root"); // easy!
2136   } else {
2137   // Next check if fg-root is set as an env variable
2138     char *envp = ::getenv( "FG_ROOT" );
2139     if ( envp != NULL ) {
2140       root = envp;
2141     } else {
2142       root = platformDefaultRoot();
2143     }
2144   } 
2145   
2146   SG_LOG(SG_INPUT, SG_INFO, "fg_root = " << root );
2147   globals->set_fg_root(root);
2148   
2149 // validate it
2150   static char required_version[] = "2.5.0";
2151   string base_version = fgBasePackageVersion();
2152   if ( !(base_version == required_version) ) {
2153     // tell the operator how to use this application
2154     
2155     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
2156     cerr << endl << "Base package check failed:" << endl \
2157     << "  Version " << base_version << " found at: " \
2158     << globals->get_fg_root() << endl \
2159     << "  Version " << required_version << " is required." << endl \
2160     << "Please upgrade/downgrade base package and set the path to your fgdata" << endl \
2161     << "with --fg-root=path_to_your_fgdata" << endl;
2162 #ifdef _MSC_VER
2163     cerr << "Hit a key to continue..." << endl;
2164     cin.get();
2165 #endif
2166     exit(-1);
2167   }
2168 }
2169   
2170 } // of namespace flightgear
2171