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