]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/FGFDMExec.cpp
Don't create a new instance of /fdm/jsbsim upon reset
[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 (jsb@hal-pc.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 "FGState.h"
46 #include <models/FGAtmosphere.h>
47 #include <models/atmosphere/FGMSIS.h>
48 #include <models/atmosphere/FGMars.h>
49 #include <models/FGFCS.h>
50 #include <models/FGPropulsion.h>
51 #include <models/FGMassBalance.h>
52 #include <models/FGGroundReactions.h>
53 #include <models/FGExternalReactions.h>
54 #include <models/FGBuoyantForces.h>
55 #include <models/FGAerodynamics.h>
56 #include <models/FGInertial.h>
57 #include <models/FGAircraft.h>
58 #include <models/FGPropagate.h>
59 #include <models/FGAuxiliary.h>
60 #include <models/FGInput.h>
61 #include <models/FGOutput.h>
62 #include <initialization/FGInitialCondition.h>
63 //#include <initialization/FGTrimAnalysis.h> // Remove until later
64 #include <input_output/FGPropertyManager.h>
65 #include <input_output/FGScript.h>
66
67 #include <iostream>
68 #include <iterator>
69
70 namespace JSBSim {
71
72 static const char *IdSrc = "$Id$";
73 static const char *IdHdr = ID_FDMEXEC;
74
75 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
76 GLOBAL DECLARATIONS
77 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
78
79 unsigned int FGFDMExec::FDMctr = 0;
80 FGPropertyManager* FGFDMExec::master=0;
81
82 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
83 CLASS IMPLEMENTATION
84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
85
86 void checkTied ( FGPropertyManager *node )
87 {
88   int N = node->nChildren();
89   string name;
90
91   for (int i=0; i<N; i++) {
92     if (node->getChild(i)->nChildren() ) {
93       checkTied( (FGPropertyManager*)node->getChild(i) );
94     } else if ( node->getChild(i)->isTied() ) {
95       name = ((FGPropertyManager*)node->getChild(i))->GetFullyQualifiedName();
96       node->Untie(name);
97     }
98   }
99 }
100
101 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
102 // Constructor
103
104 FGFDMExec::FGFDMExec(FGPropertyManager* root) : Root(root)
105 {
106
107   Frame           = 0;
108   FirstModel      = 0;
109   Error           = 0;
110   GroundCallback  = 0;
111   State           = 0;
112   Atmosphere      = 0;
113   FCS             = 0;
114   Propulsion      = 0;
115   MassBalance     = 0;
116   Aerodynamics    = 0;
117   Inertial        = 0;
118   GroundReactions = 0;
119   ExternalReactions = 0;
120   BuoyantForces   = 0;
121   Aircraft        = 0;
122   Propagate       = 0;
123   Auxiliary       = 0;
124   Input           = 0;
125   IC              = 0;
126   Trim            = 0;
127   Script          = 0;
128
129   modelLoaded = false;
130   IsChild = false;
131   holding = false;
132   Terminate = false;
133
134   IdFDM = FDMctr; // The main (parent) JSBSim instance is always the "zeroth"
135                   // instance. "child" instances are loaded last.
136
137   try {
138     char* num = getenv("JSBSIM_DEBUG");
139     if (num) debug_lvl = atoi(num); // set debug level
140   } catch (...) {               // if error set to 1
141     debug_lvl = 1;
142   }
143
144   if (Root == 0) {
145     if (master == 0)
146       master = new FGPropertyManager;
147     Root = master;
148
149     // JSBSim Standalone, multiple childs are allowed
150     FDMctr++;
151   }
152
153   instance = Root->GetNode("/fdm/jsbsim",IdFDM,true);
154   Debug(0);
155   // this is to catch errors in binding member functions to the property tree.
156   try {
157     Allocate();
158   } catch ( string msg ) {
159     cout << "Caught error: " << msg << endl;
160     exit(1);
161   }
162
163   trim_status = false;
164   ta_mode     = 99;
165
166   Constructing = true;
167   typedef int (FGFDMExec::*iPMF)(void) const;
168 //  instance->Tie("simulation/do_trim_analysis", this, (iPMF)0, &FGFDMExec::DoTrimAnalysis);
169   instance->Tie("simulation/do_simple_trim", this, (iPMF)0, &FGFDMExec::DoTrim);
170   instance->Tie("simulation/reset", this, (iPMF)0, &FGFDMExec::ResetToInitialConditions);
171   instance->Tie("simulation/terminate", (int *)&Terminate);
172   Constructing = false;
173 }
174
175 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
176
177 FGFDMExec::~FGFDMExec()
178 {
179   try {
180     checkTied( instance );
181     DeAllocate();
182     if (Root == 0)  delete master;
183   } catch ( string msg ) {
184     cout << "Caught error: " << msg << endl;
185   }
186
187   for (unsigned int i=1; i<ChildFDMList.size(); i++) delete ChildFDMList[i]->exec;
188   ChildFDMList.clear();
189
190   PropertyCatalog.clear();
191
192   Debug(1);
193 }
194
195 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
196
197 bool FGFDMExec::Allocate(void)
198 {
199   bool result=true;
200
201   Atmosphere      = new FGAtmosphere(this);
202   FCS             = new FGFCS(this);
203   Propulsion      = new FGPropulsion(this);
204   MassBalance     = new FGMassBalance(this);
205   Aerodynamics    = new FGAerodynamics (this);
206   Inertial        = new FGInertial(this);
207
208   GroundCallback  = new FGGroundCallback(Inertial->GetRefRadius());
209
210   GroundReactions = new FGGroundReactions(this);
211   ExternalReactions = new FGExternalReactions(this);
212   BuoyantForces   = new FGBuoyantForces(this);
213   Aircraft        = new FGAircraft(this);
214   Propagate       = new FGPropagate(this);
215   Auxiliary       = new FGAuxiliary(this);
216   Input           = new FGInput(this);
217
218   State           = new FGState(this); // This must be done here, as the FGState
219                                        // class needs valid pointers to the above
220                                        // model classes
221
222   // Initialize models so they can communicate with each other
223
224   Atmosphere->InitModel();
225   FCS->InitModel();
226   Propulsion->InitModel();
227   MassBalance->InitModel();
228   Aerodynamics->InitModel();
229   Inertial->InitModel();
230   GroundReactions->InitModel();
231   ExternalReactions->InitModel();
232   BuoyantForces->InitModel();
233   Aircraft->InitModel();
234   Propagate->InitModel();
235   Auxiliary->InitModel();
236   Input->InitModel();
237
238   IC = new FGInitialCondition(this);
239
240   // Schedule a model. The second arg (the integer) is the pass number. For
241   // instance, the atmosphere model could get executed every fifth pass it is called
242   // by the executive. IC and Trim objects are NOT scheduled.
243
244   Schedule(Input,           1);
245   Schedule(Atmosphere,      1);
246   Schedule(FCS,             1);
247   Schedule(Propulsion,      1);
248   Schedule(MassBalance,     1);
249   Schedule(Aerodynamics,    1);
250   Schedule(Inertial,        1);
251   Schedule(GroundReactions, 1);
252   Schedule(ExternalReactions, 1);
253   Schedule(BuoyantForces,   1);
254   Schedule(Aircraft,        1);
255   Schedule(Propagate,       1);
256   Schedule(Auxiliary,       1);
257
258   modelLoaded = false;
259
260   return result;
261 }
262
263 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
264
265 bool FGFDMExec::DeAllocate(void)
266 {
267   delete Input;
268   delete Atmosphere;
269   delete FCS;
270   delete Propulsion;
271   delete MassBalance;
272   delete Aerodynamics;
273   delete Inertial;
274   delete GroundReactions;
275   delete ExternalReactions;
276   delete BuoyantForces;
277   delete Aircraft;
278   delete Propagate;
279   delete Auxiliary;
280   delete State;
281   delete Script;
282
283   for (unsigned i=0; i<Outputs.size(); i++) delete Outputs[i];
284   Outputs.clear();
285
286   delete IC;
287   delete Trim;
288
289   delete GroundCallback;
290
291   FirstModel  = 0L;
292   Error       = 0;
293
294   State           = 0;
295   Input           = 0;
296   Atmosphere      = 0;
297   FCS             = 0;
298   Propulsion      = 0;
299   MassBalance     = 0;
300   Aerodynamics    = 0;
301   Inertial        = 0;
302   GroundReactions = 0;
303   ExternalReactions = 0;
304   BuoyantForces   = 0;
305   Aircraft        = 0;
306   Propagate       = 0;
307   Auxiliary       = 0;
308   Script          = 0;
309
310   modelLoaded = false;
311   return modelLoaded;
312 }
313
314 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
315
316 int FGFDMExec::Schedule(FGModel* model, int rate)
317 {
318   FGModel* model_iterator;
319
320   model_iterator = FirstModel;
321
322   if (model_iterator == 0L) {                  // this is the first model
323
324     FirstModel = model;
325     FirstModel->NextModel = 0L;
326     FirstModel->SetRate(rate);
327
328   } else {                                     // subsequent model
329
330     while (model_iterator->NextModel != 0L) {
331       model_iterator = model_iterator->NextModel;
332     }
333     model_iterator->NextModel = model;
334     model_iterator->NextModel->SetRate(rate);
335
336   }
337
338   return 0;
339 }
340
341 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
342
343 bool FGFDMExec::Run(void)
344 {
345   bool success=true;
346   FGModel* model_iterator;
347
348   model_iterator = FirstModel;
349   if (model_iterator == 0L) return false;
350
351   Debug(2);
352
353   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
354     ChildFDMList[i]->AssignState(Propagate); // Transfer state to the child FDM
355     ChildFDMList[i]->Run();
356   }
357
358   // returns true if success
359   // false if complete
360   if (Script != 0 && !State->IntegrationSuspended()) success = Script->RunScript();
361
362   while (model_iterator != 0L) {
363     model_iterator->Run();
364     model_iterator = model_iterator->NextModel;
365   }
366
367   Frame++;
368   if (!Holding()) State->IncrTime();
369   if (Terminate) success = false;
370
371   return (success);
372 }
373
374 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
375 // This call will cause the sim time to reset to 0.0
376
377 bool FGFDMExec::RunIC(void)
378 {
379   State->SuspendIntegration();
380   State->Initialize(IC);
381   Run();
382   State->ResumeIntegration();
383
384   return true;
385 }
386
387 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
388 //
389 // A private, internal function call for Tie-ing to a property, so it needs an
390 // argument.
391
392 void FGFDMExec::ResetToInitialConditions(int mode)
393 {
394   if (mode == 1) {
395     for (unsigned int i=0; i<Outputs.size(); i++) {
396       Outputs[i]->SetStartNewFile(true); 
397     }
398   }
399   
400   ResetToInitialConditions();
401 }
402
403 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
404
405 void FGFDMExec::ResetToInitialConditions(void)
406 {
407   FGModel* model_iterator;
408
409   model_iterator = FirstModel;
410   if (model_iterator == 0L || Constructing) return;
411
412   while (model_iterator != 0L) {
413     model_iterator->InitModel();
414     model_iterator = model_iterator->NextModel;
415   }
416
417   RunIC();
418   if (Script) Script->ResetEvents();
419 }
420
421 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
422
423 void FGFDMExec::SetGroundCallback(FGGroundCallback* p)
424 {
425   delete GroundCallback;
426   GroundCallback = p;
427 }
428
429 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
430
431 double FGFDMExec::GetSimTime(void)
432 {
433   return (State->Getsim_time());
434 }
435
436 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
437
438 double FGFDMExec::GetDeltaT(void)
439 {
440   return (State->Getdt());
441 }
442
443 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
444
445 vector <string> FGFDMExec::EnumerateFDMs(void)
446 {
447   vector <string> FDMList;
448
449   FDMList.push_back(Aircraft->GetAircraftName());
450
451   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
452     FDMList.push_back(ChildFDMList[i]->exec->GetAircraft()->GetAircraftName());
453   }
454
455   return FDMList;
456 }
457
458 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
459
460 bool FGFDMExec::LoadScript(string script)
461 {
462   bool result;
463
464   Script = new FGScript(this);
465   result = Script->LoadScript(script);
466
467   return result;
468 }
469
470 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
471
472 bool FGFDMExec::LoadModel(string AircraftPath, string EnginePath, string SystemsPath,
473                 string model, bool addModelToPath)
474 {
475   FGFDMExec::AircraftPath = AircraftPath;
476   FGFDMExec::EnginePath = EnginePath;
477   FGFDMExec::SystemsPath = SystemsPath;
478
479   return LoadModel(model, addModelToPath);
480 }
481
482 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
483
484 bool FGFDMExec::LoadModel(string model, bool addModelToPath)
485 {
486   string token;
487   string aircraftCfgFileName;
488   string separator = "/";
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 += separator + model;
502   aircraftCfgFileName = FullAircraftPath + separator + 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     element = document->FindElement("output");
655     while (element) {
656       FGOutput* Output = new FGOutput(this);
657       Output->InitModel();
658       Schedule(Output, 1);
659       result = Output->Load(element);
660       Outputs.push_back(Output);
661       if (!result) {
662         cerr << endl << "Aircraft output element has problems in file " << aircraftCfgFileName << endl;
663         return result;
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       cout << endl << fgblue << highint
682            << "End of vehicle configuration loading." << endl
683            << "-------------------------------------------------------------------------------"
684            << reset << endl;
685     }
686     
687     if (IsChild) debug_lvl = saved_debug_lvl;
688
689   } else {
690     cerr << fgred
691          << "  JSBSim failed to open the configuration file: " << aircraftCfgFileName
692          << fgdef << endl;
693   }
694
695   struct PropertyCatalogStructure masterPCS;
696   masterPCS.base_string = "";
697   masterPCS.node = (FGPropertyManager*)Root;
698
699   BuildPropertyCatalog(&masterPCS);
700
701   return result;
702 }
703
704 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
705
706 void FGFDMExec::BuildPropertyCatalog(struct PropertyCatalogStructure* pcs)
707 {
708   struct PropertyCatalogStructure* pcsNew = new struct PropertyCatalogStructure;
709   int node_idx = 0;
710   char int_buf[10];
711
712   for (unsigned int i=0; i<pcs->node->nChildren(); i++) {
713     pcsNew->base_string = pcs->base_string + "/" + pcs->node->getChild(i)->getName();
714     node_idx = pcs->node->getChild(i)->getIndex();
715     sprintf(int_buf, "[%d]", node_idx);
716     if (node_idx != 0) pcsNew->base_string += string(int_buf);
717     if (pcs->node->getChild(i)->nChildren() == 0) {
718       if (pcsNew->base_string.substr(0,11) == string("/fdm/jsbsim")) {
719         pcsNew->base_string = pcsNew->base_string.erase(0,12);
720       }
721       PropertyCatalog.push_back(pcsNew->base_string);
722     } else {
723       pcsNew->node = (FGPropertyManager*)pcs->node->getChild(i);
724       BuildPropertyCatalog(pcsNew);
725     }
726   }
727   delete pcsNew;
728 }
729
730 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
731
732 string FGFDMExec::QueryPropertyCatalog(string in)
733 {
734   string results="";
735   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
736     if (PropertyCatalog[i].find(in) != string::npos) results += PropertyCatalog[i] + "\n";
737   }
738   if (results.empty()) return "No matches found\n";
739   return results;
740 }
741
742 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
743
744 void FGFDMExec::PrintPropertyCatalog(void)
745 {
746   cout << endl;
747   cout << "  " << fgblue << highint << underon << "Property Catalog for "
748        << modelName << reset << endl << endl;
749   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
750     cout << "    " << PropertyCatalog[i] << endl;
751   }
752 }
753
754 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
755
756 bool FGFDMExec::ReadFileHeader(Element* el)
757 {
758   bool result = true; // true for success
759
760   if (debug_lvl == 0) return result;
761
762   if (IsChild) {
763     cout << endl <<highint << fgblue << "Reading child model: " << IdFDM << reset << endl << endl;
764   }
765
766   if (el->FindElement("description"))
767     cout << "  Description:   " << el->FindElement("description")->GetDataLine() << endl;
768   if (el->FindElement("author"))
769     cout << "  Model Author:  " << el->FindElement("author")->GetDataLine() << endl;
770   if (el->FindElement("filecreationdate"))
771     cout << "  Creation Date: " << el->FindElement("filecreationdate")->GetDataLine() << endl;
772   if (el->FindElement("version"))
773     cout << "  Version:       " << el->FindElement("version")->GetDataLine() << endl;
774
775   return result;
776 }
777
778 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
779
780 bool FGFDMExec::ReadPrologue(Element* el) // el for ReadPrologue is the document element
781 {
782   bool result = true; // true for success
783
784   if (!el) return false;
785
786   string AircraftName = el->GetAttributeValue("name");
787   Aircraft->SetAircraftName(AircraftName);
788
789   if (debug_lvl & 1) cout << underon << "Reading Aircraft Configuration File"
790             << underoff << ": " << highint << AircraftName << normint << endl;
791
792   CFGVersion = el->GetAttributeValue("version");
793   Release    = el->GetAttributeValue("release");
794
795   if (debug_lvl & 1)
796     cout << "                            Version: " << highint << CFGVersion
797                                                     << normint << endl;
798   if (CFGVersion != needed_cfg_version) {
799     cerr << endl << fgred << "YOU HAVE AN INCOMPATIBLE CFG FILE FOR THIS AIRCRAFT."
800             " RESULTS WILL BE UNPREDICTABLE !!" << endl;
801     cerr << "Current version needed is: " << needed_cfg_version << endl;
802     cerr << "         You have version: " << CFGVersion << endl << fgdef << endl;
803     return false;
804   }
805
806   if (Release == "ALPHA" && (debug_lvl & 1)) {
807     cout << endl << endl
808          << highint << "This aircraft model is an " << fgred << Release
809          << reset << highint << " release!!!" << endl << endl << reset
810          << "This aircraft model may not even properly load, and probably"
811          << " will not fly as expected." << endl << endl
812          << fgred << highint << "Use this model for development purposes ONLY!!!"
813          << normint << reset << endl << endl;
814   } else if (Release == "BETA" && (debug_lvl & 1)) {
815     cout << endl << endl
816          << highint << "This aircraft model is a " << fgred << Release
817          << reset << highint << " release!!!" << endl << endl << reset
818          << "This aircraft model probably will not fly as expected." << endl << endl
819          << fgblue << highint << "Use this model for development purposes ONLY!!!"
820          << normint << reset << endl << endl;
821   } else if (Release == "PRODUCTION" && (debug_lvl & 1)) {
822     cout << endl << endl
823          << highint << "This aircraft model is a " << fgblue << Release
824          << reset << highint << " release." << endl << endl << reset;
825   } else if (debug_lvl & 1) {
826     cout << endl << endl
827          << highint << "This aircraft model is an " << fgred << Release
828          << reset << highint << " release!!!" << endl << endl << reset
829          << "This aircraft model may not even properly load, and probably"
830          << " will not fly as expected." << endl << endl
831          << fgred << highint << "Use this model for development purposes ONLY!!!"
832          << normint << reset << endl << endl;
833   }
834
835   return result;
836 }
837
838 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
839
840 bool FGFDMExec::ReadChild(Element* el)
841 {
842   // Add a new childData object to the child FDM list
843   // Populate that childData element with a new FDMExec object
844   // Set the IsChild flag for that FDMExec object
845   // Get the aircraft name
846   // set debug level to print out no additional data for child objects
847   // Load the model given the aircraft name
848   // reset debug level to prior setting
849
850   string token;
851
852   struct childData* child = new childData;
853
854   child->exec = new FGFDMExec();
855   child->exec->SetChild(true);
856
857   string childAircraft = el->GetAttributeValue("name");
858   string sMated = el->GetAttributeValue("mated");
859   if (sMated == "false") child->mated = false; // child objects are mated by default.
860   string sInternal = el->GetAttributeValue("internal");
861   if (sInternal == "true") child->internal = true; // child objects are external by default.
862
863   child->exec->SetAircraftPath( AircraftPath );
864   child->exec->SetEnginePath( EnginePath );
865   child->exec->SetSystemsPath( SystemsPath );
866   child->exec->LoadModel(childAircraft);
867
868   Element* location = el->FindElement("location");
869   if (location) {
870     child->Loc = location->FindElementTripletConvertTo("IN");
871   } else {
872     cerr << endl << highint << fgred << "  No location was found for this child object!" << reset << endl;
873     exit(-1);
874   }
875   
876   Element* orientation = el->FindElement("orient");
877   if (orientation) {
878     child->Orient = orientation->FindElementTripletConvertTo("RAD");
879   } else if (debug_lvl > 0) {
880     cerr << endl << highint << "  No orientation was found for this child object! Assuming 0,0,0." << reset << endl;
881   }
882
883   ChildFDMList.push_back(child);
884
885   return true;
886 }
887
888 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
889
890 FGPropertyManager* FGFDMExec::GetPropertyManager(void)
891 {
892   return instance;
893 }
894
895 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
896
897 FGTrim* FGFDMExec::GetTrim(void)
898 {
899   delete Trim;
900   Trim = new FGTrim(this,tNone);
901   return Trim;
902 }
903
904 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
905
906 void FGFDMExec::DisableOutput(void)
907 {
908   for (unsigned i=0; i<Outputs.size(); i++) {
909     Outputs[i]->Disable();
910   }
911 }
912
913 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
914
915 void FGFDMExec::EnableOutput(void)
916 {
917   for (unsigned i=0; i<Outputs.size(); i++) {
918     Outputs[i]->Enable();
919   }
920 }
921
922 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
923
924 bool FGFDMExec::SetOutputDirectives(string fname)
925 {
926   bool result;
927
928   FGOutput* Output = new FGOutput(this);
929   Output->SetDirectivesFile(fname);
930   Output->InitModel();
931   Schedule(Output,       1);
932   result = Output->Load(0);
933   Outputs.push_back(Output);
934
935   return result;
936 }
937
938 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
939
940 void FGFDMExec::DoTrim(int mode)
941 {
942   double saved_time;
943
944   if (Constructing) return;
945
946   if (mode < 0 || mode > JSBSim::tNone) {
947     cerr << endl << "Illegal trimming mode!" << endl << endl;
948     return;
949   }
950   saved_time = State->Getsim_time();
951   FGTrim trim(this, (JSBSim::TrimMode)mode);
952   if ( !trim.DoTrim() ) cerr << endl << "Trim Failed" << endl << endl;
953   trim.Report();
954   State->Setsim_time(saved_time);
955 }
956
957 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
958 /*
959 void FGFDMExec::DoTrimAnalysis(int mode)
960 {
961   double saved_time;
962   if (Constructing) return;
963
964   if (mode < 0 || mode > JSBSim::taNone) {
965     cerr << endl << "Illegal trimming mode!" << endl << endl;
966     return;
967   }
968   saved_time = State->Getsim_time();
969
970   FGTrimAnalysis trimAnalysis(this, (JSBSim::TrimAnalysisMode)mode);
971
972   if ( !trimAnalysis.Load(IC->GetInitFile(), false) ) {
973     cerr << "A problem occurred with trim configuration file " << trimAnalysis.Load(IC->GetInitFile()) << endl;
974     exit(-1);
975   }
976
977   bool result = trimAnalysis.DoTrim();
978
979   if ( !result ) cerr << endl << "Trim Failed" << endl << endl;
980
981   trimAnalysis.Report();
982   State->Setsim_time(saved_time);
983
984   EnableOutput();
985   cout << "\nOutput: " << GetOutputFileName() << endl;
986
987 }
988 */
989 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
990
991 void FGFDMExec::UseAtmosphereMSIS(void)
992 {
993   FGAtmosphere *oldAtmosphere = Atmosphere;
994   Atmosphere = new MSIS(this);
995   if (!Atmosphere->InitModel()) {
996     cerr << fgred << "MSIS Atmosphere model init failed" << fgdef << endl;
997     Error+=1;
998   }
999   delete oldAtmosphere;
1000 }
1001
1002 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1003
1004 void FGFDMExec::UseAtmosphereMars(void)
1005 {
1006 /*
1007   FGAtmosphere *oldAtmosphere = Atmosphere;
1008   Atmosphere = new FGMars(this);
1009   if (!Atmosphere->InitModel()) {
1010     cerr << fgred << "Mars Atmosphere model init failed" << fgdef << endl;
1011     Error+=1;
1012   }
1013   delete oldAtmosphere;
1014 */
1015 }
1016
1017 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1018 //    The bitmasked value choices are as follows:
1019 //    unset: In this case (the default) JSBSim would only print
1020 //       out the normally expected messages, essentially echoing
1021 //       the config files as they are read. If the environment
1022 //       variable is not set, debug_lvl is set to 1 internally
1023 //    0: This requests JSBSim not to output any messages
1024 //       whatsoever.
1025 //    1: This value explicity requests the normal JSBSim
1026 //       startup messages
1027 //    2: This value asks for a message to be printed out when
1028 //       a class is instantiated
1029 //    4: When this value is set, a message is displayed when a
1030 //       FGModel object executes its Run() method
1031 //    8: When this value is set, various runtime state variables
1032 //       are printed out periodically
1033 //    16: When set various parameters are sanity checked and
1034 //       a message is printed out when they go out of bounds
1035
1036 void FGFDMExec::Debug(int from)
1037 {
1038   if (debug_lvl <= 0) return;
1039
1040   if (debug_lvl & 1 && IdFDM == 0) { // Standard console startup message output
1041     if (from == 0) { // Constructor
1042       cout << "\n\n     " << highint << underon << "JSBSim Flight Dynamics Model v"
1043                                      << JSBSim_version << underoff << normint << endl;
1044       cout << halfint << "            [JSBSim-ML v" << needed_cfg_version << "]\n\n";
1045       cout << normint << "JSBSim startup beginning ...\n\n";
1046     } else if (from == 3) {
1047       cout << "\n\nJSBSim startup complete\n\n";
1048     }
1049   }
1050   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
1051     if (from == 0) cout << "Instantiated: FGFDMExec" << endl;
1052     if (from == 1) cout << "Destroyed:    FGFDMExec" << endl;
1053   }
1054   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
1055     if (from == 2) {
1056       cout << "================== Frame: " << Frame << "  Time: "
1057            << State->Getsim_time() << " dt: " << State->Getdt() << endl;
1058     }
1059   }
1060   if (debug_lvl & 8 ) { // Runtime state variables
1061   }
1062   if (debug_lvl & 16) { // Sanity checking
1063   }
1064   if (debug_lvl & 64) {
1065     if (from == 0) { // Constructor
1066       cout << IdSrc << endl;
1067       cout << IdHdr << endl;
1068     }
1069   }
1070 }
1071 }
1072
1073