]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/FGFDMExec.h
6a92a2e817a128338101949fbd7126f9a2d4afd6
[flightgear.git] / src / FDM / JSBSim / FGFDMExec.h
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2  Header:       FGFDMExec.h
3  Author:       Jon Berndt
4  Date started: 11/17/98
5  file The header file for the JSBSim executive.
6
7  ------------- Copyright (C) 1999  Jon S. Berndt (jsb@hal-pc.org) -------------
8
9  This program is free software; you can redistribute it and/or modify it under
10  the terms of the GNU Lesser General Public License as published by the Free Software
11  Foundation; either version 2 of the License, or (at your option) any later
12  version.
13
14  This program is distributed in the hope that it will be useful, but WITHOUT
15  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
17  details.
18
19  You should have received a copy of the GNU Lesser General Public License along with
20  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
21  Place - Suite 330, Boston, MA  02111-1307, USA.
22
23  Further information about the GNU Lesser General Public License can also be found on
24  the world wide web at http://www.gnu.org.
25
26 HISTORY
27 --------------------------------------------------------------------------------
28 11/17/98   JSB   Created
29 7/31/99     TP   Added RunIC function that runs the sim so that every frame
30                  begins with the IC values from the given FGInitialCondition
31                  object and dt=0.
32
33 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
34 SENTRY
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
36
37 #ifndef FGFDMEXEC_HEADER_H
38 #define FGFDMEXEC_HEADER_H
39
40 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41 INCLUDES
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
43
44 #include <models/FGModel.h>
45 #include <models/FGOutput.h>
46 #include <models/FGInput.h>
47 #include <initialization/FGTrim.h>
48 #include <initialization/FGInitialCondition.h>
49 #include <FGJSBBase.h>
50 #include <input_output/FGPropertyManager.h>
51 #include <input_output/FGGroundCallback.h>
52 #include <input_output/FGXMLFileRead.h>
53 #include <models/FGPropagate.h>
54
55 #include <vector>
56 #include <string>
57
58 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
59 DEFINITIONS
60 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
61
62 #define ID_FDMEXEC "$Id$"
63
64 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
65 FORWARD DECLARATIONS
66 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
67
68 namespace JSBSim {
69
70 class FGScript;
71
72 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
73 CLASS DOCUMENTATION
74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
75
76 /** Encapsulates the JSBSim simulation executive.
77     This class is the executive class through which all other simulation classes
78     are instantiated, initialized, and run. When integrated with FlightGear (or
79     other flight simulator) this class is typically instantiated by an interface
80     class on the simulator side.
81
82     At the time of simulation initialization, the interface
83     class creates an instance of this executive class. The
84     executive is subsequently directed to load the chosen aircraft specification
85     file:
86
87     @code
88     fdmex = new FGFDMExec( \85 );
89     result = fdmex->LoadModel( \85 );
90     @endcode
91
92     When an aircraft model is loaded, the config file is parsed and for each of the
93     sections of the config file (propulsion, flight control, etc.) the
94     corresponding Load() method is called (e.g. FGFCS::Load()).
95
96     Subsequent to the creation of the executive and loading of the model,
97     initialization is performed. Initialization involves copying control inputs
98     into the appropriate JSBSim data storage locations, configuring it for the set
99     of user supplied initial conditions, and then copying state variables from
100     JSBSim. The state variables are used to drive the instrument displays and to
101     place the vehicle model in world space for visual rendering:
102
103     @code
104     copy_to_JSBsim(); // copy control inputs to JSBSim
105     fdmex->RunIC(); // loop JSBSim once w/o integrating
106     copy_from_JSBsim(); // update the bus
107     @endcode
108
109     Once initialization is complete, cyclic execution proceeds:
110
111     @code
112     copy_to_JSBsim(); // copy control inputs to JSBSim
113     fdmex->Run(); // execute JSBSim
114     copy_from_JSBsim(); // update the bus
115     @endcode
116
117     JSBSim can be used in a standalone mode by creating a compact stub program
118     that effectively performs the same progression of steps as outlined above for
119     the integrated version, but with two exceptions. First, the copy_to_JSBSim()
120     and copy_from_JSBSim() functions are not used because the control inputs are
121     handled directly by the scripting facilities and outputs are handled by the
122     output (data logging) class. Second, the name of a script file can be supplied
123     to the stub program. Scripting (see FGScript) provides a way to supply command
124     inputs to the simulation:
125
126     @code
127     FDMExec = new JSBSim::FGFDMExec();
128     FDMExec->LoadScript( ScriptName ); // the script loads the aircraft and ICs
129     result = FDMExec->Run();
130     while (result) { // cyclic execution
131       result = FDMExec->Run(); // execute JSBSim
132     }
133     @endcode
134
135     The standalone mode has been useful for verifying changes before committing
136     updates to the source code repository. It is also useful for running sets of
137     tests that reveal some aspects of simulated aircraft performance, such as
138     range, time-to-climb, takeoff distance, etc.
139
140     <h3>JSBSim Debugging Directives</h3>
141
142     This describes to any interested entity the debug level
143     requested by setting the JSBSIM_DEBUG environment variable.
144     The bitmasked value choices are as follows:
145     - <b>unset</b>: In this case (the default) JSBSim would only print
146        out the normally expected messages, essentially echoing
147        the config files as they are read. If the environment
148        variable is not set, debug_lvl is set to 1 internally
149     - <b>0</b>: This requests JSBSim not to output any messages
150        whatsoever
151     - <b>1</b>: This value explicity requests the normal JSBSim
152        startup messages
153     - <b>2</b>: This value asks for a message to be printed out when
154        a class is instantiated
155     - <b>4</b>: When this value is set, a message is displayed when a
156        FGModel object executes its Run() method
157     - <b>8</b>: When this value is set, various runtime state variables
158        are printed out periodically
159     - <b>16</b>: When set various parameters are sanity checked and
160        a message is printed out when they go out of bounds
161
162     <h3>Properties</h3>
163     @property simulator/do_trim (write only) Can be set to the integer equivalent to one of
164                                 tLongitudinal (0), tFull (1), tGround (2), tPullup (3),
165                                 tCustom (4), tTurn (5). Setting this to a legal value
166                                 (such as by a script) causes a trim to be performed. This
167                                 property actually maps toa function call of DoTrim().
168
169     @author Jon S. Berndt
170     @version $Revision$
171 */
172
173 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
174 CLASS DECLARATION
175 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
176
177 class FGFDMExec : public FGJSBBase, public FGXMLFileRead
178 {
179 public:
180
181   /// Default constructor
182   FGFDMExec(FGPropertyManager* root = 0);
183
184   /// Default destructor
185   ~FGFDMExec();
186
187   /** This routine places a model into the runlist at the specified rate. The
188       "rate" is not really a clock rate. It represents how many calls to the
189       FGFDMExec::Run() method must be made before the model is executed. A
190       value of 1 means that the model will be executed for each call to the
191       exec's Run() method. A value of 5 means that the model will only be
192       executed every 5th call to the exec's Run() method. Use of a rate other than
193       one is at this time not recommended.
194       @param model A pointer to the model being scheduled.
195       @param rate The rate at which to execute the model as described above.
196       @return Currently returns 0 always. */
197   int  Schedule(FGModel* model, int rate);
198
199   /** This function executes each scheduled model in succession.
200       @return true if successful, false if sim should be ended  */
201   bool Run(void);
202
203   /** Initializes the sim from the initial condition object and executes
204       each scheduled model without integrating i.e. dt=0.
205       @return true if successful */
206   bool RunIC(void);
207
208   /** Sets the ground callback pointer.
209       @param gc A pointer to a ground callback object.  */
210   void SetGroundCallback(FGGroundCallback* gc);
211
212   /** Loads an aircraft model.
213       @param AircraftPath path to the aircraft/ directory. For instance:
214       "aircraft". Under aircraft, then, would be directories for various
215       modeled aircraft such as C172/, x15/, etc.
216       @param EnginePath path to the directory under which engine config
217       files are kept, for instance "engine"
218       @param SystemsPath path to the directory under which systems config
219       files are kept, for instance "systems"
220       @param model the name of the aircraft model itself. This file will
221       be looked for in the directory specified in the AircraftPath variable,
222       and in turn under the directory with the same name as the model. For
223       instance: "aircraft/x15/x15.xml"
224       @param addModelToPath set to true to add the model name to the
225       AircraftPath, defaults to true
226       @return true if successful */
227   bool LoadModel(string AircraftPath, string EnginePath, string SystemsPath,
228                  string model, bool addModelToPath = true);
229
230   /** Loads an aircraft model.  The paths to the aircraft and engine
231       config file directories must be set prior to calling this.  See
232       below.
233       @param model the name of the aircraft model itself. This file will
234       be looked for in the directory specified in the AircraftPath variable,
235       and in turn under the directory with the same name as the model. For
236       instance: "aircraft/x15/x15.xml"
237       @param addModelToPath set to true to add the model name to the
238       AircraftPath, defaults to true
239       @return true if successful*/
240   bool LoadModel(string model, bool addModelToPath = true);
241
242   /** Loads a script
243       @param Script the full path name and file name for the script to be loaded.
244       @return true if successfully loadsd; false otherwise. */
245   bool LoadScript(string Script);
246
247   /** Sets the path to the engine config file directories.
248       @param path path to the directory under which engine config
249       files are kept, for instance "engine"  */
250   bool SetEnginePath(string path)   { EnginePath = path; return true; }
251
252   /** Sets the path to the aircraft config file directories.
253       @param path path to the aircraft directory. For instance:
254       "aircraft". Under aircraft, then, would be directories for various
255       modeled aircraft such as C172/, x15/, etc.  */
256   bool SetAircraftPath(string path) { AircraftPath = path; return true; }
257   
258   /** Sets the path to the systems config file directories.
259       @param path path to the directory under which systems config
260       files are kept, for instance "systems"  */
261   bool SetSystemsPath(string path)   { SystemsPath = path; return true; }
262   
263   /// @name Top-level executive State and Model retrieval mechanism
264   //@{
265   /// Returns the FGAtmosphere pointer.
266   inline FGAtmosphere* GetAtmosphere(void)    {return Atmosphere;}
267   /// Returns the FGFCS pointer.
268   inline FGFCS* GetFCS(void)                  {return FCS;}
269   /// Returns the FGPropulsion pointer.
270   inline FGPropulsion* GetPropulsion(void)    {return Propulsion;}
271   /// Returns the FGAircraft pointer.
272   inline FGMassBalance* GetMassBalance(void)  {return MassBalance;}
273   /// Returns the FGAerodynamics pointer
274   inline FGAerodynamics* GetAerodynamics(void){return Aerodynamics;}
275   /// Returns the FGInertial pointer.
276   inline FGInertial* GetInertial(void)        {return Inertial;}
277   /// Returns the FGGroundReactions pointer.
278   inline FGGroundReactions* GetGroundReactions(void) {return GroundReactions;}
279   /// Returns the FGExternalReactions pointer.
280   inline FGExternalReactions* GetExternalReactions(void) {return ExternalReactions;}
281   /// Returns the FGBuoyantForces pointer.
282   inline FGBuoyantForces* GetBuoyantForces(void) {return BuoyantForces;}
283   /// Returns the FGAircraft pointer.
284   inline FGAircraft* GetAircraft(void)        {return Aircraft;}
285   /// Returns the FGPropagate pointer.
286   inline FGPropagate* GetPropagate(void)      {return Propagate;}
287   /// Returns the FGAuxiliary pointer.
288   inline FGAuxiliary* GetAuxiliary(void)      {return Auxiliary;}
289   /// Returns the FGInput pointer.
290   inline FGInput* GetInput(void)              {return Input;}
291   /// Returns the FGGroundCallback pointer.
292   inline FGGroundCallback* GetGroundCallback(void) {return GroundCallback;}
293   /// Returns the FGState pointer.
294   inline FGState* GetState(void)              {return State;}
295   /// Retrieves the script object
296   inline FGScript* GetScript(void) {return Script;}
297   // Returns a pointer to the FGInitialCondition object
298   inline FGInitialCondition* GetIC(void)      {return IC;}
299   // Returns a pointer to the FGTrim object
300   FGTrim* GetTrim(void);
301   //@}
302
303   /// Retrieves the engine path.
304   inline string GetEnginePath(void)          {return EnginePath;}
305   /// Retrieves the aircraft path.
306   inline string GetAircraftPath(void)        {return AircraftPath;}
307   /// Retrieves the systems path.
308   inline string GetSystemsPath(void)         {return SystemsPath;}
309   /// Retrieves the full aircraft path name.
310   inline string GetFullAircraftPath(void)    {return FullAircraftPath;}
311
312   /** Retrieves the value of a property.
313       @param property the name of the property
314       @result the value of the specified property */
315   inline double GetPropertyValue(string property) {return instance->GetDouble(property);}
316
317   /** Sets a property value.
318       @param property the property to be set
319       @param value the value to set the property to */
320   inline void SetPropertyValue(string property, double value) {
321     instance->SetDouble(property, value);
322   }
323
324   /// Returns the model name.
325   string GetModelName(void) { return modelName; }
326
327   /// Returns the current time.
328   double GetSimTime(void);
329
330   /// Returns the current frame time (delta T).
331   double GetDeltaT(void);
332   
333   /// Returns a pointer to the property manager object.
334   FGPropertyManager* GetPropertyManager(void);
335   /// Returns a vector of strings representing the names of all loaded models (future)
336   vector <string> EnumerateFDMs(void);
337   /// Marks this instance of the Exec object as a "slave" object.
338   void SetSlave(bool s) {IsSlave = s;}
339
340   /** Sets the output (logging) mechanism for this run.
341       Calling this function passes the name of an output directives file to
342       the FGOutput object associated with this run. The call to this function
343       should be made prior to loading an aircraft model. This call results in an
344       FGOutput object being built as the first Output object in the FDMExec-managed
345       list of Output objects that may be created for an aircraft model. If this call
346       is made after an aircraft model is loaded, there is no effect. Any Output
347       objects added by the aircraft model itself (in an &lt;output> element) will be
348       added after this one. Care should be taken not to refer to the same file
349       name.
350       An output directives file contains an &lt;output> &lt;/output> element, within
351       which should be specified the parameters or parameter groups that should
352       be logged.
353       @param fname the filename of an output directives file.
354     */
355   bool SetOutputDirectives(string fname);
356
357   /** Sets (or overrides) the output filename
358       @param fname the name of the file to output data to
359       @return true if successful, false if there is no output specified for the flight model */
360   bool SetOutputFileName(string fname) {
361     if (Outputs.size() > 0) Outputs[0]->SetOutputFileName(fname);
362     else return false;
363     return true;
364   }
365
366   /** Retrieves the current output filename.
367       @return the name of the output file for the first output specified by the flight model.
368               If none is specified, the empty string is returned. */
369   string GetOutputFileName(void) {
370     if (Outputs.size() > 0) return Outputs[0]->GetOutputFileName();
371     else return string("");
372   }
373
374   /** Executes trimming in the selected mode.
375   *   @param mode Specifies how to trim:
376   * - tLongitudinal=0
377   * - tFull
378   * - tGround
379   * - tPullup
380   * - tCustom
381   * - tTurn
382   * - tNone  */
383   void DoTrim(int mode);
384 //  void DoTrimAnalysis(int mode);
385
386   /// Disables data logging to all outputs.
387   void DisableOutput(void);
388   /// Enables data logging to all outputs.
389   void EnableOutput(void);
390   /// Pauses execution by preventing time from incrementing.
391   void Hold(void) {holding = true;}
392   /// Resumes execution from a "Hold".
393   void Resume(void) {holding = false;}
394   /// Returns true if the simulation is Holding (i.e. simulation time is not moving).
395   bool Holding(void) {return holding;}
396   /// Resets the initial conditions object and prepares the simulation to run again.
397   void ResetToInitialConditions(void);
398   /// Sets the debug level.
399   void SetDebugLevel(int level) {debug_lvl = level;}
400
401   struct PropertyCatalogStructure {
402     /// Name of the property.
403     string base_string;
404     /// The node for the property.
405     FGPropertyManager *node;
406   };
407
408   /** Builds a catalog of properties.
409   *   This function descends the property tree and creates a list (an STL vector)
410   *   containing the name and node for all properties.
411   *   @param pcs The "root" property catalog structure pointer.  */
412   void BuildPropertyCatalog(struct PropertyCatalogStructure* pcs);
413
414   /** Retrieves property or properties matching the supplied string.
415   *   A string is returned that contains a carriage return delimited list of all
416   *   strings in the property catalog that matches the supplied check string.
417   *   @param check The string to search for in the property catalog.
418   *   @return the carriage-return-delimited string containing all matching strings
419   *               in the catalog.  */
420   string QueryPropertyCatalog(string check);
421
422   // Print the contents of the property catalog for the loaded aircraft.
423   void PrintPropertyCatalog(void);
424
425   /// Use the MSIS atmosphere model.
426   void UseAtmosphereMSIS(void);
427
428   /// Use the Mars atmosphere model. (Not operative yet.)
429   void UseAtmosphereMars(void);
430
431   void SetTrimStatus(bool status){ trim_status = status; }
432   bool GetTrimStatus(void) const { return trim_status; }
433   void SetTrimMode(int mode){ ta_mode = mode; }
434   int GetTrimMode(void) const { return ta_mode; }
435
436 private:
437   static unsigned int FDMctr;
438   int Error;
439   unsigned int Frame;
440   unsigned int IdFDM;
441   unsigned short Terminate;
442   bool holding;
443   bool Constructing;
444   bool modelLoaded;
445   bool IsSlave;
446   string modelName;
447   string AircraftPath;
448   string FullAircraftPath;
449   string EnginePath;
450   string SystemsPath;
451   string CFGVersion;
452   string Release;
453
454   bool trim_status;
455   int ta_mode;
456
457
458   struct slaveData {
459     FGFDMExec* exec;
460     string info;
461     double x, y, z;
462     double roll, pitch, yaw;
463     bool mated;
464
465     slaveData(void) {
466       info = "";
467       x = y = z = 0.0;
468       roll = pitch = yaw = 0.0;
469       mated = true;
470     }
471
472     ~slaveData(void) {
473       delete exec;
474     }
475   };
476
477   static FGPropertyManager *master;
478
479   FGModel*            FirstModel;
480   FGGroundCallback*   GroundCallback;
481   FGState*            State;
482   FGAtmosphere*       Atmosphere;
483   FGFCS*              FCS;
484   FGPropulsion*       Propulsion;
485   FGMassBalance*      MassBalance;
486   FGAerodynamics*     Aerodynamics;
487   FGInertial*         Inertial;
488   FGGroundReactions*  GroundReactions;
489   FGExternalReactions* ExternalReactions;
490   FGBuoyantForces*    BuoyantForces;
491   FGAircraft*         Aircraft;
492   FGPropagate*        Propagate;
493   FGAuxiliary*        Auxiliary;
494   FGInput*            Input;
495   FGScript*           Script;
496   FGInitialCondition* IC;
497   FGTrim*             Trim;
498
499   FGPropertyManager* Root;
500   FGPropertyManager* instance;
501
502   vector <string> PropertyCatalog;
503   vector <FGOutput*> Outputs;
504   vector <slaveData*> SlaveFDMList;
505
506   bool ReadFileHeader(Element*);
507   bool ReadSlave(Element*);
508   bool ReadPrologue(Element*);
509   bool Allocate(void);
510   bool DeAllocate(void);
511
512   void Debug(int from);
513 };
514 }
515 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
516 #endif