]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
Andreas Gaeb: fix #222 (JSBSIm reset problems)
[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 Airplane::Airplane()
32 {
33     _emptyWeight = 0;
34     _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
35     _wing = 0;
36     _tail = 0;
37     _ballast = 0;
38     _cruiseP = 0;
39     _cruiseT = 0;
40     _cruiseSpeed = 0;
41     _cruiseWeight = 0;
42     _cruiseGlideAngle = 0;
43     _approachP = 0;
44     _approachT = 0;
45     _approachSpeed = 0;
46     _approachAoA = 0;
47     _approachWeight = 0;
48     _approachGlideAngle = 0;
49
50     _dragFactor = 1;
51     _liftRatio = 1;
52     _cruiseAoA = 0;
53     _tailIncidence = 0;
54
55     _failureMsg = 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(-9.8f, 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 const 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     if (len == 0) {
513         _failureMsg = "Zero length fuselage";
514         return 0;
515     }
516     float wid = f->width;
517     int segs = (int)Math::ceil(len/wid);
518     float segWgt = len*wid/segs;
519     int j;
520     for(j=0; j<segs; j++) {
521         float frac = (j+0.5f) / segs;
522
523         float scale = 1;
524         if(frac < f->mid)
525             scale = f->taper+(1-f->taper) * (frac / f->mid);
526         else
527             scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
528
529         // Where are we?
530         float pos[3];
531         Math::mul3(frac, fwd, pos);
532         Math::add3(f->back, pos, pos);
533
534         // _Mass_ weighting goes as surface area^(3/2)
535         float mass = scale*segWgt * Math::sqrt(scale*segWgt);
536         _model.getBody()->addMass(mass, pos);
537         wgt += mass;
538
539         // Make a Surface too
540         Surface* s = new Surface();
541         s->setPosition(pos);
542         float sideDrag = len/wid;
543         s->setYDrag(sideDrag*f->_cy);
544         s->setZDrag(sideDrag*f->_cz);
545         s->setTotalDrag(scale*segWgt*f->_cx);
546         s->setInducedDrag(f->_idrag);
547
548         // FIXME: fails for fuselages aligned along the Y axis
549         float o[9];
550         float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
551         Math::unit3(fwd, x);
552         y[0] = 0; y[1] = 1; y[2] = 0;
553         Math::cross3(x, y, z);
554         Math::unit3(z, z);
555         Math::cross3(z, x, y);
556         s->setOrientation(o);
557
558         _model.addSurface(s);
559         _surfs.add(s);
560     }
561     return wgt;
562 }
563
564 // FIXME: should probably add a mass for the gear, too
565 void Airplane::compileGear(GearRec* gr)
566 {
567     Gear* g = gr->gear;
568
569     // Make a Surface object for the aerodynamic behavior
570     Surface* s = new Surface();
571     gr->surf = s;
572
573     // Put the surface at the half-way point on the gear strut, give
574     // it a drag coefficient equal to a square of the same dimension
575     // (gear are really draggy) and make it symmetric.  Assume that
576     // the "length" of the gear is 3x the compression distance
577     float pos[3], cmp[3];
578     g->getCompression(cmp);
579     float length = 3 * Math::mag3(cmp);
580     g->getPosition(pos);
581     Math::mul3(0.5, cmp, cmp);
582     Math::add3(pos, cmp, pos);
583
584     s->setPosition(pos);
585     s->setTotalDrag(length*length);
586
587     _model.addGear(g);
588     _model.addSurface(s);
589     _surfs.add(s);
590 }
591
592 void Airplane::compileContactPoints()
593 {
594     // Figure it will compress by 20cm
595     float comp[3];
596     float DIST = 0.2f;
597     comp[0] = 0; comp[1] = 0; comp[2] = DIST;
598
599     // Give it a spring constant such that at full compression it will
600     // hold up 10 times the planes mass.  That's about right.  Yeah.
601     float mass = _model.getBody()->getTotalMass();
602     float spring = (1/DIST) * 9.8f * 10.0f * mass;
603     float damp = 2 * Math::sqrt(spring * mass);
604
605     int i;
606     for(i=0; i<_contacts.size(); i++) {
607         ContactRec* c = (ContactRec*)_contacts.get(i);
608
609         Gear* g = new Gear();
610         c->gear = g;
611         g->setPosition(c->p);
612         
613         g->setCompression(comp);
614         g->setSpring(spring);
615         g->setDamping(damp);
616         g->setBrake(1);
617
618         // I made these up
619         g->setStaticFriction(0.6f);
620         g->setDynamicFriction(0.5f);
621         g->setContactPoint(1);
622
623         _model.addGear(g);
624     }
625 }
626
627 void Airplane::compile()
628 {
629     RigidBody* body = _model.getBody();
630     int firstMass = body->numMasses();
631
632     // Generate the point masses for the plane.  Just use unitless
633     // numbers for a first pass, then go back through and rescale to
634     // make the weight right.
635     float aeroWgt = 0;
636
637     // The Wing objects
638     if (_wing)
639       aeroWgt += compileWing(_wing);
640     if (_tail)
641       aeroWgt += compileWing(_tail);
642     int i;
643     for(i=0; i<_vstabs.size(); i++)
644         aeroWgt += compileWing((Wing*)_vstabs.get(i)); 
645
646
647     // The fuselage(s)
648     for(i=0; i<_fuselages.size(); i++)
649         aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
650
651     // Count up the absolute weight we have
652     float nonAeroWgt = _ballast;
653     for(i=0; i<_thrusters.size(); i++)
654         nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
655
656     // Rescale to the specified empty weight
657     float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
658     for(i=firstMass; i<body->numMasses(); i++)
659         body->setMass(i, body->getMass(i)*wscale);
660
661     // Add the thruster masses
662     for(i=0; i<_thrusters.size(); i++) {
663         ThrustRec* t = (ThrustRec*)_thrusters.get(i);
664         body->addMass(t->mass, t->cg);
665     }
666
667     // Add the tanks, empty for now.
668     float totalFuel = 0;
669     for(i=0; i<_tanks.size(); i++) { 
670         Tank* t = (Tank*)_tanks.get(i); 
671         t->handle = body->addMass(0, t->pos);
672         totalFuel += t->cap;
673     }
674     _cruiseWeight = _emptyWeight + totalFuel*0.5f;
675     _approachWeight = _emptyWeight + totalFuel*0.2f;
676
677     body->recalc();
678
679     // Add surfaces for the landing gear.
680     for(i=0; i<_gears.size(); i++)
681         compileGear((GearRec*)_gears.get(i));
682
683     // The Thruster objects
684     for(i=0; i<_thrusters.size(); i++) {
685         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
686         tr->handle = _model.addThruster(tr->thruster);
687     }
688
689     // Ground effect
690     if(_wing) {
691         float gepos[3];
692         float gespan = 0;
693         gespan = _wing->getGroundEffect(gepos);
694         _model.setGroundEffect(gepos, gespan, 0.15f);
695     }
696
697     // solve function below resets failure message
698     // so check if we have any problems and abort here
699     if (_failureMsg) return;
700
701     solveGear();
702     if(_wing && _tail) solve();
703     else
704     {
705        // The rotor(s) mass:
706        compileRotorgear(); 
707        solveHelicopter();
708     }
709
710     // Do this after solveGear, because it creates "gear" objects that
711     // we don't want to affect.
712     compileContactPoints();
713 }
714
715 void Airplane::solveGear()
716 {
717     float cg[3], pos[3];
718     _model.getBody()->getCG(cg);
719
720     // Calculate spring constant weightings for the gear.  Weight by
721     // the inverse of the distance to the c.g. in the XY plane, which
722     // should be correct for most gear arrangements.  Add 50cm of
723     // "buffer" to keep things from blowing up with aircraft with a
724     // single gear very near the c.g. (AV-8, for example).
725     float total = 0;
726     int i;
727     for(i=0; i<_gears.size(); i++) {
728         GearRec* gr = (GearRec*)_gears.get(i);
729         Gear* g = gr->gear;
730         g->getPosition(pos);
731         Math::sub3(cg, pos, pos);
732         gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
733         if (!g->getIgnoreWhileSolving())
734             total += gr->wgt;
735     }
736
737     // Renormalize so they sum to 1
738     for(i=0; i<_gears.size(); i++)
739         ((GearRec*)_gears.get(i))->wgt /= total;
740     
741     // The force at max compression should be sufficient to stop a
742     // plane moving downwards at 2x the approach descent rate.  Assume
743     // a 3 degree approach.
744     float descentRate = 2.0f*_approachSpeed/19.1f;
745
746     // Spread the kinetic energy according to the gear weights.  This
747     // will results in an equal compression fraction (not distance) of
748     // each gear.
749     float energy = 0.5f*_approachWeight*descentRate*descentRate;
750
751     for(i=0; i<_gears.size(); i++) {
752         GearRec* gr = (GearRec*)_gears.get(i);
753         float e = energy * gr->wgt;
754         float comp[3];
755         gr->gear->getCompression(comp);
756         float len = Math::mag3(comp)*(1+2*gr->gear->getInitialLoad());
757
758         // Energy in a spring: e = 0.5 * k * len^2
759         float k = 2 * e / (len*len);
760
761         gr->gear->setSpring(k * gr->gear->getSpring());
762
763         // Critically damped (too damped, too!)
764         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt)
765                              * gr->gear->getDamping());
766     }
767 }
768
769 void Airplane::initEngines()
770 {
771     for(int i=0; i<_thrusters.size(); i++) {
772         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
773         tr->thruster->init();
774     }
775 }
776
777 void Airplane::stabilizeThrust()
778 {
779     int i;
780     for(i=0; i<_thrusters.size(); i++)
781         _model.getThruster(i)->stabilize();
782 }
783
784 void Airplane::setupWeights(bool isApproach)
785 {
786     int i;
787     for(i=0; i<_weights.size(); i++)
788         setWeight(i, 0);
789     for(i=0; i<_solveWeights.size(); i++) {
790         SolveWeight* w = (SolveWeight*)_solveWeights.get(i);
791         if(w->approach == isApproach)
792             setWeight(w->idx, w->wgt);
793     }
794 }
795
796 void Airplane::runCruise()
797 {
798     setupState(_cruiseAoA, _cruiseSpeed,_approachGlideAngle, &_cruiseState);
799     _model.setState(&_cruiseState);
800     _model.setAir(_cruiseP, _cruiseT,
801                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
802
803     // The control configuration
804     _controls.reset();
805     int i;
806     for(i=0; i<_cruiseControls.size(); i++) {
807         Control* c = (Control*)_cruiseControls.get(i);
808         _controls.setInput(c->control, c->val);
809     }
810     _controls.applyControls(1000000); // Huge dt value
811
812     // The local wind
813     float wind[3];
814     Math::mul3(-1, _cruiseState.v, wind);
815     Math::vmul33(_cruiseState.orient, wind, wind);
816  
817     setFuelFraction(_cruiseFuel);
818     setupWeights(false);
819    
820     // Set up the thruster parameters and iterate until the thrust
821     // stabilizes.
822     for(i=0; i<_thrusters.size(); i++) {
823         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
824         t->setWind(wind);
825         t->setAir(_cruiseP, _cruiseT,
826                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
827     }
828     stabilizeThrust();
829
830     updateGearState();
831
832     // Precompute thrust in the model, and calculate aerodynamic forces
833     _model.getBody()->recalc();
834     _model.getBody()->reset();
835     _model.initIteration();
836     _model.calcForces(&_cruiseState);
837 }
838
839 void Airplane::runApproach()
840 {
841     setupState(_approachAoA, _approachSpeed,_approachGlideAngle, &_approachState);
842     _model.setState(&_approachState);
843     _model.setAir(_approachP, _approachT,
844                   Atmosphere::calcStdDensity(_approachP, _approachT));
845
846     // The control configuration
847     _controls.reset();
848     int i;
849     for(i=0; i<_approachControls.size(); i++) {
850         Control* c = (Control*)_approachControls.get(i);
851         _controls.setInput(c->control, c->val);
852     }
853     _controls.applyControls(1000000);
854
855     // The local wind
856     float wind[3];
857     Math::mul3(-1, _approachState.v, wind);
858     Math::vmul33(_approachState.orient, wind, wind);
859     
860     setFuelFraction(_approachFuel);
861
862     setupWeights(true);
863
864     // Run the thrusters until they get to a stable setting.  FIXME:
865     // this is lots of wasted work.
866     for(i=0; i<_thrusters.size(); i++) {
867         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
868         t->setWind(wind);
869         t->setAir(_approachP, _approachT,
870                   Atmosphere::calcStdDensity(_approachP, _approachT));
871     }
872     stabilizeThrust();
873
874     updateGearState();
875
876     // Precompute thrust in the model, and calculate aerodynamic forces
877     _model.getBody()->recalc();
878     _model.getBody()->reset();
879     _model.initIteration();
880     _model.calcForces(&_approachState);
881 }
882
883 void Airplane::applyDragFactor(float factor)
884 {
885     float applied = Math::pow(factor, SOLVE_TWEAK);
886     _dragFactor *= applied;
887     if(_wing)
888       _wing->setDragScale(_wing->getDragScale() * applied);
889     if(_tail)
890       _tail->setDragScale(_tail->getDragScale() * applied);
891     int i;
892     for(i=0; i<_vstabs.size(); i++) {
893         Wing* w = (Wing*)_vstabs.get(i);
894         w->setDragScale(w->getDragScale() * applied);
895     }
896     for(i=0; i<_surfs.size(); i++) {
897         Surface* s = (Surface*)_surfs.get(i);
898         s->setTotalDrag(s->getTotalDrag() * applied);
899     }
900 }
901
902 void Airplane::applyLiftRatio(float factor)
903 {
904     float applied = Math::pow(factor, SOLVE_TWEAK);
905     _liftRatio *= applied;
906     if(_wing)
907       _wing->setLiftRatio(_wing->getLiftRatio() * applied);
908     if(_tail)
909       _tail->setLiftRatio(_tail->getLiftRatio() * applied);
910     int i;
911     for(i=0; i<_vstabs.size(); i++) {
912         Wing* w = (Wing*)_vstabs.get(i);
913         w->setLiftRatio(w->getLiftRatio() * applied);
914     }
915 }
916
917 float Airplane::clamp(float val, float min, float max)
918 {
919     if(val < min) return min;
920     if(val > max) return max;
921     return val;
922 }
923
924 float Airplane::normFactor(float f)
925 {
926     if(f < 0) f = -f;
927     if(f < 1) f = 1/f;
928     return f;
929 }
930
931 void Airplane::solve()
932 {
933     static const float ARCMIN = 0.0002909f;
934
935     float tmp[3];
936     _solutionIterations = 0;
937     _failureMsg = 0;
938
939     while(1) {
940         if(_solutionIterations++ > 10000) { 
941             _failureMsg = "Solution failed to converge after 10000 iterations";
942             return;
943         }
944
945         // Run an iteration at cruise, and extract the needed numbers:
946         runCruise();
947
948         _model.getThrust(tmp);
949         float thrust = tmp[0] + _cruiseWeight * Math::sin(_cruiseGlideAngle) * 9.81;
950
951         _model.getBody()->getAccel(tmp);
952         Math::tmul33(_cruiseState.orient, tmp, tmp);
953         float xforce = _cruiseWeight * tmp[0];
954         float clift0 = _cruiseWeight * tmp[2];
955
956         _model.getBody()->getAngularAccel(tmp);
957         Math::tmul33(_cruiseState.orient, tmp, tmp);
958         float pitch0 = tmp[1];
959
960         // Run an approach iteration, and do likewise
961         runApproach();
962
963         _model.getBody()->getAngularAccel(tmp);
964         Math::tmul33(_approachState.orient, tmp, tmp);
965         double apitch0 = tmp[1];
966
967         _model.getBody()->getAccel(tmp);
968         Math::tmul33(_approachState.orient, tmp, tmp);
969         float alift = _approachWeight * tmp[2];
970
971         // Modify the cruise AoA a bit to get a derivative
972         _cruiseAoA += ARCMIN;
973         runCruise();
974         _cruiseAoA -= ARCMIN;
975
976         _model.getBody()->getAccel(tmp);
977         Math::tmul33(_cruiseState.orient, tmp, tmp);
978         float clift1 = _cruiseWeight * tmp[2];
979
980         // Do the same with the tail incidence
981         _tail->setIncidence(_tailIncidence + ARCMIN);
982         runCruise();
983         _tail->setIncidence(_tailIncidence);
984
985         _model.getBody()->getAngularAccel(tmp);
986         Math::tmul33(_cruiseState.orient, tmp, tmp);
987         float pitch1 = tmp[1];
988
989         // Now calculate:
990         float awgt = 9.8f * _approachWeight;
991
992         float dragFactor = thrust / (thrust-xforce);
993         float liftFactor = awgt / (awgt+alift);
994         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
995         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
996
997         // Sanity:
998         if(dragFactor <= 0 || liftFactor <= 0)
999             break;
1000
1001         // And the elevator control in the approach.  This works just
1002         // like the tail incidence computation (it's solving for the
1003         // same thing -- pitching moment -- by diddling a different
1004         // variable).
1005         const float ELEVDIDDLE = 0.001f;
1006         _approachElevator.val += ELEVDIDDLE;
1007         runApproach();
1008         _approachElevator.val -= ELEVDIDDLE;
1009
1010         _model.getBody()->getAngularAccel(tmp);
1011         Math::tmul33(_approachState.orient, tmp, tmp);
1012         double apitch1 = tmp[1];
1013         float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
1014
1015         // Now apply the values we just computed.  Note that the
1016         // "minor" variables are deferred until we get the lift/drag
1017         // numbers in the right ballpark.
1018
1019         applyDragFactor(dragFactor);
1020         applyLiftRatio(liftFactor);
1021
1022         // DON'T do the following until the above are sane
1023         if(normFactor(dragFactor) > STHRESH*1.0001
1024            || normFactor(liftFactor) > STHRESH*1.0001)
1025         {
1026             continue;
1027         }
1028
1029         // OK, now we can adjust the minor variables:
1030         _cruiseAoA += SOLVE_TWEAK*aoaDelta;
1031         _tailIncidence += SOLVE_TWEAK*tailDelta;
1032         
1033         _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
1034         _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
1035
1036         if(abs(xforce/_cruiseWeight) < STHRESH*0.0001 &&
1037            abs(alift/_approachWeight) < STHRESH*0.0001 &&
1038            abs(aoaDelta) < STHRESH*.000017 &&
1039            abs(tailDelta) < STHRESH*.000017)
1040         {
1041             // If this finaly value is OK, then we're all done
1042             if(abs(elevDelta) < STHRESH*0.0001)
1043                 break;
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