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