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