]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_props.cxx
b84688aeb0b05438667680bca3dc697aed0ca523
[flightgear.git] / src / Main / fg_props.cxx
1 // fg_props.cxx -- support for FlightGear properties.
2 //
3 // Written by David Megginson, started 2000.
4 //
5 // Copyright (C) 2000, 2001 David Megginson - david@megginson.com
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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear/compiler.h>
25 #endif
26
27 #include <simgear/misc/exception.hxx>
28 #include <simgear/magvar/magvar.hxx>
29 #include <simgear/timing/sg_time.hxx>
30 #include <simgear/misc/sg_path.hxx>
31
32 #include STL_IOSTREAM
33
34 #include <ATC/ATCdisplay.hxx>
35 #include <Aircraft/aircraft.hxx>
36 #include <Time/tmp.hxx>
37 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
38 #ifdef FG_WEATHERCM
39 #  include <WeatherCM/FGLocalWeatherDatabase.h>
40 #else
41 #  include <Environment/environment.hxx>
42 #endif // FG_WEATHERCM
43 #include <Objects/matlib.hxx>
44
45 #include <GUI/gui.h>
46 #include <Sound/soundmgr.hxx>
47
48 #include "globals.hxx"
49 #include "fgfs.hxx"
50 #include "fg_props.hxx"
51
52 #if !defined(SG_HAVE_NATIVE_SGI_COMPILERS)
53 SG_USING_STD(istream);
54 SG_USING_STD(ostream);
55 #endif
56
57 #ifdef FG_WEATHERCM
58 static double getWindNorth ();
59 static double getWindEast ();
60 static double getWindDown ();
61 #endif // FG_WEATHERCM
62
63 static bool winding_ccw = true; // FIXME: temporary
64
65 static bool fdm_data_logging = false; // FIXME: temporary
66
67 static bool frozen = false;     // FIXME: temporary
68
69
70 \f
71 ////////////////////////////////////////////////////////////////////////
72 // Default property bindings (not yet handled by any module).
73 ////////////////////////////////////////////////////////////////////////
74
75 struct LogClassMapping {
76   sgDebugClass c;
77   string name;
78   LogClassMapping(sgDebugClass cc, string nname) { c = cc; name = nname; }
79 };
80
81 LogClassMapping log_class_mappings [] = {
82   LogClassMapping(SG_NONE, "none"),
83   LogClassMapping(SG_TERRAIN, "terrain"),
84   LogClassMapping(SG_ASTRO, "astro"),
85   LogClassMapping(SG_FLIGHT, "flight"),
86   LogClassMapping(SG_INPUT, "input"),
87   LogClassMapping(SG_GL, "gl"),
88   LogClassMapping(SG_VIEW, "view"),
89   LogClassMapping(SG_COCKPIT, "cockpit"),
90   LogClassMapping(SG_GENERAL, "general"),
91   LogClassMapping(SG_MATH, "math"),
92   LogClassMapping(SG_EVENT, "event"),
93   LogClassMapping(SG_AIRCRAFT, "aircraft"),
94   LogClassMapping(SG_AUTOPILOT, "autopilot"),
95   LogClassMapping(SG_IO, "io"),
96   LogClassMapping(SG_CLIPPER, "clipper"),
97   LogClassMapping(SG_NETWORK, "network"),
98   LogClassMapping(SG_UNDEFD, "")
99 };
100
101
102 /**
103  * Get the logging classes.
104  */
105 static const char *
106 getLoggingClasses ()
107 {
108   sgDebugClass classes = logbuf::get_log_classes();
109   static string result = "";    // FIXME
110   for (int i = 0; log_class_mappings[i].c != SG_UNDEFD; i++) {
111     if ((classes&log_class_mappings[i].c) > 0) {
112       if (!result.empty())
113         result += '|';
114       result += log_class_mappings[i].name;
115     }
116   }
117   return result.c_str();
118 }
119
120
121 static void
122 addLoggingClass (const string &name)
123 {
124   sgDebugClass classes = logbuf::get_log_classes();
125   for (int i = 0; log_class_mappings[i].c != SG_UNDEFD; i++) {
126     if (name == log_class_mappings[i].name) {
127       logbuf::set_log_classes(sgDebugClass(classes|log_class_mappings[i].c));
128       return;
129     }
130   }
131   SG_LOG(SG_GENERAL, SG_ALERT, "Unknown logging class: " << name);
132 }
133
134
135 /**
136  * Set the logging classes.
137  */
138 static void
139 setLoggingClasses (const char * c)
140 {
141   string classes = c;
142   logbuf::set_log_classes(SG_NONE);
143
144   if (classes == "none") {
145     SG_LOG(SG_GENERAL, SG_INFO, "Disabled all logging classes");
146     return;
147   }
148
149   if (classes.empty() || classes == "all") { // default
150     logbuf::set_log_classes(SG_ALL);
151     SG_LOG(SG_GENERAL, SG_INFO, "Enabled all logging classes: "
152            << getLoggingClasses());
153     return;
154   }
155
156   string rest = classes;
157   string name = "";
158   int sep = rest.find('|');
159   while (sep > 0) {
160     name = rest.substr(0, sep);
161     rest = rest.substr(sep+1);
162     addLoggingClass(name);
163     sep = rest.find('|');
164   }
165   addLoggingClass(rest);
166   SG_LOG(SG_GENERAL, SG_INFO, "Set logging classes to "
167          << getLoggingClasses());
168 }
169
170
171 /**
172  * Get the logging priority.
173  */
174 static const char *
175 getLoggingPriority ()
176 {
177   switch (logbuf::get_log_priority()) {
178   case SG_BULK:
179     return "bulk";
180   case SG_DEBUG:
181     return "debug";
182   case SG_INFO:
183     return "info";
184   case SG_WARN:
185     return "warn";
186   case SG_ALERT:
187     return "alert";
188   default:
189     SG_LOG(SG_GENERAL, SG_WARN, "Internal: Unknown logging priority number: "
190            << logbuf::get_log_priority());
191     return "unknown";
192   }
193 }
194
195
196 /**
197  * Set the logging priority.
198  */
199 static void
200 setLoggingPriority (const char * p)
201 {
202   string priority = p;
203   if (priority == "bulk") {
204     logbuf::set_log_priority(SG_BULK);
205   } else if (priority == "debug") {
206     logbuf::set_log_priority(SG_DEBUG);
207   } else if (priority.empty() || priority == "info") { // default
208     logbuf::set_log_priority(SG_INFO);
209   } else if (priority == "warn") {
210     logbuf::set_log_priority(SG_WARN);
211   } else if (priority == "alert") {
212     logbuf::set_log_priority(SG_ALERT);
213   } else {
214     SG_LOG(SG_GENERAL, SG_WARN, "Unknown logging priority " << priority);
215   }
216   SG_LOG(SG_GENERAL, SG_INFO, "Logging priority is " << getLoggingPriority());
217 }
218
219
220 /**
221  * Return the current frozen state.
222  */
223 static bool
224 getFreeze ()
225 {
226   return frozen;
227 }
228
229
230 /**
231  * Set the current frozen state.
232  */
233 static void
234 setFreeze (bool f)
235 {
236   frozen = f;
237                                 // Stop sound on a pause
238   if (f)
239     globals->get_soundmgr()->pause();
240   else
241     globals->get_soundmgr()->resume();
242 }
243
244
245 /**
246  * Return the current aircraft directory (UIUC) as a string.
247  */
248 static const char *
249 getAircraftDir ()
250 {
251   return aircraft_dir.c_str();
252 }
253
254
255 /**
256  * Set the current aircraft directory (UIUC).
257  */
258 static void
259 setAircraftDir (const char * dir)
260 {
261   aircraft_dir = dir;
262 }
263
264
265 /**
266  * Return the number of milliseconds elapsed since simulation started.
267  */
268 static double
269 getElapsedTime_sec ()
270 {
271   return globals->get_sim_time_sec();
272 }
273
274
275 /**
276  * Return the current Zulu time.
277  */
278 static const char *
279 getDateString ()
280 {
281   static char buf[64];          // FIXME
282   struct tm * t = globals->get_time_params()->getGmt();
283   sprintf(buf, "%.4d-%.2d-%.2dT%.2d:%.2d:%.2d",
284           t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
285           t->tm_hour, t->tm_min, t->tm_sec);
286   return buf;
287 }
288
289
290 /**
291  * Set the current Zulu time.
292  */
293 static void
294 setDateString (const char * date_string)
295 {
296   static const SGPropertyNode *cur_time_override
297         = fgGetNode("/sim/time/cur-time-override", true);
298
299   SGTime * st = globals->get_time_params();
300   struct tm * current_time = st->getGmt();
301   struct tm new_time;
302
303                                 // Scan for basic ISO format
304                                 // YYYY-MM-DDTHH:MM:SS
305   int ret = sscanf(date_string, "%d-%d-%dT%d:%d:%d",
306                    &(new_time.tm_year), &(new_time.tm_mon),
307                    &(new_time.tm_mday), &(new_time.tm_hour),
308                    &(new_time.tm_min), &(new_time.tm_sec));
309
310                                 // Be pretty picky about this, so
311                                 // that strange things don't happen
312                                 // if the save file has been edited
313                                 // by hand.
314   if (ret != 6) {
315     SG_LOG(SG_INPUT, SG_ALERT, "Date/time string " << date_string
316            << " not in YYYY-MM-DDTHH:MM:SS format; skipped");
317     return;
318   }
319
320                                 // OK, it looks like we got six
321                                 // values, one way or another.
322   new_time.tm_year -= 1900;
323   new_time.tm_mon -= 1;
324
325                                 // Now, tell flight gear to use
326                                 // the new time.  This was far
327                                 // too difficult, by the way.
328   long int warp =
329     mktime(&new_time) - mktime(current_time) + globals->get_warp();
330   double lon = current_aircraft.fdm_state->get_Longitude();
331   double lat = current_aircraft.fdm_state->get_Latitude();
332   globals->set_warp(warp);
333   st->update(lon, lat, cur_time_override->getLongValue(), warp);
334   fgUpdateSkyAndLightingParams();
335 }
336
337 /**
338  * Return the GMT as a string.
339  */
340 static const char *
341 getGMTString ()
342 {
343   static char buf[16];          // FIXME
344   struct tm *t = globals->get_time_params()->getGmt();
345   sprintf(buf, " %.2d:%.2d:%.2d",
346           t->tm_hour, t->tm_min, t->tm_sec);
347   // cout << t << " " << buf << endl;
348   return buf;
349 }
350
351
352 /**
353  * Get the texture rendering state.
354  */
355 static bool
356 getTextures ()
357 {
358   return (material_lib.get_step() == 0);
359 }
360
361
362 /**
363  * Set the texture rendering state.
364  */
365 static void
366 setTextures (bool textures)
367 {
368   if (textures)
369     material_lib.set_step(0);
370   else
371     material_lib.set_step(1);
372 }
373
374
375 /**
376  * Return the magnetic variation
377  */
378 static double
379 getMagVar ()
380 {
381   return globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
382 }
383
384
385 /**
386  * Return the magnetic dip
387  */
388 static double
389 getMagDip ()
390 {
391   return globals->get_mag()->get_magdip() * SGD_RADIANS_TO_DEGREES;
392 }
393
394
395 /**
396  * Return the current heading in degrees.
397  */
398 static double
399 getHeadingMag ()
400 {
401   return current_aircraft.fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES - getMagVar();
402 }
403
404
405 #ifdef FG_WEATHERCM
406
407 /**
408  * Get the current visibility (meters).
409  */
410 static double
411 getVisibility ()
412 {
413   return WeatherDatabase->getWeatherVisibility();
414 }
415
416
417 /**
418  * Set the current visibility (meters).
419  */
420 static void
421 setVisibility (double visibility)
422 {
423   WeatherDatabase->setWeatherVisibility(visibility);
424 }
425
426 /**
427  * Get the current wind north velocity (feet/second).
428  */
429 static double
430 getWindNorth ()
431 {
432   return current_aircraft.fdm_state->get_V_north_airmass();
433 }
434
435
436 /**
437  * Set the current wind north velocity (feet/second).
438  */
439 static void
440 setWindNorth (double speed)
441 {
442   current_aircraft.fdm_state
443     ->set_Velocities_Local_Airmass(speed, getWindEast(), getWindDown());
444 }
445
446
447 /**
448  * Get the current wind east velocity (feet/second).
449  */
450 static double
451 getWindEast ()
452 {
453   return current_aircraft.fdm_state->get_V_east_airmass();
454 }
455
456
457 /**
458  * Set the current wind east velocity (feet/second).
459  */
460 static void
461 setWindEast (double speed)
462 {
463   cout << "Set wind-east to " << speed << endl;
464   current_aircraft.fdm_state->set_Velocities_Local_Airmass(getWindNorth(),
465                                                            speed,
466                                                            getWindDown());
467 }
468
469
470 /**
471  * Get the current wind down velocity (feet/second).
472  */
473 static double
474 getWindDown ()
475 {
476   return current_aircraft.fdm_state->get_V_down_airmass();
477 }
478
479
480 /**
481  * Set the current wind down velocity (feet/second).
482  */
483 static void
484 setWindDown (double speed)
485 {
486   current_aircraft.fdm_state->set_Velocities_Local_Airmass(getWindNorth(),
487                                                            getWindEast(),
488                                                            speed);
489 }
490
491 #endif // FG_WEATHERCM
492
493 static long
494 getWarp ()
495 {
496   return globals->get_warp();
497 }
498
499 static void
500 setWarp (long warp)
501 {
502   globals->set_warp(warp);
503 }
504
505 static long
506 getWarpDelta ()
507 {
508   return globals->get_warp_delta();
509 }
510
511 static void
512 setWarpDelta (long delta)
513 {
514   globals->set_warp_delta(delta);
515 }
516
517 static bool
518 getWindingCCW ()
519 {
520   return winding_ccw;
521 }
522
523 static void
524 setWindingCCW (bool state)
525 {
526   winding_ccw = state;
527   if ( winding_ccw )
528     glFrontFace ( GL_CCW );
529   else
530     glFrontFace ( GL_CW );
531 }
532
533 static bool
534 getFullScreen ()
535 {
536 #if defined(FX) && !defined(WIN32)
537   return globals->get_fullscreen();
538 #else
539   return false;
540 #endif
541 }
542
543 static void
544 setFullScreen (bool state)
545 {
546 #if defined(FX) && !defined(WIN32)
547   globals->set_fullscreen(state);
548 #  if defined(XMESA_FX_FULLSCREEN) && defined(XMESA_FX_WINDOW)
549   XMesaSetFXmode( state ? XMESA_FX_FULLSCREEN : XMESA_FX_WINDOW );
550 #  endif
551 #endif
552 }
553
554 static bool
555 getFDMDataLogging ()
556 {
557   return fdm_data_logging;
558 }
559
560 static void
561 setFDMDataLogging (bool state)
562 {
563                                 // kludge; no getter or setter available
564   if (state != fdm_data_logging) {
565     fgToggleFDMdataLogging();
566     fdm_data_logging = state;
567   }
568 }
569
570 \f
571 ////////////////////////////////////////////////////////////////////////
572 // Tie the properties.
573 ////////////////////////////////////////////////////////////////////////
574
575 void
576 fgInitProps ()
577 {
578   cout << "start of fgInitProps()" << endl;
579                                 // Simulation
580   fgTie("/sim/logging/priority", getLoggingPriority, setLoggingPriority);
581   fgTie("/sim/logging/classes", getLoggingClasses, setLoggingClasses);
582   fgTie("/sim/freeze/master", getFreeze, setFreeze);
583   fgTie("/sim/aircraft-dir", getAircraftDir, setAircraftDir);
584
585   fgTie("/sim/time/elapsed-sec", getElapsedTime_sec);
586   fgTie("/sim/time/gmt", getDateString, setDateString);
587   fgSetArchivable("/sim/time/gmt");
588   fgTie("/sim/time/gmt-string", getGMTString);
589   fgTie("/sim/rendering/textures", getTextures, setTextures);
590
591                                 // Orientation
592   fgTie("/orientation/heading-magnetic-deg", getHeadingMag);
593
594                                 // Environment
595 #ifdef FG_WEATHERCM
596   fgTie("/environment/visibility-m", getVisibility, setVisibility);
597   fgSetArchivable("/environment/visibility-m");
598   fgTie("/environment/wind-from-north-fps", getWindNorth, setWindNorth);
599   fgSetArchivable("/environment/wind-from-north-fps");
600   fgTie("/environment/wind-from-east-fps", getWindEast, setWindEast);
601   fgSetArchivable("/environment/wind-from-east-fps");
602   fgTie("/environment/wind-from-down-fps", getWindDown, setWindDown);
603   fgSetArchivable("/environment/wind-from-down-fps");
604 #endif
605
606   fgTie("/environment/magnetic-variation-deg", getMagVar);
607   fgTie("/environment/magnetic-dip-deg", getMagDip);
608
609   fgTie("/sim/time/warp", getWarp, setWarp, false);
610   fgTie("/sim/time/warp-delta", getWarpDelta, setWarpDelta);
611
612                                 // Misc. Temporary junk.
613   fgTie("/sim/temp/winding-ccw", getWindingCCW, setWindingCCW, false);
614   fgTie("/sim/temp/full-screen", getFullScreen, setFullScreen);
615   fgTie("/sim/temp/fdm-data-logging", getFDMDataLogging, setFDMDataLogging);
616
617   cout << "end of fgInitProps()" << endl;
618 }
619
620
621 void
622 fgUpdateProps ()
623 {
624 }
625
626
627 \f
628 ////////////////////////////////////////////////////////////////////////
629 // Save and restore.
630 ////////////////////////////////////////////////////////////////////////
631
632
633 /**
634  * Save the current state of the simulator to a stream.
635  */
636 bool
637 fgSaveFlight (ostream &output, bool write_all)
638 {
639
640   fgSetBool("/sim/presets/onground", false);
641   fgSetArchivable("/sim/presets/onground");
642   fgSetBool("/sim/presets/trim", false);
643   fgSetArchivable("/sim/presets/trim");
644   fgSetString("/sim/presets/speed-set", "UVW");
645   fgSetArchivable("/sim/presets/speed-set");
646
647   try {
648     writeProperties(output, globals->get_props(), write_all);
649   } catch (const sg_exception &e) {
650     guiErrorMessage("Error saving flight: ", e);
651     return false;
652   }
653   return true;
654 }
655
656
657 /**
658  * Restore the current state of the simulator from a stream.
659  */
660 bool
661 fgLoadFlight (istream &input)
662 {
663   SGPropertyNode props;
664   try {
665     readProperties(input, &props);
666   } catch (const sg_exception &e) {
667     guiErrorMessage("Error reading saved flight: ", e);
668     return false;
669   }
670
671   fgSetBool("/sim/presets/onground", false);
672   fgSetBool("/sim/presets/trim", false);
673   fgSetString("/sim/presets/speed-set", "UVW");
674
675   copyProperties(&props, globals->get_props());
676   // When loading a flight, make it the
677   // new initial state.
678   globals->saveInitialState();
679   return true;
680 }
681
682
683 void
684 fgLoadProps (const char * path, SGPropertyNode * props)
685 {
686     SGPath loadpath(globals->get_fg_root());
687     loadpath.append(path);
688     readProperties(loadpath.c_str(), props);
689 }
690
691
692 \f
693 ////////////////////////////////////////////////////////////////////////
694 // Property convenience functions.
695 ////////////////////////////////////////////////////////////////////////
696
697 SGPropertyNode *
698 fgGetNode (const char * path, bool create)
699 {
700   return globals->get_props()->getNode(path, create);
701 }
702
703 SGPropertyNode * 
704 fgGetNode (const char * path, int index, bool create)
705 {
706   return globals->get_props()->getNode(path, index, create);
707 }
708
709 bool
710 fgHasNode (const char * path)
711 {
712   return (fgGetNode(path, false) != 0);
713 }
714
715 void
716 fgAddChangeListener (SGPropertyChangeListener * listener, const char * path)
717 {
718   fgGetNode(path, true)->addChangeListener(listener);
719 }
720
721 void
722 fgAddChangeListener (SGPropertyChangeListener * listener,
723                      const char * path, int index)
724 {
725   fgGetNode(path, index, true)->addChangeListener(listener);
726 }
727
728 bool
729 fgGetBool (const char * name, bool defaultValue)
730 {
731   return globals->get_props()->getBoolValue(name, defaultValue);
732 }
733
734 int
735 fgGetInt (const char * name, int defaultValue)
736 {
737   return globals->get_props()->getIntValue(name, defaultValue);
738 }
739
740 int
741 fgGetLong (const char * name, long defaultValue)
742 {
743   return globals->get_props()->getLongValue(name, defaultValue);
744 }
745
746 float
747 fgGetFloat (const char * name, float defaultValue)
748 {
749   return globals->get_props()->getFloatValue(name, defaultValue);
750 }
751
752 double
753 fgGetDouble (const char * name, double defaultValue)
754 {
755   return globals->get_props()->getDoubleValue(name, defaultValue);
756 }
757
758 const char *
759 fgGetString (const char * name, const char * defaultValue)
760 {
761   return globals->get_props()->getStringValue(name, defaultValue);
762 }
763
764 bool
765 fgSetBool (const char * name, bool val)
766 {
767   return globals->get_props()->setBoolValue(name, val);
768 }
769
770 bool
771 fgSetInt (const char * name, int val)
772 {
773   return globals->get_props()->setIntValue(name, val);
774 }
775
776 bool
777 fgSetLong (const char * name, long val)
778 {
779   return globals->get_props()->setLongValue(name, val);
780 }
781
782 bool
783 fgSetFloat (const char * name, float val)
784 {
785   return globals->get_props()->setFloatValue(name, val);
786 }
787
788 bool
789 fgSetDouble (const char * name, double val)
790 {
791   return globals->get_props()->setDoubleValue(name, val);
792 }
793
794 bool
795 fgSetString (const char * name, const char * val)
796 {
797   return globals->get_props()->setStringValue(name, val);
798 }
799
800 void
801 fgSetArchivable (const char * name, bool state)
802 {
803   SGPropertyNode * node = globals->get_props()->getNode(name);
804   if (node == 0)
805     SG_LOG(SG_GENERAL, SG_ALERT,
806            "Attempt to set archive flag for non-existant property "
807            << name);
808   else
809     node->setAttribute(SGPropertyNode::ARCHIVE, state);
810 }
811
812 void
813 fgSetReadable (const char * name, bool state)
814 {
815   SGPropertyNode * node = globals->get_props()->getNode(name);
816   if (node == 0)
817     SG_LOG(SG_GENERAL, SG_ALERT,
818            "Attempt to set read flag for non-existant property "
819            << name);
820   else
821     node->setAttribute(SGPropertyNode::READ, state);
822 }
823
824 void
825 fgSetWritable (const char * name, bool state)
826 {
827   SGPropertyNode * node = globals->get_props()->getNode(name);
828   if (node == 0)
829     SG_LOG(SG_GENERAL, SG_ALERT,
830            "Attempt to set write flag for non-existant property "
831            << name);
832   else
833     node->setAttribute(SGPropertyNode::WRITE, state);
834 }
835
836 void
837 fgUntie (const char * name)
838 {
839   if (!globals->get_props()->untie(name))
840     SG_LOG(SG_GENERAL, SG_WARN, "Failed to untie property " << name);
841 }
842
843
844
845 \f
846 ////////////////////////////////////////////////////////////////////////
847 // Implementation of FGCondition.
848 ////////////////////////////////////////////////////////////////////////
849
850 FGCondition::FGCondition ()
851 {
852 }
853
854 FGCondition::~FGCondition ()
855 {
856 }
857
858
859 \f
860 ////////////////////////////////////////////////////////////////////////
861 // Implementation of FGPropertyCondition.
862 ////////////////////////////////////////////////////////////////////////
863
864 FGPropertyCondition::FGPropertyCondition (const char * propname)
865   : _node(fgGetNode(propname, true))
866 {
867 }
868
869 FGPropertyCondition::~FGPropertyCondition ()
870 {
871 }
872
873
874 \f
875 ////////////////////////////////////////////////////////////////////////
876 // Implementation of FGNotCondition.
877 ////////////////////////////////////////////////////////////////////////
878
879 FGNotCondition::FGNotCondition (FGCondition * condition)
880   : _condition(condition)
881 {
882 }
883
884 FGNotCondition::~FGNotCondition ()
885 {
886   delete _condition;
887 }
888
889 bool
890 FGNotCondition::test () const
891 {
892   return !(_condition->test());
893 }
894
895
896 \f
897 ////////////////////////////////////////////////////////////////////////
898 // Implementation of FGAndCondition.
899 ////////////////////////////////////////////////////////////////////////
900
901 FGAndCondition::FGAndCondition ()
902 {
903 }
904
905 FGAndCondition::~FGAndCondition ()
906 {
907   for (unsigned int i = 0; i < _conditions.size(); i++)
908     delete _conditions[i];
909 }
910
911 bool
912 FGAndCondition::test () const
913 {
914   int nConditions = _conditions.size();
915   for (int i = 0; i < nConditions; i++) {
916     if (!_conditions[i]->test())
917       return false;
918   }
919   return true;
920 }
921
922 void
923 FGAndCondition::addCondition (FGCondition * condition)
924 {
925   _conditions.push_back(condition);
926 }
927
928
929 \f
930 ////////////////////////////////////////////////////////////////////////
931 // Implementation of FGOrCondition.
932 ////////////////////////////////////////////////////////////////////////
933
934 FGOrCondition::FGOrCondition ()
935 {
936 }
937
938 FGOrCondition::~FGOrCondition ()
939 {
940   for (unsigned int i = 0; i < _conditions.size(); i++)
941     delete _conditions[i];
942 }
943
944 bool
945 FGOrCondition::test () const
946 {
947   int nConditions = _conditions.size();
948   for (int i = 0; i < nConditions; i++) {
949     if (_conditions[i]->test())
950       return true;
951   }
952   return false;
953 }
954
955 void
956 FGOrCondition::addCondition (FGCondition * condition)
957 {
958   _conditions.push_back(condition);
959 }
960
961
962 \f
963 ////////////////////////////////////////////////////////////////////////
964 // Implementation of FGComparisonCondition.
965 ////////////////////////////////////////////////////////////////////////
966
967 static int
968 doComparison (const SGPropertyNode * left, const SGPropertyNode *right)
969 {
970   switch (left->getType()) {
971   case SGPropertyNode::BOOL: {
972     bool v1 = left->getBoolValue();
973     bool v2 = right->getBoolValue();
974     if (v1 < v2)
975       return FGComparisonCondition::LESS_THAN;
976     else if (v1 > v2)
977       return FGComparisonCondition::GREATER_THAN;
978     else
979       return FGComparisonCondition::EQUALS;
980     break;
981   }
982   case SGPropertyNode::INT: {
983     int v1 = left->getIntValue();
984     int v2 = right->getIntValue();
985     if (v1 < v2)
986       return FGComparisonCondition::LESS_THAN;
987     else if (v1 > v2)
988       return FGComparisonCondition::GREATER_THAN;
989     else
990       return FGComparisonCondition::EQUALS;
991     break;
992   }
993   case SGPropertyNode::LONG: {
994     long v1 = left->getLongValue();
995     long v2 = right->getLongValue();
996     if (v1 < v2)
997       return FGComparisonCondition::LESS_THAN;
998     else if (v1 > v2)
999       return FGComparisonCondition::GREATER_THAN;
1000     else
1001       return FGComparisonCondition::EQUALS;
1002     break;
1003   }
1004   case SGPropertyNode::FLOAT: {
1005     float v1 = left->getFloatValue();
1006     float v2 = right->getFloatValue();
1007     if (v1 < v2)
1008       return FGComparisonCondition::LESS_THAN;
1009     else if (v1 > v2)
1010       return FGComparisonCondition::GREATER_THAN;
1011     else
1012       return FGComparisonCondition::EQUALS;
1013     break;
1014   }
1015   case SGPropertyNode::DOUBLE: {
1016     double v1 = left->getDoubleValue();
1017     double v2 = right->getDoubleValue();
1018     if (v1 < v2)
1019       return FGComparisonCondition::LESS_THAN;
1020     else if (v1 > v2)
1021       return FGComparisonCondition::GREATER_THAN;
1022     else
1023       return FGComparisonCondition::EQUALS;
1024     break;
1025   }
1026   case SGPropertyNode::STRING: 
1027   case SGPropertyNode::NONE:
1028   case SGPropertyNode::UNSPECIFIED: {
1029     string v1 = left->getStringValue();
1030     string v2 = right->getStringValue();
1031     if (v1 < v2)
1032       return FGComparisonCondition::LESS_THAN;
1033     else if (v1 > v2)
1034       return FGComparisonCondition::GREATER_THAN;
1035     else
1036       return FGComparisonCondition::EQUALS;
1037     break;
1038   }
1039   }
1040   throw sg_exception("Unrecognized node type");
1041   return 0;
1042 }
1043
1044
1045 FGComparisonCondition::FGComparisonCondition (Type type, bool reverse)
1046   : _type(type),
1047     _reverse(reverse),
1048     _left_property(0),
1049     _right_property(0),
1050     _right_value(0)
1051 {
1052 }
1053
1054 FGComparisonCondition::~FGComparisonCondition ()
1055 {
1056   delete _right_value;
1057 }
1058
1059 bool
1060 FGComparisonCondition::test () const
1061 {
1062                                 // Always fail if incompletely specified
1063   if (_left_property == 0 ||
1064       (_right_property == 0 && _right_value == 0))
1065     return false;
1066
1067                                 // Get LESS_THAN, EQUALS, or GREATER_THAN
1068   int cmp =
1069     doComparison(_left_property,
1070                  (_right_property != 0 ? _right_property : _right_value));
1071   if (!_reverse)
1072     return (cmp == _type);
1073   else
1074     return (cmp != _type);
1075 }
1076
1077 void
1078 FGComparisonCondition::setLeftProperty (const char * propname)
1079 {
1080   _left_property = fgGetNode(propname, true);
1081 }
1082
1083 void
1084 FGComparisonCondition::setRightProperty (const char * propname)
1085 {
1086   delete _right_value;
1087   _right_value = 0;
1088   _right_property = fgGetNode(propname, true);
1089 }
1090
1091 void
1092 FGComparisonCondition::setRightValue (const SGPropertyNode *node)
1093 {
1094   _right_property = 0;
1095   delete _right_value;
1096   _right_value = new SGPropertyNode(*node);
1097 }
1098
1099
1100 \f
1101 ////////////////////////////////////////////////////////////////////////
1102 // Read a condition and use it if necessary.
1103 ////////////////////////////////////////////////////////////////////////
1104
1105                                 // Forward declaration
1106 static FGCondition * readCondition (const SGPropertyNode * node);
1107
1108 static FGCondition *
1109 readPropertyCondition (const SGPropertyNode * node)
1110 {
1111   return new FGPropertyCondition(node->getStringValue());
1112 }
1113
1114 static FGCondition *
1115 readNotCondition (const SGPropertyNode * node)
1116 {
1117   int nChildren = node->nChildren();
1118   for (int i = 0; i < nChildren; i++) {
1119     const SGPropertyNode * child = node->getChild(i);
1120     FGCondition * condition = readCondition(child);
1121     if (condition != 0)
1122       return new FGNotCondition(condition);
1123   }
1124   SG_LOG(SG_COCKPIT, SG_ALERT, "Panel: empty 'not' condition");
1125   return 0;
1126 }
1127
1128 static FGCondition *
1129 readAndConditions (const SGPropertyNode * node)
1130 {
1131   FGAndCondition * andCondition = new FGAndCondition;
1132   int nChildren = node->nChildren();
1133   for (int i = 0; i < nChildren; i++) {
1134     const SGPropertyNode * child = node->getChild(i);
1135     FGCondition * condition = readCondition(child);
1136     if (condition != 0)
1137       andCondition->addCondition(condition);
1138   }
1139   return andCondition;
1140 }
1141
1142 static FGCondition *
1143 readOrConditions (const SGPropertyNode * node)
1144 {
1145   FGOrCondition * orCondition = new FGOrCondition;
1146   int nChildren = node->nChildren();
1147   for (int i = 0; i < nChildren; i++) {
1148     const SGPropertyNode * child = node->getChild(i);
1149     FGCondition * condition = readCondition(child);
1150     if (condition != 0)
1151       orCondition->addCondition(condition);
1152   }
1153   return orCondition;
1154 }
1155
1156 static FGCondition *
1157 readComparison (const SGPropertyNode * node,
1158                 FGComparisonCondition::Type type,
1159                 bool reverse)
1160 {
1161   FGComparisonCondition * condition = new FGComparisonCondition(type, reverse);
1162   condition->setLeftProperty(node->getStringValue("property[0]"));
1163   if (node->hasValue("property[1]"))
1164     condition->setRightProperty(node->getStringValue("property[1]"));
1165   else
1166     condition->setRightValue(node->getChild("value", 0));
1167
1168   return condition;
1169 }
1170
1171 static FGCondition *
1172 readCondition (const SGPropertyNode * node)
1173 {
1174   const string &name = node->getName();
1175   if (name == "property")
1176     return readPropertyCondition(node);
1177   else if (name == "not")
1178     return readNotCondition(node);
1179   else if (name == "and")
1180     return readAndConditions(node);
1181   else if (name == "or")
1182     return readOrConditions(node);
1183   else if (name == "less-than")
1184     return readComparison(node, FGComparisonCondition::LESS_THAN, false);
1185   else if (name == "less-than-equals")
1186     return readComparison(node, FGComparisonCondition::GREATER_THAN, true);
1187   else if (name == "greater-than")
1188     return readComparison(node, FGComparisonCondition::GREATER_THAN, false);
1189   else if (name == "greater-than-equals")
1190     return readComparison(node, FGComparisonCondition::LESS_THAN, true);
1191   else if (name == "equals")
1192     return readComparison(node, FGComparisonCondition::EQUALS, false);
1193   else if (name == "not-equals")
1194     return readComparison(node, FGComparisonCondition::EQUALS, true);
1195   else
1196     return 0;
1197 }
1198
1199
1200 \f
1201 ////////////////////////////////////////////////////////////////////////
1202 // Implementation of FGConditional.
1203 ////////////////////////////////////////////////////////////////////////
1204
1205 FGConditional::FGConditional ()
1206   : _condition (0)
1207 {
1208 }
1209
1210 FGConditional::~FGConditional ()
1211 {
1212   delete _condition;
1213 }
1214
1215 void
1216 FGConditional::setCondition (FGCondition * condition)
1217 {
1218   delete _condition;
1219   _condition = condition;
1220 }
1221
1222 bool
1223 FGConditional::test () const
1224 {
1225   return ((_condition == 0) || _condition->test());
1226 }
1227
1228
1229 \f
1230 // The top-level is always an implicit 'and' group
1231 FGCondition *
1232 fgReadCondition (const SGPropertyNode * node)
1233 {
1234   return readAndConditions(node);
1235 }
1236
1237
1238 // end of fg_props.cxx