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);
51 void Airplane::iterate(float dt)
55 // FIXME: Consume fuel
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)
90 for(i=0; i<3; i++) _pilotPos[i] = pos[i];
93 void Airplane::getPilotPos(float* out)
96 for(i=0; i<3; i++) out[i] = _pilotPos[i];
99 int Airplane::numGear()
101 return _gears.size();
104 Gear* Airplane::getGear(int g)
106 return ((GearRec*)_gears.get(g))->gear;
109 void Airplane::setGearState(bool down, float dt)
112 for(i=0; i<_gears.size(); i++) {
113 GearRec* gr = (GearRec*)_gears.get(i);
116 gr->gear->setExtension(1);
117 gr->surf->setXDrag(1);
118 gr->surf->setYDrag(1);
119 gr->surf->setZDrag(1);
123 float diff = dt / gr->time;
124 if(!down) diff = -diff;
125 float ext = gr->gear->getExtension() + diff;
129 gr->gear->setExtension(ext);
130 gr->surf->setXDrag(ext);
131 gr->surf->setYDrag(ext);
132 gr->surf->setZDrag(ext);
136 void Airplane::setApproach(float speed, float altitude)
138 // The zero AoA will become a calculated stall AoA in compile()
139 setApproach(speed, altitude, 0);
142 void Airplane::setApproach(float speed, float altitude, float aoa)
144 _approachSpeed = speed;
145 _approachP = Atmosphere::getStdPressure(altitude);
146 _approachT = Atmosphere::getStdTemperature(altitude);
150 void Airplane::setCruise(float speed, float altitude)
152 _cruiseSpeed = speed;
153 _cruiseP = Atmosphere::getStdPressure(altitude);
154 _cruiseT = Atmosphere::getStdTemperature(altitude);
159 void Airplane::addApproachControl(int control, float val)
161 Control* c = new Control();
162 c->control = control;
164 _approachControls.add(c);
167 void Airplane::addCruiseControl(int control, float val)
169 Control* c = new Control();
170 c->control = control;
172 _cruiseControls.add(c);
175 int Airplane::numTanks()
177 return _tanks.size();
180 float Airplane::getFuel(int tank)
182 return ((Tank*)_tanks.get(tank))->fill;
185 float Airplane::getFuelDensity(int tank)
187 return ((Tank*)_tanks.get(tank))->density;
190 void Airplane::setWeight(float weight)
192 _emptyWeight = weight;
195 void Airplane::setWing(Wing* wing)
200 void Airplane::setTail(Wing* tail)
205 void Airplane::addVStab(Wing* vstab)
210 void Airplane::addFuselage(float* front, float* back, float width)
212 Fuselage* f = new Fuselage();
215 f->front[i] = front[i];
216 f->back[i] = back[i];
222 int Airplane::addTank(float* pos, float cap, float density)
224 Tank* t = new Tank();
226 for(i=0; i<3; i++) t->pos[i] = pos[i];
229 t->density = density;
230 t->handle = 0xffffffff;
231 return _tanks.add(t);
234 void Airplane::addGear(Gear* gear, float transitionTime)
236 GearRec* g = new GearRec();
239 g->time = transitionTime;
243 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
245 ThrustRec* t = new ThrustRec();
246 t->thruster = thruster;
249 for(i=0; i<3; i++) t->cg[i] = cg[i];
253 void Airplane::addBallast(float* pos, float mass)
255 _model.getBody()->addMass(mass, pos);
259 int Airplane::addWeight(float* pos, float size)
261 WeightRec* wr = new WeightRec();
262 wr->handle = _model.getBody()->addMass(0, pos);
264 wr->surf = new Surface();
265 wr->surf->setPosition(pos);
266 wr->surf->setTotalDrag(size*size);
267 _model.addSurface(wr->surf);
268 _surfs.add(wr->surf);
270 return _weights.add(wr);
273 void Airplane::setWeight(int handle, float mass)
275 WeightRec* wr = (WeightRec*)_weights.get(handle);
277 _model.getBody()->setMass(wr->handle, mass);
279 // Kill the aerodynamic drag if the mass is exactly zero. This is
280 // how we simulate droppable stores.
282 wr->surf->setXDrag(0);
283 wr->surf->setYDrag(0);
284 wr->surf->setZDrag(0);
286 wr->surf->setXDrag(1);
287 wr->surf->setYDrag(1);
288 wr->surf->setZDrag(1);
292 void Airplane::setFuelFraction(float frac)
295 for(i=0; i<_tanks.size(); i++) {
296 Tank* t = (Tank*)_tanks.get(i);
297 _model.getBody()->setMass(t->handle, t->cap * frac);
301 float Airplane::getDragCoefficient()
306 float Airplane::getLiftRatio()
311 float Airplane::getCruiseAoA()
316 float Airplane::getTailIncidence()
318 return _tailIncidence;
321 char* Airplane::getFailureMsg()
326 int Airplane::getSolutionIterations()
328 return _solutionIterations;
331 void Airplane::setupState(float aoa, float speed, State* s)
333 float cosAoA = Math::cos(aoa);
334 float sinAoA = Math::sin(aoa);
335 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
336 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
337 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
339 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
343 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
345 // Put us 1m above the origin, or else the gravity computation in
350 float Airplane::compileWing(Wing* w)
352 // Make sure it's initialized. The surfaces will pop out with
353 // total drag coefficients equal to their areas, which is what we
359 for(i=0; i<w->numSurfaces(); i++) {
360 Surface* s = (Surface*)w->getSurface(i);
361 _model.addSurface(s);
365 _model.getBody()->addMass(w->getSurfaceWeight(i), pos);
366 wgt += w->getSurfaceWeight(i);
371 float Airplane::compileFuselage(Fuselage* f)
375 Math::sub3(f->front, f->back, fwd);
376 float len = Math::mag3(fwd);
377 float wid = f->width;
378 int segs = (int)Math::ceil(len/wid);
379 float segWgt = len*wid/segs;
381 for(j=0; j<segs; j++) {
382 float frac = (j+0.5) / segs;
384 Math::mul3(frac, fwd, pos);
385 Math::add3(f->back, pos, pos);
386 _model.getBody()->addMass(segWgt, pos);
389 // Make a Surface too
390 Surface* s = new Surface();
392 float sideDrag = len/wid;
393 s->setYDrag(sideDrag);
394 s->setZDrag(sideDrag);
395 s->setTotalDrag(segWgt);
397 // FIXME: fails for fuselages aligned along the Y axis
399 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
401 y[0] = 0; y[1] = 1; y[2] = 0;
402 Math::cross3(x, y, z);
403 s->setOrientation(o);
405 _model.addSurface(s);
411 // FIXME: should probably add a mass for the gear, too
412 void Airplane::compileGear(GearRec* gr)
416 // Make a Surface object for the aerodynamic behavior
417 Surface* s = new Surface();
420 // Put the surface at the half-way point on the gear strut, give
421 // it a drag coefficient equal to a square of the same dimension
422 // (gear are really draggy) and make it symmetric. Assume that
423 // the "length" of the gear is 3x the compression distance
424 float pos[3], cmp[3];
425 g->getCompression(cmp);
426 float length = 3 * Math::mag3(cmp);
428 Math::mul3(0.5, cmp, cmp);
429 Math::add3(pos, cmp, pos);
432 s->setTotalDrag(length*length);
435 _model.addSurface(s);
439 void Airplane::compile()
442 ground[0] = 0; ground[1] = 0; ground[2] = 1;
443 _model.setGroundPlane(ground, -100000);
445 RigidBody* body = _model.getBody();
446 int firstMass = body->numMasses();
448 // Generate the point masses for the plane. Just use unitless
449 // numbers for a first pass, then go back through and rescale to
450 // make the weight right.
454 aeroWgt += compileWing(_wing);
455 aeroWgt += compileWing(_tail);
457 for(i=0; i<_vstabs.size(); i++) {
458 aeroWgt += compileWing((Wing*)_vstabs.get(i));
462 for(i=0; i<_fuselages.size(); i++) {
463 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
466 // Count up the absolute weight we have
467 float nonAeroWgt = _ballast;
468 for(i=0; i<_thrusters.size(); i++)
469 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
471 // Rescale to the specified empty weight
472 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
473 for(i=firstMass; i<body->numMasses(); i++)
474 body->setMass(i, body->getMass(i)*wscale);
476 // Add the thruster masses
477 for(i=0; i<_thrusters.size(); i++) {
478 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
479 body->addMass(t->mass, t->cg);
482 // Add the tanks, empty for now.
484 for(i=0; i<_tanks.size(); i++) {
485 Tank* t = (Tank*)_tanks.get(i);
486 t->handle = body->addMass(0, t->pos);
489 _cruiseWeight = _emptyWeight + totalFuel*0.5;
490 _approachWeight = _emptyWeight + totalFuel*0.2;
494 // Add surfaces for the landing gear.
495 for(i=0; i<_gears.size(); i++)
496 compileGear((GearRec*)_gears.get(i));
498 // The Thruster objects
499 for(i=0; i<_thrusters.size(); i++) {
500 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
501 tr->handle = _model.addThruster(tr->thruster);
506 float gespan = _wing->getGroundEffect(gepos);
507 _model.setGroundEffect(gepos, gespan, .3);
512 // Drop the gear (use a really big dt)
513 setGearState(true, 1000000);
516 void Airplane::solveGear()
519 _model.getBody()->getCG(cg);
521 // Calculate spring constant weightings for the gear. Weight by
522 // the inverse of the distance to the c.g. in the XY plane, which
523 // should be correct for most gear arrangements. Add 50cm of
524 // "buffer" to keep things from blowing up with aircraft with a
525 // single gear very near the c.g. (AV-8, for example).
528 for(i=0; i<_gears.size(); i++) {
529 GearRec* gr = (GearRec*)_gears.get(i);
532 Math::sub3(cg, pos, pos);
533 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
537 // Renormalize so they sum to 1
538 for(i=0; i<_gears.size(); i++)
539 ((GearRec*)_gears.get(i))->wgt /= total;
541 // The force at max compression should be sufficient to stop a
542 // plane moving downwards at 3x the approach descent rate. Assume
543 // a 3 degree approach.
544 float descentRate = 3*_approachSpeed/19.1;
546 // Spread the kinetic energy according to the gear weights. This
547 // will results in an equal compression fraction (not distance) of
549 float energy = 0.5*_approachWeight*descentRate*descentRate;
551 for(i=0; i<_gears.size(); i++) {
552 GearRec* gr = (GearRec*)_gears.get(i);
553 float e = energy * gr->wgt;
555 gr->gear->getCompression(comp);
556 float len = Math::mag3(comp);
558 // Energy in a spring: e = 0.5 * k * len^2
559 float k = 2 * e / (len*len);
561 gr->gear->setSpring(k);
563 // Critically damped (too damped, too!)
564 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
566 // These are pretty generic
567 gr->gear->setStaticFriction(0.8);
568 gr->gear->setDynamicFriction(0.7);
572 void Airplane::stabilizeThrust()
575 for(i=0; i<_thrusters.size(); i++)
576 _model.getThruster(i)->stabilize();
579 void Airplane::runCruise()
581 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
582 _model.setState(&_cruiseState);
583 _model.setAir(_cruiseP, _cruiseT);
585 // The control configuration
588 for(i=0; i<_cruiseControls.size(); i++) {
589 Control* c = (Control*)_cruiseControls.get(i);
590 _controls.setInput(c->control, c->val);
592 _controls.applyControls();
596 Math::mul3(-1, _cruiseState.v, wind);
597 Math::vmul33(_cruiseState.orient, wind, wind);
599 // Gear are up (if they're non-retractable, this is a noop)
600 setGearState(false, 100000);
602 // Cruise is by convention at 50% tank capacity
603 setFuelFraction(0.5);
605 // Set up the thruster parameters and iterate until the thrust
607 for(i=0; i<_thrusters.size(); i++) {
608 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
610 t->setAir(_cruiseP, _cruiseT);
614 // Precompute thrust in the model, and calculate aerodynamic forces
615 _model.getBody()->reset();
616 _model.initIteration();
617 _model.calcForces(&_cruiseState);
620 void Airplane::runApproach()
622 setupState(_approachAoA, _approachSpeed, &_approachState);
623 _model.setState(&_approachState);
624 _model.setAir(_approachP, _approachT);
626 // The control configuration
629 for(i=0; i<_approachControls.size(); i++) {
630 Control* c = (Control*)_approachControls.get(i);
631 _controls.setInput(c->control, c->val);
633 _controls.applyControls();
637 Math::mul3(-1, _approachState.v, wind);
638 Math::vmul33(_approachState.orient, wind, wind);
640 // Approach is by convention at 20% tank capacity
641 setFuelFraction(0.2);
644 setGearState(true, 100000);
646 // Run the thrusters until they get to a stable setting. FIXME:
647 // this is lots of wasted work.
648 for(i=0; i<_thrusters.size(); i++) {
649 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
651 t->setAir(_approachP, _approachT);
655 // Precompute thrust in the model, and calculate aerodynamic forces
656 _model.getBody()->reset();
657 _model.initIteration();
658 _model.calcForces(&_approachState);
661 void Airplane::applyDragFactor(float factor)
663 float applied = Math::sqrt(factor);
664 _dragFactor *= applied;
665 _wing->setDragScale(_wing->getDragScale() * applied);
666 _tail->setDragScale(_tail->getDragScale() * applied);
668 for(i=0; i<_vstabs.size(); i++) {
669 Wing* w = (Wing*)_vstabs.get(i);
670 w->setDragScale(w->getDragScale() * applied);
672 for(i=0; i<_surfs.size(); i++) {
673 Surface* s = (Surface*)_surfs.get(i);
674 s->setTotalDrag(s->getTotalDrag() * applied);
678 void Airplane::applyLiftRatio(float factor)
680 float applied = Math::sqrt(factor);
681 _liftRatio *= applied;
682 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
683 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
685 for(i=0; i<_vstabs.size(); i++) {
686 Wing* w = (Wing*)_vstabs.get(i);
687 w->setLiftRatio(w->getLiftRatio() * applied);
691 float Airplane::clamp(float val, float min, float max)
693 if(val < min) return min;
694 if(val > max) return max;
698 float Airplane::normFactor(float f)
705 void Airplane::solve()
707 static const float ARCMIN = 0.0002909;
710 _solutionIterations = 0;
713 if(_solutionIterations++ > 10000) {
714 _failureMsg = "Solution failed to converge after 10000 iterations";
718 // Run an iteration at cruise, and extract the needed numbers:
721 _model.getThrust(tmp);
722 float thrust = tmp[0];
724 _model.getBody()->getAccel(tmp);
725 float xforce = _cruiseWeight * tmp[0];
726 float clift0 = _cruiseWeight * tmp[2];
728 _model.getBody()->getAngularAccel(tmp);
729 float pitch0 = tmp[1];
731 // Run an approach iteration, and do likewise
734 _model.getBody()->getAccel(tmp);
735 float alift = _approachWeight * tmp[2];
737 // Modify the cruise AoA a bit to get a derivative
738 _cruiseAoA += ARCMIN;
740 _cruiseAoA -= ARCMIN;
742 _model.getBody()->getAccel(tmp);
743 float clift1 = _cruiseWeight * tmp[2];
745 // Do the same with the tail incidence
746 _tail->setIncidence(_tailIncidence + ARCMIN);
748 _tail->setIncidence(_tailIncidence);
750 _model.getBody()->getAngularAccel(tmp);
751 float pitch1 = tmp[1];
754 float awgt = 9.8 * _approachWeight;
756 float dragFactor = thrust / (thrust-xforce);
757 float liftFactor = awgt / (awgt+alift);
758 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
759 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
762 if(dragFactor <= 0) {
763 _failureMsg = "Zero or negative drag adjustment.";
765 } else if(liftFactor <= 0) {
766 _failureMsg = "Zero or negative lift adjustment.";
771 applyDragFactor(dragFactor);
772 applyLiftRatio(liftFactor);
774 // DON'T do the following until the above are sane
775 if(normFactor(dragFactor) > 1.1
776 || normFactor(liftFactor) > 1.1)
781 // OK, now we can adjust the minor variables
782 _cruiseAoA += 0.5*aoaDelta;
783 _tailIncidence += 0.5*tailDelta;
785 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
786 _tailIncidence = clamp(_tailIncidence, -.174, .174);
788 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
789 aoaDelta < .000017 && tailDelta < .000017)
795 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
796 _failureMsg = "Drag factor beyond reasonable bounds.";
798 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
799 _failureMsg = "Lift ratio beyond reasonable bounds.";
801 } else if(Math::abs(_cruiseAoA) >= .174) {
802 _failureMsg = "Cruise AoA > 10 degrees";
804 } else if(Math::abs(_tailIncidence) >= .174) {
805 _failureMsg = "Tail incidence > 10 degrees";
809 }; // namespace yasim