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