]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
Oops. Stray checkin. Revert.
[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 // gadgets
14 inline float norm(float f) { return f<1 ? 1/f : f; }
15 inline float abs(float f) { return f<0 ? -f : f; }
16
17 Airplane::Airplane()
18 {
19     _emptyWeight = 0;
20     _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
21     _wing = 0;
22     _tail = 0;
23     _ballast = 0;
24     _cruiseP = 0;
25     _cruiseT = 0;
26     _cruiseSpeed = 0;
27     _cruiseWeight = 0;
28     _approachP = 0;
29     _approachT = 0;
30     _approachSpeed = 0;
31     _approachAoA = 0;
32     _approachWeight = 0;
33
34     _dragFactor = 1;
35     _liftRatio = 1;
36     _cruiseAoA = 0;
37     _tailIncidence = 0;
38 }
39
40 Airplane::~Airplane()
41 {
42     int i;
43     for(i=0; i<_fuselages.size(); i++)
44         delete (Fuselage*)_fuselages.get(i);
45     for(i=0; i<_tanks.size(); i++)
46         delete (Tank*)_tanks.get(i);
47     for(i=0; i<_thrusters.size(); i++)
48         delete (ThrustRec*)_thrusters.get(i);
49     for(i=0; i<_gears.size(); i++)
50         delete (GearRec*)_gears.get(i);
51     for(i=0; i<_surfs.size(); i++)
52         delete (Surface*)_surfs.get(i);    
53     for(i=0; i<_contacts.size(); i++)
54         delete[] (float*)_contacts.get(i);
55 }
56
57 void Airplane::iterate(float dt)
58 {
59     // The gear might have moved.  Change their aerodynamics.
60     updateGearState();
61
62     _model.iterate();
63
64     // FIXME: Consume fuel
65 }
66
67 ControlMap* Airplane::getControlMap()
68 {
69     return &_controls;
70 }
71
72 Model* Airplane::getModel()
73 {
74     return &_model;
75 }
76
77 void Airplane::getPilotAccel(float* out)
78 {
79     State* s = _model.getState();
80
81     // Gravity
82     Glue::geodUp(s->pos, out);
83     Math::mul3(-9.8f, out, out);
84
85     // The regular acceleration
86     float tmp[3];
87     Math::mul3(-1, s->acc, tmp);
88     Math::add3(tmp, out, out);
89
90     // Convert to aircraft coordinates
91     Math::vmul33(s->orient, out, out);
92
93     // FIXME: rotational & centripetal acceleration needed
94 }
95
96 void Airplane::setPilotPos(float* pos)
97 {
98     int i;
99     for(i=0; i<3; i++) _pilotPos[i] = pos[i];
100 }
101
102 void Airplane::getPilotPos(float* out)
103 {
104     int i;
105     for(i=0; i<3; i++) out[i] = _pilotPos[i];
106 }
107
108 int Airplane::numGear()
109 {
110     return _gears.size();
111 }
112
113 Gear* Airplane::getGear(int g)
114 {
115     return ((GearRec*)_gears.get(g))->gear;
116 }
117
118 void Airplane::updateGearState()
119 {
120     for(int i=0; i<_gears.size(); i++) {
121         GearRec* gr = (GearRec*)_gears.get(i);
122         float ext = gr->gear->getExtension();
123
124         gr->surf->setXDrag(ext);
125         gr->surf->setYDrag(ext);
126         gr->surf->setZDrag(ext);
127     }
128 }
129
130 void Airplane::setApproach(float speed, float altitude)
131 {
132     // The zero AoA will become a calculated stall AoA in compile()
133     setApproach(speed, altitude, 0);
134 }
135
136 void Airplane::setApproach(float speed, float altitude, float aoa)
137 {
138     _approachSpeed = speed;
139     _approachP = Atmosphere::getStdPressure(altitude);
140     _approachT = Atmosphere::getStdTemperature(altitude);
141     _approachAoA = aoa;
142 }
143  
144 void Airplane::setCruise(float speed, float altitude)
145 {
146     _cruiseSpeed = speed;
147     _cruiseP = Atmosphere::getStdPressure(altitude);
148     _cruiseT = Atmosphere::getStdTemperature(altitude);
149     _cruiseAoA = 0;
150     _tailIncidence = 0;
151 }
152
153 void Airplane::setElevatorControl(int control)
154 {
155     _approachElevator.control = control;
156     _approachElevator.val = 0;
157     _approachControls.add(&_approachElevator);
158 }
159
160 void Airplane::addApproachControl(int control, float val)
161 {
162     Control* c = new Control();
163     c->control = control;
164     c->val = val;
165     _approachControls.add(c);
166 }
167
168 void Airplane::addCruiseControl(int control, float val)
169 {
170     Control* c = new Control();
171     c->control = control;
172     c->val = val;
173     _cruiseControls.add(c);
174 }
175
176 int Airplane::numTanks()
177 {
178     return _tanks.size();
179 }
180
181 float Airplane::getFuel(int tank)
182 {
183     return ((Tank*)_tanks.get(tank))->fill;
184 }
185
186 float Airplane::getFuelDensity(int tank)
187 {
188     return ((Tank*)_tanks.get(tank))->density;
189 }
190
191 void Airplane::setWeight(float weight)
192 {
193     _emptyWeight = weight;
194 }
195
196 void Airplane::setWing(Wing* wing)
197 {
198     _wing = wing;
199 }
200
201 void Airplane::setTail(Wing* tail)
202 {
203     _tail = tail;
204 }
205
206 void Airplane::addVStab(Wing* vstab)
207 {
208     _vstabs.add(vstab);
209 }
210
211 void Airplane::addFuselage(float* front, float* back, float width,
212                            float taper, float mid)
213 {
214     Fuselage* f = new Fuselage();
215     int i;
216     for(i=0; i<3; i++) {
217         f->front[i] = front[i];
218         f->back[i]  = back[i];
219     }
220     f->width = width;
221     f->taper = taper;
222     f->mid = mid;
223     _fuselages.add(f);
224 }
225
226 int Airplane::addTank(float* pos, float cap, float density)
227 {
228     Tank* t = new Tank();
229     int i;
230     for(i=0; i<3; i++) t->pos[i] = pos[i];
231     t->cap = cap;
232     t->fill = cap;
233     t->density = density;
234     t->handle = 0xffffffff;
235     return _tanks.add(t);
236 }
237
238 void Airplane::addGear(Gear* gear)
239 {
240     GearRec* g = new GearRec();
241     g->gear = gear;
242     g->surf = 0;
243     _gears.add(g);
244 }
245
246 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
247 {
248     ThrustRec* t = new ThrustRec();
249     t->thruster = thruster;
250     t->mass = mass;
251     int i;
252     for(i=0; i<3; i++) t->cg[i] = cg[i];
253     _thrusters.add(t);
254 }
255
256 void Airplane::addBallast(float* pos, float mass)
257 {
258     _model.getBody()->addMass(mass, pos);
259     _ballast += mass;
260 }
261
262 int Airplane::addWeight(float* pos, float size)
263 {
264     WeightRec* wr = new WeightRec();
265     wr->handle = _model.getBody()->addMass(0, pos);
266
267     wr->surf = new Surface();
268     wr->surf->setPosition(pos);
269     wr->surf->setTotalDrag(size*size);
270     _model.addSurface(wr->surf);
271     _surfs.add(wr->surf);
272
273     return _weights.add(wr);
274 }
275
276 void Airplane::setWeight(int handle, float mass)
277 {
278     WeightRec* wr = (WeightRec*)_weights.get(handle);
279
280     _model.getBody()->setMass(wr->handle, mass);
281
282     // Kill the aerodynamic drag if the mass is exactly zero.  This is
283     // how we simulate droppable stores.
284     if(mass == 0) {
285         wr->surf->setXDrag(0);
286         wr->surf->setYDrag(0);
287         wr->surf->setZDrag(0);
288     } else {
289         wr->surf->setXDrag(1);
290         wr->surf->setYDrag(1);
291         wr->surf->setZDrag(1);
292     }
293 }
294
295 void Airplane::setFuelFraction(float frac)
296 {
297     int i;
298     for(i=0; i<_tanks.size(); i++) {
299         Tank* t = (Tank*)_tanks.get(i);
300         _model.getBody()->setMass(t->handle, t->cap * frac);
301     }
302 }
303
304 float Airplane::getDragCoefficient()
305 {
306     return _dragFactor;
307 }
308
309 float Airplane::getLiftRatio()
310 {
311     return _liftRatio;
312 }
313
314 float Airplane::getCruiseAoA()
315 {
316     return _cruiseAoA;
317 }
318
319 float Airplane::getTailIncidence()
320 {
321     return _tailIncidence;
322 }
323
324 char* Airplane::getFailureMsg()
325 {
326     return _failureMsg;
327 }
328
329 int Airplane::getSolutionIterations()
330 {
331     return _solutionIterations;
332 }
333
334 void Airplane::setupState(float aoa, float speed, State* s)
335 {
336     float cosAoA = Math::cos(aoa);
337     float sinAoA = Math::sin(aoa);
338     s->orient[0] =  cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
339     s->orient[3] =       0; s->orient[4] = 1; s->orient[5] =      0;
340     s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
341
342     s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
343
344     int i;
345     for(i=0; i<3; i++)
346         s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
347
348     // Put us 1m above the origin, or else the gravity computation in
349     // Model goes nuts
350     s->pos[2] = 1;
351 }
352
353 void Airplane::addContactPoint(float* pos)
354 {
355     float* cp = new float[3];
356     cp[0] = pos[0];
357     cp[1] = pos[1];
358     cp[2] = pos[2];
359     _contacts.add(cp);
360 }
361
362 float Airplane::compileWing(Wing* w)
363 {
364     // The tip of the wing is a contact point
365     float tip[3];
366     w->getTip(tip);
367     addContactPoint(tip);
368     if(w->isMirrored()) {
369         tip[1] *= -1;
370         addContactPoint(tip);
371     }
372
373     // Make sure it's initialized.  The surfaces will pop out with
374     // total drag coefficients equal to their areas, which is what we
375     // want.
376     w->compile();
377
378     float wgt = 0;
379     int i;
380     for(i=0; i<w->numSurfaces(); i++) {
381         Surface* s = (Surface*)w->getSurface(i);
382
383         float td = s->getTotalDrag();
384         s->setTotalDrag(td);
385
386         _model.addSurface(s);
387
388         float mass = w->getSurfaceWeight(i);
389         mass = mass * Math::sqrt(mass);
390         float pos[3];
391         s->getPosition(pos);
392         _model.getBody()->addMass(mass, pos);
393         wgt += mass;
394     }
395     return wgt;
396 }
397
398 float Airplane::compileFuselage(Fuselage* f)
399 {
400     // The front and back are contact points
401     addContactPoint(f->front);
402     addContactPoint(f->back);
403
404     float wgt = 0;
405     float fwd[3];
406     Math::sub3(f->front, f->back, fwd);
407     float len = Math::mag3(fwd);
408     float wid = f->width;
409     int segs = (int)Math::ceil(len/wid);
410     float segWgt = len*wid/segs;
411     int j;
412     for(j=0; j<segs; j++) {
413         float frac = (j+0.5f) / segs;
414
415         float scale = 1;
416         if(frac < f->mid)
417             scale = f->taper+(1-f->taper) * (frac / f->mid);
418         else
419             scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
420
421         // Where are we?
422         float pos[3];
423         Math::mul3(frac, fwd, pos);
424         Math::add3(f->back, pos, pos);
425
426         // _Mass_ weighting goes as surface area^(3/2)
427         float mass = scale*segWgt * Math::sqrt(scale*segWgt);
428         _model.getBody()->addMass(mass, pos);
429         wgt += mass;
430
431         // Make a Surface too
432         Surface* s = new Surface();
433         s->setPosition(pos);
434         float sideDrag = len/wid;
435         s->setYDrag(sideDrag);
436         s->setZDrag(sideDrag);
437         s->setTotalDrag(scale*segWgt);
438
439         // FIXME: fails for fuselages aligned along the Y axis
440         float o[9];
441         float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
442         Math::unit3(fwd, x);
443         y[0] = 0; y[1] = 1; y[2] = 0;
444         Math::cross3(x, y, z);
445         Math::unit3(z, z);
446         Math::cross3(z, x, y);
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.2f;
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.8f * 10.0f * 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.6f);
510         g->setDynamicFriction(0.5f);
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.5f;
567     _approachWeight = _emptyWeight + totalFuel*0.2f;
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, 0.3f);
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
594 void Airplane::solveGear()
595 {
596     float cg[3], pos[3];
597     _model.getBody()->getCG(cg);
598
599     // Calculate spring constant weightings for the gear.  Weight by
600     // the inverse of the distance to the c.g. in the XY plane, which
601     // should be correct for most gear arrangements.  Add 50cm of
602     // "buffer" to keep things from blowing up with aircraft with a
603     // single gear very near the c.g. (AV-8, for example).
604     float total = 0;
605     int i;
606     for(i=0; i<_gears.size(); i++) {
607         GearRec* gr = (GearRec*)_gears.get(i);
608         Gear* g = gr->gear;
609         g->getPosition(pos);
610         Math::sub3(cg, pos, pos);
611         gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
612         total += gr->wgt;
613     }
614
615     // Renormalize so they sum to 1
616     for(i=0; i<_gears.size(); i++)
617         ((GearRec*)_gears.get(i))->wgt /= total;
618     
619     // The force at max compression should be sufficient to stop a
620     // plane moving downwards at 3x the approach descent rate.  Assume
621     // a 3 degree approach.
622     float descentRate = 3.0f*_approachSpeed/19.1f;
623
624     // Spread the kinetic energy according to the gear weights.  This
625     // will results in an equal compression fraction (not distance) of
626     // each gear.
627     float energy = 0.5f*_approachWeight*descentRate*descentRate;
628
629     for(i=0; i<_gears.size(); i++) {
630         GearRec* gr = (GearRec*)_gears.get(i);
631         float e = energy * gr->wgt;
632         float comp[3];
633         gr->gear->getCompression(comp);
634         float len = Math::mag3(comp);
635
636         // Energy in a spring: e = 0.5 * k * len^2
637         float k = 2 * e / (len*len);
638
639         gr->gear->setSpring(k);
640
641         // Critically damped (too damped, too!)
642         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
643
644         // These are pretty generic
645         gr->gear->setStaticFriction(0.8f);
646         gr->gear->setDynamicFriction(0.7f);
647     }
648 }
649
650 void Airplane::initEngines()
651 {
652     for(int i=0; i<_thrusters.size(); i++) {
653         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
654         tr->thruster->init();
655     }
656 }
657
658 void Airplane::stabilizeThrust()
659 {
660     int i;
661     for(i=0; i<_thrusters.size(); i++)
662         _model.getThruster(i)->stabilize();
663 }
664
665 void Airplane::runCruise()
666 {
667     setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
668     _model.setState(&_cruiseState);
669     _model.setAir(_cruiseP, _cruiseT);
670
671     // The control configuration
672     _controls.reset();
673     int i;
674     for(i=0; i<_cruiseControls.size(); i++) {
675         Control* c = (Control*)_cruiseControls.get(i);
676         _controls.setInput(c->control, c->val);
677     }
678     _controls.applyControls(1000000); // Huge dt value
679
680     // The local wind
681     float wind[3];
682     Math::mul3(-1, _cruiseState.v, wind);
683     Math::vmul33(_cruiseState.orient, wind, wind);
684  
685     // Cruise is by convention at 50% tank capacity
686     setFuelFraction(0.5);
687    
688     // Set up the thruster parameters and iterate until the thrust
689     // stabilizes.
690     for(i=0; i<_thrusters.size(); i++) {
691         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
692         t->setWind(wind);
693         t->setAir(_cruiseP, _cruiseT);
694     }
695     stabilizeThrust();
696
697     updateGearState();
698
699     // Precompute thrust in the model, and calculate aerodynamic forces
700     _model.getBody()->reset();
701     _model.initIteration();
702     _model.calcForces(&_cruiseState);
703 }
704
705 void Airplane::runApproach()
706 {
707     setupState(_approachAoA, _approachSpeed, &_approachState);
708     _model.setState(&_approachState);
709     _model.setAir(_approachP, _approachT);
710
711     // The control configuration
712     _controls.reset();
713     int i;
714     for(i=0; i<_approachControls.size(); i++) {
715         Control* c = (Control*)_approachControls.get(i);
716         _controls.setInput(c->control, c->val);
717     }
718     _controls.applyControls(1000000);
719
720     // The local wind
721     float wind[3];
722     Math::mul3(-1, _approachState.v, wind);
723     Math::vmul33(_approachState.orient, wind, wind);
724     
725     // Approach is by convention at 20% tank capacity
726     setFuelFraction(0.2f);
727
728     // Run the thrusters until they get to a stable setting.  FIXME:
729     // this is lots of wasted work.
730     for(i=0; i<_thrusters.size(); i++) {
731         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
732         t->setWind(wind);
733         t->setAir(_approachP, _approachT);
734     }
735     stabilizeThrust();
736
737     updateGearState();
738
739     // Precompute thrust in the model, and calculate aerodynamic forces
740     _model.getBody()->reset();
741     _model.initIteration();
742     _model.calcForces(&_approachState);
743 }
744
745 void Airplane::applyDragFactor(float factor)
746 {
747     float applied = Math::sqrt(factor);
748     _dragFactor *= applied;
749     _wing->setDragScale(_wing->getDragScale() * applied);
750     _tail->setDragScale(_tail->getDragScale() * applied);
751     int i;
752     for(i=0; i<_vstabs.size(); i++) {
753         Wing* w = (Wing*)_vstabs.get(i);
754         w->setDragScale(w->getDragScale() * applied);
755     }
756     for(i=0; i<_surfs.size(); i++) {
757         Surface* s = (Surface*)_surfs.get(i);
758         s->setTotalDrag(s->getTotalDrag() * applied);
759     }
760 }
761
762 void Airplane::applyLiftRatio(float factor)
763 {
764     float applied = Math::sqrt(factor);
765     _liftRatio *= applied;
766     _wing->setLiftRatio(_wing->getLiftRatio() * applied);
767     _tail->setLiftRatio(_tail->getLiftRatio() * applied);
768     int i;
769     for(i=0; i<_vstabs.size(); i++) {
770         Wing* w = (Wing*)_vstabs.get(i);
771         w->setLiftRatio(w->getLiftRatio() * applied);
772     }
773 }
774
775 float Airplane::clamp(float val, float min, float max)
776 {
777     if(val < min) return min;
778     if(val > max) return max;
779     return val;
780 }
781
782 float Airplane::normFactor(float f)
783 {
784     if(f < 0) f = -f;
785     if(f < 1) f = 1/f;
786     return f;
787 }
788
789 void Airplane::solve()
790 {
791     static const float ARCMIN = 0.0002909f;
792
793     float tmp[3];
794     _solutionIterations = 0;
795     _failureMsg = 0;
796     while(1) {
797         if(_solutionIterations++ > 10000) {
798             _failureMsg = "Solution failed to converge after 10000 iterations";
799             return;
800         }
801
802         // Run an iteration at cruise, and extract the needed numbers:
803         runCruise();
804
805         _model.getThrust(tmp);
806         float thrust = tmp[0];
807
808         _model.getBody()->getAccel(tmp);
809         float xforce = _cruiseWeight * tmp[0];
810         float clift0 = _cruiseWeight * tmp[2];
811
812         _model.getBody()->getAngularAccel(tmp);
813         float pitch0 = tmp[1];
814
815         // Run an approach iteration, and do likewise
816         runApproach();
817
818         _model.getBody()->getAngularAccel(tmp);
819         float apitch0 = tmp[1];
820
821         _model.getBody()->getAccel(tmp);
822         float alift = _approachWeight * tmp[2];
823
824         // Modify the cruise AoA a bit to get a derivative
825         _cruiseAoA += ARCMIN;
826         runCruise();
827         _cruiseAoA -= ARCMIN;
828
829         _model.getBody()->getAccel(tmp);
830         float clift1 = _cruiseWeight * tmp[2];
831
832         // Do the same with the tail incidence
833         _tail->setIncidence(_tailIncidence + ARCMIN);
834         runCruise();
835         _tail->setIncidence(_tailIncidence);
836
837         _model.getBody()->getAngularAccel(tmp);
838         float pitch1 = tmp[1];
839
840         // Now calculate:
841         float awgt = 9.8f * _approachWeight;
842
843         float dragFactor = thrust / (thrust-xforce);
844         float liftFactor = awgt / (awgt+alift);
845         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
846         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
847
848         // Sanity:
849         if(dragFactor <= 0) {
850             _failureMsg = "Zero or negative drag adjustment.";
851             return;
852         } else if(liftFactor <= 0) {
853             _failureMsg = "Zero or negative lift adjustment.";
854             return;
855         }
856
857         // And the elevator control in the approach.  This works just
858         // like the tail incidence computation (it's solving for the
859         // same thing -- pitching moment -- by diddling a different
860         // variable).
861         const float ELEVDIDDLE = 0.0001f;
862         _approachElevator.val += ELEVDIDDLE;
863         runApproach();
864         _approachElevator.val -= ELEVDIDDLE;
865
866         _model.getBody()->getAngularAccel(tmp);
867         float apitch1 = tmp[1];
868         float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
869
870         // Now apply the values we just computed.  Note that the
871         // "minor" variables are deferred until we get the lift/drag
872         // numbers in the right ballpark.
873
874         applyDragFactor(dragFactor);
875         applyLiftRatio(liftFactor);
876
877         // DON'T do the following until the above are sane
878         if(normFactor(dragFactor) > 1.1
879            || normFactor(liftFactor) > 1.1)
880         {
881             continue;
882         }
883
884         // OK, now we can adjust the minor variables:
885         _cruiseAoA += 0.5f*aoaDelta;
886         _tailIncidence += 0.5f*tailDelta;
887         _approachElevator.val += 0.5f*elevDelta;
888         
889         _cruiseAoA = clamp(_cruiseAoA, -0.174f, 0.174f);
890         _tailIncidence = clamp(_tailIncidence, -0.174f, 0.174f);
891         _approachElevator.val = clamp(_approachElevator.val, -1.f, 1.f);
892
893         if(norm(dragFactor) < 1.00001 &&
894            norm(liftFactor) < 1.00001 &&
895            abs(aoaDelta) < .000017 &&
896            abs(tailDelta) < .000017 &&
897            abs(elevDelta) < 0.00001)
898         {
899             break;
900         }
901     }
902
903     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
904         _failureMsg = "Drag factor beyond reasonable bounds.";
905         return;
906     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
907         _failureMsg = "Lift ratio beyond reasonable bounds.";
908         return;
909     } else if(Math::abs(_cruiseAoA) >= .174) {
910         _failureMsg = "Cruise AoA > 10 degrees";
911         return;
912     } else if(Math::abs(_tailIncidence) >= .174) {
913         _failureMsg = "Tail incidence > 10 degrees";
914         return;
915     }
916 }
917 }; // namespace yasim