]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/FGFDM.cpp
simplify name/number handling
[flightgear.git] / src / FDM / YASim / FGFDM.cpp
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include <Main/fg_props.hxx>
5
6 #include "Math.hpp"
7 #include "Jet.hpp"
8 #include "SimpleJet.hpp"
9 #include "Gear.hpp"
10 #include "Hook.hpp"
11 #include "Launchbar.hpp"
12 #include "Atmosphere.hpp"
13 #include "PropEngine.hpp"
14 #include "Propeller.hpp"
15 #include "PistonEngine.hpp"
16 #include "TurbineEngine.hpp"
17 #include "Rotor.hpp"
18 #include "Rotorpart.hpp"
19
20 #include "FGFDM.hpp"
21
22 namespace yasim {
23
24 // Some conversion factors
25 static const float KTS2MPS = 0.514444444444;
26 static const float FT2M = 0.3048;
27 static const float DEG2RAD = 0.0174532925199;
28 static const float RPM2RAD = 0.10471975512;
29 static const float LBS2N = 4.44822;
30 static const float LBS2KG = 0.45359237;
31 static const float KG2LBS = 2.2046225;
32 static const float CM2GALS = 264.172037284;
33 static const float HP2W = 745.700;
34 static const float INHG2PA = 3386.389;
35 static const float K2DEGF = 1.8;
36 static const float K2DEGFOFFSET = -459.4;
37 static const float CIN2CM = 1.6387064e-5;
38 static const float YASIM_PI = 3.14159265358979323846;
39
40 static const float NM2FTLB = (1/(LBS2N*FT2M));
41
42 // Stubs, so that this can be compiled without the FlightGear
43 // binary.  What's the best way to handle this?
44
45 //     float fgGetFloat(char* name, float def) { return 0; }
46 //     void fgSetFloat(char* name, float val) {}
47
48 FGFDM::FGFDM()
49 {
50     _vehicle_radius = 0.0f;
51
52     _nextEngine = 0;
53
54     // Map /controls/flight/elevator to the approach elevator control.  This
55     // should probably be settable, but there are very few aircraft
56     // who trim their approaches using things other than elevator.
57     _airplane.setElevatorControl(parseAxis("/controls/flight/elevator-trim"));
58
59     // FIXME: read seed from somewhere?
60     int seed = 0;
61     _turb = new Turbulence(10, seed);
62 }
63
64 FGFDM::~FGFDM()
65 {
66     int i;
67     for(i=0; i<_axes.size(); i++) {
68         AxisRec* a = (AxisRec*)_axes.get(i);
69         delete[] a->name;
70         delete a;
71     }
72     for(i=0; i<_thrusters.size(); i++) {
73         EngRec* er = (EngRec*)_thrusters.get(i);
74         delete[] er->prefix;
75         delete er->eng;
76         delete er;
77     }
78     for(i=0; i<_weights.size(); i++) {
79         WeightRec* wr = (WeightRec*)_weights.get(i);
80         delete[] wr->prop;
81         delete wr;
82     }
83     for(i=0; i<_controlProps.size(); i++)
84         delete (PropOut*)_controlProps.get(i);
85     delete _turb;
86 }
87
88 void FGFDM::iterate(float dt)
89 {
90     getExternalInput(dt);
91     _airplane.iterate(dt);
92
93     // Do fuel stuff (FIXME: should stash SGPropertyNode objects here)
94     char buf[256];
95     for(int i=0; i<_airplane.numThrusters(); i++) {
96         Thruster* t = _airplane.getThruster(i);
97
98         sprintf(buf, "/engines/engine[%d]/out-of-fuel", i);
99         t->setFuelState(!fgGetBool(buf));
100
101         sprintf(buf, "/engines/engine[%d]/fuel-consumed-lbs", i);
102         double consumed = fgGetDouble(buf) + dt * KG2LBS * t->getFuelFlow();
103         fgSetDouble(buf, consumed);
104     }
105     for(int i=0; i<_airplane.numTanks(); i++) {
106         sprintf(buf, "/consumables/fuel/tank[%d]/level-lbs", i);
107         _airplane.setFuel(i, LBS2KG * fgGetFloat(buf));
108     } 
109     _airplane.calcFuelWeights();
110     
111     setOutputProperties(dt);
112 }
113
114 Airplane* FGFDM::getAirplane()
115 {
116     return &_airplane;
117 }
118
119 void FGFDM::init()
120 {
121     // Allows the user to start with something other than full fuel
122     _airplane.setFuelFraction(fgGetFloat("/sim/fuel-fraction", 1));
123
124     // Read out the resulting fuel state
125     char buf[256];
126     for(int i=0; i<_airplane.numTanks(); i++) {
127         sprintf(buf, "/consumables/fuel/tank[%d]/level-lbs", i);
128         fgSetDouble(buf, _airplane.getFuel(i) * KG2LBS);
129
130         double density = _airplane.getFuelDensity(i);
131         sprintf(buf, "/consumables/fuel/tank[%d]/density-ppg", i);
132         fgSetDouble(buf, density * (KG2LBS/CM2GALS));
133
134         sprintf(buf, "/consumables/fuel/tank[%d]/level-gal_us", i);
135         fgSetDouble(buf, _airplane.getFuel(i) * CM2GALS / density);
136
137         sprintf(buf, "/consumables/fuel/tank[%d]/capacity-gal_us", i);
138         fgSetDouble(buf, CM2GALS * _airplane.getTankCapacity(i)/density);
139     }    
140
141     // This has a nasty habit of being false at startup.  That's not
142     // good.
143     fgSetBool("/controls/gear/gear-down", true);
144
145     _airplane.getModel()->setTurbulence(_turb);
146 }
147
148 // Not the worlds safest parser.  But it's short & sweet.
149 void FGFDM::startElement(const char* name, const XMLAttributes &atts)
150 {
151     XMLAttributes* a = (XMLAttributes*)&atts;
152     float v[3];
153     char buf[64];
154
155     if(eq(name, "airplane")) {
156         _airplane.setWeight(attrf(a, "mass") * LBS2KG);
157     } else if(eq(name, "approach")) {
158         float spd = attrf(a, "speed") * KTS2MPS;
159         float alt = attrf(a, "alt", 0) * FT2M;
160         float aoa = attrf(a, "aoa", 0) * DEG2RAD;
161         _airplane.setApproach(spd, alt, aoa, attrf(a, "fuel", 0.2));
162         _cruiseCurr = false;
163     } else if(eq(name, "cruise")) {
164         float spd = attrf(a, "speed") * KTS2MPS;
165         float alt = attrf(a, "alt") * FT2M;
166         _airplane.setCruise(spd, alt, attrf(a, "fuel", 0.5));
167         _cruiseCurr = true;
168     } else if(eq(name, "solve-weight")) {
169         int idx = attri(a, "idx");
170         float wgt = attrf(a, "weight") * LBS2KG;
171         _airplane.addSolutionWeight(!_cruiseCurr, idx, wgt);
172     } else if(eq(name, "cockpit")) {
173         v[0] = attrf(a, "x");
174         v[1] = attrf(a, "y");
175         v[2] = attrf(a, "z");
176         _airplane.setPilotPos(v);
177     } else if(eq(name, "rotor")) {
178         _airplane.getModel()->getRotorgear()->addRotor(parseRotor(a, name));
179     } else if(eq(name, "rotorgear")) {
180         Rotorgear* r = _airplane.getModel()->getRotorgear();
181         _currObj = r;
182         #define p(x) if (a->hasAttribute(#x)) r->setParameter((char *)#x,attrf(a,#x) );
183         #define p2(x,y) if (a->hasAttribute(#x)) {r->setParameter((char *)#y,attrf(a,#x) ); SG_LOG(SG_INPUT, SG_ALERT,"Warning: Aircraft defnition files uses outdated tag '" <<#x<<"', use '"<<#y<<"' instead (see README.YASim)" <<endl);}
184         p(max_power_engine)
185         p(engine_prop_factor)
186         p(yasimdragfactor)
187         p(yasimliftfactor)
188         p(max_power_rotor_brake)
189         p(rotorgear_friction)
190         p(engine_accel_limit)
191         p2(engine_accell_limit,engine_accel_limit)
192         #undef p
193         #undef p2
194         r->setInUse();
195     } else if(eq(name, "wing")) {
196         _airplane.setWing(parseWing(a, name));
197     } else if(eq(name, "hstab")) {
198         _airplane.setTail(parseWing(a, name));
199     } else if(eq(name, "vstab") || eq(name, "mstab")) {
200         _airplane.addVStab(parseWing(a, name));
201     } else if(eq(name, "piston-engine")) {
202         parsePistonEngine(a);
203     } else if(eq(name, "turbine-engine")) {
204         parseTurbineEngine(a);
205     } else if(eq(name, "propeller")) {
206         parsePropeller(a);
207     } else if(eq(name, "thruster")) {
208         SimpleJet* j = new SimpleJet();
209         _currObj = j;
210         v[0] = attrf(a, "x"); v[1] = attrf(a, "y"); v[2] = attrf(a, "z");
211         j->setPosition(v);
212         _airplane.addThruster(j, 0, v);
213         v[0] = attrf(a, "vx"); v[1] = attrf(a, "vy"); v[2] = attrf(a, "vz");
214         j->setDirection(v);
215         j->setThrust(attrf(a, "thrust") * LBS2N);
216     } else if(eq(name, "jet")) {
217         Jet* j = new Jet();
218         _currObj = j;
219         v[0] = attrf(a, "x");
220         v[1] = attrf(a, "y");
221         v[2] = attrf(a, "z");
222         float mass = attrf(a, "mass") * LBS2KG;
223         j->setMaxThrust(attrf(a, "thrust") * LBS2N,
224                         attrf(a, "afterburner", 0) * LBS2N);
225         j->setVectorAngle(attrf(a, "rotate", 0) * DEG2RAD);
226         j->setReverseThrust(attrf(a, "reverse", 0.2));
227
228         float n1min = attrf(a, "n1-idle", 55);
229         float n1max = attrf(a, "n1-max", 102);
230         float n2min = attrf(a, "n2-idle", 73);
231         float n2max = attrf(a, "n2-max", 103);
232         j->setRPMs(n1min, n1max, n2min, n2max);
233
234         j->setTSFC(attrf(a, "tsfc", 0.8));
235         if(a->hasAttribute("egt"))  j->setEGT(attrf(a, "egt"));
236         if(a->hasAttribute("epr"))  j->setEPR(attrf(a, "epr"));
237         if(a->hasAttribute("exhaust-speed"))
238             j->setVMax(attrf(a, "exhaust-speed") * KTS2MPS);
239         if(a->hasAttribute("spool-time"))
240             j->setSpooling(attrf(a, "spool-time"));
241         
242         j->setPosition(v);
243         _airplane.addThruster(j, mass, v);
244         sprintf(buf, "/engines/engine[%d]", _nextEngine++);
245         EngRec* er = new EngRec();
246         er->eng = j;
247         er->prefix = dup(buf);
248         _thrusters.add(er);
249     } else if(eq(name, "gear")) {
250         Gear* g = new Gear();
251         _currObj = g;
252         v[0] = attrf(a, "x");
253         v[1] = attrf(a, "y");
254         v[2] = attrf(a, "z");
255         g->setPosition(v);
256         float nrm = Math::mag3(v);
257         if (_vehicle_radius < nrm)
258             _vehicle_radius = nrm;
259         if(a->hasAttribute("upx")) {
260             v[0] = attrf(a, "upx");
261             v[1] = attrf(a, "upy");
262             v[2] = attrf(a, "upz");
263             Math::unit3(v, v);
264         } else {
265             v[0] = 0;
266             v[1] = 0;
267             v[2] = 1;
268         }
269         for(int i=0; i<3; i++)
270             v[i] *= attrf(a, "compression", 1);
271         g->setCompression(v);
272         g->setBrake(attrf(a, "skid", 0));
273         g->setStaticFriction(attrf(a, "sfric", 0.8));
274         g->setDynamicFriction(attrf(a, "dfric", 0.7));
275         g->setSpring(attrf(a, "spring", 1));
276         g->setDamping(attrf(a, "damp", 1));
277         _airplane.addGear(g);
278     } else if(eq(name, "hook")) {
279         Hook* h = new Hook();
280         _currObj = h;
281         v[0] = attrf(a, "x");
282         v[1] = attrf(a, "y");
283         v[2] = attrf(a, "z");
284         h->setPosition(v);
285         float length = attrf(a, "length", 1.0);
286         h->setLength(length);
287         float nrm = length+Math::mag3(v);
288         if (_vehicle_radius < nrm)
289             _vehicle_radius = nrm;
290         h->setDownAngle(attrf(a, "down-angle", 70) * DEG2RAD);
291         h->setUpAngle(attrf(a, "up-angle", 0) * DEG2RAD);
292         _airplane.addHook(h);
293     } else if(eq(name, "launchbar")) {
294         Launchbar* l = new Launchbar();
295         _currObj = l;
296         v[0] = attrf(a, "x");
297         v[1] = attrf(a, "y");
298         v[2] = attrf(a, "z");
299         l->setLaunchbarMount(v);
300         v[0] = attrf(a, "holdback-x", v[0]);
301         v[1] = attrf(a, "holdback-y", v[1]);
302         v[2] = attrf(a, "holdback-z", v[2]);
303         l->setHoldbackMount(v);
304         float length = attrf(a, "length", 1.0);
305         l->setLength(length);
306         l->setDownAngle(attrf(a, "down-angle", 45) * DEG2RAD);
307         l->setUpAngle(attrf(a, "up-angle", -45) * DEG2RAD);
308         l->setHoldbackLength(attrf(a, "holdback-length", 2.0));
309         _airplane.addLaunchbar(l);
310     } else if(eq(name, "fuselage")) {
311         float b[3];
312         v[0] = attrf(a, "ax");
313         v[1] = attrf(a, "ay");
314         v[2] = attrf(a, "az");
315         b[0] = attrf(a, "bx");
316         b[1] = attrf(a, "by");
317         b[2] = attrf(a, "bz");
318         float taper = attrf(a, "taper", 1);
319         float mid = attrf(a, "midpoint", 0.5);
320         _airplane.addFuselage(v, b, attrf(a, "width"), taper, mid);
321     } else if(eq(name, "tank")) {
322         v[0] = attrf(a, "x");
323         v[1] = attrf(a, "y");
324         v[2] = attrf(a, "z");
325         float density = 6.0; // gasoline, in lbs/gal
326         if(a->hasAttribute("jet")) density = 6.72; 
327         density *= LBS2KG*CM2GALS;
328         _airplane.addTank(v, attrf(a, "capacity") * LBS2KG, density);
329     } else if(eq(name, "ballast")) {
330         v[0] = attrf(a, "x");
331         v[1] = attrf(a, "y");
332         v[2] = attrf(a, "z");
333         _airplane.addBallast(v, attrf(a, "mass") * LBS2KG);
334     } else if(eq(name, "weight")) {
335         parseWeight(a);
336     } else if(eq(name, "stall")) {
337         Wing* w = (Wing*)_currObj;
338         w->setStall(attrf(a, "aoa") * DEG2RAD);
339         w->setStallWidth(attrf(a, "width", 2) * DEG2RAD);
340         w->setStallPeak(attrf(a, "peak", 1.5));
341     } else if(eq(name, "flap0")) {
342         ((Wing*)_currObj)->setFlap0(attrf(a, "start"), attrf(a, "end"),
343                                     attrf(a, "lift"), attrf(a, "drag"));
344     } else if(eq(name, "flap1")) {
345         ((Wing*)_currObj)->setFlap1(attrf(a, "start"), attrf(a, "end"),
346                                     attrf(a, "lift"), attrf(a, "drag"));
347     } else if(eq(name, "slat")) {
348         ((Wing*)_currObj)->setSlat(attrf(a, "start"), attrf(a, "end"),
349                                    attrf(a, "aoa"), attrf(a, "drag"));
350     } else if(eq(name, "spoiler")) {
351         ((Wing*)_currObj)->setSpoiler(attrf(a, "start"), attrf(a, "end"),
352                                       attrf(a, "lift"), attrf(a, "drag"));
353     /* } else if(eq(name, "collective")) {
354         ((Rotor*)_currObj)->setcollective(attrf(a, "min"), attrf(a, "max"));
355     } else if(eq(name, "cyclic")) {
356         ((Rotor*)_currObj)->setcyclic(attrf(a, "ail"), attrf(a, "ele"));
357     */                               
358     } else if(eq(name, "actionpt")) {
359         v[0] = attrf(a, "x");
360         v[1] = attrf(a, "y");
361         v[2] = attrf(a, "z");
362         ((Thruster*)_currObj)->setPosition(v);
363     } else if(eq(name, "dir")) {
364         v[0] = attrf(a, "x");
365         v[1] = attrf(a, "y");
366         v[2] = attrf(a, "z");
367         ((Thruster*)_currObj)->setDirection(v);
368     } else if(eq(name, "control-setting")) {
369         // A cruise or approach control setting
370         const char* axis = a->getValue("axis");
371         float value = attrf(a, "value", 0);
372         if(_cruiseCurr)
373             _airplane.addCruiseControl(parseAxis(axis), value);
374         else
375             _airplane.addApproachControl(parseAxis(axis), value);
376     } else if(eq(name, "control-input")) {
377
378         // A mapping of input property to a control
379         int axis = parseAxis(a->getValue("axis"));
380         int control = parseOutput(a->getValue("control"));
381         int opt = 0;
382         opt |= a->hasAttribute("split") ? ControlMap::OPT_SPLIT : 0;
383         opt |= a->hasAttribute("invert") ? ControlMap::OPT_INVERT : 0;
384         opt |= a->hasAttribute("square") ? ControlMap::OPT_SQUARE : 0;
385         
386         ControlMap* cm = _airplane.getControlMap();
387         if(a->hasAttribute("src0")) {
388                            cm->addMapping(axis, control, _currObj, opt,
389                            attrf(a, "src0"), attrf(a, "src1"), 
390                            attrf(a, "dst0"), attrf(a, "dst1"));
391         } else {
392             cm->addMapping(axis, control, _currObj, opt);
393         }
394     } else if(eq(name, "control-output")) {
395         // A property output for a control on the current object
396         ControlMap* cm = _airplane.getControlMap();
397         int type = parseOutput(a->getValue("control"));
398         int handle = cm->getOutputHandle(_currObj, type);
399
400         PropOut* p = new PropOut();
401         p->prop = fgGetNode(a->getValue("prop"), true);
402         p->handle = handle;
403         p->type = type;
404         p->left = !(a->hasAttribute("side") &&
405                         eq("right", a->getValue("side")));
406         p->min = attrf(a, "min", cm->rangeMin(type));
407         p->max = attrf(a, "max", cm->rangeMax(type));
408         _controlProps.add(p);
409
410     } else if(eq(name, "control-speed")) {
411         ControlMap* cm = _airplane.getControlMap();
412         int type = parseOutput(a->getValue("control"));
413         int handle = cm->getOutputHandle(_currObj, type);
414         float time = attrf(a, "transition-time", 0);
415         
416         cm->setTransitionTime(handle, time);
417     } else {
418         SG_LOG(SG_FLIGHT,SG_ALERT,"Unexpected tag '"
419                << name << "' found in YASim aircraft description");
420         exit(1);
421     }
422 }
423
424 void FGFDM::getExternalInput(float dt)
425 {
426     char buf[256];
427
428     _turb->setMagnitude(fgGetFloat("/environment/turbulence/magnitude-norm"));
429     _turb->update(dt, fgGetFloat("/environment/turbulence/rate-hz"));
430
431     // The control axes
432     ControlMap* cm = _airplane.getControlMap();
433     cm->reset();
434     int i;
435     for(i=0; i<_axes.size(); i++) {
436         AxisRec* a = (AxisRec*)_axes.get(i);
437         float val = fgGetFloat(a->name, 0);
438         cm->setInput(a->handle, val);
439     }
440     cm->applyControls(dt);
441
442     // Weights
443     for(i=0; i<_weights.size(); i++) {
444         WeightRec* wr = (WeightRec*)_weights.get(i);
445         _airplane.setWeight(wr->handle, LBS2KG * fgGetFloat(wr->prop));
446     }
447
448     for(i=0; i<_thrusters.size(); i++) {
449         EngRec* er = (EngRec*)_thrusters.get(i);
450         Thruster* t = er->eng;
451
452         if(t->getPropEngine()) {
453             PropEngine* p = t->getPropEngine();
454             sprintf(buf, "%s/rpm", er->prefix);
455             p->setOmega(fgGetFloat(buf, 500) * RPM2RAD);
456         }
457     }
458 }
459
460 // Linearly "seeks" a property by the specified fraction of the way to
461 // the target value.  Used to emulate "slowly changing" output values.
462 static void moveprop(SGPropertyNode* node, const char* prop,
463                     float target, float frac)
464 {
465     float val = node->getFloatValue(prop);
466     if(frac > 1) frac = 1;
467     if(frac < 0) frac = 0;
468     val += (target - val) * frac;
469     node->setFloatValue(prop, val);
470 }
471
472 void FGFDM::setOutputProperties(float dt)
473 {
474     // char buf[256];
475     int i;
476
477     float grossWgt = _airplane.getModel()->getBody()->getTotalMass() * KG2LBS;
478     fgSetFloat("/yasim/gross-weight-lbs", grossWgt);
479
480     ControlMap* cm = _airplane.getControlMap();
481     for(i=0; i<_controlProps.size(); i++) {
482         PropOut* p = (PropOut*)_controlProps.get(i);
483         float val = (p->left
484                      ? cm->getOutput(p->handle)
485                      : cm->getOutputR(p->handle));
486         float rmin = cm->rangeMin(p->type);
487         float rmax = cm->rangeMax(p->type);
488         float frac = (val - rmin) / (rmax - rmin);
489         val = frac*(p->max - p->min) + p->min;
490         p->prop->setFloatValue(val);
491     }
492
493     for(i=0; i<_airplane.getRotorgear()->getNumRotors(); i++) {
494         Rotor*r=(Rotor*)_airplane.getRotorgear()->getRotor(i);
495         int j = 0;
496         float f;
497         char b[256];
498         while((j = r->getValueforFGSet(j, b, &f)))
499             if(b[0]) fgSetFloat(b,f);
500         j=0;
501         while((j = _airplane.getRotorgear()->getValueforFGSet(j, b, &f)))
502             if(b[0]) fgSetFloat(b,f);
503         for(j=0; j < r->numRotorparts(); j+=r->numRotorparts()>>2) {
504             Rotorpart* s = (Rotorpart*)r->getRotorpart(j);
505             char *b;
506             int k;
507             for(k=0; k<2; k++) {
508                 b=s->getAlphaoutput(k);
509                 if(b[0]) fgSetFloat(b, s->getAlpha(k));
510             }
511         }
512     }
513
514     float fuelDensity = _airplane.getFuelDensity(0); // HACK
515     for(i=0; i<_thrusters.size(); i++) {
516         EngRec* er = (EngRec*)_thrusters.get(i);
517         Thruster* t = er->eng;
518         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
519
520         // Set: running, cranking, prop-thrust, max-hp, power-pct
521         node->setBoolValue("running", t->isRunning());
522         node->setBoolValue("cranking", t->isCranking());
523
524         float tmp[3];
525         t->getThrust(tmp);
526         float lbs = Math::mag3(tmp) * (KG2LBS/9.8);
527         node->setFloatValue("prop-thrust", lbs); // Deprecated name
528         node->setFloatValue("thrust-lbs", lbs);
529         node->setFloatValue("fuel-flow-gph",
530                             (t->getFuelFlow()/fuelDensity) * 3600 * CM2GALS);
531
532         if(t->getPropEngine()) {
533             PropEngine* p = t->getPropEngine();
534             node->setFloatValue("rpm", p->getOmega() * (1/RPM2RAD));
535             node->setFloatValue("torque-ftlb",
536                                 p->getEngine()->getTorque() * NM2FTLB);
537         
538             if(p->getEngine()->isPistonEngine()) {
539                 PistonEngine* pe = p->getEngine()->isPistonEngine();
540                 node->setFloatValue("mp-osi", pe->getMP() * (1/INHG2PA));
541                 node->setFloatValue("mp-inhg", pe->getMP() * (1/INHG2PA));
542                 node->setFloatValue("egt-degf",
543                                     pe->getEGT() * K2DEGF + K2DEGFOFFSET);
544                 node->setFloatValue("oil-temperature-degf",
545                                     pe->getOilTemp() * K2DEGF + K2DEGFOFFSET);
546                 node->setFloatValue("boost-gauge-inhg",
547                                     pe->getBoost() * (1/INHG2PA));
548             } else if(p->getEngine()->isTurbineEngine()) {
549                 TurbineEngine* te = p->getEngine()->isTurbineEngine();
550                 node->setFloatValue("n2", te->getN2());
551             }
552         }
553
554         if(t->getJet()) {
555             Jet* j = t->getJet();
556             node->setFloatValue("n1", j->getN1());
557             node->setFloatValue("n2", j->getN2());
558             node->setFloatValue("epr", j->getEPR());
559             node->setFloatValue("egt-degf",
560                                 j->getEGT() * K2DEGF + K2DEGFOFFSET);
561
562             // These are "unmodeled" values that are still needed for
563             // many cockpits.  Tie them all to the N1 speed, but
564             // normalize the numbers to the range [0:1] so the
565             // cockpit code can scale them to the right values.
566             float pnorm = j->getPerfNorm();
567             moveprop(node, "oilp-norm", pnorm, dt/3); // 3s seek time
568             moveprop(node, "oilt-norm", pnorm, dt/30); // 30s 
569             moveprop(node, "itt-norm", pnorm, dt/1); // 1s
570         }
571     }
572 }
573
574 Wing* FGFDM::parseWing(XMLAttributes* a, const char* type)
575 {
576     Wing* w = new Wing();
577
578     float defDihed = 0;
579     if(eq(type, "vstab"))
580         defDihed = 90;
581     else
582         w->setMirror(true);
583
584     float pos[3];
585     pos[0] = attrf(a, "x");
586     pos[1] = attrf(a, "y");
587     pos[2] = attrf(a, "z");
588     w->setBase(pos);
589
590     w->setLength(attrf(a, "length"));
591     w->setChord(attrf(a, "chord"));
592     w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
593     w->setTaper(attrf(a, "taper", 1));
594     w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
595     w->setCamber(attrf(a, "camber", 0));
596
597     // These come in with positive indicating positive AoA, but the
598     // internals expect a rotation about the left-pointing Y axis, so
599     // invert the sign.
600     w->setIncidence(attrf(a, "incidence", 0) * DEG2RAD * -1);
601     w->setTwist(attrf(a, "twist", 0) * DEG2RAD * -1);
602
603     // The 70% is a magic number that sorta kinda seems to match known
604     // throttle settings to approach speed.
605     w->setInducedDrag(0.7*attrf(a, "idrag", 1));
606
607     float effect = attrf(a, "effectiveness", 1);
608     w->setDragScale(w->getDragScale()*effect);
609
610     _currObj = w;
611     return w;
612 }
613
614 Rotor* FGFDM::parseRotor(XMLAttributes* a, const char* type)
615 {
616     Rotor* w = new Rotor();
617
618     // float defDihed = 0;
619
620     float pos[3];
621     pos[0] = attrf(a, "x");
622     pos[1] = attrf(a, "y");
623     pos[2] = attrf(a, "z");
624     w->setBase(pos);
625
626     float normal[3];
627     normal[0] = attrf(a, "nx");
628     normal[1] = attrf(a, "ny");
629     normal[2] = attrf(a, "nz");
630     w->setNormal(normal);
631
632     float forward[3];
633     forward[0] = attrf(a, "fx");
634     forward[1] = attrf(a, "fy");
635     forward[2] = attrf(a, "fz");
636     w->setForward(forward);
637
638     w->setMaxCyclicail(attrf(a, "maxcyclicail", 7.6));
639     w->setMaxCyclicele(attrf(a, "maxcyclicele", 4.94));
640     w->setMinCyclicail(attrf(a, "mincyclicail", -7.6));
641     w->setMinCyclicele(attrf(a, "mincyclicele", -4.94));
642     w->setMaxCollective(attrf(a, "maxcollective", 15.8));
643     w->setMinCollective(attrf(a, "mincollective", -0.2));
644     w->setDiameter(attrf(a, "diameter", 10.2));
645     w->setWeightPerBlade(attrf(a, "weightperblade", 44));
646     w->setNumberOfBlades(attrf(a, "numblades", 4));
647     w->setRelBladeCenter(attrf(a, "relbladecenter", 0.7));
648     w->setDynamic(attrf(a, "dynamic", 0.7));
649     w->setDelta3(attrf(a, "delta3", 0));
650     w->setDelta(attrf(a, "delta", 0));
651     w->setTranslift(attrf(a, "translift", 0.05));
652     w->setC2(attrf(a, "dragfactor", 1));
653     w->setStepspersecond(attrf(a, "stepspersecond", 120));
654     w->setRPM(attrf(a, "rpm", 424));
655     w->setRelLenHinge(attrf(a, "rellenflaphinge", 0.07));
656     w->setAlpha0((attrf(a, "flap0", -5))*YASIM_PI/180);
657     w->setAlphamin((attrf(a, "flapmin", -15))/180*YASIM_PI);
658     w->setAlphamax((attrf(a, "flapmax",  15))*YASIM_PI/180);
659     w->setAlpha0factor(attrf(a, "flap0factor", 1));
660     w->setTeeterdamp(attrf(a,"teeterdamp",.0001));
661     w->setMaxteeterdamp(attrf(a,"maxteeterdamp",1000));
662     w->setRelLenTeeterHinge(attrf(a,"rellenteeterhinge",0.01));
663     void setAlphamin(float f);
664     void setAlphamax(float f);
665     void setAlpha0factor(float f);
666
667     if(attrb(a,"ccw"))
668        w->setCcw(1); 
669     
670     if(a->hasAttribute("name"))
671        w->setName(a->getValue("name") );
672     if(a->hasAttribute("alphaout0"))
673        w->setAlphaoutput(0,a->getValue("alphaout0") );
674     if(a->hasAttribute("alphaout1"))  w->setAlphaoutput(1,a->getValue("alphaout1") );
675     if(a->hasAttribute("alphaout2"))  w->setAlphaoutput(2,a->getValue("alphaout2") );
676     if(a->hasAttribute("alphaout3"))  w->setAlphaoutput(3,a->getValue("alphaout3") );
677     if(a->hasAttribute("coneout"))  w->setAlphaoutput(4,a->getValue("coneout") );
678     if(a->hasAttribute("yawout"))   w->setAlphaoutput(5,a->getValue("yawout") );
679     if(a->hasAttribute("rollout"))  w->setAlphaoutput(6,a->getValue("rollout") );
680
681     w->setPitchA(attrf(a, "pitch_a", 10));
682     w->setPitchB(attrf(a, "pitch_b", 10));
683     w->setForceAtPitchA(attrf(a, "forceatpitch_a", 3000));
684     w->setPowerAtPitch0(attrf(a, "poweratpitch_0", 300));
685     w->setPowerAtPitchB(attrf(a, "poweratpitch_b", 3000));
686     if(attrb(a,"notorque"))
687        w->setNotorque(1); 
688
689 #define p(x) if (a->hasAttribute(#x)) w->setParameter((char *)#x,attrf(a,#x) );
690     p(translift_ve)
691     p(translift_maxfactor)
692     p(ground_effect_constant)
693     p(vortex_state_lift_factor)
694     p(vortex_state_c1)
695     p(vortex_state_c2)
696     p(vortex_state_c3)
697     p(vortex_state_e1)
698     p(vortex_state_e2)
699     p(twist)
700     p(number_of_segments)
701     p(number_of_parts)
702     p(rel_len_where_incidence_is_measured)
703     p(chord)
704     p(taper)
705     p(airfoil_incidence_no_lift)
706     p(rel_len_blade_start)
707     p(incidence_stall_zero_speed)
708     p(incidence_stall_half_sonic_speed)
709     p(lift_factor_stall)
710     p(stall_change_over)
711     p(drag_factor_stall)
712     p(airfoil_lift_coefficient)
713     p(airfoil_drag_coefficient0)
714     p(airfoil_drag_coefficient1)
715     p(cyclic_factor)
716     p(rotor_correction_factor)
717 #undef p
718     _currObj = w;
719     return w;
720 }
721
722 void FGFDM::parsePistonEngine(XMLAttributes* a)
723 {
724     float engP = attrf(a, "eng-power") * HP2W;
725     float engS = attrf(a, "eng-rpm") * RPM2RAD;
726
727     PistonEngine* eng = new PistonEngine(engP, engS);
728
729     if(a->hasAttribute("displacement"))
730         eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
731
732     if(a->hasAttribute("compression"))
733         eng->setCompression(attrf(a, "compression"));        
734
735     if(a->hasAttribute("turbo-mul")) {
736         float mul = attrf(a, "turbo-mul");
737         float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
738         eng->setTurboParams(mul, mp);
739         eng->setTurboLag(attrf(a, "turbo-lag", 2));
740     }
741
742     if(a->hasAttribute("supercharger"))
743         eng->setSupercharger(attrb(a, "supercharger"));
744
745     ((PropEngine*)_currObj)->setEngine(eng);
746 }
747
748 void FGFDM::parseTurbineEngine(XMLAttributes* a)
749 {
750     float power = attrf(a, "eng-power") * HP2W;
751     float omega = attrf(a, "eng-rpm") * RPM2RAD;
752     float alt = attrf(a, "alt") * FT2M;
753     float flatRating = attrf(a, "flat-rating") * HP2W;
754     TurbineEngine* eng = new TurbineEngine(power, omega, alt, flatRating);
755
756     if(a->hasAttribute("n2-low-idle"))
757         eng->setN2Range(attrf(a, "n2-low-idle"), attrf(a, "n2-high-idle"),
758                         attrf(a, "n2-max"));
759
760     // Nasty units conversion: lbs/hr per hp -> kg/s per watt
761     if(a->hasAttribute("bsfc"))
762         eng->setFuelConsumption(attrf(a, "bsfc") * (LBS2KG/(3600*HP2W)));
763
764     ((PropEngine*)_currObj)->setEngine(eng);
765 }
766
767 void FGFDM::parsePropeller(XMLAttributes* a)
768 {
769     // Legacy Handling for the old engines syntax:
770     PistonEngine* eng = 0;
771     if(a->hasAttribute("eng-power")) {
772         SG_LOG(SG_FLIGHT,SG_ALERT, "WARNING: "
773                << "Legacy engine definition in YASim configuration file.  "
774                << "Please fix.");
775         float engP = attrf(a, "eng-power") * HP2W;
776         float engS = attrf(a, "eng-rpm") * RPM2RAD;
777         eng = new PistonEngine(engP, engS);
778         if(a->hasAttribute("displacement"))
779             eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
780         if(a->hasAttribute("compression"))
781             eng->setCompression(attrf(a, "compression"));        
782         if(a->hasAttribute("turbo-mul")) {
783             float mul = attrf(a, "turbo-mul");
784             float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
785             eng->setTurboParams(mul, mp);
786         }
787     }
788
789     // Now parse the actual propeller definition:
790     float cg[3];
791     cg[0] = attrf(a, "x");
792     cg[1] = attrf(a, "y");
793     cg[2] = attrf(a, "z");
794     float mass = attrf(a, "mass") * LBS2KG;
795     float moment = attrf(a, "moment");
796     float radius = attrf(a, "radius");
797     float speed = attrf(a, "cruise-speed") * KTS2MPS;
798     float omega = attrf(a, "cruise-rpm") * RPM2RAD;
799     float power = attrf(a, "cruise-power") * HP2W;
800     float rho = Atmosphere::getStdDensity(attrf(a, "cruise-alt") * FT2M);
801
802     Propeller* prop = new Propeller(radius, speed, omega, rho, power);
803     PropEngine* thruster = new PropEngine(prop, eng, moment);
804     _airplane.addThruster(thruster, mass, cg);
805
806     // Set the stops (fine = minimum pitch, coarse = maximum pitch)
807     float fine_stop = attrf(a, "fine-stop", 0.25f);
808     float coarse_stop = attrf(a, "coarse-stop", 4.0f);
809     prop->setStops(fine_stop, coarse_stop);
810
811     if(a->hasAttribute("takeoff-power")) {
812         float power0 = attrf(a, "takeoff-power") * HP2W;
813         float omega0 = attrf(a, "takeoff-rpm") * RPM2RAD;
814         prop->setTakeoff(omega0, power0);
815     }
816
817     if(a->hasAttribute("max-rpm")) {
818         float max = attrf(a, "max-rpm") * RPM2RAD;
819         float min = attrf(a, "min-rpm") * RPM2RAD;
820         thruster->setVariableProp(min, max);
821     }
822
823     if(attrb(a, "contra"))
824         thruster->setContraPair(true);
825
826     if(a->hasAttribute("manual-pitch")) {
827         prop->setManualPitch();
828     }
829
830     thruster->setGearRatio(attrf(a, "gear-ratio", 1));
831
832     char buf[64];
833     sprintf(buf, "/engines/engine[%d]", _nextEngine++);
834     EngRec* er = new EngRec();
835     er->eng = thruster;
836     er->prefix = dup(buf);
837     _thrusters.add(er);
838
839     _currObj = thruster;
840 }
841
842 // Turns a string axis name into an integer for use by the
843 // ControlMap.  Creates a new axis if this one hasn't been defined
844 // yet.
845 int FGFDM::parseAxis(const char* name)
846 {
847     int i;
848     for(i=0; i<_axes.size(); i++) {
849         AxisRec* a = (AxisRec*)_axes.get(i);
850         if(eq(a->name, name))
851             return a->handle;
852     }
853
854     // Not there, make a new one.
855     AxisRec* a = new AxisRec();
856     a->name = dup(name);
857     fgGetNode( a->name, true ); // make sure the property name exists
858     a->handle = _airplane.getControlMap()->newInput();
859     _axes.add(a);
860     return a->handle;
861 }
862
863 int FGFDM::parseOutput(const char* name)
864 {
865     if(eq(name, "THROTTLE"))  return ControlMap::THROTTLE;
866     if(eq(name, "MIXTURE"))   return ControlMap::MIXTURE;
867     if(eq(name, "CONDLEVER")) return ControlMap::CONDLEVER;
868     if(eq(name, "STARTER"))   return ControlMap::STARTER;
869     if(eq(name, "MAGNETOS"))  return ControlMap::MAGNETOS;
870     if(eq(name, "ADVANCE"))   return ControlMap::ADVANCE;
871     if(eq(name, "REHEAT"))    return ControlMap::REHEAT;
872     if(eq(name, "BOOST"))     return ControlMap::BOOST;
873     if(eq(name, "VECTOR"))    return ControlMap::VECTOR;
874     if(eq(name, "PROP"))      return ControlMap::PROP;
875     if(eq(name, "BRAKE"))     return ControlMap::BRAKE;
876     if(eq(name, "STEER"))     return ControlMap::STEER;
877     if(eq(name, "EXTEND"))    return ControlMap::EXTEND;
878     if(eq(name, "HEXTEND"))   return ControlMap::HEXTEND;
879     if(eq(name, "LEXTEND"))   return ControlMap::LEXTEND;
880     if(eq(name, "INCIDENCE")) return ControlMap::INCIDENCE;
881     if(eq(name, "FLAP0"))     return ControlMap::FLAP0;
882     if(eq(name, "FLAP1"))     return ControlMap::FLAP1;
883     if(eq(name, "SLAT"))      return ControlMap::SLAT;
884     if(eq(name, "SPOILER"))   return ControlMap::SPOILER;
885     if(eq(name, "CASTERING")) return ControlMap::CASTERING;
886     if(eq(name, "PROPPITCH")) return ControlMap::PROPPITCH;
887     if(eq(name, "PROPFEATHER")) return ControlMap::PROPFEATHER;
888     if(eq(name, "COLLECTIVE")) return ControlMap::COLLECTIVE;
889     if(eq(name, "CYCLICAIL")) return ControlMap::CYCLICAIL;
890     if(eq(name, "CYCLICELE")) return ControlMap::CYCLICELE;
891     if(eq(name, "ROTORGEARENGINEON")) return ControlMap::ROTORENGINEON;
892     if(eq(name, "ROTORBRAKE")) return ControlMap::ROTORBRAKE;
893     if(eq(name, "REVERSE_THRUST")) return ControlMap::REVERSE_THRUST;
894     if(eq(name, "WASTEGATE")) return ControlMap::WASTEGATE;
895     SG_LOG(SG_FLIGHT,SG_ALERT,"Unrecognized control type '"
896            << name << "' in YASim aircraft description.");
897     exit(1);
898
899 }
900
901 void FGFDM::parseWeight(XMLAttributes* a)
902 {
903     WeightRec* wr = new WeightRec();
904
905     float v[3];
906     v[0] = attrf(a, "x");
907     v[1] = attrf(a, "y");
908     v[2] = attrf(a, "z");
909
910     wr->prop = dup(a->getValue("mass-prop"));
911     wr->size = attrf(a, "size", 0);
912     wr->handle = _airplane.addWeight(v, wr->size);
913
914     _weights.add(wr);
915 }
916
917 bool FGFDM::eq(const char* a, const char* b)
918 {
919     // Figure it out for yourself. :)
920     while(*a && *b && *a == *b) { a++; b++; }
921     return !(*a || *b);
922 }
923
924 char* FGFDM::dup(const char* s)
925 {
926     int len=0;
927     while(s[len++]);
928     char* s2 = new char[len+1];
929     char* p = s2;
930     while((*p++ = *s++));
931     s2[len] = 0;
932     return s2;
933 }
934
935 int FGFDM::attri(XMLAttributes* atts, char* attr)
936 {
937     if(!atts->hasAttribute(attr)) {
938         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
939                "' in YASim aircraft description");
940         exit(1);
941     }
942     return attri(atts, attr, 0);
943 }
944
945 int FGFDM::attri(XMLAttributes* atts, char* attr, int def)
946 {
947     const char* val = atts->getValue(attr);
948     if(val == 0) return def;
949     else         return atol(val);
950 }
951
952 float FGFDM::attrf(XMLAttributes* atts, char* attr)
953 {
954     if(!atts->hasAttribute(attr)) {
955         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
956                "' in YASim aircraft description");
957         exit(1);
958     }
959     return attrf(atts, attr, 0);
960 }
961
962 float FGFDM::attrf(XMLAttributes* atts, char* attr, float def)
963 {
964     const char* val = atts->getValue(attr);
965     if(val == 0) return def;
966     else         return (float)atof(val);    
967 }
968
969 // ACK: the dreaded ambiguous string boolean.  Remind me to shoot Maik
970 // when I have a chance. :).  Unless you have a parser that can check
971 // symbol constants (we don't), this kind of coding is just a Bad
972 // Idea.  This implementation, for example, silently returns a boolean
973 // falsehood for values of "1", "yes", "True", and "TRUE".  Which is
974 // especially annoying preexisting boolean attributes in the same
975 // parser want to see "1" and will choke on a "true"...
976 //
977 // Unfortunately, this usage creeped into existing configuration files
978 // while I wasn't active, and it's going to be hard to remove.  Issue
979 // a warning to nag people into changing their ways for now...
980 bool FGFDM::attrb(XMLAttributes* atts, char* attr)
981 {
982     const char* val = atts->getValue(attr);
983     if(val == 0) return false;
984
985     if(eq(val,"true")) {
986         SG_LOG(SG_FLIGHT, SG_ALERT, "Warning: " <<
987                "deprecated 'true' boolean in YASim configuration file.  " <<
988                "Use numeric booleans (attribute=\"1\") instead");
989         return true;
990     }
991     return attri(atts, attr, 0) ? true : false;
992 }
993
994 }; // namespace yasim