1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
16 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
39 for(i=0; i<_fuselages.size(); i++)
40 delete (Fuselage*)_fuselages.get(i);
41 for(i=0; i<_tanks.size(); i++)
42 delete (Tank*)_tanks.get(i);
43 for(i=0; i<_thrusters.size(); i++)
44 delete (ThrustRec*)_thrusters.get(i);
45 for(i=0; i<_gears.size(); i++)
46 delete (GearRec*)_gears.get(i);
47 for(i=0; i<_surfs.size(); i++)
48 delete (Surface*)_surfs.get(i);
49 for(i=0; i<_contacts.size(); i++)
50 delete[] (float*)_contacts.get(i);
53 void Airplane::iterate(float dt)
55 // The gear might have moved. Change their aerodynamics.
60 // FIXME: Consume fuel
63 ControlMap* Airplane::getControlMap()
68 Model* Airplane::getModel()
73 void Airplane::getPilotAccel(float* out)
75 State* s = _model.getState();
78 Glue::geodUp(s->pos, out);
79 Math::mul3(-9.8, out, out);
81 // The regular acceleration
83 Math::mul3(-1, s->acc, tmp);
84 Math::add3(tmp, out, out);
86 // Convert to aircraft coordinates
87 Math::vmul33(s->orient, out, out);
89 // FIXME: rotational & centripetal acceleration needed
92 void Airplane::setPilotPos(float* pos)
95 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
98 void Airplane::getPilotPos(float* out)
101 for(i=0; i<3; i++) out[i] = _pilotPos[i];
104 int Airplane::numGear()
106 return _gears.size();
109 Gear* Airplane::getGear(int g)
111 return ((GearRec*)_gears.get(g))->gear;
114 void Airplane::updateGearState()
116 for(int i=0; i<_gears.size(); i++) {
117 GearRec* gr = (GearRec*)_gears.get(i);
118 float ext = gr->gear->getExtension();
120 gr->surf->setXDrag(ext);
121 gr->surf->setYDrag(ext);
122 gr->surf->setZDrag(ext);
126 void Airplane::setApproach(float speed, float altitude)
128 // The zero AoA will become a calculated stall AoA in compile()
129 setApproach(speed, altitude, 0);
132 void Airplane::setApproach(float speed, float altitude, float aoa)
134 _approachSpeed = speed;
135 _approachP = Atmosphere::getStdPressure(altitude);
136 _approachT = Atmosphere::getStdTemperature(altitude);
140 void Airplane::setCruise(float speed, float altitude)
142 _cruiseSpeed = speed;
143 _cruiseP = Atmosphere::getStdPressure(altitude);
144 _cruiseT = Atmosphere::getStdTemperature(altitude);
149 void Airplane::addApproachControl(int control, float val)
151 Control* c = new Control();
152 c->control = control;
154 _approachControls.add(c);
157 void Airplane::addCruiseControl(int control, float val)
159 Control* c = new Control();
160 c->control = control;
162 _cruiseControls.add(c);
165 int Airplane::numTanks()
167 return _tanks.size();
170 float Airplane::getFuel(int tank)
172 return ((Tank*)_tanks.get(tank))->fill;
175 float Airplane::getFuelDensity(int tank)
177 return ((Tank*)_tanks.get(tank))->density;
180 void Airplane::setWeight(float weight)
182 _emptyWeight = weight;
185 void Airplane::setWing(Wing* wing)
190 void Airplane::setTail(Wing* tail)
195 void Airplane::addVStab(Wing* vstab)
200 void Airplane::addFuselage(float* front, float* back, float width,
201 float taper, float mid)
203 Fuselage* f = new Fuselage();
206 f->front[i] = front[i];
207 f->back[i] = back[i];
215 int Airplane::addTank(float* pos, float cap, float density)
217 Tank* t = new Tank();
219 for(i=0; i<3; i++) t->pos[i] = pos[i];
222 t->density = density;
223 t->handle = 0xffffffff;
224 return _tanks.add(t);
227 void Airplane::addGear(Gear* gear)
229 GearRec* g = new GearRec();
235 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
237 ThrustRec* t = new ThrustRec();
238 t->thruster = thruster;
241 for(i=0; i<3; i++) t->cg[i] = cg[i];
245 void Airplane::addBallast(float* pos, float mass)
247 _model.getBody()->addMass(mass, pos);
251 int Airplane::addWeight(float* pos, float size)
253 WeightRec* wr = new WeightRec();
254 wr->handle = _model.getBody()->addMass(0, pos);
256 wr->surf = new Surface();
257 wr->surf->setPosition(pos);
258 wr->surf->setTotalDrag(size*size);
259 _model.addSurface(wr->surf);
260 _surfs.add(wr->surf);
262 return _weights.add(wr);
265 void Airplane::setWeight(int handle, float mass)
267 WeightRec* wr = (WeightRec*)_weights.get(handle);
269 _model.getBody()->setMass(wr->handle, mass);
271 // Kill the aerodynamic drag if the mass is exactly zero. This is
272 // how we simulate droppable stores.
274 wr->surf->setXDrag(0);
275 wr->surf->setYDrag(0);
276 wr->surf->setZDrag(0);
278 wr->surf->setXDrag(1);
279 wr->surf->setYDrag(1);
280 wr->surf->setZDrag(1);
284 void Airplane::setFuelFraction(float frac)
287 for(i=0; i<_tanks.size(); i++) {
288 Tank* t = (Tank*)_tanks.get(i);
289 _model.getBody()->setMass(t->handle, t->cap * frac);
293 float Airplane::getDragCoefficient()
298 float Airplane::getLiftRatio()
303 float Airplane::getCruiseAoA()
308 float Airplane::getTailIncidence()
310 return _tailIncidence;
313 char* Airplane::getFailureMsg()
318 int Airplane::getSolutionIterations()
320 return _solutionIterations;
323 void Airplane::setupState(float aoa, float speed, State* s)
325 float cosAoA = Math::cos(aoa);
326 float sinAoA = Math::sin(aoa);
327 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
328 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
329 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
331 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
335 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
337 // Put us 1m above the origin, or else the gravity computation in
342 void Airplane::addContactPoint(float* pos)
344 float* cp = new float[3];
351 float Airplane::compileWing(Wing* w)
353 // The tip of the wing is a contact point
356 addContactPoint(tip);
357 if(w->isMirrored()) {
359 addContactPoint(tip);
362 // Make sure it's initialized. The surfaces will pop out with
363 // total drag coefficients equal to their areas, which is what we
369 for(i=0; i<w->numSurfaces(); i++) {
370 Surface* s = (Surface*)w->getSurface(i);
372 float td = s->getTotalDrag();
375 _model.addSurface(s);
377 float mass = w->getSurfaceWeight(i);
378 mass = mass * Math::sqrt(mass);
381 _model.getBody()->addMass(mass, pos);
387 float Airplane::compileFuselage(Fuselage* f)
389 // The front and back are contact points
390 addContactPoint(f->front);
391 addContactPoint(f->back);
395 Math::sub3(f->front, f->back, fwd);
396 float len = Math::mag3(fwd);
397 float wid = f->width;
398 int segs = (int)Math::ceil(len/wid);
399 float segWgt = len*wid/segs;
401 for(j=0; j<segs; j++) {
402 float frac = (j+0.5) / segs;
406 scale = f->taper+(1-f->taper) * (frac / f->mid);
408 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
412 Math::mul3(frac, fwd, pos);
413 Math::add3(f->back, pos, pos);
415 // _Mass_ weighting goes as surface area^(3/2)
416 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
417 _model.getBody()->addMass(mass, pos);
420 // Make a Surface too
421 Surface* s = new Surface();
423 float sideDrag = len/wid;
424 s->setYDrag(sideDrag);
425 s->setZDrag(sideDrag);
426 s->setTotalDrag(scale*segWgt);
428 // FIXME: fails for fuselages aligned along the Y axis
430 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
432 y[0] = 0; y[1] = 1; y[2] = 0;
433 Math::cross3(x, y, z);
434 s->setOrientation(o);
436 _model.addSurface(s);
442 // FIXME: should probably add a mass for the gear, too
443 void Airplane::compileGear(GearRec* gr)
447 // Make a Surface object for the aerodynamic behavior
448 Surface* s = new Surface();
451 // Put the surface at the half-way point on the gear strut, give
452 // it a drag coefficient equal to a square of the same dimension
453 // (gear are really draggy) and make it symmetric. Assume that
454 // the "length" of the gear is 3x the compression distance
455 float pos[3], cmp[3];
456 g->getCompression(cmp);
457 float length = 3 * Math::mag3(cmp);
459 Math::mul3(0.5, cmp, cmp);
460 Math::add3(pos, cmp, pos);
463 s->setTotalDrag(length*length);
466 _model.addSurface(s);
470 void Airplane::compileContactPoints()
472 // Figure it will compress by 20cm
475 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
477 // Give it a spring constant such that at full compression it will
478 // hold up 10 times the planes mass. That's about right. Yeah.
479 float mass = _model.getBody()->getTotalMass();
480 float spring = (1/DIST) * 9.8 * 10 * mass;
481 float damp = 2 * Math::sqrt(spring * mass);
484 for(i=0; i<_contacts.size(); i++) {
485 float *cp = (float*)_contacts.get(i);
487 Gear* g = new Gear();
490 g->setCompression(comp);
491 g->setSpring(spring);
496 g->setStaticFriction(0.6);
497 g->setDynamicFriction(0.5);
503 void Airplane::compile()
506 ground[0] = 0; ground[1] = 0; ground[2] = 1;
507 _model.setGroundPlane(ground, -100000);
509 RigidBody* body = _model.getBody();
510 int firstMass = body->numMasses();
512 // Generate the point masses for the plane. Just use unitless
513 // numbers for a first pass, then go back through and rescale to
514 // make the weight right.
518 aeroWgt += compileWing(_wing);
519 aeroWgt += compileWing(_tail);
521 for(i=0; i<_vstabs.size(); i++) {
522 aeroWgt += compileWing((Wing*)_vstabs.get(i));
526 for(i=0; i<_fuselages.size(); i++) {
527 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
530 // Count up the absolute weight we have
531 float nonAeroWgt = _ballast;
532 for(i=0; i<_thrusters.size(); i++)
533 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
535 // Rescale to the specified empty weight
536 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
537 for(i=firstMass; i<body->numMasses(); i++)
538 body->setMass(i, body->getMass(i)*wscale);
540 // Add the thruster masses
541 for(i=0; i<_thrusters.size(); i++) {
542 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
543 body->addMass(t->mass, t->cg);
546 // Add the tanks, empty for now.
548 for(i=0; i<_tanks.size(); i++) {
549 Tank* t = (Tank*)_tanks.get(i);
550 t->handle = body->addMass(0, t->pos);
553 _cruiseWeight = _emptyWeight + totalFuel*0.5;
554 _approachWeight = _emptyWeight + totalFuel*0.2;
558 // Add surfaces for the landing gear.
559 for(i=0; i<_gears.size(); i++)
560 compileGear((GearRec*)_gears.get(i));
562 // The Thruster objects
563 for(i=0; i<_thrusters.size(); i++) {
564 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
565 tr->handle = _model.addThruster(tr->thruster);
570 float gespan = _wing->getGroundEffect(gepos);
571 _model.setGroundEffect(gepos, gespan, .3);
576 // Do this after solveGear, because it creates "gear" objects that
577 // we don't want to affect.
578 compileContactPoints();
581 void Airplane::solveGear()
584 _model.getBody()->getCG(cg);
586 // Calculate spring constant weightings for the gear. Weight by
587 // the inverse of the distance to the c.g. in the XY plane, which
588 // should be correct for most gear arrangements. Add 50cm of
589 // "buffer" to keep things from blowing up with aircraft with a
590 // single gear very near the c.g. (AV-8, for example).
593 for(i=0; i<_gears.size(); i++) {
594 GearRec* gr = (GearRec*)_gears.get(i);
597 Math::sub3(cg, pos, pos);
598 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
602 // Renormalize so they sum to 1
603 for(i=0; i<_gears.size(); i++)
604 ((GearRec*)_gears.get(i))->wgt /= total;
606 // The force at max compression should be sufficient to stop a
607 // plane moving downwards at 3x the approach descent rate. Assume
608 // a 3 degree approach.
609 float descentRate = 3*_approachSpeed/19.1;
611 // Spread the kinetic energy according to the gear weights. This
612 // will results in an equal compression fraction (not distance) of
614 float energy = 0.5*_approachWeight*descentRate*descentRate;
616 for(i=0; i<_gears.size(); i++) {
617 GearRec* gr = (GearRec*)_gears.get(i);
618 float e = energy * gr->wgt;
620 gr->gear->getCompression(comp);
621 float len = Math::mag3(comp);
623 // Energy in a spring: e = 0.5 * k * len^2
624 float k = 2 * e / (len*len);
626 gr->gear->setSpring(k);
628 // Critically damped (too damped, too!)
629 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
631 // These are pretty generic
632 gr->gear->setStaticFriction(0.8);
633 gr->gear->setDynamicFriction(0.7);
637 void Airplane::initEngines()
639 for(int i=0; i<_thrusters.size(); i++) {
640 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
641 tr->thruster->init();
645 void Airplane::stabilizeThrust()
648 for(i=0; i<_thrusters.size(); i++)
649 _model.getThruster(i)->stabilize();
652 void Airplane::runCruise()
654 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
655 _model.setState(&_cruiseState);
656 _model.setAir(_cruiseP, _cruiseT);
658 // The control configuration
661 for(i=0; i<_cruiseControls.size(); i++) {
662 Control* c = (Control*)_cruiseControls.get(i);
663 _controls.setInput(c->control, c->val);
665 _controls.applyControls(1000000); // Huge dt value
669 Math::mul3(-1, _cruiseState.v, wind);
670 Math::vmul33(_cruiseState.orient, wind, wind);
672 // Cruise is by convention at 50% tank capacity
673 setFuelFraction(0.5);
675 // Set up the thruster parameters and iterate until the thrust
677 for(i=0; i<_thrusters.size(); i++) {
678 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
680 t->setAir(_cruiseP, _cruiseT);
686 // Precompute thrust in the model, and calculate aerodynamic forces
687 _model.getBody()->reset();
688 _model.initIteration();
689 _model.calcForces(&_cruiseState);
692 void Airplane::runApproach()
694 setupState(_approachAoA, _approachSpeed, &_approachState);
695 _model.setState(&_approachState);
696 _model.setAir(_approachP, _approachT);
698 // The control configuration
701 for(i=0; i<_approachControls.size(); i++) {
702 Control* c = (Control*)_approachControls.get(i);
703 _controls.setInput(c->control, c->val);
705 _controls.applyControls(1000000);
709 Math::mul3(-1, _approachState.v, wind);
710 Math::vmul33(_approachState.orient, wind, wind);
712 // Approach is by convention at 20% tank capacity
713 setFuelFraction(0.2);
715 // Run the thrusters until they get to a stable setting. FIXME:
716 // this is lots of wasted work.
717 for(i=0; i<_thrusters.size(); i++) {
718 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
720 t->setAir(_approachP, _approachT);
726 // Precompute thrust in the model, and calculate aerodynamic forces
727 _model.getBody()->reset();
728 _model.initIteration();
729 _model.calcForces(&_approachState);
732 void Airplane::applyDragFactor(float factor)
734 float applied = Math::sqrt(factor);
735 _dragFactor *= applied;
736 _wing->setDragScale(_wing->getDragScale() * applied);
737 _tail->setDragScale(_tail->getDragScale() * applied);
739 for(i=0; i<_vstabs.size(); i++) {
740 Wing* w = (Wing*)_vstabs.get(i);
741 w->setDragScale(w->getDragScale() * applied);
743 for(i=0; i<_surfs.size(); i++) {
744 Surface* s = (Surface*)_surfs.get(i);
745 s->setTotalDrag(s->getTotalDrag() * applied);
749 void Airplane::applyLiftRatio(float factor)
751 float applied = Math::sqrt(factor);
752 _liftRatio *= applied;
753 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
754 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
756 for(i=0; i<_vstabs.size(); i++) {
757 Wing* w = (Wing*)_vstabs.get(i);
758 w->setLiftRatio(w->getLiftRatio() * applied);
762 float Airplane::clamp(float val, float min, float max)
764 if(val < min) return min;
765 if(val > max) return max;
769 float Airplane::normFactor(float f)
776 void Airplane::solve()
778 static const float ARCMIN = 0.0002909;
781 _solutionIterations = 0;
784 if(_solutionIterations++ > 10000) {
785 _failureMsg = "Solution failed to converge after 10000 iterations";
789 // Run an iteration at cruise, and extract the needed numbers:
792 _model.getThrust(tmp);
793 float thrust = tmp[0];
795 _model.getBody()->getAccel(tmp);
796 float xforce = _cruiseWeight * tmp[0];
797 float clift0 = _cruiseWeight * tmp[2];
799 _model.getBody()->getAngularAccel(tmp);
800 float pitch0 = tmp[1];
802 // Run an approach iteration, and do likewise
805 _model.getBody()->getAccel(tmp);
806 float alift = _approachWeight * tmp[2];
808 // Modify the cruise AoA a bit to get a derivative
809 _cruiseAoA += ARCMIN;
811 _cruiseAoA -= ARCMIN;
813 _model.getBody()->getAccel(tmp);
814 float clift1 = _cruiseWeight * tmp[2];
816 // Do the same with the tail incidence
817 _tail->setIncidence(_tailIncidence + ARCMIN);
819 _tail->setIncidence(_tailIncidence);
821 _model.getBody()->getAngularAccel(tmp);
822 float pitch1 = tmp[1];
825 float awgt = 9.8 * _approachWeight;
827 float dragFactor = thrust / (thrust-xforce);
828 float liftFactor = awgt / (awgt+alift);
829 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
830 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
833 if(dragFactor <= 0) {
834 _failureMsg = "Zero or negative drag adjustment.";
836 } else if(liftFactor <= 0) {
837 _failureMsg = "Zero or negative lift adjustment.";
842 applyDragFactor(dragFactor);
843 applyLiftRatio(liftFactor);
845 // DON'T do the following until the above are sane
846 if(normFactor(dragFactor) > 1.1
847 || normFactor(liftFactor) > 1.1)
852 // OK, now we can adjust the minor variables
853 _cruiseAoA += 0.5*aoaDelta;
854 _tailIncidence += 0.5*tailDelta;
856 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
857 _tailIncidence = clamp(_tailIncidence, -.174, .174);
859 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
860 aoaDelta < .000017 && tailDelta < .000017)
866 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
867 _failureMsg = "Drag factor beyond reasonable bounds.";
869 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
870 _failureMsg = "Lift ratio beyond reasonable bounds.";
872 } else if(Math::abs(_cruiseAoA) >= .174) {
873 _failureMsg = "Cruise AoA > 10 degrees";
875 } else if(Math::abs(_tailIncidence) >= .174) {
876 _failureMsg = "Tail incidence > 10 degrees";
880 }; // namespace yasim