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