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