]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/FGFDMExec.cpp
sync with JSBSim CVS
[flightgear.git] / src / FDM / JSBSim / FGFDMExec.cpp
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3  Module:       FGFDMExec.cpp
4  Author:       Jon S. Berndt
5  Date started: 11/17/98
6  Purpose:      Schedules and runs the model routines.
7
8  ------------- Copyright (C) 1999  Jon S. Berndt (jon@jsbsim.org) -------------
9
10  This program is free software; you can redistribute it and/or modify it under
11  the terms of the GNU Lesser General Public License as published by the Free Software
12  Foundation; either version 2 of the License, or (at your option) any later
13  version.
14
15  This program is distributed in the hope that it will be useful, but WITHOUT
16  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
18  details.
19
20  You should have received a copy of the GNU Lesser General Public License along with
21  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
22  Place - Suite 330, Boston, MA  02111-1307, USA.
23
24  Further information about the GNU Lesser General Public License can also be found on
25  the world wide web at http://www.gnu.org.
26
27 FUNCTIONAL DESCRIPTION
28 --------------------------------------------------------------------------------
29
30 This class wraps up the simulation scheduling routines.
31
32 HISTORY
33 --------------------------------------------------------------------------------
34 11/17/98   JSB   Created
35
36 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37 COMMENTS, REFERENCES,  and NOTES
38 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
40 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41 INCLUDES
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
43
44 #include "FGFDMExec.h"
45 #include "models/FGAtmosphere.h"
46 #include "models/atmosphere/FGMSIS.h"
47 #include "models/atmosphere/FGMars.h"
48 #include "models/FGFCS.h"
49 #include "models/FGPropulsion.h"
50 #include "models/FGMassBalance.h"
51 #include "models/FGGroundReactions.h"
52 #include "models/FGExternalReactions.h"
53 #include "models/FGBuoyantForces.h"
54 #include "models/FGAerodynamics.h"
55 #include "models/FGInertial.h"
56 #include "models/FGAircraft.h"
57 #include "models/FGPropagate.h"
58 #include "models/FGAuxiliary.h"
59 #include "models/FGInput.h"
60 #include "models/FGOutput.h"
61 #include "initialization/FGInitialCondition.h"
62 //#include "initialization/FGTrimAnalysis.h" // Remove until later
63 #include "input_output/FGPropertyManager.h"
64 #include "input_output/FGScript.h"
65
66 #include <iostream>
67 #include <iterator>
68 #include <cstdlib>
69
70 using namespace std;
71
72 namespace JSBSim {
73
74 static const char *IdSrc = "$Id: FGFDMExec.cpp,v 1.95 2011/05/20 10:35:25 jberndt Exp $";
75 static const char *IdHdr = ID_FDMEXEC;
76
77 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78 CLASS IMPLEMENTATION
79 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
80
81 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82 // Constructor
83
84 FGFDMExec::FGFDMExec(FGPropertyManager* root, unsigned int* fdmctr) : Root(root), FDMctr(fdmctr)
85 {
86
87   Frame           = 0;
88   Error           = 0;
89   GroundCallback  = 0;
90   Atmosphere      = 0;
91   FCS             = 0;
92   Propulsion      = 0;
93   MassBalance     = 0;
94   Aerodynamics    = 0;
95   Inertial        = 0;
96   GroundReactions = 0;
97   ExternalReactions = 0;
98   BuoyantForces   = 0;
99   Aircraft        = 0;
100   Propagate       = 0;
101   Auxiliary       = 0;
102   Input           = 0;
103   IC              = 0;
104   Trim            = 0;
105   Script          = 0;
106
107   RootDir = "";
108
109   modelLoaded = false;
110   IsChild = false;
111   holding = false;
112   Terminate = false;
113   StandAlone = false;
114
115   sim_time = 0.0;
116   dT = 1.0/120.0; // a default timestep size. This is needed for when JSBSim is
117                   // run in standalone mode with no initialization file.
118
119   AircraftPath = "aircraft";
120   EnginePath = "engine";
121   SystemsPath = "systems";
122
123   try {
124     char* num = getenv("JSBSIM_DEBUG");
125     if (num) debug_lvl = atoi(num); // set debug level
126   } catch (...) {                   // if error set to 1
127     debug_lvl = 1;
128   }
129
130   if (Root == 0) {                 // Then this is the root FDM
131     Root = new FGPropertyManager;  // Create the property manager
132     StandAlone = true;
133   }
134
135   if (FDMctr == 0) {
136     FDMctr = new unsigned int;     // Create and initialize the child FDM counter
137     (*FDMctr) = 0;
138   }
139
140   // Store this FDM's ID
141   IdFDM = (*FDMctr); // The main (parent) JSBSim instance is always the "zeroth"
142                                                                       
143   // Prepare FDMctr for the next child FDM id
144   (*FDMctr)++;       // instance. "child" instances are loaded last.
145
146   instance = Root->GetNode("/fdm/jsbsim",IdFDM,true);
147   Debug(0);
148   // this is to catch errors in binding member functions to the property tree.
149   try {
150     Allocate();
151   } catch ( string msg ) {
152     cout << "Caught error: " << msg << endl;
153     exit(1);
154   }
155
156   trim_status = false;
157   ta_mode     = 99;
158
159   Constructing = true;
160   typedef int (FGFDMExec::*iPMF)(void) const;
161 //  instance->Tie("simulation/do_trim_analysis", this, (iPMF)0, &FGFDMExec::DoTrimAnalysis, false);
162   instance->Tie("simulation/do_simple_trim", this, (iPMF)0, &FGFDMExec::DoTrim, false);
163   instance->Tie("simulation/reset", this, (iPMF)0, &FGFDMExec::ResetToInitialConditions, false);
164   instance->Tie("simulation/terminate", (int *)&Terminate);
165   instance->Tie("simulation/sim-time-sec", this, &FGFDMExec::GetSimTime);
166   instance->Tie("simulation/jsbsim-debug", this, &FGFDMExec::GetDebugLevel, &FGFDMExec::SetDebugLevel);
167   instance->Tie("simulation/frame", (int *)&Frame, false);
168
169   Constructing = false;
170 }
171
172 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
173
174 FGFDMExec::~FGFDMExec()
175 {
176   try {
177     Unbind();
178     DeAllocate();
179     
180     if (IdFDM == 0) { // Meaning this is no child FDM
181       if(Root != 0) {
182          if(StandAlone)
183             delete Root;
184          Root = 0;
185       }
186       if(FDMctr != 0) {
187          delete FDMctr;
188          FDMctr = 0;
189       }
190     }
191   } catch ( string msg ) {
192     cout << "Caught error: " << msg << endl;
193   }
194
195   for (unsigned int i=1; i<ChildFDMList.size(); i++) delete ChildFDMList[i]->exec;
196   ChildFDMList.clear();
197
198   PropertyCatalog.clear();
199
200   FDMctr--;
201
202   Debug(1);
203 }
204
205 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
206
207 bool FGFDMExec::Allocate(void)
208 {
209   bool result=true;
210
211   Atmosphere      = new FGAtmosphere(this);
212   FCS             = new FGFCS(this);
213   Propulsion      = new FGPropulsion(this);
214   MassBalance     = new FGMassBalance(this);
215   Aerodynamics    = new FGAerodynamics (this);
216   Inertial        = new FGInertial(this);
217
218   GroundCallback  = new FGGroundCallback(Inertial->GetRefRadius());
219
220   GroundReactions = new FGGroundReactions(this);
221   ExternalReactions = new FGExternalReactions(this);
222   BuoyantForces   = new FGBuoyantForces(this);
223   Aircraft        = new FGAircraft(this);
224   Propagate       = new FGPropagate(this);
225   Auxiliary       = new FGAuxiliary(this);
226   Input           = new FGInput(this);
227
228   // Schedule a model. The second arg (the integer) is the pass number. For
229   // instance, the atmosphere model could get executed every fifth pass it is called.
230   
231   Schedule(Input,           1);   // Input model is Models[0]
232   Schedule(Atmosphere,      1);   // Input model is Models[1]
233   Schedule(FCS,             1);   // Input model is Models[2]
234   Schedule(Propulsion,      1);   // Input model is Models[3]
235   Schedule(MassBalance,     1);   // Input model is Models[4]
236   Schedule(Aerodynamics,    1);   // Input model is Models[5]
237   Schedule(Inertial,        1);   // Input model is Models[6]
238   Schedule(GroundReactions, 1);   // Input model is Models[7]
239   Schedule(ExternalReactions, 1); // Input model is Models[8]
240   Schedule(BuoyantForces,   1);   // Input model is Models[9]
241   Schedule(Aircraft,        1);   // Input model is Models[10]
242   Schedule(Propagate,       1);   // Input model is Models[11]
243   Schedule(Auxiliary,       1);   // Input model is Models[12]
244
245   // Initialize models so they can communicate with each other
246
247   vector <FGModel*>::iterator it;
248   for (it = Models.begin(); it != Models.end(); ++it) (*it)->InitModel();
249
250   IC = new FGInitialCondition(this);
251
252   modelLoaded = false;
253
254   return result;
255 }
256
257 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
258
259 bool FGFDMExec::DeAllocate(void)
260 {
261   delete Input;
262   delete Atmosphere;
263   delete FCS;
264   delete Propulsion;
265   delete MassBalance;
266   delete Aerodynamics;
267   delete Inertial;
268   delete GroundReactions;
269   delete ExternalReactions;
270   delete BuoyantForces;
271   delete Aircraft;
272   delete Propagate;
273   delete Auxiliary;
274   delete Script;
275
276   for (unsigned i=0; i<Outputs.size(); i++) delete Outputs[i];
277   Outputs.clear();
278
279   delete IC;
280   delete Trim;
281
282   delete GroundCallback;
283
284   Error       = 0;
285
286   Input           = 0;
287   Atmosphere      = 0;
288   FCS             = 0;
289   Propulsion      = 0;
290   MassBalance     = 0;
291   Aerodynamics    = 0;
292   Inertial        = 0;
293   GroundReactions = 0;
294   ExternalReactions = 0;
295   BuoyantForces   = 0;
296   Aircraft        = 0;
297   Propagate       = 0;
298   Auxiliary       = 0;
299   Script          = 0;
300
301   Models.clear();
302
303   modelLoaded = false;
304   return modelLoaded;
305 }
306
307 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
308
309 void FGFDMExec::Schedule(FGModel* model, int rate)
310 {
311   model->SetRate(rate);
312   Models.push_back(model);
313 }
314
315 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
316
317 bool FGFDMExec::Run(void)
318 {
319   bool success=true;
320
321   Debug(2);
322
323   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
324     ChildFDMList[i]->AssignState(Propagate); // Transfer state to the child FDM
325     ChildFDMList[i]->Run();
326   }
327
328   // returns true if success, false if complete
329   if (Script != 0 && !IntegrationSuspended()) success = Script->RunScript();
330
331   vector <FGModel*>::iterator it;
332   for (it = Models.begin(); it != Models.end(); ++it) (*it)->Run(holding);
333
334   IncrTime();
335   if (Terminate) success = false;
336
337   return (success);
338 }
339
340 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
341 // This call will cause the sim time to reset to 0.0
342
343 bool FGFDMExec::RunIC(void)
344 {
345   SuspendIntegration(); // saves the integration rate, dt, then sets it to 0.0.
346   Initialize(IC);
347   Run();
348   ResumeIntegration(); // Restores the integration rate to what it was.
349
350   return true;
351 }
352
353 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
354
355 void FGFDMExec::Initialize(FGInitialCondition *FGIC)
356 {
357   Setsim_time(0.0);
358
359   Propagate->SetInitialState( FGIC );
360
361   Atmosphere->Run(false);
362   Atmosphere->SetWindNED( FGIC->GetWindNFpsIC(),
363                           FGIC->GetWindEFpsIC(),
364                           FGIC->GetWindDFpsIC() );
365
366   Auxiliary->Run(false);
367 }
368
369 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
370 //
371 // A private, internal function call for Tie-ing to a property, so it needs an
372 // argument.
373
374 void FGFDMExec::ResetToInitialConditions(int mode)
375 {
376   if (mode == 1) {
377     for (unsigned int i=0; i<Outputs.size(); i++) {
378       Outputs[i]->SetStartNewFile(true); 
379     }
380   }
381   
382   ResetToInitialConditions();
383 }
384
385 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
386
387 void FGFDMExec::ResetToInitialConditions(void)
388 {
389   if (Constructing) return;
390
391   vector <FGModel*>::iterator it;
392   for (it = Models.begin(); it != Models.end(); ++it) (*it)->InitModel();
393
394   RunIC();
395   if (Script) Script->ResetEvents();
396 }
397
398 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399
400 void FGFDMExec::SetGroundCallback(FGGroundCallback* p)
401 {
402   delete GroundCallback;
403   GroundCallback = p;
404 }
405
406 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
407
408 vector <string> FGFDMExec::EnumerateFDMs(void)
409 {
410   vector <string> FDMList;
411
412   FDMList.push_back(Aircraft->GetAircraftName());
413
414   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
415     FDMList.push_back(ChildFDMList[i]->exec->GetAircraft()->GetAircraftName());
416   }
417
418   return FDMList;
419 }
420
421 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
422
423 bool FGFDMExec::LoadScript(const string& script, double deltaT)
424 {
425   bool result;
426
427   Script = new FGScript(this);
428   result = Script->LoadScript(RootDir + script, deltaT);
429
430   return result;
431 }
432
433 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
434
435 bool FGFDMExec::LoadModel(const string& AircraftPath, const string& EnginePath, const string& SystemsPath,
436                 const string& model, bool addModelToPath)
437 {
438   FGFDMExec::AircraftPath = RootDir + AircraftPath;
439   FGFDMExec::EnginePath = RootDir + EnginePath;
440   FGFDMExec::SystemsPath = RootDir + SystemsPath;
441
442   return LoadModel(model, addModelToPath);
443 }
444
445 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
446
447 bool FGFDMExec::LoadModel(const string& model, bool addModelToPath)
448 {
449   string token;
450   string aircraftCfgFileName;
451   Element* element = 0L;
452   bool result = false; // initialize result to false, indicating input file not yet read
453
454   modelName = model; // Set the class modelName attribute
455
456   if( AircraftPath.empty() || EnginePath.empty() || SystemsPath.empty()) {
457     cerr << "Error: attempted to load aircraft with undefined ";
458     cerr << "aircraft, engine, and system paths" << endl;
459     return false;
460   }
461
462   FullAircraftPath = AircraftPath;
463   if (addModelToPath) FullAircraftPath += "/" + model;
464   aircraftCfgFileName = FullAircraftPath + "/" + model + ".xml";
465
466   if (modelLoaded) {
467     DeAllocate();
468     Allocate();
469   }
470
471   int saved_debug_lvl = debug_lvl;
472
473   document = LoadXMLDocument(aircraftCfgFileName); // "document" is a class member
474   if (document) {
475     if (IsChild) debug_lvl = 0;
476
477     ReadPrologue(document);
478
479     if (IsChild) debug_lvl = saved_debug_lvl;
480
481     // Process the fileheader element in the aircraft config file. This element is OPTIONAL.
482     element = document->FindElement("fileheader");
483     if (element) {
484       result = ReadFileHeader(element);
485       if (!result) {
486         cerr << endl << "Aircraft fileheader element has problems in file " << aircraftCfgFileName << endl;
487         return result;
488       }
489     }
490
491     if (IsChild) debug_lvl = 0;
492
493     // Process the metrics element. This element is REQUIRED.
494     element = document->FindElement("metrics");
495     if (element) {
496       result = Aircraft->Load(element);
497       if (!result) {
498         cerr << endl << "Aircraft metrics element has problems in file " << aircraftCfgFileName << endl;
499         return result;
500       }
501     } else {
502       cerr << endl << "No metrics element was found in the aircraft config file." << endl;
503       return false;
504     }
505
506     // Process the mass_balance element. This element is REQUIRED.
507     element = document->FindElement("mass_balance");
508     if (element) {
509       result = MassBalance->Load(element);
510       if (!result) {
511         cerr << endl << "Aircraft mass_balance element has problems in file " << aircraftCfgFileName << endl;
512         return result;
513       }
514     } else {
515       cerr << endl << "No mass_balance element was found in the aircraft config file." << endl;
516       return false;
517     }
518
519     // Process the ground_reactions element. This element is REQUIRED.
520     element = document->FindElement("ground_reactions");
521     if (element) {
522       result = GroundReactions->Load(element);
523       if (!result) {
524         cerr << endl << "Aircraft ground_reactions element has problems in file " << aircraftCfgFileName << endl;
525         return result;
526       }
527     } else {
528       cerr << endl << "No ground_reactions element was found in the aircraft config file." << endl;
529       return false;
530     }
531
532     // Process the external_reactions element. This element is OPTIONAL.
533     element = document->FindElement("external_reactions");
534     if (element) {
535       result = ExternalReactions->Load(element);
536       if (!result) {
537         cerr << endl << "Aircraft external_reactions element has problems in file " << aircraftCfgFileName << endl;
538         return result;
539       }
540     }
541
542     // Process the buoyant_forces element. This element is OPTIONAL.
543     element = document->FindElement("buoyant_forces");
544     if (element) {
545       result = BuoyantForces->Load(element);
546       if (!result) {
547         cerr << endl << "Aircraft buoyant_forces element has problems in file " << aircraftCfgFileName << endl;
548         return result;
549       }
550     }
551
552     // Process the propulsion element. This element is OPTIONAL.
553     element = document->FindElement("propulsion");
554     if (element) {
555       result = Propulsion->Load(element);
556       if (!result) {
557         cerr << endl << "Aircraft propulsion element has problems in file " << aircraftCfgFileName << endl;
558         return result;
559       }
560     }
561
562     // Process the system element[s]. This element is OPTIONAL, and there may be more than one.
563     element = document->FindElement("system");
564     while (element) {
565       result = FCS->Load(element, FGFCS::stSystem);
566       if (!result) {
567         cerr << endl << "Aircraft system element has problems in file " << aircraftCfgFileName << endl;
568         return result;
569       }
570       element = document->FindNextElement("system");
571     }
572
573     // Process the autopilot element. This element is OPTIONAL.
574     element = document->FindElement("autopilot");
575     if (element) {
576       result = FCS->Load(element, FGFCS::stAutoPilot);
577       if (!result) {
578         cerr << endl << "Aircraft autopilot element has problems in file " << aircraftCfgFileName << endl;
579         return result;
580       }
581     }
582
583     // Process the flight_control element. This element is OPTIONAL.
584     element = document->FindElement("flight_control");
585     if (element) {
586       result = FCS->Load(element, FGFCS::stFCS);
587       if (!result) {
588         cerr << endl << "Aircraft flight_control element has problems in file " << aircraftCfgFileName << endl;
589         return result;
590       }
591     }
592
593     // Process the aerodynamics element. This element is OPTIONAL, but almost always expected.
594     element = document->FindElement("aerodynamics");
595     if (element) {
596       result = Aerodynamics->Load(element);
597       if (!result) {
598         cerr << endl << "Aircraft aerodynamics element has problems in file " << aircraftCfgFileName << endl;
599         return result;
600       }
601     } else {
602       cerr << endl << "No expected aerodynamics element was found in the aircraft config file." << endl;
603     }
604
605     // Process the input element. This element is OPTIONAL.
606     element = document->FindElement("input");
607     if (element) {
608       result = Input->Load(element);
609       if (!result) {
610         cerr << endl << "Aircraft input element has problems in file " << aircraftCfgFileName << endl;
611         return result;
612       }
613     }
614
615     // Process the output element[s]. This element is OPTIONAL, and there may be more than one.
616     unsigned int idx=0;
617     typedef double (FGOutput::*iOPMF)(void) const;
618     typedef int (FGFDMExec::*iOPV)(void) const;
619     typedef void (FGFDMExec::*vOPI)(int) const;
620     element = document->FindElement("output");
621     while (element) {
622       if (debug_lvl > 0) cout << endl << "  Output data set: " << idx << "  ";
623       FGOutput* Output = new FGOutput(this);
624       Output->InitModel();
625       Schedule(Output, 1);
626       result = Output->Load(element);
627       if (!result) {
628         cerr << endl << "Aircraft output element has problems in file " << aircraftCfgFileName << endl;
629         return result;
630       } else {
631         Outputs.push_back(Output);
632         string outputProp = CreateIndexedPropertyName("simulation/output",idx);
633         instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate, false);
634         instance->Tie("simulation/force-output", this, (iOPV)0, &FGFDMExec::ForceOutput, false);
635         idx++;
636       }
637       element = document->FindNextElement("output");
638     }
639
640     // Lastly, process the child element. This element is OPTIONAL - and NOT YET SUPPORTED.
641     element = document->FindElement("child");
642     if (element) {
643       result = ReadChild(element);
644       if (!result) {
645         cerr << endl << "Aircraft child element has problems in file " << aircraftCfgFileName << endl;
646         return result;
647       }
648     }
649
650     modelLoaded = true;
651
652     if (debug_lvl > 0) {
653       MassBalance->Run(false); // Update all mass properties for the report.
654       MassBalance->GetMassPropertiesReport();
655
656       cout << endl << fgblue << highint
657            << "End of vehicle configuration loading." << endl
658            << "-------------------------------------------------------------------------------"
659            << reset << endl;
660     }
661     
662     if (IsChild) debug_lvl = saved_debug_lvl;
663
664   } else {
665     cerr << fgred
666          << "  JSBSim failed to open the configuration file: " << aircraftCfgFileName
667          << fgdef << endl;
668   }
669
670   if (result) {
671     struct PropertyCatalogStructure masterPCS;
672     masterPCS.base_string = "";
673     masterPCS.node = (FGPropertyManager*)Root;
674     BuildPropertyCatalog(&masterPCS);
675   }
676
677   return result;
678 }
679
680 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
681
682 void FGFDMExec::BuildPropertyCatalog(struct PropertyCatalogStructure* pcs)
683 {
684   struct PropertyCatalogStructure* pcsNew = new struct PropertyCatalogStructure;
685   int node_idx = 0;
686
687   for (int i=0; i<pcs->node->nChildren(); i++) {
688     pcsNew->base_string = pcs->base_string + "/" + pcs->node->getChild(i)->getName();
689     node_idx = pcs->node->getChild(i)->getIndex();
690     if (node_idx != 0) {
691       pcsNew->base_string = CreateIndexedPropertyName(pcsNew->base_string, node_idx);
692     }
693     if (pcs->node->getChild(i)->nChildren() == 0) {
694       if (pcsNew->base_string.substr(0,11) == string("/fdm/jsbsim")) {
695         pcsNew->base_string = pcsNew->base_string.erase(0,12);
696       }
697       PropertyCatalog.push_back(pcsNew->base_string);
698     } else {
699       pcsNew->node = (FGPropertyManager*)pcs->node->getChild(i);
700       BuildPropertyCatalog(pcsNew);
701     }
702   }
703   delete pcsNew;
704 }
705
706 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
707
708 string FGFDMExec::QueryPropertyCatalog(const string& in)
709 {
710   string results="";
711   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
712     if (PropertyCatalog[i].find(in) != string::npos) results += PropertyCatalog[i] + "\n";
713   }
714   if (results.empty()) return "No matches found\n";
715   return results;
716 }
717
718 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
719
720 void FGFDMExec::PrintPropertyCatalog(void)
721 {
722   cout << endl;
723   cout << "  " << fgblue << highint << underon << "Property Catalog for "
724        << modelName << reset << endl << endl;
725   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
726     cout << "    " << PropertyCatalog[i] << endl;
727   }
728 }
729
730 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
731
732 bool FGFDMExec::ReadFileHeader(Element* el)
733 {
734   bool result = true; // true for success
735
736   if (debug_lvl == 0) return result;
737
738   if (IsChild) {
739     cout << endl <<highint << fgblue << "Reading child model: " << IdFDM << reset << endl << endl;
740   }
741
742   if (el->FindElement("description"))
743     cout << "  Description:   " << el->FindElement("description")->GetDataLine() << endl;
744   if (el->FindElement("author"))
745     cout << "  Model Author:  " << el->FindElement("author")->GetDataLine() << endl;
746   if (el->FindElement("filecreationdate"))
747     cout << "  Creation Date: " << el->FindElement("filecreationdate")->GetDataLine() << endl;
748   if (el->FindElement("version"))
749     cout << "  Version:       " << el->FindElement("version")->GetDataLine() << endl;
750
751   return result;
752 }
753
754 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
755
756 bool FGFDMExec::ReadPrologue(Element* el) // el for ReadPrologue is the document element
757 {
758   bool result = true; // true for success
759
760   if (!el) return false;
761
762   string AircraftName = el->GetAttributeValue("name");
763   Aircraft->SetAircraftName(AircraftName);
764
765   if (debug_lvl & 1) cout << underon << "Reading Aircraft Configuration File"
766             << underoff << ": " << highint << AircraftName << normint << endl;
767
768   CFGVersion = el->GetAttributeValue("version");
769   Release    = el->GetAttributeValue("release");
770
771   if (debug_lvl & 1)
772     cout << "                            Version: " << highint << CFGVersion
773                                                     << normint << endl;
774   if (CFGVersion != needed_cfg_version) {
775     cerr << endl << fgred << "YOU HAVE AN INCOMPATIBLE CFG FILE FOR THIS AIRCRAFT."
776             " RESULTS WILL BE UNPREDICTABLE !!" << endl;
777     cerr << "Current version needed is: " << needed_cfg_version << endl;
778     cerr << "         You have version: " << CFGVersion << endl << fgdef << endl;
779     return false;
780   }
781
782   if (Release == "ALPHA" && (debug_lvl & 1)) {
783     cout << endl << endl
784          << highint << "This aircraft model is an " << fgred << Release
785          << reset << highint << " release!!!" << endl << endl << reset
786          << "This aircraft model may not even properly load, and probably"
787          << " will not fly as expected." << endl << endl
788          << fgred << highint << "Use this model for development purposes ONLY!!!"
789          << normint << reset << endl << endl;
790   } else if (Release == "BETA" && (debug_lvl & 1)) {
791     cout << endl << endl
792          << highint << "This aircraft model is a " << fgred << Release
793          << reset << highint << " release!!!" << endl << endl << reset
794          << "This aircraft model probably will not fly as expected." << endl << endl
795          << fgblue << highint << "Use this model for development purposes ONLY!!!"
796          << normint << reset << endl << endl;
797   } else if (Release == "PRODUCTION" && (debug_lvl & 1)) {
798     cout << endl << endl
799          << highint << "This aircraft model is a " << fgblue << Release
800          << reset << highint << " release." << endl << endl << reset;
801   } else if (debug_lvl & 1) {
802     cout << endl << endl
803          << highint << "This aircraft model is an " << fgred << Release
804          << reset << highint << " release!!!" << endl << endl << reset
805          << "This aircraft model may not even properly load, and probably"
806          << " will not fly as expected." << endl << endl
807          << fgred << highint << "Use this model for development purposes ONLY!!!"
808          << normint << reset << endl << endl;
809   }
810
811   return result;
812 }
813
814 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
815
816 bool FGFDMExec::ReadChild(Element* el)
817 {
818   // Add a new childData object to the child FDM list
819   // Populate that childData element with a new FDMExec object
820   // Set the IsChild flag for that FDMExec object
821   // Get the aircraft name
822   // set debug level to print out no additional data for child objects
823   // Load the model given the aircraft name
824   // reset debug level to prior setting
825
826   string token;
827
828   struct childData* child = new childData;
829
830   child->exec = new FGFDMExec(Root, FDMctr);
831   child->exec->SetChild(true);
832
833   string childAircraft = el->GetAttributeValue("name");
834   string sMated = el->GetAttributeValue("mated");
835   if (sMated == "false") child->mated = false; // child objects are mated by default.
836   string sInternal = el->GetAttributeValue("internal");
837   if (sInternal == "true") child->internal = true; // child objects are external by default.
838
839   child->exec->SetAircraftPath( AircraftPath );
840   child->exec->SetEnginePath( EnginePath );
841   child->exec->SetSystemsPath( SystemsPath );
842   child->exec->LoadModel(childAircraft);
843
844   Element* location = el->FindElement("location");
845   if (location) {
846     child->Loc = location->FindElementTripletConvertTo("IN");
847   } else {
848     cerr << endl << highint << fgred << "  No location was found for this child object!" << reset << endl;
849     exit(-1);
850   }
851   
852   Element* orientation = el->FindElement("orient");
853   if (orientation) {
854     child->Orient = orientation->FindElementTripletConvertTo("RAD");
855   } else if (debug_lvl > 0) {
856     cerr << endl << highint << "  No orientation was found for this child object! Assuming 0,0,0." << reset << endl;
857   }
858
859   ChildFDMList.push_back(child);
860
861   return true;
862 }
863
864 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
865
866 FGPropertyManager* FGFDMExec::GetPropertyManager(void)
867 {
868   return instance;
869 }
870
871 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
872
873 FGTrim* FGFDMExec::GetTrim(void)
874 {
875   delete Trim;
876   Trim = new FGTrim(this,tNone);
877   return Trim;
878 }
879
880 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
881
882 void FGFDMExec::DisableOutput(void)
883 {
884   for (unsigned i=0; i<Outputs.size(); i++) {
885     Outputs[i]->Disable();
886   }
887 }
888
889 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
890
891 void FGFDMExec::EnableOutput(void)
892 {
893   for (unsigned i=0; i<Outputs.size(); i++) {
894     Outputs[i]->Enable();
895   }
896 }
897
898 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
899
900 void FGFDMExec::ForceOutput(int idx)
901 {
902   if (idx >= 0 && idx < Outputs.size()) Outputs[idx]->Print();
903 }
904         
905 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
906
907 bool FGFDMExec::SetOutputDirectives(const string& fname)
908 {
909   bool result;
910
911   FGOutput* Output = new FGOutput(this);
912   Output->SetDirectivesFile(RootDir + fname);
913   Output->InitModel();
914   Schedule(Output, 1);
915   result = Output->Load(0);
916
917   if (result) {
918     Outputs.push_back(Output);
919     typedef double (FGOutput::*iOPMF)(void) const;
920     string outputProp = CreateIndexedPropertyName("simulation/output",Outputs.size()-1);
921     instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate, false);
922   }
923
924   return result;
925 }
926
927 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
928
929 void FGFDMExec::DoTrim(int mode)
930 {
931   double saved_time;
932
933   if (Constructing) return;
934
935   if (mode < 0 || mode > JSBSim::tNone) {
936     cerr << endl << "Illegal trimming mode!" << endl << endl;
937     return;
938   }
939   saved_time = sim_time;
940   FGTrim trim(this, (JSBSim::TrimMode)mode);
941   if ( !trim.DoTrim() ) cerr << endl << "Trim Failed" << endl << endl;
942   trim.Report();
943   sim_time = saved_time;
944 }
945
946 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
947
948 void FGFDMExec::UseAtmosphereMSIS(void)
949 {
950   FGAtmosphere *oldAtmosphere = Atmosphere;
951   Atmosphere = new MSIS(this);
952   if (!Atmosphere->InitModel()) {
953     cerr << fgred << "MSIS Atmosphere model init failed" << fgdef << endl;
954     Error+=1;
955   }
956   Models[1] = Atmosphere; // Reassign the atmosphere model that has already been scheduled
957                           // to the new atmosphere.
958   delete oldAtmosphere;
959 }
960
961 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
962
963 void FGFDMExec::UseAtmosphereMars(void)
964 {
965 /*
966   FGAtmosphere *oldAtmosphere = Atmosphere;
967   Atmosphere = new FGMars(this);
968   if (!Atmosphere->InitModel()) {
969     cerr << fgred << "Mars Atmosphere model init failed" << fgdef << endl;
970     Error+=1;
971   }
972   Models[1] = Atmosphere; // Reassign the atmosphere model that has already been scheduled
973                           // to the new atmosphere.
974   delete oldAtmosphere;
975 */
976 }
977
978 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
979 //    The bitmasked value choices are as follows:
980 //    unset: In this case (the default) JSBSim would only print
981 //       out the normally expected messages, essentially echoing
982 //       the config files as they are read. If the environment
983 //       variable is not set, debug_lvl is set to 1 internally
984 //    0: This requests JSBSim not to output any messages
985 //       whatsoever.
986 //    1: This value explicity requests the normal JSBSim
987 //       startup messages
988 //    2: This value asks for a message to be printed out when
989 //       a class is instantiated
990 //    4: When this value is set, a message is displayed when a
991 //       FGModel object executes its Run() method
992 //    8: When this value is set, various runtime state variables
993 //       are printed out periodically
994 //    16: When set various parameters are sanity checked and
995 //       a message is printed out when they go out of bounds
996
997 void FGFDMExec::Debug(int from)
998 {
999   if (debug_lvl <= 0) return;
1000
1001   if (debug_lvl & 1 && IdFDM == 0) { // Standard console startup message output
1002     if (from == 0) { // Constructor
1003       cout << "\n\n     " << highint << underon << "JSBSim Flight Dynamics Model v"
1004                                      << JSBSim_version << underoff << normint << endl;
1005       cout << halfint << "            [JSBSim-ML v" << needed_cfg_version << "]\n\n";
1006       cout << normint << "JSBSim startup beginning ...\n\n";
1007     } else if (from == 3) {
1008       cout << "\n\nJSBSim startup complete\n\n";
1009     }
1010   }
1011   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
1012     if (from == 0) cout << "Instantiated: FGFDMExec" << endl;
1013     if (from == 1) cout << "Destroyed:    FGFDMExec" << endl;
1014   }
1015   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
1016     if (from == 2) {
1017       cout << "================== Frame: " << Frame << "  Time: "
1018            << sim_time << " dt: " << dT << endl;
1019     }
1020   }
1021   if (debug_lvl & 8 ) { // Runtime state variables
1022   }
1023   if (debug_lvl & 16) { // Sanity checking
1024   }
1025   if (debug_lvl & 64) {
1026     if (from == 0) { // Constructor
1027       cout << IdSrc << endl;
1028       cout << IdHdr << endl;
1029     }
1030   }
1031 }
1032 }
1033
1034