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