]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Sync. w. JSBSim cvs
[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.1;
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
243   // Create IFSC and VE to match the engine if not provided
244   int calculated_ve=0;
245   if (volumetric_efficiency < 0) {
246       volumetric_efficiency = MaxManifoldPressure_inHg / 29.92;
247       calculated_ve=1;
248   }
249   if (ISFC < 0) {
250       double pmep = MaxManifoldPressure_inHg > 29.92 ? 0 : 29.92 - MaxManifoldPressure_inHg;
251       pmep *= inhgtopa;
252       double fmep = (18400 * (2*(Stroke/12)*(MaxRPM/60)) * fttom + 46500)/2;
253       double hp_loss = ((pmep + fmep) * displacement_SI * MaxRPM)/(Cycles*22371);
254       ISFC = ( Displacement * MaxRPM * volumetric_efficiency ) / (9411 * (MaxHP+hp_loss));
255 // cout <<"FMEP: "<< fmep <<" PMEP: "<< pmep << " hp_loss: " <<hp_loss <<endl;
256   }
257   if ( MaxManifoldPressure_inHg > 29.9 ) {   // Don't allow boosting with a bogus number
258       MaxManifoldPressure_inHg = 29.9;
259       if (calculated_ve) volumetric_efficiency = 1.0;
260   }
261   minMAP = MinManifoldPressure_inHg * inhgtopa;  // inHg to Pa
262   maxMAP = MaxManifoldPressure_inHg * inhgtopa;
263
264 // For throttle
265   RatedMeanPistonSpeed_fps =  ( MaxRPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
266   if(Z_airbox < 998){
267     double Ze=RatedMeanPistonSpeed_fps/PeakMeanPistonSpeed_fps; // engine impedence
268     Z_airbox = (standard_pressure *Ze / maxMAP) - Ze; // impedence of airbox
269   }
270   Z_throttle=(((MaxRPM * Stroke) / 360)/((IdleRPM * Stroke) / 360))*(standard_pressure/minMAP - 1) - Z_airbox; // Constant for Throttle impedence
271
272   string property_name, base_property_name;
273   base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
274   property_name = base_property_name + "/power-hp";
275   PropertyManager->Tie(property_name, &HP);
276   property_name = base_property_name + "/bsfc-lbs_hphr";
277   PropertyManager->Tie(property_name, &ISFC);
278   property_name = base_property_name + "/volumetric-efficiency";
279   PropertyManager->Tie(property_name, &volumetric_efficiency);
280   property_name = base_property_name + "/map-pa";
281   PropertyManager->Tie(property_name, &MAP);
282   property_name = base_property_name + "/map-inhg";
283   PropertyManager->Tie(property_name, &ManifoldPressure_inHg);
284   property_name = base_property_name + "/air-intake-impedance-factor";
285   PropertyManager->Tie(property_name, &Z_airbox);
286   property_name = base_property_name + "/ram-air-factor";
287   PropertyManager->Tie(property_name, &Ram_Air_Factor);
288   property_name = base_property_name + "/boost-speed";
289   PropertyManager->Tie(property_name, &BoostSpeed);
290
291   // Set up and sanity-check the turbo/supercharging configuration based on the input values.
292   if (TakeoffBoost > RatedBoost[0]) bTakeoffBoost = true;
293   for (i=0; i<BoostSpeeds; ++i) {
294     bool bad = false;
295     if (RatedBoost[i] <= 0.0) bad = true;
296     if (RatedPower[i] <= 0.0) bad = true;
297     if (RatedAltitude[i] < 0.0) bad = true;  // 0.0 is deliberately allowed - this corresponds to unregulated supercharging.
298     if (i > 0 && RatedAltitude[i] < RatedAltitude[i - 1]) bad = true;
299     if (bad) {
300       // We can't recover from the above - don't use this supercharger speed.
301       BoostSpeeds--;
302       // TODO - put out a massive error message!
303       break;
304     }
305     // Now sanity-check stuff that is recoverable.
306     if (i < BoostSpeeds - 1) {
307       if (BoostSwitchAltitude[i] < RatedAltitude[i]) {
308         // TODO - put out an error message
309         // But we can also make a reasonable estimate, as below.
310         BoostSwitchAltitude[i] = RatedAltitude[i] + 1000;
311       }
312       BoostSwitchPressure[i] = Atmosphere->GetPressure(BoostSwitchAltitude[i]) * psftopa;
313       //cout << "BoostSwitchAlt = " << BoostSwitchAltitude[i] << ", pressure = " << BoostSwitchPressure[i] << '\n';
314       // Assume there is some hysteresis on the supercharger gear switch, and guess the value for now
315       BoostSwitchHysteresis = 1000;
316     }
317     // Now work out the supercharger pressure multiplier of this speed from the rated boost and altitude.
318     RatedMAP[i] = Atmosphere->GetPressureSL() * psftopa + RatedBoost[i] * 6895;  // psi*6895 = Pa.
319     // Sometimes a separate BCV setting for takeoff or extra power is fitted.
320     if (TakeoffBoost > RatedBoost[0]) {
321       // Assume that the effect on the BCV is the same whichever speed is in use.
322       TakeoffMAP[i] = RatedMAP[i] + ((TakeoffBoost - RatedBoost[0]) * 6895);
323       bTakeoffBoost = true;
324     } else {
325       TakeoffMAP[i] = RatedMAP[i];
326       bTakeoffBoost = false;
327     }
328     BoostMul[i] = RatedMAP[i] / (Atmosphere->GetPressure(RatedAltitude[i]) * psftopa);
329
330   }
331
332   if (BoostSpeeds > 0) {
333     Boosted = true;
334     BoostSpeed = 0;
335   }
336   bBoostOverride = (BoostOverride == 1 ? true : false);
337   bBoostManual   = (BoostManual   == 1 ? true : false);
338   Debug(0); // Call Debug() routine from constructor if needed
339 }
340
341 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
342
343 FGPiston::~FGPiston()
344 {
345   delete Lookup_Combustion_Efficiency;
346   delete Mixture_Efficiency_Correlation;
347   Debug(1); // Call Debug() routine from constructor if needed
348 }
349
350 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
351
352 void FGPiston::ResetToIC(void)
353 {
354   FGEngine::ResetToIC();
355
356   ManifoldPressure_inHg = Atmosphere->GetPressure() * psftoinhg; // psf to in Hg
357   MAP = Atmosphere->GetPressure() * psftopa;
358   TMAP = MAP;
359   double airTemperature_degK = RankineToKelvin(Atmosphere->GetTemperature());
360   OilTemp_degK = airTemperature_degK;
361   CylinderHeadTemp_degK = airTemperature_degK;
362   ExhaustGasTemp_degK = airTemperature_degK;
363   EGT_degC = ExhaustGasTemp_degK - 273;
364   Thruster->SetRPM(0.0);
365   RPM = 0.0;
366   OilPressure_psi = 0.0;
367 }
368
369 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
370
371 double FGPiston::Calculate(void)
372 {
373   if (FuelFlow_gph > 0.0) ConsumeFuel();
374
375   Throttle = FCS->GetThrottlePos(EngineNumber);
376   // calculate the throttle plate angle.  1 unit is approx pi/2 radians.
377   ThrottleAngle = MinThrottle+((MaxThrottle-MinThrottle)*Throttle );
378   Mixture = FCS->GetMixturePos(EngineNumber);
379
380   //
381   // Input values.
382   //
383
384   p_amb = Atmosphere->GetPressure() * psftopa;
385   double p = Auxiliary->GetTotalPressure() * psftopa;
386   p_ram = (p - p_amb) * Ram_Air_Factor + p_amb;
387   T_amb = RankineToKelvin(Atmosphere->GetTemperature());
388
389   RPM = Thruster->GetRPM() * Thruster->GetGearRatio();
390   MeanPistonSpeed_fps =  ( RPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
391
392   IAS = Auxiliary->GetVcalibratedKTS();
393
394   doEngineStartup();
395   if (Boosted) doBoostControl();
396   doMAP();
397   doAirFlow();
398   doFuelFlow();
399
400   //Now that the fuel flow is done check if the mixture is too lean to run the engine
401   //Assume lean limit at 22 AFR for now - thats a thi of 0.668
402   //This might be a bit generous, but since there's currently no audiable warning of impending
403   //cutout in the form of misfiring and/or rough running its probably reasonable for now.
404 //  if (equivalence_ratio < 0.668)
405 //    Running = false;
406
407   doEnginePower();
408   if (IndicatedHorsePower < 0.1250) Running = false;
409
410   doEGT();
411   doCHT();
412   doOilTemperature();
413   doOilPressure();
414
415   if (Thruster->GetType() == FGThruster::ttPropeller) {
416     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
417     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
418   }
419
420   PowerAvailable = (HP * hptoftlbssec) - Thruster->GetPowerRequired();
421
422   return Thruster->Calculate(PowerAvailable);
423 }
424
425 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
426
427 double FGPiston::CalcFuelNeed(void)
428 {
429   double dT = State->Getdt() * Propulsion->GetRate();
430   FuelExpended = FuelFlowRate * dT;
431   return FuelExpended;
432 }
433
434 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
435
436 int FGPiston::InitRunning(void) {
437   Magnetos=3;
438   //Thruster->SetRPM( 1.1*IdleRPM/Thruster->GetGearRatio() );
439   Thruster->SetRPM( 1000 );
440   Running=true;
441   return 1;
442 }
443
444 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
445 /**
446  * Start or stop the engine.
447  */
448
449 void FGPiston::doEngineStartup(void)
450 {
451   // Check parameters that may alter the operating state of the engine.
452   // (spark, fuel, starter motor etc)
453   bool spark;
454   bool fuel;
455
456   // Check for spark
457   Magneto_Left = false;
458   Magneto_Right = false;
459   // Magneto positions:
460   // 0 -> off
461   // 1 -> left only
462   // 2 -> right only
463   // 3 -> both
464   if (Magnetos != 0) {
465     spark = true;
466   } else {
467     spark = false;
468   }  // neglects battery voltage, master on switch, etc for now.
469
470   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
471   if (Magnetos > 1)  Magneto_Right = true;
472
473   // Assume we have fuel for now
474   fuel = !Starved;
475
476   // Check if we are turning the starter motor
477   if (Cranking != Starter) {
478     // This check saves .../cranking from getting updated every loop - they
479     // only update when changed.
480     Cranking = Starter;
481     crank_counter = 0;
482   }
483
484   if (Cranking) crank_counter++;  //Check mode of engine operation
485
486   if (!Running && spark && fuel) {  // start the engine if revs high enough
487     if (Cranking) {
488       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
489         Running = true;                         // on the starter
490     } else {
491       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
492         Running = true;                         // when windmilling
493     }
494   }
495
496   // Cut the engine *power* - Note: the engine may continue to
497   // spin if the prop is in a moving airstream
498
499   if ( Running && (!spark || !fuel) ) Running = false;
500
501   // Check for stalling (RPM = 0).
502   if (Running) {
503     if (RPM == 0) {
504       Running = false;
505     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
506       Running = false;
507     }
508   }
509 }
510
511 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
512
513 /**
514  * Calculate the Current Boost Speed
515  *
516  * This function calculates the current turbo/supercharger boost speed
517  * based on altitude and the (automatic) boost-speed control valve configuration.
518  *
519  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
520  *
521  * Outputs: BoostSpeed
522  */
523
524 void FGPiston::doBoostControl(void)
525 {
526   if(BoostManual) {
527     if(BoostSpeed > BoostSpeeds-1) BoostSpeed = BoostSpeeds-1;
528     if(BoostSpeed < 0) BoostSpeed = 0;
529   } else {
530     if(BoostSpeed < BoostSpeeds - 1) {
531       // Check if we need to change to a higher boost speed
532       if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
533         BoostSpeed++;
534       }
535     } else if(BoostSpeed > 0) {
536       // Check if we need to change to a lower boost speed
537       if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
538         BoostSpeed--;
539       }
540     }
541   }
542 }
543
544 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
545
546 /**
547  * Calculate the manifold absolute pressure (MAP) in inches hg
548  *
549  * This function calculates manifold absolute pressure (MAP)
550  * from the throttle position, turbo/supercharger boost control
551  * system, engine speed and local ambient air density.
552  *
553  * Inputs: p_amb, Throttle, ThrottleAngle,
554  *         MeanPistonSpeed_fps, dt
555  *
556  * Outputs: MAP, ManifoldPressure_inHg, TMAP
557  */
558
559 void FGPiston::doMAP(void)
560 {
561   double Zt =(1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence
562   double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence
563
564   double map_coefficient = Ze/(Ze+Z_airbox+Zt);
565
566   // Add a one second lag to manifold pressure changes
567   double dMAP = (TMAP - p_ram * map_coefficient) * dt;
568   TMAP -=dMAP;
569
570   // Find the mean effective pressure required to achieve this manifold pressure
571   // Fixme: determine the HP consumed by the supercharger
572
573   PMEP = TMAP - p_amb; // Fixme: p_amb should be exhaust manifold pressure
574
575   if (Boosted) {
576     // If takeoff boost is fitted, we currently assume the following throttle map:
577     // (In throttle % - actual input is 0 -> 1)
578     // 99 / 100 - Takeoff boost
579     // In real life, most planes would be fitted with a mechanical 'gate' between
580     // the rated boost and takeoff boost positions.
581
582     bool bTakeoffPos = false;
583     if (bTakeoffBoost) {
584       if (Throttle > 0.98) {
585         bTakeoffPos = true;
586       }
587     }
588     // Boost the manifold pressure.
589     double boost_factor = (( BoostMul[BoostSpeed] - 1 ) / RatedRPM[BoostSpeed] ) * RPM + 1;
590     MAP = TMAP * boost_factor;
591     // Now clip the manifold pressure to BCV or Wastegate setting.
592     if (bTakeoffPos) {
593       if (MAP > TakeoffMAP[BoostSpeed]) MAP = TakeoffMAP[BoostSpeed];
594     } else {
595       if (MAP > RatedMAP[BoostSpeed]) MAP = RatedMAP[BoostSpeed];
596     }
597   } else {
598       MAP = TMAP;
599   }
600
601   // And set the value in American units as well
602   ManifoldPressure_inHg = MAP / inhgtopa;
603 }
604
605 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
606 /**
607  * Calculate the air flow through the engine.
608  * Also calculates ambient air density
609  * (used in CHT calculation for air-cooled engines).
610  *
611  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
612  *   RPM, volumetric_efficiency, ThrottleAngle
613  *
614  * TODO: Model inlet manifold air temperature.
615  *
616  * Outputs: rho_air, m_dot_air
617  */
618
619 void FGPiston::doAirFlow(void)
620 {
621   double gamma = 1.1; // specific heat constants
622 // loss of volumentric efficiency due to difference between MAP and exhaust pressure
623   double ve =((gamma-1)/gamma)+( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1));
624
625   rho_air = p_amb / (R_air * T_amb);
626   double swept_volume = (displacement_SI * (RPM/60)) / 2;
627   double v_dot_air = swept_volume * volumetric_efficiency *ve;
628
629   double rho_air_manifold = MAP / (R_air * T_amb);
630   m_dot_air = v_dot_air * rho_air_manifold;
631
632 }
633
634 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
635 /**
636  * Calculate the fuel flow into the engine.
637  *
638  * Inputs: Mixture, thi_sea_level, p_amb, m_dot_air
639  *
640  * Outputs: equivalence_ratio, m_dot_fuel
641  */
642
643 void FGPiston::doFuelFlow(void)
644 {
645   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
646   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
647 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
648 //  m_dot_fuel = m_dot_air / AFR;
649   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
650   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
651   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
652   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
653 }
654
655 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656 /**
657  * Calculate the power produced by the engine.
658  *
659  * Currently, the JSBSim propellor model does not allow the
660  * engine to produce enough RPMs to get up to a high horsepower.
661  * When tested with sufficient RPM, it has no trouble reaching
662  * 200HP.
663  *
664  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb,
665  *   Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP,
666  *
667  * Outputs: PctPower, HP
668  */
669
670 void FGPiston::doEnginePower(void)
671 {
672   IndicatedHorsePower = 0;
673   FMEP = 0;
674   if (Running) {
675     // FIXME: this needs to be generalized
676     double ME, percent_RPM, power;  // Convienience term for use in the calculations
677     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
678
679     percent_RPM = RPM/MaxRPM;
680 // Guestimate engine friction as a percentage of rated HP + a percentage of rpm + a percentage of Indicted HP
681 //    friction = 1 - (percent_RPM * percent_RPM * percent_RPM/10);
682     FMEP = (-18400 * MeanPistonSpeed_fps * fttom - 46500);
683
684     power = 1;
685
686     if ( Magnetos != 3 ) power *= SparkFailDrop;
687
688
689     IndicatedHorsePower = (FuelFlow_pph / ISFC )* ME * power;
690
691   } else {
692     // Power output when the engine is not running
693     if (Cranking) {
694       if (RPM < 10) {
695         IndicatedHorsePower = StarterHP;
696       } else if (RPM < IdleRPM*0.8) {
697         IndicatedHorsePower = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
698         // This is a guess - would be nice to find a proper starter moter torque curve
699       } else {
700         IndicatedHorsePower = StarterHP;
701       }
702     }
703   }
704
705   // Constant is (1/2) * 60 * 745.7
706   // (1/2) convert cycles, 60 minutes to seconds, 745.7 watts to hp.
707   double pumping_hp = ((PMEP + FMEP) * displacement_SI * RPM)/(Cycles*22371);
708
709   HP = IndicatedHorsePower + pumping_hp - 1.5; //FIXME 1.5 static friction should depend on oil temp and configuration
710 //  cout << "pumping_hp " <<pumping_hp << FMEP << PMEP <<endl;
711   PctPower = HP / MaxHP ;
712 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
713 }
714
715 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
716 /**
717  * Calculate the exhaust gas temperature.
718  *
719  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
720  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, PctPower
721  *
722  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
723  */
724
725 void FGPiston::doEGT(void)
726 {
727   double delta_T_exhaust;
728   double enthalpy_exhaust;
729   double heat_capacity_exhaust;
730   double dEGTdt;
731
732   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
733     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
734     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
735                               combustion_efficiency * 0.33;
736     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
737     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
738     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
739     ExhaustGasTemp_degK *= 0.444 + ((0.544 - 0.444) * PctPower);
740   } else {  // Drop towards ambient - guess an appropriate time constant for now
741     combustion_efficiency = 0;
742     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
743     delta_T_exhaust = dEGTdt * dt;
744     ExhaustGasTemp_degK += delta_T_exhaust;
745   }
746 }
747
748 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
749 /**
750  * Calculate the cylinder head temperature.
751  *
752  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
753  *   combustion_efficiency, RPM, MaxRPM, Displacement
754  *
755  * Outputs: CylinderHeadTemp_degK
756  */
757
758 void FGPiston::doCHT(void)
759 {
760   double h1 = -95.0;
761   double h2 = -3.95;
762   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
763
764   double arbitary_area = 1.0;
765   double CpCylinderHead = 800.0;
766   double MassCylinderHead = 8.0;
767
768   double temperature_difference = CylinderHeadTemp_degK - T_amb;
769   double v_apparent = IAS * 0.5144444;
770   double v_dot_cooling_air = arbitary_area * v_apparent;
771   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
772   double dqdt_from_combustion =
773     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
774   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
775     (h3 * RPM * temperature_difference / MaxRPM);
776   double dqdt_free = h1 * temperature_difference;
777   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
778
779   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
780
781   CylinderHeadTemp_degK +=
782     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
783 }
784
785 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
786 /**
787  * Calculate the oil temperature.
788  *
789  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
790  *
791  * Outputs: OilTemp_degK
792  */
793
794 void FGPiston::doOilTemperature(void)
795 {
796   double target_oil_temp;        // Steady state oil temp at the current engine conditions
797   double time_constant;          // The time constant for the differential equation
798   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
799
800 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
801 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
802   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
803
804   if (OilPressure_psi > 5.0 ) {
805     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
806                                             // The higher the pressure the faster it reaches
807                                             // target temperature.  Oil pressure should be about
808                                             // 60 PSI yielding a TC of about 80.
809   } else {
810     time_constant = 1000;  // Time constant for engine-off; reflects the fact
811                            // that oil is no longer getting circulated
812   }
813
814   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
815
816   OilTemp_degK += (dOilTempdt * dt);
817 }
818
819 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
820 /**
821  * Calculate the oil pressure.
822  *
823  * Inputs: RPM, MaxRPM, OilTemp_degK
824  *
825  * Outputs: OilPressure_psi
826  */
827
828 void FGPiston::doOilPressure(void)
829 {
830   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
831   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
832   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
833   double Oil_Viscosity_Index = 0.25;
834
835   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
836
837   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
838     OilPressure_psi = Oil_Press_Relief_Valve;
839   }
840
841   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
842 }
843
844 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
845
846 string FGPiston::GetEngineLabels(const string& delimiter)
847 {
848   std::ostringstream buf;
849
850   buf << Name << " Power Available (engine " << EngineNumber << " in HP)" << delimiter
851       << Name << " HP (engine " << EngineNumber << ")" << delimiter
852       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimiter
853       << Name << " MAP (engine " << EngineNumber << " in inHg)" << delimiter
854       << Thruster->GetThrusterLabels(EngineNumber, delimiter);
855
856   return buf.str();
857 }
858
859 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
860
861 string FGPiston::GetEngineValues(const string& delimiter)
862 {
863   std::ostringstream buf;
864
865   buf << PowerAvailable << delimiter << HP << delimiter
866       << equivalence_ratio << delimiter << ManifoldPressure_inHg << delimiter
867       << Thruster->GetThrusterValues(EngineNumber, delimiter);
868
869   return buf.str();
870 }
871
872 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
873 //
874 //    The bitmasked value choices are as follows:
875 //    unset: In this case (the default) JSBSim would only print
876 //       out the normally expected messages, essentially echoing
877 //       the config files as they are read. If the environment
878 //       variable is not set, debug_lvl is set to 1 internally
879 //    0: This requests JSBSim not to output any messages
880 //       whatsoever.
881 //    1: This value explicity requests the normal JSBSim
882 //       startup messages
883 //    2: This value asks for a message to be printed out when
884 //       a class is instantiated
885 //    4: When this value is set, a message is displayed when a
886 //       FGModel object executes its Run() method
887 //    8: When this value is set, various runtime state variables
888 //       are printed out periodically
889 //    16: When set various parameters are sanity checked and
890 //       a message is printed out when they go out of bounds
891
892 void FGPiston::Debug(int from)
893 {
894   if (debug_lvl <= 0) return;
895
896   if (debug_lvl & 1) { // Standard console startup message output
897     if (from == 0) { // Constructor
898
899       cout << "\n    Engine Name: "         << Name << endl;
900       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
901       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
902       cout << "      MinMaP (Pa):         " << minMAP << endl;
903       cout << "      MaxMaP (Pa):         " << maxMAP << endl;
904       cout << "      Displacement: "        << Displacement             << endl;
905       cout << "      Bore: "                << Bore                     << endl;
906       cout << "      Stroke: "              << Stroke                   << endl;
907       cout << "      Cylinders: "           << Cylinders                << endl;
908       cout << "      Compression Ratio: "   << CompressionRatio         << endl;
909       cout << "      MaxHP: "               << MaxHP                    << endl;
910       cout << "      Cycles: "              << Cycles                   << endl;
911       cout << "      IdleRPM: "             << IdleRPM                  << endl;
912       cout << "      MaxRPM: "              << MaxRPM                   << endl;
913       cout << "      MaxThrottle: "         << MaxThrottle              << endl;
914       cout << "      MinThrottle: "         << MinThrottle              << endl;
915       cout << "      ISFC: "                << ISFC                     << endl;
916       cout << "      Volumentric Efficiency: " << volumetric_efficiency    << endl;
917
918       cout << endl;
919       cout << "      Combustion Efficiency table:" << endl;
920       Lookup_Combustion_Efficiency->Print();
921       cout << endl;
922
923       cout << endl;
924       cout << "      Mixture Efficiency Correlation table:" << endl;
925       Mixture_Efficiency_Correlation->Print();
926       cout << endl;
927
928     }
929   }
930   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
931     if (from == 0) cout << "Instantiated: FGPiston" << endl;
932     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
933   }
934   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
935   }
936   if (debug_lvl & 8 ) { // Runtime state variables
937   }
938   if (debug_lvl & 16) { // Sanity checking
939   }
940   if (debug_lvl & 64) {
941     if (from == 0) { // Constructor
942       cout << IdSrc << endl;
943       cout << IdHdr << endl;
944     }
945   }
946 }
947 } // namespace JSBSim