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,
211 float taper, float mid)
213 Fuselage* f = new Fuselage();
216 f->front[i] = front[i];
217 f->back[i] = back[i];
225 int Airplane::addTank(float* pos, float cap, float density)
227 Tank* t = new Tank();
229 for(i=0; i<3; i++) t->pos[i] = pos[i];
232 t->density = density;
233 t->handle = 0xffffffff;
234 return _tanks.add(t);
237 void Airplane::addGear(Gear* gear, float transitionTime)
239 GearRec* g = new GearRec();
242 g->time = transitionTime;
246 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
248 ThrustRec* t = new ThrustRec();
249 t->thruster = thruster;
252 for(i=0; i<3; i++) t->cg[i] = cg[i];
256 void Airplane::addBallast(float* pos, float mass)
258 _model.getBody()->addMass(mass, pos);
262 int Airplane::addWeight(float* pos, float size)
264 WeightRec* wr = new WeightRec();
265 wr->handle = _model.getBody()->addMass(0, pos);
267 wr->surf = new Surface();
268 wr->surf->setPosition(pos);
269 wr->surf->setTotalDrag(size*size);
270 _model.addSurface(wr->surf);
271 _surfs.add(wr->surf);
273 return _weights.add(wr);
276 void Airplane::setWeight(int handle, float mass)
278 WeightRec* wr = (WeightRec*)_weights.get(handle);
280 _model.getBody()->setMass(wr->handle, mass);
282 // Kill the aerodynamic drag if the mass is exactly zero. This is
283 // how we simulate droppable stores.
285 wr->surf->setXDrag(0);
286 wr->surf->setYDrag(0);
287 wr->surf->setZDrag(0);
289 wr->surf->setXDrag(1);
290 wr->surf->setYDrag(1);
291 wr->surf->setZDrag(1);
295 void Airplane::setFuelFraction(float frac)
298 for(i=0; i<_tanks.size(); i++) {
299 Tank* t = (Tank*)_tanks.get(i);
300 _model.getBody()->setMass(t->handle, t->cap * frac);
304 float Airplane::getDragCoefficient()
309 float Airplane::getLiftRatio()
314 float Airplane::getCruiseAoA()
319 float Airplane::getTailIncidence()
321 return _tailIncidence;
324 char* Airplane::getFailureMsg()
329 int Airplane::getSolutionIterations()
331 return _solutionIterations;
334 void Airplane::setupState(float aoa, float speed, State* s)
336 float cosAoA = Math::cos(aoa);
337 float sinAoA = Math::sin(aoa);
338 s->orient[0] = cosAoA; s->orient[1] = 0; s->orient[2] = sinAoA;
339 s->orient[3] = 0; s->orient[4] = 1; s->orient[5] = 0;
340 s->orient[6] = -sinAoA; s->orient[7] = 0; s->orient[8] = cosAoA;
342 s->v[0] = speed; s->v[1] = 0; s->v[2] = 0;
346 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
348 // Put us 1m above the origin, or else the gravity computation in
353 float Airplane::compileWing(Wing* w)
355 // Make sure it's initialized. The surfaces will pop out with
356 // total drag coefficients equal to their areas, which is what we
362 for(i=0; i<w->numSurfaces(); i++) {
363 Surface* s = (Surface*)w->getSurface(i);
365 float td = s->getTotalDrag();
368 _model.addSurface(s);
370 float mass = w->getSurfaceWeight(i);
371 mass = mass * Math::sqrt(mass);
374 _model.getBody()->addMass(mass, pos);
380 float Airplane::compileFuselage(Fuselage* f)
384 Math::sub3(f->front, f->back, fwd);
385 float len = Math::mag3(fwd);
386 float wid = f->width;
387 int segs = (int)Math::ceil(len/wid);
388 float segWgt = len*wid/segs;
390 for(j=0; j<segs; j++) {
391 float frac = (j+0.5) / segs;
395 scale = f->taper+(1-f->taper) * (frac / f->mid);
397 scale = f->taper+(1-f->taper) * (frac - f->mid) / (1 - f->mid);
401 Math::mul3(frac, fwd, pos);
402 Math::add3(f->back, pos, pos);
404 // _Mass_ weighting goes as surface area^(3/2)
405 float mass = scale*segWgt * Math::sqrt(scale*segWgt);
406 _model.getBody()->addMass(mass, pos);
409 // Make a Surface too
410 Surface* s = new Surface();
412 float sideDrag = len/wid;
413 s->setYDrag(sideDrag);
414 s->setZDrag(sideDrag);
415 s->setTotalDrag(scale*segWgt);
417 // FIXME: fails for fuselages aligned along the Y axis
419 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
421 y[0] = 0; y[1] = 1; y[2] = 0;
422 Math::cross3(x, y, z);
423 s->setOrientation(o);
425 _model.addSurface(s);
431 // FIXME: should probably add a mass for the gear, too
432 void Airplane::compileGear(GearRec* gr)
436 // Make a Surface object for the aerodynamic behavior
437 Surface* s = new Surface();
440 // Put the surface at the half-way point on the gear strut, give
441 // it a drag coefficient equal to a square of the same dimension
442 // (gear are really draggy) and make it symmetric. Assume that
443 // the "length" of the gear is 3x the compression distance
444 float pos[3], cmp[3];
445 g->getCompression(cmp);
446 float length = 3 * Math::mag3(cmp);
448 Math::mul3(0.5, cmp, cmp);
449 Math::add3(pos, cmp, pos);
452 s->setTotalDrag(length*length);
455 _model.addSurface(s);
459 void Airplane::compile()
462 ground[0] = 0; ground[1] = 0; ground[2] = 1;
463 _model.setGroundPlane(ground, -100000);
465 RigidBody* body = _model.getBody();
466 int firstMass = body->numMasses();
468 // Generate the point masses for the plane. Just use unitless
469 // numbers for a first pass, then go back through and rescale to
470 // make the weight right.
474 aeroWgt += compileWing(_wing);
475 aeroWgt += compileWing(_tail);
477 for(i=0; i<_vstabs.size(); i++) {
478 aeroWgt += compileWing((Wing*)_vstabs.get(i));
482 for(i=0; i<_fuselages.size(); i++) {
483 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
486 // Count up the absolute weight we have
487 float nonAeroWgt = _ballast;
488 for(i=0; i<_thrusters.size(); i++)
489 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
491 // Rescale to the specified empty weight
492 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
493 for(i=firstMass; i<body->numMasses(); i++)
494 body->setMass(i, body->getMass(i)*wscale);
496 // Add the thruster masses
497 for(i=0; i<_thrusters.size(); i++) {
498 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
499 body->addMass(t->mass, t->cg);
502 // Add the tanks, empty for now.
504 for(i=0; i<_tanks.size(); i++) {
505 Tank* t = (Tank*)_tanks.get(i);
506 t->handle = body->addMass(0, t->pos);
509 _cruiseWeight = _emptyWeight + totalFuel*0.5;
510 _approachWeight = _emptyWeight + totalFuel*0.2;
514 // Add surfaces for the landing gear.
515 for(i=0; i<_gears.size(); i++)
516 compileGear((GearRec*)_gears.get(i));
518 // The Thruster objects
519 for(i=0; i<_thrusters.size(); i++) {
520 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
521 tr->handle = _model.addThruster(tr->thruster);
526 float gespan = _wing->getGroundEffect(gepos);
527 _model.setGroundEffect(gepos, gespan, .3);
532 // Drop the gear (use a really big dt)
533 setGearState(true, 1000000);
536 void Airplane::solveGear()
539 _model.getBody()->getCG(cg);
541 // Calculate spring constant weightings for the gear. Weight by
542 // the inverse of the distance to the c.g. in the XY plane, which
543 // should be correct for most gear arrangements. Add 50cm of
544 // "buffer" to keep things from blowing up with aircraft with a
545 // single gear very near the c.g. (AV-8, for example).
548 for(i=0; i<_gears.size(); i++) {
549 GearRec* gr = (GearRec*)_gears.get(i);
552 Math::sub3(cg, pos, pos);
553 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
557 // Renormalize so they sum to 1
558 for(i=0; i<_gears.size(); i++)
559 ((GearRec*)_gears.get(i))->wgt /= total;
561 // The force at max compression should be sufficient to stop a
562 // plane moving downwards at 3x the approach descent rate. Assume
563 // a 3 degree approach.
564 float descentRate = 3*_approachSpeed/19.1;
566 // Spread the kinetic energy according to the gear weights. This
567 // will results in an equal compression fraction (not distance) of
569 float energy = 0.5*_approachWeight*descentRate*descentRate;
571 for(i=0; i<_gears.size(); i++) {
572 GearRec* gr = (GearRec*)_gears.get(i);
573 float e = energy * gr->wgt;
575 gr->gear->getCompression(comp);
576 float len = Math::mag3(comp);
578 // Energy in a spring: e = 0.5 * k * len^2
579 float k = 2 * e / (len*len);
581 gr->gear->setSpring(k);
583 // Critically damped (too damped, too!)
584 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
586 // These are pretty generic
587 gr->gear->setStaticFriction(0.8);
588 gr->gear->setDynamicFriction(0.7);
592 void Airplane::stabilizeThrust()
595 for(i=0; i<_thrusters.size(); i++)
596 _model.getThruster(i)->stabilize();
599 void Airplane::runCruise()
601 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
602 _model.setState(&_cruiseState);
603 _model.setAir(_cruiseP, _cruiseT);
605 // The control configuration
608 for(i=0; i<_cruiseControls.size(); i++) {
609 Control* c = (Control*)_cruiseControls.get(i);
610 _controls.setInput(c->control, c->val);
612 _controls.applyControls();
616 Math::mul3(-1, _cruiseState.v, wind);
617 Math::vmul33(_cruiseState.orient, wind, wind);
619 // Gear are up (if they're non-retractable, this is a noop)
620 setGearState(false, 100000);
622 // Cruise is by convention at 50% tank capacity
623 setFuelFraction(0.5);
625 // Set up the thruster parameters and iterate until the thrust
627 for(i=0; i<_thrusters.size(); i++) {
628 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
630 t->setAir(_cruiseP, _cruiseT);
634 // Precompute thrust in the model, and calculate aerodynamic forces
635 _model.getBody()->reset();
636 _model.initIteration();
637 _model.calcForces(&_cruiseState);
640 void Airplane::runApproach()
642 setupState(_approachAoA, _approachSpeed, &_approachState);
643 _model.setState(&_approachState);
644 _model.setAir(_approachP, _approachT);
646 // The control configuration
649 for(i=0; i<_approachControls.size(); i++) {
650 Control* c = (Control*)_approachControls.get(i);
651 _controls.setInput(c->control, c->val);
653 _controls.applyControls();
657 Math::mul3(-1, _approachState.v, wind);
658 Math::vmul33(_approachState.orient, wind, wind);
660 // Approach is by convention at 20% tank capacity
661 setFuelFraction(0.2);
664 setGearState(true, 100000);
666 // Run the thrusters until they get to a stable setting. FIXME:
667 // this is lots of wasted work.
668 for(i=0; i<_thrusters.size(); i++) {
669 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
671 t->setAir(_approachP, _approachT);
675 // Precompute thrust in the model, and calculate aerodynamic forces
676 _model.getBody()->reset();
677 _model.initIteration();
678 _model.calcForces(&_approachState);
681 void Airplane::applyDragFactor(float factor)
683 float applied = Math::sqrt(factor);
684 _dragFactor *= applied;
685 _wing->setDragScale(_wing->getDragScale() * applied);
686 _tail->setDragScale(_tail->getDragScale() * applied);
688 for(i=0; i<_vstabs.size(); i++) {
689 Wing* w = (Wing*)_vstabs.get(i);
690 w->setDragScale(w->getDragScale() * applied);
692 for(i=0; i<_surfs.size(); i++) {
693 Surface* s = (Surface*)_surfs.get(i);
694 s->setTotalDrag(s->getTotalDrag() * applied);
698 void Airplane::applyLiftRatio(float factor)
700 float applied = Math::sqrt(factor);
701 _liftRatio *= applied;
702 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
703 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
705 for(i=0; i<_vstabs.size(); i++) {
706 Wing* w = (Wing*)_vstabs.get(i);
707 w->setLiftRatio(w->getLiftRatio() * applied);
711 float Airplane::clamp(float val, float min, float max)
713 if(val < min) return min;
714 if(val > max) return max;
718 float Airplane::normFactor(float f)
725 void Airplane::solve()
727 static const float ARCMIN = 0.0002909;
730 _solutionIterations = 0;
733 if(_solutionIterations++ > 10000) {
734 _failureMsg = "Solution failed to converge after 10000 iterations";
738 // Run an iteration at cruise, and extract the needed numbers:
741 _model.getThrust(tmp);
742 float thrust = tmp[0];
744 _model.getBody()->getAccel(tmp);
745 float xforce = _cruiseWeight * tmp[0];
746 float clift0 = _cruiseWeight * tmp[2];
748 _model.getBody()->getAngularAccel(tmp);
749 float pitch0 = tmp[1];
751 // Run an approach iteration, and do likewise
754 _model.getBody()->getAccel(tmp);
755 float alift = _approachWeight * tmp[2];
757 // Modify the cruise AoA a bit to get a derivative
758 _cruiseAoA += ARCMIN;
760 _cruiseAoA -= ARCMIN;
762 _model.getBody()->getAccel(tmp);
763 float clift1 = _cruiseWeight * tmp[2];
765 // Do the same with the tail incidence
766 _tail->setIncidence(_tailIncidence + ARCMIN);
768 _tail->setIncidence(_tailIncidence);
770 _model.getBody()->getAngularAccel(tmp);
771 float pitch1 = tmp[1];
774 float awgt = 9.8 * _approachWeight;
776 float dragFactor = thrust / (thrust-xforce);
777 float liftFactor = awgt / (awgt+alift);
778 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
779 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
782 if(dragFactor <= 0) {
783 _failureMsg = "Zero or negative drag adjustment.";
785 } else if(liftFactor <= 0) {
786 _failureMsg = "Zero or negative lift adjustment.";
791 applyDragFactor(dragFactor);
792 applyLiftRatio(liftFactor);
794 // DON'T do the following until the above are sane
795 if(normFactor(dragFactor) > 1.1
796 || normFactor(liftFactor) > 1.1)
801 // OK, now we can adjust the minor variables
802 _cruiseAoA += 0.5*aoaDelta;
803 _tailIncidence += 0.5*tailDelta;
805 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
806 _tailIncidence = clamp(_tailIncidence, -.174, .174);
808 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
809 aoaDelta < .000017 && tailDelta < .000017)
815 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
816 _failureMsg = "Drag factor beyond reasonable bounds.";
818 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
819 _failureMsg = "Lift ratio beyond reasonable bounds.";
821 } else if(Math::abs(_cruiseAoA) >= .174) {
822 _failureMsg = "Cruise AoA > 10 degrees";
824 } else if(Math::abs(_tailIncidence) >= .174) {
825 _failureMsg = "Tail incidence > 10 degrees";
829 }; // namespace yasim