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