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