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