]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/FGFDM.cpp
Patch from Melchior Franz:
[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         _airplane.addGear(g);
178     } else if(eq(name, "fuselage")) {
179         float b[3];
180         v[0] = attrf(a, "ax");
181         v[1] = attrf(a, "ay");
182         v[2] = attrf(a, "az");
183         b[0] = attrf(a, "bx");
184         b[1] = attrf(a, "by");
185         b[2] = attrf(a, "bz");
186         float taper = attrf(a, "taper", 1);
187         float mid = attrf(a, "midpoint", 0.5);
188         _airplane.addFuselage(v, b, attrf(a, "width"), taper, mid);
189     } else if(eq(name, "tank")) {
190         v[0] = attrf(a, "x");
191         v[1] = attrf(a, "y");
192         v[2] = attrf(a, "z");
193         float density = 6.0; // gasoline, in lbs/gal
194         if(a->hasAttribute("jet")) density = 6.72; 
195         density *= LBS2KG*CM2GALS;
196         _airplane.addTank(v, attrf(a, "capacity") * LBS2KG, density);
197     } else if(eq(name, "ballast")) {
198         v[0] = attrf(a, "x");
199         v[1] = attrf(a, "y");
200         v[2] = attrf(a, "z");
201         _airplane.addBallast(v, attrf(a, "mass") * LBS2KG);
202     } else if(eq(name, "weight")) {
203         parseWeight(a);
204     } else if(eq(name, "stall")) {
205         Wing* w = (Wing*)_currObj;
206         w->setStall(attrf(a, "aoa") * DEG2RAD);
207         w->setStallWidth(attrf(a, "width", 2) * DEG2RAD);
208         w->setStallPeak(attrf(a, "peak", 1.5));
209     } else if(eq(name, "flap0")) {
210         ((Wing*)_currObj)->setFlap0(attrf(a, "start"), attrf(a, "end"),
211                                     attrf(a, "lift"), attrf(a, "drag"));
212     } else if(eq(name, "flap1")) {
213         ((Wing*)_currObj)->setFlap1(attrf(a, "start"), attrf(a, "end"),
214                                     attrf(a, "lift"), attrf(a, "drag"));
215     } else if(eq(name, "slat")) {
216         ((Wing*)_currObj)->setSlat(attrf(a, "start"), attrf(a, "end"),
217                                    attrf(a, "aoa"), attrf(a, "drag"));
218     } else if(eq(name, "spoiler")) {
219         ((Wing*)_currObj)->setSpoiler(attrf(a, "start"), attrf(a, "end"),
220                                       attrf(a, "lift"), attrf(a, "drag"));
221     } else if(eq(name, "actionpt")) {
222         v[0] = attrf(a, "x");
223         v[1] = attrf(a, "y");
224         v[2] = attrf(a, "z");
225         ((Thruster*)_currObj)->setPosition(v);
226     } else if(eq(name, "dir")) {
227         v[0] = attrf(a, "x");
228         v[1] = attrf(a, "y");
229         v[2] = attrf(a, "z");
230         ((Thruster*)_currObj)->setDirection(v);
231     } else if(eq(name, "control-setting")) {
232         // A cruise or approach control setting
233         const char* axis = a->getValue("axis");
234         float value = attrf(a, "value", 0);
235         if(_cruiseCurr)
236             _airplane.addCruiseControl(parseAxis(axis), value);
237         else
238             _airplane.addApproachControl(parseAxis(axis), value);
239     } else if(eq(name, "control-input")) {
240
241         // A mapping of input property to a control
242         int axis = parseAxis(a->getValue("axis"));
243         int control = parseOutput(a->getValue("control"));
244         int opt = 0;
245         opt |= a->hasAttribute("split") ? ControlMap::OPT_SPLIT : 0;
246         opt |= a->hasAttribute("invert") ? ControlMap::OPT_INVERT : 0;
247         opt |= a->hasAttribute("square") ? ControlMap::OPT_SQUARE : 0;
248         
249         ControlMap* cm = _airplane.getControlMap();
250         if(a->hasAttribute("src0")) {
251                            cm->addMapping(axis, control, _currObj, opt,
252                            attrf(a, "src0"), attrf(a, "src1"), 
253                            attrf(a, "dst0"), attrf(a, "dst1"));
254         } else {
255             cm->addMapping(axis, control, _currObj, opt);
256         }
257     } else if(eq(name, "control-output")) {
258         // A property output for a control on the current object
259         ControlMap* cm = _airplane.getControlMap();
260         int type = parseOutput(a->getValue("control"));
261         int handle = cm->getOutputHandle(_currObj, type);
262
263         PropOut* p = new PropOut();
264         p->prop = fgGetNode(a->getValue("prop"), true);
265         p->handle = handle;
266         p->type = type;
267         p->left = !(a->hasAttribute("side") &&
268                         eq("right", a->getValue("side")));
269         p->min = attrf(a, "min", cm->rangeMin(type));
270         p->max = attrf(a, "max", cm->rangeMax(type));
271         _controlProps.add(p);
272
273     } else if(eq(name, "control-speed")) {
274         ControlMap* cm = _airplane.getControlMap();
275         int type = parseOutput(a->getValue("control"));
276         int handle = cm->getOutputHandle(_currObj, type);
277         float time = attrf(a, "transition-time", 0);
278         
279         cm->setTransitionTime(handle, time);
280     } else {
281         SG_LOG(SG_FLIGHT,SG_ALERT,"Unexpected tag '"
282                << name << "' found in YASim aircraft description");
283         exit(1);
284     }
285 }
286
287 void FGFDM::getExternalInput(float dt)
288 {
289     // The control axes
290     ControlMap* cm = _airplane.getControlMap();
291     cm->reset();
292     int i;
293     for(i=0; i<_axes.size(); i++) {
294         AxisRec* a = (AxisRec*)_axes.get(i);
295         float val = fgGetFloat(a->name, 0);
296         cm->setInput(a->handle, val);
297     }
298     cm->applyControls(dt);
299
300     // Weights
301     for(i=0; i<_weights.size(); i++) {
302         WeightRec* wr = (WeightRec*)_weights.get(i);
303         _airplane.setWeight(wr->handle, fgGetFloat(wr->prop));
304     }
305 }
306
307 void FGFDM::setOutputProperties()
308 {
309     char buf[256];
310     int i;
311
312     ControlMap* cm = _airplane.getControlMap();
313     for(i=0; i<_controlProps.size(); i++) {
314         PropOut* p = (PropOut*)_controlProps.get(i);
315         float val = (p->left
316                      ? cm->getOutput(p->handle)
317                      : cm->getOutputR(p->handle));
318         float rmin = cm->rangeMin(p->type);
319         float rmax = cm->rangeMax(p->type);
320         float frac = (val - rmin) / (rmax - rmin);
321         val = frac*(p->max - p->min) + p->min;
322         p->prop->setFloatValue(val);
323     }
324
325     float fuelDensity = 718.95; // default to gasoline: ~6 lb/gal
326     for(i=0; i<_airplane.numTanks(); i++) {
327         fuelDensity = _airplane.getFuelDensity(i);
328         sprintf(buf, "/consumables/fuel/tank[%d]/level-gal_us", i);
329         fgSetFloat(buf, CM2GALS*_airplane.getFuel(i)/fuelDensity);
330     }
331
332     for(i=0; i<_thrusters.size(); i++) {
333         EngRec* er = (EngRec*)_thrusters.get(i);
334         Thruster* t = er->eng;
335
336         sprintf(buf, "%s/fuel-flow-gph", er->prefix);
337         fgSetFloat(buf, (t->getFuelFlow()/fuelDensity) * 3600 * CM2GALS);
338
339         if(t->getPropEngine()) {
340             PropEngine* p = t->getPropEngine();
341
342             sprintf(buf, "%s/rpm", er->prefix);
343             fgSetFloat(buf, p->getOmega() / RPM2RAD);
344         }
345
346         if(t->getPistonEngine()) {
347             PistonEngine* p = t->getPistonEngine();
348             
349             sprintf(buf, "%s/mp-osi", er->prefix);
350             fgSetFloat(buf, p->getMP() * (1/INHG2PA));
351
352             sprintf(buf, "%s/egt-degf", er->prefix);
353             fgSetFloat(buf, p->getEGT() * K2DEGF + 459.4);
354         }
355
356         if(t->getJet()) {
357             Jet* j = t->getJet();
358
359             sprintf(buf, "%s/n1", er->prefix);
360             fgSetFloat(buf, j->getN1());
361
362             sprintf(buf, "%s/n2", er->prefix);
363             fgSetFloat(buf, j->getN2());
364
365             sprintf(buf, "%s/epr", er->prefix);
366             fgSetFloat(buf, j->getEPR());
367
368             sprintf(buf, "%s/egt-degf", er->prefix);
369             fgSetFloat(buf, j->getEGT() * K2DEGF + 459.4);
370         }
371     }
372 }
373
374 Wing* FGFDM::parseWing(XMLAttributes* a, const char* type)
375 {
376     Wing* w = new Wing();
377
378     float defDihed = 0;
379     if(eq(type, "vstab"))
380         defDihed = 90;
381     else
382         w->setMirror(true);
383
384     float pos[3];
385     pos[0] = attrf(a, "x");
386     pos[1] = attrf(a, "y");
387     pos[2] = attrf(a, "z");
388     w->setBase(pos);
389
390     w->setLength(attrf(a, "length"));
391     w->setChord(attrf(a, "chord"));
392     w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
393     w->setTaper(attrf(a, "taper", 1));
394     w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
395     w->setCamber(attrf(a, "camber", 0));
396     w->setIncidence(attrf(a, "incidence", 0) * DEG2RAD);
397
398     float effect = attrf(a, "effectiveness", 1);
399     w->setDragScale(w->getDragScale()*effect);
400
401     _currObj = w;
402     return w;
403 }
404
405 void FGFDM::parsePropeller(XMLAttributes* a)
406 {
407     float cg[3];
408     cg[0] = attrf(a, "x");
409     cg[1] = attrf(a, "y");
410     cg[2] = attrf(a, "z");
411     float mass = attrf(a, "mass") * LBS2KG;
412     float moment = attrf(a, "moment");
413     float radius = attrf(a, "radius");
414     float speed = attrf(a, "cruise-speed") * KTS2MPS;
415     float omega = attrf(a, "cruise-rpm") * RPM2RAD;
416     float power = attrf(a, "cruise-power") * HP2W;
417     float rho = Atmosphere::getStdDensity(attrf(a, "cruise-alt") * FT2M);
418
419     // Hack, fix this pronto:
420     float engP = attrf(a, "eng-power") * HP2W;
421     float engS = attrf(a, "eng-rpm") * RPM2RAD;
422
423     Propeller* prop = new Propeller(radius, speed, omega, rho, power);
424     PistonEngine* eng = new PistonEngine(engP, engS);
425     PropEngine* thruster = new PropEngine(prop, eng, moment);
426     _airplane.addThruster(thruster, mass, cg);
427
428     if(a->hasAttribute("displacement"))
429         eng->setDisplacement(attrf(a, "displacement") * CIN2CM);
430
431     if(a->hasAttribute("compression"))
432         eng->setCompression(attrf(a, "compression"));        
433
434     if(a->hasAttribute("turbo-mul")) {
435         float mul = attrf(a, "turbo-mul");
436         float mp = attrf(a, "wastegate-mp", 1e6) * INHG2PA;
437         eng->setTurboParams(mul, mp);
438     }
439
440     if(a->hasAttribute("takeoff-power")) {
441         float power0 = attrf(a, "takeoff-power") * HP2W;
442         float omega0 = attrf(a, "takeoff-rpm") * RPM2RAD;
443         prop->setTakeoff(omega0, power0);
444     }
445
446     if(a->hasAttribute("max-rpm")) {
447         float max = attrf(a, "max-rpm") * RPM2RAD;
448         float min = attrf(a, "min-rpm") * RPM2RAD;
449         thruster->setVariableProp(min, max);
450     }
451
452     char buf[64];
453     sprintf(buf, "/engines/engine[%d]", _nextEngine++);
454     EngRec* er = new EngRec();
455     er->eng = thruster;
456     er->prefix = dup(buf);
457     _thrusters.add(er);
458
459     _currObj = thruster;
460 }
461
462 // Turns a string axis name into an integer for use by the
463 // ControlMap.  Creates a new axis if this one hasn't been defined
464 // yet.
465 int FGFDM::parseAxis(const char* name)
466 {
467     int i;
468     for(i=0; i<_axes.size(); i++) {
469         AxisRec* a = (AxisRec*)_axes.get(i);
470         if(eq(a->name, name))
471             return a->handle;
472     }
473
474     // Not there, make a new one.
475     AxisRec* a = new AxisRec();
476     a->name = dup(name);
477     a->handle = _airplane.getControlMap()->newInput();
478     _axes.add(a);
479     return a->handle;
480 }
481
482 int FGFDM::parseOutput(const char* name)
483 {
484     if(eq(name, "THROTTLE"))  return ControlMap::THROTTLE;
485     if(eq(name, "MIXTURE"))   return ControlMap::MIXTURE;
486     if(eq(name, "STARTER"))   return ControlMap::STARTER;
487     if(eq(name, "MAGNETOS"))  return ControlMap::MAGNETOS;
488     if(eq(name, "ADVANCE"))   return ControlMap::ADVANCE;
489     if(eq(name, "REHEAT"))    return ControlMap::REHEAT;
490     if(eq(name, "BOOST"))     return ControlMap::BOOST;
491     if(eq(name, "VECTOR"))    return ControlMap::VECTOR;
492     if(eq(name, "PROP"))      return ControlMap::PROP;
493     if(eq(name, "BRAKE"))     return ControlMap::BRAKE;
494     if(eq(name, "STEER"))     return ControlMap::STEER;
495     if(eq(name, "EXTEND"))    return ControlMap::EXTEND;
496     if(eq(name, "INCIDENCE")) return ControlMap::INCIDENCE;
497     if(eq(name, "FLAP0"))     return ControlMap::FLAP0;
498     if(eq(name, "FLAP1"))     return ControlMap::FLAP1;
499     if(eq(name, "SLAT"))      return ControlMap::SLAT;
500     if(eq(name, "SPOILER"))   return ControlMap::SPOILER;
501     if(eq(name, "CASTERING")) return ControlMap::CASTERING;
502     SG_LOG(SG_FLIGHT,SG_ALERT,"Unrecognized control type '"
503            << name << "' in YASim aircraft description.");
504     exit(1);
505
506 }
507
508 void FGFDM::parseWeight(XMLAttributes* a)
509 {
510     WeightRec* wr = new WeightRec();
511
512     float v[3];
513     v[0] = attrf(a, "x");
514     v[1] = attrf(a, "y");
515     v[2] = attrf(a, "z");
516
517     wr->prop = dup(a->getValue("mass-prop"));
518     wr->size = attrf(a, "size", 0);
519     wr->handle = _airplane.addWeight(v, wr->size);
520
521     _weights.add(wr);
522 }
523
524 bool FGFDM::eq(const char* a, const char* b)
525 {
526     // Figure it out for yourself. :)
527     while(*a && *b && *a == *b) { a++; b++; }
528     return !(*a || *b);
529 }
530
531 char* FGFDM::dup(const char* s)
532 {
533     int len=0;
534     while(s[len++]);
535     char* s2 = new char[len+1];
536     char* p = s2;
537     while((*p++ = *s++));
538     s2[len] = 0;
539     return s2;
540 }
541
542 int FGFDM::attri(XMLAttributes* atts, char* attr)
543 {
544     if(!atts->hasAttribute(attr)) {
545         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
546                "' in YASim aircraft description");
547         exit(1);
548     }
549     return attri(atts, attr, 0);
550 }
551
552 int FGFDM::attri(XMLAttributes* atts, char* attr, int def)
553 {
554     const char* val = atts->getValue(attr);
555     if(val == 0) return def;
556     else         return atol(val);
557 }
558
559 float FGFDM::attrf(XMLAttributes* atts, char* attr)
560 {
561     if(!atts->hasAttribute(attr)) {
562         SG_LOG(SG_FLIGHT,SG_ALERT,"Missing '" << attr <<
563                "' in YASim aircraft description");
564         exit(1);
565     }
566     return attrf(atts, attr, 0);
567 }
568
569 float FGFDM::attrf(XMLAttributes* atts, char* attr, float def)
570 {
571     const char* val = atts->getValue(attr);
572     if(val == 0) return def;
573     else         return (float)atof(val);    
574 }
575
576 }; // namespace yasim