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