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