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