]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Merge branch 'ehofman/sound'
[flightgear.git] / src / FDM / JSBSim / models / propulsion / FGPiston.cpp
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3  Module:       FGPiston.cpp
4  Author:       Jon S. Berndt, JSBSim framework
5                Dave Luff, Piston engine model
6                Ronald Jensen, Piston engine model
7  Date started: 09/12/2000
8  Purpose:      This module models a Piston engine
9
10  ------------- Copyright (C) 2000  Jon S. Berndt (jon@jsbsim.org) --------------
11
12  This program is free software; you can redistribute it and/or modify it under
13  the terms of the GNU Lesser General Public License as published by the Free Software
14  Foundation; either version 2 of the License, or (at your option) any later
15  version.
16
17  This program is distributed in the hope that it will be useful, but WITHOUT
18  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
20  details.
21
22  You should have received a copy of the GNU Lesser General Public License along with
23  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
24  Place - Suite 330, Boston, MA  02111-1307, USA.
25
26  Further information about the GNU Lesser General Public License can also be found on
27  the world wide web at http://www.gnu.org.
28
29 FUNCTIONAL DESCRIPTION
30 --------------------------------------------------------------------------------
31
32 This class descends from the FGEngine class and models a Piston engine based on
33 parameters given in the engine config file for this class
34
35 HISTORY
36 --------------------------------------------------------------------------------
37 09/12/2000  JSB  Created
38
39 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40 INCLUDES
41 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
42
43 #include <sstream>
44
45 #include "FGPiston.h"
46 #include "FGState.h"
47 #include "models/FGAtmosphere.h"
48 #include "models/FGPropulsion.h"
49 #include "FGPropeller.h"
50 #include <iostream>
51
52 using namespace std;
53
54 namespace JSBSim {
55
56 static const char *IdSrc = "$Id$";
57 static const char *IdHdr = ID_PISTON;
58
59 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
60 CLASS IMPLEMENTATION
61 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
62
63 FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number)
64   : FGEngine(exec, el, engine_number),
65   R_air(287.3),                  // Gas constant for air J/Kg/K
66   rho_fuel(800),                 // estimate
67   calorific_value_fuel(47.3e6),
68   Cp_air(1005),                  // Specific heat (constant pressure) J/Kg/K
69   Cp_fuel(1700),
70   standard_pressure(101320.73)
71 {
72   string token;
73
74   // Defaults and initializations
75
76   Type = etPiston;
77   dt = State->Getdt();
78
79   // These items are read from the configuration file
80   // Defaults are from a Lycoming O-360, more or less
81
82   Cycles = 4;
83   IdleRPM = 600;
84   MaxRPM = 2800;
85   Displacement = 360;
86   SparkFailDrop = 1.0;
87   MaxHP = 200;
88   MinManifoldPressure_inHg = 6.5;
89   MaxManifoldPressure_inHg = 28.5;
90   ISFC = -1;
91   volumetric_efficiency = 0.85;
92   Bore = 5.125;
93   Stroke = 4.375;
94   Cylinders = 4;
95   CompressionRatio = 8.5;
96   Z_airbox = -999;
97   Ram_Air_Factor = 1;
98   PeakMeanPistonSpeed_fps = 100;
99
100   // These are internal program variables
101
102   crank_counter = 0;
103   Magnetos = 0;
104   minMAP = 21950;
105   maxMAP = 96250;
106
107   ResetToIC();
108
109   // Supercharging
110   BoostSpeeds = 0;  // Default to no supercharging
111   BoostSpeed = 0;
112   Boosted = false;
113   BoostOverride = 0;
114   BoostManual = 0;
115   bBoostOverride = false;
116   bTakeoffBoost = false;
117   TakeoffBoost = 0.0;   // Default to no extra takeoff-boost
118   int i;
119   for (i=0; i<FG_MAX_BOOST_SPEEDS; i++) {
120     RatedBoost[i] = 0.0;
121     RatedPower[i] = 0.0;
122     RatedAltitude[i] = 0.0;
123     BoostMul[i] = 1.0;
124     RatedMAP[i] = 100000;
125     RatedRPM[i] = 2500;
126     TakeoffMAP[i] = 100000;
127   }
128   for (i=0; i<FG_MAX_BOOST_SPEEDS-1; i++) {
129     BoostSwitchAltitude[i] = 0.0;
130     BoostSwitchPressure[i] = 0.0;
131   }
132
133   // First column is thi, second is neta (combustion efficiency)
134   Lookup_Combustion_Efficiency = new FGTable(12);
135   *Lookup_Combustion_Efficiency << 0.00 << 0.980;
136   *Lookup_Combustion_Efficiency << 0.90 << 0.980;
137   *Lookup_Combustion_Efficiency << 1.00 << 0.970;
138   *Lookup_Combustion_Efficiency << 1.05 << 0.950;
139   *Lookup_Combustion_Efficiency << 1.10 << 0.900;
140   *Lookup_Combustion_Efficiency << 1.15 << 0.850;
141   *Lookup_Combustion_Efficiency << 1.20 << 0.790;
142   *Lookup_Combustion_Efficiency << 1.30 << 0.700;
143   *Lookup_Combustion_Efficiency << 1.40 << 0.630;
144   *Lookup_Combustion_Efficiency << 1.50 << 0.570;
145   *Lookup_Combustion_Efficiency << 1.60 << 0.525;
146   *Lookup_Combustion_Efficiency << 2.00 << 0.345;
147
148   Mixture_Efficiency_Correlation = new FGTable(15);
149   *Mixture_Efficiency_Correlation << 0.05000 << 0.00000;
150   *Mixture_Efficiency_Correlation << 0.05137 << 0.00862;
151   *Mixture_Efficiency_Correlation << 0.05179 << 0.21552;
152   *Mixture_Efficiency_Correlation << 0.05430 << 0.48276;
153   *Mixture_Efficiency_Correlation << 0.05842 << 0.70690;
154   *Mixture_Efficiency_Correlation << 0.06312 << 0.83621;
155   *Mixture_Efficiency_Correlation << 0.06942 << 0.93103;
156   *Mixture_Efficiency_Correlation << 0.07786 << 1.00000;
157   *Mixture_Efficiency_Correlation << 0.08845 << 1.00000;
158   *Mixture_Efficiency_Correlation << 0.09270 << 0.98276;
159   *Mixture_Efficiency_Correlation << 0.10120 << 0.93103;
160   *Mixture_Efficiency_Correlation << 0.11455 << 0.72414;
161   *Mixture_Efficiency_Correlation << 0.12158 << 0.45690;
162   *Mixture_Efficiency_Correlation << 0.12435 << 0.23276;
163   *Mixture_Efficiency_Correlation << 0.12500 << 0.00000;
164
165
166   // Read inputs from engine data file where present.
167
168   if (el->FindElement("minmp")) // Should have ELSE statement telling default value used?
169     MinManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("minmp","INHG");
170   if (el->FindElement("maxmp"))
171     MaxManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("maxmp","INHG");
172   if (el->FindElement("displacement"))
173     Displacement = el->FindElementValueAsNumberConvertTo("displacement","IN3");
174   if (el->FindElement("maxhp"))
175     MaxHP = el->FindElementValueAsNumberConvertTo("maxhp","HP");
176   if (el->FindElement("sparkfaildrop"))
177     SparkFailDrop = Constrain(0, 1 - el->FindElementValueAsNumber("sparkfaildrop"), 1);
178   if (el->FindElement("cycles"))
179     Cycles = el->FindElementValueAsNumber("cycles");
180   if (el->FindElement("idlerpm"))
181     IdleRPM = el->FindElementValueAsNumber("idlerpm");
182   if (el->FindElement("maxrpm"))
183     MaxRPM = el->FindElementValueAsNumber("maxrpm");
184   if (el->FindElement("maxthrottle"))
185     MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
186   if (el->FindElement("minthrottle"))
187     MinThrottle = el->FindElementValueAsNumber("minthrottle");
188   if (el->FindElement("bsfc"))
189     ISFC = el->FindElementValueAsNumberConvertTo("bsfc", "LBS/HP*HR");
190   if (el->FindElement("volumetric-efficiency"))
191     volumetric_efficiency = el->FindElementValueAsNumber("volumetric-efficiency");
192   if (el->FindElement("compression-ratio"))
193     CompressionRatio = el->FindElementValueAsNumber("compression-ratio");
194   if (el->FindElement("bore"))
195     Bore = el->FindElementValueAsNumberConvertTo("bore","IN");
196   if (el->FindElement("stroke"))
197     Stroke = el->FindElementValueAsNumberConvertTo("stroke","IN");
198   if (el->FindElement("cylinders"))
199     Cylinders = el->FindElementValueAsNumber("cylinders");
200   if (el->FindElement("air-intake-impedance-factor"))
201     Z_airbox = el->FindElementValueAsNumber("air-intake-impedance-factor");
202   if (el->FindElement("ram-air-factor"))
203     Ram_Air_Factor  = el->FindElementValueAsNumber("ram-air-factor");
204   if (el->FindElement("peak-piston-speed"))
205     PeakMeanPistonSpeed_fps  = el->FindElementValueAsNumber("peak-piston-speed");
206   if (el->FindElement("numboostspeeds")) { // Turbo- and super-charging parameters
207     BoostSpeeds = (int)el->FindElementValueAsNumber("numboostspeeds");
208     if (el->FindElement("boostoverride"))
209       BoostOverride = (int)el->FindElementValueAsNumber("boostoverride");
210     if (el->FindElement("boostmanual"))
211       BoostManual = (int)el->FindElementValueAsNumber("boostmanual");
212     if (el->FindElement("takeoffboost"))
213       TakeoffBoost = el->FindElementValueAsNumberConvertTo("takeoffboost", "PSI");
214     if (el->FindElement("ratedboost1"))
215       RatedBoost[0] = el->FindElementValueAsNumberConvertTo("ratedboost1", "PSI");
216     if (el->FindElement("ratedboost2"))
217       RatedBoost[1] = el->FindElementValueAsNumberConvertTo("ratedboost2", "PSI");
218     if (el->FindElement("ratedboost3"))
219       RatedBoost[2] = el->FindElementValueAsNumberConvertTo("ratedboost3", "PSI");
220     if (el->FindElement("ratedpower1"))
221       RatedPower[0] = el->FindElementValueAsNumberConvertTo("ratedpower1", "HP");
222     if (el->FindElement("ratedpower2"))
223       RatedPower[1] = el->FindElementValueAsNumberConvertTo("ratedpower2", "HP");
224     if (el->FindElement("ratedpower3"))
225       RatedPower[2] = el->FindElementValueAsNumberConvertTo("ratedpower3", "HP");
226     if (el->FindElement("ratedrpm1"))
227       RatedRPM[0] = el->FindElementValueAsNumber("ratedrpm1");
228     if (el->FindElement("ratedrpm2"))
229       RatedRPM[1] = el->FindElementValueAsNumber("ratedrpm2");
230     if (el->FindElement("ratedrpm3"))
231       RatedRPM[2] = el->FindElementValueAsNumber("ratedrpm3");
232     if (el->FindElement("ratedaltitude1"))
233       RatedAltitude[0] = el->FindElementValueAsNumberConvertTo("ratedaltitude1", "FT");
234     if (el->FindElement("ratedaltitude2"))
235       RatedAltitude[1] = el->FindElementValueAsNumberConvertTo("ratedaltitude2", "FT");
236     if (el->FindElement("ratedaltitude3"))
237       RatedAltitude[2] = el->FindElementValueAsNumberConvertTo("ratedaltitude3", "FT");
238   }
239
240   StarterHP = sqrt(MaxHP) * 0.4;
241   displacement_SI = Displacement * in3tom3;
242   RatedMeanPistonSpeed_fps =  ( MaxRPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
243
244   // Create IFSC to match the engine if not provided
245   if (ISFC < 0) {
246       double pmep = 29.92 - MaxManifoldPressure_inHg;
247       pmep *= inhgtopa;
248       double fmep = (18400 * RatedMeanPistonSpeed_fps * fttom + 46500);
249       double hp_loss = ((pmep + fmep) * displacement_SI * MaxRPM)/(Cycles*22371);
250       ISFC = ( 1.1*Displacement * MaxRPM * volumetric_efficiency *(MaxManifoldPressure_inHg / 29.92) ) / (9411 * (MaxHP+hp_loss));
251 // cout <<"FMEP: "<< fmep <<" PMEP: "<< pmep << " hp_loss: " <<hp_loss <<endl;
252   }
253   if ( MaxManifoldPressure_inHg > 29.9 ) {   // Don't allow boosting with a bogus number
254       MaxManifoldPressure_inHg = 29.9;
255   }
256   minMAP = MinManifoldPressure_inHg * inhgtopa;  // inHg to Pa
257   maxMAP = MaxManifoldPressure_inHg * inhgtopa;
258
259 // For throttle
260 /*
261  * Pm = ( Ze / ( Ze + Zi + Zt ) ) * Pa
262  * Where:
263  * Pm = Manifold Pressure
264  * Pa = Ambient Pressre
265  * Ze = engine impedance, Ze is effectively 1 / Mean Piston Speed  
266  * Zi = airbox impedance
267  * Zt = throttle impedance
268  * 
269  * For the calculation below throttle is fully open or Zt = 0
270  *
271  * 
272  *
273  */
274
275   if(Z_airbox < 0.0){
276     double Ze=PeakMeanPistonSpeed_fps/RatedMeanPistonSpeed_fps; // engine impedence
277     Z_airbox = (standard_pressure *Ze / maxMAP) - Ze; // impedence of airbox
278   }
279   Z_throttle=(((MaxRPM * Stroke) / 360)/((IdleRPM * Stroke) / 360))*(standard_pressure/minMAP - 1) - Z_airbox; // Constant for Throttle impedence
280
281   string property_name, base_property_name;
282   base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
283   property_name = base_property_name + "/power-hp";
284   PropertyManager->Tie(property_name, &HP);
285   property_name = base_property_name + "/bsfc-lbs_hphr";
286   PropertyManager->Tie(property_name, &ISFC);
287   property_name = base_property_name + "/volumetric-efficiency";
288   PropertyManager->Tie(property_name, &volumetric_efficiency);
289   property_name = base_property_name + "/map-pa";
290   PropertyManager->Tie(property_name, &MAP);
291   property_name = base_property_name + "/map-inhg";
292   PropertyManager->Tie(property_name, &ManifoldPressure_inHg);
293   property_name = base_property_name + "/air-intake-impedance-factor";
294   PropertyManager->Tie(property_name, &Z_airbox);
295   property_name = base_property_name + "/ram-air-factor";
296   PropertyManager->Tie(property_name, &Ram_Air_Factor);
297   property_name = base_property_name + "/boost-speed";
298   PropertyManager->Tie(property_name, &BoostSpeed);
299
300   // Set up and sanity-check the turbo/supercharging configuration based on the input values.
301   if (TakeoffBoost > RatedBoost[0]) bTakeoffBoost = true;
302   for (i=0; i<BoostSpeeds; ++i) {
303     bool bad = false;
304     if (RatedBoost[i] <= 0.0) bad = true;
305     if (RatedPower[i] <= 0.0) bad = true;
306     if (RatedAltitude[i] < 0.0) bad = true;  // 0.0 is deliberately allowed - this corresponds to unregulated supercharging.
307     if (i > 0 && RatedAltitude[i] < RatedAltitude[i - 1]) bad = true;
308     if (bad) {
309       // We can't recover from the above - don't use this supercharger speed.
310       BoostSpeeds--;
311       // TODO - put out a massive error message!
312       break;
313     }
314     // Now sanity-check stuff that is recoverable.
315     if (i < BoostSpeeds - 1) {
316       if (BoostSwitchAltitude[i] < RatedAltitude[i]) {
317         // TODO - put out an error message
318         // But we can also make a reasonable estimate, as below.
319         BoostSwitchAltitude[i] = RatedAltitude[i] + 1000;
320       }
321       BoostSwitchPressure[i] = Atmosphere->GetPressure(BoostSwitchAltitude[i]) * psftopa;
322       //cout << "BoostSwitchAlt = " << BoostSwitchAltitude[i] << ", pressure = " << BoostSwitchPressure[i] << '\n';
323       // Assume there is some hysteresis on the supercharger gear switch, and guess the value for now
324       BoostSwitchHysteresis = 1000;
325     }
326     // Now work out the supercharger pressure multiplier of this speed from the rated boost and altitude.
327     RatedMAP[i] = Atmosphere->GetPressureSL() * psftopa + RatedBoost[i] * 6895;  // psi*6895 = Pa.
328     // Sometimes a separate BCV setting for takeoff or extra power is fitted.
329     if (TakeoffBoost > RatedBoost[0]) {
330       // Assume that the effect on the BCV is the same whichever speed is in use.
331       TakeoffMAP[i] = RatedMAP[i] + ((TakeoffBoost - RatedBoost[0]) * 6895);
332       bTakeoffBoost = true;
333     } else {
334       TakeoffMAP[i] = RatedMAP[i];
335       bTakeoffBoost = false;
336     }
337     BoostMul[i] = RatedMAP[i] / (Atmosphere->GetPressure(RatedAltitude[i]) * psftopa);
338
339   }
340
341   if (BoostSpeeds > 0) {
342     Boosted = true;
343     BoostSpeed = 0;
344   }
345   bBoostOverride = (BoostOverride == 1 ? true : false);
346   bBoostManual   = (BoostManual   == 1 ? true : false);
347   Debug(0); // Call Debug() routine from constructor if needed
348 }
349
350 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
351
352 FGPiston::~FGPiston()
353 {
354   delete Lookup_Combustion_Efficiency;
355   delete Mixture_Efficiency_Correlation;
356   Debug(1); // Call Debug() routine from constructor if needed
357 }
358
359 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
360
361 void FGPiston::ResetToIC(void)
362 {
363   FGEngine::ResetToIC();
364
365   ManifoldPressure_inHg = Atmosphere->GetPressure() * psftoinhg; // psf to in Hg
366   MAP = Atmosphere->GetPressure() * psftopa;
367   TMAP = MAP;
368   double airTemperature_degK = RankineToKelvin(Atmosphere->GetTemperature());
369   OilTemp_degK = airTemperature_degK;
370   CylinderHeadTemp_degK = airTemperature_degK;
371   ExhaustGasTemp_degK = airTemperature_degK;
372   EGT_degC = ExhaustGasTemp_degK - 273;
373   Thruster->SetRPM(0.0);
374   RPM = 0.0;
375   OilPressure_psi = 0.0;
376 }
377
378 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
379
380 double FGPiston::Calculate(void)
381 {
382   if (FuelFlow_gph > 0.0) ConsumeFuel();
383
384   Throttle = FCS->GetThrottlePos(EngineNumber);
385   // calculate the throttle plate angle.  1 unit is approx pi/2 radians.
386   ThrottleAngle = MinThrottle+((MaxThrottle-MinThrottle)*Throttle );
387   Mixture = FCS->GetMixturePos(EngineNumber);
388
389   //
390   // Input values.
391   //
392
393   p_amb = Atmosphere->GetPressure() * psftopa;
394   double p = Auxiliary->GetTotalPressure() * psftopa;
395   p_ram = (p - p_amb) * Ram_Air_Factor + p_amb;
396   T_amb = RankineToKelvin(Atmosphere->GetTemperature());
397
398   RPM = Thruster->GetRPM() * Thruster->GetGearRatio();
399   MeanPistonSpeed_fps =  ( RPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
400
401   IAS = Auxiliary->GetVcalibratedKTS();
402
403   doEngineStartup();
404   if (Boosted) doBoostControl();
405   doMAP();
406   doAirFlow();
407   doFuelFlow();
408
409   //Now that the fuel flow is done check if the mixture is too lean to run the engine
410   //Assume lean limit at 22 AFR for now - thats a thi of 0.668
411   //This might be a bit generous, but since there's currently no audiable warning of impending
412   //cutout in the form of misfiring and/or rough running its probably reasonable for now.
413 //  if (equivalence_ratio < 0.668)
414 //    Running = false;
415
416   doEnginePower();
417   if (IndicatedHorsePower < 0.1250) Running = false;
418
419   doEGT();
420   doCHT();
421   doOilTemperature();
422   doOilPressure();
423
424   if (Thruster->GetType() == FGThruster::ttPropeller) {
425     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
426     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
427   }
428
429   PowerAvailable = (HP * hptoftlbssec) - Thruster->GetPowerRequired();
430
431   return Thruster->Calculate(PowerAvailable);
432 }
433
434 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
435
436 double FGPiston::CalcFuelNeed(void)
437 {
438   double dT = State->Getdt() * Propulsion->GetRate();
439   FuelExpended = FuelFlowRate * dT;
440   return FuelExpended;
441 }
442
443 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
444
445 int FGPiston::InitRunning(void) {
446   Magnetos=3;
447   //Thruster->SetRPM( 1.1*IdleRPM/Thruster->GetGearRatio() );
448   Thruster->SetRPM( 1000 );
449   Running=true;
450   return 1;
451 }
452
453 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
454 /**
455  * Start or stop the engine.
456  */
457
458 void FGPiston::doEngineStartup(void)
459 {
460   // Check parameters that may alter the operating state of the engine.
461   // (spark, fuel, starter motor etc)
462   bool spark;
463   bool fuel;
464
465   // Check for spark
466   Magneto_Left = false;
467   Magneto_Right = false;
468   // Magneto positions:
469   // 0 -> off
470   // 1 -> left only
471   // 2 -> right only
472   // 3 -> both
473   if (Magnetos != 0) {
474     spark = true;
475   } else {
476     spark = false;
477   }  // neglects battery voltage, master on switch, etc for now.
478
479   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
480   if (Magnetos > 1)  Magneto_Right = true;
481
482   // Assume we have fuel for now
483   fuel = !Starved;
484
485   // Check if we are turning the starter motor
486   if (Cranking != Starter) {
487     // This check saves .../cranking from getting updated every loop - they
488     // only update when changed.
489     Cranking = Starter;
490     crank_counter = 0;
491   }
492
493   if (Cranking) crank_counter++;  //Check mode of engine operation
494
495   if (!Running && spark && fuel) {  // start the engine if revs high enough
496     if (Cranking) {
497       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
498         Running = true;                         // on the starter
499     } else {
500       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
501         Running = true;                         // when windmilling
502     }
503   }
504
505   // Cut the engine *power* - Note: the engine may continue to
506   // spin if the prop is in a moving airstream
507
508   if ( Running && (!spark || !fuel) ) Running = false;
509
510   // Check for stalling (RPM = 0).
511   if (Running) {
512     if (RPM == 0) {
513       Running = false;
514     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
515       Running = false;
516     }
517   }
518 }
519
520 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
521
522 /**
523  * Calculate the Current Boost Speed
524  *
525  * This function calculates the current turbo/supercharger boost speed
526  * based on altitude and the (automatic) boost-speed control valve configuration.
527  *
528  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
529  *
530  * Outputs: BoostSpeed
531  */
532
533 void FGPiston::doBoostControl(void)
534 {
535   if(BoostManual) {
536     if(BoostSpeed > BoostSpeeds-1) BoostSpeed = BoostSpeeds-1;
537     if(BoostSpeed < 0) BoostSpeed = 0;
538   } else {
539     if(BoostSpeed < BoostSpeeds - 1) {
540       // Check if we need to change to a higher boost speed
541       if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
542         BoostSpeed++;
543       }
544     } else if(BoostSpeed > 0) {
545       // Check if we need to change to a lower boost speed
546       if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
547         BoostSpeed--;
548       }
549     }
550   }
551 }
552
553 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
554
555 /**
556  * Calculate the manifold absolute pressure (MAP) in inches hg
557  *
558  * This function calculates manifold absolute pressure (MAP)
559  * from the throttle position, turbo/supercharger boost control
560  * system, engine speed and local ambient air density.
561  *
562  * Inputs: p_amb, Throttle, ThrottleAngle,
563  *         MeanPistonSpeed_fps, dt
564  *
565  * Outputs: MAP, ManifoldPressure_inHg, TMAP
566  */
567
568 void FGPiston::doMAP(void)
569 {
570   double Zt =(1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence
571   double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence
572
573   double map_coefficient = Ze/(Ze+Z_airbox+Zt);
574
575   // Add a one second lag to manifold pressure changes
576   double dMAP = (TMAP - p_ram * map_coefficient) * dt;
577   TMAP -=dMAP;
578
579   // Find the mean effective pressure required to achieve this manifold pressure
580   // Fixme: determine the HP consumed by the supercharger
581
582   PMEP = TMAP - p_amb; // Fixme: p_amb should be exhaust manifold pressure
583
584   if (Boosted) {
585     // If takeoff boost is fitted, we currently assume the following throttle map:
586     // (In throttle % - actual input is 0 -> 1)
587     // 99 / 100 - Takeoff boost
588     // In real life, most planes would be fitted with a mechanical 'gate' between
589     // the rated boost and takeoff boost positions.
590
591     bool bTakeoffPos = false;
592     if (bTakeoffBoost) {
593       if (Throttle > 0.98) {
594         bTakeoffPos = true;
595       }
596     }
597     // Boost the manifold pressure.
598     double boost_factor = (( BoostMul[BoostSpeed] - 1 ) / RatedRPM[BoostSpeed] ) * RPM + 1;
599     MAP = TMAP * boost_factor;
600     // Now clip the manifold pressure to BCV or Wastegate setting.
601     if (bTakeoffPos) {
602       if (MAP > TakeoffMAP[BoostSpeed]) MAP = TakeoffMAP[BoostSpeed];
603     } else {
604       if (MAP > RatedMAP[BoostSpeed]) MAP = RatedMAP[BoostSpeed];
605     }
606   } else {
607       MAP = TMAP;
608   }
609
610   // And set the value in American units as well
611   ManifoldPressure_inHg = MAP / inhgtopa;
612 }
613
614 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
615 /**
616  * Calculate the air flow through the engine.
617  * Also calculates ambient air density
618  * (used in CHT calculation for air-cooled engines).
619  *
620  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
621  *   RPM, volumetric_efficiency, ThrottleAngle
622  *
623  * TODO: Model inlet manifold air temperature.
624  *
625  * Outputs: rho_air, m_dot_air
626  */
627
628 void FGPiston::doAirFlow(void)
629 {
630   double gamma = 1.1; // specific heat constants
631 // loss of volumentric efficiency due to difference between MAP and exhaust pressure
632   double ve =((gamma-1)/gamma)+( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1));
633
634   rho_air = p_amb / (R_air * T_amb);
635   double swept_volume = (displacement_SI * (RPM/60)) / 2;
636   double v_dot_air = swept_volume * volumetric_efficiency *ve;
637
638   double rho_air_manifold = MAP / (R_air * T_amb);
639   m_dot_air = v_dot_air * rho_air_manifold;
640
641 }
642
643 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
644 /**
645  * Calculate the fuel flow into the engine.
646  *
647  * Inputs: Mixture, thi_sea_level, p_amb, m_dot_air
648  *
649  * Outputs: equivalence_ratio, m_dot_fuel
650  */
651
652 void FGPiston::doFuelFlow(void)
653 {
654   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
655   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
656 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
657 //  m_dot_fuel = m_dot_air / AFR;
658   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
659   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
660   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
661   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
662 }
663
664 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
665 /**
666  * Calculate the power produced by the engine.
667  *
668  * Currently, the JSBSim propellor model does not allow the
669  * engine to produce enough RPMs to get up to a high horsepower.
670  * When tested with sufficient RPM, it has no trouble reaching
671  * 200HP.
672  *
673  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb,
674  *   Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP,
675  *
676  * Outputs: PctPower, HP
677  */
678
679 void FGPiston::doEnginePower(void)
680 {
681   IndicatedHorsePower = 0;
682   FMEP = 0;
683   if (Running) {
684     // FIXME: this needs to be generalized
685     double ME, percent_RPM, power;  // Convienience term for use in the calculations
686     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
687
688     percent_RPM = RPM/MaxRPM;
689 // Guestimate engine friction as a percentage of rated HP + a percentage of rpm + a percentage of Indicted HP
690 //    friction = 1 - (percent_RPM * percent_RPM * percent_RPM/10);
691     FMEP = (-18400 * MeanPistonSpeed_fps * fttom - 46500);
692
693     power = 1;
694
695     if ( Magnetos != 3 ) power *= SparkFailDrop;
696
697
698     IndicatedHorsePower = (FuelFlow_pph / ISFC )* ME * power;
699
700   } else {
701     // Power output when the engine is not running
702     if (Cranking) {
703       if (RPM < 10) {
704         IndicatedHorsePower = StarterHP;
705       } else if (RPM < IdleRPM*0.8) {
706         IndicatedHorsePower = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
707         // This is a guess - would be nice to find a proper starter moter torque curve
708       } else {
709         IndicatedHorsePower = StarterHP;
710       }
711     }
712   }
713
714   // Constant is (1/2) * 60 * 745.7
715   // (1/2) convert cycles, 60 minutes to seconds, 745.7 watts to hp.
716   double pumping_hp = ((PMEP + FMEP) * displacement_SI * RPM)/(Cycles*22371);
717
718   HP = IndicatedHorsePower + pumping_hp - 1.5; //FIXME 1.5 static friction should depend on oil temp and configuration
719 //  cout << "pumping_hp " <<pumping_hp << FMEP << PMEP <<endl;
720   PctPower = HP / MaxHP ;
721 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
722 }
723
724 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
725 /**
726  * Calculate the exhaust gas temperature.
727  *
728  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
729  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, PctPower
730  *
731  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
732  */
733
734 void FGPiston::doEGT(void)
735 {
736   double delta_T_exhaust;
737   double enthalpy_exhaust;
738   double heat_capacity_exhaust;
739   double dEGTdt;
740
741   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
742     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
743     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
744                               combustion_efficiency * 0.33;
745     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
746     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
747     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
748     ExhaustGasTemp_degK *= 0.444 + ((0.544 - 0.444) * PctPower);
749   } else {  // Drop towards ambient - guess an appropriate time constant for now
750     combustion_efficiency = 0;
751     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
752     delta_T_exhaust = dEGTdt * dt;
753     ExhaustGasTemp_degK += delta_T_exhaust;
754   }
755 }
756
757 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
758 /**
759  * Calculate the cylinder head temperature.
760  *
761  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
762  *   combustion_efficiency, RPM, MaxRPM, Displacement
763  *
764  * Outputs: CylinderHeadTemp_degK
765  */
766
767 void FGPiston::doCHT(void)
768 {
769   double h1 = -95.0;
770   double h2 = -3.95;
771   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
772
773   double arbitary_area = 1.0;
774   double CpCylinderHead = 800.0;
775   double MassCylinderHead = 8.0;
776
777   double temperature_difference = CylinderHeadTemp_degK - T_amb;
778   double v_apparent = IAS * 0.5144444;
779   double v_dot_cooling_air = arbitary_area * v_apparent;
780   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
781   double dqdt_from_combustion =
782     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
783   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
784     (h3 * RPM * temperature_difference / MaxRPM);
785   double dqdt_free = h1 * temperature_difference;
786   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
787
788   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
789
790   CylinderHeadTemp_degK +=
791     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
792 }
793
794 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
795 /**
796  * Calculate the oil temperature.
797  *
798  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
799  *
800  * Outputs: OilTemp_degK
801  */
802
803 void FGPiston::doOilTemperature(void)
804 {
805   double target_oil_temp;        // Steady state oil temp at the current engine conditions
806   double time_constant;          // The time constant for the differential equation
807   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
808
809 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
810 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
811   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
812
813   if (OilPressure_psi > 5.0 ) {
814     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
815                                             // The higher the pressure the faster it reaches
816                                             // target temperature.  Oil pressure should be about
817                                             // 60 PSI yielding a TC of about 80.
818   } else {
819     time_constant = 1000;  // Time constant for engine-off; reflects the fact
820                            // that oil is no longer getting circulated
821   }
822
823   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
824
825   OilTemp_degK += (dOilTempdt * dt);
826 }
827
828 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
829 /**
830  * Calculate the oil pressure.
831  *
832  * Inputs: RPM, MaxRPM, OilTemp_degK
833  *
834  * Outputs: OilPressure_psi
835  */
836
837 void FGPiston::doOilPressure(void)
838 {
839   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
840   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
841   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
842   double Oil_Viscosity_Index = 0.25;
843
844   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
845
846   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
847     OilPressure_psi = Oil_Press_Relief_Valve;
848   }
849
850   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
851 }
852
853 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
854
855 string FGPiston::GetEngineLabels(const string& delimiter)
856 {
857   std::ostringstream buf;
858
859   buf << Name << " Power Available (engine " << EngineNumber << " in HP)" << delimiter
860       << Name << " HP (engine " << EngineNumber << ")" << delimiter
861       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimiter
862       << Name << " MAP (engine " << EngineNumber << " in inHg)" << delimiter
863       << Thruster->GetThrusterLabels(EngineNumber, delimiter);
864
865   return buf.str();
866 }
867
868 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
869
870 string FGPiston::GetEngineValues(const string& delimiter)
871 {
872   std::ostringstream buf;
873
874   buf << PowerAvailable << delimiter << HP << delimiter
875       << equivalence_ratio << delimiter << ManifoldPressure_inHg << delimiter
876       << Thruster->GetThrusterValues(EngineNumber, delimiter);
877
878   return buf.str();
879 }
880
881 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
882 //
883 //    The bitmasked value choices are as follows:
884 //    unset: In this case (the default) JSBSim would only print
885 //       out the normally expected messages, essentially echoing
886 //       the config files as they are read. If the environment
887 //       variable is not set, debug_lvl is set to 1 internally
888 //    0: This requests JSBSim not to output any messages
889 //       whatsoever.
890 //    1: This value explicity requests the normal JSBSim
891 //       startup messages
892 //    2: This value asks for a message to be printed out when
893 //       a class is instantiated
894 //    4: When this value is set, a message is displayed when a
895 //       FGModel object executes its Run() method
896 //    8: When this value is set, various runtime state variables
897 //       are printed out periodically
898 //    16: When set various parameters are sanity checked and
899 //       a message is printed out when they go out of bounds
900
901 void FGPiston::Debug(int from)
902 {
903   if (debug_lvl <= 0) return;
904
905   if (debug_lvl & 1) { // Standard console startup message output
906     if (from == 0) { // Constructor
907
908       cout << "\n    Engine Name: "         << Name << endl;
909       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
910       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
911       cout << "      MinMaP (Pa):         " << minMAP << endl;
912       cout << "      MaxMaP (Pa):         " << maxMAP << endl;
913       cout << "      Displacement: "        << Displacement             << endl;
914       cout << "      Bore: "                << Bore                     << endl;
915       cout << "      Stroke: "              << Stroke                   << endl;
916       cout << "      Cylinders: "           << Cylinders                << endl;
917       cout << "      Compression Ratio: "   << CompressionRatio         << endl;
918       cout << "      MaxHP: "               << MaxHP                    << endl;
919       cout << "      Cycles: "              << Cycles                   << endl;
920       cout << "      IdleRPM: "             << IdleRPM                  << endl;
921       cout << "      MaxRPM: "              << MaxRPM                   << endl;
922       cout << "      MaxThrottle: "         << MaxThrottle              << endl;
923       cout << "      MinThrottle: "         << MinThrottle              << endl;
924       cout << "      ISFC: "                << ISFC                     << endl;
925       cout << "      Volumetric Efficiency: " << volumetric_efficiency    << endl;
926       cout << "      PeakMeanPistonSpeed_fps: " << PeakMeanPistonSpeed_fps << endl;
927       cout << "      Intake Impedance Factor: " << Z_airbox << endl;
928
929       cout << endl;
930       cout << "      Combustion Efficiency table:" << endl;
931       Lookup_Combustion_Efficiency->Print();
932       cout << endl;
933
934       cout << endl;
935       cout << "      Mixture Efficiency Correlation table:" << endl;
936       Mixture_Efficiency_Correlation->Print();
937       cout << endl;
938
939     }
940   }
941   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
942     if (from == 0) cout << "Instantiated: FGPiston" << endl;
943     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
944   }
945   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
946   }
947   if (debug_lvl & 8 ) { // Runtime state variables
948   }
949   if (debug_lvl & 16) { // Sanity checking
950   }
951   if (debug_lvl & 64) {
952     if (from == 0) { // Constructor
953       cout << IdSrc << endl;
954       cout << IdHdr << endl;
955     }
956   }
957 }
958 } // namespace JSBSim