5 #include "Atmosphere.hpp"
6 #include "ControlMap.hpp"
10 #include "RigidBody.hpp"
11 #include "Surface.hpp"
12 #include "Rotorpart.hpp"
13 #include "Thruster.hpp"
15 #include "Airplane.hpp"
20 inline float norm(float f) { return f<1 ? 1/f : f; }
21 inline float abs(float f) { return f<0 ? -f : f; }
23 // Solver threshold. How close to the solution are we trying
24 // to get? Trying too hard can result in oscillations about
25 // the correct solution, which is bad. Stick this in as a
26 // compile time constant for now, and consider making it
27 // settable per-model.
28 const float STHRESH = 1;
30 // How slowly do we change values in the solver. Too slow, and
31 // the solution converges very slowly. Too fast, and it can
33 const float SOLVE_TWEAK = 0.3226;
38 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
46 _cruiseGlideAngle = 0;
52 _approachGlideAngle = 0;
65 for(i=0; i<_fuselages.size(); i++)
66 delete (Fuselage*)_fuselages.get(i);
67 for(i=0; i<_tanks.size(); i++)
68 delete (Tank*)_tanks.get(i);
69 for(i=0; i<_thrusters.size(); i++)
70 delete (ThrustRec*)_thrusters.get(i);
71 for(i=0; i<_gears.size(); i++) {
72 GearRec* g = (GearRec*)_gears.get(i);
76 for(i=0; i<_surfs.size(); i++)
77 delete (Surface*)_surfs.get(i);
78 for(i=0; i<_contacts.size(); i++) {
79 ContactRec* c = (ContactRec*)_contacts.get(i);
83 for(i=0; i<_solveWeights.size(); i++)
84 delete (SolveWeight*)_solveWeights.get(i);
85 for(i=0; i<_cruiseControls.size(); i++)
86 delete (Control*)_cruiseControls.get(i);
87 for(i=0; i<_approachControls.size(); i++) {
88 Control* c = (Control*)_approachControls.get(i);
89 if(c != &_approachElevator)
94 for(i=0; i<_vstabs.size(); i++)
95 delete (Wing*)_vstabs.get(i);
96 for(i=0; i<_weights.size(); i++)
97 delete (WeightRec*)_weights.get(i);
100 void Airplane::iterate(float dt)
102 // The gear might have moved. Change their aerodynamics.
108 void Airplane::calcFuelWeights()
110 for(int i=0; i<_tanks.size(); i++) {
111 Tank* t = (Tank*)_tanks.get(i);
112 _model.getBody()->setMass(t->handle, t->fill);
116 ControlMap* Airplane::getControlMap()
121 Model* Airplane::getModel()
126 void Airplane::getPilotAccel(float* out)
128 State* s = _model.getState();
131 Glue::geodUp(s->pos, out);
132 Math::mul3(-9.8f, out, out);
133 Math::vmul33(s->orient, out, out);
136 // The regular acceleration
138 // Convert to aircraft coordinates
139 Math::vmul33(s->orient, s->acc, tmp);
143 Math::add3(tmp, out, out);
145 // FIXME: rotational & centripetal acceleration needed
148 void Airplane::setPilotPos(float* pos)
151 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
154 void Airplane::getPilotPos(float* out)
157 for(i=0; i<3; i++) out[i] = _pilotPos[i];
160 int Airplane::numGear()
162 return _gears.size();
165 Gear* Airplane::getGear(int g)
167 return ((GearRec*)_gears.get(g))->gear;
170 Hook* Airplane::getHook()
172 return _model.getHook();
175 Launchbar* Airplane::getLaunchbar()
177 return _model.getLaunchbar();
180 Rotorgear* Airplane::getRotorgear()
182 return _model.getRotorgear();
185 void Airplane::updateGearState()
187 for(int i=0; i<_gears.size(); i++) {
188 GearRec* gr = (GearRec*)_gears.get(i);
189 float ext = gr->gear->getExtension();
191 gr->surf->setXDrag(ext);
192 gr->surf->setYDrag(ext);
193 gr->surf->setZDrag(ext);
197 void Airplane::setApproach(float speed, float altitude, float aoa, float fuel, float gla)
199 _approachSpeed = speed;
200 _approachP = Atmosphere::getStdPressure(altitude);
201 _approachT = Atmosphere::getStdTemperature(altitude);
203 _approachFuel = fuel;
204 _approachGlideAngle = gla;
207 void Airplane::setCruise(float speed, float altitude, float fuel, float gla)
209 _cruiseSpeed = speed;
210 _cruiseP = Atmosphere::getStdPressure(altitude);
211 _cruiseT = Atmosphere::getStdTemperature(altitude);
215 _cruiseGlideAngle = gla;
218 void Airplane::setElevatorControl(int control)
220 _approachElevator.control = control;
221 _approachElevator.val = 0;
222 _approachControls.add(&_approachElevator);
225 void Airplane::addApproachControl(int control, float val)
227 Control* c = new Control();
228 c->control = control;
230 _approachControls.add(c);
233 void Airplane::addCruiseControl(int control, float val)
235 Control* c = new Control();
236 c->control = control;
238 _cruiseControls.add(c);
241 void Airplane::addSolutionWeight(bool approach, int idx, float wgt)
243 SolveWeight* w = new SolveWeight();
244 w->approach = approach;
247 _solveWeights.add(w);
250 int Airplane::numTanks()
252 return _tanks.size();
255 float Airplane::getFuel(int tank)
257 return ((Tank*)_tanks.get(tank))->fill;
260 float Airplane::setFuel(int tank, float fuel)
262 return ((Tank*)_tanks.get(tank))->fill = fuel;
265 float Airplane::getFuelDensity(int tank)
267 return ((Tank*)_tanks.get(tank))->density;
270 float Airplane::getTankCapacity(int tank)
272 return ((Tank*)_tanks.get(tank))->cap;
275 void Airplane::setWeight(float weight)
277 _emptyWeight = weight;
280 void Airplane::setWing(Wing* wing)
285 void Airplane::setTail(Wing* tail)
290 void Airplane::addVStab(Wing* vstab)
295 void Airplane::addFuselage(float* front, float* back, float width,
296 float taper, float mid,
297 float cx, float cy, float cz, float idrag)
299 Fuselage* f = new Fuselage();
302 f->front[i] = front[i];
303 f->back[i] = back[i];
315 int Airplane::addTank(float* pos, float cap, float density)
317 Tank* t = new Tank();
319 for(i=0; i<3; i++) t->pos[i] = pos[i];
322 t->density = density;
323 t->handle = 0xffffffff;
324 return _tanks.add(t);
327 void Airplane::addGear(Gear* gear)
329 GearRec* g = new GearRec();
335 void Airplane::addHook(Hook* hook)
337 _model.addHook(hook);
340 void Airplane::addHitch(Hitch* hitch)
342 _model.addHitch(hitch);
345 void Airplane::addLaunchbar(Launchbar* launchbar)
347 _model.addLaunchbar(launchbar);
350 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
352 ThrustRec* t = new ThrustRec();
353 t->thruster = thruster;
356 for(i=0; i<3; i++) t->cg[i] = cg[i];
360 void Airplane::addBallast(float* pos, float mass)
362 _model.getBody()->addMass(mass, pos);
366 int Airplane::addWeight(float* pos, float size)
368 WeightRec* wr = new WeightRec();
369 wr->handle = _model.getBody()->addMass(0, pos);
371 wr->surf = new Surface(this);
372 wr->surf->setPosition(pos);
373 wr->surf->setTotalDrag(size*size);
374 _model.addSurface(wr->surf);
375 _surfs.add(wr->surf);
377 return _weights.add(wr);
380 void Airplane::setWeight(int handle, float mass)
382 WeightRec* wr = (WeightRec*)_weights.get(handle);
384 _model.getBody()->setMass(wr->handle, mass);
386 // Kill the aerodynamic drag if the mass is exactly zero. This is
387 // how we simulate droppable stores.
389 wr->surf->setXDrag(0);
390 wr->surf->setYDrag(0);
391 wr->surf->setZDrag(0);
393 wr->surf->setXDrag(1);
394 wr->surf->setYDrag(1);
395 wr->surf->setZDrag(1);
399 void Airplane::setFuelFraction(float frac)
402 for(i=0; i<_tanks.size(); i++) {
403 Tank* t = (Tank*)_tanks.get(i);
404 t->fill = frac * t->cap;
405 _model.getBody()->setMass(t->handle, t->cap * frac);
409 float Airplane::getDragCoefficient()
414 float Airplane::getLiftRatio()
419 float Airplane::getCruiseAoA()
424 float Airplane::getTailIncidence()
426 return _tailIncidence;
429 const char* Airplane::getFailureMsg()
434 int Airplane::getSolutionIterations()
436 return _solutionIterations;
439 void Airplane::setupState(float aoa, float speed, float gla, State* s)
441 float cosAoA = Math::cos(aoa);
442 float sinAoA = Math::sin(aoa);
443 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
444 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
445 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
447 s->v[0] = speed*Math::cos(gla); s->v[1] = -speed*Math::sin(gla); s->v[2] = 0;
451 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
453 // Put us 1m above the origin, or else the gravity computation in
458 void Airplane::addContactPoint(float* pos)
460 ContactRec* c = new ContactRec;
468 float Airplane::compileWing(Wing* w)
470 // The tip of the wing is a contact point
473 addContactPoint(tip);
474 if(w->isMirrored()) {
476 addContactPoint(tip);
479 // Make sure it's initialized. The surfaces will pop out with
480 // total drag coefficients equal to their areas, which is what we
486 for(i=0; i<w->numSurfaces(); i++) {
487 Surface* s = (Surface*)w->getSurface(i);
489 float td = s->getTotalDrag();
492 _model.addSurface(s);
494 float mass = w->getSurfaceWeight(i);
495 mass = mass * Math::sqrt(mass);
498 _model.getBody()->addMass(mass, pos);
504 void Airplane::compileRotorgear()
506 getRotorgear()->compile();
509 float Airplane::compileFuselage(Fuselage* f)
511 // The front and back are contact points
512 addContactPoint(f->front);
513 addContactPoint(f->back);
517 Math::sub3(f->front, f->back, fwd);
518 float len = Math::mag3(fwd);
520 _failureMsg = "Zero length fuselage";
523 float wid = f->width;
524 int segs = (int)Math::ceil(len/wid);
525 float segWgt = len*wid/segs;
527 for(j=0; j<segs; j++) {
528 float frac = (j+0.5f) / segs;
532 scale = f->taper+(1-f->taper) * (frac / f->mid);
534 if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
535 // Correct calculation of width for fuselage taper.
536 scale = 1 - (1-f->taper) * (frac - f->mid) / (1 - f->mid);
538 // Original, incorrect calculation of width for fuselage taper.
539 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
545 Math::mul3(frac, fwd, pos);
546 Math::add3(f->back, pos, pos);
548 // _Mass_ weighting goes as surface area^(3/2)
549 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
550 _model.getBody()->addMass(mass, pos);
553 // Make a Surface too
554 Surface* s = new Surface(this);
557 // The following is the original YASim value for sideDrag.
558 // Originally YASim calculated the fuselage's lateral drag
559 // coefficient as (solver drag factor) * (len/wid).
560 // However, this greatly underestimates a fuselage's lateral drag.
561 float sideDrag = len/wid;
563 if ( isVersionOrNewer( YASIM_VERSION_32 ) ) {
564 // New YASim assumes a fixed lateral drag coefficient of 0.5.
565 // This will not be multiplied by the solver drag factor, because
566 // that factor is tuned to match the drag in the direction of
567 // flight, which is completely independent of lateral drag.
568 // The value of 0.5 is only a ballpark estimate, roughly matching
569 // the side-on drag for a long cylinder at the higher Reynolds
570 // numbers typical for an aircraft's lateral drag.
571 // This fits if the fuselage is long and has a round cross section.
572 // For flat-sided fuselages, the value should be increased, up to
573 // a limit of around 2 for a long rectangular prism.
574 // For very short fuselages, in which the end effects are strong,
575 // the value should be reduced.
576 // Such adjustments can be made using the fuselage's "cy" and "cz"
577 // XML parameters: "cy" for the sides, "cz" for top and bottom.
581 if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
584 s->setYDrag(sideDrag*f->_cy);
585 s->setZDrag(sideDrag*f->_cz);
586 if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
587 s->setTotalDrag(scale*segWgt);
589 s->setTotalDrag(scale*segWgt*f->_cx);
591 s->setInducedDrag(f->_idrag);
593 // FIXME: fails for fuselages aligned along the Y axis
595 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
597 y[0] = 0; y[1] = 1; y[2] = 0;
598 Math::cross3(x, y, z);
600 Math::cross3(z, x, y);
601 s->setOrientation(o);
603 _model.addSurface(s);
610 // FIXME: should probably add a mass for the gear, too
611 void Airplane::compileGear(GearRec* gr)
615 // Make a Surface object for the aerodynamic behavior
616 Surface* s = new Surface(this);
619 // Put the surface at the half-way point on the gear strut, give
620 // it a drag coefficient equal to a square of the same dimension
621 // (gear are really draggy) and make it symmetric. Assume that
622 // the "length" of the gear is 3x the compression distance
623 float pos[3], cmp[3];
624 g->getCompression(cmp);
625 float length = 3 * Math::mag3(cmp);
627 Math::mul3(0.5, cmp, cmp);
628 Math::add3(pos, cmp, pos);
631 s->setTotalDrag(length*length);
634 _model.addSurface(s);
638 void Airplane::compileContactPoints()
640 // Figure it will compress by 20cm
643 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
645 // Give it a spring constant such that at full compression it will
646 // hold up 10 times the planes mass. That's about right. Yeah.
647 float mass = _model.getBody()->getTotalMass();
648 float spring = (1/DIST) * 9.8f * 10.0f * mass;
649 float damp = 2 * Math::sqrt(spring * mass);
652 for(i=0; i<_contacts.size(); i++) {
653 ContactRec* c = (ContactRec*)_contacts.get(i);
655 Gear* g = new Gear();
657 g->setPosition(c->p);
659 g->setCompression(comp);
660 g->setSpring(spring);
665 g->setStaticFriction(0.6f);
666 g->setDynamicFriction(0.5f);
667 g->setContactPoint(1);
673 void Airplane::compile()
675 RigidBody* body = _model.getBody();
676 int firstMass = body->numMasses();
678 // Generate the point masses for the plane. Just use unitless
679 // numbers for a first pass, then go back through and rescale to
680 // make the weight right.
685 aeroWgt += compileWing(_wing);
687 aeroWgt += compileWing(_tail);
689 for(i=0; i<_vstabs.size(); i++)
690 aeroWgt += compileWing((Wing*)_vstabs.get(i));
694 for(i=0; i<_fuselages.size(); i++)
695 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
697 // Count up the absolute weight we have
698 float nonAeroWgt = _ballast;
699 for(i=0; i<_thrusters.size(); i++)
700 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
702 // Rescale to the specified empty weight
703 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
704 for(i=firstMass; i<body->numMasses(); i++)
705 body->setMass(i, body->getMass(i)*wscale);
707 // Add the thruster masses
708 for(i=0; i<_thrusters.size(); i++) {
709 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
710 body->addMass(t->mass, t->cg);
713 // Add the tanks, empty for now.
715 for(i=0; i<_tanks.size(); i++) {
716 Tank* t = (Tank*)_tanks.get(i);
717 t->handle = body->addMass(0, t->pos);
720 _cruiseWeight = _emptyWeight + totalFuel*_cruiseFuel;
721 _approachWeight = _emptyWeight + totalFuel*_approachFuel;
725 // Add surfaces for the landing gear.
726 for(i=0; i<_gears.size(); i++)
727 compileGear((GearRec*)_gears.get(i));
729 // The Thruster objects
730 for(i=0; i<_thrusters.size(); i++) {
731 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
732 tr->handle = _model.addThruster(tr->thruster);
739 gespan = _wing->getGroundEffect(gepos);
740 _model.setGroundEffect(gepos, gespan, 0.15f);
743 // solve function below resets failure message
744 // so check if we have any problems and abort here
745 if (_failureMsg) return;
748 if(_wing && _tail) solve();
751 // The rotor(s) mass:
756 // Do this after solveGear, because it creates "gear" objects that
757 // we don't want to affect.
758 compileContactPoints();
761 void Airplane::solveGear()
764 _model.getBody()->getCG(cg);
766 // Calculate spring constant weightings for the gear. Weight by
767 // the inverse of the distance to the c.g. in the XY plane, which
768 // should be correct for most gear arrangements. Add 50cm of
769 // "buffer" to keep things from blowing up with aircraft with a
770 // single gear very near the c.g. (AV-8, for example).
773 for(i=0; i<_gears.size(); i++) {
774 GearRec* gr = (GearRec*)_gears.get(i);
777 Math::sub3(cg, pos, pos);
778 gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
779 if (!g->getIgnoreWhileSolving())
783 // Renormalize so they sum to 1
784 for(i=0; i<_gears.size(); i++)
785 ((GearRec*)_gears.get(i))->wgt /= total;
787 // The force at max compression should be sufficient to stop a
788 // plane moving downwards at 2x the approach descent rate. Assume
789 // a 3 degree approach.
790 float descentRate = 2.0f*_approachSpeed/19.1f;
792 // Spread the kinetic energy according to the gear weights. This
793 // will results in an equal compression fraction (not distance) of
795 float energy = 0.5f*_approachWeight*descentRate*descentRate;
797 for(i=0; i<_gears.size(); i++) {
798 GearRec* gr = (GearRec*)_gears.get(i);
799 float e = energy * gr->wgt;
801 gr->gear->getCompression(comp);
802 float len = Math::mag3(comp)*(1+2*gr->gear->getInitialLoad());
804 // Energy in a spring: e = 0.5 * k * len^2
805 float k = 2 * e / (len*len);
807 gr->gear->setSpring(k * gr->gear->getSpring());
809 // Critically damped (too damped, too!)
810 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt)
811 * gr->gear->getDamping());
815 void Airplane::initEngines()
817 for(int i=0; i<_thrusters.size(); i++) {
818 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
819 tr->thruster->init();
823 void Airplane::stabilizeThrust()
826 for(i=0; i<_thrusters.size(); i++)
827 _model.getThruster(i)->stabilize();
830 void Airplane::setupWeights(bool isApproach)
833 for(i=0; i<_weights.size(); i++)
835 for(i=0; i<_solveWeights.size(); i++) {
836 SolveWeight* w = (SolveWeight*)_solveWeights.get(i);
837 if(w->approach == isApproach)
838 setWeight(w->idx, w->wgt);
842 void Airplane::runCruise()
844 setupState(_cruiseAoA, _cruiseSpeed,_cruiseGlideAngle, &_cruiseState);
845 _model.setState(&_cruiseState);
846 _model.setAir(_cruiseP, _cruiseT,
847 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
849 // The control configuration
852 for(i=0; i<_cruiseControls.size(); i++) {
853 Control* c = (Control*)_cruiseControls.get(i);
854 _controls.setInput(c->control, c->val);
856 _controls.applyControls(1000000); // Huge dt value
860 Math::mul3(-1, _cruiseState.v, wind);
861 Math::vmul33(_cruiseState.orient, wind, wind);
863 setFuelFraction(_cruiseFuel);
866 // Set up the thruster parameters and iterate until the thrust
868 for(i=0; i<_thrusters.size(); i++) {
869 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
871 t->setAir(_cruiseP, _cruiseT,
872 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
878 // Precompute thrust in the model, and calculate aerodynamic forces
879 _model.getBody()->recalc();
880 _model.getBody()->reset();
881 _model.initIteration();
882 _model.calcForces(&_cruiseState);
885 void Airplane::runApproach()
887 setupState(_approachAoA, _approachSpeed,_approachGlideAngle, &_approachState);
888 _model.setState(&_approachState);
889 _model.setAir(_approachP, _approachT,
890 Atmosphere::calcStdDensity(_approachP, _approachT));
892 // The control configuration
895 for(i=0; i<_approachControls.size(); i++) {
896 Control* c = (Control*)_approachControls.get(i);
897 _controls.setInput(c->control, c->val);
899 _controls.applyControls(1000000);
903 Math::mul3(-1, _approachState.v, wind);
904 Math::vmul33(_approachState.orient, wind, wind);
906 setFuelFraction(_approachFuel);
910 // Run the thrusters until they get to a stable setting. FIXME:
911 // this is lots of wasted work.
912 for(i=0; i<_thrusters.size(); i++) {
913 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
915 t->setAir(_approachP, _approachT,
916 Atmosphere::calcStdDensity(_approachP, _approachT));
922 // Precompute thrust in the model, and calculate aerodynamic forces
923 _model.getBody()->recalc();
924 _model.getBody()->reset();
925 _model.initIteration();
926 _model.calcForces(&_approachState);
929 void Airplane::applyDragFactor(float factor)
931 float applied = Math::pow(factor, SOLVE_TWEAK);
932 _dragFactor *= applied;
934 _wing->setDragScale(_wing->getDragScale() * applied);
936 _tail->setDragScale(_tail->getDragScale() * applied);
938 for(i=0; i<_vstabs.size(); i++) {
939 Wing* w = (Wing*)_vstabs.get(i);
940 w->setDragScale(w->getDragScale() * applied);
942 for(i=0; i<_fuselages.size(); i++) {
943 Fuselage* f = (Fuselage*)_fuselages.get(i);
945 for(j=0; j<f->surfs.size(); j++) {
946 Surface* s = (Surface*)f->surfs.get(j);
947 if( isVersionOrNewer( YASIM_VERSION_32 ) ) {
948 // For new YASim, the solver drag factor is only applied to
949 // the X axis for Fuselage Surfaces.
950 // The solver is tuning the coefficient for longitudinal drag,
951 // along the direction of flight. A fuselage's lateral drag
952 // is completely independent and is normally much higher;
953 // it won't be affected by the streamlining done to reduce
954 // longitudinal drag. So the solver should only adjust the
955 // fuselage's longitudinal (X axis) drag coefficient.
956 s->setXDrag(s->getXDrag() * applied);
958 // Originally YASim applied the drag factor to all axes
959 // for Fuselage Surfaces.
960 s->setTotalDrag(s->getTotalDrag() * applied);
964 for(i=0; i<_weights.size(); i++) {
965 WeightRec* wr = (WeightRec*)_weights.get(i);
966 wr->surf->setTotalDrag(wr->surf->getTotalDrag() * applied);
968 for(i=0; i<_gears.size(); i++) {
969 GearRec* gr = (GearRec*)_gears.get(i);
970 gr->surf->setTotalDrag(gr->surf->getTotalDrag() * applied);
974 void Airplane::applyLiftRatio(float factor)
976 float applied = Math::pow(factor, SOLVE_TWEAK);
977 _liftRatio *= applied;
979 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
981 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
983 for(i=0; i<_vstabs.size(); i++) {
984 Wing* w = (Wing*)_vstabs.get(i);
985 w->setLiftRatio(w->getLiftRatio() * applied);
989 float Airplane::clamp(float val, float min, float max)
991 if(val < min) return min;
992 if(val > max) return max;
996 float Airplane::normFactor(float f)
1003 void Airplane::solve()
1005 static const float ARCMIN = 0.0002909f;
1008 _solutionIterations = 0;
1012 if(_solutionIterations++ > 10000) {
1013 _failureMsg = "Solution failed to converge after 10000 iterations";
1017 // Run an iteration at cruise, and extract the needed numbers:
1020 _model.getThrust(tmp);
1021 float thrust = tmp[0] + _cruiseWeight * Math::sin(_cruiseGlideAngle) * 9.81;
1023 _model.getBody()->getAccel(tmp);
1024 Math::tmul33(_cruiseState.orient, tmp, tmp);
1025 float xforce = _cruiseWeight * tmp[0];
1026 float clift0 = _cruiseWeight * tmp[2];
1028 _model.getBody()->getAngularAccel(tmp);
1029 Math::tmul33(_cruiseState.orient, tmp, tmp);
1030 float pitch0 = tmp[1];
1032 // Run an approach iteration, and do likewise
1035 _model.getBody()->getAngularAccel(tmp);
1036 Math::tmul33(_approachState.orient, tmp, tmp);
1037 double apitch0 = tmp[1];
1039 _model.getBody()->getAccel(tmp);
1040 Math::tmul33(_approachState.orient, tmp, tmp);
1041 float alift = _approachWeight * tmp[2];
1043 // Modify the cruise AoA a bit to get a derivative
1044 _cruiseAoA += ARCMIN;
1046 _cruiseAoA -= ARCMIN;
1048 _model.getBody()->getAccel(tmp);
1049 Math::tmul33(_cruiseState.orient, tmp, tmp);
1050 float clift1 = _cruiseWeight * tmp[2];
1052 // Do the same with the tail incidence
1053 _tail->setIncidence(_tailIncidence + ARCMIN);
1055 _tail->setIncidence(_tailIncidence);
1057 _model.getBody()->getAngularAccel(tmp);
1058 Math::tmul33(_cruiseState.orient, tmp, tmp);
1059 float pitch1 = tmp[1];
1062 float awgt = 9.8f * _approachWeight;
1064 float dragFactor = thrust / (thrust-xforce);
1065 float liftFactor = awgt / (awgt+alift);
1066 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
1067 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
1070 if(dragFactor <= 0 || liftFactor <= 0)
1073 // And the elevator control in the approach. This works just
1074 // like the tail incidence computation (it's solving for the
1075 // same thing -- pitching moment -- by diddling a different
1077 const float ELEVDIDDLE = 0.001f;
1078 _approachElevator.val += ELEVDIDDLE;
1080 _approachElevator.val -= ELEVDIDDLE;
1082 _model.getBody()->getAngularAccel(tmp);
1083 Math::tmul33(_approachState.orient, tmp, tmp);
1084 double apitch1 = tmp[1];
1085 float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
1087 // Now apply the values we just computed. Note that the
1088 // "minor" variables are deferred until we get the lift/drag
1089 // numbers in the right ballpark.
1091 applyDragFactor(dragFactor);
1092 applyLiftRatio(liftFactor);
1094 // DON'T do the following until the above are sane
1095 if(normFactor(dragFactor) > STHRESH*1.0001
1096 || normFactor(liftFactor) > STHRESH*1.0001)
1101 // OK, now we can adjust the minor variables:
1102 _cruiseAoA += SOLVE_TWEAK*aoaDelta;
1103 _tailIncidence += SOLVE_TWEAK*tailDelta;
1105 _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
1106 _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
1108 if(abs(xforce/_cruiseWeight) < STHRESH*0.0001 &&
1109 abs(alift/_approachWeight) < STHRESH*0.0001 &&
1110 abs(aoaDelta) < STHRESH*.000017 &&
1111 abs(tailDelta) < STHRESH*.000017)
1113 // If this finaly value is OK, then we're all done
1114 if(abs(elevDelta) < STHRESH*0.0001)
1117 // Otherwise, adjust and do the next iteration
1118 _approachElevator.val += SOLVE_TWEAK * elevDelta;
1119 if(abs(_approachElevator.val) > 1) {
1120 _failureMsg = "Insufficient elevator to trim for approach";
1126 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
1127 _failureMsg = "Drag factor beyond reasonable bounds.";
1129 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
1130 _failureMsg = "Lift ratio beyond reasonable bounds.";
1132 } else if(Math::abs(_cruiseAoA) >= .17453293) {
1133 _failureMsg = "Cruise AoA > 10 degrees";
1135 } else if(Math::abs(_tailIncidence) >= .17453293) {
1136 _failureMsg = "Tail incidence > 10 degrees";
1141 void Airplane::solveHelicopter()
1143 _solutionIterations = 0;
1145 if (getRotorgear()!=0)
1147 Rotorgear* rg = getRotorgear();
1148 applyDragFactor(Math::pow(rg->getYasimDragFactor()/1000,
1150 applyLiftRatio(Math::pow(rg->getYasimLiftFactor(),
1154 //huh, no wing and no rotor? (_rotorgear is constructed,
1155 //if a rotor is defined
1157 applyDragFactor(Math::pow(15.7/1000, 1/SOLVE_TWEAK));
1158 applyLiftRatio(Math::pow(104, 1/SOLVE_TWEAK));
1160 setupState(0,0,0, &_cruiseState);
1161 _model.setState(&_cruiseState);
1164 _model.getBody()->reset();
1165 _model.setAir(_cruiseP, _cruiseT,
1166 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
1170 }; // namespace yasim