]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
Disable the defaulting of gear friction so the tunables actually work
[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 }
743
744 void Airplane::initEngines()
745 {
746     for(int i=0; i<_thrusters.size(); i++) {
747         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
748         tr->thruster->init();
749     }
750 }
751
752 void Airplane::stabilizeThrust()
753 {
754     int i;
755     for(i=0; i<_thrusters.size(); i++)
756         _model.getThruster(i)->stabilize();
757 }
758
759 void Airplane::setupWeights(bool isApproach)
760 {
761     int i;
762     for(i=0; i<_weights.size(); i++)
763         setWeight(i, 0);
764     for(i=0; i<_solveWeights.size(); i++) {
765         SolveWeight* w = (SolveWeight*)_solveWeights.get(i);
766         if(w->approach == isApproach)
767             setWeight(w->idx, w->wgt);
768     }
769 }
770
771 void Airplane::runCruise()
772 {
773     setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
774     _model.setState(&_cruiseState);
775     _model.setAir(_cruiseP, _cruiseT,
776                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
777
778     // The control configuration
779     _controls.reset();
780     int i;
781     for(i=0; i<_cruiseControls.size(); i++) {
782         Control* c = (Control*)_cruiseControls.get(i);
783         _controls.setInput(c->control, c->val);
784     }
785     _controls.applyControls(1000000); // Huge dt value
786
787     // The local wind
788     float wind[3];
789     Math::mul3(-1, _cruiseState.v, wind);
790     Math::vmul33(_cruiseState.orient, wind, wind);
791  
792     setFuelFraction(_cruiseFuel);
793     setupWeights(false);
794    
795     // Set up the thruster parameters and iterate until the thrust
796     // stabilizes.
797     for(i=0; i<_thrusters.size(); i++) {
798         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
799         t->setWind(wind);
800         t->setAir(_cruiseP, _cruiseT,
801                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
802     }
803     stabilizeThrust();
804
805     updateGearState();
806
807     // Precompute thrust in the model, and calculate aerodynamic forces
808     _model.getBody()->recalc();
809     _model.getBody()->reset();
810     _model.initIteration();
811     _model.calcForces(&_cruiseState);
812 }
813
814 void Airplane::runApproach()
815 {
816     setupState(_approachAoA, _approachSpeed, &_approachState);
817     _model.setState(&_approachState);
818     _model.setAir(_approachP, _approachT,
819                   Atmosphere::calcStdDensity(_approachP, _approachT));
820
821     // The control configuration
822     _controls.reset();
823     int i;
824     for(i=0; i<_approachControls.size(); i++) {
825         Control* c = (Control*)_approachControls.get(i);
826         _controls.setInput(c->control, c->val);
827     }
828     _controls.applyControls(1000000);
829
830     // The local wind
831     float wind[3];
832     Math::mul3(-1, _approachState.v, wind);
833     Math::vmul33(_approachState.orient, wind, wind);
834     
835     setFuelFraction(_approachFuel);
836
837     setupWeights(true);
838
839     // Run the thrusters until they get to a stable setting.  FIXME:
840     // this is lots of wasted work.
841     for(i=0; i<_thrusters.size(); i++) {
842         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
843         t->setWind(wind);
844         t->setAir(_approachP, _approachT,
845                   Atmosphere::calcStdDensity(_approachP, _approachT));
846     }
847     stabilizeThrust();
848
849     updateGearState();
850
851     // Precompute thrust in the model, and calculate aerodynamic forces
852     _model.getBody()->recalc();
853     _model.getBody()->reset();
854     _model.initIteration();
855     _model.calcForces(&_approachState);
856 }
857
858 void Airplane::applyDragFactor(float factor)
859 {
860     float applied = Math::pow(factor, SOLVE_TWEAK);
861     _dragFactor *= applied;
862     if(_wing)
863       _wing->setDragScale(_wing->getDragScale() * applied);
864     if(_tail)
865       _tail->setDragScale(_tail->getDragScale() * applied);
866     int i;
867     for(i=0; i<_vstabs.size(); i++) {
868         Wing* w = (Wing*)_vstabs.get(i);
869         w->setDragScale(w->getDragScale() * applied);
870     }
871     for(i=0; i<_surfs.size(); i++) {
872         Surface* s = (Surface*)_surfs.get(i);
873         s->setTotalDrag(s->getTotalDrag() * applied);
874     }
875 }
876
877 void Airplane::applyLiftRatio(float factor)
878 {
879     float applied = Math::pow(factor, SOLVE_TWEAK);
880     _liftRatio *= applied;
881     if(_wing)
882       _wing->setLiftRatio(_wing->getLiftRatio() * applied);
883     if(_tail)
884       _tail->setLiftRatio(_tail->getLiftRatio() * applied);
885     int i;
886     for(i=0; i<_vstabs.size(); i++) {
887         Wing* w = (Wing*)_vstabs.get(i);
888         w->setLiftRatio(w->getLiftRatio() * applied);
889     }
890 }
891
892 float Airplane::clamp(float val, float min, float max)
893 {
894     if(val < min) return min;
895     if(val > max) return max;
896     return val;
897 }
898
899 float Airplane::normFactor(float f)
900 {
901     if(f < 0) f = -f;
902     if(f < 1) f = 1/f;
903     return f;
904 }
905
906 void Airplane::solve()
907 {
908     static const float ARCMIN = 0.0002909f;
909
910     float tmp[3];
911     _solutionIterations = 0;
912     _failureMsg = 0;
913
914     while(1) {
915         if(_solutionIterations++ > 10000) { 
916             _failureMsg = "Solution failed to converge after 10000 iterations";
917             return;
918         }
919
920         // Run an iteration at cruise, and extract the needed numbers:
921         runCruise();
922
923         _model.getThrust(tmp);
924         float thrust = tmp[0];
925
926         _model.getBody()->getAccel(tmp);
927         Math::tmul33(_cruiseState.orient, tmp, tmp);
928         float xforce = _cruiseWeight * tmp[0];
929         float clift0 = _cruiseWeight * tmp[2];
930
931         _model.getBody()->getAngularAccel(tmp);
932         Math::tmul33(_cruiseState.orient, tmp, tmp);
933         float pitch0 = tmp[1];
934
935         // Run an approach iteration, and do likewise
936         runApproach();
937
938         _model.getBody()->getAngularAccel(tmp);
939         Math::tmul33(_approachState.orient, tmp, tmp);
940         double apitch0 = tmp[1];
941
942         _model.getBody()->getAccel(tmp);
943         Math::tmul33(_approachState.orient, tmp, tmp);
944         float alift = _approachWeight * tmp[2];
945
946         // Modify the cruise AoA a bit to get a derivative
947         _cruiseAoA += ARCMIN;
948         runCruise();
949         _cruiseAoA -= ARCMIN;
950
951         _model.getBody()->getAccel(tmp);
952         Math::tmul33(_cruiseState.orient, tmp, tmp);
953         float clift1 = _cruiseWeight * tmp[2];
954
955         // Do the same with the tail incidence
956         _tail->setIncidence(_tailIncidence + ARCMIN);
957         runCruise();
958         _tail->setIncidence(_tailIncidence);
959
960         _model.getBody()->getAngularAccel(tmp);
961         Math::tmul33(_cruiseState.orient, tmp, tmp);
962         float pitch1 = tmp[1];
963
964         // Now calculate:
965         float awgt = 9.8f * _approachWeight;
966
967         float dragFactor = thrust / (thrust-xforce);
968         float liftFactor = awgt / (awgt+alift);
969         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
970         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
971
972         // Sanity:
973         if(dragFactor <= 0 || liftFactor <= 0)
974             break;
975
976         // And the elevator control in the approach.  This works just
977         // like the tail incidence computation (it's solving for the
978         // same thing -- pitching moment -- by diddling a different
979         // variable).
980         const float ELEVDIDDLE = 0.001f;
981         _approachElevator.val += ELEVDIDDLE;
982         runApproach();
983         _approachElevator.val -= ELEVDIDDLE;
984
985         _model.getBody()->getAngularAccel(tmp);
986         Math::tmul33(_approachState.orient, tmp, tmp);
987         double apitch1 = tmp[1];
988         float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
989
990         // Now apply the values we just computed.  Note that the
991         // "minor" variables are deferred until we get the lift/drag
992         // numbers in the right ballpark.
993
994         applyDragFactor(dragFactor);
995         applyLiftRatio(liftFactor);
996
997         // DON'T do the following until the above are sane
998         if(normFactor(dragFactor) > STHRESH*1.0001
999            || normFactor(liftFactor) > STHRESH*1.0001)
1000         {
1001             continue;
1002         }
1003
1004         // OK, now we can adjust the minor variables:
1005         _cruiseAoA += SOLVE_TWEAK*aoaDelta;
1006         _tailIncidence += SOLVE_TWEAK*tailDelta;
1007         
1008         _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
1009         _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
1010
1011         if(abs(xforce/_cruiseWeight) < STHRESH*0.0001 &&
1012            abs(alift/_approachWeight) < STHRESH*0.0001 &&
1013            abs(aoaDelta) < STHRESH*.000017 &&
1014            abs(tailDelta) < STHRESH*.000017)
1015         {
1016             // If this finaly value is OK, then we're all done
1017             if(abs(elevDelta) < STHRESH*0.0001)
1018                 break;
1019
1020             // Otherwise, adjust and do the next iteration
1021             _approachElevator.val += SOLVE_TWEAK * elevDelta;
1022             if(abs(_approachElevator.val) > 1) {
1023                 _failureMsg = "Insufficient elevator to trim for approach";
1024                 break;
1025             }
1026         }
1027     }
1028
1029     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
1030         _failureMsg = "Drag factor beyond reasonable bounds.";
1031         return;
1032     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
1033         _failureMsg = "Lift ratio beyond reasonable bounds.";
1034         return;
1035     } else if(Math::abs(_cruiseAoA) >= .17453293) {
1036         _failureMsg = "Cruise AoA > 10 degrees";
1037         return;
1038     } else if(Math::abs(_tailIncidence) >= .17453293) {
1039         _failureMsg = "Tail incidence > 10 degrees";
1040         return;
1041     }
1042 }
1043
1044 void Airplane::solveHelicopter()
1045 {
1046     _solutionIterations = 0;
1047     _failureMsg = 0;
1048     if (getRotorgear()!=0)
1049     {
1050         Rotorgear* rg = getRotorgear();
1051         applyDragFactor(Math::pow(rg->getYasimDragFactor()/1000,
1052             1/SOLVE_TWEAK));
1053         applyLiftRatio(Math::pow(rg->getYasimLiftFactor(),
1054             1/SOLVE_TWEAK));
1055     }
1056     else
1057     //huh, no wing and no rotor? (_rotorgear is constructed, 
1058     //if a rotor is defined
1059     {
1060         applyDragFactor(Math::pow(15.7/1000, 1/SOLVE_TWEAK));
1061         applyLiftRatio(Math::pow(104, 1/SOLVE_TWEAK));
1062     }
1063     setupState(0,0, &_cruiseState);
1064     _model.setState(&_cruiseState);
1065     setupWeights(true);
1066     _controls.reset();
1067     _model.getBody()->reset();
1068     _model.setAir(_cruiseP, _cruiseT,
1069                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
1070     
1071 }
1072
1073 }; // namespace yasim