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