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