]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
7515dc6392594aaf316e08d2c64e7a2127b5b0f0
[flightgear.git] / src / FDM / YASim / Airplane.cpp
1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
3 #include "Gear.hpp"
4 #include "Math.hpp"
5 #include "Glue.hpp"
6 #include "RigidBody.hpp"
7 #include "Surface.hpp"
8 #include "Thruster.hpp"
9
10 #include "Airplane.hpp"
11 namespace yasim {
12
13 Airplane::Airplane()
14 {
15     _emptyWeight = 0;
16     _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
17     _wing = 0;
18     _tail = 0;
19     _ballast = 0;
20     _cruiseP = 0;
21     _cruiseT = 0;
22     _cruiseSpeed = 0;
23     _cruiseWeight = 0;
24     _approachP = 0;
25     _approachT = 0;
26     _approachSpeed = 0;
27     _approachAoA = 0;
28     _approachWeight = 0;
29
30     _dragFactor = 1;
31     _liftRatio = 1;
32     _cruiseAoA = 0;
33     _tailIncidence = 0;
34 }
35
36 Airplane::~Airplane()
37 {
38     int i;
39     for(i=0; i<_fuselages.size(); i++)
40         delete (Fuselage*)_fuselages.get(i);
41     for(i=0; i<_tanks.size(); i++)
42         delete (Tank*)_tanks.get(i);
43     for(i=0; i<_thrusters.size(); i++)
44         delete (ThrustRec*)_thrusters.get(i);
45     for(i=0; i<_gears.size(); i++)
46         delete (GearRec*)_gears.get(i);
47     for(i=0; i<_surfs.size(); i++)
48         delete (Surface*)_surfs.get(i);    
49     for(i=0; i<_contacts.size(); i++)
50         delete[] (float*)_contacts.get(i);
51 }
52
53 void Airplane::iterate(float dt)
54 {
55     _model.iterate();
56
57     // FIXME: Consume fuel
58 }
59
60 ControlMap* Airplane::getControlMap()
61 {
62     return &_controls;
63 }
64
65 Model* Airplane::getModel()
66 {
67     return &_model;
68 }
69
70 void Airplane::getPilotAccel(float* out)
71 {
72     State* s = _model.getState();
73
74     // Gravity
75     Glue::geodUp(s->pos, out);
76     Math::mul3(-9.8, out, out);
77
78     // The regular acceleration
79     float tmp[3];
80     Math::mul3(-1, s->acc, tmp);
81     Math::add3(tmp, out, out);
82
83     // Convert to aircraft coordinates
84     Math::vmul33(s->orient, out, out);
85
86     // FIXME: rotational & centripetal acceleration needed
87 }
88
89 void Airplane::setPilotPos(float* pos)
90 {
91     int i;
92     for(i=0; i<3; i++) _pilotPos[i] = pos[i];
93 }
94
95 void Airplane::getPilotPos(float* out)
96 {
97     int i;
98     for(i=0; i<3; i++) out[i] = _pilotPos[i];
99 }
100
101 int Airplane::numGear()
102 {
103     return _gears.size();
104 }
105
106 Gear* Airplane::getGear(int g)
107 {
108     return ((GearRec*)_gears.get(g))->gear;
109 }
110
111 void Airplane::setGearState(bool down, float dt)
112 {
113     int i;
114     for(i=0; i<_gears.size(); i++) {
115         GearRec* gr = (GearRec*)_gears.get(i);
116         if(gr->time == 0) {
117             // Non-extensible
118             gr->gear->setExtension(1);
119             gr->surf->setXDrag(1);
120             gr->surf->setYDrag(1);
121             gr->surf->setZDrag(1);
122             continue;
123         }
124
125         float diff = dt / gr->time;
126         if(!down) diff = -diff;
127         float ext = gr->gear->getExtension() + diff;
128         if(ext < 0) ext = 0;
129         if(ext > 1) ext = 1;
130
131         gr->gear->setExtension(ext);
132         gr->surf->setXDrag(ext);
133         gr->surf->setYDrag(ext);
134         gr->surf->setZDrag(ext);
135     }
136 }
137
138 void Airplane::setApproach(float speed, float altitude)
139 {
140     // The zero AoA will become a calculated stall AoA in compile()
141     setApproach(speed, altitude, 0);
142 }
143
144 void Airplane::setApproach(float speed, float altitude, float aoa)
145 {
146     _approachSpeed = speed;
147     _approachP = Atmosphere::getStdPressure(altitude);
148     _approachT = Atmosphere::getStdTemperature(altitude);
149     _approachAoA = aoa;
150 }
151  
152 void Airplane::setCruise(float speed, float altitude)
153 {
154     _cruiseSpeed = speed;
155     _cruiseP = Atmosphere::getStdPressure(altitude);
156     _cruiseT = Atmosphere::getStdTemperature(altitude);
157     _cruiseAoA = 0;
158     _tailIncidence = 0;
159 }
160
161 void Airplane::addApproachControl(int control, float val)
162 {
163     Control* c = new Control();
164     c->control = control;
165     c->val = val;
166     _approachControls.add(c);
167 }
168
169 void Airplane::addCruiseControl(int control, float val)
170 {
171     Control* c = new Control();
172     c->control = control;
173     c->val = val;
174     _cruiseControls.add(c);
175 }
176
177 int Airplane::numTanks()
178 {
179     return _tanks.size();
180 }
181
182 float Airplane::getFuel(int tank)
183 {
184     return ((Tank*)_tanks.get(tank))->fill;
185 }
186
187 float Airplane::getFuelDensity(int tank)
188 {
189     return ((Tank*)_tanks.get(tank))->density;
190 }
191
192 void Airplane::setWeight(float weight)
193 {
194     _emptyWeight = weight;
195 }
196
197 void Airplane::setWing(Wing* wing)
198 {
199     _wing = wing;
200 }
201
202 void Airplane::setTail(Wing* tail)
203 {
204     _tail = tail;
205 }
206
207 void Airplane::addVStab(Wing* vstab)
208 {
209     _vstabs.add(vstab);
210 }
211
212 void Airplane::addFuselage(float* front, float* back, float width,
213                            float taper, float mid)
214 {
215     Fuselage* f = new Fuselage();
216     int i;
217     for(i=0; i<3; i++) {
218         f->front[i] = front[i];
219         f->back[i]  = back[i];
220     }
221     f->width = width;
222     f->taper = taper;
223     f->mid = mid;
224     _fuselages.add(f);
225 }
226
227 int Airplane::addTank(float* pos, float cap, float density)
228 {
229     Tank* t = new Tank();
230     int i;
231     for(i=0; i<3; i++) t->pos[i] = pos[i];
232     t->cap = cap;
233     t->fill = cap;
234     t->density = density;
235     t->handle = 0xffffffff;
236     return _tanks.add(t);
237 }
238
239 void Airplane::addGear(Gear* gear, float transitionTime)
240 {
241     GearRec* g = new GearRec();
242     g->gear = gear;
243     g->surf = 0;
244     g->time = transitionTime;
245     _gears.add(g);
246 }
247
248 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
249 {
250     ThrustRec* t = new ThrustRec();
251     t->thruster = thruster;
252     t->mass = mass;
253     int i;
254     for(i=0; i<3; i++) t->cg[i] = cg[i];
255     _thrusters.add(t);
256 }
257
258 void Airplane::addBallast(float* pos, float mass)
259 {
260     _model.getBody()->addMass(mass, pos);
261     _ballast += mass;
262 }
263
264 int Airplane::addWeight(float* pos, float size)
265 {
266     WeightRec* wr = new WeightRec();
267     wr->handle = _model.getBody()->addMass(0, pos);
268
269     wr->surf = new Surface();
270     wr->surf->setPosition(pos);
271     wr->surf->setTotalDrag(size*size);
272     _model.addSurface(wr->surf);
273     _surfs.add(wr->surf);
274
275     return _weights.add(wr);
276 }
277
278 void Airplane::setWeight(int handle, float mass)
279 {
280     WeightRec* wr = (WeightRec*)_weights.get(handle);
281
282     _model.getBody()->setMass(wr->handle, mass);
283
284     // Kill the aerodynamic drag if the mass is exactly zero.  This is
285     // how we simulate droppable stores.
286     if(mass == 0) {
287         wr->surf->setXDrag(0);
288         wr->surf->setYDrag(0);
289         wr->surf->setZDrag(0);
290     } else {
291         wr->surf->setXDrag(1);
292         wr->surf->setYDrag(1);
293         wr->surf->setZDrag(1);
294     }
295 }
296
297 void Airplane::setFuelFraction(float frac)
298 {
299     int i;
300     for(i=0; i<_tanks.size(); i++) {
301         Tank* t = (Tank*)_tanks.get(i);
302         _model.getBody()->setMass(t->handle, t->cap * frac);
303     }
304 }
305
306 float Airplane::getDragCoefficient()
307 {
308     return _dragFactor;
309 }
310
311 float Airplane::getLiftRatio()
312 {
313     return _liftRatio;
314 }
315
316 float Airplane::getCruiseAoA()
317 {
318     return _cruiseAoA;
319 }
320
321 float Airplane::getTailIncidence()
322 {
323     return _tailIncidence;
324 }
325
326 char* Airplane::getFailureMsg()
327 {
328     return _failureMsg;
329 }
330
331 int Airplane::getSolutionIterations()
332 {
333     return _solutionIterations;
334 }
335
336 void Airplane::setupState(float aoa, float speed, State* s)
337 {
338     float cosAoA = Math::cos(aoa);
339     float sinAoA = Math::sin(aoa);
340     s->orient[0] =  cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
341     s->orient[3] =       0; s->orient[4] = 1; s->orient[5] =      0;
342     s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
343
344     s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
345
346     int i;
347     for(i=0; i<3; i++)
348         s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
349
350     // Put us 1m above the origin, or else the gravity computation in
351     // Model goes nuts
352     s->pos[2] = 1;
353 }
354
355 void Airplane::addContactPoint(float* pos)
356 {
357     float* cp = new float[3];
358     cp[0] = pos[0];
359     cp[1] = pos[1];
360     cp[2] = pos[2];
361     _contacts.add(cp);
362 }
363
364 float Airplane::compileWing(Wing* w)
365 {
366     // The tip of the wing is a contact point
367     float tip[3];
368     w->getTip(tip);
369     addContactPoint(tip);
370     if(w->isMirrored()) {
371         tip[1] *= -1;
372         addContactPoint(tip);
373     }
374
375     // Make sure it's initialized.  The surfaces will pop out with
376     // total drag coefficients equal to their areas, which is what we
377     // want.
378     w->compile();
379
380     float wgt = 0;
381     int i;
382     for(i=0; i<w->numSurfaces(); i++) {
383         Surface* s = (Surface*)w->getSurface(i);
384
385         float td = s->getTotalDrag();
386         s->setTotalDrag(td);
387
388         _model.addSurface(s);
389
390         float mass = w->getSurfaceWeight(i);
391         mass = mass * Math::sqrt(mass);
392         float pos[3];
393         s->getPosition(pos);
394         _model.getBody()->addMass(mass, pos);
395         wgt += mass;
396     }
397     return wgt;
398 }
399
400 float Airplane::compileFuselage(Fuselage* f)
401 {
402     // The front and back are contact points
403     addContactPoint(f->front);
404     addContactPoint(f->back);
405
406     float wgt = 0;
407     float fwd[3];
408     Math::sub3(f->front, f->back, fwd);
409     float len = Math::mag3(fwd);
410     float wid = f->width;
411     int segs = (int)Math::ceil(len/wid);
412     float segWgt = len*wid/segs;
413     int j;
414     for(j=0; j<segs; j++) {
415         float frac = (j+0.5) / segs;
416
417         float scale = 1;
418         if(frac < f->mid)
419             scale = f->taper+(1-f->taper) * (frac / f->mid);
420         else
421             scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
422
423         // Where are we?
424         float pos[3];
425         Math::mul3(frac, fwd, pos);
426         Math::add3(f->back, pos, pos);
427
428         // _Mass_ weighting goes as surface area^(3/2)
429         float mass = scale*segWgt * Math::sqrt(scale*segWgt);
430         _model.getBody()->addMass(mass, pos);
431         wgt += mass;
432
433         // Make a Surface too
434         Surface* s = new Surface();
435         s->setPosition(pos);
436         float sideDrag = len/wid;
437         s->setYDrag(sideDrag);
438         s->setZDrag(sideDrag);
439         s->setTotalDrag(scale*segWgt);
440
441         // FIXME: fails for fuselages aligned along the Y axis
442         float o[9];
443         float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
444         Math::unit3(fwd, x);
445         y[0] = 0; y[1] = 1; y[2] = 0;
446         Math::cross3(x, y, z);
447         s->setOrientation(o);
448
449         _model.addSurface(s);
450         _surfs.add(s);
451     }
452     return wgt;
453 }
454
455 // FIXME: should probably add a mass for the gear, too
456 void Airplane::compileGear(GearRec* gr)
457 {
458     Gear* g = gr->gear;
459
460     // Make a Surface object for the aerodynamic behavior
461     Surface* s = new Surface();
462     gr->surf = s;
463
464     // Put the surface at the half-way point on the gear strut, give
465     // it a drag coefficient equal to a square of the same dimension
466     // (gear are really draggy) and make it symmetric.  Assume that
467     // the "length" of the gear is 3x the compression distance
468     float pos[3], cmp[3];
469     g->getCompression(cmp);
470     float length = 3 * Math::mag3(cmp);
471     g->getPosition(pos);
472     Math::mul3(0.5, cmp, cmp);
473     Math::add3(pos, cmp, pos);
474
475     s->setPosition(pos);
476     s->setTotalDrag(length*length);
477
478     _model.addGear(g);
479     _model.addSurface(s);
480     _surfs.add(s);
481 }
482
483 void Airplane::compileContactPoints()
484 {
485     // Figure it will compress by 20cm
486     float comp[3];
487     float DIST = 0.2;
488     comp[0] = 0; comp[1] = 0; comp[2] = DIST;
489
490     // Give it a spring constant such that at full compression it will
491     // hold up 10 times the planes mass.  That's about right.  Yeah.
492     float mass = _model.getBody()->getTotalMass();
493     float spring = (1/DIST) * 9.8 * 10 * mass;
494     float damp = 2 * Math::sqrt(spring * mass);
495
496     int i;
497     for(i=0; i<_contacts.size(); i++) {
498         float *cp = (float*)_contacts.get(i);
499
500         Gear* g = new Gear();
501         g->setPosition(cp);
502         
503         g->setCompression(comp);
504         g->setSpring(spring);
505         g->setDamping(damp);
506         g->setBrake(1);
507
508         // I made these up
509         g->setStaticFriction(0.6);
510         g->setDynamicFriction(0.5);
511
512         _model.addGear(g);
513     }
514 }
515
516 void Airplane::compile()
517 {
518     double ground[3];
519     ground[0] = 0; ground[1] = 0; ground[2] = 1;
520     _model.setGroundPlane(ground, -100000);
521
522     RigidBody* body = _model.getBody();
523     int firstMass = body->numMasses();
524
525     // Generate the point masses for the plane.  Just use unitless
526     // numbers for a first pass, then go back through and rescale to
527     // make the weight right.
528     float aeroWgt = 0;
529
530     // The Wing objects
531     aeroWgt += compileWing(_wing);
532     aeroWgt += compileWing(_tail);
533     int i;
534     for(i=0; i<_vstabs.size(); i++) {
535         aeroWgt += compileWing((Wing*)_vstabs.get(i)); 
536     }
537     
538     // The fuselage(s)
539     for(i=0; i<_fuselages.size(); i++) {
540         aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
541     }
542
543     // Count up the absolute weight we have
544     float nonAeroWgt = _ballast;
545     for(i=0; i<_thrusters.size(); i++)
546         nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
547
548     // Rescale to the specified empty weight
549     float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
550     for(i=firstMass; i<body->numMasses(); i++)
551         body->setMass(i, body->getMass(i)*wscale);
552
553     // Add the thruster masses
554     for(i=0; i<_thrusters.size(); i++) {
555         ThrustRec* t = (ThrustRec*)_thrusters.get(i);
556         body->addMass(t->mass, t->cg);
557     }
558
559     // Add the tanks, empty for now.
560     float totalFuel = 0;
561     for(i=0; i<_tanks.size(); i++) { 
562         Tank* t = (Tank*)_tanks.get(i); 
563         t->handle = body->addMass(0, t->pos);
564         totalFuel += t->cap;
565     }
566     _cruiseWeight = _emptyWeight + totalFuel*0.5;
567     _approachWeight = _emptyWeight + totalFuel*0.2;
568
569     body->recalc();
570
571     // Add surfaces for the landing gear.
572     for(i=0; i<_gears.size(); i++)
573         compileGear((GearRec*)_gears.get(i));
574
575     // The Thruster objects
576     for(i=0; i<_thrusters.size(); i++) {
577         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
578         tr->handle = _model.addThruster(tr->thruster);
579     }
580
581     // Ground effect
582     float gepos[3];
583     float gespan = _wing->getGroundEffect(gepos);
584     _model.setGroundEffect(gepos, gespan, .3);
585
586     solveGear();
587     solve();
588
589     // Do this after solveGear, because it creates "gear" objects that
590     // we don't want to affect.
591     compileContactPoints();
592
593     // Drop the gear (use a really big dt)
594     setGearState(true, 1000000);
595 }
596
597 void Airplane::solveGear()
598 {
599     float cg[3], pos[3];
600     _model.getBody()->getCG(cg);
601
602     // Calculate spring constant weightings for the gear.  Weight by
603     // the inverse of the distance to the c.g. in the XY plane, which
604     // should be correct for most gear arrangements.  Add 50cm of
605     // "buffer" to keep things from blowing up with aircraft with a
606     // single gear very near the c.g. (AV-8, for example).
607     float total = 0;
608     int i;
609     for(i=0; i<_gears.size(); i++) {
610         GearRec* gr = (GearRec*)_gears.get(i);
611         Gear* g = gr->gear;
612         g->getPosition(pos);
613         Math::sub3(cg, pos, pos);
614         gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
615         total += gr->wgt;
616     }
617
618     // Renormalize so they sum to 1
619     for(i=0; i<_gears.size(); i++)
620         ((GearRec*)_gears.get(i))->wgt /= total;
621     
622     // The force at max compression should be sufficient to stop a
623     // plane moving downwards at 3x the approach descent rate.  Assume
624     // a 3 degree approach.
625     float descentRate = 3*_approachSpeed/19.1;
626
627     // Spread the kinetic energy according to the gear weights.  This
628     // will results in an equal compression fraction (not distance) of
629     // each gear.
630     float energy = 0.5*_approachWeight*descentRate*descentRate;
631
632     for(i=0; i<_gears.size(); i++) {
633         GearRec* gr = (GearRec*)_gears.get(i);
634         float e = energy * gr->wgt;
635         float comp[3];
636         gr->gear->getCompression(comp);
637         float len = Math::mag3(comp);
638
639         // Energy in a spring: e = 0.5 * k * len^2
640         float k = 2 * e / (len*len);
641
642         gr->gear->setSpring(k);
643
644         // Critically damped (too damped, too!)
645         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
646
647         // These are pretty generic
648         gr->gear->setStaticFriction(0.8);
649         gr->gear->setDynamicFriction(0.7);
650     }
651 }
652
653 void Airplane::stabilizeThrust()
654 {
655     int i;
656     for(i=0; i<_thrusters.size(); i++)
657         _model.getThruster(i)->stabilize();
658 }
659
660 void Airplane::runCruise()
661 {
662     setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
663     _model.setState(&_cruiseState);
664     _model.setAir(_cruiseP, _cruiseT);
665
666     // The control configuration
667     _controls.reset();
668     int i;
669     for(i=0; i<_cruiseControls.size(); i++) {
670         Control* c = (Control*)_cruiseControls.get(i);
671         _controls.setInput(c->control, c->val);
672     }
673     _controls.applyControls();
674
675     // The local wind
676     float wind[3];
677     Math::mul3(-1, _cruiseState.v, wind);
678     Math::vmul33(_cruiseState.orient, wind, wind);
679  
680     // Gear are up (if they're non-retractable, this is a noop)
681     setGearState(false, 100000);
682     
683     // Cruise is by convention at 50% tank capacity
684     setFuelFraction(0.5);
685    
686     // Set up the thruster parameters and iterate until the thrust
687     // stabilizes.
688     for(i=0; i<_thrusters.size(); i++) {
689         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
690         t->setWind(wind);
691         t->setAir(_cruiseP, _cruiseT);
692     }
693     stabilizeThrust();
694
695     // Precompute thrust in the model, and calculate aerodynamic forces
696     _model.getBody()->reset();
697     _model.initIteration();
698     _model.calcForces(&_cruiseState);
699 }
700
701 void Airplane::runApproach()
702 {
703     setupState(_approachAoA, _approachSpeed, &_approachState);
704     _model.setState(&_approachState);
705     _model.setAir(_approachP, _approachT);
706
707     // The control configuration
708     _controls.reset();
709     int i;
710     for(i=0; i<_approachControls.size(); i++) {
711         Control* c = (Control*)_approachControls.get(i);
712         _controls.setInput(c->control, c->val);
713     }
714     _controls.applyControls();
715
716     // The local wind
717     float wind[3];
718     Math::mul3(-1, _approachState.v, wind);
719     Math::vmul33(_approachState.orient, wind, wind);
720     
721     // Approach is by convention at 20% tank capacity
722     setFuelFraction(0.2);
723
724     // Gear are down
725     setGearState(true, 100000);
726
727     // Run the thrusters until they get to a stable setting.  FIXME:
728     // this is lots of wasted work.
729     for(i=0; i<_thrusters.size(); i++) {
730         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
731         t->setWind(wind);
732         t->setAir(_approachP, _approachT);
733     }
734     stabilizeThrust();
735
736     // Precompute thrust in the model, and calculate aerodynamic forces
737     _model.getBody()->reset();
738     _model.initIteration();
739     _model.calcForces(&_approachState);
740 }
741
742 void Airplane::applyDragFactor(float factor)
743 {
744     float applied = Math::sqrt(factor);
745     _dragFactor *= applied;
746     _wing->setDragScale(_wing->getDragScale() * applied);
747     _tail->setDragScale(_tail->getDragScale() * applied);
748     int i;
749     for(i=0; i<_vstabs.size(); i++) {
750         Wing* w = (Wing*)_vstabs.get(i);
751         w->setDragScale(w->getDragScale() * applied);
752     }
753     for(i=0; i<_surfs.size(); i++) {
754         Surface* s = (Surface*)_surfs.get(i);
755         s->setTotalDrag(s->getTotalDrag() * applied);
756     }
757 }
758
759 void Airplane::applyLiftRatio(float factor)
760 {
761     float applied = Math::sqrt(factor);
762     _liftRatio *= applied;
763     _wing->setLiftRatio(_wing->getLiftRatio() * applied);
764     _tail->setLiftRatio(_tail->getLiftRatio() * applied);
765     int i;
766     for(i=0; i<_vstabs.size(); i++) {
767         Wing* w = (Wing*)_vstabs.get(i);
768         w->setLiftRatio(w->getLiftRatio() * applied);
769     }
770 }
771
772 float Airplane::clamp(float val, float min, float max)
773 {
774     if(val < min) return min;
775     if(val > max) return max;
776     return val;
777 }
778
779 float Airplane::normFactor(float f)
780 {
781     if(f < 0) f = -f;
782     if(f < 1) f = 1/f;
783     return f;
784 }
785
786 void Airplane::solve()
787 {
788     static const float ARCMIN = 0.0002909;
789
790     float tmp[3];
791     _solutionIterations = 0;
792     _failureMsg = 0;
793     while(1) {
794         if(_solutionIterations++ > 10000) {
795             _failureMsg = "Solution failed to converge after 10000 iterations";
796             return;
797         }
798
799         // Run an iteration at cruise, and extract the needed numbers:
800         runCruise();
801
802         _model.getThrust(tmp);
803         float thrust = tmp[0];
804
805         _model.getBody()->getAccel(tmp);
806         float xforce = _cruiseWeight * tmp[0];
807         float clift0 = _cruiseWeight * tmp[2];
808
809         _model.getBody()->getAngularAccel(tmp);
810         float pitch0 = tmp[1];
811
812         // Run an approach iteration, and do likewise
813         runApproach();
814
815         _model.getBody()->getAccel(tmp);
816         float alift = _approachWeight * tmp[2];
817
818         // Modify the cruise AoA a bit to get a derivative
819         _cruiseAoA += ARCMIN;
820         runCruise();
821         _cruiseAoA -= ARCMIN;
822
823         _model.getBody()->getAccel(tmp);
824         float clift1 = _cruiseWeight * tmp[2];
825
826         // Do the same with the tail incidence
827         _tail->setIncidence(_tailIncidence + ARCMIN);
828         runCruise();
829         _tail->setIncidence(_tailIncidence);
830
831         _model.getBody()->getAngularAccel(tmp);
832         float pitch1 = tmp[1];
833
834         // Now calculate:
835         float awgt = 9.8 * _approachWeight;
836
837         float dragFactor = thrust / (thrust-xforce);
838         float liftFactor = awgt / (awgt+alift);
839         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
840         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
841
842         // Sanity:
843         if(dragFactor <= 0) {
844             _failureMsg = "Zero or negative drag adjustment.";
845             return;
846         } else if(liftFactor <= 0) {
847             _failureMsg = "Zero or negative lift adjustment.";
848             return;
849         }
850
851         // And apply:
852         applyDragFactor(dragFactor);
853         applyLiftRatio(liftFactor);
854
855         // DON'T do the following until the above are sane
856         if(normFactor(dragFactor) > 1.1
857            || normFactor(liftFactor) > 1.1)
858         {
859             continue;
860         }
861
862         // OK, now we can adjust the minor variables
863         _cruiseAoA += 0.5*aoaDelta;
864         _tailIncidence += 0.5*tailDelta;
865         
866         _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
867         _tailIncidence = clamp(_tailIncidence, -.174, .174);
868
869         if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
870            aoaDelta < .000017   && tailDelta < .000017)
871         {
872             break;
873         }
874     }
875
876     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
877         _failureMsg = "Drag factor beyond reasonable bounds.";
878         return;
879     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
880         _failureMsg = "Lift ratio beyond reasonable bounds.";
881         return;
882     } else if(Math::abs(_cruiseAoA) >= .174) {
883         _failureMsg = "Cruise AoA > 10 degrees";
884         return;
885     } else if(Math::abs(_tailIncidence) >= .174) {
886         _failureMsg = "Tail incidence > 10 degrees";
887         return;
888     }
889 }
890 }; // namespace yasim