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