]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/FGFDM.cpp
Solve for the elevator control input during approach. It turns out that
[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 "Jet.hpp"
7 #include "SimpleJet.hpp"
8 #include "Gear.hpp"
9 #include "Atmosphere.hpp"
10 #include "PropEngine.hpp"
11 #include "Propeller.hpp"
12 #include "PistonEngine.hpp"
13
14 #include "FGFDM.hpp"
15 namespace yasim {
16
17 // Some conversion factors
18 static const float KTS2MPS = 0.514444444444;
19 static const float FT2M = 0.3048;
20 static const float DEG2RAD = 0.0174532925199;
21 static const float RPM2RAD = 0.10471975512;
22 static const float LBS2N = 4.44822;
23 static const float LBS2KG = 0.45359237;
24 static const float CM2GALS = 264.172037284;
25 static const float HP2W = 745.700;
26 static const float INHG2PA = 3386.389;
27 static const float K2DEGF = 1.8;
28 static const float CIN2CM = 1.6387064e-5;
29
30 // Stubs, so that this can be compiled without the FlightGear
31 // binary.  What's the best way to handle this?
32
33 //     float fgGetFloat(char* name, float def) { return 0; }
34 //     void fgSetFloat(char* name, float val) {}
35
36 FGFDM::FGFDM()
37 {
38     _nextEngine = 0;
39
40     // Map /controls/elevator to the approach elevator control.  This
41     // should probably be settable, but there are very few aircraft
42     // who trim their approaches using things other than elevator.
43     _airplane.setElevatorControl(parseAxis("/controls/elevator"));
44 }
45
46 FGFDM::~FGFDM()
47 {
48     int i;
49     for(i=0; i<_axes.size(); i++) {
50         AxisRec* a = (AxisRec*)_axes.get(i);
51         delete[] a->name;
52         delete a;
53     }
54     for(i=0; i<_thrusters.size(); i++) {
55         EngRec* er = (EngRec*)_thrusters.get(i);
56         delete[] er->prefix;
57         delete er->eng;
58         delete er;
59     }
60     for(i=0; i<_weights.size(); i++) {
61         WeightRec* wr = (WeightRec*)_weights.get(i);
62         delete[] wr->prop;
63         delete wr;
64     }
65     for(i=0; i<_controlProps.size(); i++)
66         delete (PropOut*)_controlProps.get(i);
67 }
68
69 void FGFDM::iterate(float dt)
70 {
71     getExternalInput(dt);
72     _airplane.iterate(dt);
73     setOutputProperties();
74 }
75
76 Airplane* FGFDM::getAirplane()
77 {
78     return &_airplane;
79 }
80
81 void FGFDM::init()
82 {
83     // Allows the user to start with something other than full fuel
84     _airplane.setFuelFraction(fgGetFloat("/sim/fuel-fraction", 1));
85
86     // This has a nasty habit of being false at startup.  That's not
87     // good.
88     fgSetBool("/controls/gear-down", true);
89 }
90
91 // Not the worlds safest parser.  But it's short & sweet.
92 void FGFDM::startElement(const char* name, const XMLAttributes &atts)
93 {
94     XMLAttributes* a = (XMLAttributes*)&atts;
95     float v[3];
96     char buf[64];
97
98     if(eq(name, "airplane")) {
99         _airplane.setWeight(attrf(a, "mass") * LBS2KG);
100     } else if(eq(name, "approach")) {
101         float spd = attrf(a, "speed") * KTS2MPS;
102         float alt = attrf(a, "alt", 0) * FT2M;
103         float aoa = attrf(a, "aoa", 0) * DEG2RAD;
104         _airplane.setApproach(spd, alt, aoa);
105         _cruiseCurr = false;
106     } else if(eq(name, "cruise")) {
107         float spd = attrf(a, "speed") * KTS2MPS;
108         float alt = attrf(a, "alt") * FT2M;
109         _airplane.setCruise(spd, alt);
110         _cruiseCurr = true;
111     } else if(eq(name, "cockpit")) {
112         v[0] = attrf(a, "x");
113         v[1] = attrf(a, "y");
114         v[2] = attrf(a, "z");
115         _airplane.setPilotPos(v);
116     } else if(eq(name, "wing")) {
117         _airplane.setWing(parseWing(a, name));
118     } else if(eq(name, "hstab")) {
119         _airplane.setTail(parseWing(a, name));
120     } else if(eq(name, "vstab")) {
121         _airplane.addVStab(parseWing(a, name));
122     } else if(eq(name, "propeller")) {
123         parsePropeller(a);
124     } else if(eq(name, "thruster")) {
125         SimpleJet* j = new SimpleJet();
126         _currObj = j;
127         v[0] = attrf(a, "x"); v[1] = attrf(a, "y"); v[2] = attrf(a, "z");
128         j->setPosition(v);
129         _airplane.addThruster(j, 0, v);
130         v[0] = attrf(a, "vx"); v[1] = attrf(a, "vy"); v[2] = attrf(a, "vz");
131         j->setDirection(v);
132         j->setThrust(attrf(a, "thrust") * LBS2N);
133     } else if(eq(name, "jet")) {
134         Jet* j = new Jet();
135         _currObj = j;
136         v[0] = attrf(a, "x");
137         v[1] = attrf(a, "y");
138         v[2] = attrf(a, "z");
139         float mass = attrf(a, "mass") * LBS2KG;
140         j->setMaxThrust(attrf(a, "thrust") * LBS2N,
141                         attrf(a, "afterburner", 0) * LBS2N);
142         j->setVectorAngle(attrf(a, "rotate", 0) * DEG2RAD);
143
144         float n1min = attrf(a, "n1-idle", 55);
145         float n1max = attrf(a, "n1-max", 102);
146         float n2min = attrf(a, "n2-idle", 73);
147         float n2max = attrf(a, "n2-max", 103);
148         j->setRPMs(n1min, n1max, n2min, n2max);
149
150         if(a->hasAttribute("tsfc")) j->setTSFC(attrf(a, "tsfc"));
151         if(a->hasAttribute("egt"))  j->setEGT(attrf(a, "egt"));
152         if(a->hasAttribute("epr"))  j->setEPR(attrf(a, "epr"));
153         if(a->hasAttribute("exhaust-speed"))
154             j->setVMax(attrf(a, "exhaust-speed") * KTS2MPS);
155         
156         j->setPosition(v);
157         _airplane.addThruster(j, mass, v);
158         sprintf(buf, "/engines/engine[%d]", _nextEngine++);
159         EngRec* er = new EngRec();
160         er->eng = j;
161         er->prefix = dup(buf);
162         _thrusters.add(er);
163     } else if(eq(name, "gear")) {
164         Gear* g = new Gear();
165         _currObj = g;
166         v[0] = attrf(a, "x");
167         v[1] = attrf(a, "y");
168         v[2] = attrf(a, "z");
169         g->setPosition(v);
170         v[0] = 0;
171         v[1] = 0;
172         v[2] = attrf(a, "compression", 1);
173         g->setCompression(v);
174         g->setBrake(attrf(a, "skid", 0));
175         g->setStaticFriction(attrf(a, "sfric", 0.8));
176         g->setDynamicFriction(attrf(a, "dfric", 0.7));
177         if(a->hasAttribute("castering"))
178             g->setCastering(true);
179         _airplane.addGear(g);
180     } else if(eq(name, "fuselage")) {
181         float b[3];
182         v[0] = attrf(a, "ax");
183         v[1] = attrf(a, "ay");
184         v[2] = attrf(a, "az");
185         b[0] = attrf(a, "bx");
186         b[1] = attrf(a, "by");
187         b[2] = attrf(a, "bz");
188         float taper = attrf(a, "taper", 1);
189         float mid = attrf(a, "midpoint", 0.5);
190         _airplane.addFuselage(v, b, attrf(a, "width"), taper, mid);
191     } else if(eq(name, "tank")) {
192         v[0] = attrf(a, "x");
193         v[1] = attrf(a, "y");
194         v[2] = attrf(a, "z");
195         float density = 6.0; // gasoline, in lbs/gal
196         if(a->hasAttribute("jet")) density = 6.72; 
197         density *= LBS2KG*CM2GALS;
198         _airplane.addTank(v, attrf(a, "capacity") * LBS2KG, density);
199     } else if(eq(name, "ballast")) {
200         v[0] = attrf(a, "x");
201         v[1] = attrf(a, "y");
202         v[2] = attrf(a, "z");
203         _airplane.addBallast(v, attrf(a, "mass") * LBS2KG);
204     } else if(eq(name, "weight")) {
205         parseWeight(a);
206     } else if(eq(name, "stall")) {
207         Wing* w = (Wing*)_currObj;
208         w->setStall(attrf(a, "aoa") * DEG2RAD);
209         w->setStallWidth(attrf(a, "width", 2) * DEG2RAD);
210         w->setStallPeak(attrf(a, "peak", 1.5));
211     } else if(eq(name, "flap0")) {
212         ((Wing*)_currObj)->setFlap0(attrf(a, "start"), attrf(a, "end"),
213                                     attrf(a, "lift"), attrf(a, "drag"));
214     } else if(eq(name, "flap1")) {
215         ((Wing*)_currObj)->setFlap1(attrf(a, "start"), attrf(a, "end"),
216                                     attrf(a, "lift"), attrf(a, "drag"));
217     } else if(eq(name, "slat")) {
218         ((Wing*)_currObj)->setSlat(attrf(a, "start"), attrf(a, "end"),
219                                    attrf(a, "aoa"), attrf(a, "drag"));
220     } else if(eq(name, "spoiler")) {
221         ((Wing*)_currObj)->setSpoiler(attrf(a, "start"), attrf(a, "end"),
222                                       attrf(a, "lift"), attrf(a, "drag"));
223     } else if(eq(name, "actionpt")) {
224         v[0] = attrf(a, "x");
225         v[1] = attrf(a, "y");
226         v[2] = attrf(a, "z");
227         ((Thruster*)_currObj)->setPosition(v);
228     } else if(eq(name, "dir")) {
229         v[0] = attrf(a, "x");
230         v[1] = attrf(a, "y");
231         v[2] = attrf(a, "z");
232         ((Thruster*)_currObj)->setDirection(v);
233     } else if(eq(name, "control-setting")) {
234         // A cruise or approach control setting
235         const char* axis = a->getValue("axis");
236         float value = attrf(a, "value", 0);
237         if(_cruiseCurr)
238             _airplane.addCruiseControl(parseAxis(axis), value);
239         else
240             _airplane.addApproachControl(parseAxis(axis), value);
241     } else if(eq(name, "control-input")) {
242
243         // A mapping of input property to a control
244         int axis = parseAxis(a->getValue("axis"));
245         int control = parseOutput(a->getValue("control"));
246         int opt = 0;
247         opt |= a->hasAttribute("split") ? ControlMap::OPT_SPLIT : 0;
248         opt |= a->hasAttribute("invert") ? ControlMap::OPT_INVERT : 0;
249         opt |= a->hasAttribute("square") ? ControlMap::OPT_SQUARE : 0;
250         
251         ControlMap* cm = _airplane.getControlMap();
252         if(a->hasAttribute("src0")) {
253                            cm->addMapping(axis, control, _currObj, opt,
254                            attrf(a, "src0"), attrf(a, "src1"), 
255                            attrf(a, "dst0"), attrf(a, "dst1"));
256         } else {
257             cm->addMapping(axis, control, _currObj, opt);
258         }
259     } else if(eq(name, "control-output")) {
260         // A property output for a control on the current object
261         ControlMap* cm = _airplane.getControlMap();
262         int type = parseOutput(a->getValue("control"));
263         int handle = cm->getOutputHandle(_currObj, type);
264
265         PropOut* p = new PropOut();
266         p->prop = fgGetNode(a->getValue("prop"), true);
267         p->handle = handle;
268         p->type = type;
269         p->left = !(a->hasAttribute("side") &&
270                         eq("right", a->getValue("side")));
271         p->min = attrf(a, "min", cm->rangeMin(type));
272         p->max = attrf(a, "max", cm->rangeMax(type));
273         _controlProps.add(p);
274
275     } else if(eq(name, "control-speed")) {
276         ControlMap* cm = _airplane.getControlMap();
277         int type = parseOutput(a->getValue("control"));
278         int handle = cm->getOutputHandle(_currObj, type);
279         float time = attrf(a, "transition-time", 0);
280         
281         cm->setTransitionTime(handle, time);
282     } else {
283         SG_LOG(SG_FLIGHT,SG_ALERT,"Unexpected tag '"
284                << name << "' found in YASim aircraft description");
285         exit(1);
286     }
287 }
288
289 void FGFDM::getExternalInput(float dt)
290 {
291     // The control axes
292     ControlMap* cm = _airplane.getControlMap();
293     cm->reset();
294     int i;
295     for(i=0; i<_axes.size(); i++) {
296         AxisRec* a = (AxisRec*)_axes.get(i);
297         float val = fgGetFloat(a->name, 0);
298         cm->setInput(a->handle, val);
299     }
300     cm->applyControls(dt);
301
302     // Weights
303     for(i=0; i<_weights.size(); i++) {
304         WeightRec* wr = (WeightRec*)_weights.get(i);
305         _airplane.setWeight(wr->handle, fgGetFloat(wr->prop));
306     }
307 }
308
309 void FGFDM::setOutputProperties()
310 {
311     char buf[256];
312     int i;
313
314     ControlMap* cm = _airplane.getControlMap();
315     for(i=0; i<_controlProps.size(); i++) {
316         PropOut* p = (PropOut*)_controlProps.get(i);
317         float val = (p->left
318                      ? cm->getOutput(p->handle)
319                      : cm->getOutputR(p->handle));
320         float rmin = cm->rangeMin(p->type);
321         float rmax = cm->rangeMax(p->type);
322         float frac = (val - rmin) / (rmax - rmin);
323         val = frac*(p->max - p->min) + p->min;
324         p->prop->setFloatValue(val);
325     }
326
327     float fuelDensity = 718.95; // default to gasoline: ~6 lb/gal
328     for(i=0; i<_airplane.numTanks(); i++) {
329         fuelDensity = _airplane.getFuelDensity(i);
330         sprintf(buf, "/consumables/fuel/tank[%d]/level-gal_us", i);
331         fgSetFloat(buf, CM2GALS*_airplane.getFuel(i)/fuelDensity);
332     }
333
334     for(i=0; i<_thrusters.size(); i++) {
335         EngRec* er = (EngRec*)_thrusters.get(i);
336         Thruster* t = er->eng;
337
338         sprintf(buf, "%s/fuel-flow-gph", er->prefix);
339         fgSetFloat(buf, (t->getFuelFlow()/fuelDensity) * 3600 * CM2GALS);
340
341         if(t->getPropEngine()) {
342             PropEngine* p = t->getPropEngine();
343
344             sprintf(buf, "%s/rpm", er->prefix);
345             fgSetFloat(buf, p->getOmega() / RPM2RAD);
346         }
347
348         if(t->getPistonEngine()) {
349             PistonEngine* p = t->getPistonEngine();
350             
351             sprintf(buf, "%s/mp-osi", er->prefix);
352             fgSetFloat(buf, p->getMP() * (1/INHG2PA));
353
354             sprintf(buf, "%s/egt-degf", er->prefix);
355             fgSetFloat(buf, p->getEGT() * K2DEGF + 459.4);
356         }
357
358         if(t->getJet()) {
359             Jet* j = t->getJet();
360
361             sprintf(buf, "%s/n1", er->prefix);
362             fgSetFloat(buf, j->getN1());
363
364             sprintf(buf, "%s/n2", er->prefix);
365             fgSetFloat(buf, j->getN2());
366
367             sprintf(buf, "%s/epr", er->prefix);
368             fgSetFloat(buf, j->getEPR());
369
370             sprintf(buf, "%s/egt-degf", er->prefix);
371             fgSetFloat(buf, j->getEGT() * K2DEGF + 459.4);
372         }
373     }
374 }
375
376 Wing* FGFDM::parseWing(XMLAttributes* a, const char* type)
377 {
378     Wing* w = new Wing();
379
380     float defDihed = 0;
381     if(eq(type, "vstab"))
382         defDihed = 90;
383     else
384         w->setMirror(true);
385
386     float pos[3];
387     pos[0] = attrf(a, "x");
388     pos[1] = attrf(a, "y");
389     pos[2] = attrf(a, "z");
390     w->setBase(pos);
391
392     w->setLength(attrf(a, "length"));
393     w->setChord(attrf(a, "chord"));
394     w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
395     w->setTaper(attrf(a, "taper", 1));
396     w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
397     w->setCamber(attrf(a, "camber", 0));
398     w->setIncidence(attrf(a, "incidence", 0) * DEG2RAD);
399
400     float effect = attrf(a, "effectiveness", 1);
401     w->setDragScale(w->getDragScale()*effect);
402
403     _currObj = w;
404     return w;
405 }
406
407 void FGFDM::parsePropeller(XMLAttributes* a)
408 {
409     float cg[3];
410     cg[0] = attrf(a, "x");
411     cg[1] = attrf(a, "y");
412     cg[2] = attrf(a, "z");
413     float mass = attrf(a, "mass") * LBS2KG;
414     float moment = attrf(a, "moment");
415     float radius = attrf(a, "radius");
416     float speed = attrf(a, "cruise-speed") * KTS2MPS;
417     float omega = attrf(a, "cruise-rpm") * RPM2RAD;
418     float power = attrf(a, "cruise-power") * HP2W;
419     float rho = Atmosphere::getStdDensity(attrf(a, "cruise-alt") * FT2M);
420
421     // Hack, fix this pronto:
422     float engP = attrf(a, "eng-power") * HP2W;
423     float engS = attrf(a, "eng-rpm") * RPM2RAD;
424
425     Propeller* prop = new Propeller(radius, speed, omega, rho, power);
426     PistonEngine* eng = new PistonEngine(engP, engS);
427     PropEngine* thruster = new PropEngine(prop, eng, moment);
428     _airplane.addThruster(thruster, mass, cg);
429
430     if(a->hasAttribute("displacement"))
431         eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
432
433     if(a->hasAttribute("compression"))
434         eng->setCompression(attrf(a, "compression"));        
435
436     if(a->hasAttribute("turbo-mul")) {
437         float mul = attrf(a, "turbo-mul");
438         float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
439         eng->setTurboParams(mul, mp);
440     }
441
442     if(a->hasAttribute("takeoff-power")) {
443         float power0 = attrf(a, "takeoff-power") * HP2W;
444         float omega0 = attrf(a, "takeoff-rpm") * RPM2RAD;
445         prop->setTakeoff(omega0, power0);
446     }
447
448     if(a->hasAttribute("max-rpm")) {
449         float max = attrf(a, "max-rpm") * RPM2RAD;
450         float min = attrf(a, "min-rpm") * RPM2RAD;
451         thruster->setVariableProp(min, max);
452     }
453
454     char buf[64];
455     sprintf(buf, "/engines/engine[%d]", _nextEngine++);
456     EngRec* er = new EngRec();
457     er->eng = thruster;
458     er->prefix = dup(buf);
459     _thrusters.add(er);
460
461     _currObj = thruster;
462 }
463
464 // Turns a string axis name into an integer for use by the
465 // ControlMap.  Creates a new axis if this one hasn't been defined
466 // yet.
467 int FGFDM::parseAxis(const char* name)
468 {
469     int i;
470     for(i=0; i<_axes.size(); i++) {
471         AxisRec* a = (AxisRec*)_axes.get(i);
472         if(eq(a->name, name))
473             return a->handle;
474     }
475
476     // Not there, make a new one.
477     AxisRec* a = new AxisRec();
478     a->name = dup(name);
479     a->handle = _airplane.getControlMap()->newInput();
480     _axes.add(a);
481     return a->handle;
482 }
483
484 int FGFDM::parseOutput(const char* name)
485 {
486     if(eq(name, "THROTTLE"))  return ControlMap::THROTTLE;
487     if(eq(name, "MIXTURE"))   return ControlMap::MIXTURE;
488     if(eq(name, "STARTER"))   return ControlMap::STARTER;
489     if(eq(name, "MAGNETOS"))  return ControlMap::MAGNETOS;
490     if(eq(name, "ADVANCE"))   return ControlMap::ADVANCE;
491     if(eq(name, "REHEAT"))    return ControlMap::REHEAT;
492     if(eq(name, "BOOST"))     return ControlMap::BOOST;
493     if(eq(name, "VECTOR"))    return ControlMap::VECTOR;
494     if(eq(name, "PROP"))      return ControlMap::PROP;
495     if(eq(name, "BRAKE"))     return ControlMap::BRAKE;
496     if(eq(name, "STEER"))     return ControlMap::STEER;
497     if(eq(name, "EXTEND"))    return ControlMap::EXTEND;
498     if(eq(name, "INCIDENCE")) return ControlMap::INCIDENCE;
499     if(eq(name, "FLAP0"))     return ControlMap::FLAP0;
500     if(eq(name, "FLAP1"))     return ControlMap::FLAP1;
501     if(eq(name, "SLAT"))      return ControlMap::SLAT;
502     if(eq(name, "SPOILER"))   return ControlMap::SPOILER;
503     SG_LOG(SG_FLIGHT,SG_ALERT,"Unrecognized control type '"
504            << name << "' in YASim aircraft description.");
505     exit(1);
506
507 }
508
509 void FGFDM::parseWeight(XMLAttributes* a)
510 {
511     WeightRec* wr = new WeightRec();
512
513     float v[3];
514     v[0] = attrf(a, "x");
515     v[1] = attrf(a, "y");
516     v[2] = attrf(a, "z");
517
518     wr->prop = dup(a->getValue("mass-prop"));
519     wr->size = attrf(a, "size", 0);
520     wr->handle = _airplane.addWeight(v, wr->size);
521
522     _weights.add(wr);
523 }
524
525 bool FGFDM::eq(const char* a, const char* b)
526 {
527     // Figure it out for yourself. :)
528     while(*a && *b && *a == *b) { a++; b++; }
529     return !(*a || *b);
530 }
531
532 char* FGFDM::dup(const char* s)
533 {
534     int len=0;
535     while(s[len++]);
536     char* s2 = new char[len+1];
537     char* p = s2;
538     while((*p++ = *s++));
539     s2[len] = 0;
540     return s2;
541 }
542
543 int FGFDM::attri(XMLAttributes* atts, char* attr)
544 {
545     if(!atts->hasAttribute(attr)) {
546         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
547                "' in YASim aircraft description");
548         exit(1);
549     }
550     return attri(atts, attr, 0);
551 }
552
553 int FGFDM::attri(XMLAttributes* atts, char* attr, int def)
554 {
555     const char* val = atts->getValue(attr);
556     if(val == 0) return def;
557     else         return atol(val);
558 }
559
560 float FGFDM::attrf(XMLAttributes* atts, char* attr)
561 {
562     if(!atts->hasAttribute(attr)) {
563         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
564                "' in YASim aircraft description");
565         exit(1);
566     }
567     return attrf(atts, attr, 0);
568 }
569
570 float FGFDM::attrf(XMLAttributes* atts, char* attr, float def)
571 {
572     const char* val = atts->getValue(attr);
573     if(val == 0) return def;
574     else         return (float)atof(val);    
575 }
576
577 }; // namespace yasim