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