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