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