3 #include "Atmosphere.hpp"
4 #include "ControlMap.hpp"
8 #include "RigidBody.hpp"
10 #include "Thruster.hpp"
12 #include "Airplane.hpp"
16 inline float norm(float f) { return f<1 ? 1/f : f; }
17 inline float abs(float f) { return f<0 ? -f : f; }
22 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
45 for(i=0; i<_fuselages.size(); i++)
46 delete (Fuselage*)_fuselages.get(i);
47 for(i=0; i<_tanks.size(); i++)
48 delete (Tank*)_tanks.get(i);
49 for(i=0; i<_thrusters.size(); i++)
50 delete (ThrustRec*)_thrusters.get(i);
51 for(i=0; i<_gears.size(); i++)
52 delete (GearRec*)_gears.get(i);
53 for(i=0; i<_surfs.size(); i++)
54 delete (Surface*)_surfs.get(i);
55 for(i=0; i<_contacts.size(); i++)
56 delete[] (float*)_contacts.get(i);
59 void Airplane::iterate(float dt)
61 // The gear might have moved. Change their aerodynamics.
66 // FIXME: Consume fuel
69 ControlMap* Airplane::getControlMap()
74 Model* Airplane::getModel()
79 void Airplane::getPilotAccel(float* out)
81 State* s = _model.getState();
84 Glue::geodUp(s->pos, out);
85 Math::mul3(-9.8f, out, out);
87 // The regular acceleration
89 Math::mul3(-1, s->acc, tmp);
90 Math::add3(tmp, out, out);
92 // Convert to aircraft coordinates
93 Math::vmul33(s->orient, out, out);
95 // FIXME: rotational & centripetal acceleration needed
98 void Airplane::setPilotPos(float* pos)
101 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
104 void Airplane::getPilotPos(float* out)
107 for(i=0; i<3; i++) out[i] = _pilotPos[i];
110 int Airplane::numGear()
112 return _gears.size();
115 Gear* Airplane::getGear(int g)
117 return ((GearRec*)_gears.get(g))->gear;
120 void Airplane::updateGearState()
122 for(int i=0; i<_gears.size(); i++) {
123 GearRec* gr = (GearRec*)_gears.get(i);
124 float ext = gr->gear->getExtension();
126 gr->surf->setXDrag(ext);
127 gr->surf->setYDrag(ext);
128 gr->surf->setZDrag(ext);
132 void Airplane::setApproach(float speed, float altitude)
134 // The zero AoA will become a calculated stall AoA in compile()
135 setApproach(speed, altitude, 0);
138 void Airplane::setApproach(float speed, float altitude, float aoa)
140 _approachSpeed = speed;
141 _approachP = Atmosphere::getStdPressure(altitude);
142 _approachT = Atmosphere::getStdTemperature(altitude);
146 void Airplane::setCruise(float speed, float altitude)
148 _cruiseSpeed = speed;
149 _cruiseP = Atmosphere::getStdPressure(altitude);
150 _cruiseT = Atmosphere::getStdTemperature(altitude);
155 void Airplane::setElevatorControl(int control)
157 _approachElevator.control = control;
158 _approachElevator.val = 0;
159 _approachControls.add(&_approachElevator);
162 void Airplane::addApproachControl(int control, float val)
164 Control* c = new Control();
165 c->control = control;
167 _approachControls.add(c);
170 void Airplane::addCruiseControl(int control, float val)
172 Control* c = new Control();
173 c->control = control;
175 _cruiseControls.add(c);
178 int Airplane::numTanks()
180 return _tanks.size();
183 float Airplane::getFuel(int tank)
185 return ((Tank*)_tanks.get(tank))->fill;
188 float Airplane::getFuelDensity(int tank)
190 return ((Tank*)_tanks.get(tank))->density;
193 void Airplane::setWeight(float weight)
195 _emptyWeight = weight;
198 void Airplane::setWing(Wing* wing)
203 void Airplane::setTail(Wing* tail)
208 void Airplane::addVStab(Wing* vstab)
213 void Airplane::addFuselage(float* front, float* back, float width,
214 float taper, float mid)
216 Fuselage* f = new Fuselage();
219 f->front[i] = front[i];
220 f->back[i] = back[i];
228 int Airplane::addTank(float* pos, float cap, float density)
230 Tank* t = new Tank();
232 for(i=0; i<3; i++) t->pos[i] = pos[i];
235 t->density = density;
236 t->handle = 0xffffffff;
237 return _tanks.add(t);
240 void Airplane::addGear(Gear* gear)
242 GearRec* g = new GearRec();
248 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
250 ThrustRec* t = new ThrustRec();
251 t->thruster = thruster;
254 for(i=0; i<3; i++) t->cg[i] = cg[i];
258 void Airplane::addBallast(float* pos, float mass)
260 _model.getBody()->addMass(mass, pos);
264 int Airplane::addWeight(float* pos, float size)
266 WeightRec* wr = new WeightRec();
267 wr->handle = _model.getBody()->addMass(0, pos);
269 wr->surf = new Surface();
270 wr->surf->setPosition(pos);
271 wr->surf->setTotalDrag(size*size);
272 _model.addSurface(wr->surf);
273 _surfs.add(wr->surf);
275 return _weights.add(wr);
278 void Airplane::setWeight(int handle, float mass)
280 WeightRec* wr = (WeightRec*)_weights.get(handle);
282 _model.getBody()->setMass(wr->handle, mass);
284 // Kill the aerodynamic drag if the mass is exactly zero. This is
285 // how we simulate droppable stores.
287 wr->surf->setXDrag(0);
288 wr->surf->setYDrag(0);
289 wr->surf->setZDrag(0);
291 wr->surf->setXDrag(1);
292 wr->surf->setYDrag(1);
293 wr->surf->setZDrag(1);
297 void Airplane::setFuelFraction(float frac)
300 for(i=0; i<_tanks.size(); i++) {
301 Tank* t = (Tank*)_tanks.get(i);
302 _model.getBody()->setMass(t->handle, t->cap * frac);
306 float Airplane::getDragCoefficient()
311 float Airplane::getLiftRatio()
316 float Airplane::getCruiseAoA()
321 float Airplane::getTailIncidence()
323 return _tailIncidence;
326 char* Airplane::getFailureMsg()
331 int Airplane::getSolutionIterations()
333 return _solutionIterations;
336 void Airplane::setupState(float aoa, float speed, State* s)
338 float cosAoA = Math::cos(aoa);
339 float sinAoA = Math::sin(aoa);
340 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
341 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
342 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
344 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
348 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
350 // Put us 1m above the origin, or else the gravity computation in
355 void Airplane::addContactPoint(float* pos)
357 float* cp = new float[3];
364 float Airplane::compileWing(Wing* w)
366 // The tip of the wing is a contact point
369 addContactPoint(tip);
370 if(w->isMirrored()) {
372 addContactPoint(tip);
375 // Make sure it's initialized. The surfaces will pop out with
376 // total drag coefficients equal to their areas, which is what we
382 for(i=0; i<w->numSurfaces(); i++) {
383 Surface* s = (Surface*)w->getSurface(i);
385 float td = s->getTotalDrag();
388 _model.addSurface(s);
390 float mass = w->getSurfaceWeight(i);
391 mass = mass * Math::sqrt(mass);
394 _model.getBody()->addMass(mass, pos);
400 float Airplane::compileFuselage(Fuselage* f)
402 // The front and back are contact points
403 addContactPoint(f->front);
404 addContactPoint(f->back);
408 Math::sub3(f->front, f->back, fwd);
409 float len = Math::mag3(fwd);
410 float wid = f->width;
411 int segs = (int)Math::ceil(len/wid);
412 float segWgt = len*wid/segs;
414 for(j=0; j<segs; j++) {
415 float frac = (j+0.5f) / segs;
419 scale = f->taper+(1-f->taper) * (frac / f->mid);
421 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
425 Math::mul3(frac, fwd, pos);
426 Math::add3(f->back, pos, pos);
428 // _Mass_ weighting goes as surface area^(3/2)
429 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
430 _model.getBody()->addMass(mass, pos);
433 // Make a Surface too
434 Surface* s = new Surface();
436 float sideDrag = len/wid;
437 s->setYDrag(sideDrag);
438 s->setZDrag(sideDrag);
439 s->setTotalDrag(scale*segWgt);
441 // FIXME: fails for fuselages aligned along the Y axis
443 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
445 y[0] = 0; y[1] = 1; y[2] = 0;
446 Math::cross3(x, y, z);
448 Math::cross3(z, x, y);
449 s->setOrientation(o);
451 _model.addSurface(s);
457 // FIXME: should probably add a mass for the gear, too
458 void Airplane::compileGear(GearRec* gr)
462 // Make a Surface object for the aerodynamic behavior
463 Surface* s = new Surface();
466 // Put the surface at the half-way point on the gear strut, give
467 // it a drag coefficient equal to a square of the same dimension
468 // (gear are really draggy) and make it symmetric. Assume that
469 // the "length" of the gear is 3x the compression distance
470 float pos[3], cmp[3];
471 g->getCompression(cmp);
472 float length = 3 * Math::mag3(cmp);
474 Math::mul3(0.5, cmp, cmp);
475 Math::add3(pos, cmp, pos);
478 s->setTotalDrag(length*length);
481 _model.addSurface(s);
485 void Airplane::compileContactPoints()
487 // Figure it will compress by 20cm
490 comp[0] = 0; comp[1] = 0; comp[2] = DIST;
492 // Give it a spring constant such that at full compression it will
493 // hold up 10 times the planes mass. That's about right. Yeah.
494 float mass = _model.getBody()->getTotalMass();
495 float spring = (1/DIST) * 9.8f * 10.0f * mass;
496 float damp = 2 * Math::sqrt(spring * mass);
499 for(i=0; i<_contacts.size(); i++) {
500 float *cp = (float*)_contacts.get(i);
502 Gear* g = new Gear();
505 g->setCompression(comp);
506 g->setSpring(spring);
511 g->setStaticFriction(0.6f);
512 g->setDynamicFriction(0.5f);
518 void Airplane::compile()
521 ground[0] = 0; ground[1] = 0; ground[2] = 1;
522 _model.setGroundPlane(ground, -100000);
524 RigidBody* body = _model.getBody();
525 int firstMass = body->numMasses();
527 // Generate the point masses for the plane. Just use unitless
528 // numbers for a first pass, then go back through and rescale to
529 // make the weight right.
533 aeroWgt += compileWing(_wing);
534 aeroWgt += compileWing(_tail);
536 for(i=0; i<_vstabs.size(); i++) {
537 aeroWgt += compileWing((Wing*)_vstabs.get(i));
541 for(i=0; i<_fuselages.size(); i++) {
542 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
545 // Count up the absolute weight we have
546 float nonAeroWgt = _ballast;
547 for(i=0; i<_thrusters.size(); i++)
548 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
550 // Rescale to the specified empty weight
551 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
552 for(i=firstMass; i<body->numMasses(); i++)
553 body->setMass(i, body->getMass(i)*wscale);
555 // Add the thruster masses
556 for(i=0; i<_thrusters.size(); i++) {
557 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
558 body->addMass(t->mass, t->cg);
561 // Add the tanks, empty for now.
563 for(i=0; i<_tanks.size(); i++) {
564 Tank* t = (Tank*)_tanks.get(i);
565 t->handle = body->addMass(0, t->pos);
568 _cruiseWeight = _emptyWeight + totalFuel*0.5f;
569 _approachWeight = _emptyWeight + totalFuel*0.2f;
573 // Add surfaces for the landing gear.
574 for(i=0; i<_gears.size(); i++)
575 compileGear((GearRec*)_gears.get(i));
577 // The Thruster objects
578 for(i=0; i<_thrusters.size(); i++) {
579 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
580 tr->handle = _model.addThruster(tr->thruster);
585 float gespan = _wing->getGroundEffect(gepos);
586 _model.setGroundEffect(gepos, gespan, 0.3f);
591 // Do this after solveGear, because it creates "gear" objects that
592 // we don't want to affect.
593 compileContactPoints();
596 void Airplane::solveGear()
599 _model.getBody()->getCG(cg);
601 // Calculate spring constant weightings for the gear. Weight by
602 // the inverse of the distance to the c.g. in the XY plane, which
603 // should be correct for most gear arrangements. Add 50cm of
604 // "buffer" to keep things from blowing up with aircraft with a
605 // single gear very near the c.g. (AV-8, for example).
608 for(i=0; i<_gears.size(); i++) {
609 GearRec* gr = (GearRec*)_gears.get(i);
612 Math::sub3(cg, pos, pos);
613 gr->wgt = 1.0f/(0.5f+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
617 // Renormalize so they sum to 1
618 for(i=0; i<_gears.size(); i++)
619 ((GearRec*)_gears.get(i))->wgt /= total;
621 // The force at max compression should be sufficient to stop a
622 // plane moving downwards at 3x the approach descent rate. Assume
623 // a 3 degree approach.
624 float descentRate = 3.0f*_approachSpeed/19.1f;
626 // Spread the kinetic energy according to the gear weights. This
627 // will results in an equal compression fraction (not distance) of
629 float energy = 0.5f*_approachWeight*descentRate*descentRate;
631 for(i=0; i<_gears.size(); i++) {
632 GearRec* gr = (GearRec*)_gears.get(i);
633 float e = energy * gr->wgt;
635 gr->gear->getCompression(comp);
636 float len = Math::mag3(comp);
638 // Energy in a spring: e = 0.5 * k * len^2
639 float k = 2 * e / (len*len);
641 gr->gear->setSpring(k);
643 // Critically damped (too damped, too!)
644 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
646 // These are pretty generic
647 gr->gear->setStaticFriction(0.8f);
648 gr->gear->setDynamicFriction(0.7f);
652 void Airplane::initEngines()
654 for(int i=0; i<_thrusters.size(); i++) {
655 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
656 tr->thruster->init();
660 void Airplane::stabilizeThrust()
663 for(i=0; i<_thrusters.size(); i++)
664 _model.getThruster(i)->stabilize();
667 void Airplane::runCruise()
669 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
670 _model.setState(&_cruiseState);
671 _model.setAir(_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);
701 // Precompute thrust in the model, and calculate aerodynamic forces
702 _model.getBody()->reset();
703 _model.initIteration();
704 _model.calcForces(&_cruiseState);
707 void Airplane::runApproach()
709 setupState(_approachAoA, _approachSpeed, &_approachState);
710 _model.setState(&_approachState);
711 _model.setAir(_approachP, _approachT);
713 // The control configuration
716 for(i=0; i<_approachControls.size(); i++) {
717 Control* c = (Control*)_approachControls.get(i);
718 _controls.setInput(c->control, c->val);
720 _controls.applyControls(1000000);
724 Math::mul3(-1, _approachState.v, wind);
725 Math::vmul33(_approachState.orient, wind, wind);
727 // Approach is by convention at 20% tank capacity
728 setFuelFraction(0.2f);
730 // Run the thrusters until they get to a stable setting. FIXME:
731 // this is lots of wasted work.
732 for(i=0; i<_thrusters.size(); i++) {
733 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
735 t->setAir(_approachP, _approachT);
741 // Precompute thrust in the model, and calculate aerodynamic forces
742 _model.getBody()->reset();
743 _model.initIteration();
744 _model.calcForces(&_approachState);
747 void Airplane::applyDragFactor(float factor)
749 float applied = Math::sqrt(factor);
750 _dragFactor *= applied;
751 _wing->setDragScale(_wing->getDragScale() * applied);
752 _tail->setDragScale(_tail->getDragScale() * applied);
754 for(i=0; i<_vstabs.size(); i++) {
755 Wing* w = (Wing*)_vstabs.get(i);
756 w->setDragScale(w->getDragScale() * applied);
758 for(i=0; i<_surfs.size(); i++) {
759 Surface* s = (Surface*)_surfs.get(i);
760 s->setTotalDrag(s->getTotalDrag() * applied);
764 void Airplane::applyLiftRatio(float factor)
766 float applied = Math::sqrt(factor);
767 _liftRatio *= applied;
768 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
769 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
771 for(i=0; i<_vstabs.size(); i++) {
772 Wing* w = (Wing*)_vstabs.get(i);
773 w->setLiftRatio(w->getLiftRatio() * applied);
777 float Airplane::clamp(float val, float min, float max)
779 if(val < min) return min;
780 if(val > max) return max;
784 float Airplane::normFactor(float f)
791 void Airplane::solve()
793 static const float ARCMIN = 0.0002909f;
796 _solutionIterations = 0;
799 if(_solutionIterations++ > 10000) {
800 _failureMsg = "Solution failed to converge after 10000 iterations";
804 // Run an iteration at cruise, and extract the needed numbers:
807 _model.getThrust(tmp);
808 float thrust = tmp[0];
810 _model.getBody()->getAccel(tmp);
811 float xforce = _cruiseWeight * tmp[0];
812 float clift0 = _cruiseWeight * tmp[2];
814 _model.getBody()->getAngularAccel(tmp);
815 float pitch0 = tmp[1];
817 // Run an approach iteration, and do likewise
820 _model.getBody()->getAngularAccel(tmp);
821 float apitch0 = tmp[1];
823 _model.getBody()->getAccel(tmp);
824 float alift = _approachWeight * tmp[2];
826 // Modify the cruise AoA a bit to get a derivative
827 _cruiseAoA += ARCMIN;
829 _cruiseAoA -= ARCMIN;
831 _model.getBody()->getAccel(tmp);
832 float clift1 = _cruiseWeight * tmp[2];
834 // Do the same with the tail incidence
835 _tail->setIncidence(_tailIncidence + ARCMIN);
837 _tail->setIncidence(_tailIncidence);
839 _model.getBody()->getAngularAccel(tmp);
840 float pitch1 = tmp[1];
843 float awgt = 9.8f * _approachWeight;
845 float dragFactor = thrust / (thrust-xforce);
846 float liftFactor = awgt / (awgt+alift);
847 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
848 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
851 if(dragFactor <= 0) {
852 _failureMsg = "Zero or negative drag adjustment.";
854 } else if(liftFactor <= 0) {
855 _failureMsg = "Zero or negative lift adjustment.";
859 // And the elevator control in the approach. This works just
860 // like the tail incidence computation (it's solving for the
861 // same thing -- pitching moment -- by diddling a different
863 const float ELEVDIDDLE = 0.0001f;
864 _approachElevator.val += ELEVDIDDLE;
866 _approachElevator.val -= ELEVDIDDLE;
868 _model.getBody()->getAngularAccel(tmp);
869 float apitch1 = tmp[1];
870 float elevDelta = -apitch0 * (ELEVDIDDLE/(apitch1-apitch0));
872 // Now apply the values we just computed. Note that the
873 // "minor" variables are deferred until we get the lift/drag
874 // numbers in the right ballpark.
876 applyDragFactor(dragFactor);
877 applyLiftRatio(liftFactor);
879 // DON'T do the following until the above are sane
880 if(normFactor(dragFactor) > 1.1
881 || normFactor(liftFactor) > 1.1)
886 // OK, now we can adjust the minor variables:
887 _cruiseAoA += 0.5f*aoaDelta;
888 _tailIncidence += 0.5f*tailDelta;
889 _approachElevator.val += 0.5f*elevDelta;
891 _cruiseAoA = clamp(_cruiseAoA, -0.174f, 0.174f);
892 _tailIncidence = clamp(_tailIncidence, -0.174f, 0.174f);
893 _approachElevator.val = clamp(_approachElevator.val, -1.f, 1.f);
895 fprintf(stderr, "p0 %6f p1 %6f e %5f d %5f\n",
896 apitch0, apitch1, _approachElevator.val, elevDelta); // DEBUG
898 fprintf(stderr, "l %5f d %5f aoa %5f inc %5f ele %5f\n",
899 _liftRatio, _dragFactor, _cruiseAoA, _tailIncidence,
900 _approachElevator.val);
902 if(norm(dragFactor) < 1.00001 &&
903 norm(liftFactor) < 1.00001 &&
904 abs(aoaDelta) < .000017 &&
905 abs(tailDelta) < .000017 &&
906 abs(elevDelta) < 0.00001)
912 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
913 _failureMsg = "Drag factor beyond reasonable bounds.";
915 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
916 _failureMsg = "Lift ratio beyond reasonable bounds.";
918 } else if(Math::abs(_cruiseAoA) >= .174) {
919 _failureMsg = "Cruise AoA > 10 degrees";
921 } else if(Math::abs(_tailIncidence) >= .174) {
922 _failureMsg = "Tail incidence > 10 degrees";
926 }; // namespace yasim