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