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