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