1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
15 inline float norm(float f) { return f<1 ? 1/f : f; }
16 inline float abs(float f) { return f<0 ? -f : f; }
21 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
44 for(i=0; i<_fuselages.size(); i++)
45 delete (Fuselage*)_fuselages.get(i);
46 for(i=0; i<_tanks.size(); i++)
47 delete (Tank*)_tanks.get(i);
48 for(i=0; i<_thrusters.size(); i++)
49 delete (ThrustRec*)_thrusters.get(i);
50 for(i=0; i<_gears.size(); i++)
51 delete (GearRec*)_gears.get(i);
52 for(i=0; i<_surfs.size(); i++)
53 delete (Surface*)_surfs.get(i);
54 for(i=0; i<_contacts.size(); i++)
55 delete[] (float*)_contacts.get(i);
58 void Airplane::iterate(float dt)
60 // The gear might have moved. Change their aerodynamics.
65 // FIXME: Consume fuel
68 ControlMap* Airplane::getControlMap()
73 Model* Airplane::getModel()
78 void Airplane::getPilotAccel(float* out)
80 State* s = _model.getState();
83 Glue::geodUp(s->pos, out);
84 Math::mul3(-9.8f, out, out);
86 // The regular acceleration
88 Math::mul3(-1, s->acc, tmp);
89 Math::add3(tmp, out, out);
91 // Convert to aircraft coordinates
92 Math::vmul33(s->orient, out, out);
94 // FIXME: rotational & centripetal acceleration needed
97 void Airplane::setPilotPos(float* pos)
100 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
103 void Airplane::getPilotPos(float* out)
106 for(i=0; i<3; i++) out[i] = _pilotPos[i];
109 int Airplane::numGear()
111 return _gears.size();
114 Gear* Airplane::getGear(int g)
116 return ((GearRec*)_gears.get(g))->gear;
119 void Airplane::updateGearState()
121 for(int i=0; i<_gears.size(); i++) {
122 GearRec* gr = (GearRec*)_gears.get(i);
123 float ext = gr->gear->getExtension();
125 gr->surf->setXDrag(ext);
126 gr->surf->setYDrag(ext);
127 gr->surf->setZDrag(ext);
131 void Airplane::setApproach(float speed, float altitude)
133 // The zero AoA will become a calculated stall AoA in compile()
134 setApproach(speed, altitude, 0);
137 void Airplane::setApproach(float speed, float altitude, float aoa)
139 _approachSpeed = speed;
140 _approachP = Atmosphere::getStdPressure(altitude);
141 _approachT = Atmosphere::getStdTemperature(altitude);
145 void Airplane::setCruise(float speed, float altitude)
147 _cruiseSpeed = speed;
148 _cruiseP = Atmosphere::getStdPressure(altitude);
149 _cruiseT = Atmosphere::getStdTemperature(altitude);
154 void Airplane::setElevatorControl(int control)
156 _approachElevator.control = control;
157 _approachElevator.val = 0;
158 _approachControls.add(&_approachElevator);
161 void Airplane::addApproachControl(int control, float val)
163 Control* c = new Control();
164 c->control = control;
166 _approachControls.add(c);
169 void Airplane::addCruiseControl(int control, float val)
171 Control* c = new Control();
172 c->control = control;
174 _cruiseControls.add(c);
177 int Airplane::numTanks()
179 return _tanks.size();
182 float Airplane::getFuel(int tank)
184 return ((Tank*)_tanks.get(tank))->fill;
187 float Airplane::getFuelDensity(int tank)
189 return ((Tank*)_tanks.get(tank))->density;
192 void Airplane::setWeight(float weight)
194 _emptyWeight = weight;
197 void Airplane::setWing(Wing* wing)
202 void Airplane::setTail(Wing* tail)
207 void Airplane::addVStab(Wing* vstab)
212 void Airplane::addFuselage(float* front, float* back, float width,
213 float taper, float mid)
215 Fuselage* f = new Fuselage();
218 f->front[i] = front[i];
219 f->back[i] = back[i];
227 int Airplane::addTank(float* pos, float cap, float density)
229 Tank* t = new Tank();
231 for(i=0; i<3; i++) t->pos[i] = pos[i];
234 t->density = density;
235 t->handle = 0xffffffff;
236 return _tanks.add(t);
239 void Airplane::addGear(Gear* gear)
241 GearRec* g = new GearRec();
247 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
249 ThrustRec* t = new ThrustRec();
250 t->thruster = thruster;
253 for(i=0; i<3; i++) t->cg[i] = cg[i];
257 void Airplane::addBallast(float* pos, float mass)
259 _model.getBody()->addMass(mass, pos);
263 int Airplane::addWeight(float* pos, float size)
265 WeightRec* wr = new WeightRec();
266 wr->handle = _model.getBody()->addMass(0, pos);
268 wr->surf = new Surface();
269 wr->surf->setPosition(pos);
270 wr->surf->setTotalDrag(size*size);
271 _model.addSurface(wr->surf);
272 _surfs.add(wr->surf);
274 return _weights.add(wr);
277 void Airplane::setWeight(int handle, float mass)
279 WeightRec* wr = (WeightRec*)_weights.get(handle);
281 _model.getBody()->setMass(wr->handle, mass);
283 // Kill the aerodynamic drag if the mass is exactly zero. This is
284 // how we simulate droppable stores.
286 wr->surf->setXDrag(0);
287 wr->surf->setYDrag(0);
288 wr->surf->setZDrag(0);
290 wr->surf->setXDrag(1);
291 wr->surf->setYDrag(1);
292 wr->surf->setZDrag(1);
296 void Airplane::setFuelFraction(float frac)
299 for(i=0; i<_tanks.size(); i++) {
300 Tank* t = (Tank*)_tanks.get(i);
301 _model.getBody()->setMass(t->handle, t->cap * frac);
305 float Airplane::getDragCoefficient()
310 float Airplane::getLiftRatio()
315 float Airplane::getCruiseAoA()
320 float Airplane::getTailIncidence()
322 return _tailIncidence;
325 char* Airplane::getFailureMsg()
330 int Airplane::getSolutionIterations()
332 return _solutionIterations;
335 void Airplane::setupState(float aoa, float speed, State* s)
337 float cosAoA = Math::cos(aoa);
338 float sinAoA = Math::sin(aoa);
339 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
340 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
341 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
343 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
347 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
349 // Put us 1m above the origin, or else the gravity computation in
354 void Airplane::addContactPoint(float* pos)
356 float* cp = new float[3];
363 float Airplane::compileWing(Wing* w)
365 // The tip of the wing is a contact point
368 addContactPoint(tip);
369 if(w->isMirrored()) {
371 addContactPoint(tip);
374 // Make sure it's initialized. The surfaces will pop out with
375 // total drag coefficients equal to their areas, which is what we
381 for(i=0; i<w->numSurfaces(); i++) {
382 Surface* s = (Surface*)w->getSurface(i);
384 float td = s->getTotalDrag();
387 _model.addSurface(s);
389 float mass = w->getSurfaceWeight(i);
390 mass = mass * Math::sqrt(mass);
393 _model.getBody()->addMass(mass, pos);
399 float Airplane::compileFuselage(Fuselage* f)
401 // The front and back are contact points
402 addContactPoint(f->front);
403 addContactPoint(f->back);
407 Math::sub3(f->front, f->back, fwd);
408 float len = Math::mag3(fwd);
409 float wid = f->width;
410 int segs = (int)Math::ceil(len/wid);
411 float segWgt = len*wid/segs;
413 for(j=0; j<segs; j++) {
414 float frac = (j+0.5f) / segs;
418 scale = f->taper+(1-f->taper) * (frac / f->mid);
420 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
424 Math::mul3(frac, fwd, pos);
425 Math::add3(f->back, pos, pos);
427 // _Mass_ weighting goes as surface area^(3/2)
428 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
429 _model.getBody()->addMass(mass, pos);
432 // Make a Surface too
433 Surface* s = new Surface();
435 float sideDrag = len/wid;
436 s->setYDrag(sideDrag);
437 s->setZDrag(sideDrag);
438 s->setTotalDrag(scale*segWgt);
440 // FIXME: fails for fuselages aligned along the Y axis
442 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
444 y[0] = 0; y[1] = 1; y[2] = 0;
445 Math::cross3(x, y, z);
447 Math::cross3(z, x, y);
448 s->setOrientation(o);
450 _model.addSurface(s);
456 // FIXME: should probably add a mass for the gear, too
457 void Airplane::compileGear(GearRec* gr)
461 // Make a Surface object for the aerodynamic behavior
462 Surface* s = new Surface();
465 // Put the surface at the half-way point on the gear strut, give
466 // it a drag coefficient equal to a square of the same dimension
467 // (gear are really draggy) and make it symmetric. Assume that
468 // the "length" of the gear is 3x the compression distance
469 float pos[3], cmp[3];
470 g->getCompression(cmp);
471 float length = 3 * Math::mag3(cmp);
473 Math::mul3(0.5, cmp, cmp);
474 Math::add3(pos, cmp, pos);
477 s->setTotalDrag(length*length);
480 _model.addSurface(s);
484 void Airplane::compileContactPoints()
486 // Figure it will compress by 20cm
489 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
491 // Give it a spring constant such that at full compression it will
492 // hold up 10 times the planes mass. That's about right. Yeah.
493 float mass = _model.getBody()->getTotalMass();
494 float spring = (1/DIST) * 9.8f * 10.0f * mass;
495 float damp = 2 * Math::sqrt(spring * mass);
498 for(i=0; i<_contacts.size(); i++) {
499 float *cp = (float*)_contacts.get(i);
501 Gear* g = new Gear();
504 g->setCompression(comp);
505 g->setSpring(spring);
510 g->setStaticFriction(0.6f);
511 g->setDynamicFriction(0.5f);
517 void Airplane::compile()
520 ground[0] = 0; ground[1] = 0; ground[2] = 1;
521 _model.setGroundPlane(ground, -100000);
523 RigidBody* body = _model.getBody();
524 int firstMass = body->numMasses();
526 // Generate the point masses for the plane. Just use unitless
527 // numbers for a first pass, then go back through and rescale to
528 // make the weight right.
532 aeroWgt += compileWing(_wing);
533 aeroWgt += compileWing(_tail);
535 for(i=0; i<_vstabs.size(); i++) {
536 aeroWgt += compileWing((Wing*)_vstabs.get(i));
540 for(i=0; i<_fuselages.size(); i++) {
541 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
544 // Count up the absolute weight we have
545 float nonAeroWgt = _ballast;
546 for(i=0; i<_thrusters.size(); i++)
547 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
549 // Rescale to the specified empty weight
550 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
551 for(i=firstMass; i<body->numMasses(); i++)
552 body->setMass(i, body->getMass(i)*wscale);
554 // Add the thruster masses
555 for(i=0; i<_thrusters.size(); i++) {
556 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
557 body->addMass(t->mass, t->cg);
560 // Add the tanks, empty for now.
562 for(i=0; i<_tanks.size(); i++) {
563 Tank* t = (Tank*)_tanks.get(i);
564 t->handle = body->addMass(0, t->pos);
567 _cruiseWeight = _emptyWeight + totalFuel*0.5f;
568 _approachWeight = _emptyWeight + totalFuel*0.2f;
572 // Add surfaces for the landing gear.
573 for(i=0; i<_gears.size(); i++)
574 compileGear((GearRec*)_gears.get(i));
576 // The Thruster objects
577 for(i=0; i<_thrusters.size(); i++) {
578 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
579 tr->handle = _model.addThruster(tr->thruster);
584 float gespan = _wing->getGroundEffect(gepos);
585 _model.setGroundEffect(gepos, gespan, 0.15f);
590 // Do this after solveGear, because it creates "gear" objects that
591 // we don't want to affect.
592 compileContactPoints();
595 void Airplane::solveGear()
598 _model.getBody()->getCG(cg);
600 // Calculate spring constant weightings for the gear. Weight by
601 // the inverse of the distance to the c.g. in the XY plane, which
602 // should be correct for most gear arrangements. Add 50cm of
603 // "buffer" to keep things from blowing up with aircraft with a
604 // single gear very near the c.g. (AV-8, for example).
607 for(i=0; i<_gears.size(); i++) {
608 GearRec* gr = (GearRec*)_gears.get(i);
611 Math::sub3(cg, pos, pos);
612 gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
616 // Renormalize so they sum to 1
617 for(i=0; i<_gears.size(); i++)
618 ((GearRec*)_gears.get(i))->wgt /= total;
620 // The force at max compression should be sufficient to stop a
621 // plane moving downwards at 3x the approach descent rate. Assume
622 // a 3 degree approach.
623 float descentRate = 3.0f*_approachSpeed/19.1f;
625 // Spread the kinetic energy according to the gear weights. This
626 // will results in an equal compression fraction (not distance) of
628 float energy = 0.5f*_approachWeight*descentRate*descentRate;
630 for(i=0; i<_gears.size(); i++) {
631 GearRec* gr = (GearRec*)_gears.get(i);
632 float e = energy * gr->wgt;
634 gr->gear->getCompression(comp);
635 float len = Math::mag3(comp);
637 // Energy in a spring: e = 0.5 * k * len^2
638 float k = 2 * e / (len*len);
640 gr->gear->setSpring(k);
642 // Critically damped (too damped, too!)
643 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
645 // These are pretty generic
646 gr->gear->setStaticFriction(0.8f);
647 gr->gear->setDynamicFriction(0.7f);
651 void Airplane::initEngines()
653 for(int i=0; i<_thrusters.size(); i++) {
654 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
655 tr->thruster->init();
659 void Airplane::stabilizeThrust()
662 for(i=0; i<_thrusters.size(); i++)
663 _model.getThruster(i)->stabilize();
666 void Airplane::runCruise()
668 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
669 _model.setState(&_cruiseState);
670 _model.setAir(_cruiseP, _cruiseT,
671 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
673 // The control configuration
676 for(i=0; i<_cruiseControls.size(); i++) {
677 Control* c = (Control*)_cruiseControls.get(i);
678 _controls.setInput(c->control, c->val);
680 _controls.applyControls(1000000); // Huge dt value
684 Math::mul3(-1, _cruiseState.v, wind);
685 Math::vmul33(_cruiseState.orient, wind, wind);
687 // Cruise is by convention at 50% tank capacity
688 setFuelFraction(0.5);
690 // Set up the thruster parameters and iterate until the thrust
692 for(i=0; i<_thrusters.size(); i++) {
693 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
695 t->setAir(_cruiseP, _cruiseT,
696 Atmosphere::calcStdDensity(_cruiseP, _cruiseT));
702 // Precompute thrust in the model, and calculate aerodynamic forces
703 _model.getBody()->recalc();
704 _model.getBody()->reset();
705 _model.initIteration();
706 _model.calcForces(&_cruiseState);
709 void Airplane::runApproach()
711 setupState(_approachAoA, _approachSpeed, &_approachState);
712 _model.setState(&_approachState);
713 _model.setAir(_approachP, _approachT,
714 Atmosphere::calcStdDensity(_approachP, _approachT));
716 // The control configuration
719 for(i=0; i<_approachControls.size(); i++) {
720 Control* c = (Control*)_approachControls.get(i);
721 _controls.setInput(c->control, c->val);
723 _controls.applyControls(1000000);
727 Math::mul3(-1, _approachState.v, wind);
728 Math::vmul33(_approachState.orient, wind, wind);
730 // Approach is by convention at 20% tank capacity
731 setFuelFraction(0.2f);
733 // Run the thrusters until they get to a stable setting. FIXME:
734 // this is lots of wasted work.
735 for(i=0; i<_thrusters.size(); i++) {
736 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
738 t->setAir(_approachP, _approachT,
739 Atmosphere::calcStdDensity(_approachP, _approachT));
745 // Precompute thrust in the model, and calculate aerodynamic forces
746 _model.getBody()->recalc();
747 _model.getBody()->reset();
748 _model.initIteration();
749 _model.calcForces(&_approachState);
752 void Airplane::applyDragFactor(float factor)
754 float applied = Math::sqrt(factor);
755 _dragFactor *= applied;
756 _wing->setDragScale(_wing->getDragScale() * applied);
757 _tail->setDragScale(_tail->getDragScale() * applied);
759 for(i=0; i<_vstabs.size(); i++) {
760 Wing* w = (Wing*)_vstabs.get(i);
761 w->setDragScale(w->getDragScale() * applied);
763 for(i=0; i<_surfs.size(); i++) {
764 Surface* s = (Surface*)_surfs.get(i);
765 s->setTotalDrag(s->getTotalDrag() * applied);
769 void Airplane::applyLiftRatio(float factor)
771 float applied = Math::sqrt(factor);
772 _liftRatio *= applied;
773 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
774 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
776 for(i=0; i<_vstabs.size(); i++) {
777 Wing* w = (Wing*)_vstabs.get(i);
778 w->setLiftRatio(w->getLiftRatio() * applied);
782 float Airplane::clamp(float val, float min, float max)
784 if(val < min) return min;
785 if(val > max) return max;
789 float Airplane::normFactor(float f)
796 void Airplane::solve()
798 static const float ARCMIN = 0.0002909f;
801 _solutionIterations = 0;
805 printf("%d %f %f %f %f %f\n", //DEBUG
811 _approachElevator.val);
814 if(_solutionIterations++ > 10000) {
815 _failureMsg = "Solution failed to converge after 10000 iterations";
819 // Run an iteration at cruise, and extract the needed numbers:
822 _model.getThrust(tmp);
823 float thrust = tmp[0];
825 _model.getBody()->getAccel(tmp);
826 Math::tmul33(_cruiseState.orient, tmp, tmp);
827 float xforce = _cruiseWeight * tmp[0];
828 float clift0 = _cruiseWeight * tmp[2];
830 _model.getBody()->getAngularAccel(tmp);
831 Math::tmul33(_cruiseState.orient, tmp, tmp);
832 float pitch0 = tmp[1];
834 // Run an approach iteration, and do likewise
837 _model.getBody()->getAngularAccel(tmp);
838 Math::tmul33(_approachState.orient, tmp, tmp);
839 double apitch0 = tmp[1];
841 _model.getBody()->getAccel(tmp);
842 Math::tmul33(_approachState.orient, tmp, tmp);
843 float alift = _approachWeight * tmp[2];
845 // Modify the cruise AoA a bit to get a derivative
846 _cruiseAoA += ARCMIN;
848 _cruiseAoA -= ARCMIN;
850 _model.getBody()->getAccel(tmp);
851 Math::tmul33(_cruiseState.orient, tmp, tmp);
852 float clift1 = _cruiseWeight * tmp[2];
854 // Do the same with the tail incidence
855 _tail->setIncidence(_tailIncidence + ARCMIN);
857 _tail->setIncidence(_tailIncidence);
859 _model.getBody()->getAngularAccel(tmp);
860 Math::tmul33(_cruiseState.orient, tmp, tmp);
861 float pitch1 = tmp[1];
864 float awgt = 9.8f * _approachWeight;
866 float dragFactor = thrust / (thrust-xforce);
867 float liftFactor = awgt / (awgt+alift);
868 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
869 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
872 if(dragFactor <= 0 || liftFactor <= 0)
875 // And the elevator control in the approach. This works just
876 // like the tail incidence computation (it's solving for the
877 // same thing -- pitching moment -- by diddling a different
879 const float ELEVDIDDLE = 0.001f;
880 _approachElevator.val += ELEVDIDDLE;
882 _approachElevator.val -= ELEVDIDDLE;
884 _model.getBody()->getAngularAccel(tmp);
885 Math::tmul33(_approachState.orient, tmp, tmp);
886 double apitch1 = tmp[1];
887 float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
889 // Now apply the values we just computed. Note that the
890 // "minor" variables are deferred until we get the lift/drag
891 // numbers in the right ballpark.
893 applyDragFactor(dragFactor);
894 applyLiftRatio(liftFactor);
896 // DON'T do the following until the above are sane
897 if(normFactor(dragFactor) > 1.0001
898 || normFactor(liftFactor) > 1.0001)
903 // OK, now we can adjust the minor variables:
904 _cruiseAoA += 0.5f*aoaDelta;
905 _tailIncidence += 0.5f*tailDelta;
907 _cruiseAoA = clamp(_cruiseAoA, -0.175f, 0.175f);
908 _tailIncidence = clamp(_tailIncidence, -0.175f, 0.175f);
910 if(abs(xforce/_cruiseWeight) < 0.0001 &&
911 abs(alift/_approachWeight) < 0.0001 &&
912 abs(aoaDelta) < .000017 &&
913 abs(tailDelta) < .000017)
915 // If this finaly value is OK, then we're all done
916 if(abs(elevDelta) < 0.0001)
919 // Otherwise, adjust and do the next iteration
920 _approachElevator.val += 0.8 * elevDelta;
921 if(abs(_approachElevator.val) > 1) {
922 _failureMsg = "Insufficient elevator to trim for approach";
928 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
929 _failureMsg = "Drag factor beyond reasonable bounds.";
931 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
932 _failureMsg = "Lift ratio beyond reasonable bounds.";
934 } else if(Math::abs(_cruiseAoA) >= .17453293) {
935 _failureMsg = "Cruise AoA > 10 degrees";
937 } else if(Math::abs(_tailIncidence) >= .17453293) {
938 _failureMsg = "Tail incidence > 10 degrees";
942 }; // namespace yasim