1 #include "Atmosphere.hpp"
2 #include "ControlMap.hpp"
6 #include "RigidBody.hpp"
8 #include "Thruster.hpp"
10 #include "Airplane.hpp"
13 // FIXME: hook gear extension into the force calculation somehow...
18 _pilotPos[0] = _pilotPos[1] = _pilotPos[2] = 0;
38 for(int i=0; i<_fuselages.size(); i++)
39 delete (Fuselage*)_fuselages.get(i);
40 for(int i=0; i<_tanks.size(); i++)
41 delete (Tank*)_tanks.get(i);
42 for(int i=0; i<_thrusters.size(); i++)
43 delete (ThrustRec*)_thrusters.get(i);
44 for(int i=0; i<_gears.size(); i++)
45 delete (GearRec*)_gears.get(i);
46 for(int i=0; i<_surfs.size(); i++)
47 delete (Surface*)_surfs.get(i);
50 void Airplane::iterate(float dt)
58 ControlMap* Airplane::getControlMap()
63 Model* Airplane::getModel()
68 void Airplane::getPilotAccel(float* out)
70 State* s = _model.getState();
73 Glue::geodUp(s->pos, out);
74 Math::mul3(-9.8, out, out);
76 // The regular acceleration
78 Math::mul3(-1, s->acc, tmp);
79 Math::add3(tmp, out, out);
81 // Convert to aircraft coordinates
82 Math::vmul33(s->orient, out, out);
84 // FIXME: rotational & centripetal acceleration needed
87 void Airplane::setPilotPos(float* pos)
89 for(int i=0; i<3; i++) _pilotPos[i] = pos[i];
92 void Airplane::getPilotPos(float* out)
94 for(int i=0; i<3; i++) out[i] = _pilotPos[i];
97 int Airplane::numGear()
102 Gear* Airplane::getGear(int g)
104 return ((GearRec*)_gears.get(g))->gear;
107 void Airplane::setGearState(bool down, float dt)
109 for(int i=0; i<_gears.size(); i++) {
110 GearRec* gr = (GearRec*)_gears.get(i);
113 gr->gear->setExtension(1);
114 gr->surf->setXDrag(1);
115 gr->surf->setYDrag(1);
116 gr->surf->setZDrag(1);
120 float diff = dt / gr->time;
121 if(!down) diff = -diff;
122 float ext = gr->gear->getExtension() + diff;
126 gr->gear->setExtension(ext);
127 gr->surf->setXDrag(ext);
128 gr->surf->setYDrag(ext);
129 gr->surf->setZDrag(ext);
133 void Airplane::setApproach(float speed, float altitude)
135 // The zero AoA will become a calculated stall AoA in compile()
136 setApproach(speed, altitude, 0);
139 void Airplane::setApproach(float speed, float altitude, float aoa)
141 _approachSpeed = speed;
142 _approachRho = Atmosphere::getStdDensity(altitude);
146 void Airplane::setCruise(float speed, float altitude)
148 _cruiseSpeed = speed;
149 _cruiseRho = Atmosphere::getStdDensity(altitude);
154 void Airplane::addApproachControl(int control, float val)
156 Control* c = new Control();
157 c->control = control;
159 _approachControls.add(c);
162 void Airplane::addCruiseControl(int control, float val)
164 Control* c = new Control();
165 c->control = control;
167 _cruiseControls.add(c);
170 int Airplane::numTanks()
172 return _tanks.size();
175 float Airplane::getFuel(int tank)
177 return ((Tank*)_tanks.get(tank))->fill;
180 float Airplane::getFuelDensity(int tank)
182 return ((Tank*)_tanks.get(tank))->density;
185 void Airplane::setWeight(float weight)
187 _emptyWeight = weight;
190 void Airplane::setWing(Wing* wing)
195 void Airplane::setTail(Wing* tail)
200 void Airplane::addVStab(Wing* vstab)
205 void Airplane::addFuselage(float* front, float* back, float width)
207 Fuselage* f = new Fuselage();
208 for(int i=0; i<3; i++) {
209 f->front[i] = front[i];
210 f->back[i] = back[i];
216 int Airplane::addTank(float* pos, float cap, float density)
218 Tank* t = new Tank();
219 for(int 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, float transitionTime)
229 GearRec* g = new GearRec();
232 g->time = transitionTime;
236 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
238 ThrustRec* t = new ThrustRec();
239 t->thruster = thruster;
241 for(int 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->setTotalDrag(size*size);
258 _model.addSurface(wr->surf);
259 _surfs.add(wr->surf);
261 return _weights.add(wr);
264 void Airplane::setWeight(int handle, float mass)
266 WeightRec* wr = (WeightRec*)_weights.get(handle);
268 _model.getBody()->setMass(wr->handle, mass);
270 // Kill the aerodynamic drag if the mass is exactly zero. This is
271 // how we simulate droppable stores.
273 wr->surf->setXDrag(0);
274 wr->surf->setYDrag(0);
275 wr->surf->setZDrag(0);
277 wr->surf->setXDrag(1);
278 wr->surf->setYDrag(1);
279 wr->surf->setZDrag(1);
283 void Airplane::setFuelFraction(float frac)
285 for(int i=0; i<_tanks.size(); i++) {
286 Tank* t = (Tank*)_tanks.get(i);
287 _model.getBody()->setMass(t->handle, t->cap * frac);
291 float Airplane::getDragCoefficient()
296 float Airplane::getLiftRatio()
301 float Airplane::getCruiseAoA()
306 float Airplane::getTailIncidence()
308 return _tailIncidence;
311 char* Airplane::getFailureMsg()
316 int Airplane::getSolutionIterations()
318 return _solutionIterations;
321 void Airplane::setupState(float aoa, float speed, State* s)
323 float cosAoA = Math::cos(aoa);
324 float sinAoA = Math::sin(aoa);
325 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
326 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
327 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
329 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
331 for(int i=0; i<3; i++)
332 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
334 // Put us 1m above the origin, or else the gravity computation in
339 float Airplane::compileWing(Wing* w)
341 // Make sure it's initialized. The surfaces will pop out with
342 // total drag coefficients equal to their areas, which is what we
347 for(int i=0; i<w->numSurfaces(); i++) {
348 Surface* s = (Surface*)w->getSurface(i);
349 _model.addSurface(s);
353 _model.getBody()->addMass(w->getSurfaceWeight(i), pos);
354 wgt += w->getSurfaceWeight(i);
359 float Airplane::compileFuselage(Fuselage* f)
363 Math::sub3(f->front, f->back, fwd);
364 float len = Math::mag3(fwd);
365 float wid = f->width;
366 int segs = (int)Math::ceil(len/wid);
367 float segWgt = wid*wid/segs;
368 for(int j=0; j<segs; j++) {
369 float frac = (j+0.5) / segs;
371 Math::mul3(frac, fwd, pos);
372 Math::add3(f->back, pos, pos);
373 _model.getBody()->addMass(segWgt, pos);
376 // Make a Surface too
377 Surface* s = new Surface();
379 float sideDrag = len/wid;
380 s->setYDrag(sideDrag);
381 s->setZDrag(sideDrag);
382 s->setTotalDrag(segWgt);
384 // FIXME: fails for fuselages aligned along the Y axis
386 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
388 y[0] = 0; y[1] = 1; y[2] = 0;
389 Math::cross3(x, y, z);
390 s->setOrientation(o);
392 _model.addSurface(s);
398 // FIXME: should probably add a mass for the gear, too
399 void Airplane::compileGear(GearRec* gr)
403 // Make a Surface object for the aerodynamic behavior
404 Surface* s = new Surface();
407 // Put the surface at the half-way point on the gear strut, give
408 // it a drag coefficient equal to a square of the same dimension
409 // (gear are really draggy) and make it symmetric.
410 float pos[3], cmp[3];
411 g->getCompression(cmp);
412 float length = Math::mag3(cmp);
414 Math::mul3(0.5, cmp, cmp);
415 Math::add3(pos, cmp, pos);
418 s->setTotalDrag(length*length);
421 _model.addSurface(s);
425 void Airplane::compile()
428 ground[0] = 0; ground[1] = 0; ground[2] = 1;
429 _model.setGroundPlane(ground, -100000);
431 RigidBody* body = _model.getBody();
432 int firstMass = body->numMasses();
434 // Generate the point masses for the plane. Just use unitless
435 // numbers for a first pass, then go back through and rescale to
436 // make the weight right.
440 aeroWgt += compileWing(_wing);
441 aeroWgt += compileWing(_tail);
442 for(int i=0; i<_vstabs.size(); i++) {
443 aeroWgt += compileWing((Wing*)_vstabs.get(i));
447 for(int i=0; i<_fuselages.size(); i++) {
448 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
451 // Count up the absolute weight we have
452 float nonAeroWgt = _ballast;
453 for(int i=0; i<_thrusters.size(); i++)
454 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
456 // Rescale to the specified empty weight
457 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
458 for(int i=firstMass; i<body->numMasses(); i++)
459 body->setMass(i, body->getMass(i)*wscale);
461 // Add the thruster masses
462 for(int i=0; i<_thrusters.size(); i++) {
463 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
464 body->addMass(t->mass, t->cg);
467 // Add the tanks, empty for now.
469 for(int i=0; i<_tanks.size(); i++) {
470 Tank* t = (Tank*)_tanks.get(i);
471 t->handle = body->addMass(0, t->pos);
474 _cruiseWeight = _emptyWeight + totalFuel*0.5;
475 _approachWeight = _emptyWeight + totalFuel*0.2;
479 // Add surfaces for the landing gear.
480 for(int i=0; i<_gears.size(); i++)
481 compileGear((GearRec*)_gears.get(i));
483 // The Thruster objects
484 for(int i=0; i<_thrusters.size(); i++) {
485 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
486 tr->handle = _model.addThruster(tr->thruster);
492 // Drop the gear (use a really big dt)
493 setGearState(true, 1000000);
496 void Airplane::solveGear()
499 _model.getBody()->getCG(cg);
501 // Calculate spring constant weightings for the gear. Weight by
502 // the inverse of the distance to the c.g. in the XY plane, which
503 // should be correct for most gear arrangements. Add 50cm of
504 // "buffer" to keep things from blowing up with aircraft with a
505 // single gear very near the c.g. (AV-8, for example).
507 for(int i=0; i<_gears.size(); i++) {
508 GearRec* gr = (GearRec*)_gears.get(i);
511 Math::sub3(cg, pos, pos);
512 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
516 // Renormalize so they sum to 1
517 for(int i=0; i<_gears.size(); i++)
518 ((GearRec*)_gears.get(i))->wgt /= total;
520 // The force at max compression should be sufficient to stop a
521 // plane moving downwards at 3x the approach descent rate. Assume
522 // a 3 degree approach.
523 float descentRate = 3*_approachSpeed/19.1;
525 // Spread the kinetic energy according to the gear weights. This
526 // will results in an equal compression fraction (not distance) of
528 float energy = 0.5*_approachWeight*descentRate*descentRate;
530 for(int i=0; i<_gears.size(); i++) {
531 GearRec* gr = (GearRec*)_gears.get(i);
532 float e = energy * gr->wgt;
534 gr->gear->getCompression(comp);
535 float len = Math::mag3(comp);
537 // Energy in a spring: e = 0.5 * k * len^2
538 float k = 2 * e / (len*len);
540 gr->gear->setSpring(k);
542 // Critically damped (too damped, too!)
543 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
545 // These are pretty generic
546 gr->gear->setStaticFriction(0.8);
547 gr->gear->setDynamicFriction(0.7);
551 void Airplane::stabilizeThrust()
553 float thrust[3], tmp[3];
556 thrust[0] = thrust[1] = thrust[2] = 0;
557 for(int i=0; i<_thrusters.size(); i++) {
558 Thruster* t = _model.getThruster(i);
561 Math::add3(thrust, tmp, thrust);
564 float t = Math::mag3(thrust);
565 float ratio = (t+0.1)/(last+0.1);
566 if(ratio < 1.00001 && ratio > 0.99999)
573 void Airplane::runCruise()
575 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
576 _model.setState(&_cruiseState);
577 _model.setAirDensity(_cruiseRho);
579 // The control configuration
581 for(int i=0; i<_cruiseControls.size(); i++) {
582 Control* c = (Control*)_cruiseControls.get(i);
583 _controls.setInput(c->control, c->val);
585 _controls.applyControls();
589 Math::mul3(-1, _cruiseState.v, wind);
590 Math::vmul33(_cruiseState.orient, wind, wind);
592 // Gear are up (if they're non-retractable, this is a noop)
593 setGearState(false, 100000);
595 // Cruise is by convention at 50% tank capacity
596 setFuelFraction(0.5);
598 // Set up the thruster parameters and iterate until the thrust
600 for(int i=0; i<_thrusters.size(); i++) {
601 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
603 t->setDensity(_cruiseRho);
607 // Precompute thrust in the model, and calculate aerodynamic forces
608 _model.getBody()->reset();
609 _model.initIteration();
610 _model.calcForces(&_cruiseState);
613 void Airplane::runApproach()
615 setupState(_approachAoA, _approachSpeed, &_approachState);
616 _model.setState(&_approachState);
617 _model.setAirDensity(_approachRho);
619 // The control configuration
621 for(int i=0; i<_approachControls.size(); i++) {
622 Control* c = (Control*)_approachControls.get(i);
623 _controls.setInput(c->control, c->val);
625 _controls.applyControls();
629 Math::mul3(-1, _approachState.v, wind);
630 Math::vmul33(_approachState.orient, wind, wind);
632 // Approach is by convention at 20% tank capacity
633 setFuelFraction(0.2);
636 setGearState(true, 100000);
638 // Run the thrusters until they get to a stable setting. FIXME:
639 // this is lots of wasted work.
640 for(int i=0; i<_thrusters.size(); i++) {
641 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
643 t->setDensity(_approachRho);
647 // Precompute thrust in the model, and calculate aerodynamic forces
648 _model.getBody()->reset();
649 _model.initIteration();
650 _model.calcForces(&_approachState);
653 void Airplane::applyDragFactor(float factor)
655 float applied = Math::sqrt(factor);
656 _dragFactor *= applied;
657 _wing->setDragScale(_wing->getDragScale() * applied);
658 _tail->setDragScale(_tail->getDragScale() * applied);
659 for(int i=0; i<_vstabs.size(); i++) {
660 Wing* w = (Wing*)_vstabs.get(i);
661 w->setDragScale(w->getDragScale() * applied);
663 for(int i=0; i<_surfs.size(); i++) {
664 Surface* s = (Surface*)_surfs.get(i);
665 s->setTotalDrag(s->getTotalDrag() * applied);
669 void Airplane::applyLiftRatio(float factor)
671 float applied = Math::sqrt(factor);
672 _liftRatio *= applied;
673 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
674 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
675 for(int i=0; i<_vstabs.size(); i++) {
676 Wing* w = (Wing*)_vstabs.get(i);
677 w->setLiftRatio(w->getLiftRatio() * applied);
681 float Airplane::clamp(float val, float min, float max)
683 if(val < min) return min;
684 if(val > max) return max;
688 float Airplane::normFactor(float f)
695 void Airplane::solve()
697 static const float ARCMIN = 0.0002909;
700 _solutionIterations = 0;
703 if(_solutionIterations++ > 10000) {
704 _failureMsg = "Solution failed to converge after 10000 iterations";
708 // Run an iteration at cruise, and extract the needed numbers:
711 _model.getThrust(tmp);
712 float thrust = tmp[0];
714 _model.getBody()->getAccel(tmp);
715 float xforce = _cruiseWeight * tmp[0];
716 float clift0 = _cruiseWeight * tmp[2];
718 _model.getBody()->getAngularAccel(tmp);
719 float pitch0 = tmp[1];
721 // Run an approach iteration, and do likewise
724 _model.getBody()->getAccel(tmp);
725 float alift = _approachWeight * tmp[2];
727 // Modify the cruise AoA a bit to get a derivative
728 _cruiseAoA += ARCMIN;
730 _cruiseAoA -= ARCMIN;
732 _model.getBody()->getAccel(tmp);
733 float clift1 = _cruiseWeight * tmp[2];
735 // Do the same with the tail incidence
736 _tail->setIncidence(_tailIncidence + ARCMIN);
738 _tail->setIncidence(_tailIncidence);
740 _model.getBody()->getAngularAccel(tmp);
741 float pitch1 = tmp[1];
744 float awgt = 9.8 * _approachWeight;
746 float dragFactor = thrust / (thrust-xforce);
747 float liftFactor = awgt / (awgt+alift);
748 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
749 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
752 if(dragFactor <= 0) {
753 _failureMsg = "Zero or negative drag adjustment.";
755 } else if(liftFactor <= 0) {
756 _failureMsg = "Zero or negative lift adjustment.";
761 applyDragFactor(dragFactor);
762 applyLiftRatio(liftFactor);
764 // DON'T do the following until the above are sane
765 if(normFactor(dragFactor) > 1.1
766 || normFactor(liftFactor) > 1.1)
771 // OK, now we can adjust the minor variables
772 _cruiseAoA += 0.5*aoaDelta;
773 _tailIncidence += 0.5*tailDelta;
775 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
776 _tailIncidence = clamp(_tailIncidence, -.174, .174);
778 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
779 aoaDelta < .000017 && tailDelta < .000017)
785 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
786 _failureMsg = "Drag factor beyond reasonable bounds.";
788 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
789 _failureMsg = "Lift ratio beyond reasonable bounds.";
791 } else if(Math::abs(_cruiseAoA) >= .174) {
792 _failureMsg = "Cruise AoA > 10 degrees";
794 } else if(Math::abs(_tailIncidence) >= .174) {
795 _failureMsg = "Tail incidence > 10 degrees";
799 }; // namespace yasim