1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5 file The header file for the JSBSim executive.
7 ------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
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
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
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.
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.
27 --------------------------------------------------------------------------------
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
33 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
37 #ifndef FGFDMEXEC_HEADER_H
38 #define FGFDMEXEC_HEADER_H
40 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
47 #include "initialization/FGTrim.h"
48 #include "FGJSBBase.h"
49 #include "input_output/FGPropertyManager.h"
50 #include "models/FGPropagate.h"
51 #include "math/FGColumnVector3.h"
52 #include "models/FGOutput.h"
54 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
56 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
58 #define ID_FDMEXEC "$Id: FGFDMExec.h,v 1.86 2014/01/02 21:37:14 bcoconni Exp $"
60 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
62 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
71 class FGAccelerations;
74 class FGBuoyantForces;
75 class FGExternalReactions;
76 class FGGroundReactions;
83 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
87 /** Encapsulates the JSBSim simulation executive.
88 This class is the executive class through which all other simulation classes
89 are instantiated, initialized, and run. When integrated with FlightGear (or
90 other flight simulator) this class is typically instantiated by an interface
91 class on the simulator side.
93 At the time of simulation initialization, the interface
94 class creates an instance of this executive class. The
95 executive is subsequently directed to load the chosen aircraft specification
99 fdmex = new FGFDMExec( ... );
100 result = fdmex->LoadModel( ... );
103 When an aircraft model is loaded, the config file is parsed and for each of the
104 sections of the config file (propulsion, flight control, etc.) the
105 corresponding Load() method is called (e.g. FGFCS::Load()).
107 Subsequent to the creation of the executive and loading of the model,
108 initialization is performed. Initialization involves copying control inputs
109 into the appropriate JSBSim data storage locations, configuring it for the set
110 of user supplied initial conditions, and then copying state variables from
111 JSBSim. The state variables are used to drive the instrument displays and to
112 place the vehicle model in world space for visual rendering:
115 copy_to_JSBsim(); // copy control inputs to JSBSim
116 fdmex->RunIC(); // loop JSBSim once w/o integrating
117 copy_from_JSBsim(); // update the bus
120 Once initialization is complete, cyclic execution proceeds:
123 copy_to_JSBsim(); // copy control inputs to JSBSim
124 fdmex->Run(); // execute JSBSim
125 copy_from_JSBsim(); // update the bus
128 JSBSim can be used in a standalone mode by creating a compact stub program
129 that effectively performs the same progression of steps as outlined above for
130 the integrated version, but with two exceptions. First, the copy_to_JSBSim()
131 and copy_from_JSBSim() functions are not used because the control inputs are
132 handled directly by the scripting facilities and outputs are handled by the
133 output (data logging) class. Second, the name of a script file can be supplied
134 to the stub program. Scripting (see FGScript) provides a way to supply command
135 inputs to the simulation:
138 FDMExec = new JSBSim::FGFDMExec();
139 FDMExec->LoadScript( ScriptName ); // the script loads the aircraft and ICs
140 result = FDMExec->Run();
141 while (result) { // cyclic execution
142 result = FDMExec->Run(); // execute JSBSim
146 The standalone mode has been useful for verifying changes before committing
147 updates to the source code repository. It is also useful for running sets of
148 tests that reveal some aspects of simulated aircraft performance, such as
149 range, time-to-climb, takeoff distance, etc.
151 <h3>JSBSim Debugging Directives</h3>
153 This describes to any interested entity the debug level
154 requested by setting the JSBSIM_DEBUG environment variable.
155 The bitmasked value choices are as follows:
156 - <b>unset</b>: In this case (the default) JSBSim would only print
157 out the normally expected messages, essentially echoing
158 the config files as they are read. If the environment
159 variable is not set, debug_lvl is set to 1 internally
160 - <b>0</b>: This requests JSBSim not to output any messages
162 - <b>1</b>: This value explicity requests the normal JSBSim
164 - <b>2</b>: This value asks for a message to be printed out when
165 a class is instantiated
166 - <b>4</b>: When this value is set, a message is displayed when a
167 FGModel object executes its Run() method
168 - <b>8</b>: When this value is set, various runtime state variables
169 are printed out periodically
170 - <b>16</b>: When set various parameters are sanity checked and
171 a message is printed out when they go out of bounds
174 @property simulator/do_trim (write only) Can be set to the integer equivalent to one of
175 tLongitudinal (0), tFull (1), tGround (2), tPullup (3),
176 tCustom (4), tTurn (5). Setting this to a legal value
177 (such as by a script) causes a trim to be performed. This
178 property actually maps toa function call of DoTrim().
180 @author Jon S. Berndt
181 @version $Revision: 1.86 $
184 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
186 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
188 class FGFDMExec : public FGJSBBase
194 FGColumnVector3 Orient;
200 Loc = FGColumnVector3(0,0,0);
201 Orient = FGColumnVector3(0,0,0);
206 void Run(void) {exec->Run();}
207 void AssignState(FGPropagate* source_prop) {
208 exec->GetPropagate()->SetVState(source_prop->GetVState());
218 /// Default constructor
219 FGFDMExec(FGPropertyManager* root = 0, unsigned int* fdmctr = 0);
221 /// Default destructor
224 // This list of enums is very important! The order in which models are listed here
225 // determines the order of execution of the models.
226 enum eModels { ePropagate=0,
242 eNumStandardModels };
244 /** Unbind all tied JSBSim properties. */
245 void Unbind(void) {instance->Unbind();}
247 /** This routine places a model into the runlist at the specified rate. The
248 "rate" is not really a clock rate. It represents how many calls to the
249 FGFDMExec::Run() method must be made before the model is executed. A
250 value of 1 means that the model will be executed for each call to the
251 exec's Run() method. A value of 5 means that the model will only be
252 executed every 5th call to the exec's Run() method. Use of a rate other than
253 one is at this time not recommended.
254 @param model A pointer to the model being scheduled.
255 @param rate The rate at which to execute the model as described above.
256 Default is every frame (rate=1).
257 @return Currently returns 0 always. */
258 void Schedule(FGModel* model, int rate=1);
260 /** This function executes each scheduled model in succession.
261 @return true if successful, false if sim should be ended */
264 /** Initializes the sim from the initial condition object and executes
265 each scheduled model without integrating i.e. dt=0.
266 @return true if successful */
269 /** Sets the ground callback pointer. For optimal memory management, a shared
270 pointer is used internally that maintains a reference counter. The calling
271 application must therefore use FGGroundCallback_ptr 'smart pointers' to
272 manage their copy of the ground callback.
273 @param gc A pointer to a ground callback object
274 @see FGGroundCallback
276 void SetGroundCallback(FGGroundCallback* gc) { FGLocation::SetGroundCallback(gc); }
278 /** Loads an aircraft model.
279 @param AircraftPath path to the aircraft/ directory. For instance:
280 "aircraft". Under aircraft, then, would be directories for various
281 modeled aircraft such as C172/, x15/, etc.
282 @param EnginePath path to the directory under which engine config
283 files are kept, for instance "engine"
284 @param SystemsPath path to the directory under which systems config
285 files are kept, for instance "systems"
286 @param model the name of the aircraft model itself. This file will
287 be looked for in the directory specified in the AircraftPath variable,
288 and in turn under the directory with the same name as the model. For
289 instance: "aircraft/x15/x15.xml"
290 @param addModelToPath set to true to add the model name to the
291 AircraftPath, defaults to true
292 @return true if successful */
293 bool LoadModel(const std::string& AircraftPath, const std::string& EnginePath,
294 const std::string& SystemsPath, const std::string& model,
295 bool addModelToPath = true);
297 /** Loads an aircraft model. The paths to the aircraft and engine
298 config file directories must be set prior to calling this. See
300 @param model the name of the aircraft model itself. This file will
301 be looked for in the directory specified in the AircraftPath variable,
302 and in turn under the directory with the same name as the model. For
303 instance: "aircraft/x15/x15.xml"
304 @param addModelToPath set to true to add the model name to the
305 AircraftPath, defaults to true
306 @return true if successful*/
307 bool LoadModel(const std::string& model, bool addModelToPath = true);
310 @param Script The full path name and file name for the script to be loaded.
311 @param deltaT The simulation integration step size, if given. If no value is supplied
312 then 0.0 is used and the value is expected to be supplied in
313 the script file itself.
314 @param initfile The initialization file that will override the initialization file
315 specified in the script file. If no file name is given on the command line,
316 the file specified in the script will be used. If an initialization file
317 is not given in either place, an error will result.
318 @return true if successfully loads; false otherwise. */
319 bool LoadScript(const std::string& Script, double deltaT=0.0,
320 const std::string initfile="");
322 /** Sets the path to the engine config file directories.
323 @param path path to the directory under which engine config
324 files are kept, for instance "engine" */
325 bool SetEnginePath(const std::string& path) { EnginePath = RootDir + path; return true; }
327 /** Sets the path to the aircraft config file directories.
328 @param path path to the aircraft directory. For instance:
329 "aircraft". Under aircraft, then, would be directories for various
330 modeled aircraft such as C172/, x15/, etc. */
331 bool SetAircraftPath(const std::string& path) { AircraftPath = RootDir + path; return true; }
333 /** Sets the path to the systems config file directories.
334 @param path path to the directory under which systems config
335 files are kept, for instance "systems" */
336 bool SetSystemsPath(const std::string& path) { SystemsPath = RootDir + path; return true; }
338 /// @name Top-level executive State and Model retrieval mechanism
340 /// Returns the FGAtmosphere pointer.
341 FGAtmosphere* GetAtmosphere(void) {return (FGAtmosphere*)Models[eAtmosphere];}
342 /// Returns the FGAccelerations pointer.
343 FGAccelerations* GetAccelerations(void) {return (FGAccelerations*)Models[eAccelerations];}
344 /// Returns the FGWinds pointer.
345 FGWinds* GetWinds(void) {return (FGWinds*)Models[eWinds];}
346 /// Returns the FGFCS pointer.
347 FGFCS* GetFCS(void) {return (FGFCS*)Models[eSystems];}
348 /// Returns the FGPropulsion pointer.
349 FGPropulsion* GetPropulsion(void) {return (FGPropulsion*)Models[ePropulsion];}
350 /// Returns the FGAircraft pointer.
351 FGMassBalance* GetMassBalance(void) {return (FGMassBalance*)Models[eMassBalance];}
352 /// Returns the FGAerodynamics pointer
353 FGAerodynamics* GetAerodynamics(void){return (FGAerodynamics*)Models[eAerodynamics];}
354 /// Returns the FGInertial pointer.
355 FGInertial* GetInertial(void) {return (FGInertial*)Models[eInertial];}
356 /// Returns the FGGroundReactions pointer.
357 FGGroundReactions* GetGroundReactions(void) {return (FGGroundReactions*)Models[eGroundReactions];}
358 /// Returns the FGExternalReactions pointer.
359 FGExternalReactions* GetExternalReactions(void) {return (FGExternalReactions*)Models[eExternalReactions];}
360 /// Returns the FGBuoyantForces pointer.
361 FGBuoyantForces* GetBuoyantForces(void) {return (FGBuoyantForces*)Models[eBuoyantForces];}
362 /// Returns the FGAircraft pointer.
363 FGAircraft* GetAircraft(void) {return (FGAircraft*)Models[eAircraft];}
364 /// Returns the FGPropagate pointer.
365 FGPropagate* GetPropagate(void) {return (FGPropagate*)Models[ePropagate];}
366 /// Returns the FGAuxiliary pointer.
367 FGAuxiliary* GetAuxiliary(void) {return (FGAuxiliary*)Models[eAuxiliary];}
368 /// Returns the FGInput pointer.
369 FGInput* GetInput(void) {return (FGInput*)Models[eInput];}
370 /** Get a pointer to the ground callback currently used. It is recommanded
371 to store the returned pointer in a 'smart pointer' FGGroundCallback_ptr.
372 @return A pointer to the current ground callback object.
373 @see FGGroundCallback
375 FGGroundCallback* GetGroundCallback(void) {return FGLocation::GetGroundCallback();}
376 /// Retrieves the script object
377 FGScript* GetScript(void) {return Script;}
378 /// Returns a pointer to the FGInitialCondition object
379 FGInitialCondition* GetIC(void) {return IC;}
380 /// Returns a pointer to the FGTrim object
381 FGTrim* GetTrim(void);
384 /// Retrieves the engine path.
385 const std::string& GetEnginePath(void) {return EnginePath;}
386 /// Retrieves the aircraft path.
387 const std::string& GetAircraftPath(void) {return AircraftPath;}
388 /// Retrieves the systems path.
389 const std::string& GetSystemsPath(void) {return SystemsPath;}
390 /// Retrieves the full aircraft path name.
391 const std::string& GetFullAircraftPath(void) {return FullAircraftPath;}
393 /** Retrieves the value of a property.
394 @param property the name of the property
395 @result the value of the specified property */
396 inline double GetPropertyValue(const std::string& property)
397 { return instance->GetNode()->GetDouble(property); }
399 /** Sets a property value.
400 @param property the property to be set
401 @param value the value to set the property to */
402 inline void SetPropertyValue(const std::string& property, double value) {
403 instance->GetNode()->SetDouble(property, value);
406 /// Returns the model name.
407 const std::string& GetModelName(void) const { return modelName; }
409 /// Returns the current time.
410 double GetSimTime(void);
412 /// Returns the current frame time (delta T).
413 double GetDeltaT(void);
415 /// Returns a pointer to the property manager object.
416 FGPropertyManager* GetPropertyManager(void);
417 /// Returns a vector of strings representing the names of all loaded models (future)
418 std::vector <std::string> EnumerateFDMs(void);
419 /// Gets the number of child FDMs.
420 int GetFDMCount(void) const {return (int)ChildFDMList.size();}
421 /// Gets a particular child FDM.
422 childData* GetChildFDM(int i) const {return ChildFDMList[i];}
423 /// Marks this instance of the Exec object as a "child" object.
424 void SetChild(bool ch) {IsChild = ch;}
426 /** Sets the output (logging) mechanism for this run.
427 Calling this function passes the name of an output directives file to
428 the FGOutput object associated with this run. The call to this function
429 should be made prior to loading an aircraft model. This call results in an
430 FGOutput object being built as the first Output object in the FDMExec-managed
431 list of Output objects that may be created for an aircraft model. If this call
432 is made after an aircraft model is loaded, there is no effect. Any Output
433 objects added by the aircraft model itself (in an <output> element) will be
434 added after this one. Care should be taken not to refer to the same file
436 An output directives file contains an <output> </output> element, within
437 which should be specified the parameters or parameter groups that should
439 @param fname the filename of an output directives file.
441 bool SetOutputDirectives(const std::string& fname)
442 {return Output->SetDirectivesFile(RootDir + fname);}
444 /** Forces the specified output object to print its items once */
445 void ForceOutput(int idx=0) { Output->ForceOutput(idx); }
447 /** Sets the logging rate for all output objects (if any). */
448 void SetLoggingRate(double rate) { Output->SetRate(rate); }
450 /** Sets (or overrides) the output filename
451 @param fname the name of the file to output data to
452 @return true if successful, false if there is no output specified for the flight model */
453 bool SetOutputFileName(const int n, const std::string& fname) { return Output->SetOutputName(n, fname); }
455 /** Retrieves the current output filename.
456 @param n index of file
457 @return the name of the output file for the output specified by the flight model.
458 If none is specified, the empty string is returned. */
459 std::string GetOutputFileName(int n) const { return Output->GetOutputName(n); }
461 /** Executes trimming in the selected mode.
462 * @param mode Specifies how to trim:
470 void DoTrim(int mode);
471 void DoSimplexTrim(int mode);
473 /** Executes linearization with state-space output
474 * You must trim first to get an accurate state-space model
476 void DoLinearization(int mode);
478 /// Disables data logging to all outputs.
479 void DisableOutput(void) { Output->Disable(); }
480 /// Enables data logging to all outputs.
481 void EnableOutput(void) { Output->Enable(); }
482 /// Pauses execution by preventing time from incrementing.
483 void Hold(void) {holding = true;}
484 /// Turn on hold after increment
485 void EnableIncrementThenHold(int Timesteps) {TimeStepsUntilHold = Timesteps; IncrementThenHolding = true;}
486 /// Checks if required to hold afer increment
487 void CheckIncrementalHold(void);
488 /// Resumes execution from a "Hold".
489 void Resume(void) {holding = false;}
490 /// Returns true if the simulation is Holding (i.e. simulation time is not moving).
491 bool Holding(void) {return holding;}
492 /// Resets the initial conditions object and prepares the simulation to run again.
493 void ResetToInitialConditions(void);
494 /// Sets the debug level.
495 void SetDebugLevel(int level) {debug_lvl = level;}
497 struct PropertyCatalogStructure {
498 /// Name of the property.
499 std::string base_string;
500 /// The node for the property.
501 FGPropertyNode_ptr node;
504 /** Builds a catalog of properties.
505 * This function descends the property tree and creates a list (an STL vector)
506 * containing the name and node for all properties.
507 * @param pcs The "root" property catalog structure pointer. */
508 void BuildPropertyCatalog(struct PropertyCatalogStructure* pcs);
510 /** Retrieves property or properties matching the supplied string.
511 * A string is returned that contains a carriage return delimited list of all
512 * strings in the property catalog that matches the supplied check string.
513 * @param check The string to search for in the property catalog.
514 * @return the carriage-return-delimited string containing all matching strings
516 std::string QueryPropertyCatalog(const std::string& check);
518 // Print the contents of the property catalog for the loaded aircraft.
519 void PrintPropertyCatalog(void);
521 std::vector<std::string>& GetPropertyCatalog(void) {return PropertyCatalog;}
523 void SetTrimStatus(bool status){ trim_status = status; }
524 bool GetTrimStatus(void) const { return trim_status; }
525 void SetTrimMode(int mode){ ta_mode = mode; }
526 int GetTrimMode(void) const { return ta_mode; }
528 std::string GetPropulsionTankReport();
530 /// Returns the cumulative simulation time in seconds.
531 double GetSimTime(void) const { return sim_time; }
533 /// Returns the simulation delta T.
534 double GetDeltaT(void) const {return dT;}
536 /// Suspends the simulation and sets the delta T to zero.
537 void SuspendIntegration(void) {saved_dT = dT; dT = 0.0;}
539 /// Resumes the simulation by resetting delta T to the correct value.
540 void ResumeIntegration(void) {dT = saved_dT;}
542 /** Returns the simulation suspension state.
543 @return true if suspended, false if executing */
544 bool IntegrationSuspended(void) const {return dT == 0.0;}
546 /** Sets the current sim time.
547 @param cur_time the current time
548 @return the current simulation time. */
549 double Setsim_time(double cur_time) {
554 /** Sets the integration time step for the simulation executive.
555 @param delta_t the time step in seconds. */
556 void Setdt(double delta_t) { dT = delta_t; }
558 /** Sets the root directory where JSBSim starts looking for its system directories.
559 @param rootDir the string containing the root directory. */
560 void SetRootDir(const std::string& rootDir) {RootDir = rootDir;}
562 /** Retrieves the Root Directory.
563 @return the string representing the root (base) JSBSim directory. */
564 const std::string& GetRootDir(void) const {return RootDir;}
566 /** Increments the simulation time if not in Holding mode. The Frame counter
568 @return the new simulation time. */
569 double IncrTime(void) {
570 if (!holding) sim_time += dT;
575 /** Retrieves the current debug level setting. */
576 int GetDebugLevel(void) const {return debug_lvl;};
578 /** Initializes the simulation with initial conditions
579 @param FGIC The initial conditions that will be passed to the simulation. */
580 void Initialize(FGInitialCondition *FGIC);
586 unsigned short Terminate;
591 bool IncrementThenHolding;
592 int TimeStepsUntilHold;
596 std::string modelName;
597 std::string AircraftPath;
598 std::string FullAircraftPath;
599 std::string EnginePath;
600 std::string SystemsPath;
601 std::string CFGVersion;
605 // Standard Model pointers - shortcuts for internal executive use only.
606 FGPropagate* Propagate;
607 FGInertial* Inertial;
608 FGAtmosphere* Atmosphere;
610 FGAuxiliary* Auxiliary;
612 FGPropulsion* Propulsion;
613 FGAerodynamics* Aerodynamics;
614 FGGroundReactions* GroundReactions;
615 FGExternalReactions* ExternalReactions;
616 FGBuoyantForces* BuoyantForces;
617 FGMassBalance* MassBalance;
618 FGAircraft* Aircraft;
619 FGAccelerations* Accelerations;
624 unsigned int ResetMode;
627 FGInitialCondition* IC;
630 FGPropertyManager* Root;
632 FGPropertyManager* instance;
634 // The FDM counter is used to give each child FDM an unique ID. The root FDM has the ID 0
635 unsigned int* FDMctr;
637 std::vector <std::string> PropertyCatalog;
638 std::vector <childData*> ChildFDMList;
639 std::vector <FGModel*> Models;
641 bool ReadFileHeader(Element*);
642 bool ReadChild(Element*);
643 bool ReadPrologue(Element*);
645 void LoadInputs(unsigned int idx);
646 void LoadPlanetConstants(void);
647 void LoadModelConstants(void);
649 bool DeAllocate(void);
651 void Debug(int from);
654 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%