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