]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/Airplane.cpp
GUI ‘restore defaults’ support.
[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(this);
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             if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
535                 // Correct calculation of width for fuselage taper.
536                 scale = 1 - (1-f->taper) * (frac - f->mid) / (1 - f->mid);
537             } else {
538                 // Original, incorrect calculation of width for fuselage taper.
539                 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
540             }
541         }
542
543         // Where are we?
544         float pos[3];
545         Math::mul3(frac, fwd, pos);
546         Math::add3(f->back, pos, pos);
547
548         // _Mass_ weighting goes as surface area^(3/2)
549         float mass = scale*segWgt * Math::sqrt(scale*segWgt);
550         _model.getBody()->addMass(mass, pos);
551         wgt += mass;
552
553         // Make a Surface too
554         Surface* s = new Surface(this);
555         s->setPosition(pos);
556
557         // The following is the original YASim value for sideDrag.
558         // Originally YASim calculated the fuselage's lateral drag
559         // coefficient as (solver drag factor) * (len/wid).
560         // However, this greatly underestimates a fuselage's lateral drag.
561         float sideDrag = len/wid;
562
563         if ( isVersionOrNewer( YASIM_VERSION_32 ) ) {
564             // New YASim assumes a fixed lateral drag coefficient of 0.5.
565             // This will not be multiplied by the solver drag factor, because
566             // that factor is tuned to match the drag in the direction of
567             // flight, which is completely independent of lateral drag.
568             // The value of 0.5 is only a ballpark estimate, roughly matching
569             // the side-on drag for a long cylinder at the higher Reynolds
570             // numbers typical for an aircraft's lateral drag.
571             // This fits if the fuselage is long and has a round cross section.
572             // For flat-sided fuselages, the value should be increased, up to
573             // a limit of around 2 for a long rectangular prism.
574             // For very short fuselages, in which the end effects are strong,
575             // the value should be reduced.
576             // Such adjustments can be made using the fuselage's "cy" and "cz"
577             // XML parameters: "cy" for the sides, "cz" for top and bottom.
578             sideDrag = 0.5;
579         }
580
581         if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
582                 s->setXDrag(f->_cx);
583         }
584         s->setYDrag(sideDrag*f->_cy);
585         s->setZDrag(sideDrag*f->_cz);
586         if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
587                 s->setTotalDrag(scale*segWgt);
588         } else {
589                 s->setTotalDrag(scale*segWgt*f->_cx);
590         }
591         s->setInducedDrag(f->_idrag);
592
593         // FIXME: fails for fuselages aligned along the Y axis
594         float o[9];
595         float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
596         Math::unit3(fwd, x);
597         y[0] = 0; y[1] = 1; y[2] = 0;
598         Math::cross3(x, y, z);
599         Math::unit3(z, z);
600         Math::cross3(z, x, y);
601         s->setOrientation(o);
602
603         _model.addSurface(s);
604         f->surfs.add(s);
605         _surfs.add(s);
606     }
607     return wgt;
608 }
609
610 // FIXME: should probably add a mass for the gear, too
611 void Airplane::compileGear(GearRec* gr)
612 {
613     Gear* g = gr->gear;
614
615     // Make a Surface object for the aerodynamic behavior
616     Surface* s = new Surface(this);
617     gr->surf = s;
618
619     // Put the surface at the half-way point on the gear strut, give
620     // it a drag coefficient equal to a square of the same dimension
621     // (gear are really draggy) and make it symmetric.  Assume that
622     // the "length" of the gear is 3x the compression distance
623     float pos[3], cmp[3];
624     g->getCompression(cmp);
625     float length = 3 * Math::mag3(cmp);
626     g->getPosition(pos);
627     Math::mul3(0.5, cmp, cmp);
628     Math::add3(pos, cmp, pos);
629
630     s->setPosition(pos);
631     s->setTotalDrag(length*length);
632
633     _model.addGear(g);
634     _model.addSurface(s);
635     _surfs.add(s);
636 }
637
638 void Airplane::compileContactPoints()
639 {
640     // Figure it will compress by 20cm
641     float comp[3];
642     float DIST = 0.2f;
643     comp[0] = 0; comp[1] = 0; comp[2] = DIST;
644
645     // Give it a spring constant such that at full compression it will
646     // hold up 10 times the planes mass.  That's about right.  Yeah.
647     float mass = _model.getBody()->getTotalMass();
648     float spring = (1/DIST) * 9.8f * 10.0f * mass;
649     float damp = 2 * Math::sqrt(spring * mass);
650
651     int i;
652     for(i=0; i<_contacts.size(); i++) {
653         ContactRec* c = (ContactRec*)_contacts.get(i);
654
655         Gear* g = new Gear();
656         c->gear = g;
657         g->setPosition(c->p);
658         
659         g->setCompression(comp);
660         g->setSpring(spring);
661         g->setDamping(damp);
662         g->setBrake(1);
663
664         // I made these up
665         g->setStaticFriction(0.6f);
666         g->setDynamicFriction(0.5f);
667         g->setContactPoint(1);
668
669         _model.addGear(g);
670     }
671 }
672
673 void Airplane::compile()
674 {
675     RigidBody* body = _model.getBody();
676     int firstMass = body->numMasses();
677
678     // Generate the point masses for the plane.  Just use unitless
679     // numbers for a first pass, then go back through and rescale to
680     // make the weight right.
681     float aeroWgt = 0;
682
683     // The Wing objects
684     if (_wing)
685       aeroWgt += compileWing(_wing);
686     if (_tail)
687       aeroWgt += compileWing(_tail);
688     int i;
689     for(i=0; i<_vstabs.size(); i++)
690         aeroWgt += compileWing((Wing*)_vstabs.get(i)); 
691
692
693     // The fuselage(s)
694     for(i=0; i<_fuselages.size(); i++)
695         aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
696
697     // Count up the absolute weight we have
698     float nonAeroWgt = _ballast;
699     for(i=0; i<_thrusters.size(); i++)
700         nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
701
702     // Rescale to the specified empty weight
703     float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
704     for(i=firstMass; i<body->numMasses(); i++)
705         body->setMass(i, body->getMass(i)*wscale);
706
707     // Add the thruster masses
708     for(i=0; i<_thrusters.size(); i++) {
709         ThrustRec* t = (ThrustRec*)_thrusters.get(i);
710         body->addMass(t->mass, t->cg);
711     }
712
713     // Add the tanks, empty for now.
714     float totalFuel = 0;
715     for(i=0; i<_tanks.size(); i++) { 
716         Tank* t = (Tank*)_tanks.get(i); 
717         t->handle = body->addMass(0, t->pos);
718         totalFuel += t->cap;
719     }
720     _cruiseWeight = _emptyWeight + totalFuel*_cruiseFuel;
721     _approachWeight = _emptyWeight + totalFuel*_approachFuel;
722
723     body->recalc();
724
725     // Add surfaces for the landing gear.
726     for(i=0; i<_gears.size(); i++)
727         compileGear((GearRec*)_gears.get(i));
728
729     // The Thruster objects
730     for(i=0; i<_thrusters.size(); i++) {
731         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
732         tr->handle = _model.addThruster(tr->thruster);
733     }
734
735     // Ground effect
736     if(_wing) {
737         float gepos[3];
738         float gespan = 0;
739         gespan = _wing->getGroundEffect(gepos);
740         _model.setGroundEffect(gepos, gespan, 0.15f);
741     }
742
743     // solve function below resets failure message
744     // so check if we have any problems and abort here
745     if (_failureMsg) return;
746
747     solveGear();
748     if(_wing && _tail) solve();
749     else
750     {
751        // The rotor(s) mass:
752        compileRotorgear(); 
753        solveHelicopter();
754     }
755
756     // Do this after solveGear, because it creates "gear" objects that
757     // we don't want to affect.
758     compileContactPoints();
759 }
760
761 void Airplane::solveGear()
762 {
763     float cg[3], pos[3];
764     _model.getBody()->getCG(cg);
765
766     // Calculate spring constant weightings for the gear.  Weight by
767     // the inverse of the distance to the c.g. in the XY plane, which
768     // should be correct for most gear arrangements.  Add 50cm of
769     // "buffer" to keep things from blowing up with aircraft with a
770     // single gear very near the c.g. (AV-8, for example).
771     float total = 0;
772     int i;
773     for(i=0; i<_gears.size(); i++) {
774         GearRec* gr = (GearRec*)_gears.get(i);
775         Gear* g = gr->gear;
776         g->getPosition(pos);
777         Math::sub3(cg, pos, pos);
778         gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
779         if (!g->getIgnoreWhileSolving())
780             total += gr->wgt;
781     }
782
783     // Renormalize so they sum to 1
784     for(i=0; i<_gears.size(); i++)
785         ((GearRec*)_gears.get(i))->wgt /= total;
786     
787     // The force at max compression should be sufficient to stop a
788     // plane moving downwards at 2x the approach descent rate.  Assume
789     // a 3 degree approach.
790     float descentRate = 2.0f*_approachSpeed/19.1f;
791
792     // Spread the kinetic energy according to the gear weights.  This
793     // will results in an equal compression fraction (not distance) of
794     // each gear.
795     float energy = 0.5f*_approachWeight*descentRate*descentRate;
796
797     for(i=0; i<_gears.size(); i++) {
798         GearRec* gr = (GearRec*)_gears.get(i);
799         float e = energy * gr->wgt;
800         float comp[3];
801         gr->gear->getCompression(comp);
802         float len = Math::mag3(comp)*(1+2*gr->gear->getInitialLoad());
803
804         // Energy in a spring: e = 0.5 * k * len^2
805         float k = 2 * e / (len*len);
806
807         gr->gear->setSpring(k * gr->gear->getSpring());
808
809         // Critically damped (too damped, too!)
810         gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt)
811                              * gr->gear->getDamping());
812     }
813 }
814
815 void Airplane::initEngines()
816 {
817     for(int i=0; i<_thrusters.size(); i++) {
818         ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
819         tr->thruster->init();
820     }
821 }
822
823 void Airplane::stabilizeThrust()
824 {
825     int i;
826     for(i=0; i<_thrusters.size(); i++)
827         _model.getThruster(i)->stabilize();
828 }
829
830 void Airplane::setupWeights(bool isApproach)
831 {
832     int i;
833     for(i=0; i<_weights.size(); i++)
834         setWeight(i, 0);
835     for(i=0; i<_solveWeights.size(); i++) {
836         SolveWeight* w = (SolveWeight*)_solveWeights.get(i);
837         if(w->approach == isApproach)
838             setWeight(w->idx, w->wgt);
839     }
840 }
841
842 void Airplane::runCruise()
843 {
844     setupState(_cruiseAoA, _cruiseSpeed,_cruiseGlideAngle, &_cruiseState);
845     _model.setState(&_cruiseState);
846     _model.setAir(_cruiseP, _cruiseT,
847                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
848
849     // The control configuration
850     _controls.reset();
851     int i;
852     for(i=0; i<_cruiseControls.size(); i++) {
853         Control* c = (Control*)_cruiseControls.get(i);
854         _controls.setInput(c->control, c->val);
855     }
856     _controls.applyControls(1000000); // Huge dt value
857
858     // The local wind
859     float wind[3];
860     Math::mul3(-1, _cruiseState.v, wind);
861     Math::vmul33(_cruiseState.orient, wind, wind);
862  
863     setFuelFraction(_cruiseFuel);
864     setupWeights(false);
865    
866     // Set up the thruster parameters and iterate until the thrust
867     // stabilizes.
868     for(i=0; i<_thrusters.size(); i++) {
869         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
870         t->setWind(wind);
871         t->setAir(_cruiseP, _cruiseT,
872                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
873     }
874     stabilizeThrust();
875
876     updateGearState();
877
878     // Precompute thrust in the model, and calculate aerodynamic forces
879     _model.getBody()->recalc();
880     _model.getBody()->reset();
881     _model.initIteration();
882     _model.calcForces(&_cruiseState);
883 }
884
885 void Airplane::runApproach()
886 {
887     setupState(_approachAoA, _approachSpeed,_approachGlideAngle, &_approachState);
888     _model.setState(&_approachState);
889     _model.setAir(_approachP, _approachT,
890                   Atmosphere::calcStdDensity(_approachP, _approachT));
891
892     // The control configuration
893     _controls.reset();
894     int i;
895     for(i=0; i<_approachControls.size(); i++) {
896         Control* c = (Control*)_approachControls.get(i);
897         _controls.setInput(c->control, c->val);
898     }
899     _controls.applyControls(1000000);
900
901     // The local wind
902     float wind[3];
903     Math::mul3(-1, _approachState.v, wind);
904     Math::vmul33(_approachState.orient, wind, wind);
905     
906     setFuelFraction(_approachFuel);
907
908     setupWeights(true);
909
910     // Run the thrusters until they get to a stable setting.  FIXME:
911     // this is lots of wasted work.
912     for(i=0; i<_thrusters.size(); i++) {
913         Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
914         t->setWind(wind);
915         t->setAir(_approachP, _approachT,
916                   Atmosphere::calcStdDensity(_approachP, _approachT));
917     }
918     stabilizeThrust();
919
920     updateGearState();
921
922     // Precompute thrust in the model, and calculate aerodynamic forces
923     _model.getBody()->recalc();
924     _model.getBody()->reset();
925     _model.initIteration();
926     _model.calcForces(&_approachState);
927 }
928
929 void Airplane::applyDragFactor(float factor)
930 {
931     float applied = Math::pow(factor, SOLVE_TWEAK);
932     _dragFactor *= applied;
933     if(_wing)
934       _wing->setDragScale(_wing->getDragScale() * applied);
935     if(_tail)
936       _tail->setDragScale(_tail->getDragScale() * applied);
937     int i;
938     for(i=0; i<_vstabs.size(); i++) {
939         Wing* w = (Wing*)_vstabs.get(i);
940         w->setDragScale(w->getDragScale() * applied);
941     }
942     for(i=0; i<_fuselages.size(); i++) {
943         Fuselage* f = (Fuselage*)_fuselages.get(i);
944         int j;
945         for(j=0; j<f->surfs.size(); j++) {
946             Surface* s = (Surface*)f->surfs.get(j);
947             if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
948                 // For new YASim, the solver drag factor is only applied to
949                 // the X axis for Fuselage Surfaces.
950                 // The solver is tuning the coefficient for longitudinal drag,
951                 // along the direction of flight. A fuselage's lateral drag
952                 // is completely independent and is normally much higher;
953                 // it won't be affected by the streamlining done to reduce
954                 // longitudinal drag. So the solver should only adjust the
955                 // fuselage's longitudinal (X axis) drag coefficient.
956                 s->setXDrag(s->getXDrag() * applied);
957             } else {
958                 // Originally YASim applied the drag factor to all axes
959                 // for Fuselage Surfaces.
960                 s->setTotalDrag(s->getTotalDrag() * applied);
961             }
962         }
963     }
964     for(i=0; i<_weights.size(); i++) {
965         WeightRec* wr = (WeightRec*)_weights.get(i);
966         wr->surf->setTotalDrag(wr->surf->getTotalDrag() * applied);
967     }
968     for(i=0; i<_gears.size(); i++) {
969         GearRec* gr = (GearRec*)_gears.get(i);
970         gr->surf->setTotalDrag(gr->surf->getTotalDrag() * applied);
971     }
972 }
973
974 void Airplane::applyLiftRatio(float factor)
975 {
976     float applied = Math::pow(factor, SOLVE_TWEAK);
977     _liftRatio *= applied;
978     if(_wing)
979       _wing->setLiftRatio(_wing->getLiftRatio() * applied);
980     if(_tail)
981       _tail->setLiftRatio(_tail->getLiftRatio() * applied);
982     int i;
983     for(i=0; i<_vstabs.size(); i++) {
984         Wing* w = (Wing*)_vstabs.get(i);
985         w->setLiftRatio(w->getLiftRatio() * applied);
986     }
987 }
988
989 float Airplane::clamp(float val, float min, float max)
990 {
991     if(val < min) return min;
992     if(val > max) return max;
993     return val;
994 }
995
996 float Airplane::normFactor(float f)
997 {
998     if(f < 0) f = -f;
999     if(f < 1) f = 1/f;
1000     return f;
1001 }
1002
1003 void Airplane::solve()
1004 {
1005     static const float ARCMIN = 0.0002909f;
1006
1007     float tmp[3];
1008     _solutionIterations = 0;
1009     _failureMsg = 0;
1010
1011     while(1) {
1012         if(_solutionIterations++ > 10000) { 
1013             _failureMsg = "Solution failed to converge after 10000 iterations";
1014             return;
1015         }
1016
1017         // Run an iteration at cruise, and extract the needed numbers:
1018         runCruise();
1019
1020         _model.getThrust(tmp);
1021         float thrust = tmp[0] + _cruiseWeight * Math::sin(_cruiseGlideAngle) * 9.81;
1022
1023         _model.getBody()->getAccel(tmp);
1024         Math::tmul33(_cruiseState.orient, tmp, tmp);
1025         float xforce = _cruiseWeight * tmp[0];
1026         float clift0 = _cruiseWeight * tmp[2];
1027
1028         _model.getBody()->getAngularAccel(tmp);
1029         Math::tmul33(_cruiseState.orient, tmp, tmp);
1030         float pitch0 = tmp[1];
1031
1032         // Run an approach iteration, and do likewise
1033         runApproach();
1034
1035         _model.getBody()->getAngularAccel(tmp);
1036         Math::tmul33(_approachState.orient, tmp, tmp);
1037         double apitch0 = tmp[1];
1038
1039         _model.getBody()->getAccel(tmp);
1040         Math::tmul33(_approachState.orient, tmp, tmp);
1041         float alift = _approachWeight * tmp[2];
1042
1043         // Modify the cruise AoA a bit to get a derivative
1044         _cruiseAoA += ARCMIN;
1045         runCruise();
1046         _cruiseAoA -= ARCMIN;
1047
1048         _model.getBody()->getAccel(tmp);
1049         Math::tmul33(_cruiseState.orient, tmp, tmp);
1050         float clift1 = _cruiseWeight * tmp[2];
1051
1052         // Do the same with the tail incidence
1053         _tail->setIncidence(_tailIncidence + ARCMIN);
1054         runCruise();
1055         _tail->setIncidence(_tailIncidence);
1056
1057         _model.getBody()->getAngularAccel(tmp);
1058         Math::tmul33(_cruiseState.orient, tmp, tmp);
1059         float pitch1 = tmp[1];
1060
1061         // Now calculate:
1062         float awgt = 9.8f * _approachWeight;
1063
1064         float dragFactor = thrust / (thrust-xforce);
1065         float liftFactor = awgt / (awgt+alift);
1066         float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
1067         float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
1068
1069         // Sanity:
1070         if(dragFactor <= 0 || liftFactor <= 0)
1071             break;
1072
1073         // And the elevator control in the approach.  This works just
1074         // like the tail incidence computation (it's solving for the
1075         // same thing -- pitching moment -- by diddling a different
1076         // variable).
1077         const float ELEVDIDDLE = 0.001f;
1078         _approachElevator.val += ELEVDIDDLE;
1079         runApproach();
1080         _approachElevator.val -= ELEVDIDDLE;
1081
1082         _model.getBody()->getAngularAccel(tmp);
1083         Math::tmul33(_approachState.orient, tmp, tmp);
1084         double apitch1 = tmp[1];
1085         float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
1086
1087         // Now apply the values we just computed.  Note that the
1088         // "minor" variables are deferred until we get the lift/drag
1089         // numbers in the right ballpark.
1090
1091         applyDragFactor(dragFactor);
1092         applyLiftRatio(liftFactor);
1093
1094         // DON'T do the following until the above are sane
1095         if(normFactor(dragFactor) > STHRESH*1.0001
1096            || normFactor(liftFactor) > STHRESH*1.0001)
1097         {
1098             continue;
1099         }
1100
1101         // OK, now we can adjust the minor variables:
1102         _cruiseAoA += SOLVE_TWEAK*aoaDelta;
1103         _tailIncidence += SOLVE_TWEAK*tailDelta;
1104         
1105         _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
1106         _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
1107
1108         if(abs(xforce/_cruiseWeight) < STHRESH*0.0001 &&
1109            abs(alift/_approachWeight) < STHRESH*0.0001 &&
1110            abs(aoaDelta) < STHRESH*.000017 &&
1111            abs(tailDelta) < STHRESH*.000017)
1112         {
1113             // If this finaly value is OK, then we're all done
1114             if(abs(elevDelta) < STHRESH*0.0001)
1115                 break;
1116
1117             // Otherwise, adjust and do the next iteration
1118             _approachElevator.val += SOLVE_TWEAK * elevDelta;
1119             if(abs(_approachElevator.val) > 1) {
1120                 _failureMsg = "Insufficient elevator to trim for approach";
1121                 break;
1122             }
1123         }
1124     }
1125
1126     if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
1127         _failureMsg = "Drag factor beyond reasonable bounds.";
1128         return;
1129     } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
1130         _failureMsg = "Lift ratio beyond reasonable bounds.";
1131         return;
1132     } else if(Math::abs(_cruiseAoA) >= .17453293) {
1133         _failureMsg = "Cruise AoA > 10 degrees";
1134         return;
1135     } else if(Math::abs(_tailIncidence) >= .17453293) {
1136         _failureMsg = "Tail incidence > 10 degrees";
1137         return;
1138     }
1139 }
1140
1141 void Airplane::solveHelicopter()
1142 {
1143     _solutionIterations = 0;
1144     _failureMsg = 0;
1145     if (getRotorgear()!=0)
1146     {
1147         Rotorgear* rg = getRotorgear();
1148         applyDragFactor(Math::pow(rg->getYasimDragFactor()/1000,
1149             1/SOLVE_TWEAK));
1150         applyLiftRatio(Math::pow(rg->getYasimLiftFactor(),
1151             1/SOLVE_TWEAK));
1152     }
1153     else
1154     //huh, no wing and no rotor? (_rotorgear is constructed, 
1155     //if a rotor is defined
1156     {
1157         applyDragFactor(Math::pow(15.7/1000, 1/SOLVE_TWEAK));
1158         applyLiftRatio(Math::pow(104, 1/SOLVE_TWEAK));
1159     }
1160     setupState(0,0,0, &_cruiseState);
1161     _model.setState(&_cruiseState);
1162     setupWeights(true);
1163     _controls.reset();
1164     _model.getBody()->reset();
1165     _model.setAir(_cruiseP, _cruiseT,
1166                   Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
1167     
1168 }
1169
1170 }; // namespace yasim