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